# `Wise.Internal.CircuitBreaker`
[🔗](https://github.com/iamkanishka/wise/blob/v1.0.0/lib/wise/internal/circuit_breaker.ex#L1)

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

# `state`

```elixir
@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()
}
```

# `state_name`

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

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `current_state`

```elixir
@spec current_state(GenServer.server()) :: state_name()
```

Returns the current circuit state: `:closed`, `:open`, or `:half_open`.

# `execute`

```elixir
@spec execute(GenServer.server(), (-&gt; {: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.

# `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 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

---

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