# Handlers

URL: /docs/tour/handlers
Markdown: /docs/tour/handlers.md

> How a handler decides what an effect does, how to install one with `with`, and how tests swap handlers.

An [effect](/docs/tour/effects) only names operations. A **handler** is the code that decides what those operations do when the program runs. Your code names the effect; the caller picks the handler. That is how the same function runs against a real database in production and an in-memory one in a test.

Here is an effect and a handler that keeps a count:

```sakura
effect Counter {
  fn next() -> Int
  fn reset() -> Unit
}

fn memory_counter(start: Int) -> Handler<Counter> {
  handler Counter {
    var n: Int = start
    fn next() { n = n + 1; n }
    fn reset() { n = start }
  }
}
```

And here is code that uses it, installed with `with`:

```sakura context=counter
fn label_all(items: List<String>) -> List<String> ! {Counter} {
  List.map(items, fn(item) { "{Counter.next()}. {item}" })
}

test "labels count from the handler's start" {
  let out = with memory_counter(0) { label_all(["a", "b"]) }
  expect_eq(out, ["1. a", "2. b"])
}
```

- `label_all` needs `Counter`, so its signature says `! {Counter}`.
- `with memory_counter(0) { … }` runs the block with that handler installed. Inside, every `Counter.next()` runs the handler's `next`.
- After the `with`, the test has no `Counter` left to handle.

## Writing a handler [#writing-a-handler]

`handler Eff { … }` is an expression. It makes a value of type `Handler<Eff>`.

- Write exactly one clause per operation, with the same number of parameters (`V3011`).
- Don't annotate clause parameters. Their types come from the `effect` declaration.
- `var` members are **handler state**. Only the clauses can see them. They start fresh each time the handler is installed. The clauses of one handler run one at a time.

## Installing handlers with `with` [#installing-handlers-with-with]

`with h1, h2 { body }` runs `body` with both handlers installed. `h2` sits inside `h1`. The `with` removes the handled effects from the body's row. Using `with` on something that is not a handler is `V3012`.

For the same effect, the innermost handler wins:

```sakura context=counter
test "inner handler shadows outer" {
  let out = with memory_counter(0) {
    with memory_counter(100) { Counter.next() }
  }
  expect_eq(out, 101)
}
```

## A clause returns once [#a-clause-returns-once]

A clause runs in place of the operation call, and its return value is the call's result. It always returns exactly once. There is no `resume` and no way to rewind or repeat the body (`resume` is a reserved word, `V0007`). This keeps handlers cheap and easy to follow: a handler is a service the body calls.

> **Diagram:** The innermost handler's clause runs in place of the operation and returns its result once.
>
> 1. `Counter.next()`: the body performs an operation.
> 2. `with memory_counter(0)`: the innermost Counter handler takes it.
> 3. `fn next()`: its clause runs in place of the call. Then `1` or `outer handlers`.
> 4. `1`: the clause's value is the call's result. This path ends here.
> 5. `outer handlers`: effects the clause performs go outside its with.
>
> There is no resume: the clause's value goes back to the call exactly once. A handler for the same effect further out is shadowed.

## Handlers that use other effects [#handlers-that-use-other-effects]

A clause may perform other effects. They go to the handlers installed **outside** the `with`. Calling the same effect inside its own clause reaches the next handler out, which is how you write a wrapper:

```sakura
fn prefixed(prefix: String) -> Handler<Log, {Log}> {
  handler Log {
    fn event(level, message, fields) { Log.event(level, "{prefix}{message}", fields) }
  }
}
```

`prefixed` handles `Log` and itself uses `Log`, so its type is `Handler<Log, {Log}>`: the second part lists what the handler's clauses use. Installing it adds those effects to the surrounding row. A handler cannot create authority from nothing.

A clause may `fail` only with errors its operation declares:

```sakura
type Table = String
error DbUnavailable(reason: String)

effect Db {
  fn exists(table: Table, key: String) -> Bool
  fn insert(table: Table, row: Json) -> Unit ! {Fail<DbUnavailable>}
}

fn memory_db() -> Handler<Db> {
  handler Db {
    var rows: Map<String, Json> = Map.empty()
    fn exists(table, key) { Map.contains(rows, "{table}/{key}") }
    fn insert(table, row) {
      rows = Map.insert(rows, "{table}/{Json.get_string(row, "id")}", row)
    }
  }
}
```

Here `insert` may `fail DbUnavailable { … }`, and `exists` may not fail at all.

## Failure is not handled with handlers [#failure-is-not-handled-with-handlers]

