weight.go 2.0 KB

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