| 1 | package g8 |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | // RateLimiter is a fixed rate limiter |
| 9 | type RateLimiter struct { |
| 10 | maximumExecutionsPerSecond int |
| 11 | executionsLeftInWindow int |
| 12 | windowStartTime time.Time |
| 13 | mutex sync.Mutex |
| 14 | } |
| 15 | |
| 16 | // NewRateLimiter creates a RateLimiter |
| 17 | func NewRateLimiter(maximumExecutionsPerSecond int) *RateLimiter { |
| 18 | return &RateLimiter{ |
| 19 | windowStartTime: time.Now(), |
| 20 | executionsLeftInWindow: maximumExecutionsPerSecond, |
| 21 | maximumExecutionsPerSecond: maximumExecutionsPerSecond, |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | // Try updates the number of executions if the rate limit quota hasn't been reached and returns whether the |
| 26 | // attempt was successful or not. |
| 27 | // |
| 28 | // Returns false if the execution was not successful (rate limit quota has been reached) |
| 29 | // Returns true if the execution was successful (rate limit quota has not been reached) |
| 30 | func (r *RateLimiter) Try() bool { |
| 31 | r.mutex.Lock() |
| 32 | defer r.mutex.Unlock() |
| 33 | if time.Now().Add(-time.Second).After(r.windowStartTime) { |
| 34 | r.windowStartTime = time.Now() |
| 35 | r.executionsLeftInWindow = r.maximumExecutionsPerSecond |
| 36 | } |
| 37 | if r.executionsLeftInWindow == 0 { |
| 38 | return false |
| 39 | } |
| 40 | r.executionsLeftInWindow-- |
| 41 | return true |
| 42 | } |