strategy_leastping.go 1.6 KB

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