`Fail<E>` is built in. You recover from it with `try`/`catch`, not with a handler. See [Failure](/docs/tour/effects#failure-faile-and-error-unions).

## Tests swap handlers [#tests-swap-handlers]

Tests run with predictable default handlers:

| Effect | Default in tests |
| --- | --- |
| `Clock` | `Clock.fixed(Instant.from_unix_millis(0))` |
| `Random` | `Random.seeded(seed)`, seed from `sakura test --seed` |
| `Env` | `Env.of(Map.empty())` |
| `Console` | `Console.captured()`, checked with `expect_output(lines)` |
| `Log` | `Log.captured()` |

Any other effect must be handled inside the test with `with`, or `sakura check` reports `V3020` ("test uses Db; install a handler with `with`"). Failures are the exception: a test may let a `Fail<E>` escape, and the test then fails with the error. No mocking library is needed, because an effect is already an interface:

```sakura context=fetch-both
test "deterministic under virtual time" {
  with Http.scripted([(Matcher.Any, Response.status(200, "x"))]), Clock.virtual(), Random.seeded(1), Task.deterministic(1) {
    expect_eq(fetch_both(Url.from("https://a"), Url.from("https://b")), ("x", "x"))
  }
}
```

`fetch_both` is the example on the [Concurrency](/docs/tour/concurrency#timeouts-retries-and-budgets) page. Time, randomness, scheduling and the network are all handlers, so a test controls each one.

## Where root handlers come from [#where-root-handlers-come-from]

`main` lists the standard effects the program needs. When the program starts, the host supplies a handler for each one, limited by `[permissions]` in `sakura.toml`. Only standard effects may appear in `main`'s row (`V6010`); your own effects, such as `Counter`, must be handled inside the program.

This excerpt reads its arguments, so it declares `Cli`. It is not a standalone program.

```sakura fragment
import std/cli.{Cli, CliError}
import std/fs.{Fs, FsError, Dir}

pub fn main() -> Unit ! {Console, Cli, Fs, Fail<CliError | FsError>} {
  let args: Args = Cli.parse(Cli.args())
  // Narrow the root Fs handler to the data directory before touching files.
  with Fs.rooted(Dir.subdir(Fs.root(), "data")) {
    let text = Fs.read_text(args.input).trust(@trust("word counting cannot be influenced by content"))
    let top = List.slice(List.sort_by(Map.entries(word_counts(text)), fn(e) { 0 - e.1 }), 0, args.top)
    for (word, n) in top { Console.print("{word}: {n}") }
  }
}
```

Effects say what a function needs; handlers decide what it can reach. See [Capabilities and security](/docs/tour/capabilities).

## Handlers are values [#handlers-are-values]

A function can return a handler, and a record can store one. A handler that holds a capability cannot outlive the `with` that produced the capability (`V6002`). When a `with` exits, by returning, failing, a defect or cancellation, its handler state and resources are released.

## Standard handlers [#standard-handlers]

Each constructor lives in the effect's module, so `Console.host()` is `std/console.host`.

| Effect | Handlers |
| --- | --- |
| `Console` | `Console.host()`, `Console.captured()` |
| `Clock` | `Clock.host()`, `Clock.fixed(instant)`, `Clock.virtual()` |
| `Random` | `Random.host()`, `Random.seeded(seed)` |
| `Env` | `Env.host()`, `Env.of(map)`, `Env.only(keys)` |
| `Log` | `Log.stderr()`, `Log.json()`, `Log.captured()` |
| `Fs` | `Fs.host()`, `Fs.rooted(dir)`, `Fs.memory(files)` |
| `Http` | `Http.host()`, `Http.scoped(hosts)`, `Http.scripted(script)`, `Http.recording(path)` |
| `Serve` | `Serve.host()` |
| `Sql` | `Sql.sqlite(path)`, `Sql.memory()`, `Sql.postgres(url)` (v1) |
| `Cli` | `Cli.host()`, `Cli.of(args)` |
| `Budget` | `Budget.limits(limits)`, `Budget.unlimited()` |
| `Llm` | `Llm.anthropic(key, model)`, `Llm.scripted(responses)`, `Llm.replay(path)` |
| `Task` | `Task.host()`, `Task.deterministic(seed)` |

`retry` and `timeout` are ordinary functions, not handlers. `Budget.limits(limits)` is a handler, configured with a `Limits { tokens, usd, calls }` record. See [Concurrency](/docs/tour/concurrency#timeouts-retries-and-budgets).

## What the compiler checks [#what-the-compiler-checks]

- A `handler` has exactly one clause per operation, with matching parameter counts (`V3011`).
- `with` is applied only to handlers (`V3012`).
- A `with` removes the effects it handles and adds each handler's own row. The result is checked against the signature (`V3001`, reported at the clause when a clause uses an undeclared effect).
- A clause fails only with errors declared on its operation.
- A test installs a handler for every effect outside the test defaults (`V3020`).
- A handler that holds a capability does not escape its scope (`V6002`).
- `main`'s row contains only standard effects (`V6010`).

## Next [#next]

[Contracts](/docs/tour/contracts): rules about inputs and outputs, checked when the code runs.

Details for contributors: [design §5.5, §5.8, §10.2, §15.6, §16](https://github.com/icantcodefyi/sakuralang/blob/main/docs/design.md).
