strategy_leastping.go 1.4 KB

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