Circuit Breaker
Threadsafe pure-Python implementation of the Circuit Breaker pattern, described by Michael T. Nygard in his book ‘Release It!’.
For more information on this and other patterns and best practices, buy the book at https://pragprog.com/titles/mnee2/release-it-second-edition/
CircuitBreaker
- class aiobreaker.circuitbreaker.CircuitBreaker(fail_max=5, timeout_duration=None, exclude=None, listeners=None, state_storage=None, name=None)[source]
Bases:
object
A circuit breaker is a route through which functions are executed. When a function is executed via a circuit breaker, the breaker is notified. Multiple failed attempts will open the breaker and block additional calls.
- __init__(fail_max=5, timeout_duration=None, exclude=None, listeners=None, state_storage=None, name=None)[source]
Creates a new circuit breaker with the given parameters.
- Parameters
fail_max – The maximum number of failures for the breaker.
timeout_duration (
Optional
[timedelta
]) – The timeout to elapse for a breaker to close again.exclude (
Optional
[Iterable
[Union
[Callable
,Type
[Exception
]]]]) – A list of excludedException
types to ignore.listeners (
Optional
[Iterable
[CircuitBreakerListener
]]) – A list ofCircuitBreakerListener
state_storage (
Optional
[CircuitBreakerStorage
]) – A type of storage. Defaults toCircuitMemoryStorage
- property fail_counter
Returns the current number of consecutive failures.
- property fail_max
Returns the maximum number of failures tolerated before the circuit is opened.
- property timeout_duration
Once this circuit breaker is opened, it should remain opened until the timeout period elapses.
- property opens_at: Optional[datetime.datetime]
Gets the remaining timeout for a breaker.
- property time_until_open: Optional[datetime.timedelta]
Returns a timedelta representing the difference between the current time and when the breaker closes again, or None if it has elapsed.
- property state
Update (if needed) and returns the cached state object.
- property current_state: aiobreaker.state.CircuitBreakerState
Returns a CircuitBreakerState that identifies the state of the circuit breaker.
- Return type
- property excluded_exceptions: tuple
Returns a tuple of the excluded exceptions, e.g., exceptions that should not be considered system errors by this circuit breaker.
- Return type
- add_excluded_exceptions(*exceptions)[source]
Adds exceptions to the list of excluded exceptions.
- Parameters
exceptions – Any Exception types you wish to ignore.
- remove_excluded_exception(exception)[source]
Removes an exception from the list of excluded exceptions.
- is_system_error(exception)[source]
Returns whether the exception exception is considered a signal of system malfunction. Business exceptions should not cause this circuit breaker to open.
- call(func, *args, **kwargs)[source]
Calls func with the given args and kwargs according to the rules implemented by the current state of this circuit breaker.
- async call_async(func, *args, **kwargs)[source]
Calls func with the given args and kwargs according to the rules implemented by the current state of this circuit breaker.
- open()[source]
Opens the circuit, e.g., the following calls will immediately fail until timeout elapses.
- half_open()[source]
Half-opens the circuit, e.g. lets the following call pass through and opens the circuit if the call fails (or closes the circuit if the call succeeds).
- __call__(*call_args, ignore_on_call=True)[source]
Decorates the function such that calls are handled according to the rules implemented by the current state of this circuit breaker.
- Parameters
ignore_on_call – Whether the decorated function should be ignored when using
call()
, preventing the breaker being triggered twice.
- property listeners
Returns the registered listeners as a tuple.
Listener
- class aiobreaker.listener.CircuitBreakerListener[source]
Bases:
object
Listener class used to plug code to a CircuitBreaker instance when certain events happen.
todo async listener handlers
- before_call(breaker, func, *args, **kwargs)[source]
Called before a function is executed over a breaker.
- Parameters
breaker (CircuitBreaker) – The breaker that is used.
func (
Callable
) – The function that is called.args – The args to the function.
kwargs – The kwargs to the function.
- Return type
- failure(breaker, exception)[source]
Called when a function executed over the circuit breaker ‘breaker’ fails.
- Return type
State
- exception aiobreaker.state.CircuitBreakerError(message, reopen_time)[source]
Bases:
Exception
Raised when the function fails due to the breaker being open.
- property time_remaining: datetime.timedelta
- Return type
- class aiobreaker.state.CircuitBreakerBaseState(breaker, state)[source]
Bases:
abc.ABC
Implements the behavior needed by all circuit breaker states.
- __init__(breaker, state)[source]
Creates a new instance associated with the circuit breaker cb and identified by name.
- property state: aiobreaker.state.CircuitBreakerState
Returns a human friendly name that identifies this state.
- Return type
- call(func, *args, **kwargs)[source]
Calls func with the given args and kwargs, and updates the circuit breaker state according to the result.
- Return type
~T
- before_call(func, *args, **kwargs)[source]
Override this method to be notified before a call to the guarded operation is attempted.
- class aiobreaker.state.CircuitClosedState(breaker, prev_state=None, notify=False)[source]
Bases:
aiobreaker.state.CircuitBreakerBaseState
In the normal “closed” state, the circuit breaker executes operations as usual. If the call succeeds, nothing happens. If it fails, however, the circuit breaker makes a note of the failure.
Once the number of failures exceeds a threshold, the circuit breaker trips and “opens” the circuit.
- class aiobreaker.state.CircuitOpenState(breaker, prev_state=None, notify=False)[source]
Bases:
aiobreaker.state.CircuitBreakerBaseState
When the circuit is “open”, calls to the circuit breaker fail immediately, without any attempt to execute the real operation. This is indicated by the
CircuitBreakerError
exception.After a suitable amount of time, the circuit breaker decides that the operation has a chance of succeeding, so it goes into the “half-open” state.
- __init__(breaker, prev_state=None, notify=False)[source]
Moves the given circuit breaker to the “open” state.
- before_call(func, *args, **kwargs)[source]
After the timeout elapses, move the circuit breaker to the “half-open” state. :raises CircuitBreakerError: if the timeout has still to be elapsed.
- class aiobreaker.state.CircuitHalfOpenState(breaker, prev_state=None, notify=False)[source]
Bases:
aiobreaker.state.CircuitBreakerBaseState
In the “half-open” state, the next call to the circuit breaker is allowed to execute the dangerous operation. Should the call succeed, the circuit breaker resets and returns to the “closed” state. If this trial call fails, however, the circuit breaker returns to the “open” state until another timeout elapses.
- class aiobreaker.state.CircuitBreakerState(value)[source]
Bases:
enum.Enum
An enumeration.
- OPEN = <class 'aiobreaker.state.CircuitOpenState'>
- CLOSED(breaker, prev_state=None, notify=False) = <class 'aiobreaker.state.CircuitClosedState'>
- HALF_OPEN = <class 'aiobreaker.state.CircuitHalfOpenState'>
Version
- aiobreaker.version.short_version = '1.1'
A short version.