File tree Expand file tree Collapse file tree 1 file changed +46
-1
lines changed
Expand file tree Collapse file tree 1 file changed +46
-1
lines changed Original file line number Diff line number Diff line change 1- // internal/algorithm/sliding_window.go
1+ package algorithm
2+
3+ import (
4+ "sync"
5+ "time"
6+ )
7+
8+ type SlidingWindow struct {
9+ mu sync.Mutex
10+ requests []time.Time
11+ limit int
12+ window time.Duration
13+ }
14+
15+ func NewSlidingWindoe (limit int , window time.Duration ) * SlidingWindow {
16+ return & SlidingWindow {limit : limit , window : window }
17+ }
18+
19+ func (sw : * SlidingWindow ) Allow () bool {
20+ sw .mu .Lock ()
21+ defer sw .mu .Unlock ()
22+
23+ now := time .Now ()
24+ cutoff := now .Add (- sw .window )
25+
26+ valid := sw .requests [:0 ]
27+ for _ , t := range sw .requests {
28+ if t .After (cutoff ) {
29+ valid = append (valid , t )
30+ }
31+ }
32+ sw .requests = valid
33+
34+ if len (sw .requests ) >= sw .limit {
35+ return false
36+ }
37+
38+ sw .requests = append (sw .requests , now )
39+ return true
40+ }
41+
42+ func (sw * SlidingWindow ) Count () int {
43+ sw .mu .Lock ()
44+ defer sw .mu .Unlock ()
45+ return len (sw .requests )
46+ }
You can’t perform that action at this time.
0 commit comments