-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_limiter.go
57 lines (44 loc) · 1.01 KB
/
base_limiter.go
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"
"sync/atomic"
"time"
)
type LimiterOptions struct {
//limit of requests
Limit int32
//whole window interval, limit sets per window
Interval time.Duration
//one tick of sliding window interval
Tick time.Duration
}
type Limiter struct {
opts LimiterOptions //do not want external changes, so copy
requestsLock sync.RWMutex
//total requests allowed for current tick
total int32
//already used requests for current tick
used int32
}
func (l *Limiter) IsTokenExists() bool {
l.requestsLock.RLock()
defer l.requestsLock.RUnlock()
return atomic.LoadInt32(&l.used) < l.total
}
func (l *Limiter) GetTokens(amount int32) (actual int32) {
l.requestsLock.RLock()
defer l.requestsLock.RUnlock()
//return up to actual amount of ticks
actual = l.total - atomic.LoadInt32(&l.used)
if actual < 0 {
actual = 0
}
if actual > amount {
actual = amount
}
atomic.AddInt32(&l.used, actual)
return actual
}
func (l *Limiter) GetTickDuration() time.Duration {
return l.opts.Tick
}