File: strategy.go

package info (click to toggle)
golang-gopkg-retry.v1 0.0~git20161025.0.c09f6b8-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 132 kB
  • ctags: 100
  • sloc: makefile: 2
file content (60 lines) | stat: -rw-r--r-- 1,362 bytes parent folder | download
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
package retry // import "gopkg.in/retry.v1"

import (
	"time"
)

type strategyFunc func(now time.Time) Timer

// NewTimer implements Strategy.NewTimer.
func (f strategyFunc) NewTimer(now time.Time) Timer {
	return f(now)
}

// LimitCount limits the number of attempts that the given
// strategy will perform to n. Note that all strategies
// will allow at least one attempt.
func LimitCount(n int, strategy Strategy) Strategy {
	return strategyFunc(func(now time.Time) Timer {
		return &countLimitTimer{
			timer:  strategy.NewTimer(now),
			remain: n,
		}
	})
}

type countLimitTimer struct {
	timer  Timer
	remain int
}

func (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {
	if t.remain--; t.remain <= 0 {
		return 0, false
	}
	return t.timer.NextSleep(now)
}

// LimitTime limits the given strategy such that no attempt will
// made after the given duration has elapsed.
func LimitTime(limit time.Duration, strategy Strategy) Strategy {
	return strategyFunc(func(now time.Time) Timer {
		return &timeLimitTimer{
			timer: strategy.NewTimer(now),
			end:   now.Add(limit),
		}
	})
}

type timeLimitTimer struct {
	timer Timer
	end   time.Time
}

func (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {
	sleep, ok := t.timer.NextSleep(now)
	if ok && now.Add(sleep).After(t.end) {
		return 0, false
	}
	return sleep, ok
}