circuitbreaker

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2024 License: Apache-2.0 Imports: 10 Imported by: 1

Documentation

Overview

Package circuitbreaker provides a CircuitBreaker policy.

Index

Constants

This section is empty.

Variables

View Source
var ErrOpen = errors.New("circuit breaker open")

ErrOpen is returned when an execution is attempted against a circuit breaker that is open.

Functions

This section is empty.

Types

type CircuitBreaker

type CircuitBreaker[R any] interface {
	failsafe.Policy[R]
	// Open opens the CircuitBreaker.
	Open()

	// HalfOpen half-opens the CircuitBreaker.
	HalfOpen()

	// Close closes the CircuitBreaker.
	Close()

	// IsOpen returns whether the CircuitBreaker is open.
	IsOpen() bool

	// IsHalfOpen returns whether the CircuitBreaker is half-open.
	IsHalfOpen() bool

	// IsClosed returns whether the CircuitBreaker is closed.
	IsClosed() bool

	// State returns the State of the CircuitBreaker.
	State() State

	// RemainingDelay returns the remaining delay until the circuit is half-opened and allows another execution, when in the
	// OpenState, else returns 0 when in other states.
	RemainingDelay() time.Duration

	// Metrics returns metrics for the CircuitBreaker.
	Metrics() Metrics

	// TryAcquirePermit tries to acquire a permit to use the circuit breaker and returns whether a permit was acquired.
	// Permission will be automatically released when a result or failure is recorded.
	TryAcquirePermit() bool

	// RecordResult records an execution result as a success or failure based on the failure handling configuration.
	RecordResult(result R)

	// RecordError records an error as a success or failure based on the failure handling configuration.
	RecordError(err error)

	// RecordSuccess records an execution success.
	RecordSuccess()

	// RecordFailure records an execution failure.
	RecordFailure()
}

CircuitBreaker is a policy that temporarily blocks execution when a configured number of failures are exceeded. Circuit breakers have three states: closed, open, and half-open. When a circuit breaker is in the ClosedState (default), executions are allowed. If a configurable number of failures occur, optionally over some time period, the circuit breaker transitions to OpenState. In the OpenState a circuit breaker will fail executions with ErrOpen. After a configurable delay, the circuit breaker will transition to HalfOpenState. In the HalfOpenState a configurable number of trial executions will be allowed, after which the circuit breaker will transition to either ClosedState or OpenState depending on how many were successful.

A circuit breaker can be count based or time based:

  • Count based circuit breakers will transition between states when recent execution results exceed a threshold.
  • Time based circuit breakers will transition between states when recent execution results exceed a threshold within a time period. A minimum number of executions must be performed in order for a state transition to occur. Time based circuit breakers use a sliding window to aggregate execution results. The window is divided into 10 time slices, each representing 1/10th of the failureThresholdingPeriod. As time progresses, statistics for old time slices are gradually discarded, which smoothes the calculation of success and failure rates.

This type is concurrency safe.

func WithDefaults

func WithDefaults[R any]() CircuitBreaker[R]

WithDefaults creates a count based CircuitBreaker for execution result type R that opens after a single failure, closes after a single success, and has a 1 minute delay by default. To configure additional options on a CircuitBreaker, use Builder() instead.

type CircuitBreakerBuilder

