Debian Codegraph @

api/v1/lib/backoff/backoff.go

raw symbols SCIP
1 package backoff
2
3 import (
4 "fmt"
5 "reflect"
6 "time"
7 )
8
9 func BurstNotifier(burst int, minWait, maxWait time.Duration, until <-chan struct{}) <-chan struct{} {
10 if burst < 1 {
11 return nil // no limit
12 }
13 if burst == 1 {
14 return Notifier(minWait, maxWait, until)
15 }
16
17 // build a synamic select/case statement based on burst size
18 cases := make([]reflect.SelectCase, burst+1)
19 for i := 0; i < burst; i++ {
20 ch := Notifier(minWait, maxWait, until)
21 cases[i].Dir = reflect.SelectRecv
22 cases[i].Chan = reflect.ValueOf(ch)
23 }
24 cases[burst].Dir = reflect.SelectRecv
25 cases[burst].Chan = reflect.ValueOf(until)
26
27 // listen for tokens emitted by child buckets and forward them to the tokens chan
28 tokens := make(chan struct{})
29 go func() {
30 defer close(tokens)
31 for {
32 i, _, _ := reflect.Select(cases)
33 if i == burst {
34 // special case: this is the "until" chan
35 return
36 }
37 // otherwise we got a signal from a child bucket that we need to forward
38 select {
39 case tokens <- struct{}{}:
40 case <-until:
41 return
42 }
43 }
44 }()
45 return tokens
46 }
47
48 // Notifier returns a chan that yields a struct{}{} every so often. the wait period
49 // between structs is between minWait and maxWait. greedy consumers that continuously read
50 // from the returned chan will see the wait period generally increase.
51 //
52 // Note: this func panics if minWait is a non-positive value to avoid busy-looping.
53 func Notifier(minWait, maxWait time.Duration, until <-chan struct{}) <-chan struct{} {
54 // TODO(jdef) add jitter to this func
55 if maxWait < minWait {
56 maxWait, minWait = minWait, maxWait
57 }
58 if minWait <= 0 {
59 panic(fmt.Sprintf("illegal value for minWait: %v", minWait))
60 }
61 tokens := make(chan struct{})
62 limiter := tokens
63 go func() {
64 d := 0 * time.Second
65 t := time.NewTimer(d)
66 defer t.Stop()
67 for {
68 select {
69 case limiter <- struct{}{}:
70 d *= 2
71 if d > maxWait {
72 d = maxWait
73 }
74 limiter = nil
75 case <-t.C:
76 if limiter != nil {
77 d /= 2
78 } else {
79 limiter = tokens
80 }
81 case <-until:
82 return
83 }
84 // important to have non-zero minWait otherwise we busy-loop
85 if d == 0 {
86 d = minWait
87 }
88 t.Reset(d)
89 }
90 }()
91 return tokens
92 }