strategy_leastping.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package router
  2. import (
  3. "context"
  4. core "github.com/v2fly/v2ray-core/v4"
  5. "github.com/v2fly/v2ray-core/v4/app/observatory"
  6. "github.com/v2fly/v2ray-core/v4/common"
  7. "github.com/v2fly/v2ray-core/v4/features/extension"
  8. )
  9. type LeastPingStrategy struct {
  10. ctx context.Context
  11. observatory extension.Observatory
  12. }
  13. func (l *LeastPingStrategy) InjectContext(ctx context.Context) {
  14. common.Must(core.RequireFeatures(ctx, func(observatory extension.Observatory) error {
  15. l.observatory = observatory
  16. return nil
  17. }))
  18. l.ctx = ctx
  19. }
  20. func (l *LeastPingStrategy) PickOutbound(strings []string) string {
  21. observeReport, err := l.observatory.GetObservation(l.ctx)
  22. if err != nil {
  23. newError("cannot get observe report").Base(err).WriteToLog()
  24. return ""
  25. }
  26. outboundsList := outboundList(strings)
  27. if result, ok := observeReport.(*observatory.ObservationResult); ok {
  28. status := result.Status
  29. leastPing := int64(99999999)
  30. selectedOutboundName := ""
  31. for _, v := range status {
  32. if outboundsList.contains(v.OutboundTag) && v.Alive && v.Delay < leastPing {
  33. selectedOutboundName = v.OutboundTag
  34. }
  35. }
  36. return selectedOutboundName
  37. }
  38. //No way to understand observeReport
  39. return ""
  40. }
  41. type outboundList []string
  42. func (o outboundList) contains(name string) bool {
  43. for _, v := range o {
  44. if v == name {
  45. return true
  46. }
  47. }
  48. return false
  49. }