type CircuitBreakerBuilder[R any] interface {
	failsafe.FailurePolicyBuilder[CircuitBreakerBuilder[R], R]
	failsafe.DelayablePolicyBuilder[CircuitBreakerBuilder[R], R]

	// OnStateChanged calls the listener when the CircuitBreaker state changes.
	OnStateChanged(listener func(StateChangedEvent)) CircuitBreakerBuilder[R]

	// OnClose calls the listener when the CircuitBreaker state changes to closed.
	OnClose(listener func(StateChangedEvent)) CircuitBreakerBuilder[R]

	// OnOpen calls the listener when the CircuitBreaker state changes to open.
	OnOpen(listener func(StateChangedEvent)) CircuitBreakerBuilder[R]

	// OnHalfOpen calls the listener when the CircuitBreaker state changes to half-open.
	OnHalfOpen(listener func(StateChangedEvent)) CircuitBreakerBuilder[R]

	// WithFailureThreshold configures count based failure thresholding by setting the number of consecutive failures that
	// must occur when in a ClosedState in order to open the circuit.
	//
	// If WithSuccessThreshold is not configured, the failureThreshold will also be used when the circuit breaker is in a
	// HalfOpenState to determine whether to transition back to OpenState or ClosedState.
	WithFailureThreshold(failureThreshold uint) CircuitBreakerBuilder[R]

	// WithFailureThresholdRatio configures count based failure thresholding by setting the ratio of failures to executions
	// that must occur when in a ClosedState in order to open the circuit. For example: 5, 10 would open the circuit if 5 out
	// of the last 10 executions result in a failure.
	//
	// If WithSuccessThreshold is not configured, the failureThreshold and failureThresholdingCapacity will also be used when
	// the circuit breaker is in a HalfOpenState to determine whether to transition back to OpenState or ClosedState.
	WithFailureThresholdRatio(failureThreshold uint, failureThresholdingCapacity uint) CircuitBreakerBuilder[R]

	// WithFailureThresholdPeriod configures time based failure thresholding by setting the number of failures that must
	// occur within the failureThresholdingPeriod when in a ClosedState in order to open the circuit.
	//
	// If WithSuccessThreshold is not configured, the failureThreshold will also be used when the circuit breaker is in a
	// HalfOpenState to determine whether to transition back to OpenState or ClosedState.
	WithFailureThresholdPeriod(failureThreshold uint, failureThresholdingPeriod time.Duration) CircuitBreakerBuilder[R]

	// WithFailureRateThreshold configures time based failure rate thresholding by setting the percentage rate of failures,
	// from 1 to 100, that must occur within the rolling failureThresholdingPeriod when in a ClosedState in order to open the
	// circuit. The number of executions must also exceed the failureExecutionThreshold within the failureThresholdingPeriod
	// before the circuit will be opened.
	//
	// If WithSuccessThreshold is not configured, the failureExecutionThreshold will also be used when the circuit breaker is
	// in a HalfOpenSttate state to determine whether to transition back to open or closed.
	WithFailureRateThreshold(failureRateThreshold uint, failureExecutionThreshold uint, failureThresholdingPeriod time.Duration) CircuitBreakerBuilder[R]

	// WithSuccessThreshold configures count based success thresholding by setting the number of consecutive successful
	// executions that must occur when in a HalfOpenState in order to close the circuit, else the circuit is re-opened when a
	// failure occurs.
	WithSuccessThreshold(successThreshold uint) CircuitBreakerBuilder[R]

	// WithSuccessThresholdRatio configures count based success thresholding by setting the ratio of successful executions
	// that must occur when in a HalfOpenState in order to close the circuit. For example: 5, 10 would close the circuit if 5
	// out of the last 10 executions were successful.
	WithSuccessThresholdRatio(successThreshold uint, successThresholdingCapacity uint) CircuitBreakerBuilder[R]

	// Build returns a new CircuitBreaker using the builder's configuration.
	Build() CircuitBreaker[R]
}

CircuitBreakerBuilder builds CircuitBreaker instances.

  • By default, any error is considered a failure and will be handled by the policy. You can override this by specifying your own handle conditions. The default error handling condition will only be overridden by another condition that handles error such as HandleErrors or HandleIf. Specifying a condition that only handles results, such as HandleResult or HandleResultIf will not replace the default error handling condition.
  • If multiple handle conditions are specified, any condition that matches an execution result or error will trigger policy handling.

This type is not concurrency safe.

func Builder

func Builder[R any]() CircuitBreakerBuilder[R]

Builder creates a CircuitBreakerBuilder for execution result type R which by default will build a count based circuit breaker that opens after a single failure, closes after a single success, and has a 1 minute delay, unless configured otherwise.

type Metrics

type Metrics interface {
	// Executions returns the number of executions recorded in the current state when the state is ClosedState or
	// HalfOpenState. When the state is OpenState, this returns the executions recorded during the previous ClosedState.
	//
	// For count based thresholding, the max number of executions is limited to the execution threshold. For time based
	// thresholds, the number of executions may vary within the thresholding period.
	Executions() uint

	// Failures returns the number of failures recorded in the current state when in a ClosedState or HalfOpenState. When
	// in OpenState, this returns the failures recorded during the previous ClosedState.
	//
	// For count based thresholds, the max number of failures is based on the failure threshold. For time based thresholds,
	// the number of failures may vary within the failure thresholding period.
	Failures() uint

	// FailureRate returns the percentage rate of failed executions, from 0 to 100, in the current state when in a
	// ClosedState or HalfOpenState. When in OpenState, this returns the rate recorded during the previous ClosedState.
	//
	// The rate is based on the configured failure thresholding capacity.
	FailureRate() uint

	// Successes returns the number of successes recorded in the current state when in a ClosedState or HalfOpenState.
	// When in OpenState, this returns the successes recorded during the previous ClosedState.
	//
	// The max number of successes is based on the success threshold.
	Successes() uint

	// SuccessRate returns percentage rate of successful executions, from 0 to 100, in the current state when in a
	// ClosedState or HalfOpenState. When in OpenState, this returns the successes recorded during the previous ClosedState.
	//
	// The rate is based on the configured success thresholding capacity.
	SuccessRate() uint
}

type State

type State int

State of a CircuitBreaker.

const (
	// ClosedState indicates the circuit is closed and fully functional, allowing executions to occur.
	ClosedState State = iota

	// OpenState indicates the circuit is opened and not allowing executions to occur.
	OpenState

	// HalfOpenState indicates the circuit is temporarily allowing executions to occur.
	HalfOpenState
)

func (State) String

func (s State) String() string

type StateChangedEvent

type StateChangedEvent struct {
	OldState State
	NewState State
}

StateChangedEvent indicates a CircuitBreaker's state has changed.

Jump to

Keyboard shortcuts

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