2021-04-09 00:20:30 +03:00
|
|
|
package router
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/xtls/xray-core/app/observatory"
|
2024-06-29 21:32:57 +03:00
|
|
|
"github.com/xtls/xray-core/common/errors"
|
2021-12-15 03:28:47 +03:00
|
|
|
"github.com/xtls/xray-core/core"
|
2021-04-09 00:20:30 +03:00
|
|
|
"github.com/xtls/xray-core/features/extension"
|
|
|
|
)
|
|
|
|
|
|
|
|
type LeastPingStrategy struct {
|
|
|
|
ctx context.Context
|
|
|
|
observatory extension.Observatory
|
|
|
|
}
|
|
|
|
|
2024-02-18 06:51:37 +03:00
|
|
|
func (l *LeastPingStrategy) GetPrincipleTarget(strings []string) []string {
|
|
|
|
return []string{l.PickOutbound(strings)}
|
|
|
|
}
|
|
|
|
|
2021-04-09 00:20:30 +03:00
|
|
|
func (l *LeastPingStrategy) InjectContext(ctx context.Context) {
|
|
|
|
l.ctx = ctx
|
2024-12-11 04:07:52 +03:00
|
|
|
core.RequireFeaturesAsync(l.ctx, func(observatory extension.Observatory) {
|
|
|
|
l.observatory = observatory
|
|
|
|
})
|
2021-04-09 00:20:30 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *LeastPingStrategy) PickOutbound(strings []string) string {
|
2021-11-14 07:23:38 +03:00
|
|
|
if l.observatory == nil {
|
2024-12-11 04:07:52 +03:00
|
|
|
errors.LogError(l.ctx, "observer is nil")
|
|
|
|
return ""
|
2021-11-14 07:23:38 +03:00
|
|
|
}
|
2021-04-09 00:20:30 +03:00
|
|
|
observeReport, err := l.observatory.GetObservation(l.ctx)
|
|
|
|
if err != nil {
|
2024-12-11 04:07:52 +03:00
|
|
|
errors.LogInfoInner(l.ctx, err, "cannot get observer report")
|
2021-04-09 00:20:30 +03:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
outboundsList := outboundList(strings)
|
|
|
|
if result, ok := observeReport.(*observatory.ObservationResult); ok {
|
|
|
|
status := result.Status
|
|
|
|
leastPing := int64(99999999)
|
|
|
|
selectedOutboundName := ""
|
|
|
|
for _, v := range status {
|
|
|
|
if outboundsList.contains(v.OutboundTag) && v.Alive && v.Delay < leastPing {
|
|
|
|
selectedOutboundName = v.OutboundTag
|
2021-10-26 08:00:31 +03:00
|
|
|
leastPing = v.Delay
|
2021-04-09 00:20:30 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return selectedOutboundName
|
|
|
|
}
|
|
|
|
|
2022-05-18 10:29:01 +03:00
|
|
|
// No way to understand observeReport
|
2021-04-09 00:20:30 +03:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
type outboundList []string
|
|
|
|
|
|
|
|
func (o outboundList) contains(name string) bool {
|
|
|
|
for _, v := range o {
|
|
|
|
if v == name {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|