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
|
package backoff
import (
"context"
"sync"
"time"
)
type controller struct {
ctx context.Context
cancel func()
ig IntervalGenerator
maxRetries int64
mu *sync.RWMutex
next chan struct{} // user-facing channel
resetTimer chan time.Duration
retries int64
timer *time.Timer
}
func newController(ctx context.Context, ig IntervalGenerator, options ...ControllerOption) *controller {
cctx, cancel := context.WithCancel(ctx) // DO NOT fire this cancel here
maxRetries := int64(10)
for _, option := range options {
switch option.Ident() {
case identMaxRetries{}:
maxRetries = option.Value().(int64)
}
}
c := &controller{
cancel: cancel,
ctx: cctx,
ig: ig,
maxRetries: maxRetries,
mu: &sync.RWMutex{},
next: make(chan struct{}, 1),
resetTimer: make(chan time.Duration, 1),
timer: time.NewTimer(ig.Next()),
}
// enqueue a single fake event so the user gets to retry once
c.next <- struct{}{}
go c.loop()
return c
}
func (c *controller) loop() {
for {
select {
case <-c.ctx.Done():
return
case d := <-c.resetTimer:
if !c.timer.Stop() {
select {
case <-c.timer.C:
default:
}
}
c.timer.Reset(d)
case <-c.timer.C:
select {
case <-c.ctx.Done():
return
case c.next <- struct{}{}:
}
if c.maxRetries > 0 {
c.retries++
}
if !c.check() {
c.cancel()
return
}
c.resetTimer <- c.ig.Next()
}
}
}
func (c *controller) check() bool {
if c.maxRetries > 0 && c.retries >= c.maxRetries {
return false
}
return true
}
func (c *controller) Done() <-chan struct{} {
c.mu.RLock()
defer c.mu.RUnlock()
return c.ctx.Done()
}
func (c *controller) Next() <-chan struct{} {
c.mu.RLock()
defer c.mu.RUnlock()
return c.next
}
|