breaker

package
v0.0.0-...-ad5f057 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 20, 2018 License: MIT Imports: 11 Imported by: 0

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

View Source
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

View Source
var (
	ErrBreakerOpen    = breakerOpenErr{}
	ErrBreakerTimeout = breakerTimeoutErr{}
)

Error codes returned by Call

View Source
var NilTripper = TripFunc(func(cb Breaker) bool {
	return false
})

NilTripper is a Tripper that always returns false

View Source
var SystemClock = systemClock{}

SystemClock is a simple clock using the time package

Functions

func IsOpen

func IsOpen(err error) bool

IsOpen returns true if the error is caused by a "breaker open" error.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout returns true if the error is caused by a "breaker timeout" error.

func New

func New(options ...Option) *breaker

New creates a base breaker with a specified backoff, clock and TripFunc

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

type Clock interface {
	After(d time.Duration) <-chan time.Time
	Now() time.Time
}

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 Event

type Event int

Event indicates the type of event received over an event channel

const (
	// TrippedEvent is sent when a breaker trips
	TrippedEvent Event = iota + 1

	// ResetEvent is sent when a breaker resets
	ResetEvent

	// FailEvent is sent when Fail() is called
	FailEvent

	// ReadyEvent is sent when the breaker enters the half open state and is ready to retry
	ReadyEvent
)

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 Map

type Map interface {
	Get(string) (Breaker, bool)
	Set(string, Breaker)
}

Map represents a map of breakers

func NewMap

func NewMap() Map

NewMap creates a default breaker map

type Option

type Option interface {
	Name() string
	Get() interface{}
}

Option is the interface used to provide optional arguments

func WithBackOff

func WithBackOff(v backoff.BackOff) Option

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

func WithClock(v Clock) Option

WithClock is used specify the clock used by the circuir breaker. Normally, this is only used for testing

func WithTimeout

func WithTimeout(v time.Duration) Option

WithTimeout is used to specify the timeout used when `Call` is executed.

func WithTripper

func WithTripper(v Tripper) Option

WithTripper is used to specify the tripper that is used when determining when the breaker should trip.

type State

type State int

State describes the current state of the Breaker

const (
	Open State = iota
	Halfopen
	Closed
)

The various states that the Breaker can take

func (State) String

func (s State) String() string

type TripFunc

type TripFunc func(Breaker) bool

TripFunc is a type of Tripper that is represented by a function with no state

func (TripFunc) Trip

func (f TripFunc) Trip(cb Breaker) bool

Trip return true if the TripFunc thinks the failure state has reached the point where the circuit breaker should be tripped

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

func ConsecutiveTripper(threshold int64) Tripper

ConsecutiveTripper returns a Tripper that trips whenever the *consecutive* failure count meets the given threshold.

func RateTripper

func RateTripper(rate float64, minSamples int64) Tripper

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

func ThresholdTripper(threshold int64) Tripper

ThresholdTripper returns a Tripper that trips whenever the failure count meets the given threshold.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL