# Stages

> Read when asynchronous work writes only if it succeeds, or shows its writes before the server answers. Hold the writes in a stage, land them in one update or discard them, refuse a landing when what it read changed, and show an optimistic write that a failure takes off.

## Example

A stage holds the writes of asynchronous work until it succeeds: `Stage.apply` lands them in one update, `Stage.drop` discards them. Until then no box changes, so nothing renders a half-done result and a failure leaves nothing to undo.

```ts
import { Stage } from "@frondruntime/sorus";
import { $messages, type Message } from "./messages.ts";
import { app } from "./realm.ts";
import { $composer } from "./state.ts";

// The message lands once the server takes it; until then no box changes and
// nothing reruns, so the composer still shows the text. A post that fails
// leaves the composer and the messages as they were.
const sendStaged = async (message: Message, post: Post) => {
  const stage = Stage.make(app, { name: "send" });
  try {
    Stage.update(stage, (read, write) => {
      write.upsert($messages, message, { at: "end" });
      // The recipe runs again at apply: text typed while the server took the
      // message is kept, and only the text that was sent is cleared.
      if (read($composer).text === message.text) write($composer, { text: "", replyTo: null });
    });
    await post(message);
    Stage.apply(stage);
  } finally {
    // Does nothing once applied: a throw anywhere above leaves nothing behind.
    Stage.drop(stage);
  }
};
```

A stage made with `{ visible: true }` shows its writes over the realm's confirmed values at once, until it applies or drops. An optimistic write is a visible stage, and a failure takes it off.

```ts
import { Collection, Stage } from "@frondruntime/sorus";
import { $messages, type Message } from "./messages.ts";
import { app } from "./realm.ts";

// The ids of the messages the server has not taken yet.
const $sending = Collection.make(app, { keyOf: (id: string) => id, name: "sending" });

// The message shows at once, marked as sending, over the realm's confirmed
// values; the guess is the answer, so the stage applies on success.
const sendShown = async (message: Message, post: Post) => {
  const guess = Stage.make(app, { name: "send (guess)", visible: true });
  try {
    Stage.update(guess, (_read, write) => {
      write.upsert($messages, message, { at: "end" });
      // Marks the message as sending for exactly as long as the guess shows.
      write.upsert($sending, message.id);
    });
    await post(message);
    Stage.update(guess, (_read, write) => {
      write.remove($sending, message.id);
    });
    Stage.apply(guess);
  } finally {
    // A failed post takes the message off the screen.
    Stage.drop(guess);
  }
};
```

## Rules

- Make an id, a time, or a model outside a recipe and close over it. A recipe runs at `Stage.update` and again at each `Stage.apply`, so a value made inside it lands differently than the one staged.
- A recipe creates no observable and calls no stage call, `Realm.watch`, or `Realm.autorun`; each throws in every build. `Realm.update(otherRealm, ...)` is not guarded, runs on every replay, and its writes survive `Stage.drop`.
- `{ conflicts: "fail" }` makes `Stage.apply` throw `StageConflictError` and drop the stage when a box or collection it read or wrote changed. By default it lands: adding 2 at 1 gives 7 after another update set 5.
- A stage closes once, `"applied"` or `"dropped"`; `Stage.drop` after that does nothing, so a `finally` drops whether or not the work applied. Any other call on a closed stage throws `StageClosedError`.
- A stage left open holds its overlay until applied, dropped, or its realm is disposed. A test realm's dispose reports it ([Testing](../guides/testing.md)).
- A `Realm.update` recipe reads and writes confirmed values, not a guess: adding 1 to a shown 11 leaves 12 after the guess drops. Change a guessed value in a stage above it; Sorus does not check this.
- When the server's answer wins over the guess, hold the answer in a hidden stage and apply it and drop the guess in one `Realm.update`, so a watcher runs once with the settled value.

## Answers

| Call | Answers |
| --- | --- |
| `Stage.make(realm, { name?, conflicts?, visible? })` | A `Stage` over the realm, holding nothing. `conflicts: "fail"` makes `Stage.apply` refuse on a change. `visible: true` shows its writes until it applies or drops. |
| `Stage.make(stage, { name? })` | A child stage: a savepoint that applies into its parent. A parent with an open child does not apply; dropping the parent drops the child. |
| `Stage.update(stage, (read, write) => ...)` | Runs the recipe at once and keeps it. No box changes; over a visible stage, readers rerun on what is shown. A recipe that throws is not kept. |
| `Stage.read(stage, (read) => ...)` | The function's result, reading the stage's writes, then the realm's current values. |
| `Stage.realmRead(stage, (read) => ...)` | The function's result, reading the realm's confirmed values, ignoring every stage. |
| `Stage.apply(stage)` | Replays the recipes, then lands the final state in one update, nested in an open one. A conflict or a replay throw drops the stage and reaches the caller. |
| `Stage.drop(stage)` | Closes the stage and its open children, discarding their writes. |
| `Stage.status(stage)` | `"open"`, `"applied"`, or `"dropped"`. |
| `Stage.inspect(stage)` | Name, parent, status, conflict mode, what the stage wrote and read, `showing`, and `failure`. A visible stage that `Stage.apply` would refuse stops showing and keeps its error in `failure`. |
| `StageClosedError` | Thrown by a call on a closed stage; carries `stage` and `status`. |
| `StageConflictError` | Thrown by `Stage.apply` on a conflict; carries `stage` and `changed`, the names of what changed. |

## With Effect

`Stage.scoped` applies a stage when an Effect section succeeds and drops it when the section fails, dies, or is interrupted; a conflict fails with `StageConflictError`. See [Programs](../effect/programs.md).

## See also

- [Updates](./updates.md): `Realm.update`, which a stage lands in.
- [Programs](../effect/programs.md): `Stage.scoped`.
- [Testing](../guides/testing.md): a stage left open in a test realm.
