aqm.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package aqm
  2. import (
  3. "context"
  4. "go-common/library/container/queue/aqm"
  5. "go-common/library/ecode"
  6. bm "go-common/library/net/http/blademaster"
  7. "go-common/library/rate"
  8. "go-common/library/rate/limit"
  9. "go-common/library/stat/prom"
  10. )
  11. const (
  12. _family = "blademaster"
  13. )
  14. var (
  15. stats = prom.New().WithState("go_active_queue_mng", []string{"family", "title"})
  16. )
  17. // AQM aqm midleware.
  18. type AQM struct {
  19. limiter rate.Limiter
  20. }
  21. // New return a ratelimit midleware.
  22. func New(conf *aqm.Config) (s *AQM) {
  23. return &AQM{
  24. limiter: limit.New(conf),
  25. }
  26. }
  27. // Limit return a bm handler func.
  28. func (a *AQM) Limit() bm.HandlerFunc {
  29. return func(c *bm.Context) {
  30. done, err := a.limiter.Allow(c)
  31. if err != nil {
  32. stats.Incr(_family, c.Request.URL.Path[1:])
  33. // TODO: priority request.
  34. // c.JSON(nil, err)
  35. // c.Abort()
  36. return
  37. }
  38. defer func() {
  39. if c.Error != nil && !ecode.Deadline.Equal(c.Error) && c.Err() != context.DeadlineExceeded {
  40. done(rate.Ignore)
  41. return
  42. }
  43. done(rate.Success)
  44. }()
  45. c.Next()
  46. }
  47. }