{saving ? "Saving…" : "Saved"}
; }); const NameList = memo(function NameList({ names }: { readonly names: ReadonlyArray(realm, { symbol: "ACME", price: 10, receivedAt: 0 }); // What the card shows. Each recompute builds a new object, so `equals` // compares the shown fields: a tick that changes only `receivedAt` keeps the // previous object, and the card does not rerender. const $quoteCard = computed( realm, (read) => { const quote = read($quote); return { symbol: quote.symbol, price: quote.price.toFixed(2) }; }, { equals: (previous, next) => previous.symbol === next.symbol && previous.price === next.price }, ); const QuoteCard = memo(function QuoteCard() { const card = useValue($quoteCard); return ({card.symbol} {card.price}
); }); ``` ## With Effect A model from `pinna-effect` is read the same way, with the same hooks. A list reads a collection's `keys`, and each row reads its own `row(key)`. Toggling one todo rerenders one `TodoLabel`. The `TodoList` is the one from [Collection fields](../effect/collections.md). ```tsx import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; import type { Todo, TodoList } from "./models.ts"; // Rerenders when a key is added, removed, or moved; never for a row's own change. function TodoRows({ list }: { readonly list: TodoList }) { const ids = useValue(list.$items.keys); return ({ids.map((id) => (
); } // Rerenders when the row under its key is replaced. const TodoRow = memo(function TodoRow({ list, id, }: { readonly list: TodoList; readonly id: string; }) { const todo = useValue(list.$items.row(id)); return todo === undefined ? null :))} ; }); // Rerenders when its own label changes. const TodoLabel = memo(function TodoLabel({ todo }: { readonly todo: Todo }) { const label = useValue(todo.$label); return ( ); }); ``` ## See also - [Start](../start/index.md): a counter from box to button. - [Classes](../effect/classes.md): the models these components read. - [Collections](../state/collections.md): `keys` and `row(key)`, and a list that rerenders one row. - [Testing](../guides/testing.md): a realm per test, for the models a component reads. --- # Schema-checked boxes URL: https://pinna.frondruntime.dev/docs/effect/boxes Description: Read when an app already uses Effect. Import the core's calls from pinna-effect, make a box that checks an Effect Schema on every write, and know what a schema adds to a write. The Effect pages are for applications that already use Effect. `@frondruntime/pinna-effect` has the same calls as `@frondruntime/pinna`, on Effect Schema, and `effect` is its peer dependency. It adds what the core lacks: boxes that check a schema on every write, models as [classes](./classes.md) decoded from the wire, with boxes and [collections](./collections.md) as fields, and [programs](./programs.md) that run with a scope. An application without Effect needs none of it: start at [Start](../start/index.md). ## Example `schemaBox` takes a schema before the initial value. The other calls, and the hooks of `@frondruntime/pinna-react`, are the core's. ```ts import { createRealm, schemaBox } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); const $price = schemaBox(realm, Schema.Number, 10, { name: "price" }); const $tags = schemaBox(realm, Schema.Array(Schema.String), [], { name: "tags" }); ``` A write equal to the current value notifies nobody. A box compares with its schema's equivalence, so an equal array or object counts as unchanged. ```ts import { update } from "@frondruntime/pinna-effect"; const tagSale = () => { update(realm, (_read, write) => { // A new array each time, equal under the schema after the first: // the second call notifies nobody. write($tags, ["sale"]); }); }; ``` A write the schema rejects throws from the update, and every write before it in the same update is undone. ```ts import { schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const $quantity = schemaBox(realm, Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), 1); const $note = schemaBox(realm, Schema.String, ""); const take = (amount: number) => { update(realm, (read, write) => { write($note, `took ${amount}`); write($quantity, read($quantity) - amount); // throws below zero, and $note is undone too }); }; ``` `write.modify` drafts an array or a plain object, then writes it back once, checked against the schema. ```ts import { update } from "@frondruntime/pinna-effect"; const addTag = (tag: string) => { update(realm, (_read, write) => { // The drafted array is checked against the schema once, when the recipe ends. write.modify($tags, (tags) => { tags.push(tag); }); }); }; ``` ## Rules - `pinna-effect` re-exports every name of `pinna` as it is. Its `box` and `collection` check nothing and compare with `Object.is` unless given `{ equals }`, and its `reconcile` checks nothing and takes the `equals` it is given. The names it adds say they use a schema: `schemaBox`, `SchemaModel` with `BoxField` and `CollectionField`, and `reconcileSchema`. An application imports from one package. - `box` given a schema throws and names `schemaBox`, so a box meant to check a schema never silently checks nothing. - A box of a plain `Schema.Array(element)` checks only the elements a write put there: a push onto 10,000 rows checks one. Any other box checks its whole value on every write. A list written one row at a time is a [collection field](./collections.md). - A `schemaBox` compares with its schema's equivalence unless `{ equals }` says otherwise. What each schema counts as equal is on [Equality and hashing](./equality.md). - `schemaBox` throws when `initial` does not fit the schema. - A value the schema accepts is plain data, `readonly` in the types. A value changed in place is checked by no schema. ## Answers | Call | Answers | | --- | --- | | `schemaBox(realm, schema, initial, { name?, equals? })` | A box of the values `schema` accepts. Throws when `initial` does not fit. | | `write($box, value)` | Replaces the value, checked against the schema. | | `write.modify($box, (draft) => ...)` | Writes the drafted array or object back once, checked. | ## Checks and rules A check runs when a value is written, on that value alone, and never again (a write of the value the box holds runs none): a read, a recompute, or a change elsewhere does not run it. So a check holds only what the value itself decides. - Terms that must agree, such as the two dates of a stay, are one schema value with one check. A `BoxField`'s check sees its own value and no sibling field, and a check on the `SchemaModel` as a whole runs when an instance is made, decoded, or written to a schema box, never when a box of the instance changes. A filter made with `Schema.makeFilter` that returns a string fails with that string as its message: see [Errors](../guides/errors.md#fields-a-schema-refuses). ```ts import { BoxField, decode, SchemaModel } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; // Both dates are one value, so one check sees them together. const Stay = Schema.Struct({ checkIn: Schema.String, checkOut: Schema.String }).check( Schema.makeFilter((stay) => stay.checkIn < stay.checkOut || "Check out after checking in"), ); class Booking extends SchemaModel ("Booking")({ id: Schema.String, // As two fields, $checkIn and $checkOut, each check would see its own // date alone, and a write to one would never see the other. $stay: BoxField(Stay), }) {} const booking = decode( realm, Booking, )({ id: "b1", stay: { checkIn: "2026-05-01", checkOut: "2026-05-03" }, }); ``` - A rule that depends on time, such as a date that must be after today, or on another box's value, is no check of the box: the value it judged would stay in the box after today moves past it. It is checked where the input is accepted, in the update that writes it, and what it allows from then on is a computed value that follows both. ```ts import { box, computed, update } from "@frondruntime/pinna-effect"; // Today changes with no write to the stay, so no check on the stay sees it. const $today = box(realm, "2026-04-20"); // Checked once, as the input arrives. const changeStay = (stay: typeof Stay.Type) => { update(realm, (read, write) => { if (stay.checkIn <= read($today)) { throw new Error("Check in after today"); } write(booking.$stay, stay); }); }; // Whether the stay can still change is derived, so it follows today. const $changeable = computed(realm, (read) => read($today) < read(booking.$stay).checkIn); ``` ## See also - [Boxes and computed](../state/boxes.md): the core's box, with no schema. - [Updates](../state/updates.md): what an update undoes when it throws. - [Classes](./classes.md): boxes as fields of a model decoded from the wire. - [Errors and debugging](../guides/errors.md#with-effect): the errors a schema adds, and the path and message of each field it refuses. - [Equality and hashing](./equality.md): what each schema counts as the same value, and a class's own `Equal`. --- # Classes URL: https://pinna.frondruntime.dev/docs/effect/classes Description: Read when modeling domain data. Declare a SchemaModel with box fields, derive values on it, write from its methods, decode it from the wire, and hand it the caller's own values, in a decode or an Effect program. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). ## Example A model is a `SchemaModel`: a `Schema.Class` whose instances hold a realm that its wire form never carries. A field whose name starts with `$` is a `BoxField`, or a `CollectionField` of rows by key ([Collection fields](./collections.md)), and its wire key drops the `$`. A field without `$` is plain, `readonly` data. The class keeps `check` and `annotate`, and seals `extend`, `mapFields`, `makeOption`, and `makeEffect`. ```ts import { BoxField, computed, createRealm, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); class Todo extends SchemaModel ("Todo")({ id: Schema.String, title: Schema.String, $done: BoxField(Schema.Boolean), // a box field; the wire key is "done" }) { readonly $label = computed(this.realm, (read) => read(this.$done) ? `✓ ${this.title}` : this.title, ); toggle(): void { update(this.realm, (read, write) => { write(this.$done, !read(this.$done)); }); } } ``` - A derived value is a `$` property of the class body, made with `computed(this.realm, ...)`. It is not a schema field, so it is not on the wire. - A method that writes calls `update(this.realm, ...)`. `decode(realm, Todo)` makes instances from wire data. Every instance and every box inside it belongs to the realm `decode` is given, the one made above the class. ```ts import { decode, untracked } from "@frondruntime/pinna-effect"; // Throws the SchemaError when the input does not fit. const todo = decode(realm, Todo)({ id: "1", title: "Write the docs", done: false }); todo.toggle(); const label = untracked(realm, (read) => read(todo.$label)); // "✓ Write the docs" ``` A `FromContext` field holds a value of the caller's own, such as a formatter or a client: the service of an Effect `Context.Service` tag. `decode` takes it from the `Context` it is given; it is never on the wire. ```ts import { BoxField, computed, decode, FromContext, SchemaModel } from "@frondruntime/pinna-effect"; import { Context, Schema } from "effect"; interface MoneyFormat { readonly format: (amount: number) => string; } // An Effect service: the field requires it, and the caller provides it. class Money extends Context.Service ()("app/Money") {} class Price extends SchemaModel ("Price")({ $amount: BoxField(Schema.Number), money: FromContext(Money), // the caller's own value, never on the wire }) { readonly $label = computed(this.realm, (read) => this.money.format(read(this.$amount))); } const euros: MoneyFormat = { format: (amount) => `€${amount.toFixed(2)}` }; const price = decode(realm, Price, Context.make(Money, euros))({ amount: 12 }); ``` An Effect program decodes the same class with `Schema.decodeUnknownEffect`. The tag is one of its requirements, provided as any service is, with `Effect.provideService` or a `Layer`. The realm comes from `RealmService`, as for every Effect program. ```ts import { RealmService } from "@frondruntime/pinna-effect"; import { Effect, Schema } from "effect"; // Money is a requirement like any service: Effect . const loadPrice = (json: unknown) => Schema.decodeUnknownEffect(Price)(json); const loaded = Effect.runSync( loadPrice({ amount: 12 }).pipe( Effect.provideService(Money, euros), Effect.provideService(RealmService, realm), ), ); ``` ## Rules - Make instances with `decode(realm, Todo)(json)`. Every instance has a `realm` field, never on the wire: `decode` fills it, and field initializers use `this.realm`. - `Todo.make({ id, title, done: false, realm })` builds an instance from values already in hand. It takes each `$` field's starting value under its wire key, and builds the box in the instance's realm. A box under the `$` key throws `pinna: Todo.make takes the value of $done under "done", never a box under "$done"`, so a spread instance never shares its box with the new one. - `make` checks each `$` field's value even under `{ disableChecks: true }`, which skips only the plain fields' checks: the box checks every value it holds, its first included. - A model in another schema's `make` is an instance. A plain object in its place throws `pinna: a Todo field of another schema takes an instance; build it with Todo.make or decode`, because its boxes would be another instance's, or none. - A field list that breaks a naming rule makes `SchemaModel` throw when the class is defined, so no instance is ever half-declared: - two fields with one wire key, such as `$count` and `count`: `pinna: Counter.$count and Counter.count both read "count"; rename one`; - a field whose wire key is `realm`: `pinna: Counter.realm reads "realm", the realm the instance belongs to; rename the field`; - a `$` field that is not a `BoxField` or a `CollectionField`: `pinna: Counter.$count is named as a box; declare it BoxField(...) or CollectionField(...)`; - a `BoxField` or a `CollectionField` without `$`: `pinna: Counter.count holds a box; name it $count`. - `BoxField` and `CollectionField` are fields of a `SchemaModel` only. In any other schema they fail to decode and encode with `pinna: BoxField is a SchemaModel field; declare it in SchemaModel(...), never in another schema` (or `CollectionField`), because the `$` key would go on the wire. - `extend`, `mapFields`, `makeOption`, and `makeEffect` throw and do not compile on a `SchemaModel`: the first two would declare fields without its checks, and the last two would take boxes where `make` takes values. The call throws `pinna: Todo.extend is not supported; declare another SchemaModel with every field it needs`, and the same for `mapFields`; `makeOption` and `makeEffect` throw `pinna: Todo.makeOption is not supported; call make, which throws the schema error, or decode`. - A plain getter has no `read` to call, and a method that takes `read` is not cached. A value several components need is a computed field. - A context field's tag is a requirement of the decode, at any depth: `decode` without a `Context` holding the tag does not compile, and neither does running a `Schema.decodeUnknownEffect` that nothing provides it to. A `Context` holding more tags compiles. A schema with no context field takes no `Context`. `Schema.decodeUnknownSync` does not compile on such a schema, because it runs without services. - The `Context` given to `decode` may hold any Effect service, such as a `Clock`, and the schema's own transformations read them from Effect. - A field reads its tag from the Effect context, so the innermost provider wins, as for any service: an Effect decode inside a `decode`'s transformation that provides a tag the outer `decode` also holds reads its own value. - Plain fields are never written after `decode`. A value that changes is a `$` field. - Encoding an instance, as `Schema.encodeSync(Todo)(todo)`, gives the schema's wire fields and nothing else, each `$` field's current value under its wire key. The `realm`, a `FromContext` field, computed fields, and other instance properties stay off the wire, so what is sent is the schema's encoded form. - Declare a class with no `$` field as a plain `Schema.Class`. A `SchemaModel` without one still has a `realm` field, so decoding it needs a realm, and `RealmService` in an Effect program, for nothing to observe. ## Answers | Call | Answers | | --- | --- | | `SchemaModel (identifier)(fields)` | A class whose `$` fields are boxes or collections, checked by its schema. | | `BoxField(schema)` | A field that is a box of `schema`, under the wire key without the `$`. | | `CollectionField(rowSchema, { keyOf })` | A field that is a collection of rows by key, each row checked against `rowSchema` and compared with its equivalence: see [Collection fields](./collections.md). | | `decode(realm, schema, context?)(input)` | The decoded value, or throws `Schema.SchemaError`. | | `FromContext(tag)` | A field holding the service of `tag`, never on the wire, that puts `tag` in the schema's requirements. | | `Todo.make({ ...values, realm })` | An instance from values in hand, each `$` field's value under its wire key. | ## See also - [Schema-checked boxes](./boxes.md): what a `$` field checks on a write. - [Errors](../guides/errors.md#fields-a-schema-refuses): the path and message of each field `decode` refuses. - [Collection fields](./collections.md): rows by key, as a `$` field. - [Boxes and computed](../state/boxes.md): what a `$` field and a computed field are. - [Updates](../state/updates.md): what a write checks, and when it is undone. - [Hooks](../react/hooks.md): reading a model in a component. - [Equality and hashing](./equality.md): when two instances of a model are equal, and a class's own `Equal`. - [Coming from MobX](../start/mobx.md): a MobX store as a `SchemaModel`. --- # Collection fields URL: https://pinna.frondruntime.dev/docs/effect/collections Description: Read when a model holds rows by key. Declare a CollectionField, decode it from a plain array, write a refetch that keeps rows equal under the schema, and reconcile a schema-checked box of an array. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). A `CollectionField` is the core's [collection](../state/collections.md) as a field of a `SchemaModel`: it is read with `row(key)`, `read.row`, `keys`, and `rows`, and written with `write.upsert`, `write.remove`, and `write.replaceAll`, as that page shows. ## Example A `CollectionField` holds rows by key, each row checked against the row schema. On the wire it is a plain array. The rows here are the `Todo` of [Classes](./classes.md): ```ts import { BoxField, computed, createRealm, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); class Todo extends SchemaModel ("Todo")({ id: Schema.String, title: Schema.String, $done: BoxField(Schema.Boolean), // a box field; the wire key is "done" }) { readonly $label = computed(this.realm, (read) => read(this.$done) ? `✓ ${this.title}` : this.title, ); toggle(): void { update(this.realm, (read, write) => { write(this.$done, !read(this.$done)); }); } } ``` ```ts import { CollectionField, computed, SchemaModel, update } from "@frondruntime/pinna-effect"; class TodoList extends SchemaModel ("TodoList")({ $items: CollectionField(Todo, { keyOf: (todo) => todo.id }), }) { readonly $open = computed( this.realm, (read) => read(this.$items.rows).filter((todo) => !read(todo.$done)).length, { name: "TodoList.open" }, ); add(todo: Todo): void { update(this.realm, (_read, write) => { write.upsert(this.$items, todo, { at: "end" }); }); } remove(id: string): void { update(this.realm, (_read, write) => { write.remove(this.$items, id); }); } } ``` ```ts import { decode, untracked } from "@frondruntime/pinna-effect"; // On the wire, a collection is a plain array. const items = [ { id: "1", title: "Write the docs", done: false }, { id: "2", title: "Read them", done: true }, ]; const list = decode(realm, TodoList)({ items }); const open = untracked(realm, (read) => read(list.$open)); // 1 ``` A refetch writes every row at once with `write.replaceAll`. A row equal under the schema to the one held is kept, and what read it does not rerun. A `SchemaModel` row with a `$` field is merged: the held row stays, and its boxes take the refetched values. ```ts import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; // No `$` field, so it is declared as a plain Schema.Class. class Quote extends Schema.Class ("Quote")({ symbol: Schema.String, price: Schema.Number, }) {} class Market extends SchemaModel("Market")({ $quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }), }) { receive(quotes: ReadonlyArray ): void { update(this.realm, (_read, write) => { // A quote equal to the one held is kept: what read its row does not rerun. write.replaceAll(this.$quotes, quotes); }); } } const market = decode(realm, Market)({ quotes: [] }); const receiveQuotes = (json: unknown) => { market.receive(decode(realm, Schema.Array(Quote))(json)); }; ``` `reconcile` takes `equals`, here the item schema's equivalence, so a `schemaBox` of a plain array keeps the previous object of every item that did not change. `reconcileSchema` takes no schema, and works `equals` out from each pair of items when it is left out, as [Equality and hashing](./equality.md) lists. A plain `Schema.Struct` row compares with Effect's `Equal.equals`, which never sees a schema, so a `toEquivalence` annotation on a Struct is not used there. ```ts import { computedFunction, decode, reconcile, schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const Rate = Schema.Struct({ currency: Schema.String, rate: Schema.Number }); const sameRate = Schema.toEquivalence(Rate); const $rates = schemaBox(realm, Schema.Array(Rate), []); const rateOf = computedFunction(realm, (read, currency: string) => read($rates).find((rate) => rate.currency === currency), ); const receiveRates = (json: unknown) => { const next = decode(realm, Schema.Array(Rate))(json); update(realm, (read, write) => { // An unchanged rate keeps its previous object, so rateOf for it // returns the same value and its readers do not rerun. write( $rates, reconcile(read($rates), next, { keyOf: (rate) => rate.currency, equals: sameRate }), ); }); }; ``` `reconcileSchema` takes arrays only. One refetched model is a list of one on each side, under any key, such as a constant: the result is the held instance, its boxes set to the refetched values, or the refetched instance when a plain field differs. ```ts import { decode, reconcileSchema } from "@frondruntime/pinna-effect"; // One model, refetched: a list of one on each side. With one item, any key // does, such as a constant. const refreshTodo = (held: Todo, json: unknown): Todo => { const fresh = decode(realm, Todo)(json); const [next = fresh] = reconcileSchema([held], [fresh], { keyOf: () => "todo" }); return next; // `held`, its $done set to the refetched value, or `fresh` }; ``` `schemaCollection` is the collection a `CollectionField` holds, with no model around it: for rows a service or a feed owns, such as the trades a feed writes. It starts empty and checks and compares rows as the field does. ```ts import { decode, schemaCollection, update } from "@frondruntime/pinna-effect"; // The collection a CollectionField holds, with no model around it. const $quotes = schemaCollection(realm, Quote, { keyOf: (quote) => quote.symbol }); const receiveQuote = (json: unknown) => { // decode checks the wire data; upsert checks the row again as it lands. const quote = decode(realm, Quote)(json); update(realm, (_read, write) => { write.upsert($quotes, quote); }); }; ``` ## Rules - A `CollectionField` checks each row against the row schema when it lands: on `decode`, `write.upsert`, and `write.replaceAll`. A row the schema rejects throws from the update, which rolls back. A `schemaCollection` checks on `write.upsert` and `write.replaceAll` the same way. - An `undefined` row is rejected with `pinna: a collection row cannot be undefined`, even when the row schema accepts it: `row(key)` and `read.row` use `undefined` for a missing key. `decode` throws a `Schema.SchemaError` with that message and an Effect decode fails with it, before `keyOf` runs; `make` throws its schema error; `write.upsert` and `write.replaceAll` throw the message before changing any row. - A row written under a held key is compared with the row schema's equivalence, so a refetch of equal rows reruns nothing. - A key names one row. A repeated key fails the `decode` and throws from `write.replaceAll`, both with `pinna: the collection keyappears twice`. `reconcile` and `reconcileSchema` throw `pinna: reconcile: the key appears twice`. - A row with a `$` field is a new instance after every `decode`, with new boxes. `replaceAll`, `upsert`, and `reconcileSchema` merge it into the row held under its key, so only the readers of a changed box rerun. When they merge is on [Equality and hashing](./equality.md). ## Answers | Call | Answers | | --- | --- | | `CollectionField(schema, { keyOf, name? })` | A field of rows by key, each checked against `schema`, a plain array on the wire. `name` names every instance's collection, as `collection`'s does. | | `schemaCollection(realm, schema, { keyOf, equals?, name? })` | An empty collection of rows `schema` accepts, the one a `CollectionField` holds. A row is compared with `equals`, the schema's equivalence by default, and a `SchemaModel` row is merged into the held one. | | `reconcileSchema(previous, next, { keyOf, equals? })` | As `reconcile` on [Updates](../state/updates.md), with `equals` optional and a `SchemaModel` item merged into the held one. | ## See also - [Collections](../state/collections.md): reading and writing a collection, and rendering one row per key. - [Classes](./classes.md): the model a collection field lives on. - [Updates](../state/updates.md): the update every write runs in. - [Hooks](../react/hooks.md): a row component that rerenders alone. - [Equality and hashing](./equality.md): a row class's own `Equal`, and what each schema counts as equal. - [Live data](../guides/live-data.md): a refetch and a feed written into a collection field. --- # Equality and hashing URL: https://pinna.frondruntime.dev/docs/effect/equality Description: Read when a write, a refetch, or a reconcile keeps or replaces a value. Know what each box, collection, and reconcile compares with by default, why two decodes of a model with a box are not equal unless the class defines its own Equal, what Effect's Equal.equals and HashSet see, and how a class defines its own Equal and Hash. Pinna compares a value written over the one held. When the two are equal, the held value stays, and nothing that read it reruns. What counts as equal depends on what holds the value. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). ## Example A `schemaBox` compares as `Schema.toEquivalence` of its schema does. An equal write keeps the object the box holds. ```ts import { createRealm, schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); const Reading = Schema.Struct({ at: Schema.Date, value: Schema.Number }); type Reading = typeof Reading.Type; const $reading = schemaBox(realm, Reading, { at: new Date(0), value: 1 }); const record = (reading: Reading) => { update(realm, (_read, write) => { // A Date compares by its time: an equal reading keeps the object // the box holds, and nobody reruns. write($reading, reading); }); }; ``` A `SchemaModel` without its own Equal compares its boxes and its realm by identity, so two decodes of the same JSON are not equal when the class has a `$` field. ```ts import { BoxField, decode, SchemaModel } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; class Position extends SchemaModel ("Position")({ id: Schema.String, $size: BoxField(Schema.Number), }) {} const samePosition = Schema.toEquivalence(Position); const first = decode(realm, Position)({ id: "a", size: 1 }); const again = decode(realm, Position)({ id: "a", size: 1 }); // false: each decode makes its own $size box, and boxes compare by identity. const positionsEqual = samePosition(first, again); ``` A refetch through `write.replaceAll` keeps each plain row that did not change. ```ts import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; // No `$` field, so a plain Schema.Class. class Quote extends Schema.Class ("Quote")({ symbol: Schema.String, price: Schema.Number, }) {} class Market extends SchemaModel("Market")({ $quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }), }) {} const market = decode(realm, Market)({ quotes: [] }); const receiveQuotes = (json: unknown) => { const quotes = decode(realm, Schema.Array(Quote))(json); update(realm, (_read, write) => { // A quote equal under Quote's schema is kept, and what read its row does not rerun. write.replaceAll(market.$quotes, quotes); }); }; ``` A refetched `SchemaModel` row is merged into the held one, so a component that reads the row reruns only when a plain field changes, and one that reads `$size` reruns when the size does. ```ts import { decode, reconcileSchema, schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const $positions = schemaBox(realm, Schema.Array(Position), []); const receivePositions = (json: unknown) => { const fresh = decode(realm, Schema.Array(Position))(json); update(realm, (read, write) => { // A held id keeps its Position, and the new size goes into its $size box. write( $positions, reconcileSchema(read($positions), fresh, { keyOf: (position) => position.id }), ); }); }; ``` A `SchemaModel` that defines `[Equal.symbol]` decides its own equality. A refetched rate under a held pair is merged, and its box takes the new bid. ```ts import { BoxField, decode, reconcileSchema, SchemaModel, schemaBox, update, } from "@frondruntime/pinna-effect"; import { Equal, Hash, Schema } from "effect"; class Rate extends SchemaModel ("Rate")({ pair: Schema.String, $bid: BoxField(Schema.Number), }) { // One rate per pair. Plain fields only: Effect caches what Equal.equals answers. [Equal.symbol](that: unknown): boolean { return that instanceof Rate && that.realm === this.realm && this.pair === that.pair; } [Hash.symbol](): number { return Hash.string(this.pair); } } const $rates = schemaBox(realm, Schema.Array(Rate), []); const receiveRates = (json: unknown) => { const fresh = decode(realm, Schema.Array(Rate))(json); update(realm, (read, write) => { // A pair already held keeps its rate, and the new bid goes into that rate's box. write($rates, reconcileSchema(read($rates), fresh, { keyOf: (rate) => rate.pair })); }); }; ``` `{ equals }` replaces the default of any box. ```ts import { schemaBox } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const Row = Schema.Struct({ id: Schema.String, price: Schema.Number }); // Every new array is a change, even one equal part by part. const $log = schemaBox(realm, Schema.Array(Schema.String), [], { equals: Object.is }); // The same row while the id is the same, whatever the price. const $selected = schemaBox( realm, Row, { id: "a", price: 1 }, { equals: (held, next) => held.id === next.id }, ); ``` ## Rules - The core's `box`, `collection`, and `computed` compare with `Object.is` unless `{ equals }` says otherwise, so a new array or object is a change. A computed value compares with `Object.is` in `pinna-effect` too, even when what it reads is a `schemaBox`. - A `schemaBox` and a `BoxField` compare with the schema's equivalence, with the answers of `Schema.toEquivalence`. An equal write keeps the value held and notifies nobody, so a refetch of the same data reruns nothing. - Under a schema's equivalence a primitive equals the same value, `NaN` equals `NaN`, and `0` equals `-0`. A `Date` equals one with the same time, and two invalid Dates are equal. An array or a struct compares part by part. A schema with an equivalence annotation, such as `Schema.overrideToEquivalence`, compares with it. - A box of `Schema.Unknown`, `Schema.Any`, or `Schema.ObjectKeyword` compares with `Object.is`: such a schema says nothing of the value's shape, and a structural compare would hash the whole value on every write. An `Unknown` field inside a struct compares structurally. - `{ equals }` replaces the schema's equivalence: `Object.is` counts every new array or object as a change, even one equal part by part, and a function by id counts a row with a new price as unchanged. - A `SchemaModel` instance without its own `Equal` compares its plain fields by value and its boxes and its realm by identity. Every `decode` makes new boxes, so a refetched instance with a `$` field is not equal to the one held, and neither is an instance from another realm. - A `SchemaModel` with its own `[Equal.symbol]` is compared by that method wherever Pinna compares with the class's schema, as in a `schemaBox` and in `reconcileSchema`, on every comparison, with no answer cached. A plain `Schema.Class` ignores its own `[Equal.symbol]` there, as Effect's schema does, and compares field by field. - A refetched `SchemaModel` instance under a held key is merged into the held one when both are of the same class and realm and their plain fields are equal, or the class's own `[Equal.symbol]` finds them equal, even when a plain field differs. The held instance stays; each `BoxField` takes the refetched value, compared with its schema, and each `CollectionField` merges its rows the same way, so a refetch reruns only the readers of a box that changed. A plain field that holds a model is compared, not merged. Any other difference replaces the instance. - `reconcileSchema`, `write.replaceAll`, and `write.upsert` merge. A `schemaBox` of an array compares by index and does not. - A `CollectionField` merges a `SchemaModel` row written under a held key and compares any other row with the row schema's equivalence: `replaceAll` and `upsert` keep every equal or merged row, and notify nobody when nothing changed. - `reconcile` takes `equals` and has no default: a refetch builds new objects, and the comparison is the caller's choice. - `reconcileSchema` keeps a row that is the same instance, merges a `SchemaModel` row, compares any other instance of a `Schema.Class` with its class's equivalence, and anything else with Effect's `Equal.equals`. A key repeated in the new array throws before any box is written. The merge writes in the open update, or in one of its own; a refetch that changes no box opens none, so it runs inside a computed value too. `equals` replaces all of it. - Effect's `Equal.equals`, which `HashSet` and `HashMap` look values up with, is not the schema's equivalence. It compares `Hash.hash` first, caches each object's hash, caches its answer for a pair of objects, and compares an instance by every own property. The two agree on a plain `Schema.Class` and on a `SchemaModel` whose fields are all plain: two decodes of the same JSON into one realm are equal, and `HashSet.has` finds either. They part on two cases: - A `$` property of the class body, such as a computed value, is no schema field. The schema's equivalence ignores it; `Equal.equals` compares it by identity, so two instances are not equal under Effect. - A `SchemaModel` with `[Equal.symbol]` and no `[Hash.symbol]` is equal under the schema's equivalence and not under `Equal.equals`, which compares hashes first. Define both, on plain fields only, such as the key, since Effect caches the hash. - Under Effect's `Equal.equals`, a box, a computed value, an atom, and a realm equal only themselves. A plain object holding them compares them by identity, never by their contents. ## Answers | Call | Compares a new value with the held one by default with | | --- | --- | | `box(realm, initial, { equals? })` | `Object.is`. | | `collection(realm, { keyOf, equals? })` | `Object.is`, row by row. | | `computed(realm, compute, { equals? })` | `Object.is`. | | `schemaBox(realm, schema, initial, { equals? })` | The schema's equivalence. | | `BoxField(schema)` | The schema's equivalence. | | `CollectionField(schema, { keyOf })` | A merge for a `SchemaModel` row, the row schema's equivalence otherwise, row by row. | | `reconcile(previous, next, { keyOf, equals })` | `equals`, required. | | `reconcileSchema(previous, next, { keyOf, equals? })` | A merge for a `SchemaModel` row, the class's equivalence for another schema class instance, `Equal.equals` otherwise. | ## See also - [Schema-checked boxes](./boxes.md): the box that checks a schema on every write. - [Classes](./classes.md): the model whose fields these rules compare. - [Collection fields](./collections.md): `replaceAll` and `reconcile` on a refetch. - [Boxes and computed](../state/boxes.md): the core's box and its `equals`. - [Collections](../state/collections.md): the core's collection and its `equals`. --- # Programs URL: https://pinna.frondruntime.dev/docs/effect/programs Description: Read when an app is written as Effect programs. Run an effect per change, stream changes, hold a value observed for a scope, feed a value from a stream, run a feed while its data is read, and hold a section's writes in a stage until it succeeds. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). The functions on this page are for apps written as Effect programs, and `@frondruntime/pinna-effect` exports them next to the rest. Models and components need none of them. `watchScoped` and `observeScoped` end in `Scoped`, Effect's suffix for a call that lives for the caller's scope, because the plain `watch` and `observe` keep their names and return a stop function instead. ## Example No program requires a service for the realm. `watchScoped` and `fromStream` take it first, as `watch` does, and `changes`, `observeScoped`, and `whileObserved` take it from the observable, so a program that refuses every requirement but `Scope` runs each of them. ```ts import { createRealm } from "@frondruntime/pinna-effect"; // Every program below takes the realm, or an observable that carries it, // so none requires a service for it; a test makes a realm of its own. const realm = createRealm(); ``` `watchScoped` runs an effect for each change of what the select reads, in the caller's scope. A new value interrupts the running effect: the latest value wins. `search` stands for the application's own effect. ```ts import { schemaBox, update, watchScoped } from "@frondruntime/pinna-effect"; import { Effect, Schema } from "effect"; const $query = schemaBox(realm, Schema.String, ""); const $results = schemaBox(realm, Schema.Array(Schema.String), []); const searchAsTyped = watchScoped( realm, (read) => read($query), (query) => Effect.gen(function* () { // A newer query interrupts this effect, here or in the search. yield* Effect.sleep("200 millis"); const results = yield* search(query); update(realm, (_read, write) => write($results, results)); }), ); ``` `changes` is a stream of the current value, then each change. ```ts import { changes } from "@frondruntime/pinna-effect"; import { Effect, Stream } from "effect"; // The query now, then each change; a slow consumer skips to the newest. const logQueries = changes($query).pipe( Stream.runForEach((query) => Effect.log(`query: ${query}`)), ); ``` `fromStream` is a read-only value fed by a stream. The stream runs only while the value is observed. When the last observer leaves, the value resets to `initial` synchronously. Each run starts from `initial` until its first element arrives. `fetchRate` stands for the application's own effect. ```ts import { computed, fromStream, schemaBox } from "@frondruntime/pinna-effect"; import { Effect, Schedule, Schema, Stream } from "effect"; const $price = schemaBox(realm, Schema.Number, 10); const priceInEuros = Effect.gen(function* () { // No rate until the stream emits, then its latest rate. The poll runs // only while $rate is observed. Losing the last observer resets $rate // to undefined, so a stale rate never shows as current. const $rate = yield* fromStream ( realm, Stream.fromEffectSchedule(fetchRate, Schedule.spaced("1 minute")), undefined, ); return computed(realm, (read) => { const rate = read($rate); return rate === undefined ? undefined : read($price) * rate; }); }); ``` `whileObserved` runs a program while an observable is observed: from the start when the first observer arrives, interrupted when the last one leaves. It is how a feed writes the rows of a collection only while a list shows them: a list reads `keys`, and a reader of one present row does not. `fromStream` is the same lifetime around a single value. A row checked against a schema lands in a `schemaCollection` ([Collection fields](./collections.md)). `fetchTrades` and `tradeUpdates` stand for the application's own snapshot and updates. ```ts import { Schema } from "effect"; class Trade extends Schema.Class ("Trade")({ id: Schema.String, notional: Schema.Number.check(Schema.isGreaterThan(0)), }) {} ``` ```ts import { box, schemaCollection, update, whileObserved } from "@frondruntime/pinna-effect"; import { Effect, Stream } from "effect"; const $trades = schemaCollection(realm, Trade, { keyOf: (trade) => trade.id }); // Only the app knows when its snapshot is complete, so the flag is its own. const $loaded = box(realm, false); // A list observes the keys; a reader of one present row does not, so this // feed runs while a list shows the trades. const tradeFeed = whileObserved( $trades.keys, Effect.gen(function* () { const trades = yield* fetchTrades; update(realm, (_read, write) => { write.replaceAll($trades, trades); write($loaded, true); }); // The run ends when the last reader leaves, so it must not end before: // it runs the updates for as long as it is observed. yield* tradeUpdates.pipe( Stream.runForEach((trade) => Effect.sync(() => update(realm, (_read, write) => write.upsert($trades, trade))), ), ); }).pipe( // Not loaded once nobody reads it: the next reader waits for a new snapshot. Effect.ensuring(Effect.sync(() => update(realm, (_read, write) => write($loaded, false)))), ), ); ``` `observeScoped` holds a value observed until the scope closes, so the stream behind it keeps running with nothing rendered. ```ts import { observeScoped } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const keepRateFresh = Effect.gen(function* () { const $euros = yield* priceInEuros; // Observed until the scope closes, rendered or not: // the poll keeps running, and $euros stays cached. yield* observeScoped($euros); return $euros; }); ``` Each of them stops when its scope closes. ```ts import { Effect } from "effect"; const main = Effect.gen(function* () { yield* searchAsTyped; yield* Effect.forkScoped(logQueries); yield* keepRateFresh; yield* tradeFeed; }); // Every watch, stream, and hold above stops when the scope // closes: here, when the fiber is interrupted. const start = () => Effect.runFork(main.pipe(Effect.andThen(Effect.never), Effect.scoped)); ``` ## Rules - Pass the realm, as `watch` takes it. A test makes a realm of its own. `RealmService` is for a `SchemaModel` decoded inside an Effect program ([Classes](./classes.md)). - A watch's effect has no error channel. A defect is a bug: it is logged at the error level, and the watch keeps running. A stream behind `fromStream` logs a defect too. - While observed, a `fromStream` value is the last element of the current run, or `initial` before the first; while unobserved, it is `initial`. A stream that completes or dies leaves the value as it is until the last observer leaves. A failure the screen must show is an element the stream gives, such as a status beside the rate: see [Failures as values](#failures-as-values). - A watch's select is tracked and must not write. Its effect writes through `update`. - `watchScoped` runs for changes, not for the current value. `changes` starts with the current value. - `changes`, `observeScoped`, and `whileObserved` take the realm from the observable. A host whose programs require nothing but `Scope` watches a box with `changes` while its work awaits. - A `whileObserved` program runs in a scope of its own, closed when the run ends, so a fiber it forks into that scope stops with it. A program that returns ends its run while the value is still observed, and the next run starts only after the last observer leaves and another arrives: a feed ends on the stream it runs. - `whileObserved` and `fromStream` keep the services of the program that called them, not of the code that observes later. Provide a service before the call. - A program that writes more than one value per element runs on `whileObserved` and writes them in one update. `fromStream` publishes each element in an update of its own, so a box written from inside its stream lands one update earlier, and a reader of both sees them disagree. - Whether a feed has loaded is the application's own box. Pinna cannot tell when a snapshot is complete. The program writes the flag in the same update as the rows, so no reader sees it loaded with the rows missing. - `watchScoped` and `fromStream` compare with `Object.is` unless given `{ equals }`, as the core's `watch` and `box` do: a value from a stream or a select has no schema to compare by, unlike a `schemaBox`. `changes` takes no options and compares with `Object.is`. - Stop a program by closing its scope, not by keeping stop functions. ## Answers | Call | Answers | | --- | --- | | `watchScoped(realm, (read) => ..., (value, previous) => effect, { equals?, name? })` | An effect that starts the watch in the caller's scope. A result equal under `equals`, `Object.is` by default, is no change, so it neither runs nor interrupts the effect. `name` names the watch in its errors. | | `changes($x)` | A stream of `$x`'s current value, then each change; a slow consumer skips to the newest. Takes a box or a computed value, not an atom. | | `observeScoped($x)` | An effect that holds `$x`, a box, a computed value, or an atom, observed until the scope closes. | | `whileObserved($x, program)` | An effect that runs `program` while `$x`, a box, a computed value, or an atom, is observed, each run in a scope of its own. A defect is logged at the error level, and the next observation starts the program again. Closing the caller's scope interrupts a run and waits for it; later observation does not start it again. | | `fromStream(realm, stream, initial, { equals?, name? })` | A read-only value: `initial`, then the stream's latest element; needs the stream's services. The stream runs with the services of the program that made the value, and restarts each time the value is observed again. The value resets to `initial` when the last observer leaves or the scope closes; closing the scope stops the stream for good. An element equal under `equals`, `Object.is` by default, notifies nobody; `name` names the value for `inspect`. | | `withStage(realm, (stage) => section, { name?, conflicts? })` | The section's value, with its stage applied; a section failure, defect, or interruption drops the stage and the outcome stands. A conflict fails with `StageConflict`; a recipe that throws on replay is a defect. An interruption once landing began leaves the stage applied; the exit still contains `Interrupt`. | | `withStage(stage, (child) => section, { name? })` | A savepoint over `stage`, with the same success and failure behavior. The child inherits its root's conflict mode, takes no `conflicts` option, and never fails with `StageConflict`: its root checks what the child read. | | `StageConflict` | The tagged error `withStage` fails with when a stage opened with `{ conflicts: "fail" }` finds that what it read changed: `stage`, `changed`, and `observables`, as on `StageConflictError`. | ## Lifetimes Three owners run an effect, and the owner decides what stops it. - Observation owns the stream of a `fromStream` value and a `whileObserved` program: each runs from the first observer to the last, and starts again with the next. This fits data that matters only while something shows it, such as a rate or a search result: the last observer leaving stops the work, and the value resets to `initial`, so a stale rate never shows as current. - A fiber owns a feed whose data is kept whether shown or not, such as the quotes of a board that several screens and watches read from one collection. The feed runs until the fiber is interrupted, with nothing observing it ([Live data](../guides/live-data.md#with-effect)). - A scope owns a command, such as an order sent or a file saved. It runs to its end whatever the screen does, and only closing the scope interrupts it. This fits work a person started and expects finished. A `fromStream` value keeps the context of the program that made it, and its stream runs with that context on every observation. A service the stream needs is provided where the value is made, not where it is observed. The stream's type lists the services it needs but not the clock, so a stream that polls or sleeps keeps the clock of the program that made the value: a test on `TestClock` provides it before the value is made ([Testing](#testing)). ```ts import { fromStream } from "@frondruntime/pinna-effect"; import { Context, Effect, Schedule, Stream } from "effect"; class Rates extends Context.Service }>()("Rates") {} // The stream needs Rates, so making the value needs it: fromStream keeps the // context of the program that makes the value, and the stream runs with it // on every observation, whatever program observes the value later. const makeRate = fromStream ( realm, Stream.fromEffectSchedule( Effect.gen(function* () { const rates = yield* Rates; return yield* rates.latest; }), Schedule.spaced("1 minute"), ), undefined, ); const rate = makeRate.pipe(Effect.provideService(Rates, { latest: fetchRate })); ``` A command that an event handler starts runs in a scope made once for the application. `Effect.forkIn` runs it in that scope, and `Effect.runForkWith(context)` gives it the application's services, the clock among them, so a test's `TestClock` reaches the command too. ```ts import { box, update } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; type OrderStatus = "idle" | "sending" | "sent"; const $orderStatus = box (realm, "idle"); const sendOrder = (amount: number) => Effect.gen(function* () { update(realm, (_read, write) => write($orderStatus, "sending")); yield* submit(amount); update(realm, (_read, write) => write($orderStatus, "sent")); }); // Made once, in the application's scope. An event handler calls `send`; the // order runs in that scope, so unmounting the component that sent it, or the // last observer of $orderStatus leaving, interrupts nothing. Closing the // application's scope interrupts it. The order runs with the services the // application was given, its clock among them. const orders = Effect.gen(function* () { const scope = yield* Effect.scope; const context = yield* Effect.context (); const send = (amount: number): void => { Effect.runForkWith(context)(Effect.forkIn(sendOrder(amount), scope)); }; return { send }; }); ``` `Effect.forkScoped` schedules its fiber and returns before the fiber runs, so the next line cannot count on what the fiber writes. `{ startImmediately: true }` runs the fiber up to its first wait at once. ```ts import { untracked } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const sendAndRead = Effect.gen(function* () { // The fiber runs up to its first wait before the next line, so the read // sees "sending". Without startImmediately, it starts later, and the read // sees "idle". yield* Effect.forkScoped(sendOrder(10), { startImmediately: true }); return untracked(realm, (read) => read($orderStatus)); }); ``` ## Failures as values `fromStream` takes a stream whose error type is `never`, because a value has no channel for a failure. A typed failure the screen shows is mapped into the value's own type: the good elements and the failure become members of one union, and `Stream.catch` turns the failure into the last element. ```ts import { fromStream } from "@frondruntime/pinna-effect"; import { Data, Stream } from "effect"; // The transport's typed failure. class RateUnavailable extends Data.TaggedError("RateUnavailable")<{ readonly reason: string }> {} // What the screen shows: a rate, or why there is none. type RateState = | { readonly _tag: "Loading" } | { readonly _tag: "Rate"; readonly rate: number } | { readonly _tag: "Unavailable"; readonly reason: string }; const showRate = (rates: Stream.Stream ) => fromStream ( realm, rates.pipe( Stream.map((rate): RateState => ({ _tag: "Rate", rate })), // The failure becomes the last element: the stream ends on it, and the // value shows it until the last observer leaves. Stream.catch((error) => Stream.succeed ({ _tag: "Unavailable", reason: error.reason }), ), ), { _tag: "Loading" }, ); ``` The stream ends on the failure, and the value shows it until the last observer leaves. The next observer starts the stream again, from `initial`. ## Testing A program that polls or sleeps is tested on `TestClock`, from `effect/testing`, so the test moves time instead of waiting for it. The test realm is as on [Testing](../guides/testing.md). - Provide `TestClock.layer()` around the program that makes a `fromStream` value, not only around the one that observes it. The value keeps the clock of the program that made it, and a value made on the live clock polls on the live clock whatever the observer provides. - Hold the value observed with `observeScoped`. Its stream runs only while something observes the value, so an unobserved poll never runs and the value stays `initial`. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { fromStream, observeScoped, RealmService, untracked } from "@frondruntime/pinna-effect"; import { Effect, Schedule, Stream } from "effect"; import { TestClock } from "effect/testing"; test("a poll advances with the test clock", async () => { using realm = testRealm(); let polls = 0; const poll = Effect.sync(() => ++polls); const latest = await Effect.gen(function* () { // Made under TestClock: fromStream keeps the clock of the program that // makes the value, and the poll waits on it. const $polls = yield* fromStream( realm, Stream.fromEffectSchedule(poll, Schedule.spaced("1 minute")), 0, ); // The poll runs only while something observes the value. yield* observeScoped($polls); yield* TestClock.adjust("2 minutes"); return untracked(realm, (read) => read($polls)); }).pipe( Effect.scoped, Effect.provideService(RealmService, realm), Effect.provide(TestClock.layer()), Effect.runPromise, ); expect(latest).toBe(3); }); ``` `TestClock.adjust` is not a completion signal. It runs the sleeps that fall due and waits for the fibers it woke to suspend; work that no sleep holds, such as a load that yields between rows, can still be running when it returns, and `TestClock.adjust(0)` wakes nothing at all. A test waits on a value the program publishes when its work is done: a `Deferred`, or a box read through `changes`. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { box, changes, RealmService, untracked, update } from "@frondruntime/pinna-effect"; import { Effect, Stream } from "effect"; import { TestClock } from "effect/testing"; test("a test waits on what the program publishes, not on the clock", async () => { using realm = testRealm(); const $loadedRows = box(realm, 0); const $loaded = box(realm, false); // Yields between rows; no sleep holds it, so the clock has nothing to wait for. const load = Effect.gen(function* () { for (let row = 1; row <= 100; row++) { yield* Effect.yieldNow; update(realm, (_read, write) => write($loadedRows, row)); } update(realm, (_read, write) => write($loaded, true)); }); const loaded = await Effect.gen(function* () { yield* Effect.forkScoped(load); yield* changes($loaded).pipe( Stream.filter((done) => done), Stream.runHead, ); return untracked(realm, (read) => read($loadedRows)); }).pipe( Effect.scoped, Effect.provideService(RealmService, realm), Effect.provide(TestClock.layer()), Effect.runPromise, ); expect(loaded).toBe(100); }); ``` A helper that runs a program and declares its realm with `using` is `async` and awaits the run before it returns. Returning the promise without `await` disposes the realm while the program's scope is still open, and the dispose throws `The test realm is not at rest: watch still running.`, one entry per watch the program holds. The dispose stops each watch first, so no watch reruns in the next test, but a fiber the program forked runs on until its scope closes; the fix is `return await`. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { RealmService, schemaBox, update, watchScoped } from "@frondruntime/pinna-effect"; import { Deferred, Effect, Schema } from "effect"; // `async` and `return await`: the realm is disposed after the program's scope // closes. A helper that returns the promise without awaiting it disposes the // realm while the program's watch still runs. const searchOnce = async (query: string): Promise => { using realm = testRealm(); const $query = schemaBox(realm, Schema.String, ""); return await Effect.gen(function* () { const searched = yield* Deferred.make (); yield* watchScoped( realm, (read) => read($query), (value) => Deferred.succeed(searched, value), ); update(realm, (_read, write) => write($query, query)); return yield* Deferred.await(searched); }).pipe(Effect.scoped, Effect.provideService(RealmService, realm), Effect.runPromise); }; test("a helper awaits its program before its realm is disposed", async () => { expect(await searchOnce("pinna")).toBe("pinna"); }); ``` | Call | Answers | | --- | --- | | `Effect.provide(TestClock.layer())` | A program whose sleeps and schedules wait on the test clock. | | `TestClock.adjust(duration)` | Moves the test clock and runs the sleeps that fall due; not a signal that other work finished. | ## Stages `withStage` holds a section's writes in a stage ([Updates](../state/updates.md#stages)) and lands them when the section succeeds. A section failure, defect, or interruption drops them, so nothing the section staged reaches the realm. An interruption once landing began leaves the stage applied; the exit still contains `Interrupt`. ```ts import { box, stageUpdate, withStage } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const $balance = box(realm, 100); const $status = box<"idle" | "sent">(realm, "idle"); const transfer = (amount: number) => withStage(realm, (stage) => Effect.gen(function* () { stageUpdate(stage, (read, write) => { write($balance, read($balance) - amount); write($status, "sent"); }); // Nothing shows until send succeeds; a failure or an interruption drops it. yield* send(amount); }), ); ``` Over a stage, `withStage` is a savepoint. A section that fails and is caught leaves the outer stage as it was, and each attempt of an `Effect.retry` opens a fresh child. ```ts import { box, stageUpdate, withStage } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const $notes = box >(realm, []); const transferWithNote = (amount: number, note: string) => withStage(realm, (stage) => Effect.gen(function* () { stageUpdate(stage, (read, write) => { write($balance, read($balance) - amount); }); // A child stage: when the section fails, its writes never reach the outer // stage, and each retry starts from a fresh child. yield* withStage(stage, (section) => Effect.gen(function* () { const text = yield* describeTransfer(note); stageUpdate(section, (_read, write) => { write.modify($notes, (notes) => { notes.push(text); }); }); }), ).pipe( Effect.retry({ times: 2 }), Effect.catch(() => Effect.void), ); yield* send(amount); }), ); ``` With `{ conflicts: "fail" }`, a stage whose reads changed before it landed fails with `StageConflict`, and `Effect.retry` runs the section again over the new values. ```ts import { box, StageConflict, stageUpdate, withStage } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const $price = box(realm, 10); const $total = box(realm, 0); const checkout = withStage( realm, (stage) => Effect.sync(() => { stageUpdate(stage, (read, write) => { write($total, read($price) * 2); }); }), { conflicts: "fail" }, ).pipe( // The price changed after the stage read it: run the section again over the new one. Effect.retry({ while: (error) => error instanceof StageConflict, times: 3 }), ); ``` - `withStage` applies the stage after the section succeeds, synchronously, so nothing runs between the section's last write and the landing. - The release drops the stage whether or not it applied: `dropStage` does nothing to a closed stage. An `applyStage` precondition failure leaves the stage open and becomes a defect in `withStage`; the release then drops it and its open children. A conflict or replay throw drops it before the release. - Retrying reruns the section, requests included. Retry only a section that is safe to repeat; `withStage` never retries on its own. - A host that lands a stage inside its own update, or applies only on a condition, calls `openStage`, `applyStage`, and `dropStage` itself, with `Effect.acquireUseRelease`. ## See also - [Reacting](../state/reacting.md): `watch` and `autorun` without Effect. - [Classes](./classes.md): `decode`, JSON in and a checked model out. - [Live data](../guides/live-data.md): a WebSocket feed and a refetch as Effect programs. - [Testing](../guides/testing.md): a test realm, and a program run in it. --- # Live data URL: https://pinna.frondruntime.dev/docs/guides/live-data Description: Read when state comes from a socket or a server. Open a socket while a value is observed and reconnect after a drop, write each message in one update, refetch without losing row identity, and run the same feed as an Effect stream. ## Example A quote feed keeps one row per symbol, written from a WebSocket. The server sends a snapshot of every quote when the socket opens, then one change per message. The parser checks each message by hand, builds new objects with the fields a quote has, and returns `undefined` for anything else. ```ts interface Quote { readonly symbol: string; readonly bid: number; readonly ask: number; } type QuoteMessage = | { readonly type: "snapshot"; readonly quotes: ReadonlyArray } | { readonly type: "upsert"; readonly quote: Quote } | { readonly type: "delete"; readonly symbol: string }; const isRecord = (value: unknown): value is Readonly> => typeof value === "object" && value !== null; const isPrice = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value); // A new object with a quote's fields alone, or undefined. const toQuote = (value: unknown): Quote | undefined => { if (!isRecord(value)) { return undefined; } const { symbol, bid, ask } = value; return typeof symbol === "string" && isPrice(bid) && isPrice(ask) ? { symbol, bid, ask } : undefined; }; // The message in `data`, or undefined. A snapshot that repeats a symbol is // no message: `write.replaceAll` would throw on it. const parseMessage = (data: unknown): QuoteMessage | undefined => { let value: unknown; try { value = JSON.parse(String(data)); } catch { return undefined; } if (!isRecord(value)) { return undefined; } const { type, quotes, quote, symbol } = value; if (type === "snapshot" && Array.isArray(quotes)) { const parsed: Array = []; const seen = new Set(); for (const item of quotes) { const next = toQuote(item); if (next === undefined || seen.has(next.symbol)) { return undefined; } seen.add(next.symbol); parsed.push(next); } return { type, quotes: parsed }; } if (type === "upsert") { const next = toQuote(quote); return next === undefined ? undefined : { type, quote: next }; } if (type === "delete" && typeof symbol === "string") { return { type, symbol }; } return undefined; }; ``` The socket is open while something observes the feed. A private atom stands for the socket, and `$status`, `$symbols`, and each `quote(symbol)` read it, so the first observer of any of them runs `connect`, and the last one leaving runs its cleanup, which closes the socket and cancels a pending reconnect. A hook on `keys` would miss a reader of one row: `row(key)` never reads `keys`. ```ts import { atom, box, collection, computed, computedFunction, Model, onObserved, type Realm, update, } from "@frondruntime/pinna"; type Status = "connecting" | "open" | "closed"; const quotesUrl = "wss://example.com/quotes"; class QuoteFeed extends Model { // Stands for the socket: observing any public field below opens it. private readonly $socket = atom(this.realm); private readonly $state = box (this.realm, "closed"); private readonly $rows = collection(this.realm, { keyOf: (quote: Quote) => quote.symbol, // A snapshot builds new objects; a quote with the same prices is kept. equals: (previous, next) => previous.bid === next.bid && previous.ask === next.ask, }); readonly $status = computed(this.realm, (read) => { read(this.$socket); return read(this.$state); }); readonly $symbols = computed(this.realm, (read) => { read(this.$socket); return read(this.$rows.keys); }); readonly quote = computedFunction(this.realm, (read, symbol: string) => { read(this.$socket); return read.row(this.$rows, symbol); }); constructor(realm: Realm) { super(realm); onObserved(this.$socket, () => this.connect()); } // Opens the socket, and reopens it after each drop: 0.5 s after the // first, doubling up to 30 s, back to 0.5 s once a message arrives. // Returns what closes it. The state lives in this call, so a socket from // an earlier observation never schedules a reconnect. private connect(): () => void { let socket: WebSocket | undefined; let timer: ReturnType | undefined; let attempt = 0; const open = () => { this.setStatus("connecting"); const next = new WebSocket(quotesUrl); next.onopen = () => { this.setStatus("open"); }; next.onmessage = (event: MessageEvent) => { attempt = 0; this.receive(event.data); }; next.onclose = () => { this.setStatus("closed"); timer = setTimeout(open, Math.min(30_000, 500 * 2 ** attempt)); attempt++; }; socket = next; }; open(); return () => { clearTimeout(timer); if (socket !== undefined) { socket.onclose = null; socket.close(); } }; } private setStatus(status: Status): void { update(this.realm, (_read, write) => write(this.$state, status)); } private receive(data: unknown): void { const message = parseMessage(data); if (message === undefined) { // The host's error sink, which a realm made without onError uses too. reportError(new TypeError("quotes: dropped a message that is not one")); return; } // One update per message: a reader sees all of it or none of it. update(this.realm, (_read, write) => { switch (message.type) { case "snapshot": // A quote equal to the one held keeps its row and notifies nobody. return write.replaceAll(this.$rows, message.quotes); case "upsert": return write.upsert(this.$rows, message.quote, { at: "end" }); case "delete": return write.remove(this.$rows, message.symbol); } }); } } ``` A watch, an autorun, `observe`, or a mounted `useValue(feed.$symbols)` opens the socket. ```ts import { createRealm, watch } from "@frondruntime/pinna"; const realm = createRealm(); const feed = new QuoteFeed(realm); // The first observer opens the socket; stopping the last one closes it. const stop = watch( realm, (read) => read(feed.$status), (status) => { console.log(`quotes: ${status}`); }, ); ``` A request is the same shape without a socket. An `AbortController` cancels the request a newer one replaces, and `reconcile` keeps each unchanged row's instance, so a refetch that changed nothing notifies nobody. The parser reuses `isRecord` and `isPrice` from the first sample and throws on a body that does not fit, and the status ends in `"failed"`. ```ts import { box, Model, reconcile, update } from "@frondruntime/pinna"; interface Position { readonly id: string; readonly symbol: string; readonly quantity: number; } type Load = | { readonly state: "loading" } | { readonly state: "loaded" } | { readonly state: "failed"; readonly error: unknown }; const positionsUrl = "https://example.com/positions"; const toPosition = (value: unknown): Position => { if (isRecord(value)) { const { id, symbol, quantity } = value; if (typeof id === "string" && typeof symbol === "string" && isPrice(quantity)) { return { id, symbol, quantity }; } } throw new TypeError("positions: a row is not a position"); }; class Positions extends Model { readonly $rows = box >(this.realm, []); readonly $load = box (this.realm, { state: "loading" }); private controller: AbortController | undefined; // Loads the account's positions. A newer call aborts this one, and an // aborted call writes nothing, so the last call wins. The rows stay on // screen while the next ones load. async refresh(account: string): Promise { this.controller?.abort(); const controller = new AbortController(); this.controller = controller; update(this.realm, (_read, write) => write(this.$load, { state: "loading" })); try { const response = await fetch(`${positionsUrl}/${encodeURIComponent(account)}`, { signal: controller.signal, }); if (!response.ok) { throw new Error(`positions: the server answered ${response.status}`); } const body: unknown = await response.json(); if (!Array.isArray(body)) { throw new TypeError("positions: the body is not a list"); } const next = body.map(toPosition); if (controller.signal.aborted) { return; } update(this.realm, (read, write) => { // Unchanged positions keep their instance; nothing changed keeps the array. write( this.$rows, reconcile(read(this.$rows), next, { keyOf: (position) => position.id, equals: (previous, current) => previous.symbol === current.symbol && previous.quantity === current.quantity, }), ); write(this.$load, { state: "loaded" }); }); } catch (error) { // An aborted fetch rejects too; the newer call owns the status. if (controller.signal.aborted) { return; } update(this.realm, (_read, write) => write(this.$load, { state: "failed", error })); } } } ``` ## Rules - Write each message in one update. A reader then sees a snapshot whole or not at all; a write per row would show every row in between. - Write a snapshot through `write.replaceAll` on a collection with `equals`. An unchanged row keeps its instance, so a reconnect that sends the same quotes reruns no reader. `write.replaceAll` throws on a repeated key and writes nothing, so reject one at the boundary. - Await a request, then write its result in an update of its own: an update is synchronous ([Updates](../state/updates.md)). - Check that a request was not aborted before writing its result or its failure. An aborted `fetch` rejects, and without the check the older request's failure overwrites the newer one's `"loading"`. - The hook writes `"connecting"`, in an update. The cleanup writes nothing, so rows and status stay as last written while nothing observes the feed, and the next snapshot replaces the rows. - Keep a connection's state inside the call that opens it, and detach the socket's `onclose` before closing it, so a socket from an earlier observation schedules no reconnect. - A message the parser drops goes to the host's `reportError`, where a realm made without `onError` also reports. A realm made with `onError` does not see it. `onObserved` and atoms are on [Lifecycles](../state/lifecycles.md), the writes to a collection on [Collections](../state/collections.md), and `reconcile` on [Updates](../state/updates.md). ## With Effect The same feed as an Effect program. `Schema.fromJsonString` parses and checks a message in one step, and fails with a `SchemaError` for anything that does not fit. ```ts import { Schema } from "effect"; const Quote = Schema.Struct({ symbol: Schema.String, bid: Schema.Finite, ask: Schema.Finite, }); type Quote = typeof Quote.Type; const QuoteMessage = Schema.Union([ Schema.Struct({ type: Schema.Literal("snapshot"), quotes: Schema.Array(Quote) }), Schema.Struct({ type: Schema.Literal("upsert"), quote: Quote }), Schema.Struct({ type: Schema.Literal("delete"), symbol: Schema.String }), ]); type QuoteMessage = typeof QuoteMessage.Type; // Parses the JSON and checks it in one step; fails with a SchemaError. const decodeMessage = Schema.decodeUnknownEffect(Schema.fromJsonString(QuoteMessage)); ``` The watchlist is a `BoxField`, checked on every write: people type it, and it is saved with the board. The quotes are a plain collection and the status a plain box, written only from messages the decode checked, so nothing checks them twice ([Plain or schema boxes](../start/index.md#plain-or-schema-boxes)). Loosening a field's schema to make the feed fast would leave every other writer of that field unchecked; the hot rows go in a plain collection instead. ```ts import { BoxField, box, collection, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; type Status = "connecting" | "open" | "closed"; class QuoteBoard extends SchemaModel ("QuoteBoard")({ // Typed by people and saved with the board: every write is checked. $watchlist: BoxField(Schema.Array(Schema.String)), }) { // Written by the feed alone, from messages the decode checked: checked nowhere else. readonly $quotes = collection(this.realm, { keyOf: (quote: Quote) => quote.symbol, equals: Schema.toEquivalence(Quote), }); readonly $status = box (this.realm, "closed"); setStatus(status: Status): void { update(this.realm, (_read, write) => write(this.$status, status)); } add(symbol: string): void { update(this.realm, (read, write) => write(this.$watchlist, [...read(this.$watchlist), symbol])); } // One update per message: a reader sees all of it or none of it. receive(message: QuoteMessage): void { update(this.realm, (_read, write) => { switch (message.type) { case "snapshot": return write.replaceAll(this.$quotes, message.quotes); case "upsert": return write.upsert(this.$quotes, message.quote, { at: "end" }); case "delete": return write.remove(this.$quotes, message.symbol); } }); } } ``` `Stream.callback` turns the socket's callbacks into a stream. The socket opens in `Effect.acquireRelease`, so closing the stream's scope closes it, and a drop fails the stream with `SocketClosed`. ```ts import { Cause, Data, Effect, Queue, Stream } from "effect"; class SocketClosed extends Data.TaggedError("SocketClosed")<{ readonly code: number }> {} // Each message the socket receives. The stream fails with SocketClosed when // the socket closes, and closing the stream's scope closes the socket. const socket = (url: string, onOpen: () => void): Stream.Stream => Stream.callback ((queue) => Effect.acquireRelease( Effect.sync(() => { const next = new WebSocket(url); next.onopen = onOpen; next.onmessage = (event: MessageEvent) => { Queue.offerUnsafe(queue, String(event.data)); }; next.onclose = (event: CloseEvent) => { Queue.failCauseUnsafe(queue, Cause.fail(new SocketClosed({ code: event.code }))); }; return next; }), (next) => Effect.sync(() => { next.onclose = null; next.close(); }), ), ); ``` `changes` streams the watchlist, and `Stream.switchMap` closes the socket of the previous list and opens one for the new list. `Stream.retry` reopens the socket after a drop, and its schedule resets once a message passes through. Each message is decoded, then written in one update; a message that fails either step is logged and dropped. ```ts import { changes } from "@frondruntime/pinna-effect"; import { Effect, Schedule, Stream } from "effect"; const quotesUrl = "wss://example.com/quotes"; // 0.5 s after a drop, doubling up to 30 s; a message that arrives resets it. const reconnect = Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("30 seconds")]); // Follows the board's watchlist: a new list closes the socket and opens one for it. const follow = Effect.fn("follow")(function* (board: QuoteBoard) { yield* changes(board.$watchlist).pipe( Stream.switchMap((symbols) => { const url = `${quotesUrl}?symbols=${symbols.map(encodeURIComponent).join(",")}`; return socket(url, () => board.setStatus("open")).pipe( Stream.onStart(Effect.sync(() => board.setStatus("connecting"))), Stream.tapError(() => Effect.sync(() => board.setStatus("closed"))), Stream.retry(reconnect), ); }), Stream.runForEach((data) => decodeMessage(data).pipe( // A write that throws, such as a snapshot that repeats a symbol, is undone. Effect.flatMap((message) => Effect.try(() => board.receive(message))), Effect.catch((error) => Effect.logWarning("quotes: dropped a message", error)), ), ), ); }); ``` A layer provides the realm. The fiber owns the feed: the socket is open while the fiber runs, whether or not anything observes the board, and interrupting the fiber closes it. A value that should run only while a screen shows it is owned by observation instead, through `fromStream` ([Programs](../effect/programs.md#lifetimes)). ```ts import { createRealm, decode, RealmService } from "@frondruntime/pinna-effect"; import { Effect, Fiber, Layer } from "effect"; const realm = createRealm(); const RealmLive = Layer.succeed(RealmService, realm); // Throws the SchemaError when the saved board does not fit. const board = decode(realm, QuoteBoard)({ watchlist: ["ACME", "GLOBEX"] }); // The socket is open while the fiber runs. const fiber = Effect.runFork(follow(board).pipe(Effect.provide(RealmLive))); // Interrupting the fiber closes the socket. const close = () => Effect.runFork(Fiber.interrupt(fiber)); ``` - Wrap the write in `Effect.try`. A throw inside `Effect.sync` is a defect, and a defect in `Stream.runForEach` ends the program, socket and all. `Effect.try` makes it an error the program logs; the update has already undone the write. - Write each status in the stage that knows it: `Stream.onStart` for `"connecting"`, the socket's `onopen` for `"open"`, and `Stream.tapError`, before `Stream.retry`, for `"closed"`. Without `Stream.tapError`, the status stays `"open"` through every reconnect wait. ## See also - [Lifecycles](../state/lifecycles.md): `onObserved`, atoms, and `observe`. - [Collections](../state/collections.md): `keys`, `row(key)`, and `equals`. - [Updates](../state/updates.md): what an update undoes when it throws. - [Programs](../effect/programs.md): `changes`, `watchScoped`, `fromStream`, and who owns a feed. - [Classes](../effect/classes.md): `SchemaModel`, `BoxField`, and `decode`. - [Hooks](../react/hooks.md): `useValue` and a list that rerenders one row. --- # Indexes and sets URL: https://pinna.frondruntime.dev/docs/guides/row-indexes Description: Read when a value follows a collection a row at a time. Keep a set of keys, the keys of each group, and a sum per group, with collections, boxes, and onRowChange. ## Example Each structure on this page takes a few lines over the calls on [Collections](../state/collections.md); Pinna has no call for any of them. `onRowChange` keeps a structure in step with a collection a row at a time. The samples share one collection of orders, with amounts in whole cents. ```ts import { collection, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); interface Order { readonly id: string; readonly customer: string; /** Whole cents, so a sum kept by adding and subtracting stays exact. */ readonly cents: number; } const $orders = collection(realm, { keyOf: (order: Order) => order.id, equals: (previous, next) => previous.customer === next.customer && previous.cents === next.cents, }); ``` A set of keys is a collection keyed by the key itself. `read.row` tracks one key, so a row that asks whether it is selected reruns only when its own key joins or leaves the set. An array in a box reruns every such reader on each change, and each one scans the array. ```ts import { collection, computedFunction, update } from "@frondruntime/pinna"; // A set of order ids: a collection keyed by the id itself. const $selected = collection(realm, { keyOf: (id: string) => id }); const toggleSelected = (id: string) => { update(realm, (read, write) => { if (read.row($selected, id) === undefined) { write.upsert($selected, id); } else { write.remove($selected, id); } }); }; // Tracks one id: selecting another order reruns nothing here. const isSelected = computedFunction( realm, (read, id: string) => read.row($selected, id) !== undefined, ); ``` A value per group, such as its keys or its sum, is one box per group, made on the first ask. A map of groups in one box copies every group on each change and reruns every reader of every group. ```ts import { type Box, box, type Realm } from "@frondruntime/pinna"; // One box per key, made on the first ask. The map holds boxes, never values, // so a write that fails puts back what the boxes hold and leaves at most an // empty box behind. const boxPerKey = (realm: Realm, initial: Value) => { const boxes = new Map >(); return (key: Key): Box => { let $value = boxes.get(key); if ($value === undefined) { $value = box(realm, initial); boxes.set(key, $value); } return $value; }; }; ``` The ids of each customer's orders. `onRowChange` reports a row `before` and `after` the write, so an order that moves to another customer leaves one group and joins the other in the same report. ```ts import { onRowChange } from "@frondruntime/pinna"; // The ids of each customer's orders. A write to one customer's orders reruns // the readers of that customer alone. const ordersOf = boxPerKey >(realm, []); const stopOrdersOf = onRowChange($orders, ({ key, before, after }, read, write) => { if (before?.customer === after?.customer) { return; // a new amount under the same customer moves no id } if (before !== undefined) { const $ids = ordersOf(before.customer); write( $ids, read($ids).filter((id) => id !== key), ); } if (after !== undefined) { const $ids = ordersOf(after.customer); write($ids, [...read($ids), key]); } }); ``` A sum per customer subtracts the row `before` and adds the row `after`: two writes per change, however many orders the customer has. ```ts import { onRowChange } from "@frondruntime/pinna"; // The sum of each customer's orders, in cents. const totalOf = boxPerKey (realm, 0); const stopTotalOf = onRowChange($orders, ({ before, after }, read, write) => { if (before !== undefined) { const $total = totalOf(before.customer); write($total, read($total) - before.cents); } if (after !== undefined) { const $total = totalOf(after.customer); write($total, read($total) + after.cents); } }); ``` A graph is a collection of edges with two such indexes, one by source and one by target. A walk over it, such as every key reachable from one key, is a function that reads them, run in a `computed` or an update, and reruns in full on each change it reads. Rows kept in sorted order are on [Collections](../state/collections.md#sorted-rows). ## Rules - Keep what a listener builds in boxes and collections, so a failed write puts it back with the row ([Collections](../state/collections.md)). - Skip a report that leaves a row's group as it was. Removing the key and adding it again moves it to the end of its group and reruns that group's readers for nothing. - Keep amounts as integers. Each floating-point add and subtract rounds, so a sum kept that way drifts from the sum of its rows. - A change copies the group it writes, as a collection copies its key order when a key is added or removed. - A `computed` over `rows` derives the same values with no listener, and reruns over every row on each change. It fits a collection that is small or rarely written. ## See also - [Collections](../state/collections.md): `onRowChange`, `read.row`, what each write reports, and sorted rows. - [Updates](../state/updates.md): the update a listener runs in, and what a failed one puts back. - [Collection fields](../effect/collections.md): a collection as a field of a `SchemaModel`. --- # Saving state URL: https://pinna.frondruntime.dev/docs/guides/saving Description: Read when state outlives a reload. Save a computed projection of what to keep, restore before the watch starts, write a burst of changes once, skip a save that changes nothing, keep a storage error as state, and write a pending save on dispose. ## Example A workspace keeps a theme and whether the sidebar is open across reloads, in `localStorage`. The storage is passed in, so a test hands the model one that keeps the saves in memory, or one that refuses them. ```ts interface SettingsStorage { readonly load: () => string | undefined; // Throws when the storage refuses the write, as a full localStorage does. readonly save: (text: string) => void; } const browserStorage: SettingsStorage = { load: () => localStorage.getItem("workspace") ?? undefined, save: (text) => localStorage.setItem("workspace", text), }; ``` The model saves a computed projection: `$saved` is the text to store, built from the boxes that are saved and from nothing else. `$hovered` is shown on screen and never saved: `$saved` does not read it, so a write to it neither recomputes `$saved` nor runs the watch. The constructor and `flush` read `$saved` through `untracked`, which reads without subscribing. ```ts import { box, computed, Model, type Realm, untracked, update, watch } from "@frondruntime/pinna"; type Theme = "light" | "dark"; class Workspace extends Model implements Disposable { readonly $theme = box (this.realm, "light"); readonly $sidebarOpen = box(this.realm, true); // Shown, never saved: a restart begins with nothing hovered. readonly $hovered = box (this.realm, undefined); readonly $storageError = box (this.realm, undefined); // The text to save, and nothing else: it never reads $hovered, so a write // to $hovered leaves it, and the watch below, untouched. private readonly $saved = computed(this.realm, (read) => JSON.stringify({ theme: read(this.$theme), sidebarOpen: read(this.$sidebarOpen) }), ); private readonly storage: SettingsStorage; private readonly stopSaving: () => void; private queued = false; private lastSaved: string; constructor(realm: Realm, storage: SettingsStorage) { super(realm); this.storage = storage; // Restored before the watch starts, so restoring saves nothing back. this.restore(); this.lastSaved = untracked(realm, (read) => read(this.$saved)); this.stopSaving = watch( realm, (read) => read(this.$saved), () => { this.queue(); }, ); } private restore() { const text = this.storage.load(); if (text === undefined) return; let saved: { readonly theme?: unknown; readonly sidebarOpen?: unknown } | null; try { saved = JSON.parse(text); } catch { return; // a damaged save starts from the defaults } // Each field is taken only when it is valid, so one bad field keeps the rest. update(this.realm, (_read, write) => { if (saved?.theme === "light" || saved?.theme === "dark") write(this.$theme, saved.theme); if (typeof saved?.sidebarOpen === "boolean") write(this.$sidebarOpen, saved.sidebarOpen); }); } // A burst of updates in one task queues one save, which reads the end state. private queue() { if (this.queued) return; this.queued = true; queueMicrotask(() => this.flush()); } flush() { if (!this.queued) return; this.queued = false; const text = untracked(this.realm, (read) => read(this.$saved)); if (text === this.lastSaved) return; // the burst ended where it began try { this.storage.save(text); this.lastSaved = text; update(this.realm, (_read, write) => write(this.$storageError, undefined)); } catch (error) { // Kept as state for the screen to show; the next change tries again. const message = error instanceof Error ? error.message : String(error); update(this.realm, (_read, write) => write(this.$storageError, message)); } } [Symbol.dispose]() { this.stopSaving(); this.flush(); // a save still queued is written now, not lost } } ``` The workspace is made once, in module code. ```ts import { createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const workspace = new Workspace(realm, browserStorage); ``` ## Rules - Save a `computed` that builds the stored text, not the boxes one by one. The watch runs only when that text changes, so state the screen shows but the save leaves out, such as a hover or a selection, writes nothing to the storage. - Restore before starting the watch, and set the last saved text from the restored state. A restore after the watch starts writes boxes the watch reads, which queues a save of what the restore loaded. - Take each restored field only when it is valid, and keep the default for the rest. A save written by an older version, or edited by hand, then loses one field, not the whole workspace; text that does not parse starts from the defaults. - Queue the save with `queueMicrotask`, read the text when it runs, and skip it when the text equals the last one written. A watch runs once per outermost update, so an event handler that makes several updates runs it several times; the queued save runs once, after the handler returns, and a burst that ends where it began, such as a toggle clicked twice, writes nothing. - Catch a storage error in `flush` and write it to a box. `flush` runs from a microtask, where a throw reaches no caller; as state, the screen shows it. The last saved text stays as it was, so the next change saves again. - Dispose with `using` or `[Symbol.dispose]()`: it stops the watch, then writes a save still queued, at once. A workspace made right after the dispose loads what it saved, and a test realm's dispose finds no watch still running. ## With Effect Stored text comes from outside the program: an older version wrote it, or a person edited it. With Effect, `restore` decodes it through a schema instead of checking each field by hand, so the check and the type come from one declaration and cannot drift apart. Each field recovers from a refusal with `Schema.catchDecoding` and decodes to no field at all, so one bad field keeps its default and the others still restore. ```ts import { Effect, Option, Schema } from "effect"; // A field the schema refuses decodes to no field at all, so it keeps its // default and the other fields still restore. const SavedSettings = Schema.fromJsonString( Schema.Struct({ theme: Schema.optionalKey( Schema.Literals(["light", "dark"]).pipe(Schema.catchDecoding(() => Effect.succeedNone)), ), sidebarOpen: Schema.optionalKey( Schema.Boolean.pipe(Schema.catchDecoding(() => Effect.succeedNone)), ), }), ); // Text that does not parse decodes to no fields, so the workspace keeps its defaults. const readSaved = (text: string): typeof SavedSettings.Type => Schema.decodeUnknownOption(SavedSettings)(text).pipe(Option.getOrElse(() => ({}))); ``` `restore` writes each field `readSaved` returns, in one update. The boxes stay plain: the workspace writes them itself, so only the restore needs the check. ## See also - [Reacting](../state/reacting.md): `watch` and when its effect runs. - [Updates](../state/updates.md): an effect that cannot be taken back runs after the update. - [Boxes and computed](../state/boxes.md): a `Model` and its `$` fields. - [Testing](./testing.md): `testRealm`, and the dispose that finds a watch still running. - [Errors](./errors.md#fields-a-schema-refuses): what a schema reports for a field it refuses. --- # Testing URL: https://pinna.frondruntime.dev/docs/guides/testing Description: Read when writing tests. Make a test realm per test, read and write as application code does, record what a select changed to, check what a collection still holds, and test models and programs with Effect. ## Example The state under test is a model: a class that extends `Model`, so each test can make one in a realm of its own. ```ts import { box, computed, Model, update } from "@frondruntime/pinna"; // The state under test: a count of open todos and the method that closes one. class Todos extends Model { readonly $open = box(this.realm, 2); readonly $label = computed(this.realm, (read) => `${read(this.$open)} open`); close(): void { update(this.realm, (read, write) => { if (read(this.$open) === 0) throw new Error("nothing is open"); write(this.$open, read(this.$open) - 1); }); } } ``` A test makes its own realm with `testRealm` from `@frondruntime/pinna/testing` and builds its state in it. It reads through `untracked` and writes through the methods that call `update`, as an event handler does. Held with `using`, the realm is disposed when the test ends, and its dispose throws if a watch, an autorun, an `observe`, an `onRowChange` listener, or a stage is still running. ```ts import { expect, test } from "bun:test"; import { untracked } from "@frondruntime/pinna"; import { testRealm } from "@frondruntime/pinna/testing"; test("closing a todo updates the label", () => { // A realm per test: nothing one test made is seen by the next. Its dispose, // when the test ends, throws if a watch or an autorun is still running. using realm = testRealm(); const todos = new Todos(realm); todos.close(); expect(untracked(realm, (read) => read(todos.$label))).toBe("1 open"); }); ``` `record` keeps each value a select changes to, in `values`, and stops when its `using` scope ends. Each update reruns it once, after the update ends, and only when the value changed, so `values.length` counts the changes. ```ts import { expect, test } from "bun:test"; import { update } from "@frondruntime/pinna"; import { record, testRealm } from "@frondruntime/pinna/testing"; test("closing two todos in one update records one change", () => { using realm = testRealm(); const todos = new Todos(realm); // Declared after the realm, so it stops before the realm checks. using labels = record(realm, (read) => read(todos.$label)); update(realm, () => { todos.close(); todos.close(); }); expect(labels.values).toEqual(["0 open"]); }); ``` An update that throws leaves the realm as it was. ```ts import { expect, test } from "bun:test"; import { untracked, update } from "@frondruntime/pinna"; import { testRealm } from "@frondruntime/pinna/testing"; test("an update that throws leaves the realm as it was", () => { using realm = testRealm(); const todos = new Todos(realm); expect(() => update(realm, () => { todos.close(); todos.close(); todos.close(); // nothing is open: throws, and the two before it are undone }), ).toThrow("nothing is open"); expect(untracked(realm, (read) => read(todos.$open))).toBe(2); }); ``` `retainedKeys` names the keys a collection still keeps something for: a row, or the box and computed value a reader made for a key. A test of a feed that removes rows checks that this set is exactly the keys that remain, so a removed row that stays in memory fails the test, which a count of the rows would not show. ```ts import { expect, test } from "bun:test"; import { collection, observe, update } from "@frondruntime/pinna"; import { retainedKeys, testRealm } from "@frondruntime/pinna/testing"; test("a refetch lets go of the rows it drops", () => { using realm = testRealm(); const $trades = collection(realm, { keyOf: (trade: { readonly id: string }) => trade.id }); update(realm, (_read, write) => { write.replaceAll($trades, [{ id: "a" }, { id: "b" }, { id: "c" }]); }); // A reader of a row makes a box and a computed value for its key. const release = observe($trades.row("c")); update(realm, (_read, write) => { write.replaceAll($trades, [{ id: "a" }]); }); // "c" is gone with its box and computed value, though still observed. expect(retainedKeys($trades)).toEqual(new Set(["a"])); release(); }); ``` ## Rules - One realm per test, made with `using realm = testRealm()`. A realm made at module level carries state from one test into the next. - Read with `untracked(realm, (read) => ...)`, write with `update` or a model method that calls it. The testing entry adds no reader or writer, so a test goes through the same calls as application code. - A watch's effect runs after the outermost update ends, so a test that records values asserts after the update returns. - Declare the realm before the recordings: `using` disposes in reverse order, so each recording stops before the realm checks. - Stop every watch, autorun, `observe`, and `onRowChange` listener a test starts, and apply or drop every stage. One left running keeps its values cached and its `onObserved` hooks started, and a stage left open holds its overlay, so the test realm's dispose throws, naming each by its `name`, or `watch`, `autorun`, `onRowChange`, or `stage`, and stops it so the next test starts clean; a stage is dropped. A React component's subscription is not counted. - Hold each one in `using`: a watch through `record`, the rest through `held`, as in `using _ = held(autorun(realm, ...))`. A stop function called at the end of the test is skipped when an assertion fails, the dispose then throws too, and Bun 1.4.4 prints the resulting `SuppressedError` without either error, so the assertion's diff is lost. - Check what a collection holds with `retainedKeys`, never through its private fields: they are not part of the API and change without notice. ## Answers | Call | Answers | | --- | --- | | `testRealm(options?)` | A realm of the test's own; its dispose throws if a watch, an autorun, an `observe`, an `onRowChange` listener, or a stage is still running. | | `record(realm, select, options?)` | `values`, each value `select` changed to, oldest first; `stop`, which `using` also runs. | | `held(stop)` | A `Disposable` that runs `stop` when its `using` scope ends. | | `retainedKeys($items)` | A copy of the set of keys `$items` keeps a row, a box, or a computed value for; every one is a present key. Throws for a value that is not a collection Pinna made. | ## With Effect A model decoded from `pinna-effect` is tested the same way. The `TodoList` and its wire data, `items`, are the ones from [Collection fields](../effect/collections.md). ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { decode, untracked } from "@frondruntime/pinna-effect"; import { TodoList } from "./models.ts"; test("toggling a todo closes it", () => { // A realm per test: nothing one test made is seen by the next. using realm = testRealm(); const list = decode(realm, TodoList)({ items }); const first = untracked(realm, (read) => read(list.$items.row("1"))); first?.toggle(); expect(untracked(realm, (read) => read(list.$open))).toBe(0); }); ``` A watch on the model and a write the schema rejects behave as above: one rerun per update, and a rejected write leaves the realm as it was. An Effect program takes the test's realm: `watchScoped(realm, ...)` and `fromStream(realm, ...)` take it first, and `changes`, `observeScoped`, and `whileObserved` take it from the observable. A `SchemaModel` decoded inside an Effect program reads it from `RealmService`, which the test provides. A `Deferred` waits for the watch's effect without a sleep. Close every program's scope: a program left running keeps its values cached and its `onObserved` hooks started, and the test realm's dispose throws for its watch. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { RealmService, schemaBox, update, watchScoped } from "@frondruntime/pinna-effect"; import { Deferred, Effect, Schema } from "effect"; test("a program reads the test's realm", async () => { using realm = testRealm(); const $query = schemaBox(realm, Schema.String, ""); const program = Effect.gen(function* () { const searched = yield* Deferred.make (); yield* watchScoped( realm, (read) => read($query), (query) => Deferred.succeed(searched, query), ); update(realm, (_read, write) => write($query, "pinna")); return yield* Deferred.await(searched); }); const query = await Effect.runPromise( program.pipe(Effect.scoped, Effect.provideService(RealmService, realm)), ); expect(query).toBe("pinna"); }); ``` | Call | Answers | | --- | --- | | `decode(realm, Model)(json)` | A model in the test's realm. | | `Effect.provideService(RealmService, realm)` | A `SchemaModel` decoded inside the program lands in the test's realm. | A program that polls or sleeps runs on `TestClock`: [Programs](../effect/programs.md#testing) shows where to provide it and what a test waits on instead of the clock. ## See also - [Updates](../state/updates.md): what an update undoes when it throws. - [Reacting](../state/reacting.md): when a watch reruns. - [Programs](../effect/programs.md): `watchScoped`, `withStage`, and testing a program on `TestClock`. - [Errors and debugging](./errors.md): what throws, and where the rest goes. --- # Errors and debugging URL: https://pinna.frondruntime.dev/docs/guides/errors Description: Read when something throws or reruns unexpectedly. Know which errors reach the caller and which go to onError, how a computed value keeps its error, find why a value recomputed with inspect and names, and know the errors Effect adds. ## Example A realm takes `onError`: where an error goes when there is no caller to throw to. `report` stands for the application's own error reporter. ```ts import { createRealm } from "@frondruntime/pinna"; // Errors with no caller to throw to: a watch effect's, an autorun's after // its first run, an onObserved hook's. The host's reportError by default. const realm = createRealm({ onError: (error) => report(error) }); ``` A computed value that throws keeps the error as its value. Every read rethrows it, and it computes again only when what it read changes. ```ts import { box, computed, update } from "@frondruntime/pinna"; const $count = box(realm, 1, { name: "count" }); const $inverse = computed( realm, (read) => { const count = read($count); if (count === 0) throw new Error("no inverse of zero"); return 1 / count; }, { name: "inverse" }, ); update(realm, (_read, write) => write($count, 0)); // Every read of $inverse throws "no inverse of zero" until $count changes. ``` A watch effect runs after the write has landed, so its error goes to `onError`, not to the writer. ```ts import { update, watch } from "@frondruntime/pinna"; const stop = watch( realm, (read) => read($count), (count) => { if (count > 10) throw new Error(`too many: ${count}`); }, ); // The write lands; the effect's error goes to onError, and the watch keeps running. update(realm, (_read, write) => write($count, 11)); ``` `inspect` reports what a value last read, how many observe it, and, for a named computed value, why it last recomputed. It reports one level; inspect a dependency to go further. ```ts import { inspect, update, watch } from "@frondruntime/pinna"; update(realm, (_read, write) => write($count, 2)); const stopInverse = watch( realm, (read) => read($inverse), () => undefined, ); update(realm, (_read, write) => write($count, 4)); inspect($inverse); // { name: "inverse", realm: undefined, dependencies: ["count"], observers: 1, // lastReason: "count changed" } ``` ## Rules - Errors with a caller throw to it: every misuse throws from the call that made it, and an update that throws rolls back. An `onError` that throws while a write's watchers run throws to the writer, with the writes in place. - Errors without one go to `onError`: a watch effect's, an autorun's after its first run, an `onObserved` hook's or cleanup's, and watchers that never settle. The first run of a `watch` or `autorun` throws to the caller, and nothing is watched. - Name what gets debugged: `{ name }` on a box or a computed value. A named computed value keeps why it last recomputed, and its errors name it. An unnamed one costs nothing for names. - Pinna has no development mode. Every check runs in every build. ## Answers | Call | Answers | | --- | --- | | `inspect($x)` | `{ name, realm, dependencies, observers, lastReason }`. `realm` is the name of the realm that made the value, `undefined` for an unnamed realm. | Every message Pinna throws, with its cause and fix, is on [Error messages](../reference/errors.md). ## With Effect A schema adds errors with a caller, and a program has a place for defects. - A write the schema of a [`schemaBox`](../effect/boxes.md) or a `BoxField` refuses throws from the write, and the update rolls back. The error's `cause` is the `Schema.SchemaError` that says what did not fit. A row a [collection field](../effect/collections.md) refuses throws the same error. - `decode` throws `Schema.SchemaError` for input that does not fit the schema. - A [program's](../effect/programs.md) defect is logged at the error level through Effect's logger. A `watchScoped` watch keeps running; a `fromStream` stream or a `whileObserved` run ends, and the next observation starts it again. Their messages are on [Error messages](../reference/errors.md#with-effect). ### Fields a schema refuses A form shows each refused field beside its input, so it needs the field's path and a message, not the error's text. A filter made with `Schema.makeFilter` gives its own message when it returns a string in place of `false`. ```ts import { Schema } from "effect"; // A filter that returns a string fails with that string as its message. const Password = Schema.String.check( Schema.makeFilter((password) => password.length >= 8 || "Use at least 8 characters"), ); const Signup = Schema.Struct({ email: Schema.String, password: Password }); ``` The `Schema.SchemaError` holds an `issue`, and `SchemaIssue.makeFormatterStandardSchemaV1()` turns it into a list of `{ path, message }`. `decode` throws the `SchemaError` itself; a write a box refuses throws an `Error` whose `cause` is the `SchemaError`. ```ts import { Schema, SchemaIssue } from "effect"; const toStandard = SchemaIssue.makeFormatterStandardSchemaV1(); // Each refused field's path and message. `decode` throws the SchemaError; a // write a box refuses throws an Error whose `cause` is the SchemaError. // Anything else is not a schema's refusal, and is thrown again. const issuesOf = (error: unknown) => { const schemaError = error instanceof Error && !Schema.isSchemaError(error) ? error.cause : error; if (!Schema.isSchemaError(schemaError)) { throw error; } return toStandard(schemaError.issue).issues; }; ``` ```ts import { createRealm, decode, schemaBox, update } from "@frondruntime/pinna-effect"; const realm = createRealm(); const $signup = schemaBox(realm, Signup, { email: "", password: "correct horse" }); const submit = (input: unknown) => { try { return { signup: decode(realm, Signup)(input), issues: [] }; } catch (error) { // [{ path: ["password"], message: "Use at least 8 characters" }] return { signup: undefined, issues: issuesOf(error) }; } }; const editPassword = (password: string) => { try { update(realm, (read, write) => { write($signup, { ...read($signup), password }); }); return []; } catch (error) { return issuesOf(error); } }; ``` - `decode` stops at the first field it refuses, so for a struct such as `Signup` the list holds one issue: input with two bad fields reports the first. A union, or a filter that returns several issues, reports more. - A field that is absent reads as `Missing key` at its path, and a value of the wrong type as `Expected` and the type, such as `Expected string`. - A refused write leaves the box as it was, as every update that throws does, so the form keeps the last value that fit. - An error that is neither is no schema's refusal, such as a failed request, and is thrown again rather than shown as a field's message. ## See also - [Updates](../state/updates.md): what an update undoes when it throws. - [Reacting](../state/reacting.md): watch and autorun, and their first run. - [Programs](../effect/programs.md): how a program reports a defect. - [Error messages](../reference/errors.md): every message, its cause, and the fix. - [Testing](./testing.md): asserting on a rejected write. - [Schema-checked boxes](../effect/boxes.md): what a box checks, and when. --- # Error messages URL: https://pinna.frondruntime.dev/docs/reference/errors Description: Read when Pinna throws or logs a message. Every message Pinna and pinna-effect throw or log, what caused it, and the fix. This page lists every message Pinna and `@frondruntime/pinna-effect` throw or log, grouped by the call that causes it, with the cause and the fix. [Errors and debugging](../guides/errors.md) covers where an error goes and how to find why a value recomputed. ## Rules - Every message starts with `pinna: `, except the test realm's ([Testing](../guides/testing.md)). - A part in angle brackets is filled in. ` ` is the value's `{ name }`. Without one, a `read` or a `write` message prints `$observable`, and a message from a computed value prints `a derived value`. - A `read` or a `write` message puts the name in quotes, such as `read("count")`. ## Answers ### Reading and writing | Error | Answers | | --- | --- | | `pinna: read( ) runs outside a place. ...` | A `read` used outside every place of its realm, such as one kept in a closure. Pass `read` down instead. | | `pinna: read.row($collection, key) runs outside a place. ...` | The same, for `read.row`. | | `pinna: write inside update` | A `write` kept past its update. | | `pinna: ( ) is handed an observable of another realm. ...` | A `read` or a `write` of one realm given what another realm made. ` ` is `read`, `read.row`, `write`, `write.modify`, `write.upsert`, `write.remove`, `write.replaceAll`, or `write.changed`. A realm made with `createRealm({ name })` is named in the message, such as `(realm "quotes", not "ui")`. Build each observable from the realm that reads it. | | `pinna: needs a box, a computed value, or an atom` | `onObserved`, `observe`, or `inspect` given a value Pinna did not make. | | `pinna: expected a box, a computed value, or an atom` | `useValues` given a value Pinna did not make. | ### Updates | Error | Answers | | --- | --- | | `pinna: update cannot run in a computed value; ...` | An update inside a computed value or a computed function's value. Write from an event, a watch's effect, or an autorun. `onRowChange` called there says `onRowChange` in place of `update`. | | `pinna: update cannot run in a watch's select or a selector; ...` | An update inside a watch's select or a `useSelect` function. Write from an event, a watch's effect, or an autorun. `onRowChange` called there says `onRowChange` in place of `update`. | | `pinna: update recipes are synchronous; await outside, then update` | A recipe that returned a promise. The update is undone. Await outside, then update. | | `pinna: an update recipe returns nothing` | A recipe that returned a value other than `undefined` or a promise. The update is undone. | | `pinna: cannot write while it computes` | A computed value that wrote, through a `write` kept from an update. | ### Stages | Error | Answers | | --- | --- | | `pinna: runs on a stage after it was ; ...` | A `StageClosedError`: a stage call after `applyStage` or `dropStage` closed it. ` ` is `stageUpdate`, `stageRead`, `realmRead`, `applyStage`, or `openStage` of a child; a named stage reads `the stage " "`. `stageStatus` and `inspectStage` remain callable outside a recipe after closing. `dropStage` on a closed stage does nothing. | | `pinna: applyStage finds that changed since the stage read ; nothing lands` | A `StageConflictError`: a stage opened with `{ conflicts: "fail" }` read a box or a collection that changed in the realm before it landed. ` ` names each by its `{ name }`: an unnamed box is ` `, an unnamed collection `a collection`. The stage is dropped. Retry the work over the new values, or open the stage without the option to replay over them. | | `pinna: of a stage runs after its recipe returned; ...` | A `read` or a `write` a stage handed out, kept past its recipe. ` ` is `read`, `read.row`, `write`, `write.modify`, `write.upsert`, `write.remove`, `write.replaceAll`, or `write.changed`. | | `pinna: runs inside a stage recipe, ...` | A stage call, `onObserved`, or `onRowChange` on the stage's realm inside a recipe, a `stageRead` function, or a computed value the stage evaluates. Call it outside the recipe or evaluation. | | `pinna: a stage recipe writes the realm, through update or a write kept from one; ...` | A realm write inside a stage recipe, which would show at once and survive a drop. Write through the recipe's own `write`. | | `pinna: read( ) of the realm runs inside a stage recipe, ...` | A `read` of the stage's realm, kept from another place, inside a recipe, a `stageRead` function, or a computed value the stage evaluates, where it would skip the stage's values. `read.row` and `untracked` say so in its place. Read through the stage's `read`. | | `pinna: is made inside a stage recipe, ...` | A box, a computed value, a computed function, an atom, a collection, or a model made on the stage's realm inside a recipe, a `stageRead` function, or a computed value the stage evaluates; replay would make it again. Make it outside and close over it. | | `pinna: a stage recipe cannot observe or release while it computes` | A `watch`, an `autorun`, or an `observe` started inside a stage recipe. | | `pinna: runs in stageRead, which writes nothing; write in stageUpdate` | A write inside a `stageRead` function, such as a `reconcileSchema` merge. | | `pinna: applyStage runs on a stage while a child stage of it is open; ...` | A precondition failure: the stage stays open. Apply or drop the child first. | | `pinna: conflicts is "replay" or "fail", not ` | `openStage` given another `conflicts` value, from code the types did not check. | | `pinna: a child stage takes no conflicts option; ...` | `openStage(stage, { conflicts })`. The root stage's option covers what its children read. | | `pinna: is read while a stage evaluates it (cycle)` | A computed value that reads itself, read through a stage. | | `pinna: stageUpdate cannot run in a computed value; ...` | As for `update`, with `stageUpdate` or `applyStage` in its place, and the same for a watch's select or a selector. This precondition failure leaves the stage open. | | `pinna: stageRead cannot run in a computed value; ...` | `stageRead` or `realmRead` in a computed value, a watch's select, or a selector: a stage's reads are not tracked, so the derivation would go stale. | | `pinna: stageUpdate recipes are synchronous; await outside, then stageUpdate` | A `stageUpdate` recipe that returned a promise. Its writes to the stage are put back. | | `pinna: a stageUpdate recipe returns nothing` | A `stageUpdate` recipe that returned a value other than `undefined` or a promise. | | `StageConflict` | Not thrown: `withStage` fails with this tagged error on a conflict, in the error channel, where `Effect.catchTag` and `Effect.retry` take it. | ### Drafts | Error | Answers | | --- | --- | | `pinna: write.modify drafts arrays and plain objects; ...` | `write.modify` on a box holding another kind of value. Write it whole with `write($box, value)`. | | `pinna: a modify recipe returns nothing; write through the draft` | A `write.modify` recipe that returned a value. | | `pinna: a draft is used after its recipe returned` | A draft kept past its recipe. | | `pinna: write.modify left an object it wrote under two keys; ...` | A recipe wrote a draft and left it at a second key, inside itself, or inside an object the recipe placed at two keys, such as `draft.history.push(draft.present)` followed by a write to `draft.present`. The update is undone. Refer to the object by a key, or read a snapshot with `read($box)` before the write. | | `pinna: a draft does not take defineProperty; assign instead` | `Object.defineProperty` on a draft. | | `pinna: a draft cannot change its prototype` | `Object.setPrototypeOf` on a draft. | ### Declaring | Error | Answers | | --- | --- | | `pinna: a name is a non-empty string` | `{ name: "" }`. | | `pinna: box takes a value, not a schema; ...` | `box` given an Effect schema. A box that checks a schema is `schemaBox` from `@frondruntime/pinna-effect`. | ### Computed values and watchers | Error | Answers | | --- | --- | | `pinna: is read while it computes (cycle)` | A computed value that reads itself, directly or through others. | | `pinna: cannot observe or release while it computes` | A `watch`, an `autorun`, an `observe`, or a release inside a computed value. | | `pinna: watchers did not settle after 100 rounds` | Sent to `onError`: watchers kept changing what they read, such as an autorun that writes what it reads on every run. Make the write settle. | | `pinna: onObserved hooks did not settle after 100 passes` | Sent to `onError`: hooks kept starting other hooks. The hooks still due wait for the next settle. | ### Collections | Error | Answers | | --- | --- | | `pinna: the collection key appears twice` | A [collection](../state/collections.md)'s `write.replaceAll` given two rows of one key. Nothing is written. | | `pinna: reconcile: the key appears twice` | `reconcile` given two items of one key in `next`. | | `pinna: on the collection an onRowChange listener is reporting; ...` | A listener that wrote the collection it listens to. ` ` is `write.upsert`, `write.remove`, or `write.replaceAll`. The write fails and is put back. | | `pinna: onRowChange on the collection an onRowChange listener is reporting` | A listener that added another listener to the collection it listens to. | | `pinna: an onRowChange listener is synchronous and returns nothing` | A listener that returned a value, such as a promise. The write fails and is put back. | | `pinna: onRowChange needs a collection made by Pinna` | `onRowChange` given a value Pinna did not make. | ### React | Error | Answers | | --- | --- | | `pinna: useRealm and useSelect need a RealmProvider above the component` | `useRealm` or `useSelect` with no `RealmProvider` above. `useValue` and `useValues` need none. | | `pinna: expected a realm made by createRealm()` | `useSelect` under a `RealmProvider` given something other than a realm. | | `pinna: useValues takes observables of one realm` | `useValues` given observables of two realms; named realms are named in the message. | ## With Effect | Error | Answers | | --- | --- | | `pinna: the box rejects this value: ...` | A write the schema refused, with the `Schema.SchemaError` as its `cause`. The update rolled back. | | `pinna: Todo.a and Todo.b both read "key"; rename one` | Two fields under one wire key, thrown when the class is defined. The other naming errors are on [Classes](../effect/classes.md). | | `pinna: the collection key appears twice` | Also a `decode` of a [collection field](../effect/collections.md) given two rows of one key, inside the `Schema.SchemaError`. | | `pinna: a watch effect died`, `pinna: a stream into a value died`, `pinna: a program run while observed died` | Logged at the error level, with the defect as its cause: a `watchScoped` effect, a `fromStream` stream, or a `whileObserved` program died. The watch keeps running. A stream's value keeps its last element while observed and resets to `initial` when the last observer leaves. The next observation starts a stream or a program again. | | `Schema.SchemaError` | `decode` input that does not fit the schema. | ## See also - [Errors and debugging](../guides/errors.md): which errors reach the caller, which go to `onError`, and `inspect`. - [Updates](../state/updates.md): what an update undoes when it throws. - [Collections](../state/collections.md): the writes that report a repeated key. - [Classes](../effect/classes.md): the naming errors a `SchemaModel` throws when it is defined.