Sync / foldkit-sync
Growing the application
Compose a document from features
Each feature declares the fields it shares and the Messages that change them;
compose merges them into one document:
const AppSync = forApplication(App)
const Todos = AppSync.fragment({
shared: Projection.pick(App.model.todos),
durable: MessageSet.make(App, [Message.CreatedTodo, Message.RenamedTodo]),
})
const Members = AppSync.fragment({
shared: Projection.pick(App.model.members),
durable: MessageSet.make(App, [Message.Invited]),
})
const Board = AppSync.make({
documentId: DocumentId.make('board'),
...AppSync.compose(Todos, Members),
})compose throws on a field declared twice with different codecs, a Message
declared durable twice, or a fragment from another application. The result is
still one document: one outbox, one cursor, one server order.
Authorize on the server
Policy belongs on the contract, beside the Messages it governs, and runs on the server inside the journal's commit. The client never runs it.
const Authorized = forApplication(App).withPrincipal<{ readonly role: 'admin' | 'guest' }>()
const GuardedBoard = Authorized.make({
documentId: DocumentId.make('board'),
...Authorized.compose(Todos, Members),
authorize: {
RenamedTodo: ({ principal, message, shared }) =>
principal.role === 'admin' && shared.todos.some(todo => todo.id === message.id),
},
})A rule returns true, false, or { allowed: false, reason }; the reason
is sent to the replica whose edit it was, as its rejection's
Forbidden refusal.
message is exactly that variant, shared is the authoritative snapshot, and
principal is whatever the server's transport established for the connection;
it is never read from the operation. A variant without a rule is allowed. A key
that is not a durable variant is a type error. The rules ride in
journalContract(), so the server enforces them by spreading the contract.
An edit the policy refuses still shows at once on the client, then comes back as a rejection, as above.
Laws: what every snapshot keeps
authorize decides who may make a change. What the document must always be,
whoever changes it and whichever Message does, is a law: a predicate over
the snapshot an operation leaves.
const CappedBoard = AppSync.make({
documentId: DocumentId.make('capped-board'),
...AppSync.compose(Todos, Members),
laws: {
atMost100Todos: {
holds: ({ after }) => after.todos.length <= 100,
message: 'A board holds 100 todos',
path: ['todos'],
},
},
})Commit pipeline: operation → validate → authorize → reduce → laws(before, after) → written.
- Where it is judged. The contract's
journalContract()carries ajudgebuilt from the laws, which the journal runs inside the commit afterreduce, over the snapshot before and the one the operation leaves. The first law that does not answertrue, in the record's order, refuses the operation:journalExchangesends it asInvalidwith the law's id asrule, itsmessage, and itspath. On D1 a commit that lost a race is reduced and judged again over the snapshot it then lands on. - What it sees.
holdsgets{ before, after }, typed over the shared fields alone, so a law that reads a local field does not compile. It sees no principal and no Message: a rule about who belongs inauthorize. - In the Module graph. The contract declares its law ids
(
contract.laws.model), andGraph.ofdraws a law per declared law (sync:<name>.<id>), read as reading the whole shared slice sinceholdsis a function, and a transition per durable and server-only tag (durable:<tag>), each writing it. SoGraph.validate(module, { evidence })reports each durable Message aslaw-unwitnessedagainst each law until a walk or a scenario (Scenario.runMessages) issues its evidence, or anEvidence.runtimeOnlyline says only the journal's judge refuses it: a durable Message added later is reported until something draws it. - Matching the refusal.
CappedBoard.laws.atMost100Todosis the declared law ({ id, message, path }), andSync.isInvalidBy(refusal, CappedBoard.laws.atMost100Todos)tells its refusal from any other. - On the replica.
submitjudges the Message's optimistic result before writing the outbox, and fails withLawBrokenError(rule,message,path) when it breaks a law, so nothing is sent;Sync.mountreverts the edit it showed and hands the error toonPersistenceFailure. It is a hint: the optimistic snapshot holds pending edits the server may still refuse, and the server judges again where it commits. - Strict. A law judges
after, whateverbeforeheld. A document that already breaks one, because the law was added after the fact, refuses every operation that leaves it broken until one repairs it. To let such documents shrink toward a new cap, write the law overbeforetoo (after.todos.length <= Math.max(100, before.todos.length)), and runCappedBoard.judge(snapshot, snapshot)over the stored snapshots before the deploy to find the ones it would refuse. - The server's own appends go through the same commit, so
appendAsServerand a reaction's appends are judged too.
make throws for a law whose id or message is over 500 characters, or whose
path names more than 16 fields: its refusal could not be sent.
Write a law and a replay as expressions
A holds callback is code make can only run, so it cannot tell you that the
Message you wrote for CreatedTodo keeps the cap: you learn it when the
journal refuses an operation. metakit writes a rule as
an expression (a value built from Num, Arr and the like, which a
checker can read as well as evaluate), and foldkit-sync/metakit turns two of
them into what make takes:
SyncDeclared.holds(expression)is a law'sholds. The expression reads the snapshot the operation leaves asmodel, sobeforeis not available to it: a cap that lets an over-full document shrink needs the callback form. The law holds only where the expression is true. A snapshot it is null over, or that metakit refuses to evaluate it over (an integer result past ±(2^53 − 1)), breaks the law.SyncDeclared.transition(transition)declares what one durable Message does as a metakitTransition, under its tag inmake({ transitions }). The Transition's state is{ model }over the shared slice, and its input is the Message's own constructor (an input of another shape is a type error). Itswhenis a guard: a Message whose guard is false is refused, by the replica'ssubmitand by the journal. It may change the shared slice and nothing else; one that emits a Command is rejected.
import { Arr, Num, Path, Transition } from '@doeixd/metakit'
import { SyncDeclared } from 'foldkit-sync/metakit'
const todos = Projection.pick(App.model.todos)
const { model } = Path.forEnv({ model: todos.schema })
const CappedBoard = forApplication(App).make({
documentId: DocumentId.make('capped-board'),
shared: todos,
durable: MessageSet.make(App, [Message.CreatedTodo]),
laws: {
atMost100Todos: {
holds: SyncDeclared.holds(Num.lte(Arr.count(model.todos), 100)),
message: 'A board holds 100 todos',
path: ['todos'],
},
},
transitions: {
CreatedTodo: SyncDeclared.transition(
Transition.make({
state: Schema.Struct({ model: todos.schema }),
input: Message.CreatedTodo,
when: ({ state }) => Num.lt(Arr.count(state.model.todos), 100),
apply: ({ state, input }) => [
Transition.append(state.model.todos, { id: input.id, title: input.title }),
],
}),
),
},
})The mount and the journal replay CreatedTodo with that Transition in place
of your update; a tag with no declaration still goes through update. At
definition time make also checks each declared transition against the laws
written with SyncDeclared.holds: it throws Sync.make: "CreatedTodo" has an
unreachable guard for a guard that no snapshot satisfying those laws can
pass, and … violates a shared-state invariant for a transition proved to
break one. A check the solver cannot decide lets the declaration through, and
the journal still judges every operation on admission. A law written as a
callback is run, never read by this check.
foldkit-sync/metakit is the only part of foldkit-sync that imports metakit,
so a page whose laws are callbacks carries none of it. If your application
already declares a metakit Machine, SyncDeclared.fromMachine(machine, tags,
shared, initial) takes the durable tags from it as one transition each. A
replay runs the transition over initial (your application's initial Model)
with the shared slice written in, as forApplication does for update.
const machine = Machine.make({
state: Model,
transitions: {
CreatedTodo: Transition.make({
state: Model,
input: Message.CreatedTodo,
apply: ({ state, input }) => [
Transition.append(state.todos, { id: input.id, title: input.title }),
],
}),
},
})
const todos = Projection.pick(App.model.todos)
const Board = forApplication(App).make({
documentId: DocumentId.make('board'),
shared: todos,
durable: MessageSet.make(App, [Message.CreatedTodo]),
transitions: SyncDeclared.fromMachine(machine, ['CreatedTodo'], todos, App.initial),
})fromMachine throws at definition, naming the tag, for a transition that:
- is not one of the Machine's;
- emits a Command (a durable transition is state-only);
- declares supplied values (a time, a new id): a replay passes none, so every replay would be refused;
- has a read it does not bound (an opaque term may read anything);
- reads or writes a path that is not inside a shared path. A write to a parent of the shared slice is refused, as is a read of one; a path below it is fine.
It does not check the document's laws, and it does not check for an
unreachable guard: those checks need the solver, which foldkit-sync/metakit
keeps out of a page that only replays. Declare a transition with
SyncDeclared.transition where you want them. As with that function, a
Message whose guard is false is refused: replica.submit fails with
ReplayError, so an application should not submit a durable Message its own
guard refuses.
Which edits can the server's order change?
Two replicas edit at once. Each shows its own edit at the moment it is made;
when the server has put the edits in one order, each replays its own after the
other's (a rebase). If the two edits commute, nothing a person saw changes.
convergence(machine, arms) reads which pairs of durable Messages might
change it, from the transitions you already declared. You name each durable
Message by the transition the machine holds for it, machine.transitions.Titled:
import { convergence } from 'foldkit-sync/metakit'
const machine = Machine.make({
state: Model,
transitions: {
Titled: Transition.make({
state: Model,
input: Input,
apply: ({ state, input }) => [Transition.set(state.title, input.text)],
}),
Tagged: Transition.make({
state: Model,
input: Input,
apply: ({ state, input }) => [Transition.append(state.tags, input.text)],
}),
Cleared: Transition.make({
state: Model,
input: Input,
apply: ({ state }) => [Transition.removeWhere(state.items, item => item.done)],
}),
},
})
const { Titled, Tagged, Cleared } = machine.transitions
const { pairs, redelivery } = convergence(machine, [Titled, Tagged, Cleared])
for (const pair of pairs) console.log(`${pair.name}: ${pair.rebase}`)
for (const entry of redelivery) console.log(`${entry.tag}: ${entry.copy}`)It prints:
Titled/Titled: possible
Tagged/Tagged: possible
Cleared/Cleared: never
Titled: harmless
Tagged: removed by id
Cleared: harmlessA pair appears when one Message writes a path the other reads or writes.
never means commutes from @doeixd/metakit/pairs can show that either
order has the same effect (two clears of the done items). An undecided pair
gets possible (two titles keep the later title). A Message gets harmless
when idempotent from the same entry can show that repeating it immediately
leaves the same result (a set from the input, an
insert, a remove), and removed by id otherwise (an append would list
twice, so the operation's id removes the copy); a copy arriving later after another
write still relies on id deduplication unless the Message also commutes with every
durable Message. A Transition.combine of a custom operation is read from its
claims only when you pass a rewrite policy as the third argument:
{ foreign: table, rewritePolicy: Expr.RewritePolicy.verified(evidence) }, with the
evidence checkOperation(op, table) returned; without one such a pair is possible
and its copy removed by id. The answers say what the
declaration lets a rebase do; they run nothing. await settleConvergence(machine,
arms, { owner, walkPair, walkRedelivery }) makes each possible pair and each
copy an obligation, discharges them with the two-replica walks you give it, and
returns the result as evidence: Temporal.report(evidence) from
@doeixd/metakit/temporal lists what is still open. examples/todo-app/test/sync.convergence.ts is
one, over the real replica and journal.
Stamp what only the commit decides
A fact carries its own nondeterminism, but a client cannot know where its operation lands in the server's order. A stamp writes it in, on the server, as the journal commits:
const Message = defineMessageUnion({
// `at` is absent on what a client sends: the server's sequence once committed.
PriceEdited: { id: Schema.String, cents: Schema.Number, at: Schema.optionalKey(Schema.Number) },
})
const App = Surface.application({
Model,
Message,
initial: { prices: [] },
update: model => ({ model }),
})
const Prices = forApplication(App).make({
documentId: DocumentId.make('prices'),
shared: Projection.pick(App.model.prices),
durable: MessageSet.make(App, [Message.PriceEdited]),
stamp: {
PriceEdited: ({ id, cents }, { sequence }) => Message.PriceEdited({ id, cents, at: sequence }),
},
})The rule gets that variant and { sequence, actorId, replicaId } (the
replica that sent it, which tells one person's tabs apart), and returns the same
variant; a key that is not durable is a type error, and a rule that returns
another variant has its operation rejected. It rides in journalContract() as
Durable's stamp, so the journal stores, reduces and sends the stamped
Message. A replica shows what it sent until the exchange, then replays the
stamped Message in its place, the same on every replica. A retry is still
recognized by what was sent.
Use it for what a reader compares with the server's order: a read model that
records the last sequence it applied can tell which edits it holds by comparing
the two. A client that sends the stamped field itself is claiming a commit it
did not get; refuse it in the journal's validate.
Messages only the server appends
Some facts only the server may record: a payment provider confirmed a
charge, the table absorbed an edit. Declare those Messages serverOnly,
beside durable. A replica stores and replays them like any other; it can
never submit one:
const Message = defineMessageUnion({
PlacedOrder: { id: Schema.String },
ConfirmedPayment: { id: Schema.String, charge: Schema.String },
SentReceipt: { id: Schema.String },
})
const mark = (model: Model, id: string, change: Partial<typeof Order.Type>): Model =>
modifyFields(model, {
orders: () => model.orders.map(order => (order.id === id ? { ...order, ...change } : order)),
})
const App = Surface.application({
Model,
Message,
initial: { orders: [] },
update: (model, message) => ({
model: Message.match(message, {
PlacedOrder: ({ id }) =>
modifyFields(model, {
orders: () => [...model.orders, { id, paid: false, receipted: false }],
}),
ConfirmedPayment: ({ id }) => mark(model, id, { paid: true }),
SentReceipt: ({ id }) => mark(model, id, { receipted: true }),
}),
}),
})
const Confirmed = MessageSet.make(App, [Message.ConfirmedPayment])
const Receipted = MessageSet.make(App, [Message.SentReceipt])
const Orders = forApplication(App).make({
documentId: DocumentId.make('orders'),
shared: Projection.pick(App.model.orders),
// What a replica may submit.
durable: MessageSet.make(App, [Message.PlacedOrder]),
// What only the server appends. A Message in both sets is a type error.
serverOnly: MessageSet.union(Confirmed, Receipted),
})- A replica submitting one is a type error, and refused at run time.
- The server refuses one any replica sends, whoever it says it is:
every reader of a sent entry (
codec.writtenFrom,normalizeOperation,operationFrom) refuses it, judged after upcasting, beforeadmit,validateorauthorizerun.journalExchangerejects it by its id asForbidden("Only the server makes this change") and reports aServerOnlySubmitteddiagnostic; the edits beside it still go. No rule about who the principal is is involved, so a resolver's mistake cannot let one through. - Replica ids under
server/belong to the server: a sent entry naming one is rejected asInvalid, and so is one whose replica id is longer than 128 characters. - The contract's
surfacestill listsdurablealone, so an agent bound to it cannot dispatch a server-only Message;authorizeandstamprules may name one.
The server appends one through serverJournal from foldkit-sync/journal,
as a principal it holds in code and never resolves from a request:
import { serverJournal } from 'foldkit-sync/journal'
const serving = Effect.gen(function* () {
const server = yield* serverJournal({ sync: Orders, journal, server: { actorId: 'orders' } })
// A payment provider's webhook: its event id names the fact.
return (event: { readonly id: string; readonly order: string; readonly charge: string }) =>
server.appendAsServer(Message.ConfirmedPayment({ id: event.order, charge: event.charge }), {
key: `payment/${event.id}`,
})
})keynames the fact, and is required: a webhook's event id, a clock tick. A repeat with the same key and Message appends nothing new, so a redelivered webhook is harmless; the same key with another Message fails withServerKeyReusedError, and the first fact stands. A key is a non-empty string of at most 200 characters.- It goes through the journal's
append, sovalidate,authorizeand the laws judge it like any operation. - Keep the server's
actorId. The journal binds each replica id to the first actor that commits from it, so after a change ofactorIda redelivered key is anIdentityConflictError: that fact was the first actor's. A new key, and a reaction's append for a new commit, commit as the new actor. - A refused append frees its key. The key is recorded before the append,
so a redelivery after a deploy appends the bytes first written; when the
journal refuses the append (
validate,authorize, a law), nothing committed and the record is cleared, so the key can name a Message the rules take. A redelivery after a refusal is judged afresh: refused again with the same error, or committed if the rules now take it, neverServerKeyReusedError. - Each key leaves a row. The journal keeps a replica binding per
appendAsServerkey, and one per reaction append (per trigger and index), infoldkit-durable'sreplicastable; neither compaction norresetdeletes them, so they grow with the facts and reactions recorded. Nothing prunes them yet. - A server that hands
foldkit-durable'sappendinput it did not first read with acodecreader gets no server-only check: the journal knows no Message's tag. Read every sent entry withcodec.writtenFrombefore appending it, asjournalExchangedoes. The types hold you to it: what an exchange receives (Sync.transport.serve'sexchange, aTransportClient, aloopbackhandler) isReadonlyArray<unknown>, andappendtakes only aWrittenOperation.
Work after a commit: reactions
A reaction runs after each committed Message of a set, in journal order:
mail a receipt, call a provider, append a server-only Message as a result.
It is a declared value, given to the serverJournal:
import { reaction } from 'foldkit-sync/journal'
const receipt = reaction(Orders, {
name: 'receipt',
on: Confirmed,
appends: Receipted,
run: ({ message, key }) =>
sendReceipt(message.id, key).pipe(Effect.as([Message.SentReceipt({ id: message.id })])),
})
const running = Effect.gen(function* () {
// Made before the journal serves its first exchange: the reaction sees every commit after it.
const server = yield* serverJournal({
sync: Orders,
journal,
server: { actorId: 'orders' },
reactions: [receipt],
})
// One pass; none when every reaction has caught up, else how long to wait.
const next: Option.Option<unknown> = yield* server.react
return { server, next }
})On each commit, react reads operations after the stored cursor, runs the reaction handler (recording its answer), appends any returned messages as the server, and advances the cursor.
- At least once, never exactly once. The provider and the journal share
no transaction: a crash or a timeout between the call and the ledger's
record runs the call again.
keyis the same on every run of one reaction on one commit (64 hex characters); give it to the provider as its idempotency key, and the provider decides whether a repeat is a no-op. The appends are once: their ids come from the reaction and its trigger's id (never its place in the order, which aresetreuses), and the journal answers a repeat from history. - The cursor is stored beside the journal (
foldkit-durable's schema 7), one per reaction, so a restart neither walks the log again nor misses what committed while it was down. A reaction starts where the journal was whenserverJournalregistered it: deploying a mailer does not mail the past. - A run that fails waits: that reaction stops at the commit, on a backoff
from 0.5 s doubling to 30 s that the store keeps, and the others go on.
reactnever fails; it reportsReactionFailedand answers the delay. A defect and a timeout (timeout, 10 s by default) are failures like any other. - A run that can never succeed is parked: the journal refused its append
(
validate,authorize, a law), or its answer holds a Messageappendsdoes not name, more than 16, or one that will not encode. So is one that has failedattemptstimes (8) and for at leastparkAfter(an hour), so an outage parks nothing. The journal itself failing counts toward neither. A parked run is reported asReactionParkedand set aside with its trigger; the reaction goes on. Why it failed, onparked'serrorand the report'scause, is the failure's own text (a provider's, a driver's), kept beside the journal for whoever runs the server: no exchange sends it, and a page for the document's readers should not show it.parkedlists them,retryruns one again out of order (a recorded answer is reused, so no second call), anddismissgives one up. After areseta parked run isstale: it can be dismissed, not retried. - Compact no further than
settledThrough, the lowest reaction cursor, or a reaction skips what it never saw (ReactionSkipped). - What a handler is given is the committed Message, its id, sequence and
actor: never the snapshot, which has moved on by the time it runs. Its
fields are what a client wrote; a handler that mails
message.emailmails wherever the client said. - A reaction's append commits where the journal is when it runs, after whatever committed meanwhile. Two reactions in a cycle (one appends what the other runs on) are refused when the journal is made.
Who calls react is the host's:
- A long-lived process forks
server.follow: it runsreactnow, after each commit this journal instance hears of, and after the delayreactanswers. A reaction's commit reaches the document's sockets throughserveJournal's notices. - A Durable Object: give
defineDocumentHostaserver(below). It registers the reactions when it opens the journal, sets the object's alarm before replying to an exchange that committed, runs them without holding the reply, andalarm()runs them again and sets the alarm from their answer. Work after a reply lasts only while the object stays loaded; the alarm is what resumes a run eviction cut off. - A stateless Worker over D1:
ctx.waitUntil(server.react)in the request that committed, withrunsPerPassat 1 or 2 sincewaitUntillasts about 30 seconds, and a Cron Trigger callingreactfor what failed or was cut off. Two isolates may run one reaction at once, a duplicate call without a crash. And no other request is told: a reaction's commit reaches another replica when it next exchanges, never as a notice, since one request cannot wake another's stream.
settle stays for a read model the reply depends on: it runs before the
reply and may fail the exchange. Reactions are for everything else.
Coalesce a burst of typing
Typing makes one durable Message per keystroke. coalesce(last, next) is
offered each submit together with the last operation in the outbox; return a
merged Message to replace it, or undefined to keep them apart:
coalesce: (last, next) =>
last._tag === 'RenamedTodo' && next._tag === 'RenamedTodo' && last.id === next.id
? next
: undefinedReplaying the merged Message must equal replaying last then next. An
operation is only merged into while no exchange has carried it, so there is no
timer to tune: keystrokes typed while a request is out become one operation, and
a lone keystroke goes out as fast as before.
Change a durable Message
An operation is stored, in the outbox and in the server's journal, as it was written, and read later, possibly by a newer build. Renaming a field of a durable Message, splitting a variant, or changing what a number means would leave what was stored unreadable. So the document declares its Message's history, and every reader sees an old operation upcast to the current version:
// Version 1, as the first build shipped it: a note had a `title`. Kept as
// long as a stored operation may hold it; only the changed variant is copied.
const RenamedNoteV1 = Schema.TaggedStruct('RenamedNote', {
id: Schema.String,
title: Schema.String,
})
const MessageV1 = Schema.Union([RenamedNoteV1, Message.ClearedNotes])
// Version 2 is the application's own Message, where `title` became `name`.
const NoteHistory = migrations(MessageV1).next(App.Message, previous =>
Match.valueTags(previous, {
RenamedNote: ({ id, title }) => ({ _tag: 'RenamedNote' as const, id, name: title }),
ClearedNotes: cleared => cleared,
}),
)
const Notes = forApplication(App).make({
documentId: DocumentId.make('notes'),
shared: Projection.pick(App.model.notes),
durable: MessageSet.make(App, [Message.RenamedNote, Message.ClearedNotes]),
migrations: NoteHistory,
})Version 1 is the first Schema; each next adds a version with its Schema and
a function from the version before, encoded, to its own, encoded. Each step's
input is typed by the step before, so a step that returns the old shape does
not compile. Steps are written once and never changed: a later change adds a
step. A step must be pure and deterministic, with no clock and no random id:
the server reads an entry more than once (admit, then the journal), and
each read must find the same Message. It is given the version before checked
and normalized by that version's Schema. The history must end at
App.Message itself (make throws otherwise), and with no migrations the
Message is version 1, written exactly as before.
What each side does with it:
- The replica keeps each operation as it was written, with its
messageVersion(absent for version 1), in its outbox and on the wire, and replays it upcast. So an outbox written by the old build opens and sends under the new one. - The server (
journalExchange) hands every hook,admit,validate,authorize,reduceandstamp, the Message upcast to the current version, so a client claiming version 1 is judged exactly as the current Message would be. It stores what commits at the current version, and recognizes a retransmission by the operation as it was written, so an edit committed before a deploy, whose acknowledgement was lost, still reads as committed.
When something will not read:
- An older version no step reads (its version's Schema refuses it, or a
step throws): a pending operation moves to
status.refused, kept as written with its payload, never sent, untilreplica.dismiss(opId); the rest of the outbox opens and sends. No Schema of this build reads it, so a page shows it raw (operation.message,operation.messageVersion) or not at all. The server rejects one it receives asUnreadable { version }, and the replica keeps it inrefusedtoo. A committed one fails what has to read it, withUnreadableHistoryErroron the server: every exchange of a replica whose cursor is before it (what that replica sends still commits, and is acknowledged once a build reads the row), a retransmission of its id, and, while the row is after the journal's stored snapshot, an append or load that rebuilds the document from that snapshot. A replica past the row is served, and other documents are not affected. Only a build with a step that reads it recovers it. The replica is told only "This server cannot read the history of this document" and an incident; the operation's id and version stay on the error, which a served socket reports as anExchangeDefectunder that incident. - A newer version (a rollback, or an old client): the replica refuses to
open on one in its outbox (
UnsupportedMessageVersionError, nothing removed), and an exchange that receives one fails with it, recorded instatus.lastErrorand retried on the backoff; the page reloads the new build when it sees that error (ExchangeFailedonDiagnostics). A server receiving one fails the exchange before appending anything, so the client waits with its edits rather than losing them.
Deploy order: the release of Sync that reads messageVersion goes to every
server and client first, and skipping that step loses edits. A server on
an older release rejects an operation carrying messageVersion as Invalid,
and the replica drops it; a replica on an older release that is sent an
Unreadable refusal drops that operation too, since it keeps no refused
list. Then deploy an application's new version server first. A client on the
old version keeps syncing until the first operation of the new version
commits, then fails its exchanges until it reloads; its outbox is kept and
sent after the reload.
A rollback of the Sync release itself meets a replica state holding
refused, which an older release refuses to open
(InvalidReplicaHistoryError). Do not clear storage on that error: the
outbox is in the same state, and clearing it loses every unsent edit.
Roll forward instead.
A server that builds an operation itself and appends it (editsJournal's
absorbed) writes it at the current version:
Notes.journalContract().operation.encode(operation). The journal takes a
WrittenOperation, which is branded so that only Sync makes one: a decoded
Operation names no version, would read as version 1, and is refused by the
type. An entry from a wire is unknown until codec.writtenFrom reads it.
Nothing read as history writes again: operation.decode takes only a
WrittenOperation, and encode refuses what codec.committedFrom returns,
stripped of its commit or not. Changing the shared
slice's own Schema is not covered: a stored snapshot or checkpoint of the old
shape still needs a migration of your own.
The URL, mirrors, and agents
mount takes the application's own subscriptions and the resources Layer
they need, and url: { init, onUrlChange, onUrlRequest? } to route navigation
through update: init(model, url) reduces the first URL before the first
render and onUrlChange(url) names the Message for every navigation. A
foldkit-mirror URL mirror plugs into exactly that seam.
Mounted is also the host an agent binds to: model, dispatch, subscribe,
and observe, which reports every application Message the runtime applies.
See examples/todo-app for both.
Carry local state across a reinstall
When an exchange or a failed persist replaces the shared slice outside
update, onReinstall(next, previous, { reset }) returns the transition
instead. Use it to keep a selection that points into the slice, or to return a
Command that patches a DOM the change has to reach. Omitted, the Model stays
next. It is not called for a status that changed nothing the Model
shows. reset is true when the server's history is a new one (a new
status.epoch: the server was reset), so whatever the application derived
from the old one, such as reads keyed by commit sequence, is to be read again.
afterUpdate(model) runs after every update of the mounted application, a
durable Message's and a reinstall's included, and never in replay. A durable
Message is replayed through update on the server and in the replica, where
it may change only the shared slice; local state derived from the slice (the
Remote overlays below) is kept in step here instead.
Edit rows a server owns
When rows are too many to replicate but edits to them must survive offline,
let the journal own the edits and the table be its read model, each row
carrying the highest sequence it has applied (revision). foldkit-sync/entity
keeps such edits one per cell, and foldkit-sync/remote shows them over the
rows Remote reads: each shown cell starts from Remote's row and overlays any
pending edit, any edit committed past the row's revision, or any edit the
journal absorbed while the cached row is still below it.
EditableEntity.make(Product, { members: ['description', 'cents'] }) gives
the schemas (Change on the wire, Edit in the slice, the Message fields
edited and absorbed) and pure functions for update, the stamp
(stamped) and onReinstall: merge, absorb, replaced (a cell of this
tab's that another's later commit took), cellsOf (what a refusal undid) and
changeAt (what a row holds in a member, as the change that sets it: an
undo's value) as pure schemas and functions without storing state.
RemoteEdits.make(Data, ProductEdits) is the bridge to a Remote domain over
the same Entity. Its reconcile(model, edits, replica) brings Remote's
overlays (overlay from foldkit-remote/overlay) in line with the slice, so every read of a row draws
its edits, a second view or a filter as well as the grid. It holds an edit the
journal absorbed while the cached row is below it, and lifts it once a read
reaches it; it returns those newly held (ask for their rows again) and this
replica's edits a read reached with another value (replaced: the table
applies in commit order, so a later edit took the cell). An edit to a field a
list orders or filters by moves its row there at once, as Remote places any
pending edit. To see that when the
row arrives live after its own edit landed, it keeps this replica's landed
edit, showing the row's own value, until the slice drops it. Call it from
afterUpdate. shown(model) lists what the overlays show, for a cell's
mark, and clear lifts them all, for a reset. Remote stores none of it: after
a reload, reconcile rebuilds the overlays from the slice the replica
restored. On the server, editsJournal from foldkit-sync/journal keeps
the table: its settle (for journalExchange) applies each committed change
through your apply as a recovery intent, from the journal's floor and keyed
by its epoch, and its absorb (on a clock) records what the table holds and
compacts behind it. It refuses to settle a table whose tableRevision is past
the journal's cursor (TableAheadOfJournalError: the table outlived a reset of
the journal), and an edit to a row the table lacks is the journal's validate
to refuse. Editing server data through a
journal explains the pattern, its failure
cases and its limits; examples/registry is the
whole of it.