Debian Codegraph @

util/attempt.go

raw symbols SCIP
1 package util
2
3 import (
4 "time"
5 )
6
7 // AttemptStrategy is reused from the goamz package
8
9 // AttemptStrategy represents a strategy for waiting for an action
10 // to complete successfully. This is an internal type used by the
11 // implementation of other packages.
12 type AttemptStrategy struct {
13 Total time.Duration // total duration of attempt.
14 Delay time.Duration // interval between each try in the burst.
15 Min int // minimum number of retries; overrides Total
16 }
17
18 type Attempt struct {
19 strategy AttemptStrategy
20 last time.Time
21 end time.Time
22 force bool
23 count int
24 }
25
26 // Start begins a new sequence of attempts for the given strategy.
27 func (s AttemptStrategy) Start() *Attempt {
28 now := time.Now()
29 return &Attempt{
30 strategy: s,
31 last: now,
32 end: now.Add(s.Total),
33 force: true,
34 }
35 }
36
37 // Next waits until it is time to perform the next attempt or returns
38 // false if it is time to stop trying.
39 func (a *Attempt) Next() bool {
40 now := time.Now()
41 sleep := a.nextSleep(now)
42 if !a.force && !now.Add(sleep).Before(a.end) && a.strategy.Min <= a.count {
43 return false
44 }
45 a.force = false
46 if sleep > 0 && a.count > 0 {
47 time.Sleep(sleep)
48 now = time.Now()
49 }
50 a.count++
51 a.last = now
52 return true
53 }
54
55 func (a *Attempt) nextSleep(now time.Time) time.Duration {
56 sleep := a.strategy.Delay - now.Sub(a.last)
57 if sleep < 0 {
58 return 0
59 }
60 return sleep
61 }
62
63 // HasNext returns whether another attempt will be made if the current
64 // one fails. If it returns true, the following call to Next is
65 // guaranteed to return true.
66 func (a *Attempt) HasNext() bool {
67 if a.force || a.strategy.Min > a.count {
68 return true
69 }
70 now := time.Now()
71 if now.Add(a.nextSleep(now)).Before(a.end) {
72 a.force = true
73 return true
74 }
75 return false
76 }