# Services and handlers

> Declare services, virtual objects and workflows, choose handler types, and serve them with serve().

Source: https://cairnflow.dev/docs/develop/services

A **service** is a named set of handlers. Cairnflow discovers the services your endpoint exposes,
and calls each handler over HTTP when an invocation needs to run or resume.

```ts title="service.ts"

const orders = service(
  "OrderService",
  {
    async submit(ctx: Context, input: { amount: number }) {
      if (typeof input?.amount !== "number" || input.amount <= 0) {
        throw new TerminalError("amount must be a positive number", 400);
      }
      const soFar = (await ctx.get<number>("total")) ?? 0;
      const receipt = await ctx.run("charge", () => chargeCard(input.amount));
      ctx.set("total", soFar + input.amount);
      return { receipt, total: soFar + input.amount };
    },
    async total(ctx: Context) {
      return (await ctx.get<number>("total")) ?? 0;
    },
  },
  { type: "VIRTUAL_OBJECT", handlerTypes: { submit: "EXCLUSIVE", total: "SHARED" } },
);

await serve({ services: [orders], port: 9080, hostname: "0.0.0.0" });
```

## Three kinds of service

| Declared with | Kind | Context type | State and durable promises |
|---|---|---|---|
| `service(name, handlers)` | Service | `ServiceContext` | No |
| `service(name, handlers, { type: "VIRTUAL_OBJECT" })` | Virtual object | `Context` | Yes, per key |
| `workflow(name, { run, ... })` | Workflow | `Context` | Yes, per workflow ID |

A plain service has no key, so there is no object for state to belong to. Its handlers receive a
`ServiceContext`: the same as `Context` without `get`, `set`, `clear`, `clearAll`, `getKeys` and
`promise`. Calling them is a compile error, and the runtime also rejects them with a terminal error
(code `574`). If you need state, declare a virtual object and call it with a key — see
[Virtual objects and state](/docs/develop/state).

Workflows are covered in [Workflows](/docs/workflows/workflows).

## Handler types

| Type | Where | Behaviour |
|---|---|---|
| `EXCLUSIVE` | Virtual objects (default) | One exclusive handler per key runs at a time; others queue behind it |
| `SHARED` | Virtual objects, workflows (default for every handler except `run`) | Runs alongside other invocations on the same key |
| `WORKFLOW` | Workflows | Set by `workflow()` on `run`; you do not set it yourself |

Set types per handler with `handlerTypes`. A handler you do not list is `EXCLUSIVE` in a virtual
object and `SHARED` in a workflow.

Shared handlers cannot write state. Type them with `SharedContext` (a `Context` without `set`,
`clear` and `clearAll`) so the compiler catches a write; `handlerTypes` does not change the type of
`ctx` for you. The runtime enforces the rule too, in virtual objects and workflows alike: a write
from a shared handler fails the invocation with a terminal `571` protocol violation.

## Handler signature

```ts
type Handler<I, O> = (ctx: Context, input: I) => Promise<O> | O;
```

- **Input** is the request body parsed as JSON. If the body is not valid JSON, the handler receives
  it as a string. The `I` type is your declaration only: nothing checks the shape at runtime, so
  validate it and throw `TerminalError` (for example with code `400`) when it is wrong — retrying a
  bad payload never fixes it.
- **Output** is whatever you return, serialized with `JSON.stringify` (`undefined` becomes `null`).
- `ctx.key` is the object key (or workflow ID); it is empty in a plain service.
  `ctx.invocationId` is the invocation's ID, the same one the HTTP API uses.

## Handler options

Options are part of the deployment's contract. Set them for the whole service with `options`, or
per handler with `handlerOptions` (a handler's options override the service's):

```ts
service("Agent", { think, quick }, {
  type: "VIRTUAL_OBJECT",
  options: {
    inactivityTimeout: 10 * 60_000,
    retryPolicy: { maxAttempts: 5, onMaxAttempts: "PAUSE", initialInterval: 200 },
  },
  handlerOptions: { quick: { inactivityTimeout: 5_000 } },
});
```

