-
Notifications
You must be signed in to change notification settings - Fork 3
/
slider.go
118 lines (106 loc) · 3.24 KB
/
slider.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
package equalizer
import (
"context"
"fmt"
"runtime"
"sync/atomic"
"time"
"github.com/reugn/equalizer/internal/async"
)
// A Slider represents a rate limiter which is based on a sliding window
// with a specified quota capacity. Implements the equalizer.Limiter interface.
//
// A Slider is safe for use by multiple goroutines simultaneously.
//
// The underlying slider instance ensures that the background goroutine does
// not keep the main Slider object from being garbage collected. When it is
// garbage collected, the finalizer stops the background goroutine, after
// which the underlying slider can be collected.
type Slider struct {
slider *slider
}
var _ Limiter = (*Slider)(nil)
type slider struct {
window time.Duration
slidingInterval time.Duration
capacity int
permits chan token
issued chan int64
windowStart atomic.Int64
windowShifter *async.Task
}
// NewSlider allocates and returns a new Slider rate limiter, where
// window is the fixed duration of the sliding window,
// slidingInterval controls how frequently a new sliding window is started and
// capacity is the quota limit for the window.
func NewSlider(window, slidingInterval time.Duration, capacity int) (*Slider, error) {
if capacity < 1 {
return nil, fmt.Errorf("nonpositive capacity: %d", capacity)
}
if slidingInterval > window {
return nil, fmt.Errorf("slidingInterval must not exceed window")
}
underlying := &slider{
window: window,
slidingInterval: slidingInterval,
capacity: capacity,
permits: make(chan token, capacity),
issued: make(chan int64, capacity),
windowShifter: async.NewTask(slidingInterval),
}
underlying.init()
// initialize a goroutine responsible for periodically moving the
// window forward
underlying.windowShifter.Run(underlying.slide)
slider := &Slider{
slider: underlying,
}
// the finalizer may run as soon as the slider becomes unreachable
runtime.SetFinalizer(slider, stopWindowShifter)
return slider, nil
}
// init initializes the permits channel by populating it with the
// specified number of tokens.
func (s *slider) init() {
for i := 0; i < s.capacity; i++ {
s.permits <- token{}
}
}
// slide moves the sliding window forward.
func (s *slider) slide() {
now := time.Now().UnixNano()
s.windowStart.Store(now)
for issuedTime := range s.issued {
s.permits <- token{}
if issuedTime >= now {
break
}
}
}
// Acquire blocks the calling goroutine until a token is acquired, the Context
// is canceled, or the wait time exceeds the Context's Deadline.
func (s *Slider) Acquire(ctx context.Context) error {
select {
case <-s.slider.permits:
s.slider.issued <- s.slider.windowStart.Load()
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// TryAcquire attempts to acquire a token without blocking.
// returns true if a token was acquired, false if no tokens are available.
func (s *Slider) TryAcquire() bool {
select {
case <-s.slider.permits:
s.slider.issued <- s.slider.windowStart.Load()
return true
default:
return false
}
}
// stopWindowShifter is the callback function used to terminate the goroutine
// responsible for periodically moving the sliding window.
func stopWindowShifter(s *Slider) {
s.slider.windowShifter.Stop()
}