---
title: "Services"
description: "Declare an API once with `service`, its operations, and what may cross the wire to a caller."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Services

A `service` declares an API: the operations another program may call, what
each takes and answers, and how it fails. It is written as a struct is,
fields and then methods, and a value of it is an ordinary value. Its
**operations** are the methods it exports with `pub`; any other method is a
helper the operations call.

A service is served over REST ([below](#serving-it-over-rest)) and over
Atoll's own RPC ([below](#calling-it-over-atoll-rpc)), and another program
calls it through the API package its server's build writes
([below](#calling-another-programs-service)). Serving it as gRPC is being
built, over the same declaration and the rules `atoll check` holds every
service to, so an API written now is one that will serve.

```atoll
error UserError { NotFound }

struct User {
    id   int
    name string
}

service Users {
    greeting string

    @get("/users/{id}")
    pub fn get(&self, id int) User ! UserError {
        if id != 1 {
            return error UserError.NotFound
        }
        return User { id: id, name: self.greet("ada") }
    }

    pub fn count(&self, ids []int) int {
        return ids.len()
    }

    private fn greet(&self, who &string) string {
        return "${self.greeting}, ${who}"
    }
}

fn main() {
    users := Users { greeting: "hello" }
    match users.get(1) {
        Ok(u) => println(u.name)
        Err(_) => println("no such user")
    }
    println("${users.count([1, 2, 3])}")
}
```

A service's fields are its own settings and handles, never sent: `greeting`
is the server's. Called in the program that declares it, an operation is a
method call like any other, which is how a test calls one.

## An operation takes `&self`

One value of a service answers every call at once, so an operation reads it
and never writes it. An operation that takes `&mut self` or `self` is
refused, and so is an exported method with no `self`, which no client could
call on the service (`ATOLL1125`):

```atoll refused=ATOLL1125
service Counter {
    n int

    pub fn bump(&mut self) int {
        self.n += 1
        return self.n
    }
}

fn main() {
}
```

What changes between calls belongs where every call can see it: in the
database, or in a task that owns it and that operations send to.

## What crosses the wire

A call's arguments travel to the service and its answer travels back, so
both are values:

- numbers, `bool`, `char` and `string`;
- structs, tuples and enums of values, error types included;
- lists, sets, maps, optionals and `Result`s of values;
- a `&T` parameter, which crosses as the `T` it borrows;
- a `Stream[T]` the operation takes or answers, which crosses as a stream.

A function, a pointer (`^T`), a borrowed answer, a handle (a task, a type
with a `Drop` of its own, a stream inside another value) and a type
parameter do not, and an operation that takes, answers or fails with one is
refused (`ATOLL1126`). The refusal names the member that holds it:

```atoll refused=ATOLL1126
struct Settings {
    name      string
    on_change fn(int) -> int
}

service Config {
    pub fn apply(&self, s Settings) int {
        return s.name.len()
    }
}

fn main() {
}
```

Here `apply` takes a `Settings`, whose field `on_change` is a function: code
and what it captures, which a caller elsewhere could not send. Send what the
value computes, or a value that names it, such as an id.

## Who called

An operation reads who called it as a context, `@context who &http.Caller`:
no request fills it and no client sends it. Each operation's dispatch makes
the `Caller` of the connection the call came on, over REST and Atoll RPC
alike, and only where something the operation calls reads it. A function
the operation calls reads it as it reads any context, with nothing passing
it:

```atoll
import http

service Notes {
    @get("/mine")
    pub fn mine(&self, @context who &http.Caller) string {
        return "${who.names().len()} names: ${owner()}"
    }
}

fn owner(@context who &http.Caller) string {
    return who.principal().name ?? "nobody"
}

fn main() {
}
```

`who.names()` are the names a certificate authority vouched for on the
caller's certificate, under a server that asks for one (`client_ca`), and
none for a caller that presented none. `who.principal()` is what a program
keeps of who did something: a `Principal`, plain data that authorizes
nothing. A `Caller` lives only as a context, so it goes where the
operation's call tree and its tasks go, and nowhere else.

## Authentication and roles

A server names how its callers prove who they are once, for every
protocol it serves, and from then on every operation needs a caller who
proved it, except one marked `@open`. Roles are the program's own: a
fieldless enum, and one function that grants them.

```atoll project=guarded file=main.at
import http

enum Role { Reader, Admin }

error Refusal {
    @http.status(403)
    NotAdmin
}

service Desk {
    @open
    @get("/health")
    pub fn health(&self) string {
        return "ok"
    }

    @get("/admin")
    pub fn admin(&self, @context who &http.Caller) string ! Refusal {
        if !who.may(Role.Admin) {
            return error NotAdmin
        }
        return "admin"
    }
}

fn roles(v &http.Verified) http.Grants {
    mut g := http.Grants.none()
    if (v.subject() ?? "") == "ops.example.com" {
        g = g.with(Role.Admin)
    }
    return g
}

fn start() Result[http.Listener, http.Error] {
    mut s := http.server("0.0.0.0:8443")
    s.tls("/etc/certs/site.pem", "/etc/certs/site.key")
    s.client_ca("/etc/certs/clients.pem", true)
    s.authenticate([http.Auth.Certificate])
    s.grant(roles)
    s.serve(Desk {}, [http.Protocol.Rest, http.Protocol.Rpc])
    return s.listen()
}

fn main() {
}
```

- **A caller who proved nothing** is refused before the operation runs:
  `401` where a scheme has a challenge to send, `403` where none does, and
  a refused call over Atoll RPC. An `@open` operation answers them and
  reads a `Caller` that is not known (`who.is_known()`) and has no roles.
- **A credential that fails is refused everywhere,** `@open` operations
  included. A bad credential is never read as none.
- **The host checks the credential** where it parsed the request, so a
  refused request never wakes the program.
- **`roles` runs once a credential**, at the first request that brings
  it, and the roles it grants are kept with it. It may read a database and
  suspend.
- **A check is one bit.** `who.may(Role.Admin)` costs an AND. A role is
  one of up to 64 variants of an enum with no payloads and no type
  parameters, and a check with a role of another enum is false.
- **Narrowing hands a callee fewer roles:** `@context who := who.only(Role.Reader)`,
  and `within(grants)` and `without(role)`. Nothing narrows a caller into
  more.

Configure authentication before `listen`: a listener keeps what its server
said when it was made.

## One shape per operation

A service has no type parameters, and neither does an operation: each is one
shape on the wire, and a caller elsewhere could not name a `T`
(`ATOLL1124`, and `ATOLL1126` for an operation's own):

```atoll refused=ATOLL1124
service Store[T] {
    pub fn size(&self) int {
        return 0
    }
}

fn main() {
}
```

Declare a service for each type it serves, or take a value that says which.

## Serving it over REST

A server serves a service with `serve`, over the protocols it lists;
`listen` registers its routes, and `run` answers each connection the listener
accepts on a task of its own. Nothing more is written: the compiler derives
what a server needs from the declaration.

```atoll project=users file=main.at
import http

error UserError {
    @http.status(404) NotFound
}

struct User {
    id   int
    name string
}

service Users {
    greeting string

    @get("/users/{id}")
    pub fn get(&self, id int) User ! UserError {
        if id != 1 {
            return error UserError.NotFound
        }
        return User { id: id, name: "${self.greeting}, ada" }
    }

    @get("/users")
    pub fn list(&self, prefix string?, limit int = 10) []User {
        mut out: []User = []
        for i in 0..limit {
            out.push(User { id: i, name: "${prefix ?? "user"} ${i}" })
        }
        return out
    }

    @post("/users/{id}/name")
    pub fn rename(&self, id int, name string) User {
        return User { id: id, name: name }
    }
}

fn main() void ! http.Error {
    mut s := http.server("127.0.0.1:8080")
    s.serve(Users { greeting: "hello" }, [http.Protocol.Rest])
    l := s.listen()?
    s.run(l)?
}
```

What each part of an operation is on the wire:

| Part | Over REST |
| --- | --- |
| A path capture, `{id}` | The parameter of its name: an `int`, a `float`, a `bool` or a `string`. |
| Any other parameter of a `GET` or a `DELETE` | The query value of its name, of those types or an option of one. Left out, an option is `None` and a parameter with a default takes it. |
| The parameters of a `POST`, a `PUT` or a `PATCH` | The JSON body: one struct parameter is the whole body, and any other set one object with a member for each. |
| The result | `200`, with the result as JSON; `void` answers `204`. |
| An error | The status its variant is marked with, `@http.status(404)`, with the error as JSON. A variant marked with none answers `500` and says nothing of itself: what an operation fails with is the server's own business unless its declaration says it is the client's. |

A request whose parameters do not read is refused with `400` and a problem
document ([RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)) whose `detail`
says which; a path no route has is `404`, and a path routed under another
method `405`. A route a request could not fill is refused where the service is
served: a capture that names no parameter, a query value that is not one of
those types, a routed method that is not `pub`, two operations at one method
and path, and an error marked with a status that is not `4xx` or `5xx`.

The dispatch is compiled, and costs what a hand-written one would: the host's
router has matched the request already, the listener finds the operation in
one look, and the operation's own function reads an integer capture with no
string made and writes the answer into a buffer the connection keeps.
`atoll build --expand-to DIR` writes what the compiler derived to `DIR`, as
Atoll.

A type that is not a `service` may be served by writing `impl http.Service`
for it: `mount` answers its routes, its operations, and the function that
answers each over each protocol.

## Calling it over Atoll RPC

Listing `http.Protocol.Rpc` beside `Rest`, as
`s.serve(Users { greeting: "hello" }, [http.Protocol.Rest, http.Protocol.Rpc])`,
serves every operation the service exports, routed or not, to other Atoll
programs.

A session is one WebSocket at `/.atoll/rpc`. The server opens it with each
operation's name, `Users.get`, in the order they are declared, and a client
calls an operation by its place in that list. Every call is a frame numbered
by the caller. Calls run side by side on the server, each on a task of its own,
and answer in the order they finish, so a slow call holds up no other; a call
cancelled by its caller cancels its task.

| Part | Over Atoll RPC |
| --- | --- |
| The parameters | One protobuf message, `UsersGetArgs`, with a field for each parameter by its name. |
| The result | `UsersGetResult`, with the result as its one field, `value`; `void` answers an empty message. |
| An error | `UsersGetError`, with the error as its one field, `failure`: every variant, marked with a status or not. |

The messages are derived as any `proto.Message` is, and their numbers are
kept in the package's `wire.schema`, which the compiler alone writes, so a service
grows the way a message does: a parameter added is the next number, and one
removed is reserved. What a release holds a service to is [below](#releases). An error variant with fields of its own is a message
nested in the error's, `TakenFields` for `Taken { name: string }`.

`http.RpcSession.open("ws://host:port")` opens a session from the client's
side; `op` finds an operation's number by its name and `call` makes the call
with its arguments' message, answering an `http.Reply`: the answer's message,
the failure's, or why it was refused.

An operation that answers a `task.Stream[T]` answers `http.Reply.Stream`:
each item's message as the caller takes it. The server sends no more items
than the caller has room for, so a slow reader slows the writer, and a
caller that closes the stream stops the operation. A client of another
program's service gets the `task.Stream[T]` itself.

An operation that takes a `task.Stream[T]` is streamed to the same way:
`RpcSession.call_with` sends the items as the operation takes them, and a
client of another program's service passes the stream as the argument. One
operation may take a stream and answer one, both at once.

## Calling another program's service

A service whose operations have no bodies is another program's, and declaring
it makes this program its client. `connect` opens a session with the program
serving it, and each operation is a call that answers what the server's does,
or fails with what it declares or with an `http.CallError`: the session could
not be opened, the server does not serve the operation, or its answer did not
read.

```atoll project=weather file=main.at
import http

struct Forecast {
    city string
    high int
}

error WeatherError {
    UnknownCity
}

service Weather {
    pub fn forecast(&self, city &string) Forecast ! WeatherError
}

fn show(url &string) void ! WeatherError | http.CallError {
    w := Weather.connect(url, http.Protocol.Rpc)?
    f := w.forecast("Oslo")?
    println("${f.city}: ${f.high}")
}
```

A client's declaration is the server's operations and the types they cross
the wire as, and nothing of the server's: no fields (a field would be the
server's setting), no decorators and no bodies (`ATOLL1127`). Its messages are named and
numbered as the server's are.

A server need not have its clients write that declaration: with `[api]
package = "api"` in its manifest, its build writes it, as a package of its own
(`example.dev/users/api`): its services' operations, the types they name, and
the protobuf numbers the server keeps for them, in its `wire.schema`. A
client depends on that package, never on the server, and its operations are
numbered as the server's because they are the server's numbers.

```toml
[dependencies]
"example.dev/users/api" = { path = "../users/api" }
```

## Releases

A service's operations are kept in its block of `wire.schema`, an
operation a line, by its name and, where a route decorator routes it, its
route:

```text
service Users
  get  GET /users/{id}
  rename
```

Moving the manifest's `version` on releases what the package keeps, and a
client of a release calls an operation by its name over Atoll RPC and by its
route over REST, and reads what it answers. So within a major, `atoll check`
refuses, at the service:

- an operation the release served, gone, or answering at another route;
- a field the release answered with, gone: a field of a struct a released
  operation's result or error holds, at any depth, unless the field it
  became says `@proto.was("old")`.

An operation added is free, and so is a field removed from what only
requests carry, since the server ignores what it no longer reads. The next
major (`1.0.0` after `0.4.2`, `2.0.0` after `1.7.0`) frees them all.

A parameter added to a released operation reaches a client of that release
as nothing: over REST an omitted parameter takes its default, and over Atoll
RPC an unsent parameter reads as `None` when it is optional and as the zero
of its type when it is not, its default or not. So within a major, a
parameter added to a released operation is optional (`verbose bool?`), and
`atoll check` refuses any other at the parameter; so is a field added to a
struct a released operation takes, which a client of the release sends
without it.

## Routes and the reviewed surface

An operation that is also a REST route says so with the route decorators a
handler takes: `@get`, `@post`, `@put`, `@patch` and `@delete`, with
`{name}` captures that fill the parameters of their names. `atoll routes`
lists them.

A `pub service` is part of its package's surface, operations and routes
included, so `atoll api` prints it, and its block of `wire.schema` holds a
release to them ([Releases](#releases)): an operation added, removed or
moved shows up in the change that made it, as a line the compiler wrote.

Source: https://docs.atoll.workreef.dev/language/services/index.mdx
