This repository has been archived by the owner on Apr 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
options.go
122 lines (107 loc) · 1.92 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package rutina
import (
"context"
"os"
"time"
)
type Options struct {
ParentContext context.Context
ListenOsSignals []os.Signal
Logger func(format string, v ...interface{})
Errors chan error
}
func ParentContext(ctx context.Context) Options {
return Options{
ParentContext: ctx,
}
}
func ListenOsSignals(signals ...os.Signal) Options {
return Options{
ListenOsSignals: signals,
}
}
func Logger(l logger) Options {
return Options{
Logger: l,
}
}
func Errors(errCh chan error) Options {
return Options{
Errors: errCh,
}
}
func composeOptions(opts []Options) Options {
res := Options{
ParentContext: context.Background(),
Logger: nopLogger,
ListenOsSignals: []os.Signal{},
}
for _, o := range opts {
if o.ParentContext != nil {
res.ParentContext = o.ParentContext
}
if o.Errors != nil {
res.Errors = o.Errors
}
if o.ListenOsSignals != nil {
res.ListenOsSignals = o.ListenOsSignals
}
if o.Logger != nil {
res.Logger = o.Logger
}
}
return res
}
type Policy int
const (
DoNothing Policy = iota
Shutdown
Restart
)
type RunOptions struct {
OnDone Policy
OnError Policy
Timeout *time.Duration
MaxCount *int
}
func OnDone(policy Policy) RunOptions {
return RunOptions{
OnDone: policy,
}
}
func OnError(policy Policy) RunOptions {
return RunOptions{
OnError: policy,
}
}
func Timeout(timeout time.Duration) RunOptions {
return RunOptions{
Timeout: &timeout,
}
}
func MaxCount(maxCount int) RunOptions {
return RunOptions{
MaxCount: &maxCount,
}
}
func composeRunOptions(opts []RunOptions) RunOptions {
res := RunOptions{
OnDone: Shutdown,
OnError: Shutdown,
}
for _, o := range opts {
if o.OnDone != res.OnDone {
res.OnDone = o.OnDone
}
if o.OnError != res.OnError {
res.OnError = o.OnError
}
if o.MaxCount != nil {
res.MaxCount = o.MaxCount
}
if o.Timeout != nil {
res.Timeout = o.Timeout
}
}
return res
}