-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathconsecutivebreaker.go
45 lines (36 loc) · 1.01 KB
/
consecutivebreaker.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
package circuit
import (
log "github.com/sirupsen/logrus"
"github.com/sony/gobreaker"
)
type consecutiveBreaker struct {
settings BreakerSettings
gb *gobreaker.TwoStepCircuitBreaker
}
func newConsecutive(s BreakerSettings) *consecutiveBreaker {
b := &consecutiveBreaker{
settings: s,
}
b.gb = gobreaker.NewTwoStepCircuitBreaker(gobreaker.Settings{
Name: s.Host,
MaxRequests: uint32(s.HalfOpenRequests),
Timeout: s.Timeout,
ReadyToTrip: b.readyToTrip,
OnStateChange: func(name string, from gobreaker.State, to gobreaker.State) {
log.Infof("circuit breaker %v went from %v to %v", name, from.String(), to.String())
},
})
return b
}
func (b *consecutiveBreaker) readyToTrip(c gobreaker.Counts) bool {
return int(c.ConsecutiveFailures) >= b.settings.Failures
}
func (b *consecutiveBreaker) Allow() (func(bool), bool) {
done, err := b.gb.Allow()
// this error can only indicate that the breaker is not closed
closed := err == nil
if !closed {
return nil, false
}
return done, true
}