Updates
Example
A box has one way in: update, which hands out read and write. An array
or a plain object is changed through a draft from write.modify — mutated
inside the recipe, then written back once. The samples on this page and on
Reacting share this realm and box.
import { box, createRealm } from "@frondruntime/pinna";
const realm = createRealm();
const $tags = box<ReadonlyArray<string>>(realm, []);import { update } from "@frondruntime/pinna";
const addTag = (tag: string) => {
update(realm, (_read, write) => {
write.modify($tags, (tags) => {
tags.push(tag);
});
});
};An update is atomic. An update that throws is undone: every write before the throw in the same update is taken back. Watchers run once the update ends, so after a rollback they see the old state.
import { box, update } from "@frondruntime/pinna";
const $quantity = box(realm, 1);
const $note = box(realm, "");
const take = (amount: number) => {
update(realm, (read, write) => {
write($note, `took ${amount}`);
const left = read($quantity) - amount;
if (left < 0) throw new Error("not enough in stock"); // $note is undone too
write($quantity, left);
});
};A refetch hands back new objects for items that did not change. reconcile
keeps the previous object of every item that did not change, so what derives
one item from the list returns the same value and its readers do not rerun.
import { box, reconcile, update } from "@frondruntime/pinna";
interface Rate {
readonly currency: string;
readonly rate: number;
}
const $rates = box<ReadonlyArray<Rate>>(realm, []);
const receiveRates = (next: ReadonlyArray<Rate>) => {
update(realm, (read, write) => {
// An unchanged rate keeps its previous object, so what derives one rate
// from $rates returns the same value and its readers do not rerun.
write(
$rates,
reconcile(read($rates), next, {
keyOf: (rate) => rate.currency,
equals: (previous, latest) => previous.rate === latest.rate,
}),
);
});
};An event handler wants the value as it is now, not a subscription. It reads
through untracked.
import { untracked } from "@frondruntime/pinna";
const onSave = () => {
const tags = untracked(realm, (read) => read($tags));
console.log("saving", tags);
};Rules
- Never keep a
reador awritepast its place. Neither is bound to the place that handed it out: outside every place of its realm areadthrows, outside every update awritethrows, and inside some other place a keptreadacts as that place’s own. Passreaddown as an argument instead. - Values are plain data. Change them with
writeorwrite.modify, never in place: a value is not a proxy, so a change made in place is seen by no watcher. - A box’s value is a tree: every key holds its own value. An array or object
a recipe assigns is copied on the first write through the draft, so the
caller’s object keeps its value, and an object assigned at two keys is two
values once one of them is written. Refer to one object from two places by
a key (
selectedId), a collection row, or a box, never by holding it twice: the nextwrite.modifydrafts each key apart, so a write through one key does not show at the other. - A draft the recipe wrote and left at a second key, inside itself, or
inside an object the recipe placed at two keys, throws
pinna: write.modify left an object it wrote under two keys, and the update is undone.draft.history.push(draft.present)followed bydraft.present.count++throws; a snapshot is read before the write, withread($box).present, which is the plain value. A draft at two keys that the recipe never wrote finalizes to the one object the box held. - An update is synchronous. A recipe that returns a promise throws at once and
is undone, because a write after an
awaitwould land outside the update. Await first, then open a new update. - Nested updates join the outermost one. Watchers run once, when it ends, and see only its end state.
- An update runs from an event, a watch’s effect, or an autorun’s body. It throws in a computed value, a watch’s select, or a selector, which only read.
- An effect that cannot be taken back, such as a request, a message, or a file write, runs after the update, never inside its recipe. An update that throws undoes its writes, not what the recipe did outside the realm: a request sent inside it has gone out, and a later throw, in the same update or in a caller’s update it joined, leaves the server with what the realm no longer holds. See Effects after the update.
Answers
| Call | Answers |
|---|---|
update(realm, (read, write) => ...) |
Runs the recipe atomically. If it throws, every box it wrote gets its old value back. |
write($box, value) |
Replaces the value. |
write.modify($box, (draft) => ...) |
Writes the drafted array or object back once. |
Write |
The type of write, for a function an update hands it to. Each of its calls returns undefined, so a recipe can end in one. |
reconcile(previous, next, { keyOf, equals }) |
next, with each item equals finds unchanged replaced by its previous instance; previous itself when nothing changed. A key repeated in next throws. |
untracked(realm, (read) => ...) |
What the function returns, read without subscribing. |
openStage(realm, { name?, conflicts? }) |
A new Stage over the realm, holding nothing. conflicts: "fail" makes applyStage refuse when what the stage read changed. |
openStage(stage, { name? }) |
A child stage over stage: a savepoint that applies into it. |
stageUpdate(stage, (read, write) => ...) |
Runs the recipe at once against the stage and keeps it. No box changes. A recipe that throws puts back what it wrote to the stage and is not kept. |
stageRead(stage, (read) => ...) |
What the function returns, reading through the stage: its own writes, and the realm’s current values elsewhere. |
realmRead(stage, (read) => ...) |
What the function returns, reading the realm’s values as untracked does, ignoring the stage. These reads are not recorded for the conflict check. |
applyStage(stage) |
Replays its recipes in order: over a realm, into a fresh overlay, then lands its final state in one update nested in an open one; over a stage, into that stage. A conflict or replay throw drops it; a precondition failure leaves it open. |
dropStage(stage) |
Closes the stage and its open children, and discards them. No box changes. Does nothing to a closed stage. |
stageStatus(stage) |
"open", "applied", or "dropped". |
inspectStage(stage) |
The stage’s name, realm, parent, status, and conflict mode; the names of the boxes and collections it wrote; under { conflicts: "fail" }, the names of what it read and applyStage checks; and how many recipes and open children it holds. |
Recipe |
(read, write) => undefined: what update and stageUpdate run. |
StageClosedError |
Thrown by stageUpdate, stageRead, realmRead, applyStage, or openStage of a child on a closed stage; stage is its name and status how it closed. |
StageConflictError |
Thrown by applyStage on a conflict; changed names what changed, a named box or collection by its name, and observables holds it. |
Effects after the update
A watch runs once the outermost update ends, and only for a value that
changed. An update that is undone restores every box it wrote, so a watch
that reads only boxes does not run; a write.changed on an atom is not
undone, and a watch that reads the atom runs. An effect that a watch
runs from the state it sees is never ahead of the realm. In the sample,
addPair joins two calls of addToCart in one update; when it throws,
both writes are undone and nothing is sent, and when it succeeds, one
request carries both items.
import { box, update, watch } from "@frondruntime/pinna";
// `sendCart` is the application's request to the server.
const $cart = box<ReadonlyArray<string>>(realm, []);
// The request goes out from a watch: it runs after the outermost update ends,
// and only when the cart changed, so an update that is undone sends nothing.
const stopSending = watch(
realm,
(read) => read($cart),
(cart) => {
sendCart(cart);
},
);
const addToCart = (item: string) => {
update(realm, (_read, write) => {
write.modify($cart, (cart) => {
cart.push(item);
});
// A request sent here would go out even when a caller's update throws
// later and undoes this write.
});
};
const addPair = (first: string, second: string) => {
update(realm, () => {
addToCart(first);
if (second === "") throw new Error("a pair needs two items");
addToCart(second);
});
};An effect that needs no state from the realm, such as closing a dialog,
runs in the event handler after its update returns, and a throw leaves
the handler before it. This holds only for the outermost update: code after
an update that joined an outer one runs before the outer one ends, and
the outer one can still throw.
Stages
A stage holds back the writes of asynchronous work until it succeeds:
applyStage lands them in one update, and dropStage discards them. Until
then no box changes, so nothing renders a half-done result and a failure
leaves nothing to undo. An optimistic write, one meant to show before the
work succeeds, stays a plain update that the application undoes by hand.
import { box, createRealm } from "@frondruntime/pinna";
const realm = createRealm();
const $balance = box(realm, 100);
const $status = box<"idle" | "sent">(realm, "idle");import { applyStage, dropStage, openStage, stageUpdate } from "@frondruntime/pinna";
const transfer = async (amount: number, send: (amount: number) => Promise<void>) => {
const stage = openStage(realm, { name: "transfer" });
try {
stageUpdate(stage, (read, write) => {
write($balance, read($balance) - amount);
write($status, "sent");
});
// Until applyStage, $balance and $status keep their values and nothing reruns.
await send(amount);
applyStage(stage);
} finally {
// Does nothing once applied: a failure anywhere above leaves nothing behind.
dropStage(stage);
}
};A read through the stage sees the stage’s own writes everywhere: a box, a
collection’s keys, rows, row, and read.row, and a computed value,
which the stage evaluates over its own values. A refetch stages
write.replaceAll and decides on the result before anything shows.
import {
applyStage,
collection,
computed,
dropStage,
openStage,
stageUpdate,
} from "@frondruntime/pinna";
interface Line {
readonly sku: string;
readonly price: number;
}
const $lines = collection<string, Line>(realm, { keyOf: (line) => line.sku });
const $total = computed(realm, (read) =>
read($lines.rows).reduce((total, line) => total + line.price, 0),
);
const refetch = async (load: () => Promise<ReadonlyArray<Line>>) => {
const stage = openStage(realm);
try {
const lines = await load();
stageUpdate(stage, (read, write) => {
write.replaceAll($lines, lines);
// The stage reads its own rows: $total here is the refetched total.
if (read($total) > 1000) {
write($status, "idle");
}
});
applyStage(stage);
} finally {
dropStage(stage);
}
};realmRead reads what the realm holds, to compare it with the stage.
import { realmRead, type Stage, stageRead } from "@frondruntime/pinna";
const pendingDebit = (stage: Stage): number =>
realmRead(stage, (read) => read($balance)) - stageRead(stage, (read) => read($balance));A function that hands back a change returns a Recipe, which update and
stageUpdate both run.
import { box, Model, type Recipe, update } from "@frondruntime/pinna";
class Cart extends Model {
readonly $count = box(this.realm, 0);
// A change handed back as a Recipe runs in an update or in a stage alike.
add(amount: number): Recipe {
return (read, write) => write(this.$count, read(this.$count) + amount);
}
}
const cart = new Cart(realm);
update(realm, cart.add(1));A recipe runs once when staged and once per applyStage along its path
through parent stages to the realm. Row listeners run for each change on
each run. Root replay runs in a fresh overlay over the realm’s current values under the same
recipe guard, then one update lands the final state without user code in
its recipe. Anything it creates, an id, a time, a model, is made outside it
and closed over, so all
runs land the same thing.
import { collection, type Stage, stageUpdate } from "@frondruntime/pinna";
const $orders = collection<string, { readonly id: string; readonly at: number }>(realm, {
keyOf: (order) => order.id,
});
const placeOrder = (stage: Stage) => {
// Made outside the recipe: the recipe runs again when the stage is applied,
// and a new id or time there would land a different order than the one staged.
const order = { id: crypto.randomUUID(), at: Date.now() };
stageUpdate(stage, (_read, write) => {
write.upsert($orders, order);
});
return order.id;
};A child stage, opened over a stage, is a savepoint: applied, it replays into its parent; dropped, it leaves the parent as it was.
import { applyStage, box, dropStage, openStage, stageUpdate } from "@frondruntime/pinna";
const $note = box<string | undefined>(realm, undefined);
const transferWithNote = async (amount: number, describe: () => Promise<string>) => {
const stage = openStage(realm);
try {
stageUpdate(stage, (read, write) => {
write($balance, read($balance) - amount);
});
// A child stage is a savepoint: dropped, it leaves the outer stage as it was.
const section = openStage(stage);
try {
// A note that fails to load leaves the transfer to land without one.
const note = await describe();
stageUpdate(section, (_read, write) => {
write($note, note);
});
applyStage(section);
} catch {
dropStage(section);
}
applyStage(stage);
} finally {
dropStage(stage);
}
};A stage opened with { conflicts: "fail" } refuses to land when something it
read changed in the realm since.
import {
applyStage,
box,
openStage,
type Stage,
StageConflictError,
stageUpdate,
} from "@frondruntime/pinna";
const $price = box(realm, 10);
const checkout = (stage: Stage) => {
stageUpdate(stage, (read, write) => {
write($balance, read($balance) - read($price));
});
};
const land = (stage: Stage): boolean => {
try {
applyStage(stage);
return true;
} catch (error) {
// Opened with { conflicts: "fail" }: $price changed since the stage read it.
if (error instanceof StageConflictError) {
return false;
}
throw error;
}
};
const priced = openStage(realm, { conflicts: "fail" });
checkout(priced);A host that has its own update open lands the stage inside it, and records a failed replay in the same update.
import { applyStage, box, type Stage, update } from "@frondruntime/pinna";
const $log = box<ReadonlyArray<string>>(realm, []);
const landWithLog = (stage: Stage, entry: string) => {
update(realm, (_read, write) => {
write.modify($log, (log) => {
log.push(entry);
});
// Nested in this update: watchers see the log entry and the staged writes
// once, together. A replay that throws undoes only the stage's writes.
try {
applyStage(stage);
} catch {
write.modify($log, (log) => {
log.push(`${entry} failed`);
});
}
});
};Rules
- Every call takes the stage first, as
updatetakes the realm. The realm keeps no current stage, soupdateandreadcost the same with stages in use. - A recipe is a function of its
read. It runs once when staged and once perapplyStagethrough its parents to the realm, over the destination’s values at that moment, so an id, a time, or an observable it made would differ between runs. Inside a recipe, inside astageReadfunction, and inside a computed value the stage evaluates, making a box, a computed value, a computed function, an atom, a collection, or a model throws, and so doupdatewriting the realm, areador awritekept from another place,untracked,watch,autorun,observe,onObserved,onRowChange, and every stage call. The guard covers the stage’s own realm;update(otherRealm, ...)runs on every recipe run, and its writes survivedropStage. Pinna has no development mode, so these checks run in every build. - A read through a stage sees the stage’s writes; what it did not write
reads the realm’s current value. It is not a snapshot: a box the stage
did not write can change between two reads with an
awaitbetween them. Once a stage writes a collection it holds that collection’s rows and order, so the two agree. - A computed value read through a stage runs its own function against the
stage’s
read, outside the graph: it starts noonObservedsource, and a value nothing observes reads what its boxes hold. The result is cached on the stage until the stage, a parent stage, or the realm changes. - A stage writes boxes (
write,write.modify), collections (write.upsert,write.remove,write.replaceAll), and atoms (write.changed, which reruns observers when the stage is applied). A collection write keeps a row equal to the one held, merges a refetchedSchemaModelinto the held instance, and runsonRowChangelisteners with the stage’sreadandwrite, as in an update. - A schema box or a schema collection checks a staged write at
stageUpdate, so the work learns of a refused value where it wrote it, and during eachapplyStage’s guarded replay. Landing skips the check already performed by that same box or collection. applyStagereplays over the realm’s values when it runs. By default it does not detect a conflict: a stage that added 2 to a box at 1 lands 7 when another update moved the box to 5. With{ conflicts: "fail" }it throws aStageConflictErrorinstead and lands nothing, when a box or collection the stage read, directly or through a computed value, changed since. Awrite.modifycounts as a read of its box when its base comes from the realm, asreaddoes. A box the stage wrote without reading is the last writer’s. Reading two different versions of one box or collection conflicts even if a rollback restores the first version.applyStagereplays into a fresh overlay, then lands its final box values, collection rows and order, and atom marks in one update, nested in an update already open. Row listeners run during replay, once per change; landing does not call them again. A replay throw, including a refused write, discards the overlay without changing the realm and reaches the caller; the caller’s update keeps its own writes if it catches it. Several stages in one update land in apply order. Final values equal to the realm’s values change no version and notify nobody. If an enclosing update rolls back the landing, the stage reads"dropped"; stage the work again in a new stage. An empty journal stays"applied", since it had no landing to undo.- A stage closes once,
"applied"or"dropped", andstageStatussays which. A conflict or a replay throw drops it. AnapplyStageprecondition failure, such as an open child or a call inside a recipe or computed value, leaves it open. After closing,stageStatusandinspectStageremain callable outside a recipe;dropStagedoes nothing, so afinallydrops whether or not the work applied. Every other stage call throwsStageClosedError. Areador awritekept past its recipe throws. - Watch effects and autoruns settle after landing. Their errors go to
onErrorand the stage stays"applied". - A child stage reads through its parent.
applyStagereplays it into the parent as onestageUpdate, and a throw leaves the parent as it was. A parent with an open child does not apply; dropping the parent drops its children. - Staged values are not observable. Nothing subscribes to them, and
stageReadandrealmReadthrow in a computed value, a watch’s select, or a selector, which would go stale on them.stageUpdateandapplyStagethrow there asupdatedoes. - A stage left open holds its overlay until it is collected. A test realm’s
dispose reports it as
stage "name" still running, and drops it (Testing).inspectStagereports its name, parent, status, and what it holds.
See also
- Boxes and computed: declaring what an update writes.
- Reacting: running code when a value changes.
- Schema-checked boxes: what a write checks when the box has a schema.
- Collections:
write.upsert,write.remove, andwrite.replaceAll. - Equality and hashing: what
equalsandreconcilecount as unchanged. - Live data: a WebSocket feed and a refetch, written one update per message.