Import upstream version 1.0.1+git20191002.1.f60b320
Debian Janitor
2 years ago
59 | 59 |
clock resolution, at high rates, the actual rate may be up to 1% different from
|
60 | 60 |
the specified rate.
|
61 | 61 |
|
|
62 |
#### func (*Bucket) Available
|
|
63 |
|
|
64 |
```go
|
|
65 |
func (tb *Bucket) Available() int64
|
|
66 |
```
|
|
67 |
Available returns the number of available tokens. It will be negative
|
|
68 |
when there are consumers waiting for tokens. Note that if this
|
|
69 |
returns greater than zero, it does not guarantee that calls that take
|
|
70 |
tokens from the buffer will succeed, as the number of available
|
|
71 |
tokens could have changed in the meantime. This method is intended
|
|
72 |
primarily for metrics reporting and debugging.
|
|
73 |
|
62 | 74 |
#### func (*Bucket) Rate
|
63 | 75 |
|
64 | 76 |
```go
|
309 | 309 |
// available in the bucket at the given time, which must
|
310 | 310 |
// be in the future (positive) with respect to tb.latestTick.
|
311 | 311 |
func (tb *Bucket) adjustavailableTokens(tick int64) {
|
|
312 |
lastTick := tb.latestTick
|
|
313 |
tb.latestTick = tick
|
312 | 314 |
if tb.availableTokens >= tb.capacity {
|
313 | 315 |
return
|
314 | 316 |
}
|
315 | |
tb.availableTokens += (tick - tb.latestTick) * tb.quantum
|
|
317 |
tb.availableTokens += (tick - lastTick) * tb.quantum
|
316 | 318 |
if tb.availableTokens > tb.capacity {
|
317 | 319 |
tb.availableTokens = tb.capacity
|
318 | 320 |
}
|
319 | |
tb.latestTick = tick
|
320 | 321 |
return
|
321 | 322 |
}
|
322 | 323 |
|
381 | 381 |
|
382 | 382 |
}
|
383 | 383 |
|
|
384 |
func TestNoBonusTokenAfterBucketIsFull(t *testing.T) {
|
|
385 |
tb := NewBucketWithQuantum(time.Second*1, 100, 20)
|
|
386 |
curAvail := tb.Available()
|
|
387 |
if curAvail != 100 {
|
|
388 |
t.Fatalf("initially: actual available = %d, expected = %d", curAvail, 100)
|
|
389 |
}
|
|
390 |
|
|
391 |
time.Sleep(time.Second * 5)
|
|
392 |
|
|
393 |
curAvail = tb.Available()
|
|
394 |
if curAvail != 100 {
|
|
395 |
t.Fatalf("after pause: actual available = %d, expected = %d", curAvail, 100)
|
|
396 |
}
|
|
397 |
|
|
398 |
cnt := tb.TakeAvailable(100)
|
|
399 |
if cnt != 100 {
|
|
400 |
t.Fatalf("taking: actual taken count = %d, expected = %d", cnt, 100)
|
|
401 |
}
|
|
402 |
|
|
403 |
curAvail = tb.Available()
|
|
404 |
if curAvail != 0 {
|
|
405 |
t.Fatalf("after taken: actual available = %d, expected = %d", curAvail, 0)
|
|
406 |
}
|
|
407 |
}
|
|
408 |
|
384 | 409 |
func BenchmarkWait(b *testing.B) {
|
385 | 410 |
tb := NewBucket(1, 16*1024)
|
386 | 411 |
for i := b.N - 1; i >= 0; i-- {
|