File: ratelimiter.go

package info (click to toggle)
golang-github-twin-g8 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 192 kB
  • sloc: makefile: 2
file content (42 lines) | stat: -rw-r--r-- 1,190 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package g8

import (
	"sync"
	"time"
)

// RateLimiter is a fixed rate limiter
type RateLimiter struct {
	maximumExecutionsPerSecond int
	executionsLeftInWindow     int
	windowStartTime            time.Time
	mutex                      sync.Mutex
}

// NewRateLimiter creates a RateLimiter
func NewRateLimiter(maximumExecutionsPerSecond int) *RateLimiter {
	return &RateLimiter{
		windowStartTime:            time.Now(),
		executionsLeftInWindow:     maximumExecutionsPerSecond,
		maximumExecutionsPerSecond: maximumExecutionsPerSecond,
	}
}

// Try updates the number of executions if the rate limit quota hasn't been reached and returns whether the
// attempt was successful or not.
//
// Returns false if the execution was not successful (rate limit quota has been reached)
// Returns true if the execution was successful (rate limit quota has not been reached)
func (r *RateLimiter) Try() bool {
	r.mutex.Lock()
	defer r.mutex.Unlock()
	if time.Now().Add(-time.Second).After(r.windowStartTime) {
		r.windowStartTime = time.Now()
		r.executionsLeftInWindow = r.maximumExecutionsPerSecond
	}
	if r.executionsLeftInWindow == 0 {
		return false
	}
	r.executionsLeftInWindow--
	return true
}