breaker

package
v0.0.0-...-bc49051 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 6 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 := circuitbreaker.New[string, *http.Response](circuitbreaker.Config{})
	phoneHome := b.Intercept(async.ActionerFunc(func(ctx context.Context, url string) (*http.Response, error) {
		return http.DefaultClient.Do(http.NewRequestWithContext(ctx, http.VerbGet, url, 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 (
	DefaultOpenExpiryInterval                 = 60 * time.Second
	DefaultClosedFailureExpiryInterval        = 10 * time.Second
	DefaultHalfOpenMaxActions          uint64 = 5
	DefaultFailureThreshold            uint64 = 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 errutil.Class = "too many requests"
	// ErrOpenState is returned when the CB state is open
	ErrOpenState errutil.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 Action

type Action[A, B any] interface {
	Call(context.Context, A) (B, error)
}

Action is a type that can be used in the breaker.

type ActionFunc

type ActionFunc[A, B any] func(context.Context, A) (B, error)

ActionFunc is a function that implements action.

func (ActionFunc[A, B]) Call

func (af ActionFunc[A, B]) Call(ctx context.Context, args A) (B, error)

Action implements actioner for the function.

type Breaker

type Breaker[A, B any] struct {
	Action        Action[A, B]
	OpenAction    Action[A, B]
	OnStateChange OnStateChangeFunc
	ShouldOpen    ShouldOpenFunc[A]
	Now           NowFunc
	Config        Config
	// contains filtered or unexported fields
}

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

func New

func New[A, B any](action Action[A, B], options ...Option[A, B]) *Breaker[A, B]

New creates a new breaker with the given options.

func (*Breaker[A, B]) Call

func (b *Breaker[A, B]) Call(ctx context.Context, args A) (res B, err error)

Call invokes the action and returns the result.

func (*Breaker[A, B]) Counts

func (b *Breaker[A, B]) Counts() Counts

func (*Breaker[A, B]) EvaluateState

func (b *Breaker[A, B]) EvaluateState(ctx context.Context) State

EvaluateState returns the current state of the CircuitBreaker.

This method is a kind of idirect because can't know for sure what the state is at a given time without evaluating expiration times and potentially calling handlers if the state changes after an expiry.

As a result this method takes a context, and may call the `OnStateChange` delegate value if it's set.

type Config

type Config struct {
	FailureThreshold            uint64        `json:"failureThreshold" yaml:"failureThreshold"`
	HalfOpenMaxActions          uint64        `json:"halfOpenMaxActions" yaml:"halfOpenMaxActions"`
	OpenExpiryInterval          time.Duration `json:"openExpiryInterval" yaml:"openExpiryInterval"`
	ClosedFailureExpiryInterval time.Duration `json:"closedFailureExpiryInterval" yaml:"closedFailureExpiryInterval"`
}

Config is the breaker config.

func (Config) ClosedFailureExpiryIntervalOrDefault

func (c Config) ClosedFailureExpiryIntervalOrDefault() time.Duration

func (Config) FailureThresholdOrDefault

func (c Config) FailureThresholdOrDefault() uint64

func (Config) HalfOpenMaxActionsOrDefault

func (c Config) HalfOpenMaxActionsOrDefault() uint64

func (Config) OpenExpiryIntervalOrDefault

func (c Config) OpenExpiryIntervalOrDefault() time.Duration

type Counts

type Counts struct {
	Requests             uint64 `json:"requests"`
	TotalSuccesses       uint64 `json:"totalSuccesses"`
	TotalFailures        uint64 `json:"totalFailures"`
	ConsecutiveSuccesses uint64 `json:"consecutiveSuccesses"`
	ConsecutiveFailures  uint64 `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 NoopAction

type NoopAction[A, B any] struct{}

NoopAction is an actioner type that does nothing.

func (NoopAction[A, B]) Call

func (n NoopAction[A, B]) Call(_ context.Context, _ A) (output B, err error)

Action implements actioner

type NowFunc

type NowFunc func() time.Time

NowFunc returns the current time.

type OnStateChangeFunc

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

OnStateChangeFunc is called when the state changes.

type Option

type Option[A, B any] func(b *Breaker[A, B])

func OptConfig

func OptConfig[A, B any](cfg Config) Option[A, B]

func OptNow

func OptNow[A, B any](nowFn NowFunc) Option[A, B]

func OptOpenAction

func OptOpenAction[A, B any](action Action[A, B]) Option[A, B]

func OptShouldOpen

func OptShouldOpen[A, B any](shouldOpenFunc ShouldOpenFunc[A]) Option[A, B]

type ShouldOpenFunc

type ShouldOpenFunc[A any] func(ctx context.Context, counts Counts, args A) bool

ShouldOpenFunc returns if the breaker should open.

type State

type State int

State is a type that represents a state of breaker.Breaker.

const (
	StateClosed State = iota
	StateHalfOpen
	StateOpen
)

These constants are states of breaker.Breaker.

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