-
Notifications
You must be signed in to change notification settings - Fork 11
/
ratelimiter_memory.go
175 lines (162 loc) · 3.72 KB
/
ratelimiter_memory.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package ratelimiter
import (
"errors"
"sync"
"time"
)
// Inmemory Limiter imp
// policy status
type (
statusCacheItem struct {
index int
expire time.Time
}
// limit status
limiterCacheItem struct {
total int
remaining int
duration time.Duration
expire time.Time
}
memoryLimiter struct {
max int
duration time.Duration
status map[string]*statusCacheItem
store map[string]*limiterCacheItem
ticker *time.Ticker
lock sync.Mutex
}
)
func newMemoryLimiter(opts *RateLimiterConfig) *limiter {
m := &memoryLimiter{
max: opts.Max,
duration: opts.Duration,
store: make(map[string]*limiterCacheItem),
status: make(map[string]*statusCacheItem),
ticker: time.NewTicker(time.Second),
}
go m.cleanCache()
return &limiter{m, opts.Prefix}
}
// abstractLimiter interface
func (m *memoryLimiter) getLimit(key string, policy ...int) ([]interface{}, error) {
length := len(policy)
var args []int
if length == 0 {
args = []int{m.max, int(m.duration / time.Millisecond)}
} else {
args = make([]int, length)
for i, val := range policy {
if val <= 0 {
return nil, errors.New("ratelimiter: must be positive integer")
}
args[i] = policy[i]
}
}
res := m.getItem(key, args...)
m.lock.Lock()
defer m.lock.Unlock()
return []interface{}{res.remaining, res.total, res.duration, res.expire}, nil
}
// abstractLimiter interface
func (m *memoryLimiter) removeLimit(key string) error {
statusKey := "{" + key + "}:S"
m.lock.Lock()
defer m.lock.Unlock()
delete(m.store, key)
delete(m.status, statusKey)
return nil
}
func (m *memoryLimiter) clean() {
m.lock.Lock()
defer m.lock.Unlock()
start := time.Now()
expireTime := start.Add(time.Millisecond * 100)
frequency := 24
var expired int
for {
label:
for i := 0; i < frequency; i++ {
for key, value := range m.store {
if value.expire.Add(value.duration).Before(start) {
statusKey := "{" + key + "}:S"
delete(m.store, key)
delete(m.status, statusKey)
expired++
}
break
}
}
if expireTime.Before(time.Now()) {
return
}
if expired > frequency/4 {
expired = 0
goto label
}
return
}
}
func (m *memoryLimiter) getItem(key string, args ...int) (res *limiterCacheItem) {
policyCount := len(args) / 2
statusKey := "{" + key + "}:S"
m.lock.Lock()
defer m.lock.Unlock()
var ok bool
if res, ok = m.store[key]; !ok {
res = &limiterCacheItem{
total: args[0],
remaining: args[0] - 1,
duration: time.Duration(args[1]) * time.Millisecond,
expire: time.Now().Add(time.Duration(args[1]) * time.Millisecond),
}
m.store[key] = res
return
}
if res.expire.After(time.Now()) {
if policyCount > 1 && res.remaining-1 == -1 {
statusItem, ok := m.status[statusKey]
if ok {
statusItem.expire = time.Now().Add(res.duration * 2)
statusItem.index++
} else {
statusItem := &statusCacheItem{
index: 2,
expire: time.Now().Add(time.Duration(args[1]) * time.Millisecond * 2),
}
m.status[statusKey] = statusItem
}
}
if res.remaining >= 0 {
res.remaining--
} else {
res.remaining = -1
}
} else {
index := 1
if policyCount > 1 {
if statusItem, ok := m.status[statusKey]; ok {
if statusItem.expire.Before(time.Now()) {
index = 1
} else if statusItem.index > policyCount {
index = policyCount
} else {
index = statusItem.index
}
statusItem.index = index
}
}
total := args[(index*2)-2]
duration := args[(index*2)-1]
res.total = total
res.remaining = total - 1
res.duration = time.Duration(duration) * time.Millisecond
res.expire = time.Now().Add(time.Duration(duration) * time.Millisecond)
}
return
}
func (m *memoryLimiter) cleanCache() {
for range m.ticker.C {
m.clean()
}
}