-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixed_window.go
More file actions
57 lines (50 loc) · 1.29 KB
/
fixed_window.go
File metadata and controls
57 lines (50 loc) · 1.29 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package ratelimiter
import (
"sync"
"time"
)
type FixedWindowCounter struct {
rate int
interval time.Duration
count int
windowStart time.Time
mu sync.Mutex
timeProvider TimeProvider
}
// NewFixedWindowCounter creates a new FixedWindowCounter with a specified rate and interval.
// rate specifies the maximum number of requests per interval
// interval specifies the length of the time window
// tp is the TimeProvider that defines how current time is determined.
func NewFixedWindowCounter(rate int, interval time.Duration, tp TimeProvider) *FixedWindowCounter {
return &FixedWindowCounter{
rate: rate,
interval: interval,
count: 0,
windowStart: tp.Now(),
timeProvider: tp,
}
}
func (fwc *FixedWindowCounter) Allow() bool {
fwc.mu.Lock()
defer fwc.mu.Unlock()
now := fwc.timeProvider.Now()
// 1. Check if we're in a new window, if so reset the count
//
// windowStart now
// v v
// [----------------]
// interval
//
if now.Sub(fwc.windowStart) >= fwc.interval {
// Reset the window
fwc.count = 0
fwc.windowStart = now
}
// 2. If the count is less than the rate, increment and return true
if fwc.count < fwc.rate {
fwc.count++
return true
}
// 3. Otherwise, return false
return false
}