Package list golang-github-go-kit-kit / 4a67d58
circuitbreaker: simplify construction of gobreaker and handy_breaker Peter Bourgon 6 years ago
4 changed file(s) with 7 addition(s) and 9 deletion(s). Raw diff Collapse all Expand all
1111 // the wrapped endpoint count against the circuit breaker's error count.
1212 //
1313 // See http://godoc.org/github.com/sony/gobreaker for more information.
14 func Gobreaker(settings gobreaker.Settings) endpoint.Middleware {
15 cb := gobreaker.NewCircuitBreaker(settings)
14 func Gobreaker(cb *gobreaker.CircuitBreaker) endpoint.Middleware {
1615 return func(next endpoint.Endpoint) endpoint.Endpoint {
1716 return func(ctx context.Context, request interface{}) (interface{}, error) {
1817 return cb.Execute(func() (interface{}, error) { return next(ctx, request) })
99
1010 func TestGobreaker(t *testing.T) {
1111 var (
12 breaker = circuitbreaker.Gobreaker(gobreaker.Settings{})
12 breaker = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{}))
1313 primeWith = 100
1414 shouldPass = func(n int) bool { return n <= 5 } // https://github.com/sony/gobreaker/blob/bfa846d/gobreaker.go#L76
1515 circuitOpenError = "circuit breaker is open"
1515 //
1616 // See http://godoc.org/github.com/streadway/handy/breaker for more
1717 // information.
18 func HandyBreaker(failureRatio float64) endpoint.Middleware {
19 b := breaker.NewBreaker(failureRatio)
18 func HandyBreaker(cb breaker.Breaker) endpoint.Middleware {
2019 return func(next endpoint.Endpoint) endpoint.Endpoint {
2120 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
22 if !b.Allow() {
21 if !cb.Allow() {
2322 return nil, breaker.ErrCircuitOpen
2423 }
2524
2625 defer func(begin time.Time) {
2726 if err == nil {
28 b.Success(time.Since(begin))
27 cb.Success(time.Since(begin))
2928 } else {
30 b.Failure(time.Since(begin))
29 cb.Failure(time.Since(begin))
3130 }
3231 }(time.Now())
3332
1010 func TestHandyBreaker(t *testing.T) {
1111 var (
1212 failureRatio = 0.05
13 breaker = circuitbreaker.HandyBreaker(failureRatio)
13 breaker = circuitbreaker.HandyBreaker(handybreaker.NewBreaker(failureRatio))
1414 primeWith = handybreaker.DefaultMinObservations * 10
1515 shouldPass = func(n int) bool { return (float64(n) / float64(primeWith+n)) <= failureRatio }
1616 openCircuitError = handybreaker.ErrCircuitOpen.Error()