-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions.go
79 lines (67 loc) · 2.03 KB
/
options.go
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
package routine
import (
"context"
"github.com/aperturerobotics/util/backoff"
cbackoff "github.com/aperturerobotics/util/backoff/cbackoff"
"github.com/sirupsen/logrus"
)
// Option is an option for a RoutineContainer instance.
type Option interface {
// ApplyToRoutineContainer applies the option to the RoutineContainer.
ApplyToRoutineContainer(k *RoutineContainer)
}
type option struct {
cb func(k *RoutineContainer)
}
// newOption constructs a new option.
func newOption(cb func(k *RoutineContainer)) *option {
return &option{cb: cb}
}
// ApplyToRoutineContainer applies the option to the RoutineContainer instance.
func (o *option) ApplyToRoutineContainer(k *RoutineContainer) {
if o.cb != nil {
o.cb(k)
}
}
// WithExitCb adds a callback after a routine exits.
func WithExitCb(cb func(err error)) Option {
return newOption(func(k *RoutineContainer) {
k.exitedCbs = append(k.exitedCbs, cb)
})
}
// WithExitLogger adds a exited callback which logs information about the exit.
func WithExitLogger(le *logrus.Entry) Option {
return WithExitCb(NewLogExitedCallback(le))
}
// NewLogExitedCallback returns a ExitedCb which logs when a controller exited.
func NewLogExitedCallback(le *logrus.Entry) func(err error) {
return func(err error) {
if err != nil && err != context.Canceled {
le.WithError(err).Warnf("routine exited")
} else {
le.Debug("routine exited")
}
}
}
// WithRetry configures a backoff configuration to use when the routine returns an error.
//
// resets the backoff if the routine returned successfully.
// disables the backoff if config is nil
func WithRetry(boConf *backoff.Backoff) Option {
return newOption(func(k *RoutineContainer) {
if boConf == nil {
k.retryBo = nil
return
}
k.retryBo = boConf.Construct()
})
}
// WithBackoff configures a backoff to use when the routine returns an error.
//
// resets the backoff if the routine returned successfully.
// disables the backoff if bo = nil
func WithBackoff(bo cbackoff.BackOff) Option {
return newOption(func(k *RoutineContainer) {
k.retryBo = bo
})
}