-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleaky_bucket.go
47 lines (38 loc) · 1.29 KB
/
leaky_bucket.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
package rlimit
import (
"time"
"github.com/valsov/rlimit/storage"
)
type LeakyBucketConfig struct {
NewTokensRate time.Duration
NewTokensCount int
BucketSize int
}
type LeakyBucketValue struct {
LastCheckedUtc time.Time
RemainingTokens int
}
type LeakyBucketLimiter struct{}
func NewLeakyBucketLimiter(storageProvider storage.Storage[LeakyBucketConfig, LeakyBucketValue], globalConfig LeakyBucketConfig) *RateLimiter[LeakyBucketConfig, LeakyBucketValue] {
return &RateLimiter[LeakyBucketConfig, LeakyBucketValue]{
store: storageProvider,
InternalLimiter: &LeakyBucketLimiter{},
GlobalConfig: globalConfig,
}
}
func (l *LeakyBucketLimiter) TryAllow(count int, config LeakyBucketConfig, userValue LeakyBucketValue, nowUtc time.Time) (bool, LeakyBucketValue) {
// Compute current bucket fill
sinceLastCheck := nowUtc.Sub(userValue.LastCheckedUtc)
refillTimes := int(sinceLastCheck.Seconds() / config.NewTokensRate.Seconds())
userValue.RemainingTokens += refillTimes * config.NewTokensCount
if userValue.RemainingTokens > config.BucketSize {
userValue.RemainingTokens = config.BucketSize
}
// Try allow count
allow := userValue.RemainingTokens >= count
if allow {
userValue.RemainingTokens -= count
}
userValue.LastCheckedUtc = nowUtc
return allow, userValue
}