strategy_leastping.go 1.5 KB

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