-
Notifications
You must be signed in to change notification settings - Fork 8
/
memory.go
110 lines (90 loc) · 1.96 KB
/
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
package memory
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/cuigh/auxo/apm/limiter"
)
type counter struct {
expiry int64
remaining int64
}
func (c *counter) valid(now int64) bool {
return c.expiry > now
}
func (c *counter) reset(rate *limiter.Rate, now int64) {
c.expiry = now + rate.Period.Nanoseconds()
c.remaining = rate.Count
}
type Options struct {
PruneInterval time.Duration
}
type Store struct {
opts Options
locker sync.RWMutex
counters map[string]*counter
pruneFlag int32
pruneTime int64
}
func New(opts ...Options) *Store {
s := &Store{
counters: make(map[string]*counter),
}
if len(opts) > 0 {
s.opts = opts[0]
}
if s.opts.PruneInterval <= 0 {
s.opts.PruneInterval = time.Minute * 10
}
s.pruneTime = time.Now().Add(s.opts.PruneInterval).UnixNano()
return s
}
func (s *Store) Get(ctx context.Context, rate *limiter.Rate, key string) (res limiter.Resource, err error) {
res.Limit = rate.Count
now := time.Now().UnixNano()
s.locker.Lock()
c := s.counters[key]
if c == nil {
c = new(counter)
c.reset(rate, now)
s.counters[key] = c
} else if !c.valid(now) {
c.reset(rate, now)
}
c.remaining--
res.Reset = c.expiry
res.Remaining = c.remaining
s.locker.Unlock()
// auto clean expired counters
if s.pruneTime < now && atomic.CompareAndSwapInt32(&s.pruneFlag, 0, 1) {
go s.prune()
}
return
}
func (s *Store) Peek(ctx context.Context, rate *limiter.Rate, key string) (res limiter.Resource, err error) {
s.locker.RLock()
c := s.counters[key]
s.locker.RUnlock()
res.Limit = rate.Count
now := time.Now().UnixNano()
if c == nil || !c.valid(now) {
res.Remaining = rate.Count
res.Reset = now + rate.Period.Nanoseconds()
} else {
res.Remaining = c.remaining
res.Reset = c.expiry
}
return
}
func (s *Store) prune() {
s.locker.Lock()
defer s.locker.Unlock()
now := time.Now().UnixNano()
for key, value := range s.counters {
if !value.valid(now) {
delete(s.counters, key)
}
}
s.pruneFlag = 0
}