breaker

package
v11.3.4 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2022 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package breaker implements a circuit breaker.

Circuit breaker watches the error from executed functions and according to the configured TripFn will allow requests for a period of time before slowly allowing a few.

Circuit breakers start in StateStandby first, observing errors and watching Metrics.

Once the Circuit breaker TripFn returns true, it enters the StateTripped, where it blocks all traffic and returns ErrStateTripped for the configured Config.TrippedPeriod.

After the Config.TrippedPeriod passes, Circuit breaker enters StateRecovering, during that state it will either transition to StateStandby after the Config.RecoveryLimit is met or StateTripped if the Config.Recover TripFn is satisfied.

It is possible to define actions on transitions between states:

* Config.OnTripped is called on transition (StateStandby -> StateTripped) * Config.OnStandBy is called on transition (StateRecovering -> StateStandby)

Index

Constants

This section is empty.

Variables

View Source
var ErrStateTripped = trace.ConnectionProblem(nil, "breaker is tripped")

ErrStateTripped will be returned from executions performed while the CircuitBreaker is in StateTripped

Functions

func IsResponseSuccessful

func IsResponseSuccessful(v interface{}, err error) bool

IsResponseSuccessful determines whether the error provided should be ignored by the circuit breaker. This checks for http status codes < 500 and a few unsuccessful grpc status codes.

func NonNilErrorIsSuccess

func NonNilErrorIsSuccess(_ interface{}, err error) bool

NonNilErrorIsSuccess returns true if the provided error is non nil. This is the default value for Config.IsSuccessful if not provided.

func StreamClientInterceptor

func StreamClientInterceptor(cb *CircuitBreaker) grpc.StreamClientInterceptor

StreamClientInterceptor is a stream gRPC client interceptor that uses the provided CircuitBreaker to track errors returned from the outgoing calls.

func UnaryClientInterceptor

func UnaryClientInterceptor(cb *CircuitBreaker) grpc.UnaryClientInterceptor

UnaryClientInterceptor is a unary gRPC client interceptor that uses the provided CircuitBreaker to track errors returned from the outgoing calls.

Types

type CircuitBreaker

type CircuitBreaker struct {
	// contains filtered or unexported fields
}

CircuitBreaker implements the circuit breaker pattern

func New

func New(cfg Config) (*CircuitBreaker, error)

New returns a CircuitBreaker configured with the provided Config

func NewNoop

func NewNoop() *CircuitBreaker

func (*CircuitBreaker) Execute

func (c *CircuitBreaker) Execute(f func() (interface{}, error)) (interface{}, error)

Execute calls the provided function depending on the CircuitBreaker state.

  • StateStandby: all functions are executed.
  • StateTripped: no functions are executed and ErrStateTripped is returned.
  • StateRecovering: some functions are executed, some functions are not, when not executed ErrLimitExceeded is returned.

The CircuitBreaker state is updated according to the outcome of executing the provided function and the current state. See package docs for a more detailed explanation of state transitions.

type Config

type Config struct {
	// Clock is used to control time - mainly used for testing
	Clock clockwork.Clock
	// Interval is the period of time that execution metrics will be collected for within StateStandby before
	// transitioning to the next generation.
	Interval time.Duration
	// TrippedPeriod is the amount of time to remain in StateTripped before transitioning
	// into StateRecovering
	TrippedPeriod time.Duration
	// Recover specifies the TripFn that will be used to determine if the CircuitBreaker should transition from
	// StateRecovering to StateTripped. This is required to be supplied, failure to do so will result in an error
	// creating the CircuitBreaker.
	Recover TripFn
	// RecoveryLimit is the number on consecutive successful executions required to transition from
	// StateRecovering to StateStandby
	RecoveryLimit uint32
	// Trip specifies the TripFn that will be used to determine if the CircuitBreaker should transition from
	// StateStandby to StateTripped. This is required to be supplied, failure to do so will result in an error
	// creating the CircuitBreaker.
	Trip TripFn
	// OnTripped will be called when the CircuitBreaker enters the StateTripped state
	OnTripped func()
	// OnStandby will be called when the CircuitBreaker returns to the StateStandby state
	OnStandBy func()
	// IsSuccessful is used by the CircuitBreaker to determine if the executed function was successful or not
	IsSuccessful func(v interface{}, err error) bool
	// Logger is the logger
	Logger logrus.FieldLogger
}

Config contains configuration of the CircuitBreaker

func DefaultBreakerConfig

func DefaultBreakerConfig(clock clockwork.Clock) Config

func NoopBreakerConfig

func NoopBreakerConfig() Config

func (*Config) CheckAndSetDefaults

func (c *Config) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default config values.

type Metrics

type Metrics struct {
	// Executions the total number of times the breaker has executed within the interval
	Executions uint32
	// Successes the number of successful executions
	Successes uint32
	// Failures the total number of failed executions
	Failures uint32
	// ConsecutiveSuccesses the number of consecutive successful executions
	ConsecutiveSuccesses uint32
	// ConsecutiveFailures the number of consecutive failed executions
	ConsecutiveFailures uint32
}

Metrics tallies success and failure counts for all executions performed by a CircuitBreaker

func (*Metrics) String

func (m *Metrics) String() string

type RoundTripper

type RoundTripper struct {
	// contains filtered or unexported fields
}

RoundTripper wraps a http.RoundTripper with a CircuitBreaker

func NewRoundTripper

func NewRoundTripper(cb *CircuitBreaker, tripper http.RoundTripper) *RoundTripper

NewRoundTripper returns a RoundTripper

func (*RoundTripper) RoundTrip

func (t *RoundTripper) RoundTrip(request *http.Request) (*http.Response, error)

RoundTrip forwards the request on to the provided http.RoundTripper if the CircuitBreaker allows it

nolint:bodyclose The interface{} conversion to *http.Response trips the linter even though this is merely a pass through function. Closing the body here would prevent the actual consumer to not be able to read it. Copying here to satisfy the linter seems wasteful.

type State

type State int

State represents an operating state that a CircuitBreaker may be in.

const (
	// StateStandby indicates the breaker is passing all requests and watching stats
	StateStandby State = iota
	// StateTripped indicates too many errors have occurred and requests are actively being rejected
	StateTripped
	// StateRecovering indicates the breaker is allowing some requests to go through and rejecting others
	StateRecovering
)

func (State) String

func (s State) String() string

String returns the string representation of a State

type TripFn

type TripFn = func(m Metrics) bool

TripFn determines if the CircuitBreaker should be tripped based on the state of the provided Metrics. A return value of true will cause the CircuitBreaker to transition into the StateTripped state

func ConsecutiveFailureTripper

func ConsecutiveFailureTripper(max uint32) TripFn

ConsecutiveFailureTripper is a TripFn that will return true if Metrics.ConsecutiveFailures is greater than the provided value.

func RatioTripper

func RatioTripper(ratio float64, minExecutions uint32) TripFn

RatioTripper is a TripFn that returns true it the error ratio is greater than the provided ratio and there have been at least minExecutions performed.

func StaticTripper

func StaticTripper(b bool) TripFn

StaticTripper is a TripFn that always returns the provided value regardless of the Metrics. Useful for testing.

Jump to

Keyboard shortcuts

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