2017-03-31 19:01:58 +03:00
|
|
|
package circuitbreaker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/streadway/handy/breaker"
|
2017-05-18 19:54:23 +03:00
|
|
|
"golang.org/x/net/context"
|
2017-03-31 19:01:58 +03:00
|
|
|
|
|
|
|
"github.com/go-kit/kit/endpoint"
|
|
|
|
)
|
|
|
|
|
|
|
|
// HandyBreaker returns an endpoint.Middleware that implements the circuit
|
|
|
|
// breaker pattern using the streadway/handy/breaker package. Only errors
|
|
|
|
// returned by the wrapped endpoint count against the circuit breaker's error
|
|
|
|
// count.
|
|
|
|
//
|
|
|
|
// See http://godoc.org/github.com/streadway/handy/breaker for more
|
|
|
|
// information.
|
|
|
|
func HandyBreaker(cb breaker.Breaker) endpoint.Middleware {
|
|
|
|
return func(next endpoint.Endpoint) endpoint.Endpoint {
|
|
|
|
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
|
|
|
|
if !cb.Allow() {
|
|
|
|
return nil, breaker.ErrCircuitOpen
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func(begin time.Time) {
|
|
|
|
if err == nil {
|
|
|
|
cb.Success(time.Since(begin))
|
|
|
|
} else {
|
|
|
|
cb.Failure(time.Since(begin))
|
|
|
|
}
|
|
|
|
}(time.Now())
|
|
|
|
|
|
|
|
response, err = next(ctx, request)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|