circuit_breaker

Circuit breaker — closed, open, half-open state machine.

Implements the classic circuit breaker pattern for fault tolerance. Transitions: Closed (normal) → Open (failing) → HalfOpen (recovering).

Usage

let config = circuit_breaker.CircuitConfig(
  failure_threshold: 5,
  recovery_timeout_ms: 30_000,
  half_open_max_calls: 2,
)
let cb = circuit_breaker.new("my_service", config)

// Before calling the service:
case circuit_breaker.is_call_allowed(cb, config) {
  circuit_breaker.Allow(cb) -> // proceed with cb
  circuit_breaker.Block(cb) -> // fail fast, use cb for later
}

// After success / failure:
let cb = circuit_breaker.record_success(cb, config)
let cb = circuit_breaker.record_failure(cb, config)

Types

pub type CallAttempt {
  Allow(breaker: CircuitBreaker)
  Block(breaker: CircuitBreaker)
}

Constructors

pub type CircuitBreaker {
  CircuitBreaker(
    name: String,
    state: CircuitState,
    failure_count: Int,
    success_count: Int,
    last_failure_time_ms: Int,
    cooldown_ms: Int,
  )
}

Constructors

  • CircuitBreaker(
      name: String,
      state: CircuitState,
      failure_count: Int,
      success_count: Int,
      last_failure_time_ms: Int,
      cooldown_ms: Int,
    )
pub type CircuitConfig {
  CircuitConfig(
    failure_threshold: Int,
    recovery_timeout_ms: Int,
    half_open_max_calls: Int,
  )
}

Constructors

  • CircuitConfig(
      failure_threshold: Int,
      recovery_timeout_ms: Int,
      half_open_max_calls: Int,
    )
pub type CircuitState {
  CircuitClosed
  CircuitOpen
  CircuitHalfOpen
}

Constructors

  • CircuitClosed
  • CircuitOpen
  • CircuitHalfOpen

Values

pub fn is_call_allowed(
  breaker: CircuitBreaker,
  config: CircuitConfig,
) -> CallAttempt

Check whether a call is allowed, returning the updated breaker.

  • Closed: always allowed, no state change.
  • Open: after recovery timeout, transitions to HalfOpen and allows the call.
  • HalfOpen: allows while success_count < half_open_max_calls.

The returned breaker in each variant reflects any state transition. Callers must use the returned breaker for subsequent record_success/record_failure calls.

pub fn new(name: String, config: CircuitConfig) -> CircuitBreaker

Create a new circuit breaker in the Closed state.

pub fn record_failure(
  breaker: CircuitBreaker,
  config: CircuitConfig,
) -> CircuitBreaker

Record a failed call. Transitions Closed → Open at threshold, HalfOpen → Open immediately.

pub fn record_success(
  breaker: CircuitBreaker,
  config: CircuitConfig,
) -> CircuitBreaker

Record a successful call. Transitions HalfOpen → Closed once enough successes.

pub fn state_name(state: CircuitState) -> String

Return the state name as a string.

Search Document