# `Snakepit.CircuitBreaker`
[🔗](https://github.com/nshkrdotcom/snakepit/blob/v0.13.0/lib/snakepit/circuit_breaker.ex#L1)

Circuit breaker for Python worker fault tolerance.

Implements the circuit breaker pattern to prevent cascading failures
when workers are experiencing issues.

## States

- `:closed` - Normal operation, all calls allowed
- `:open` - Failure threshold exceeded, calls rejected
- `:half_open` - Testing if service recovered, limited calls allowed

## Usage

    {:ok, cb} = CircuitBreaker.start_link(name: :my_cb, failure_threshold: 5)

    case CircuitBreaker.call(cb, fn -> risky_operation() end) do
      {:ok, result} -> handle_success(result)
      {:error, :circuit_open} -> handle_circuit_open()
      {:error, reason} -> handle_error(reason)
    end

# `state`

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

# `t`

```elixir
@type t() :: %{
  state: state(),
  failure_count: non_neg_integer(),
  success_count: non_neg_integer(),
  failure_threshold: pos_integer(),
  reset_timeout_ms: pos_integer(),
  half_open_max_calls: pos_integer(),
  half_open_calls: non_neg_integer(),
  last_failure_time: integer() | nil,
  name: atom() | nil
}
```

# `allow_call?`

```elixir
@spec allow_call?(GenServer.server()) :: boolean()
```

Checks if a call is allowed through the circuit.

# `call`

```elixir
@spec call(GenServer.server(), (-&gt; any())) :: any()
```

Executes a function through the circuit breaker.

Returns `{:error, :circuit_open}` if the circuit is open.

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `record_failure`

```elixir
@spec record_failure(GenServer.server()) :: :ok
```

Records a failed call.

# `record_success`

```elixir
@spec record_success(GenServer.server()) :: :ok
```

Records a successful call.

# `reset`

```elixir
@spec reset(GenServer.server()) :: :ok
```

Resets the circuit breaker to closed state.

# `start_link`

```elixir
@spec start_link(keyword()) :: GenServer.on_start()
```

Starts a circuit breaker.

## Options

- `:name` - GenServer name (optional)
- `:failure_threshold` - Number of failures before opening (default: 5)
- `:reset_timeout_ms` - Time before transitioning to half-open (default: 30000)
- `:half_open_max_calls` - Max calls allowed in half-open state (default: 1)

# `state`

```elixir
@spec state(GenServer.server()) :: state()
```

Returns the current circuit state.

# `stats`

```elixir
@spec stats(GenServer.server()) :: map()
```

Returns circuit breaker statistics.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
