# HTTP API

> Reference for the cairnflow ingress and admin HTTP API, grouped by area, with parameters and main responses.

Source: https://cairnflow.dev/docs/reference/http-api

Every capability of cairnflow is an HTTP endpoint with JSON bodies. The `cairn` CLI and the
console are thin clients of this API; anything they do, `curl` can do.

## Conventions

**Base URL.** The client port of any node, `http://<node>:8080` by default, or your environment's
endpoint on Cairnflow Cloud.

**Authentication.** Every route except `GET /health` and `GET /values/v1/{token}` needs
`Authorization: Bearer <key>`. Missing or wrong key: `401`. Role not allowed: `403`. The role
each route needs is noted below; see
[Security](/docs/self-hosting/security#roles) for what each role includes. The role
columns give the smallest tenant role that can call a route: `admin` can do what `view` and
`invoke` can, `cluster-admin` can call everything, and `GET` routes open to `invoke` are open to
`view` too.

**Tenant.** Every request acts in the tenant of its key. Invocations of another tenant answer `404`.
A `cluster-admin` key can pass `?tenant=` on tenant routes that document it.

**Errors.** Errors have a JSON body with at least `error` (a sentence for humans, do not parse it).
See [Errors](/docs/reference/errors) for `code`, `leader`, `id` and retry rules.

**Request bodies** are capped at 2 MiB; a larger body gets `413`.

**Leaders.** In a cluster, a request handled by the wrong node gets `503` with `leader`. Retry once
there, or send `x-cairn-forward: leader` and let the node forward the request.

**Invocation ids** are 48 hex characters. Treat them as opaque strings: store them and look them up
on any node later. Calls made with an `Idempotency-Key` get an id that is deterministic for that key.

## Invoking handlers

| Method and path | Purpose |
|---|---|
| `POST /invoke/{service}/{handler}` | Call and wait for the result, up to `--invoke-wait-ms` (default 5 s). |
| `POST /invoke/{service}/{handler}/send` | Fire and forget: answers `202` as soon as the invocation is durable. |
| `POST /scope/{scope}/invoke/{service}/{handler}` | Same, inside a flow-control scope. |
| `POST /scope/{scope}/invoke/{service}/{handler}/send` | Same, inside a scope. |

Role: `invoke`. The request body is the handler's input, passed through as raw bytes.

| Parameter | Where | Meaning |
|---|---|---|
| `key` | query | Object key of a virtual object, or workflow id for a workflow's `run` handler. |
| `limit-key` | query, or header `x-cairn-limit-key` | Concurrency sub-key inside a scope (`l1` or `l1/l2`). Only valid with a scope. |
| `Idempotency-Key` | header | Same key (within tenant, scope, service, handler and object key) means the same invocation. The deduplication window is the retention period. Not allowed on a workflow's `run`. |
| `cairnflow-tag` | header | A user tag `k=v`; repeat the header for several (up to 8). Immutable after creation. |
| `cairnflow-log-level` | header | Minimum level for `ctx.log` in this invocation. |

Responses carry the invocation id in the `x-cairn-invocation-id` header, and a body whose `status`
field tells the outcome:

| HTTP | `status` | Other fields | Meaning |
|---|---|---|---|
| `200` | `completed` | `id`, `output` | Finished successfully. |
| `202` | `waiting` | `id` | Not finished yet (or `/send`). Ask again later. |
| `409` | `paused` | `id`, `code`, `message` | Paused, for example after the last retry attempt (`575`). |
| `409` | `already_invoked` | `id` | A workflow `run` already holds this workflow id. |
| `429` | `throttled` | `id`, `retry_after_ms` | Accepted and durable, but over a flow-control limit; it will run later. |
| `500` | `failed` | `id`, `code`, `message` | Finished with a terminal error. |

`output` is a **string**: the handler's result bytes decoded as UTF-8. The TypeScript SDK writes
results with `JSON.stringify`, so parse `output` once more to get the value.

`waiting` is only an answer of these routes, never a stored state. `202` is normal for handlers
that sleep or wait: keep the id, then attach or poll. If the call to your service fails after the
invocation was accepted (connection refused, reset, `5xx`), `/invoke` keeps waiting through the
retries like it does for a retryable handler error.

## Workflows

| Method and path | Role | Purpose |
|---|---|---|
| `POST /workflow/{service}/{key}/attach` | `invoke` | Wait for the workflow's `run` to finish, without knowing its id. Same responses as `/invoke`; `404` if `run` was never called. Accepts `?wait_ms=`. |
| `GET /workflow/{service}/{key}/output` | `invoke` | The same without waiting: `200`, `500`, `409` or `202`, or `404` if it never ran. |
| `GET /workflow/{service}/{key}/id` | `invoke` | Compute the id of the workflow's run: `{id, tenant, service, key}`. Reads nothing. |

Each has a `/scope/{scope}/workflow/...` variant. Start a workflow that waits for people with
`/send`, then collect the result with `attach`.

## Invocations

### Reading

| Method and path | Role | Purpose |
|---|---|---|
| `GET /invocations` | `view` | Invocations of the ranges this node leads (an array). See below. |
| `GET /invocations/{id}` | `invoke` | `{id, status, output?, code?, message?, lastFailure?, createdAt, modifiedAt, endedAt?, tags?}`. |
| `POST /invocations/{id}/attach` | `invoke` | Wait until the invocation finishes. Same responses as `/invoke`. |
| `GET /invocations/{id}/journal` | `view` | Journal entries: `index`, `ty`, `name`, `payload` (hex). `?decode=1` adds a decoded `entry` and `body`. Paged with `?from=` and `?limit=` (default and max 10 000; a page also ends at 4 MiB of payload); the header `x-cairnflow-journal-next` gives the next `from`, absent on the last page. |
| `GET /invocations/{id}/logs` | `view` | Records of `ctx.log`. `?level=`, `?attempt=`, `?from=`, `?limit=` (default 1 000, max 10 000); `?follow=1` streams them as server-sent events. |
| `GET /invocations/{id}/spans` | `view` | Span tree from `ctx.trace.span`, plus `tokens: {input, output}`. |
| `GET /invocations/{id}/streams/{name}` | `invoke` (user streams), `view` (`$log`, `$trace`) | A stream as server-sent events. `?from=<offset>` or `Last-Event-ID` resumes. |
| `GET /invocations/{id}/artifacts` | `invoke` | `{artifacts: [{sha256, size, contentType}]}`. |
| `GET /invocations/{id}/artifacts/{sha}` | `invoke` | Artifact bytes, served inert (`nosniff`, sandboxing CSP, download unless image, text or JSON). |

Stored states are `running`, `suspended`, `completed`, `failed` and `paused`. `lastFailure` holds
the error of the latest failed attempt while an invocation is retrying or paused.
`GET /invocations/{id}` and journal pages carry `x-cairn-read: leader` or `follower`: a follower's
copy is durable but may be older than what the leader just returned.

**Attach.** `?wait_ms=N` long-polls up to `min(N, --attach-max-wait-ms)` (default cap 60 s);
without it the wait is `--invoke-wait-ms`. Around 25 000 ms fits under common load balancer
timeouts. `GET /invocations/{id}` never waits.

**Listing.** `GET /invocations` accepts `?status=`, `?service=`, `?handler=`, `?limit=` (per range,
default 100, max 1 000, applied after filtering), `?created_after=`, `?created_before=`,
`?ended_after=`, `?ended_before=` (Unix milliseconds, half-open) and `?order=created_desc`. Scans
are bounded: at most 10 000 rows and 2 seconds per range, and a range that does not answer within
4 seconds is left out. A truncated answer carries `x-cairn-partial: true`. Two variants:

- `?scope=cluster` asks every node and returns `{scope, nodes, invocations, partial, missing,
  missingRanges}`. `partial: true` names what could not be reached; nothing is guessed.
- `?cursor=` (empty for the first page) pages across the whole cluster, newest first:
  `{invocations, nextCursor?, partial, warnings}`. Filters: `?class=active,paused,completed,failed`,
  `?service=`, `?handler=`, `?key=`, `?root=true|false`, `?tag=k=v`, `?limit=` (default 50, max
  1 000). No `nextCursor` means the last page.

**Streams.** Events are `record` (`{offset, durable, step, attempt, k, data}`), `gap` (records
dropped), `superseded` (a retried attempt replaced earlier records), `end` (stream sealed and fully
read), `moved` (the range's leader changed: reconnect to `leader`) and `reset` (after `moved`, for
in-memory streams: discard what you showed). Only the leader serves streams. In-memory streams stay
readable 60 seconds after they are sealed, then answer `410 stream_expired`. A connection lasts at
most 10 minutes; reconnect with `Last-Event-ID`. Access is checked again every 30 seconds: a
revoked key, an ended console session or a tenant being deleted closes the stream.

### Acting

| Method and path | Role | Purpose |
|---|---|---|
| `POST /invocations/{id}/signal` | `invoke` | Body `{"signal": "name" or number, "value": <JSON>}`. Wakes `ctx.signal` waiters. Returns `{id, status}`. Sending the same signal again is a no-op. |
| `POST /invocations/{id}/cancel` | `admin` | Hard cancel: the invocation ends `failed` with code `572`. Returns `{id, cancelled, status}`. |
| `POST /invocations/{id}/cancel?mode=signal` | `invoke` | Cooperative cancel: your code gets a terminal error at its next wait and can clean up. Needs your service to be up. |
| `POST /invocations/{id}/resume` | `admin` | Take a `paused` invocation out of pause and run it now. `409` if not paused. Returns `{id, resumed, status}`. |
| `POST /invocations/{id}/purge` | `admin` | Delete journal, state and idempotency key of a **finished** invocation. `409` while it runs (including `paused`). |
| `POST /invocations/{id}/restart` | `admin` | Restart as a new invocation from the first `from` entries (default 1, the input), on `deployment` (default: its own). Returns `{id, new}`. `409` for a workflow's `run`. |
| `POST /invocations/{id}/replay` | `admin` | Read-only replay of the journal on `?deployment=` (default: its own). Commits nothing. Returns `{matches, upto, mismatchAt?, expected?, got?, message?}`. |
| `POST /invocations/{id}/migrate` | `admin` | Move an unfinished invocation to `?deployment=`. Requires a matching replay unless `&force=true`. |
| `POST /invocations/batch/{op}` | `admin` | `op` is `cancel`, `purge`, `resume` or `restart`. Body `{"ids": [...]}` with 1 to 1 000 ids. Returns `{op, results: [{id, ok, status, result or error}]}`; one failing id does not fail the batch. |

**Cancellation reaches children.** Cancelling an invocation also cancels the calls it made with
`ctx.call` that have not returned, recursively. One-way sends (`ctx.send`) are left alone. A hard
cancel does not interrupt a turn already running in your service: that turn finishes, its side
effects have happened, but its outcome is discarded.

## Value segments

| Method and path | Role | Purpose |
|---|---|---|
| `GET /values/v1/{token}` | none (the token) | The bytes of one segment of a large value. The runtime hands these URLs to your service with a turn, when the node is set up to serve them; the SDK fetches them itself. |

The token is the permission: it opens exactly one segment of one tenant and expires after a short
time (60 seconds by default). An invalid or expired token, or a tenant being deleted, gets `403`; a
missing segment `404`; more than 8 reads at once for one tenant on a node `429` with `Retry-After`.
Treat these URLs as secrets and do not log them.

## Promises and awakeables

| Method and path | Role | Purpose |
|---|---|---|
| `POST /promises/{service}/{key}/{name}/resolve` | `invoke` | Body is the value, raw bytes. Returns `{service, key, name, completed, woken?}`. |
| `POST /promises/{service}/{key}/{name}/reject` | `invoke` | Body `{"code"?: number, "message": "..."}`. Waiters get a terminal error. |
| `GET /promises/{service}/{key}/{name}` | `invoke` | `{completed, value?, failure?}`: whether the promise has a result. |
| `POST /awakeables/{id}/resolve` | `invoke` | Complete a `ctx.awakeable()` with a JSON value. Returns `{id, status}`. |
| `POST /awakeables/{id}/reject` | `invoke` | Body `{"code"?: number, "message": "..."}`. |

Promise routes have `/scope/{scope}/promises/...` variants. Resolving a promise twice is a no-op
(`completed: false`), so webhook retries are safe. Resolving before anyone waits is fine: the
promise is durable and a later waiter reads it directly.

## Schedules

| Method and path | Role | Purpose |
|---|---|---|
| `PUT /schedules/{name}` | `invoke` | Create or update a schedule. The same definition is a no-op that does not move `nextAt`. |
| `GET /schedules/{name}` | `invoke` | The schedule, `nextAt`, the next 10 fire times, recent fires, and `fired`, `missed`, `skipped` counters. |
| `DELETE /schedules/{name}` | `invoke` | Delete it. Runs already started are not touched. |
| `POST /schedules/{name}/pause` | `invoke` | No fires until resumed. |
| `POST /schedules/{name}/resume` | `invoke` | Next fire computed from now; missed fires are not replayed. |
| `POST /schedules/{name}/trigger` | `invoke` | Fire once now, ignoring `paused` and `overlap`, without moving `nextAt`. Accepts `Idempotency-Key`. |
| `GET /schedules` | `invoke` | All schedules of the tenant across the cluster: `{schedules, partial, missing, missingRanges, truncatedRanges}`. Each range is read in a bounded number of chunks; a range cut short is listed in `truncatedRanges` and sets `partial: true`. |

Each route has a `/scope/{scope}/schedules/...` variant. Names are 1 to 128 characters of
`[A-Za-z0-9._-]`, unique within tenant and scope.

```json
{
  "cron": "0 9 * * 1-5",
  "timeZone": "Europe/Paris",
  "target": { "service": "Reports", "handler": "daily" },
  "input": { "kind": "summary" },
  "overlap": "skip",
  "jitterMs": 30000
}
```

| Field | Meaning |
|---|---|
| `cron` or `everyMs` | Exactly one. `cron` has 5 fields (minute, hour, day, month, weekday), no seconds. `everyMs` is anchored on the Unix epoch and must be at least `--schedule-min-period-ms` (default 10 000). |
| `timeZone` | IANA name, default UTC. Nonexistent local times do not fire; repeated ones fire twice. |
| `target` | `{service, handler, key?}`. `key` is at most 4 096 bytes. |
| `input` | JSON input of every run, up to 64 KiB. |
| `limitKey` | Flow-control limit key of the runs. |
| `overlap` | `skip` (default for targets without a key): skip a fire while the previous run is unfinished. `allow`: always fire (the only mode for keyed targets). |
| `paused` | Create paused. |
| `jitterMs` | Spread fires by a deterministic offset below this value. At most 86 400 000 (24 hours). |

## Deployments and services

| Method and path | Role | Purpose |
|---|---|---|
| `POST /deployments` | `admin` | Body `{"uri": "https://..."}`. Discovers the service at that URL and registers a new, immutable deployment (`dp_...`), then points every service it declares at it. `?activate=false` registers without moving any service. Optional `"transport": "auto"` or `"declared"`. |
| `GET /deployments` | `view` | Deployments with `id`, `endpoint`, `createdAtMs`, `protocolMode`, `currentFor`. `?pinned=true` adds `pinnedInvocations`. |
| `GET /deployments/{id}` | `view` | One deployment, with `pinnedInvocations` (unfinished invocations still bound to it) and its `manifest`. |
| `DELETE /deployments/{id}` | `admin` | `409` while it is the current revision of a service or invocations are bound to it; `503` when not every range could be counted. |
| `PUT /services/{service}/revision` | `admin` | Body `{"deployment": "dp_...", "expect"?: "dp_..."}`. Move a service to an existing deployment (rollback, pinning). With `expect`, moves only if the current revision matches, else `409`. |
| `GET /services` | `view` | Services and handlers of the current revisions, with service type (`service`, `virtualObject`, `workflow`) and effective handler type. |
| `POST /deployments/{id}/replay-check` | `admin` | `?service=&sample=20`: replay a sample of unfinished invocations of `service` on deployment `id`. Returns `{checked, matched, failures, ranges}`. `&scope=cluster` asks every node. |

Registering the same URL again creates a new id. If the service and the runtime share no protocol
version, registration is refused right away. Removal marks the deployment first: while it is being
removed, moving a service revision to it, migrating to it or restarting on it answers `409`. Each
invocation stays bound to the deployment it started on; new invocations follow the current
revision.

## SQL queries

| Method and path | Role | Purpose |
|---|---|---|
| `POST /query` | `view` | Read-only SQL over the `sys_*` tables. |

```json
{ "sql": "SELECT id, status FROM sys_invocation WHERE service = $1", "params": ["Orders"], "allow_partial": true, "timeout_ms": 10000 }
```

Returns `{columns: [{name, type}], rows, partial, warnings, read, ms}`. A key sees its own tenant
only; `cluster-admin` sees all. Errors: `400` for invalid or forbidden SQL, `422` when a limit is
exceeded and `429` when the tenant ran out of read units (both with an `error` starting with
`query_budget:`), `429` when too many queries run at once, `503` when ranges are missing and
`allow_partial` is `false`. See
[Query](/docs/query) and [Tables](/docs/query/tables).

## Archive and usage

| Method and path | Role | Purpose |
|---|---|---|
| `GET /archive?date=yyyy-mm-dd` | `view` | Archived invocations of one UTC day: `{date, entries: [{id, run, bytes, writtenAtMs}]}`. `?limit=` up to 10 000. |
| `GET /archive/{id}` | `view` | A purged invocation: `{id, status, output?, failure?, journal, purgedAtMs, chain}`. `?date=`, or searches back `?days=` days (default and max 31). Each day searched counts against the tenant's read units; when they run out, `429`. |
| `GET /metering?hour=yyyy-mm-ddThh` | `view` | Usage of the tenant for one UTC hour, summed over nodes. |
| `GET /metering/hours?from=&to=` | `view` | Usage per hour over a range of up to 744 hours. |
| `GET /stats/handlers` | `view` | Per-handler summary over `?window=5m` to `60m`: turns, outcomes, failed attempts, p50, p99, max. `?scope=cluster` for every node. |
| `GET /stats/slow-runs` | `view` | Recent slow runs of the node, newest first. `?scope=cluster` for every node. |
| `GET /audit` | `view` | Audit log of human actions on the tenant. `?from&to&actor&action`; default 24 hours, max 31 days. |

## Flow control

`GET /rules`, `POST /rules`, `DELETE /rules/{pattern}`, `GET /limits`, `GET /vqueues` and
`GET /scheduler` (`cluster-admin`; a `provision` key can manage per-tenant rate rows through
`/rules`) are described in [Flow control](/docs/reference/flow-control).

## Keys, identity and tenant

| Method and path | Role | Purpose |
|---|---|---|
| `POST /admin/keys` | `provision` | Body `{"tenant": "...", "role": "invoke"}`. Returns `{id, tenant, role, createdAtMs, secret}`; `secret` appears only here. Roles: `invoke`, `view`, `admin`, `provision`, `cluster-admin`. |
| `GET /admin/keys` | `provision` | Stored keys, without secrets. Environment keys are not listed. |
| `DELETE /admin/keys/{id}` | `provision` | Revoke. `204` when every live node confirmed; `202 {pending}` otherwise. |
| `GET /admin/keys/{id}/revocation` | `provision` | `{revoked, confirmed, pending, listed}`. Use after a `202`. |
| `GET /auth/whoami` | any | Tenant, role, key id and node of the calling key. No secrets. |
| `GET /identity` | `view` | `{tenant, signing, keys: [{generation, kid, active}]}`: public keys for verifying signed requests in your service. |
| `GET /tenant` | `view` | State, limits and usage of the key's tenant. |

## Cluster and health

| Method and path | Role | Purpose |
|---|---|---|
| `GET /health` | none | `ok` when the HTTP server is up. |
| `GET /metrics` | `cluster-admin` or metrics token | Prometheus text. |
| `GET /cluster` | `cluster-admin` | Range table: `version`, `ranges` with `range`, `start`, `end`, `gen`, `intent?`, `leader`, `address`, `term`. Same answer on every node. |
| `GET /cluster/nodes` | `cluster-admin` | Nodes, the ranges they lead, write health, disk cache. |
| `POST /ranges/{id}/split` | `cluster-admin` | Split at `?at=<16 hex digits>` (default: middle). Must reach the range's leader. Returns the new table, a timing `report` and `opId`. |
| `POST /ranges/merge?left=&right=` | `cluster-admin` | Merge two adjacent ranges. |
| `GET /ranges/ops`, `GET /ranges/ops/{id}` | `cluster-admin` | Split and merge operations started on this node (in memory). |
| `GET /ranges/stats` | `cluster-admin` | Load per range led by this node. `?scope=cluster`, `?detail=1`. |
| `GET /ranges/suggestions` | `cluster-admin` | Automatic split proposals with the reason and what blocks them, and merge proposals (`reason: merge`, `mergeWith`, `coldSecs`) for two adjacent ranges that have been cold and small for a long time. Merges are only proposed, never done automatically. `?scope=cluster` for every node. |
| `GET /admin/cluster-version` | `provision` | Cluster version, migration lock, `knows` of every node. |

Split and merge answer `400` for a bad split key, `409` when the table changed or an operation is
already pending, and `503` for temporary conditions (retry later). A client that disconnects does
not cancel a split or merge: it runs to commit or rollback; check `GET /ranges/ops`.
