# Virtual objects and state

> Keyed objects with durable state and one writer at a time.

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

A **virtual object** is a service whose invocations are addressed by a **key** — a chat ID, a user
ID, an order number. Each key has its own state, and two exclusive handlers on the same key never
run at the same time. You never create an object: calling a handler with a new key is enough.

```ts title="counter.ts"

const counter = service(
  "Counter",
  {
    async add(ctx: Context, n: number) {
      const total = ((await ctx.get<number>("total")) ?? 0) + n;
      ctx.set("total", total);
      return total;
    },
    async reset(ctx: Context) {
      ctx.clearAll();
    },
    async read(ctx: SharedContext) {
      return (await ctx.get<number>("total")) ?? 0;
    },
  },
  { type: "VIRTUAL_OBJECT", handlerTypes: { read: "SHARED" } },
);

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

Call it with a key:

```sh
curl -X POST "$CAIRN_URL/invoke/Counter/add?key=user-42" \
  -H "authorization: Bearer $CAIRN_KEY" \
  -H "content-type: application/json" -d '5'
```

`ctx.key` inside the handler is `"user-42"`.

## State API

| Call | Returns | Notes |
|---|---|---|
| `ctx.get<T>(name)` | `T \| null` (awaitable) | `null` means the entry does not exist |
| `ctx.set<T>(name, value)` | `void` | Does not wait. The value is stored as JSON |
| `ctx.clear(name)` | `void` | Removes one entry |
| `ctx.clearAll()` | `void` | Removes every entry of this object |
| `ctx.getKeys()` | `string[]` (awaitable) | Names of the object's state entries |

State reads are recorded in the journal like every other command, so a replay sees the value that
was read the first time, not whatever the state holds now.

:::caution
`null` from `ctx.get` means **missing**, which is different from an empty value. Setting a key to
`""` or `0` and reading it back gives you `""` or `0`, not `null` — keep the `?? default` pattern
for "not set yet" only.
:::

Values go through `JSON.stringify`: store plain data, not class instances, `Map`, `Set` or `Date`
objects. A large value, such as a long chat history, is stored as segments outside the journal,
and your code still reads and writes the whole value; see [Payload](/docs/cloud/limits#payload)
for the limits on Cairnflow Cloud. Do not store an [artifact](/docs/develop/artifacts) reference
in state to read in a later invocation: `ctx.artifact.get` reads only the artifacts of the
current invocation.

## One writer per key

Exclusive handlers on one key form a queue. While an invocation holds the key — including while it
sleeps, waits for a call, or waits for a promise — the next exclusive invocation on that key waits
behind it. That is what makes a read-modify-write like `add` above safe without locks or
transactions.

Two consequences:

- **A long wait blocks the key.** An exclusive handler that sleeps for a day holds the key for a
  day. If other work on the same key must keep flowing, move the waiting part into a separate
  invocation (a workflow, or a call to another object) and keep the exclusive handler short.
- **Calling `/invoke` on a busy key can return `202 waiting`.** The invocation is accepted and
  durable; it runs when the key frees up. Fetch the result later with
  `POST /invocations/{id}/attach`, or use the [typed client](/docs/develop/client), which does that
  for you.

## Shared handlers

A `SHARED` handler runs without waiting in the key's queue, so it can answer while an exclusive
handler is suspended. Use it for reads: status pages, progress, "what is in the cart".

Shared handlers only read state. They run alongside the exclusive ones, and a read-modify-write
from both sides would lose updates, so the runtime rejects `set`, `clear` and `clearAll` from a
shared handler with a terminal `571` protocol violation. Type shared handlers with `SharedContext`,
which has no `set`, `clear` or `clearAll`, to catch the mistake at compile time. Move writes to an
exclusive handler.

## Keys and scopes

- A key can be any string your callers agree on. Keep it stable: a different key is a different
  object with empty state.
- A call made inside a [scope](/docs/develop/calls#scopes) addresses a different object from the
  same call without a scope: `Cart/a` in scope `bob` and `Cart/a` with no scope have separate state
  and separate queues.

## Durable promises live here too

Virtual objects and workflows can also use `ctx.promise(name)`: a named, durable value that another
handler or an outside system completes. See
[Durable promises, signals and awakeables](/docs/develop/promises-signals).
