---
title: "12.3 Your own capabilities and handlers"
url: https://una-lang.org/en/learn/capabilities/your-own-capabilities-and-handlers/
release: v0.4.0
edition: "0.2"
---

# 12.3 Your own capabilities and handlers

## 12.3.1 What a capability you declare is

The host capabilities cover the machine: the screen, the clock, the files. A store's program also talks to services of its own: a mail service, a payment provider, a customer directory, an inventory, a scale at the packing desk. In Una each of these is a capability that you declare, and it comes in two parts:

- A **`capability` declaration** lists what the service can do: its operations, each with the types it takes and gives back, and how it can fail. It holds no code.
- A **`handler`** gives those operations their code: one way to provide the service. A capability can have many handlers, such as one that talks to the real service, one that prints what it would send, and one that always fails.

Think of a job description and the people who fill it. The description of a cashier lists the duties: take payment, give change, print a receipt. Any trained person can do the job, and the store can put a trainee on the till for practice without changing the description. The `capability` is the description; each `handler` is a person who can do the job. The code that needs the service names the description in its `uses`, and its caller chooses who does the work, with `with`.

## 12.3.2 Why declare a capability

Here is a receipt sender written before the store had a mail service. It prints each message on the console:

```una include="steps/08-mail-by-console/src/receipts.una" title="steps/08-mail-by-console/src/receipts.una" verified="check, run"
module receipts

--- Emails the receipt of an order. For now it prints the message, since the store has no mail
--- service yet.
send_receipt(to: Text, order: Text) -> Unit
  uses @console: Console[print]
=
  @console.print("to {to}: Receipt for order {order}")

pub main() -> Unit
  uses @console: Console[print]
=
  send_receipt("rosa@example.invalid", order: "A-1001")
```

```text include="steps/08-mail-by-console/expected/output.txt"
to rosa@example.invalid: Receipt for order A-1001
```

It runs, but it is fragile in three ways:

1. **The header says the wrong thing.** `uses @console: Console[print]` tells a reviewer that `send_receipt` prints. It does not say that it sends mail, which is its job.
2. **Changing the service means changing the code.** When the store gets a real mail service, the body of `send_receipt` changes, and so does the header of every function that calls it, since they must now hold whatever the new service needs.
3. **The failures have nowhere to go.** A mail service can refuse an address or not answer. Printing never fails, so the header has no `fails` clause, and no caller is ready for a failure.

A capability fixes all three. `uses @mailer: Mailer[send]` says what the function does. The handler can change without touching `send_receipt` or its callers. And the operation's `fails` clause tells every caller how mail can fail.

## 12.3.3 How to write a capability

### 12.3.3.1 The capability and its operations

A capability is the word `capability`, a name, and one operation per line under it, indented two spaces. An operation is `op`, a name, typed parameters and a result type, like a function header with no body:

```una include="steps/09-handlers/src/receipts.una#MailError..Mailer" title="steps/09-handlers/src/receipts.una"
--- How the mail service can fail.
kind MailError = Bounced(address: Text) | Timeout

--- The mail service: what it can do, with no code.
capability Mailer
  op send(to: Text, subject: Text) -> Unit
    fails MailError
```

### 12.3.3.2 An operation that can fail: `fails`

