diff --git a/gomore/06_circuit_breaker/breaker/breaker.go b/gomore/06_circuit_breaker/breaker/breaker.go index f344442..e7091f0 100644 --- a/gomore/06_circuit_breaker/breaker/breaker.go +++ b/gomore/06_circuit_breaker/breaker/breaker.go @@ -21,11 +21,10 @@ const ( type Breaker struct { errorThreshold, successThreshold int timeout time.Duration - - lock sync.Mutex - state uint32 - errors, successes int - lastError time.Time + lock sync.Mutex + state uint32 + errors, successes int + lastError time.Time } // New constructs a new circuit-breaker that starts closed. diff --git a/gomore/06_circuit_breaker/breaker/breaker_test.go b/gomore/06_circuit_breaker/breaker/breaker_test.go index b41308d..68682d8 100644 --- a/gomore/06_circuit_breaker/breaker/breaker_test.go +++ b/gomore/06_circuit_breaker/breaker/breaker_test.go @@ -20,6 +20,27 @@ func returnsSuccess() error { return nil } +func TestExampleBreaker(t *testing.T) { + breaker := New(3, 1, 5*time.Second) + + for { + result := breaker.Run(func() error { + // communicate with some external service and + // return an error if the communication failed + return nil + }) + + switch result { + case nil: + // success! + case ErrBreakerOpen: + // our function wasn't run because the breaker was open + default: + // some other error + } + } +} + func TestBreakerErrorExpiry(t *testing.T) { breaker := New(2, 1, 1*time.Second) @@ -173,24 +194,3 @@ func TestBreakerAsyncStateTransitions(t *testing.T) { t.Error(err) } } - -func ExampleBreaker() { - breaker := New(3, 1, 5*time.Second) - - for { - result := breaker.Run(func() error { - // communicate with some external service and - // return an error if the communication failed - return nil - }) - - switch result { - case nil: - // success! - case ErrBreakerOpen: - // our function wasn't run because the breaker was open - default: - // some other error - } - } -} diff --git a/gomore/06_circuit_breaker/circuit_breaker.go b/gomore/06_circuit_breaker/circuit_breaker.go index 701cc99..1b16366 100644 --- a/gomore/06_circuit_breaker/circuit_breaker.go +++ b/gomore/06_circuit_breaker/circuit_breaker.go @@ -8,13 +8,17 @@ import ( //ErrServiceUnavailable for error var ( - ErrServiceUnavailable = errors.New("Service Unavailable") + ErrTooManyRequests = errors.New("too many requests") + ErrServiceUnavailable = errors.New("service unavailable") FailureThreshold = 10 ) //State of current switch +type State int + +//states of CircuitBreaker const ( - UnknownState uint = iota + UnknownState State = iota FailureState SuccessState ) @@ -24,19 +28,19 @@ type Circuit func(context.Context) error //Counter interface type Counter interface { - Count(uint) + Count(State) ConsecutiveFailures() uint32 LastActivity() time.Time Reset() } type counters struct { - state uint + state State lastActivity time.Time counts uint32 //counts of failures } -func (c *counters) Count(state uint) { +func (c *counters) Count(state State) { }