strategy_leastping.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package router
  2. import (
  3. "context"
  4. "github.com/xtls/xray-core/core"
  5. "github.com/xtls/xray-core/app/observatory"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/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. leastPing = v.Delay
  37. }
  38. }
  39. return selectedOutboundName
  40. }
  41. //No way to understand observeReport
  42. return ""
  43. }
  44. type outboundList []string
  45. func (o outboundList) contains(name string) bool {
  46. for _, v := range o {
  47. if v == name {
  48. return true
  49. }
  50. }
  51. return false
  52. }