Tripwire.State (tripwire v0.1.0)

Copy Markdown

Pure state machine for circuit breaker states.

Implements transitions between :closed, :open, and :half_open states. Returns side-effect directives (:schedule_timer, :cancel_timer) that the caller (typically Tripwire.Breaker) executes.

States

  • :closed - Normal operation. Calls are forwarded to the target.
  • :open - Circuit is tripped. Calls are fast-failed.
  • :half_open - Probe state. One call is allowed through.

Events

  • :failure_recorded - A target call failed (closed state only).
  • :recovery_timeout - Recovery timer elapsed (open state only).
  • :probe_success - Half-open probe succeeded.
  • :probe_failure - Half-open probe failed.

Side Effects

  • :schedule_timer - Start the recovery timer.
  • :cancel_timer - Cancel the recovery timer.

Summary

Functions

Transition the circuit breaker from state on event.

Types

event()

@type event() ::
  :failure_recorded | :recovery_timeout | :probe_success | :probe_failure

opts()

@type opts() :: keyword()

side_effect()

@type side_effect() :: :schedule_timer | :cancel_timer

state()

@type state() :: :closed | :open | :half_open

Functions

transition(arg1, arg2, opts)

@spec transition(state(), event(), opts()) ::
  {:ok, state(), [side_effect()]} | {:error, :invalid_transition}

Transition the circuit breaker from state on event.

Returns {:ok, new_state, side_effects} on a valid transition, or {:error, :invalid_transition} if the event is not legal in the current state.

Parameters

  • state - Current circuit state: :closed, :open, or :half_open.
  • event - Event to process. See the module documentation for valid events per state.
  • opts - Options keyword list. Requires :failure_count and :threshold for the :failure_recorded event.

Valid transitions

Current stateEventNew stateSide effects
:closed:failure_recorded (count < threshold):closed[]
:closed:failure_recorded (count >= threshold):open[:schedule_timer]
:open:recovery_timeout:half_open[:cancel_timer]
:half_open:probe_success:closed[]
:half_open:probe_failure:open[:schedule_timer]

All other state-event pairs return {:error, :invalid_transition}.

Opts

  • :failure_count - Current consecutive failure count (required for :failure_recorded)
  • :threshold - Failure threshold to trip the circuit (required for :failure_recorded)

Examples

# After 5 consecutive failures (threshold is 5):
Tripwire.State.transition(:closed, :failure_recorded,
  failure_count: 5, threshold: 5)
# => {:ok, :open, [:schedule_timer]}

# Recovery timeout:
Tripwire.State.transition(:open, :recovery_timeout, [])
# => {:ok, :half_open, [:cancel_timer]}

# Invalid transition:
Tripwire.State.transition(:closed, :probe_success, [])
# => {:error, :invalid_transition}