throttle.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package middleware
  2. import (
  3. "net/http"
  4. "strconv"
  5. "time"
  6. )
  7. const (
  8. errCapacityExceeded = "Server capacity exceeded."
  9. errTimedOut = "Timed out while waiting for a pending request to complete."
  10. errContextCanceled = "Context was canceled."
  11. )
  12. var (
  13. defaultBacklogTimeout = time.Second * 60
  14. )
  15. // ThrottleOpts represents a set of throttling options.
  16. type ThrottleOpts struct {
  17. RetryAfterFn func(ctxDone bool) time.Duration
  18. Limit int
  19. BacklogLimit int
  20. BacklogTimeout time.Duration
  21. StatusCode int
  22. }
  23. // Throttle is a middleware that limits number of currently processed requests
  24. // at a time across all users. Note: Throttle is not a rate-limiter per user,
  25. // instead it just puts a ceiling on the number of current in-flight requests
  26. // being processed from the point from where the Throttle middleware is mounted.
  27. func Throttle(limit int) func(http.Handler) http.Handler {
  28. return ThrottleWithOpts(ThrottleOpts{Limit: limit, BacklogTimeout: defaultBacklogTimeout})
  29. }
  30. // ThrottleBacklog is a middleware that limits number of currently processed
  31. // requests at a time and provides a backlog for holding a finite number of
  32. // pending requests.
  33. func ThrottleBacklog(limit, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler {
  34. return ThrottleWithOpts(ThrottleOpts{Limit: limit, BacklogLimit: backlogLimit, BacklogTimeout: backlogTimeout})
  35. }
  36. // ThrottleWithOpts is a middleware that limits number of currently processed requests using passed ThrottleOpts.
  37. func ThrottleWithOpts(opts ThrottleOpts) func(http.Handler) http.Handler {
  38. if opts.Limit < 1 {
  39. panic("chi/middleware: Throttle expects limit > 0")
  40. }
  41. if opts.BacklogLimit < 0 {
  42. panic("chi/middleware: Throttle expects backlogLimit to be positive")
  43. }
  44. statusCode := opts.StatusCode
  45. if statusCode == 0 {
  46. statusCode = http.StatusTooManyRequests
  47. }
  48. t := throttler{
  49. tokens: make(chan token, opts.Limit),
  50. backlogTokens: make(chan token, opts.Limit+opts.BacklogLimit),
  51. backlogTimeout: opts.BacklogTimeout,
  52. statusCode: statusCode,
  53. retryAfterFn: opts.RetryAfterFn,
  54. }
  55. // Filling tokens.
  56. for i := 0; i < opts.Limit+opts.BacklogLimit; i++ {
  57. if i < opts.Limit {
  58. t.tokens <- token{}
  59. }
  60. t.backlogTokens <- token{}
  61. }
  62. return func(next http.Handler) http.Handler {
  63. fn := func(w http.ResponseWriter, r *http.Request) {
  64. ctx := r.Context()
  65. select {
  66. case <-ctx.Done():
  67. t.setRetryAfterHeaderIfNeeded(w, true)
  68. http.Error(w, errContextCanceled, t.statusCode)
  69. return
  70. case btok := <-t.backlogTokens:
  71. defer func() {
  72. t.backlogTokens <- btok
  73. }()
  74. // Try to get a processing token immediately first
  75. select {
  76. case tok := <-t.tokens:
  77. defer func() {
  78. t.tokens <- tok
  79. }()
  80. next.ServeHTTP(w, r)
  81. return
  82. default:
  83. // No immediate token available, need to wait with timer
  84. }
  85. timer := time.NewTimer(t.backlogTimeout)
  86. select {
  87. case <-timer.C:
  88. t.setRetryAfterHeaderIfNeeded(w, false)
  89. http.Error(w, errTimedOut, t.statusCode)
  90. return
  91. case <-ctx.Done():
  92. timer.Stop()
  93. t.setRetryAfterHeaderIfNeeded(w, true)
  94. http.Error(w, errContextCanceled, t.statusCode)
  95. return
  96. case tok := <-t.tokens:
  97. defer func() {
  98. timer.Stop()
  99. t.tokens <- tok
  100. }()
  101. next.ServeHTTP(w, r)
  102. }
  103. return
  104. default:
  105. t.setRetryAfterHeaderIfNeeded(w, false)
  106. http.Error(w, errCapacityExceeded, t.statusCode)
  107. return
  108. }
  109. }
  110. return http.HandlerFunc(fn)
  111. }
  112. }
  113. // token represents a request that is being processed.
  114. type token struct{}
  115. // throttler limits number of currently processed requests at a time.
  116. type throttler struct {
  117. tokens chan token
  118. backlogTokens chan token
  119. retryAfterFn func(ctxDone bool) time.Duration
  120. backlogTimeout time.Duration
  121. statusCode int
  122. }
  123. // setRetryAfterHeaderIfNeeded sets Retry-After HTTP header if corresponding retryAfterFn option of throttler is initialized.
  124. func (t throttler) setRetryAfterHeaderIfNeeded(w http.ResponseWriter, ctxDone bool) {
  125. if t.retryAfterFn == nil {
  126. return
  127. }
  128. w.Header().Set("Retry-After", strconv.Itoa(int(t.retryAfterFn(ctxDone).Seconds())))
  129. }