-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker_controller.go
68 lines (58 loc) · 1.37 KB
/
ticker_controller.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
package ratelimiter
import (
"context"
"errors"
"sync"
"time"
)
type TickerControllerOptions struct {
Ctx context.Context
// syncing, handy for tests, set to nil if do not use
Ticker chan<- struct{}
TickDuration time.Duration
}
type TickerController struct {
// i do not want external changes, so i store copy
opts TickerControllerOptions
// limiters under control
limiters []RateLimiter
limitersLock sync.Mutex
}
func (t *TickerController) controller() {
// Not protected from system hanging
// can skip some ticks in this case
ticker := time.NewTicker(t.opts.TickDuration)
for {
select {
case <-t.opts.Ctx.Done():
ticker.Stop()
return
case <-ticker.C:
if t.opts.Ticker != nil {
t.opts.Ticker <- struct{}{}
}
t.limitersLock.Lock()
for _, limiter := range t.limiters {
limiter.NextTick()
}
t.limitersLock.Unlock()
}
}
}
func (t *TickerController) AddLimiter(limiter RateLimiter) error {
if limiter.GetTickDuration() != t.opts.TickDuration {
return errors.New("limiter tick duration differs from ticker controller")
}
t.limitersLock.Lock()
defer t.limitersLock.Unlock()
t.limiters = append(t.limiters, limiter)
return nil
}
func NewTickerController(opts TickerControllerOptions) *TickerController {
tc := TickerController{
opts: opts,
limiters: make([]RateLimiter, 0, 1),
}
go tc.controller()
return &tc
}