| 1 |
package server |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
// rateLimiter is a rate limiter for the server. |
| 9 |
// If more than limit requests are made in the time window, the server will return 429. |
| 10 |
type rateLimiter struct { |
| 11 |
// limit is the rate limit to apply to the server. |
| 12 |
limit int |
| 13 |
|
| 14 |
// window is the window in which to apply the rate limit. |
| 15 |
window time.Duration |
| 16 |
|
| 17 |
// nextReset is the time at which the rate limit will reset. |
| 18 |
nextReset time.Time |
| 19 |
|
| 20 |
// count is the number of calls made to the server. |
| 21 |
count int |
| 22 |
|
| 23 |
// countLock is a mutex for the callCount. |
| 24 |
countLock sync.Mutex |
| 25 |
|
| 26 |
// statusCode to reply with |
| 27 |
statusCode int |
| 28 |
} |
| 29 |
|
| 30 |
func newRateLimiter(limit int, window time.Duration, statusCode int) *rateLimiter { |
| 31 |
return &rateLimiter{ |
| 32 |
limit: limit, |
| 33 |
window: window, |
| 34 |
statusCode: statusCode, |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
// exceeded checks the rate limit and returns how long to wait before the next request. |
| 39 |
func (r *rateLimiter) exceeded() time.Duration { |
| 40 |
r.countLock.Lock() |
| 41 |
defer r.countLock.Unlock() |
| 42 |
|
| 43 |
if time.Now().After(r.nextReset) { |
| 44 |
r.count = 0 |
| 45 |
r.nextReset = time.Now().Add(r.window) |
| 46 |
} |
| 47 |
|
| 48 |
r.count++ |
| 49 |
|
| 50 |
if r.count > r.limit { |
| 51 |
return time.Until(r.nextReset) |
| 52 |
} |
| 53 |
|
| 54 |
return 0 |
| 55 |
} |