-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimiter_wait.go
More file actions
253 lines (236 loc) · 9.15 KB
/
Copy pathlimiter_wait.go
File metadata and controls
253 lines (236 loc) · 9.15 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package rate
import (
"context"
"time"
"github.com/clipperhouse/ntime"
)
// Wait will poll [Allow] for a period of time,
// until it is cancelled by the passed context. It has the
// effect of adding latency to requests instead of refusing
// them immediately. Consider it graceful degradation.
//
// Wait will return true if a token becomes available prior to
// the context cancellation, and will consume a token. It will
// return false if not, and therefore not consume a token.
//
// Take care to create an appropriate context. You almost certainly
// want [context.WithTimeout] or [context.WithDeadline].
//
// You should be conservative, as Wait will introduce
// backpressure on your upstream systems -- connections
// may be held open longer, requests may queue in memory.
//
// A good starting place will be to timeout after waiting
// for one token. For example:
//
// ctx := context.WithTimeout(ctx, limit.DurationPerToken())
//
// The returned error will be non-nil if the context is cancelled.
//
// Wait makes no ordering guarantees. Multiple concurrent calls may
// acquire tokens in any order.
func (r *Limiter[TInput, TKey]) Wait(ctx context.Context, input TInput) (bool, error) {
return r.WaitN(ctx, input, 1)
}
// WaitN will poll [Limiter.AllowN] for a period of time,
// until it is cancelled by the passed context. It has the
// effect of adding latency to requests instead of refusing
// them immediately. Consider it graceful degradation.
//
// WaitN will return true if `n` tokens become available prior to
// the context cancellation, and will consume `n` tokens. If not,
// it will return false, and therefore consume no tokens.
//
// Take care to create an appropriate context. You almost certainly
// want [context.WithTimeout] or [context.WithDeadline].
//
// You should be conservative, as Wait will introduce
// backpressure on your upstream systems -- connections
// may be held open longer, requests may queue in memory.
//
// A good starting place will be to timeout after waiting
// for one token. For example:
//
// ctx := context.WithTimeout(ctx, limit.DurationPerToken())
//
// The returned error will be non-nil if the context is cancelled.
//
// WaitN makes no ordering guarantees. Multiple concurrent calls may
// acquire tokens in any order.
func (r *Limiter[TInput, TKey]) WaitN(ctx context.Context, input TInput, n int64) (bool, error) {
allow, _, err := r.waitNWithDetails(ctx, input, ntime.Now(), n)
return allow, err
}
// WaitWithDetails will poll [Allow] for a period of time,
// until it is cancelled by the passed context. It has the
// effect of adding latency to requests instead of refusing
// them immediately. Consider it graceful degradation.
//
// WaitWithDetails will return true if a token becomes available prior to
// the context cancellation, and will consume a token. It will
// return false if not, and therefore not consume a token. It will
// also return the details of the request.
//
// Take care to create an appropriate context. You almost certainly
// want [context.WithTimeout] or [context.WithDeadline].
//
// You should be conservative, as WaitWithDetails will introduce
// backpressure on your upstream systems -- connections
// may be held open longer, requests may queue in memory.
//
// A good starting place will be to timeout after waiting
// for one token. For example:
//
// ctx := context.WithTimeout(ctx, limit.DurationPerToken())
//
// The returned error will be non-nil if the context is cancelled.
//
// WaitWithDetails makes no ordering guarantees. Multiple concurrent calls may
// acquire tokens in any order.
func (r *Limiter[TInput, TKey]) WaitWithDetails(ctx context.Context, input TInput) (bool, Details[TInput, TKey], error) {
return r.WaitNWithDetails(ctx, input, 1)
}
// WaitNWithDetails will poll [Limiter.AllowN] for a period of time,
// until it is cancelled by the passed context. It has the
// effect of adding latency to requests instead of refusing
// them immediately. Consider it graceful degradation.
//
// WaitNWithDetails will return true if `n` tokens become available prior to
// the context cancellation, and will consume `n` tokens. If not,
// it will return false, and therefore consume no tokens. It will
// also return the details of the request.
//
// Take care to create an appropriate context. You almost certainly
// want [context.WithTimeout] or [context.WithDeadline].
//
// You should be conservative, as WaitWithDetails will introduce
// backpressure on your upstream systems -- connections
// may be held open longer, requests may queue in memory.
//
// A good starting place will be to timeout after waiting
// for one token. For example:
//
// ctx := context.WithTimeout(ctx, limit.DurationPerToken())
//
// The returned error will be non-nil if the context is cancelled.
//
// WaitWithDetails makes no ordering guarantees. Multiple concurrent calls may
// acquire tokens in any order.
func (r *Limiter[TInput, TKey]) WaitNWithDetails(ctx context.Context, input TInput, n int64) (bool, Details[TInput, TKey], error) {
return r.waitNWithDetails(ctx, input, ntime.Now(), n)
}
// waitNWithDetails is the internal implementation that accepts a context.
// It is designed to be testable by accepting any context implementation,
// including test contexts that provide deterministic behavior.
func (r *Limiter[TInput, TKey]) waitNWithDetails(
ctx context.Context,
input TInput,
startTime ntime.Time,
n int64,
) (bool, Details[TInput, TKey], error) {
// currentTime is an approximation of the real clock moving forward.
// It's imprecise because it depends on time.After below.
currentTime := startTime
for {
allow, details := r.allowNWithDetails(input, currentTime, n)
if allow {
return allow, details, nil
}
retryAfter := details.RetryAfter()
select {
case <-ctx.Done():
// Need to get updated details, since this cancellation
// event might have been a while after the last call.
allow, details := r.allowNWithDetails(input, currentTime, n)
return allow, details, ctx.Err()
case <-time.After(retryAfter):
currentTime = currentTime.Add(retryAfter)
}
}
}
// WaitWithDebug will poll [Limiter.Allow] for a period of time,
// until it is cancelled by the passed context. It has the
// effect of adding latency to requests instead of refusing
// them immediately. Consider it graceful degradation.
//
// WaitWithDebug will return true if a token becomes available prior to
// the context cancellation, and will consume a token. It will
// return false if not, and therefore not consume a token. It will
// also return the debugs of the request.
//
// Take care to create an appropriate context. You almost certainly
// want [context.WithTimeout] or [context.WithDeadline].
//
// The returned error will be non-nil if the context is cancelled.
//
// WaitNWithDebug makes no ordering guarantees. Multiple concurrent calls may
// acquire tokens in any order.
func (r *Limiter[TInput, TKey]) WaitWithDebug(
ctx context.Context,
input TInput,
) (bool, []Debug[TInput, TKey], error) {
return r.WaitNWithDebug(ctx, input, 1)
}
// WaitNWithDebug will poll [Limiter.AllowN] for a period of time,
// until it is cancelled by the passed context. It has the
// effect of adding latency to requests instead of refusing
// them immediately. Consider it graceful degradation.
//
// WaitNWithDebug will return true if `n` tokens become available prior to
// the context cancellation, and will consume `n` tokens. If not,
// it will return false, and therefore consume no tokens. It will
// also return the debugs of the request.
//
// Take care to create an appropriate context. You almost certainly
// want [context.WithTimeout] or [context.WithDeadline].
//
// The returned error will be non-nil if the context is cancelled.
//
// WaitNWithDebug makes no ordering guarantees. Multiple concurrent calls may
// acquire tokens in any order.
func (r *Limiter[TInput, TKey]) WaitNWithDebug(
ctx context.Context,
input TInput,
n int64,
) (bool, []Debug[TInput, TKey], error) {
return r.waitNWithDebug(ctx, input, ntime.Now(), n)
}
// waitNWithDetails is the internal implementation that accepts a context.
// It is designed to be testable by accepting any context implementation,
// including test contexts that provide deterministic behavior.
func (r *Limiter[TInput, TKey]) waitNWithDebug(
ctx context.Context,
input TInput,
startTime ntime.Time,
n int64,
) (bool, []Debug[TInput, TKey], error) {
// currentTime is an approximation of the real clock moving forward.
// It's imprecise because it depends on time.After below.
currentTime := startTime
for {
allow, debugs := r.allowNWithDebug(input, currentTime, n)
if allow {
return allow, debugs, nil
}
// len(debugs) will be greater than 0 here;
// if there were zero, allow was true
// Get the max retryAfter
retryAfter := debugs[0].RetryAfter()
for i := 1; i < len(debugs); i++ {
debug := debugs[i]
ra := debug.RetryAfter()
if ra > retryAfter {
retryAfter = ra
}
}
select {
case <-ctx.Done():
// Need to get updated debugs, since this cancellation
// event might have been a while after the last call.
allow, debugs := r.allowNWithDebug(input, currentTime, n)
return allow, debugs, ctx.Err()
case <-time.After(retryAfter):
currentTime = currentTime.Add(retryAfter)
}
}
}