breaker

package
v1.20240719.1 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2024 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package breaker provides a circuitbraker mechanism for dealing with flaky or unreliable counterparties.

The algorithm used for the state machine is described by Microsoft https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589784(v=pandp.10)

An example of using a circuit breaker for an http call might be:

    b := breaker.New()
	phoneHome := b.Intercept(async.ActionerFunc(func(ctx context.Context, _ interface{}) (interface{}, error) {
		return http.DefaultClient.Do(http.NewRequestWithContext(ctx, http.VerbGet "https://google.com/robots.txt", nil))
    })

In the above, `phoneHome` now will be wrapped with circuit breaker mechanics. You would call it with `phoneHome.Action(ctx, nil)` etc.

Index

Constants

View Source
const (
	DefaultClosedExpiryInterval       = 5 * time.Second
	DefaultOpenExpiryInterval         = 60 * time.Second
	DefaultHalfOpenMaxActions   int64 = 1
	DefaultOpenFailureThreshold int64 = 5
)

Constants

Variables

View Source
var (
	// ErrTooManyRequests is returned when the CB state is half open and the requests count is over the cb maxRequests
	ErrTooManyRequests ex.Class = "too many requests"
	// ErrOpenState is returned when the CB state is open
	ErrOpenState ex.Class = "circuit breaker is open"
)

Functions

func ErrIsOpen

func ErrIsOpen(err error) bool

ErrIsOpen returns if the error is an ErrOpenState.

func ErrIsTooManyRequests

func ErrIsTooManyRequests(err error) bool

ErrIsTooManyRequests returns if the error is an ErrTooManyRequests.

Types

type Actioner added in v1.20210615.7

type Actioner = async.Actioner

Actioner is a type alias from async.

type ActionerFunc added in v1.20210615.7

type ActionerFunc = async.ActionerFunc

ActionerFunc is a type alias from async.

type Breaker

type Breaker struct {
	sync.Mutex
	// OpenAction is an optional actioner to be called when the breaker is open (i.e. preventing calls
	// to intercepted action(er)s)
	OpenAction Actioner
	// OnStateChange is an optional handler called when the breaker transitions state.
	OnStateChange OnStateChangeHandler
	// ShouldOpenProvider is called optionally to determine if we should open the breaker.
	ShouldOpenProvider ShouldOpenProvider
	// NowProvider lets you optionally inject the current time for testing.
	NowProvider NowProvider

	// OpenFailureThreshold is the default failure threshold
	// before the breaker enters the open state. It is how many actions
	// have to fail consecutively.
	OpenFailureThreshold int64
	// HalfOpenMaxActions is the maximum number of requests
	// we can make when the state is HalfOpen.
	HalfOpenMaxActions int64
	// ClosedExpiryInterval is the cyclic period of the closed state for the CircuitBreaker to clear the internal Counts.
	// If Interval is 0, the CircuitBreaker doesn't clear internal Counts during the closed state.
	ClosedExpiryInterval time.Duration
	// OpenExpiryInterval is the period of the open state,
	// after which the state of the CircuitBreaker becomes half-open.
	// If Timeout is 0, the timeout value of the CircuitBreaker is set to 60 seconds.
	OpenExpiryInterval time.Duration
	// Counts are stats for the breaker.
	Counts Counts
	// contains filtered or unexported fields
}

Breaker is a state machine to prevent performing actions that are likely to fail.

func New

func New(options ...Option) *Breaker

New creates a new breaker with the given options.

func (*Breaker) EvaluateState

func (b *Breaker) EvaluateState(ctx context.Context) State

EvaluateState returns the current state of the CircuitBreaker.

It takes a context because there is a chance that evaluating the state causes the state to change, which would result in calling the `OnStateChange` handler.

func (*Breaker) Intercept added in v1.20210615.7

func (b *Breaker) Intercept(action Actioner) Actioner

Intercept implements the breaker by returning a wrapper for a given action(er).

It returns an error instantly if the Breaker rejects the request, otherwise, it returns the result of the request.

If a panic occurs in the request, the Breaker handles it as an error.

type Config

type Config struct {
	HalfOpenMaxActions   int64         `json:"halfOpenMaxActions" yaml:"halfOpenMaxActions"`
	ClosedExpiryInterval time.Duration `json:"closedExpiryInterval" yaml:"closedExpiryInterval"`
	OpenExpiryInterval   time.Duration `json:"openExpiryInterval" yaml:"openExpiryInterval"`
}

Config is the breaker config.

type Counts

type Counts struct {
	Requests             int64 `json:"requests"`
	TotalSuccesses       int64 `json:"totalSuccesses"`
	TotalFailures        int64 `json:"totalFailures"`
	ConsecutiveSuccesses int64 `json:"consecutiveSuccesses"`
	ConsecutiveFailures  int64 `json:"consecutiveFailures"`
}

Counts holds the numbers of requests and their successes/failures. CircuitBreaker clears the internal Counts either on the change of the state or at the closed-state intervals. Counts ignores the results of the requests sent before clearing.

type NowProvider

type NowProvider func() time.Time

NowProvider returns the current time.

type OnStateChangeHandler

type OnStateChangeHandler func(ctx context.Context, from, to State, generation int64)

OnStateChangeHandler is called when the state changes.

type Option

type Option func(*Breaker)

Option is a mutator for a breaker.

func OptClosedExpiryInterval

func OptClosedExpiryInterval(interval time.Duration) Option

OptClosedExpiryInterval sets the ClosedExpiryInterval.

func OptConfig

func OptConfig(cfg Config) Option

OptConfig sets the breaker based on a config.

func OptHalfOpenMaxActions

func OptHalfOpenMaxActions(maxActions int64) Option

OptHalfOpenMaxActions sets the HalfOpenMaxActions.

func OptNowProvider

func OptNowProvider(provider NowProvider) Option

OptNowProvider sets the now provider on the breaker.

func OptOnStateChange

func OptOnStateChange(handler OnStateChangeHandler) Option

OptOnStateChange sets the OnStateChange handler on the breaker.

func OptOpenAction

func OptOpenAction(action Actioner) Option

OptOpenAction sets the open action on the breaker.

The "Open" action is called when the breaker opens, that is, when it no longer allows calls.

func OptOpenExpiryInterval

func OptOpenExpiryInterval(interval time.Duration) Option

OptOpenExpiryInterval sets the OpenExpiryInterval.

func OptOpenFailureThreshold added in v1.20210615.7

func OptOpenFailureThreshold(openFailureThreshold int64) Option

OptOpenFailureThreshold sets the OpenFailureThreshold.

func OptShouldOpenProvider

func OptShouldOpenProvider(provider ShouldOpenProvider) Option

OptShouldOpenProvider sets the ShouldCloseProvider provider on the breaker.

type ShouldOpenProvider

type ShouldOpenProvider func(ctx context.Context, counts Counts) bool

ShouldOpenProvider returns if the breaker should open.

type State

type State int

State is a type that represents a state of CircuitBreaker.

const (
	StateClosed State = iota
	StateHalfOpen
	StateOpen
)

These constants are states of CircuitBreaker.

func (State) String

func (s State) String() string

String implements stringer interface.

Jump to

Keyboard shortcuts

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