Sakura Lang

Handlers

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

An effect 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:

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:

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

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

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:

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 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.

The innermost handler's clause runs in place of the operation and returns its result once.Counter.next(): the body performs an operation. with memory_counter(0): the innermost Counter handler takes it. fn next(): its clause runs in place of the call. Then 1 or outer handlers. 1: the clause's value is the call's result. This path ends here. outer handlers: effects the clause performs go outside its with.Counter.next()the body performs an operationwith memory_counter(0)the innermost Counter handler takes itfn next()its clause runs in place of the call1the clause's valueis the call'sresultouter handlerseffects the clauseperforms gooutside 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.

The innermost handler's clause runs in place of the operation and returns its result once.

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:

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:

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

Fail<E> is built in. You recover from it with try/catch, not with a handler. See Failure.

Tests swap handlers

Tests run with predictable default handlers:

EffectDefault in tests
ClockClock.fixed(Instant.from_unix_millis(0))
RandomRandom.seeded(seed), seed from sakura test --seed
EnvEnv.of(Map.empty())
ConsoleConsole.captured(), checked with expect_output(lines)
LogLog.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:

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 page. Time, randomness, scheduling and the network are all handlers, so a test controls each one.

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.

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}") }
  }
}

Open in playground

Effects say what a function needs; handlers decide what it can reach. See Capabilities and security.

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

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

EffectHandlers
ConsoleConsole.host(), Console.captured()
ClockClock.host(), Clock.fixed(instant), Clock.virtual()
RandomRandom.host(), Random.seeded(seed)
EnvEnv.host(), Env.of(map), Env.only(keys)
LogLog.stderr(), Log.json(), Log.captured()
FsFs.host(), Fs.rooted(dir), Fs.memory(files)
HttpHttp.host(), Http.scoped(hosts), Http.scripted(script), Http.recording(path)
ServeServe.host()
SqlSql.sqlite(path), Sql.memory(), Sql.postgres(url) (v1)
CliCli.host(), Cli.of(args)
BudgetBudget.limits(limits), Budget.unlimited()
LlmLlm.anthropic(key, model), Llm.scripted(responses), Llm.replay(path)
TaskTask.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.

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

Contracts: rules about inputs and outputs, checked when the code runs.

Details for contributors: design §5.5, §5.8, §10.2, §15.6, §16.

Edit on GitHub

Last updated

On this page