Circuit breaker implementing the CLOSED → OPEN → HALF_OPEN state machine.
Protects against cascading failures by rejecting requests when too many consecutive failures are detected.
States
- CLOSED — Normal operation. All requests pass through.
- OPEN — Failure threshold exceeded. Requests are rejected immediately.
- HALF_OPEN — After the timeout, one probe request is allowed through.
Usage
{:ok, cb} = Wise.Internal.CircuitBreaker.start_link(failure_threshold: 5)
case Wise.Internal.CircuitBreaker.execute(cb, fn -> make_request() end) do
{:ok, result} -> result
{:error, %Wise.Error{type: :circuit_open}} -> handle_open()
{:error, err} -> handle_error(err)
end
Summary
Functions
Returns a specification to start this module under a supervisor.
Returns the current circuit state: :closed, :open, or :half_open.
Executes fun through the circuit breaker.
Resets the circuit breaker to CLOSED state.
Starts a circuit breaker process.
Types
@type state() :: %{ state: state_name(), consecutive_fails: non_neg_integer(), consecutive_ok: non_neg_integer(), opened_at: integer() | nil, failure_threshold: pos_integer(), success_threshold: pos_integer(), timeout_ms: pos_integer() }
@type state_name() :: :closed | :open | :half_open
Functions
Returns a specification to start this module under a supervisor.
See Supervisor.
@spec current_state(GenServer.server()) :: state_name()
Returns the current circuit state: :closed, :open, or :half_open.
@spec execute(GenServer.server(), (-> {:ok, any()} | {:error, any()})) :: {:ok, any()} | {:error, Wise.Error.t()}
Executes fun through the circuit breaker.
Returns {:ok, result} on success or {:error, Wise.Error.t()} on failure.
If the circuit is OPEN, returns {:error, %Wise.Error{type: :circuit_open}} immediately.
@spec reset(GenServer.server()) :: :ok
Resets the circuit breaker to CLOSED state.
@spec start_link(keyword()) :: GenServer.on_start()
Starts a circuit breaker process.
Options
:failure_threshold- failures before opening (default: 5):success_threshold- successes in HALF_OPEN before closing (default: 2):timeout_ms- ms to stay OPEN before going HALF_OPEN (default: 30_000):name- GenServer registration name