A clause under an operation, indented two spaces more, says how it can fail. `fails MailError` works exactly as on a function ([section 7.2](https://una-lang.org/en/learn/failure/declaring-a-failure-fails-and-fail/#s7-2)): a caller handles the failure with a clause or passes it on.

### 12.3.3.3 An operation with a contract: `requires` and `ensures`

An operation can carry the contracts of [chapter 5](https://una-lang.org/en/learn/contracts/). The scale at the packing desk takes a SKU of at least four characters, and promises a weight of at least 1 gram:

```una include="steps/10-scale/src/scales.una#ScaleError..Scale" title="steps/10-scale/src/scales.una"
--- How the scale can fail.
kind ScaleError = | NotOnScale

--- The scale at the packing desk. The clauses of `weigh` are its contract: a caller passes a
--- SKU of at least four characters, and gets a weight of at least 1 gram back.
capability Scale
  op weigh(sku: Text) -> Int
    requires sku.len >= 4
    ensures result >= 1
    fails ScaleError
```

`requires` is what every caller must prove at the call. `ensures` is what every caller may rely on. For a service outside the program, an `ensures` is an assumption: the verifier checks every handler written in Una against it, and trusts the real service to keep it.

### 12.3.3.4 What an operation accepts: `accepts`

A fourth clause, `accepts`, states the most sensitive data the operation may receive. [Chapter 17](https://una-lang.org/en/learn/information-flow/) explains it.

### 12.3.3.5 A capability for other modules: `pub capability`

Like a function or a kind, a capability can be used outside its module only when it is declared `pub` ([section 11.2](https://una-lang.org/en/learn/packages/pub-and-import/#s11-2)): `pub capability Mailer`. The day-to-day program of [section 12.5](https://una-lang.org/en/learn/capabilities/day-to-day-shipping-notices/#s12-5) declares its services `pub`.

## 12.3.4 How to write a handler

### 12.3.4.1 The handler and its operations

A handler is the word `handler`, a name, parameters in parentheses, `for` and the capability it implements. Under it, one `op` line per operation of the capability, each with the operation's name, its parameter names, `=` and the body:

```una include="steps/10-scale/src/scales.una#fixed" title="steps/10-scale/src/scales.una"
--- A scale on a developer's machine: it weighs every item at the same weight.
handler fixed(grams: Int) for Scale
  op weigh(sku) = if grams < 1 then fail NotOnScale else grams
```

The operation's parameters take their names only: their types and the result type come from the capability. The body is ordinary Una code. Here it fails with a variant of the operation's error kind when the fixed weight makes no sense, and returns the weight otherwise.

### 12.3.4.2 Handler parameters

`fixed(grams: Int)` has a parameter, as a function does. Its value is given when the handler is installed, and every operation of the handler can read it: `weigh` returns `grams`. A handler with no parameters is written with empty parentheses, as `bouncing()`.

### 12.3.4.3 A handler with capabilities of its own

A handler may declare `uses` lines, under its first line. A mail service for a developer's machine prints each message, so it holds the console:

```una include="steps/09-handlers/src/receipts.una#printed" title="steps/09-handlers/src/receipts.una"
--- A mail service for a developer's machine: it prints each message instead of sending it.
handler printed(prefix: Text) for Mailer
  uses @console: Console[print]
  op send(to, subject) = @console.print("{prefix} to {to}: {subject}")
```

The code that installs the handler must hold those capabilities.

### 12.3.4.4 Installing a handler: `with`

A handler runs only where it is installed. `with @scale = fixed(850)`, at the end of a statement, installs the handler for the call in that statement:

```una include="steps/10-scale/src/scales.una#parcel_grams..main" title="steps/10-scale/src/scales.una"
--- A parcel's weight in grams: the item, and a box of 150 grams.
parcel_grams(sku: Text) -> Int
  requires sku.len >= 4
  ensures result >= 151
  uses @scale: Scale[weigh]
  fails ScaleError
=
  let grams = @scale.weigh(sku)
    if error pass
  grams + 150

--- A scale on a developer's machine: it weighs every item at the same weight.
handler fixed(grams: Int) for Scale
  op weigh(sku) = if grams < 1 then fail NotOnScale else grams

pub main() -> Unit
  uses @console: Console[print]
=
  let weighed = attempt parcel_grams("LAMP-01") with @scale = fixed(850)
  @console.print("{weighed}")
  let empty = attempt parcel_grams("LAMP-01") with @scale = fixed(0)
  @console.print("{empty}")
```

`parcel_grams` holds `@scale: Scale[weigh]`. It never learns which handler answers; `main` chooses. The step prints:

```text include="steps/10-scale/expected/output.txt#L1"
Ok(1000)
```

The weight is the item's 850 grams and the box's 150. `parcel_grams` promises at least 151 grams, and the verifier proves it from the operation's `ensures result >= 1`, without knowing any handler. [Section 12.4](https://una-lang.org/en/learn/capabilities/passing-authority-with-rebinding-and-narrowing/#s12-4) covers every form of `with`.

## 12.3.5 Receipts by email

Now the mail service, with two handlers. On a developer's machine the mail service prints each message instead of sending it, and a second handler stands for a service that refuses every address:

:::steps
```una include="steps/09-handlers/src/receipts.una" title="steps/09-handlers/src/receipts.una" verified="check, run"
module receipts

--- How the mail service can fail.
kind MailError = Bounced(address: Text) | Timeout

--- The mail service: what it can do, with no code.
capability Mailer
  op send(to: Text, subject: Text) -> Unit
    fails MailError

--- Emails the receipt of an order. It may send mail, and nothing else.
send_receipt(to: Text, order: Text) -> Unit
  uses @mailer: Mailer[send]
  fails MailError
=
  @mailer.send(to, subject: "Receipt for order {order}")
    if error pass

--- A mail service for a developer's machine: it prints each message instead of sending it.
handler printed(prefix: Text) for Mailer
  uses @console: Console[print]
  op send(to, subject) = @console.print("{prefix} to {to}: {subject}")

--- A mail service that refuses every address.
handler bouncing() for Mailer
  op send(to, subject) = fail Bounced(address: to)

pub main() -> Unit
  uses @console: Console[print]
=
  send_receipt("rosa@example.invalid", order: "A-1001") with @mailer = printed("[mail]")
    if error use unit
  let outcome = attempt send_receipt("tomas@example.invalid", order: "A-1002") with @mailer = bouncing()
  @console.print("second receipt: {outcome}")
```

1. **`capability Mailer` and `op send(...) -> Unit`.** One operation, which can fail with `MailError`.
2. **`send_receipt`.** It uses `@mailer: Mailer[send]` and fails with `MailError`. It does not know which mail service it talks to.
3. **`handler printed(prefix: Text) for Mailer`.** `prefix` is a parameter of the handler, given when it is installed and seen by `send`.
4. **`uses @console: Console[print]` inside the handler.** The console comes from the code that installs it: here `main`, which holds `@console`.
5. **`fail Bounced(address: to)`.** `bouncing` fails every time, with a variant of the operation's error kind.
6. **`with @mailer = printed("[mail]")`.** Inside that call, `@mailer` is the `printed` handler. `if error use unit` handles a failure, which `printed` never has.
7. **`attempt … with @mailer = bouncing()`.** The same function with the other handler. `attempt` keeps the failure as a value.
:::

`una run .` prints:

```text include="steps/09-handlers/expected/output.txt"
[mail] to rosa@example.invalid: Receipt for order A-1001
second receipt: Err(Bounced("tomas@example.invalid"))
```

The second line comes from `attempt` with the `bouncing` handler: the receipt was not sent, and the outcome says why.

## 12.3.6 Recovering with a default from a service

A service can fail, and the clauses of [section 7.3](https://una-lang.org/en/learn/failure/handling-a-failure-the-clauses/#s7-3) handle the failure of an operation as they handle any call's. Most code passes the failure on, but sometimes carrying on is the right behavior. A product page must show how many units a customer may order, even when the inventory service does not answer, and it must never promise stock it cannot confirm:

:::steps
```una include="steps/11-orderable/src/orderable.una" title="steps/11-orderable/src/orderable.una" verified="check, run"
module orderable

--- How the inventory service can fail.
kind StoreError = | Timeout

--- The inventory service: how many units of a SKU are on hand, or `None` for a SKU it does not
--- stock.
capability Inventory
  op on_hand(sku: Text) -> Option[Int]
    fails StoreError

--- How many units of a SKU a customer may order on the product page. The page must show a
--- number even when the inventory does not answer, and must never promise stock it cannot
--- confirm, so a failure and an unknown SKU both give 0.
orderable(sku: Text) -> Int
  uses @inventory: Inventory[on_hand]
=
  let units = @inventory.on_hand(sku)
    if error use None
    if none use 0
  units

--- An inventory held in memory: the units on hand of each SKU.
handler warehouse(stock: Map[Text, Int]) for Inventory
  op on_hand(sku) = stock.get(key: sku)

--- An inventory that never answers.
handler offline() for Inventory
  op on_hand(sku) = fail Timeout

--- Prints what the product page offers for three SKUs, then for one while the inventory is
--- offline.
pub main() -> Unit
  uses @console: Console[print]
=
  let stock = empty_map().with(key: "LAMP-01", value: 4).with(key: "DESK-02", value: 1)
  for sku in ["LAMP-01", "DESK-02", "CHAIR-09"]
    let units = orderable(sku) with @inventory = warehouse(stock)
    @console.print("{sku}: up to {units}")
  let later = orderable("LAMP-01") with @inventory = offline()
  @console.print("LAMP-01, inventory offline: up to {later}")
```

1. **`kind StoreError = | Timeout`.** How the inventory can fail. A sum kind with one variant starts with `|`.
2. **`op on_hand(sku: Text) -> Option[Int]` with `fails StoreError`.** The operation gives two kinds of answer and one failure: `Some(units)` for a SKU it stocks, `None` for a SKU it does not, and `Timeout` when it does not answer.
3. **`if error use None`, then `if none use 0`.** Two clauses on one call, read top to bottom. First, a failure of the call becomes the value `None`. Then `None`, from either source, becomes `0`.
4. **`handler warehouse(stock: Map[Text, Int]) for Inventory`.** An inventory held in a map ([section 10.4](https://una-lang.org/en/learn/collections/maps/#s10-4)), passed when the handler is installed. `stock.get(key: sku)` already gives an `Option[Int]`.
5. **`handler offline() for Inventory`.** An inventory that never answers.
6. **`with @inventory = warehouse(stock)` inside a `for`.** Each turn of the loop installs the handler for its own call of `orderable`.
:::

`una run .` prints:

```text include="steps/11-orderable/expected/output.txt"
LAMP-01: up to 4
DESK-02: up to 1
CHAIR-09: up to 0
LAMP-01, inventory offline: up to 0
```

`orderable` has no `fails` line, and it needs none: no failure leaves it. Its header promises callers a number, always. `CHAIR-09` is not in the map, so the warehouse gives `None`, and the page offers 0; with `offline()`, the failure becomes 0 too.

## 12.3.7 How handlers behave

### 12.3.7.1 A handler implements every operation

A handler must implement every operation of its capability, with the same names and the same number of parameters. Give the scale a second operation, `tare`, which sets it to zero, and leave the handler as it was:

```una include="steps/12-missing-op/src/scales.una#Scale..fixed" title="steps/12-missing-op/src/scales.una"
--- The scale at the packing desk: it weighs, and it can be set to zero.
capability Scale
  op weigh(sku: Text) -> Int
  op tare() -> Unit

--- A scale that only weighs.
handler fixed(grams: Int) for Scale
  op weigh(sku) = grams
```

```text include="steps/12-missing-op/expected/rendered.txt"
[U3011] Error: handler `fixed` does not implement the operation `tare` of `Scale`
   ╭─[ src/scales.una:9:9 ]
   │
 9 │ handler fixed(grams: Int) for Scale
   │         ──┬──
   │           ╰──── handler `fixed` does not implement the operation `tare` of `Scale`
   │
   │ Note: run `una explain U3011` for an explanation
───╯
```

U3011 names the handler, `fixed`, and the operation it lacks, `tare`. The mark is on the handler's name. Add `op tare() = unit` to the handler, or remove the operation if no handler should have it.

### 12.3.7.2 A handler is held to the operation's contract

The verifier checks each operation of a handler against the operation's `ensures`, as it checks a function. Return `grams` without the test:

```diff include="steps/10-scale..steps/13-broken-promise:src/scales.una" context="1" title="src/scales.una"
--- a/src/scales.una
+++ b/src/scales.una
@@ -26,3 +26,3 @@
 handler fixed(grams: Int) for Scale
-  op weigh(sku) = if grams < 1 then fail NotOnScale else grams
+  op weigh(sku) = grams
 
```

```text include="steps/13-broken-promise/expected/rendered.txt"
[U5001] Error: postcondition of `weigh` is refuted
    ╭─[ src/scales.una:27:19 ]
    │
 11 │     ensures result >= 1
    │             ─────┬─────
    │                  ╰─────── ensures clause
    │
 27 │   op weigh(sku) = grams
    │                   ──┬──
    │                     ╰──── postcondition of `weigh` is refuted
    │
    │ Help 1: repair 1: add a guard or an arm so that the failing path returns a value for which `result >= 1` holds
    │
    │ Help 2: repair 2: adjust the `ensures` clause
    │
    │ Note 1: obligation ob-8bdfbdc534e5 (postcondition) is refuted: result >= 1
    │
    │ Note 2: counterexample: grams = 0, result = 0, sku = Text#0, sku.len = 4
    │
    │ Note 3: run `una explain U5001` for an explanation
────╯
```

The diagnostic is U5001, the refuted postcondition of [section 5.2](https://una-lang.org/en/learn/contracts/postconditions-ensures-and-counterexamples/#s5-2). The marks show the promise, `ensures result >= 1` on the operation, and the body that breaks it, `grams`. The counterexample, `grams = 0`, is a scale installed with a weight of 0. Callers rely on the promise, so a handler that breaks it does not check.

### 12.3.7.3 A handler is not a value

> [!TIP]
> A handler is not a value. It cannot be stored in a variable, passed as an ordinary argument or returned. It exists only where `with` installs it, and its parameters are fixed there.

An example installs one too, with a `given` line, as [section 12.6](https://una-lang.org/en/learn/capabilities/testing-it/#s12-6) shows.

### 12.3.7.4 Every capability is in the report

The `authority:` part of `una report .` ([section 6.3](https://una-lang.org/en/learn/functions/what-a-header-says-pub-private-functions-and-inferred-headers/#s6-3)) lists your own capabilities as it lists the host's. Two more parts are for capabilities you declare. Under `handler authority`, the report lists what each handler may use. Under `assumptions`, it lists each capability the package declares, with its operations, since the program assumes that each service does what its declaration says:

```text include="steps/09-handlers/expected/commands/report.txt#L8-L12,L15-L16"
authority:
  receipts.main (pub): @console: Console[print]
  receipts.send_receipt (private): @mailer: Mailer[send]
handler authority:
  receipts.printed for receipts.Mailer (private): @console: Console[print]
assumptions:
  receipts.Mailer: send
```

## 12.3.8 A capability, a host capability or a pure function

:::decide
**Which to use:**

| The code needs… | Use |
| --- | --- |
| Only to compute a value from its arguments | A pure function, with no `uses` |
| The screen, the clock, the files or the network of the machine | A host capability, granted to `main` |
| A service of the business, such as mail, payments or a directory | A `capability` of your own, with a handler for each way to provide it |
| To keep working when a service fails | A clause on the operation's call, such as `if error use` |
| Another provider of the same service, for a trial run or a developer's machine | Another handler of the same capability |
:::

A capability of your own costs a declaration and a handler. It pays back as soon as the service has two providers, which it does the day you run it on a developer's machine or write a test.

## 12.3.9 Check yourself: handlers

`main` in the scale's step makes a second call, with a scale installed at a weight of 0:

```una include="steps/10-scale/src/scales.una#main" title="steps/10-scale/src/scales.una"
pub main() -> Unit
  uses @console: Console[print]
=
  let weighed = attempt parcel_grams("LAMP-01") with @scale = fixed(850)
  @console.print("{weighed}")
  let empty = attempt parcel_grams("LAMP-01") with @scale = fixed(0)
  @console.print("{empty}")
```

What does the second line print?

:::answer Show the answer
```text include="steps/10-scale/expected/output.txt#L2"
Err(NotOnScale)
```

`fixed(0)` takes the `then` branch of its test, `grams < 1`, and fails with `NotOnScale`. `parcel_grams` passes the failure on with `if error pass`, and `attempt` in `main` keeps it as `Err(NotOnScale)`.
:::

A second one, without code: a handler `free()` for `Scale` has `op weigh(sku) = 0`. Does it check?

:::answer Show the answer
No. `weigh` promises `result >= 1`, and 0 breaks it, so the verifier refutes the operation with U5001, as in [A handler is held to the operation's contract](#a-handler-is-held-to-the-operations-contract).
:::
