Debian Codegraph @

util/limit.go

raw
1 package util
2
3 import (
4 "errors"
5 "golang.org/x/time/rate"
6 "io"
7 "sync"
8 "time"
9 )
10
11 // ErrLimitReached is the error returned by the Limiter and LimitWriter when the predefined limit has been reached
12 var ErrLimitReached = errors.New("limit reached")
13
14 // Limiter is an interface that implements a rate limiting mechanism, e.g. based on time or a fixed value
15 type Limiter interface {
16 // Allow adds one to the limiters value, or returns false if the limit has been reached
17 Allow() bool
18
19 // AllowN adds n to the limiters value, or returns false if the limit has been reached
20 AllowN(n int64) bool
21
22 // Value returns the current internal limiter value
23 Value() int64
24
25 // Reset resets the state of the limiter
26 Reset()
27 }
28
29 // FixedLimiter is a helper that allows adding values up to a well-defined limit. Once the limit is reached
30 // ErrLimitReached will be returned. FixedLimiter may be used by multiple goroutines.
31 type FixedLimiter struct {
32 value int64
33 limit int64
34 mu sync.Mutex
35 }
36
37 var _ Limiter = (*FixedLimiter)(nil)
38
39 // NewFixedLimiter creates a new Limiter
40 func NewFixedLimiter(limit int64) *FixedLimiter {
41 return NewFixedLimiterWithValue(limit, 0)
42 }
43
44 // NewFixedLimiterWithValue creates a new Limiter and sets the initial value
45 func NewFixedLimiterWithValue(limit, value int64) *FixedLimiter {
46 return &FixedLimiter{
47 limit: limit,
48 value: value,
49 }
50 }
51
52 // Allow adds one to the limiters internal value, but only if the limit has not been reached. If the limit was
53 // exceeded, false is returned.
54 func (l *FixedLimiter) Allow() bool {
55 return l.AllowN(1)
56 }
57
58 // AllowN adds n to the limiters internal value, but only if the limit has not been reached. If the limit was
59 // exceeded after adding n, false is returned.
60 func (l *FixedLimiter) AllowN(n int64) bool {
61 l.mu.Lock()
62 defer l.mu.Unlock()
63 if l.value+n > l.limit {
64 return false
65 }
66 l.value += n
67 return true
68 }
69
70 // Value returns the current limiter value
71 func (l *FixedLimiter) Value() int64 {
72 l.mu.Lock()
73 defer l.mu.Unlock()
74 return l.value
75 }
76
77 // Reset sets the limiter's value back to zero
78 func (l *FixedLimiter) Reset() {
79 l.mu.Lock()
80 defer l.mu.Unlock()
81 l.value = 0
82 }
83
84 // RateLimiter is a Limiter that wraps a rate.Limiter, allowing a floating time-based limit.
85 type RateLimiter struct {
86 r rate.Limit
87 b int
88 value int64
89 limiter *rate.Limiter
90 mu sync.Mutex
91 }
92
93 var _ Limiter = (*RateLimiter)(nil)
94
95 // NewRateLimiter creates a new RateLimiter
96 func NewRateLimiter(r rate.Limit, b int) *RateLimiter {
97 return NewRateLimiterWithValue(r, b, 0)
98 }
99
100 // NewRateLimiterWithValue creates a new RateLimiter with the given starting value.
101 //
102 // Note that the starting value only has informational value. It does not impact the underlying
103 // value of the rate.Limiter.
104 func NewRateLimiterWithValue(r rate.Limit, b int, value int64) *RateLimiter {
105 return &RateLimiter{
106 r: r,
107 b: b,
108 value: value,
109 limiter: rate.NewLimiter(r, b),
110 }
111 }
112
113 // NewBytesLimiter creates a RateLimiter that is meant to be used for a bytes-per-interval limit,
114 // e.g. 250 MB per day. And example of the underlying idea can be found here: https://go.dev/play/p/0ljgzIZQ6dJ
115 func NewBytesLimiter(bytes int, interval time.Duration) *RateLimiter {
116 return NewRateLimiter(rate.Limit(bytes)*rate.Every(interval), bytes)
117 }
118
119 // Allow adds one to the limiters internal value, but only if the limit has not been reached. If the limit was
120 // exceeded, false is returned.
121 func (l *RateLimiter) Allow() bool {
122 return l.AllowN(1)
123 }
124
125 // AllowN adds n to the limiters internal value, but only if the limit has not been reached. If the limit was
126 // exceeded after adding n, false is returned.
127 func (l *RateLimiter) AllowN(n int64) bool {
128 if n <= 0 {
129 return false // No-op. Can't take back bytes you're written!
130 }
131 l.mu.Lock()
132 defer l.mu.Unlock()
133 if !l.limiter.AllowN(time.Now(), int(n)) {
134 return false
135 }
136 l.value += n
137 return true
138 }
139
140 // Value returns the current limiter value
141 func (l *RateLimiter) Value() int64 {
142 l.mu.Lock()
143 defer l.mu.Unlock()
144 return l.value
145 }
146
147 // Reset sets the limiter's value back to zero, and resets the underlying rate.Limiter
148 func (l *RateLimiter) Reset() {
149 l.mu.Lock()
150 defer l.mu.Unlock()
151 l.limiter = rate.NewLimiter(l.r, l.b)
152 l.value = 0
153 }
154
155 // CountingReader wraps an io.Reader and counts the number of bytes read through it.
156 type CountingReader struct {
157 r io.Reader
158 total int64
159 }
160
161 // NewCountingReader creates a new CountingReader
162 func NewCountingReader(r io.Reader) *CountingReader {
163 return &CountingReader{r: r}
164 }
165
166 // Read passes through to the underlying reader and counts the bytes read
167 func (r *CountingReader) Read(p []byte) (n int, err error) {
168 n, err = r.r.Read(p)
169 r.total += int64(n)
170 return
171 }
172
173 // Total returns the total number of bytes read so far
174 func (r *CountingReader) Total() int64 {
175 return r.total
176 }
177
178 // LimitReader implements an io.Reader that will pass through all Read calls to the underlying
179 // reader r until any of the limiter's limit is reached, at which point a Read will return ErrLimitReached.
180 // Each limiter's value is increased after every read based on the number of bytes actually read.
181 type LimitReader struct {
182 r io.Reader
183 limiters []Limiter
184 }
185
186 // NewLimitReader creates a new LimitReader
187 func NewLimitReader(r io.Reader, limiters ...Limiter) *LimitReader {
188 return &LimitReader{
189 r: r,
190 limiters: limiters,
191 }
192 }
193
194 // Read passes through all reads to the underlying reader until any of the given limiter's limit is reached
195 func (r *LimitReader) Read(p []byte) (n int, err error) {
196 n, err = r.r.Read(p)
197 if n > 0 {
198 for i := 0; i < len(r.limiters); i++ {
199 if !r.limiters[i].AllowN(int64(n)) {
200 for j := i - 1; j >= 0; j-- {
201 r.limiters[j].AllowN(-int64(n)) // Revert limiters if not allowed
202 }
203 return 0, ErrLimitReached
204 }
205 }
206 }
207 return
208 }
209
210 // LimitWriter implements an io.Writer that will pass through all Write calls to the underlying
211 // writer w until any of the limiter's limit is reached, at which point a Write will return ErrLimitReached.
212 // Each limiter's value is increased with every write.
213 type LimitWriter struct {
214 w io.Writer
215 written int64
216 limiters []Limiter
217 mu sync.Mutex
218 }
219
220 // NewLimitWriter creates a new LimitWriter
221 func NewLimitWriter(w io.Writer, limiters ...Limiter) *LimitWriter {
222 return &LimitWriter{
223 w: w,
224 limiters: limiters,
225 }
226 }
227
228 // Write passes through all writes to the underlying writer until any of the given limiter's limit is reached
229 func (w *LimitWriter) Write(p []byte) (n int, err error) {
230 w.mu.Lock()
231 defer w.mu.Unlock()
232 for i := 0; i < len(w.limiters); i++ {
233 if !w.limiters[i].AllowN(int64(len(p))) {
234 for j := i - 1; j >= 0; j-- {
235 w.limiters[j].AllowN(-int64(len(p))) // Revert limiters limits if not allowed
236 }
237 return 0, ErrLimitReached
238 }
239 }
240 n, err = w.w.Write(p)
241 w.written += int64(n)
242 return
243 }