2024-02-18 06:51:37 +03:00
|
|
|
package router
|
|
|
|
|
|
|
|
import (
|
2024-05-05 17:07:40 +03:00
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/xtls/xray-core/app/observatory"
|
2024-02-18 06:51:37 +03:00
|
|
|
"github.com/xtls/xray-core/common/dice"
|
2024-05-05 17:07:40 +03:00
|
|
|
"github.com/xtls/xray-core/core"
|
|
|
|
"github.com/xtls/xray-core/features/extension"
|
2024-02-18 06:51:37 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// RandomStrategy represents a random balancing strategy
|
2024-11-09 14:16:11 +03:00
|
|
|
type RandomStrategy struct {
|
2024-05-05 17:07:40 +03:00
|
|
|
FallbackTag string
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
observatory extension.Observatory
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *RandomStrategy) InjectContext(ctx context.Context) {
|
|
|
|
s.ctx = ctx
|
2024-12-11 04:07:52 +03:00
|
|
|
if len(s.FallbackTag) > 0 {
|
|
|
|
core.RequireFeaturesAsync(s.ctx, func(observatory extension.Observatory) {
|
|
|
|
s.observatory = observatory
|
|
|
|
})
|
|
|
|
}
|
2024-05-05 17:07:40 +03:00
|
|
|
}
|
2024-02-18 06:51:37 +03:00
|
|
|
|
|
|
|
func (s *RandomStrategy) GetPrincipleTarget(strings []string) []string {
|
|
|
|
return strings
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *RandomStrategy) PickOutbound(candidates []string) string {
|
2024-05-05 17:07:40 +03:00
|
|
|
if s.observatory != nil {
|
|
|
|
observeReport, err := s.observatory.GetObservation(s.ctx)
|
|
|
|
if err == nil {
|
|
|
|
aliveTags := make([]string, 0)
|
|
|
|
if result, ok := observeReport.(*observatory.ObservationResult); ok {
|
|
|
|
status := result.Status
|
|
|
|
statusMap := make(map[string]*observatory.OutboundStatus)
|
|
|
|
for _, outboundStatus := range status {
|
|
|
|
statusMap[outboundStatus.OutboundTag] = outboundStatus
|
|
|
|
}
|
|
|
|
for _, candidate := range candidates {
|
|
|
|
if outboundStatus, found := statusMap[candidate]; found {
|
|
|
|
if outboundStatus.Alive {
|
|
|
|
aliveTags = append(aliveTags, candidate)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// unfound candidate is considered alive
|
|
|
|
aliveTags = append(aliveTags, candidate)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
candidates = aliveTags
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-18 06:51:37 +03:00
|
|
|
count := len(candidates)
|
|
|
|
if count == 0 {
|
|
|
|
// goes to fallbackTag
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return candidates[dice.Roll(count)]
|
|
|
|
}
|