limit.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package util
  2. import (
  3. "errors"
  4. "golang.org/x/time/rate"
  5. "io"
  6. "sync"
  7. "time"
  8. )
  9. // ErrLimitReached is the error returned by the Limiter and LimitWriter when the predefined limit has been reached
  10. var ErrLimitReached = errors.New("limit reached")
  11. // Limiter is an interface that implements a rate limiting mechanism, e.g. based on time or a fixed value
  12. type Limiter interface {
  13. // Allow adds n to the limiters internal value, or returns ErrLimitReached if the limit has been reached
  14. Allow(n int64) error
  15. }
  16. // FixedLimiter is a helper that allows adding values up to a well-defined limit. Once the limit is reached
  17. // ErrLimitReached will be returned. FixedLimiter may be used by multiple goroutines.
  18. type FixedLimiter struct {
  19. value int64
  20. limit int64
  21. mu sync.Mutex
  22. }
  23. // NewFixedLimiter creates a new Limiter
  24. func NewFixedLimiter(limit int64) *FixedLimiter {
  25. return &FixedLimiter{
  26. limit: limit,
  27. }
  28. }
  29. // Allow adds n to the limiters internal value, but only if the limit has not been reached. If the limit was
  30. // exceeded after adding n, ErrLimitReached is returned.
  31. func (l *FixedLimiter) Allow(n int64) error {
  32. l.mu.Lock()
  33. defer l.mu.Unlock()
  34. if l.value+n > l.limit {
  35. return ErrLimitReached
  36. }
  37. l.value += n
  38. return nil
  39. }
  40. // RateLimiter is a Limiter that wraps a rate.Limiter, allowing a floating time-based limit.
  41. type RateLimiter struct {
  42. limiter *rate.Limiter
  43. }
  44. // NewRateLimiter creates a new RateLimiter
  45. func NewRateLimiter(r rate.Limit, b int) *RateLimiter {
  46. return &RateLimiter{
  47. limiter: rate.NewLimiter(r, b),
  48. }
  49. }
  50. // NewBytesLimiter creates a RateLimiter that is meant to be used for a bytes-per-interval limit,
  51. // e.g. 250 MB per day. And example of the underlying idea can be found here: https://go.dev/play/p/0ljgzIZQ6dJ
  52. func NewBytesLimiter(bytes int, interval time.Duration) *RateLimiter {
  53. return NewRateLimiter(rate.Limit(bytes)*rate.Every(interval), bytes)
  54. }
  55. // Allow adds n to the limiters internal value, but only if the limit has not been reached. If the limit was
  56. // exceeded after adding n, ErrLimitReached is returned.
  57. func (l *RateLimiter) Allow(n int64) error {
  58. if n <= 0 {
  59. return nil // No-op. Can't take back bytes you're written!
  60. }
  61. if !l.limiter.AllowN(time.Now(), int(n)) {
  62. return ErrLimitReached
  63. }
  64. return nil
  65. }
  66. // LimitWriter implements an io.Writer that will pass through all Write calls to the underlying
  67. // writer w until any of the limiter's limit is reached, at which point a Write will return ErrLimitReached.
  68. // Each limiter's value is increased with every write.
  69. type LimitWriter struct {
  70. w io.Writer
  71. written int64
  72. limiters []Limiter
  73. mu sync.Mutex
  74. }
  75. // NewLimitWriter creates a new LimitWriter
  76. func NewLimitWriter(w io.Writer, limiters ...Limiter) *LimitWriter {
  77. return &LimitWriter{
  78. w: w,
  79. limiters: limiters,
  80. }
  81. }
  82. // Write passes through all writes to the underlying writer until any of the given limiter's limit is reached
  83. func (w *LimitWriter) Write(p []byte) (n int, err error) {
  84. w.mu.Lock()
  85. defer w.mu.Unlock()
  86. for i := 0; i < len(w.limiters); i++ {
  87. if err := w.limiters[i].Allow(int64(len(p))); err != nil {
  88. for j := i - 1; j >= 0; j-- {
  89. w.limiters[j].Allow(-int64(len(p))) // Revert limiters limits if allowed
  90. }
  91. return 0, ErrLimitReached
  92. }
  93. }
  94. n, err = w.w.Write(p)
  95. w.written += int64(n)
  96. return
  97. }