| 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 |
| 12 |
} |
| 13 |
if burst == 1 { |
| 14 |
return Notifier(minWait, maxWait, until) |
| 15 |
} |
| 16 |
|
| 17 |
|
| 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 |
|
| 28 |
tokens := make(chan struct{}) |
| 29 |
go func() { |
| 30 |
defer close(tokens) |
| 31 |
for { |
| 32 |
i, _, _ := reflect.Select(cases) |
| 33 |
if i == burst { |
| 34 |
|
| 35 |
return |
| 36 |
} |
| 37 |
|
| 38 |
select { |
| 39 |
case tokens <- struct{}{}: |
| 40 |
case <-until: |
| 41 |
return |
| 42 |
} |
| 43 |
} |
| 44 |
}() |
| 45 |
return tokens |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
func Notifier(minWait, maxWait time.Duration, until <-chan struct{}) <-chan struct{} { |
| 54 |
|
| 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 |
|
| 85 |
if d == 0 { |
| 86 |
d = minWait |
| 87 |
} |
| 88 |
t.Reset(d) |
| 89 |
} |
| 90 |
}() |
| 91 |
return tokens |
| 92 |
} |