| Option | Meaning |
|---|---|
| `inactivityTimeout` | How long (ms) the runtime waits on your endpoint while it is silent within one turn — in practice, the longest `ctx.run` closure on `REQUEST_RESPONSE`. Greater than 0, at most one hour. When neither the handler nor the service sets it, the SDK declares 15 minutes |
| `retryPolicy` | Backoff and attempt limit — see [Errors and retries](/docs/develop/errors-retries) |
| `journalRetention` | How long (ms) to keep the journal of a finished invocation |
| `logLevel` | Minimum level kept by `ctx.log` (default `info`) — see [Streams, logs and traces](/docs/develop/streams-logs) |
| `trace` | `"runtime"` adds runtime spans (one per turn and per `ctx.run`); default `"off"` |
| `logFlushMs` | Flush durable log and stream records on this period (ms) even in the middle of a long `ctx.run`. Each flush is one extra write. `serve()` only |

The values are captured when you register a deployment. Changing them means registering a new
deployment.

## serve() options

`serve()` runs a Node.js HTTP server for your services. It answers both HTTP/1.1 and cleartext
HTTP/2 on one port.

| Option | Default | Meaning |
|---|---|---|
| `services` | — | The service definitions to expose |
| `port` | `9080` | Port to listen on |
| `hostname` | `"127.0.0.1"` | Address to bind. Set `"0.0.0.0"` in a container, or nothing outside the machine can reach it |
| `identityKeys` | none | Identity keys (`publickeyv1_...`) of your environment. When set, every request must carry a valid signature from one of them, or it is refused with `401`. Required by Cairnflow Cloud |
| `identityHosts` | none | The public hosts you registered. The signature covers the request body and the host it was sent to; when this is set, the signed host must be one of these. When unset, it is compared with the request's own `Host` header. Set it when a proxy in front of your service rewrites `Host` |
| `protocolMode` | `"BIDI_STREAM"` | Streaming over HTTP/2. Set `"REQUEST_RESPONSE"` if a proxy between cairnflow and your service only speaks HTTP/1.1 |
| `compression` | `true` | Accept gzip-compressed request bodies and compress responses when asked |
| `replayCache` | `true` | Keep the journal of running invocations in memory so cairnflow only sends new entries each turn. `{ maxBytes, ttlMs }` tunes it (defaults 64 MiB, 15 minutes) |
| `valueCacheBytes` | 64 MiB | Memory for segments of large values ([Payload](/docs/cloud/limits#payload)) the SDK has already downloaded. `0` keeps none |
| `maxValueBytes` | 64 MiB | Largest single value the SDK assembles from segments. A larger one fails the turn before anything is downloaded |
| `maxTurnValueBytes` | 256 MiB | Most bytes of segmented values one turn may assemble |
| `segmentOrigins` | any `http(s)` origin | Origins the SDK may download segments from. Leaving it unset is safe only with `identityKeys`, which signs the download URLs |

Each request body is capped at 256 MiB after decompression; a larger one gets `413`. If cairnflow
speaks a newer protocol version than this SDK build supports (for example after you rolled the
service back to an older SDK without registering it again), the endpoint answers `415` and the turn
is retried; register the deployment again.
`serve()` resolves to `{ port, url, close() }`. `close()` stops accepting connections and lets open
invocation streams finish.

To rotate identity keys, add the new key to `identityKeys` before it becomes active, and remove the
old one after.

:::note
On platforms that only accept a `(Request) => Promise<Response>` function — Vercel, Cloudflare
Workers, AWS Lambda — use `fetchHandler` instead of `serve()`. See
[Serverless](/docs/workflows/serverless).
:::

## Registering

Cairnflow reads your services from the endpoint's discovery route. Deploy the service, then
register its base URL:

```sh
curl -X POST $CAIRN_URL/deployments \
  -H "authorization: Bearer $CAIRN_KEY" \
  -H "content-type: application/json" \
  -d '{"uri":"https://your-service.example.com"}'
```

Each registration creates a new, immutable deployment and makes it the current revision of every
service in it. Invocations already running stay on the deployment they started on — see
[Deploying new versions](/docs/develop/versioning). `GET /services` lists the handlers you can call
and their effective types.

## Rules of handler code

The handler body runs again every time an invocation is replayed. Put side effects in
[durable steps](/docs/develop/durable-steps), do not read the clock or `Math.random()` outside one,
and do not catch and swallow errors around `ctx` commands. See [Concepts](/docs/concepts).
