weight.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package router
  2. import (
  3. "context"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "github.com/xtls/xray-core/common/errors"
  9. )
  10. type weightScaler func(value, weight float64) float64
  11. var numberFinder = regexp.MustCompile(`\d+(\.\d+)?`)
  12. // NewWeightManager creates a new WeightManager with settings
  13. func NewWeightManager(s []*StrategyWeight, defaultWeight float64, scaler weightScaler) *WeightManager {
  14. return &WeightManager{
  15. settings: s,
  16. cache: make(map[string]float64),
  17. scaler: scaler,
  18. defaultWeight: defaultWeight,
  19. }
  20. }
  21. // WeightManager manages weights for specific settings
  22. type WeightManager struct {
  23. settings []*StrategyWeight
  24. cache map[string]float64
  25. scaler weightScaler
  26. defaultWeight float64
  27. mu sync.Mutex
  28. }
  29. // Get get the weight of specified tag
  30. func (s *WeightManager) Get(tag string) float64 {
  31. s.mu.Lock()
  32. defer s.mu.Unlock()
  33. weight, ok := s.cache[tag]
  34. if ok {
  35. return weight
  36. }
  37. weight = s.findValue(tag)
  38. s.cache[tag] = weight
  39. return weight
  40. }
  41. // Apply applies weight to the value
  42. func (s *WeightManager) Apply(tag string, value float64) float64 {
  43. return s.scaler(value, s.Get(tag))
  44. }
  45. func (s *WeightManager) findValue(tag string) float64 {
  46. for _, w := range s.settings {
  47. matched := s.getMatch(tag, w.Match, w.Regexp)
  48. if matched == "" {
  49. continue
  50. }
  51. if w.Value > 0 {
  52. return float64(w.Value)
  53. }
  54. // auto weight from matched
  55. numStr := numberFinder.FindString(matched)
  56. if numStr == "" {
  57. return s.defaultWeight
  58. }
  59. weight, err := strconv.ParseFloat(numStr, 64)
  60. if err != nil {
  61. errors.LogError(context.Background(), "unexpected error from ParseFloat: ", err)
  62. return s.defaultWeight
  63. }
  64. return weight
  65. }
  66. return s.defaultWeight
  67. }
  68. func (s *WeightManager) getMatch(tag, find string, isRegexp bool) string {
  69. if !isRegexp {
  70. idx := strings.Index(tag, find)
  71. if idx < 0 {
  72. return ""
  73. }
  74. return find
  75. }
  76. r, err := regexp.Compile(find)
  77. if err != nil {
  78. errors.LogError(context.Background(), "invalid regexp: ", find, "err: ", err)
  79. return ""
  80. }
  81. return r.FindString(tag)
  82. }