Documentation
¶
Overview ¶
Package breaker implements the Circuit Breaker pattern. This work is based on github.com/rubyist/circuitbreaker, with modifications to make the API more Go-ish and some possible bug fixes.
The Breaker will wrap a Circuit (typically one which uses remote services) and monitors for failures and/or time outs. When a threshold of failures or time outs has been reached, future calls to the function will not run. During this state, the breaker will periodically allow the function to run and, if it is successful, will start running the function again.
When wrapping blocks of code with a Breaker's Call() function, a time out can be specified. If the time out is reached, the breaker's Fail() function will be called.
Other types of circuit breakers can be easily built by creating a Breaker and adding a custom Tripper. A Tripper is called when a Breaker Fail()s and receives the breaker as an argument. It then returns true or false to indicate whether the breaker should trip.
Example ¶
package main import ( "time" "github.com/cenk/backoff" "github.com/lestrrat/go-circuit-breaker/breaker" ) func main() { // Need to initialize a clock to use for the // backoff AND the breaker c := breaker.SystemClock // Create a custom backoff strategy bo := backoff.NewExponentialBackOff() bo.Clock = c cb := breaker.New( breaker.WithBackOff(bo), breaker.WithClock(c), breaker.WithTimeout(10*time.Second), breaker.WithTripper(breaker.ThresholdTripper(10)), ) err := cb.Call(breaker.CircuitFunc(func() error { // call that may trip the breaker return nil })) // err will be non-nill if either the circuit returns // an error, or the breaker is in an Open state _ = err }
Output:
Index ¶
Examples ¶
Constants ¶
const ( // DefaultWindowTime is the default time the window covers, 10 seconds. DefaultWindowTime time.Duration = time.Second * 10 // DefaultWindowBuckets is the default number of buckets the window holds, 10. DefaultWindowBuckets = 10 )
Variables ¶
var ( ErrBreakerOpen = breakerOpenErr{} ErrBreakerTimeout = breakerTimeoutErr{} )
Error codes returned by Call
var NilTripper = TripFunc(func(cb Breaker) bool { return false })
NilTripper is a Tripper that always returns false
var SystemClock = systemClock{}
SystemClock is a simple clock using the time package
Functions ¶
Types ¶
type Breaker ¶
type Breaker interface { // Break trips the circuit breaker and prevents it from auto resetting. // Use this when manual control over the circuit breaker state is needed. Break() // Call wraps a function the Breaker will protect. A failure is recorded // whenever the function returns an error. // // `WithTimeout` may be specified in the options to override the default // timeout associated with the breaker. If the called function takes longer // than timeout to run, a failure will be recorded. Call(Circuit, ...Option) error // ConsecFailures returns the number of consecutive failures that // have occured. ConsecFailures() int64 // ErrorRate returns the current error rate of the Breaker, expressed // as a floating point number (e.g. 0.9 for 90%), since the last time // the breaker was Reset. ErrorRate() float64 // Failures returns the number of failures for this circuit breaker. Failures() int64 // Ready will return true if the circuit breaker is ready to call the // function. It will be ready if the breaker is in a reset state, or if // it is time to retry the call for auto resetting. // // Note that the method has side effects. If you are only interested in // querying for the current state without causing side effects, // you should use State() Ready() (bool, State) // Reset will reset the circuit breaker. After Reset() is called, // Tripped() will return false. Reset() // ResetCounters will reset only the failures, consecFailures, // and success counters ResetCounters() // State returns the state of the Breaker. The states available are: // Closed - the circuit is in a reset state and is operational // Open - the circuit is in a tripped state // Halfopen - the circuit is in a tripped state but the reset timeout has passed State() State // Successes returns the number of successes for this circuit breaker. Successes() int64 // Trip will trip the circuit breaker. After Trip() is called, Tripped() // willreturn true. Trip() // Tripped returns true if the circuit breaker is tripped, false // if it is reset. Tripped() bool }
Breaker describes the interface of a circuit breaker. It maintains failure and success counters and state information
type Circuit ¶
type Circuit interface {
Execute() error
}
Circuit is the interface for things that can be Call'ed and protected by the Breaker
type CircuitFunc ¶
type CircuitFunc func() error
CircuitFunc is a Cuircuit represented as a standalone function
func (CircuitFunc) Execute ¶
func (c CircuitFunc) Execute() error
Execute executes the given function
type Clock ¶
Clock is an interface that defines a pluggable clock (as opposed to using the `time` package directly). This interface lists the only methods that this package cares about. You can either use your own implementation, or use a another library such as github.com/facebookgo/clock
type EventEmitter ¶
type EventEmitter interface { Breaker Emitting() chan struct{} Emit(context.Context) Events() chan Event Subscribe(context.Context) *EventSubscription }
EventEmitter is used to wrap a Breaker object so that useful notifications can be received from it.
Example ¶
package main import ( "context" "github.com/lestrrat/go-circuit-breaker/breaker" ) func main() { // Use emitter to receive notifications of events // such as TrippedEvent, ReadyEvent, ResetEvent, etc. ctx, cancel := context.WithCancel(context.Background()) defer cancel() cb := breaker.NewEventEmitter(breaker.New()) s := cb.Subscribe(ctx) for { select { case e := <-s.C: // received event _ = e } } }
Output:
func NewEventEmitter ¶
func NewEventEmitter(cb Breaker) EventEmitter
NewEventEmitter wraps Breaker and creates an EventEmitter (which also satisfies the Breaker interface) that can generate events.
type EventSubscription ¶
type EventSubscription struct { C chan Event // contains filtered or unexported fields }
EventSubscription describes a subscription to an EventEmitter
func (*EventSubscription) Stop ¶
func (s *EventSubscription) Stop()
Stop removes the subscription from the associated EventEmitter and stops receiving events
type Option ¶
type Option interface { Name() string Get() interface{} }
Option is the interface used to provide optional arguments
func WithBackOff ¶
WithBackOff is used to specify the backoff policy that is used when determining if the breaker should attempt to retry. `Breaker` objects will use an exponential backoff policy by default.
func WithClock ¶
WithClock is used specify the clock used by the circuir breaker. Normally, this is only used for testing
func WithTimeout ¶
WithTimeout is used to specify the timeout used when `Call` is executed.
func WithTripper ¶
WithTripper is used to specify the tripper that is used when determining when the breaker should trip.
type Tripper ¶
type Tripper interface { // Trip will receive the Breaker as an argument and returns a boolean. Trip(Breaker) bool }
Tripper is an interface called by a Breaker's Fail() method. It should determine whether the breaker should trip. By default, a Breaker has no Tripper
func ConsecutiveTripper ¶
ConsecutiveTripper returns a Tripper that trips whenever the *consecutive* failure count meets the given threshold.
func RateTripper ¶
RateTripper returns a Tripper that trips whenever the error rate hits the given threshold.
The error rate is calculated as such: f = number of failures s = number of successes e = f / (f + s)
The error rate is calculated over a sliding window of 10 seconds (by default) This Tripper will not trip until there has been at least minSamples events.
func ThresholdTripper ¶
ThresholdTripper returns a Tripper that trips whenever the failure count meets the given threshold.