# Change stream

> Read when tools need every write as data. Listen to each landed update's record with Realm.onUpdate, and build undo and replay with write.revert and write.replay.

## Example

`Realm.onUpdate` hands a listener one record per landed update: each box,
collection, and atom the update changed, with values before and after. The
chat's activity log reads the rows of `$messages` each record holds.

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

// One record per landed update, after its watchers ran: each row of
// $messages it changed, with the row before and after.
const activity: Array<string> = [];

const stopActivity = Realm.onUpdate(app, (record) => {
  for (const change of record.collections) {
    if (change.collection !== $messages) continue;
    for (const row of change.rows) {
      const what =
        row.before === undefined ? "added" : row.after === undefined ? "removed" : "edited";
      activity.push(`${record.name ?? "update"}: ${what} ${String(row.key)}`);
    }
  }
});

// A record is net: the row is added and edited in one update, so the record
// holds one entry, from absent to the edited row.
const receiveCorrected = (message: Message, text: string) => {
  Realm.update(
    app,
    (_read, write) => {
      write.upsert($messages, message, { at: "end" });
      write.upsert($messages, { ...message, text });
    },
    { name: "receive" },
  );
};
```

The composer's undo reverts the last named edit with `write.revert`, and its
redo replays it.

```ts
import { isSorusError, Realm, type UpdateRecord } from "@frondruntime/sorus";
import { app } from "./realm.ts";
import { $composer } from "./state.ts";

// Typing is named, so the undo stack takes only typing. The records of an
// undo and a redo are named "undo" and "redo", and never join it.
const typed: Array<UpdateRecord> = [];
const undone: Array<UpdateRecord> = [];

const stopTyping = Realm.onUpdate(app, (record) => {
  if (record.name === "type") {
    typed.push(record);
    // A new edit ends what could be redone.
    undone.length = 0;
  }
});

const type = (text: string) => {
  Realm.update(app, (read, write) => write($composer, { ...read($composer), text }), {
    name: "type",
  });
};

// A record applies only to the state it left: once a send has cleared the
// composer, the last edit no longer holds, and the revert throws before it
// writes anything.
const restore = (record: UpdateRecord, direction: "revert" | "replay") => {
  try {
    Realm.update(app, (_read, write) => write[direction](record), {
      name: direction === "revert" ? "undo" : "redo",
    });
    return true;
  } catch (error) {
    if (isSorusError(error, "SorusUsageError") && error.code === "sorus/record-not-applicable") {
      typed.length = 0;
      undone.length = 0;
      return false;
    }
    throw error;
  }
};

const undoTyping = () => {
  const record = typed.pop();
  if (record === undefined || !restore(record, "revert")) return false;
  undone.push(record);
  return true;
};

// Replays the edit undone last: the composer holds its `before` again.
const redoTyping = () => {
  const record = undone.pop();
  if (record === undefined || !restore(record, "replay")) return false;
  typed.push(record);
  return true;
};
```

## Rules

- A record is net, one per outermost update: a box written three times
  is one entry, a nested update joins its outer record, and an update that
  throws or changes nothing makes none. Undo and persistence need the net change.
- A record holds confirmed values only. A visible stage makes none until
  `Stage.apply` lands it, and the record's `stages` names the stage.
- A listener runs after the update's watchers, outside any update. A listener
  that updates on every record loops; a listener's error goes to `onError`.
- `write.revert` and `write.replay` take only a record `Realm.onUpdate` handed
  out, and only while the state is as the record left it; anything else throws
  `sorus/record-not-applicable` before a write. Revert newest first, replay oldest first.
- A record names boxes and collections by identity, so it lives for one
  session; a consumer that persists maps them to paths itself. A view and a
  collection's own boxes are in no record.

## Answers

| Call | Answers |
| --- | --- |
| `Realm.onUpdate(realm, (record) => ...)` | Adds a listener and returns its stop, which does nothing the second time. Throws in a computed value, a watch's select, a stage recipe, and once the realm is disposing. |
| `UpdateRecord` | `{ name, stages, boxes, collections, atoms }`. `collections` holds each collection's `rows` (`key`, `before`, `after`) and, when it moved, `keys`. |
| `write.revert(record)` | Writes each `before` back, as a write inside `Realm.update` or a stage recipe. A throw puts back every write it made. |
| `write.replay(record)` | The same, writing each `after`. |

## See also

- [Updates](./updates.md): `Realm.update`, its `name`, and nested updates.
- [Stages](./stages.md): what a visible stage shows before it lands.
- [Collections](./collections.md): `Collection.onRowChange`, the row change.
- [Programs](../effect/programs.md): `Program.updates`, the stream of records.
- [Error messages](../reference/errors.md#change-stream): what a restore throws.
