-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
203 lines (191 loc) · 4.88 KB
/
state.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package circuitbreaker
import (
"context"
"fmt"
"sync/atomic"
"time"
)
type State string
const (
Closed State = "CLOSED"
Open State = "OPEN"
HalfOpen State = "HALF_OPEN"
Disabled State = "DISABLED"
ForcedOpen State = "FORCED_OPEN"
)
type state struct {
name State
allowPublish bool
attempts int64
metrics *metrics
acquirePermission func() error
onError func(time.Duration)
onSuccess func(time.Duration)
preTransitionHook func()
}
func closed(breaker CircuitBreaker) *state {
s := &state{
name: Closed,
allowPublish: true,
attempts: 0,
metrics: forClosed(breaker.config()),
}
var isClosed atomic.Bool
isClosed.Store(true)
checkIfThresholdsExceeded := func(result metricsResult) {
if exceededThresholds(result) && isClosed.CompareAndSwap(true, false) {
breaker.publishThresholdsExceededEvent(result, s.metrics)
_ = breaker.TransitionToOpenState()
}
}
s.onError = func(duration time.Duration) {
checkIfThresholdsExceeded(s.metrics.onError(duration))
}
s.onSuccess = func(duration time.Duration) {
checkIfThresholdsExceeded(s.metrics.onSuccess(duration))
}
return s
}
func open(attempts int64, metrics *metrics, breaker CircuitBreaker) *state {
config := breaker.config()
s := &state{
name: Open,
allowPublish: true,
attempts: attempts,
metrics: metrics,
}
var isOpen atomic.Bool
isOpen.Store(true)
toHalfOpen := func() {
if isOpen.CompareAndSwap(true, false) {
_ = breaker.TransitionToHalfOpenState()
}
}
waitDuration := config.waitIntervalFunctionInOpenStateFn(attempts)
retryAfterWaitDuration := time.Now().Add(waitDuration)
s.acquirePermission = func() error {
if time.Now().After(retryAfterWaitDuration) {
toHalfOpen()
return breaker.acquirePermission()
}
s.metrics.onCallNotPermitted()
return &NotPermittedError{
name: breaker.Name(),
stateName: Open}
}
s.onError = func(duration time.Duration) {
s.metrics.onError(duration)
}
s.onSuccess = func(duration time.Duration) {
s.metrics.onSuccess(duration)
}
if config.automaticTransitionFromOpenToHalfOpenEnabled {
timeout, cancelFunc := context.WithTimeout(
context.Background(), waitDuration)
go func() {
select {
case <-timeout.Done():
if timeout.Err() == context.DeadlineExceeded {
toHalfOpen()
}
}
}()
s.preTransitionHook = cancelFunc
}
return s
}
func halfOpen(attempts int64, breaker CircuitBreaker) *state {
config := breaker.config()
permittedNumber := config.permittedNumberOfCallsInHalfOpenState
s := &state{
name: HalfOpen,
allowPublish: true,
attempts: attempts,
metrics: forHalfOpen(permittedNumber, config),
}
var permittedNumberOfCalls atomic.Int64
permittedNumberOfCalls.Store(permittedNumber)
s.acquirePermission = func() error {
if permittedNumberOfCalls.Add(-1) >= 0 {
return nil
}
s.metrics.onCallNotPermitted()
return &NotPermittedError{
name: breaker.Name(),
stateName: HalfOpen}
}
toOpen, toClosed := atomicHalfOpen(breaker)
checkIfThresholdsExceeded := func(result metricsResult) {
if exceededThresholds(result) {
toOpen()
}
if result == belowThresholds {
toClosed()
}
}
s.onError = func(duration time.Duration) {
checkIfThresholdsExceeded(s.metrics.onError(duration))
}
s.onSuccess = func(duration time.Duration) {
checkIfThresholdsExceeded(s.metrics.onSuccess(duration))
}
if config.maxWaitDurationInHalfOpenState > 0 {
timeout, cancelFunc := context.WithTimeout(
context.Background(), config.maxWaitDurationInHalfOpenState)
go func() {
select {
case <-timeout.Done():
if timeout.Err() == context.DeadlineExceeded {
toOpen()
}
}
}()
s.preTransitionHook = cancelFunc
}
return s
}
func atomicHalfOpen(breaker CircuitBreaker) (func(), func()) {
var isHalfOpen atomic.Bool
isHalfOpen.Store(true)
toOpen := func() {
if isHalfOpen.CompareAndSwap(true, false) {
_ = breaker.TransitionToOpenState()
}
}
toClosed := func() {
if isHalfOpen.CompareAndSwap(true, false) {
_ = breaker.TransitionToClosedState()
}
}
return toOpen, toClosed
}
func disabled(breaker CircuitBreaker) *state {
return &state{
name: Disabled,
allowPublish: false,
attempts: 0,
metrics: forDisabled(breaker.config()),
}
}
func forcedOpen(attempts int64, breaker CircuitBreaker) *state {
s := &state{
name: ForcedOpen,
allowPublish: false,
attempts: attempts,
metrics: forForcedOpen(breaker.config()),
}
s.acquirePermission = func() error {
s.metrics.onCallNotPermitted()
return &NotPermittedError{
name: breaker.Name(),
stateName: ForcedOpen}
}
return s
}
func checkStateTransition(name string, fromState, toState State) error {
if fromState == Closed && toState == HalfOpen {
return fmt.Errorf("CircuitBreaker '%s' tried an illegal state transition from %s to %s",
name, fromState, toState)
}
return nil
}