-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
70 lines (54 loc) · 1.52 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
package throttle
import (
"context"
"sync"
"time"
)
// MemoryThrottler in memory throttler
type MemoryThrottler struct {
mus map[string]*sync.Mutex
history map[string]time.Time
mu sync.Mutex
}
var _ Throttler = (*MemoryThrottler)(nil)
// NewMemoryThrottler creates a new MemoryThrottler
func NewMemoryThrottler() *MemoryThrottler {
return &MemoryThrottler{
mus: map[string]*sync.Mutex{},
history: map[string]time.Time{},
}
}
// DefaultMemoryThrottler a default MemoryThrottler
var DefaultMemoryThrottler = NewMemoryThrottler()
// New curried in memory throttling
func (m *MemoryThrottler) New(key string, duration time.Duration, fn func(ctx context.Context) error) func(context.Context) error {
return func(ctx context.Context) error {
return m.do(ctx, key, duration, fn)
}
}
// Do inline in memory throttling
func (m *MemoryThrottler) Do(ctx context.Context, key string, duration time.Duration, fn func(ctx context.Context) error) error {
return m.do(ctx, key, duration, fn)
}
func (m *MemoryThrottler) do(ctx context.Context, key string, duration time.Duration, fn func(ctx context.Context) error) error {
mu := m.getMutex(key)
mu.Lock()
defer mu.Unlock()
lastCall, ok := m.history[key]
if !ok || lastCall.Add(duration).Before(time.Now()) {
m.history[key] = time.Now()
return fn(ctx)
}
return ErrThrottled
}
func (m *MemoryThrottler) getMutex(key string) *sync.Mutex {
m.mu.Lock()
defer m.mu.Unlock()
mu, ok := m.mus[key]
if ok {
return mu
}
mu = &sync.Mutex{}
m.mus[key] = mu
return mu
}