-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreakr.go
163 lines (137 loc) · 2.49 KB
/
breakr.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package breakr
import (
"time"
"github.com/xh3b4sd/tracer"
)
type Config struct {
Failure Failure
Limiter Limiter
Success Success
Timeout Timeout
}
type Breakr struct {
fai Failure
lim *limiter
suc Success
tim Timeout
}
func New(config Config) *Breakr {
{
if config.Failure.Budget == 0 {
config.Failure.Budget = 3
}
if config.Failure.Cooler == 0 {
config.Failure.Cooler = 1 * time.Second
}
}
{
if config.Success.Budget == 0 {
config.Success.Budget = 1
}
}
{
if config.Limiter.Budget == 0 {
config.Limiter.Budget = 3
}
if config.Limiter.Cooler == 0 {
config.Limiter.Cooler = -1
}
}
{
if config.Timeout.Action == 0 {
config.Timeout.Action = 3 * time.Second
}
if config.Timeout.Budget == 0 {
config.Timeout.Budget = 1
}
if config.Timeout.Cooler == 0 {
config.Timeout.Cooler = -1
}
if config.Timeout.Global == 0 {
config.Timeout.Global = -1
}
}
b := &Breakr{
fai: config.Failure,
lim: config.Limiter.New(),
suc: config.Success,
tim: config.Timeout,
}
return b
}
func (b *Breakr) Execute(act func() error) error {
err := b.Wrapper(act)()
if err != nil {
return tracer.Mask(err)
}
return nil
}
func (b *Breakr) Wrapper(act func() error) func() error {
return func() error {
var fco uint
var sco uint
var tco uint
erc := make(chan error, 1)
exe := make(chan struct{}, 1)
glo := timeout(b.tim.Global)
suc := make(chan struct{}, 1)
exe <- struct{}{}
for {
select {
case <-exe:
go func() {
err := b.lim.Execute(act)
if err != nil {
erc <- tracer.Mask(err)
} else {
suc <- struct{}{}
}
}()
case <-suc:
sco++
if sco >= b.suc.Budget {
return nil
}
exe <- struct{}{}
case <-b.tim.Closer:
return tracer.Mask(Closed)
case <-glo:
return tracer.Mask(Passed)
case <-timeout(b.tim.Action):
tco++
if tco >= b.tim.Budget {
return tracer.Mask(Passed)
}
if b.tim.Cooler != -1 {
time.Sleep(b.tim.Cooler)
}
exe <- struct{}{}
case err := <-erc:
if IsCancel(err) {
return tracer.Mask(err)
}
if IsFilled(err) {
return tracer.Mask(err)
}
if IsRepeat(err) {
// fall through
} else {
fco++
if fco >= b.fai.Budget {
return tracer.Mask(err)
}
if b.fai.Cooler != -1 {
time.Sleep(b.fai.Cooler)
}
}
exe <- struct{}{}
}
}
}
}
func timeout(dur time.Duration) <-chan time.Time {
if dur != -1 {
return time.After(dur)
}
return nil
}