Sync

Keep a copy of your data in the browser or an app that reads without the network, writes instantly and stays up to date with the server.

Start a replica

Call sync with the server and the rows you want. Then query it with the same builder you use anywhere else.

import { sync } from './fennec.6b1ff8b969.js';
import type { FennecSchema } from './fennec-schema.js';   // fennec types, over the server's file

const db = await sync<FennecSchema>({
  url: 'http://127.0.0.1:8080',
  shapes: [{ collection: 'tasks', where: { status: 'open' }, key: 'key' }],
});
await db.ready();

// read: from the local copy, no network
const rows = await db.from('tasks').where('priority', '>=', 3).rows();

// live query: re-runs on every change
const stop = db.live(db.from('tasks').order('priority', 'desc'), draw);

// write: to the local copy first, instantly, then to the server
await db.from('tasks').insert({ title: 'new', status: 'open' });

The replica loads fennec.wasm, the full module, unless given another, so its near walks a graph.

What sync opens, and where a query binds

A copy on the client, changes streaming from the server, optimistic writes. In fennecdb that is not a library — it is an endpoint and a transport, because the same engine already runs on both sides.

With no module given, sync opens ./fennec.wasm beside the page, its collation data from collate/ beside it; wasm takes another URL, the bytes or a compiled module, and local a database already open.

The query code does not change. db.from(...) is the same builder producing the same FennecQL; the only difference is where it is bound.

The server owns the schema

A replica takes its collections as the server declares them. Code that declares its tables (Schema in code) hands them over too, and they are checked against the server's, never applied:

import { sync } from './fennec.6b1ff8b969.js';
import { todos } from './tables.js';

const db = await sync({
  url: 'https://todos.example.com',
  schema: { todos },
  shapes: [{ collection: todos, key: 'key' }],
});
  • What the code declares must be there. A collection, a field or an index the server lacks, or one of another type, refuses the open: a FennecError naming each difference.
  • What the server holds beside it is its own. A field or a collection the code does not declare is fine: an older app keeps working while the server moves ahead.
  • Nothing is applied, not even an addition. The schema changes where it lives, on the server: its owner's migrations, a deploy step's connect(url, { schema, migrations, migrate: true }), each recorded in the server's own _migrations, which no statement changes — a list starts over in a new file, or a new tenant.
How the schema is compared

The comparison is the server's engine (POST /_schema/plan?mode=follow), the same that checks a page's own database at an open, so the two say the same things in the same words. A replica reconciles rows by its server's field order and types, which is why it never declares a collection of its own: a field added in the page and not on the server could not be decoded either way.

Native apps sync too

An iOS, Android or Flutter app keeps its replica in a file on the device, with the same shapes, the same optimistic writes and the same catching up -- and its writes wait in the file while the server cannot be reached. Opening the file as a replica is the one line that changes: Fennec.sync in Swift and Kotlin, Fennec.openSynced in Dart (Sync with a server).

The stream carries state, not transactions

The server sends the current state of each row that changed, not a log of every write. That is what a replica needs; it is not an audit log.

Why the stream is a clock, not a log

The classic route is a transaction log: every write is an event and the subscriber replays them. fennecdb sends the current state of what changed instead — the stream is a clock, not a record. That is right for a replica and wrong for anyone who wanted an audit log.

A shape is a set, not a window

A shape picks the rows of one collection the client keeps, by a filter the server applies. It cannot be "the latest 100": order, limit, offset and count are refused.

Why a shape refuses order, limit and offset

The whole database is in memory and the WASM32 address space is 4 GB, so a client cannot pull an entire collection. A subscription is a subset and the filter is applied on the server.

order, limit, offset and count are refused in a subscription with a 400. A shape like "the latest 100 rows" looks correct but is not: when a new row arrives the oldest has to drop out, and an incremental diff cannot express that. An explicit error beats a silently wrong stream.

The shape condition uses the ?field=op.value form, so there is no or group and no function call. The reason is escaping: a free where= would turn into string concatenation, exactly what the builder avoids. Escaping goes to the transport via URLSearchParams and types go to the server, leaving no injection surface.

One collection per shape. The seed has to mean "this is the whole of this collection", or the cleanup step becomes ambiguous.

Optimistic writes

A write shows up locally at once, then goes to the server. It is kept until the server answers: if the server refuses it, the local change is undone; if the server cannot be reached, it waits and goes again.

const p = db.from('tasks').insert({ title: 'new', status: 'open' });
await db.from('tasks').where('title', 'new').first();  // already here
await p;                                               // the server has it
  • Inserts need a key, a text @hash field, to match the local row with the server's. Without one, an insert waits for the server.
  • Updates and deletes need no key: they work by the filter, by id or anything else -- a row an insert made before the server answered included.
  • Writes go one at a time, in order, each under an Idempotency-Key it keeps until it is answered.
  • An increment lands from every replica. update({ n: inc(1) }) is worked out over the replica's row at once and sent as the statement, which the server works out again over its own: two replicas that each increment offline leave the server 2 up, and both replicas come to its sum.
How an optimistic write is applied and undone

A write is three steps and the order matters: first gather what undoes the local change, then apply it locally, then queue it for the server. If the server refuses, the local side rolls back fully — no network needed, the undo is already in hand. The queue and the undo are kept in the replica itself, in collections of the sync's own (_sync_queue, _sync_temps, _sync_shapes with the cursors), as an app's file keeps them (Sync with a server).

Everything up to the first await is synchronous. An async function body runs synchronously until its first await, so the optimistic row is local before the caller awaits the promise. A single microtask in between would have broken the "visible instantly" promise.

Reconciliation by key. The id space belongs to the server and the client cannot know it in advance, so an optimistic row gets a temporary id starting at 252 — far from the server's range and below Number.MAX_SAFE_INTEGER. What matches the two is a business key: when a row with the same key arrives from the subscription, the temporary one is dropped. An update or a delete that reaches a row the server has not sent yet is sent a second way as well, by that key -- set tasks {..} where key in [..] beside the statement -- since the temporary id is the page's alone. An insert the shape does not hold leaves its temporary row once the stream is past the change the server answered it at (Fennec-Seq).

An insert into a keyless shape is not applied optimistically, unless it names its id. With nothing to reconcile, the row would stay a local duplicate; one round trip of latency beats a silent copy. key must be text @hash.

Writes go one at a time because a write that landed after one written after it would leave the server holding the earlier. The promise a write returns settles with the server's answer, so it waits through an outage; the row is in the replica from the start, and nothing needs to await it.

Refusals, retries and offline

A replica works offline and catches up later. It reads from its own copy, its writes wait in the queue, and they go in order once the server can be reached again. Only a refusal puts a write back. Anything else that keeps the server from answering keeps the write, and it goes again until the server answers it -- once, whatever the network did meanwhile.

The server answersThe write
2xxlanded: it leaves the queue, its promise resolves
nothing (the network failed), 408, 429, 5xxkept and sent again under its key, after 250 ms doubling to 15 s -- or after the Retry-After the server names, where that is longer: a tenant's quota, a tenant being moved or failed over
401kept; nothing is sent until a new token (tokenProvider, setToken). The provider is handed why (TokenRefusal, below) and asks the issuer for a fresh token, and the sync goes on where it stopped -- where the token it handed over is refused too, after 1 s doubling to 60 s
507 naming a tenant's quota of bytes or rowsrefused: put back, its promise rejects, onRefused is told with e.quota, and the writes behind it go on
any other 4xxrefused: put back, its promise rejects, onRefused is told -- with e.reason where it is a 412 and the write's require said why
import { sync } from './fennec.6b1ff8b969.js';

const db = await sync({
  url: 'https://api.example.com',
  token: await auth.token(),                       // sent from the first request on
  shapes: [{ collection: 'tasks', key: 'key' }],
  persist: `tasks:${auth.userId}`,                 // one account's replica: writes survive a reload
  tokenProvider: () => auth.refresh(),             // asked at every 401: the issuer's fresh token
  onRefused: (e) => toast(e.quota ? 'This workspace is full' : e.reason ?? `${e.status}: ${e.message}`),
});
await db.pushed();                                 // every write answered

A token refused. The provider is handed a TokenRefusal: errorCode, the code the server named ('token_expired' where the token's exp passed, null for none; Expiry), expired, that code's, hadToken, whether the refused request carried a token at all, and attempt, how many times in a row it is asked since the server last took the token held. It asks the issuer for a fresh token at every one, whatever the code -- forcing a refresh at expired, where a cached token is the one refused -- and the replica goes on where it stopped, its queue sent under the keys it kept. A 401 alone is never a sign-out: the server keeps no list of revoked tokens, so only the issuer knows that a session ended, and the app signs out where the issuer refuses to issue a token. A fresh token cures an expiry, a key the server has since dropped, an older server's expiry and a request sent before any token (hadToken false). It cannot cure a key the server has not fetched yet, an nbf its clock has not reached or a misconfiguration: where the token just handed over is refused too (attempt past 1), the sync asks again after 1 s doubling to 60 s, so a provider that hands over a token at every ask asks the issuer once a minute, not at the network's speed; handing over the token just refused again -- a cached one, at errorCode -- does not end that wait. An expiry of the token the server took last, or of the first one handed over since, starts the count at 1 again -- a token handed over offline may run out before it is sent -- and so does the server taking the token held, a 2xx or a stream that opens; a 408, 429 or 5xx does not, as it may come before the token is read. Any other token refused for its expiry counts, and waits: it was minted expired, as every token is where the server's clock runs ahead of the issuer's, and asked for again at once it would cost an issuer's call a round trip. A 401 to a request sent before a new token was handed over is not asked about: the request goes again with the new one.

A provider that throws -- the issuer out of reach -- or hands over no token leaves the sync waiting, and says so: status()'s token reads failed and its error the token provider failed: … (what it threw goes to onError too). The page's online event, or setOnline(true), asks it again with the same TokenRefusal, though not before a wait the server's refusal began. A provider is asked once at a time: while it is at work nothing asks it again, and what it hands over answers every ask meanwhile. Nothing bounds its time, since it may be waiting on a sign-in, so a provider must return: it times out its own requests to the issuer, and throws. One that never returns holds the sync, token reading asked, until the app hands a token over itself with setToken, which gets it going whatever the stage.

The status while a token is wanted. status()'s token is null while the sync waits on none. Otherwise it says where the ask stands, its stage -- delayed while the wait before the next ask runs (the token handed over was refused too), asked once the provider is asked and no token has come, failed where it threw or handed over none -- beside its refusal, the TokenRefusal the provider was handed, or will be once the wait runs out. Nothing is sent meanwhile, and the error is the token's, its errorCode the code the 401 named, whatever else fails while it waits: streams end where the network goes, which is where providers fail. An app that hands its tokens over with setToken rather than a provider does so at asked.

const t = db.status()[0].token;
if (t?.stage === 'asked') db.setToken(await auth.refresh());      // the provider's job, by hand
if (t?.stage === 'failed') toast('Signing in again once the network is back');

One replica, one account. A replica holds one account's rows and the writes it made: its persist key -- or a local's file -- names the account, and it is never opened for another. On a browser two people share, the second signing in over the first's replica would send the writes left in it under their own token and be shown its rows. Signing out, an app closes the replica and keeps it while status() says pending writes, for that account's next sign-in to send under the keys they kept; deleting it loses them.

A require's reason. A write given { require: 1, reason: 'the task was taken' } sends its else '…' in the statement, and the server's 412 is a refusal like any other 4xx: put back, the promise rejected, onRefused told, with an error whose reason is that text (undefined where the write gave none). A write the replica finds unmet itself, a delete of a row it does not hold under require: 1, is refused there with the same reason, and nothing is sent (A reason for the refusal).

Offline, reload, backoff, quota and failover

Once, by the key. A write whose answer was lost -- the request reached the server, the response never came back -- is sent again under the Idempotency-Key it was first sent with, and the server answers it as it answered the first time (Idempotency) rather than make the row twice.

Offline. A write made while the server cannot be reached waits in the queue; the page's online event, or setOnline(true), sends it at once, the backoff forgotten -- unless the server said when to come back (below) -- asks a provider that failed for a token again, and offline or setOnline(false) closes the streams. Writes left from before go before the streams open again, so what they bring holds them.

A reload. With persist -- or a local kept in a file (openFile) -- the queue is stored with the replica the moment a write is made, and a page opened again sends what it had not, under the same keys. Without either, a closed page takes its unsent writes with it.

Backoff. 250 ms, doubling to 15 s, with 30% jitter on top so a server back up is not met by every client at once; a stream that cannot reconnect waits the same way, and starts the count again once it opens. One that ends while a token is wanted waits for the token instead, and opens with it.

A tenant's quota. A tenant node holds each tenant to its quotas (Quotas), and names the one that refused a request in its body, which the replica reads. A 507 of bytes or rows is a refusal: waiting makes no room, deleting does, and a write that only deletes always lands -- held, the write would hold every write behind it for good, the delete that would make its room among them. A 507 naming no quota is the server's own ceiling (--max-memory) or a proxy's, and is waited out as a 5xx is. A 429 of streams, held, requests, writes or write_bytes is waited out for its retry_after_ms -- the wait to the millisecond, a bucket refilling a row in 2 ms where Retry-After rounds it up to a second -- or its retry_after, the seconds Retry-After says, where no milliseconds are given, where that is longer than the backoff, an hour at most, with the jitter on top, since every client the quota refused in one moment is told the same wait; a stream refused so waits the same way, its shape not connected meanwhile, and status() names the quota (quota) beside the error. setOnline(true) forgets the backoff but not the server's word: the network says nothing of a tenant's quota.

A move or a failover. A node answers a write to a tenant it is moving, or no longer holds, 503 with "retry_after": 1 beside its Retry-After (Moving a tenant); a standby router whose directory has not arrived answers a stream so too. The write is kept and goes again through the router after that second where it is longer than the backoff, as after a quota's 429: the node's word for how long a move holds its writes, never the backoff's guess under it.

Put back in order. A refused write's rows are written back as they stood before it. A later write to the same rows, still waiting, is not replayed on top; the server's answer to it, and the change it sends, has the last word -- and refused in turn, it puts the rows back as the server holds them, not as the first write left them.

The server's rows stay. A row the server sent while the write waited -- changed, or gone -- is newer than what the replica held before the write, so a refusal leaves it as the server sent it; a seed, which a scoped stream gets again on every reconnect, speaks for every row, the one a waiting delete took away included, which stays gone. An insertNew refused for an id the server holds deletes the row it made only where the stream has not brought the server's row yet; where it has, the server's row stays, and a block of several is put back whole but for those rows.

Statements bound to writes

A replica holds its shapes' rows, never its server's statements, so it runs no statement bound to a collection's writes. A synced write that wakes one is sent alone, and the optimistic view holds that write alone: the ledger line the binding makes is not there until the server has made it. The server runs the write and what it wakes in one block, and the derived rows come back through a shape following their collection, in the change numbered as the write's own Fennec-Seq.

import { sync } from './fennec.6b1ff8b969.js';

const db = await sync({
  url: 'https://api.example.com',
  shapes: [
    { collection: 'orders', key: 'key' },
    { collection: 'ledger' },                      // what paid_ledger writes comes by its own shape
  ],
  persist: 'orders',
  onRefused: (e) => toast(e.reason ?? `${e.status}: ${e.message}`),
});

// offline: the order reads paid at once, and the ledger has no line yet
const paid = db.from('orders').where('key', 'o-17').update({ status: 'paid' });
db.live(db.from('ledger').where('order', 17), (lines) => console.log(lines.length));   // 0, then 1
await paid;                                        // the server ran the write and paid_ledger in one block
  • An app taking orders offline can still write a bound collection. The order is paid in the replica at once and waits in the queue; the ledger line arrives once the server has the write, and a replica with no shape on ledger never hears of it.
  • A binding's refusal puts the write back. A 412 with its guard's reason, or a 409, is a refusal like any other 4xx: the optimistic write is undone and onRefused told, with e.reason. A scoped token is told no binding's name, and its write waking one its policy does not grant (Waking a bound statement) is a 403.
  • The binding runs once. A write sent again under its Idempotency-Key after its answer was lost is answered from the first try: one ledger line arrives, never two.
  • The server defines it. create statement ... after ... on a synced database is refused like every named statement (Limits).

Live queries

db.live(query, fn) runs the query again whenever a collection it reads changes, and hands fn the new rows. Running it again on the local copy takes under a millisecond.

A database in the page with no server has the same live: see State in the page. Moving from one to the other leaves the code that reads unchanged.

Why live queries re-run instead of updating

There is no incremental maintenance and none is needed. The local side is an indexed database, so re-running the query from scratch is already under a millisecond — the differential dataflow that a Map-backed collection requires buys nothing here.

It would not even be correct for near. A single insert can change the entire top-k ordering, and there is no incremental HNSW maintenance that is both cheap and correct — the machinery would have to be disabled for fennecdb's headline feature.

Invalidation is at collection granularity: the change stream says which collections changed, the live queries bound to them re-run, and all of it coalesces into one frame. Anything finer, like intersecting id sets, would cost more than the local query itself. A query built with db.from knows the collections it reads, each lookup's included; a FennecQL text names them with { collections }, or runs again after every write.

A database in the page alone runs its live queries in a microtask after the task that wrote, not at the next frame: its writes are the page's own, and nothing lands in chunks. Both use the same code.

Batches

db.batch makes several writes one: one request, one key. They land on the server together or not at all, and on a refusal the local copy is put back too.

await db.batch(async (t) => {
  await t.from('tasks').insert({ title: 'a', status: 'open' });
  await t.from('tasks').where('key', 'x').update({ status: 'closed' });
});
How a batch lands, and rolls back on both sides

The batch is one block on the server: its statements run in order under a single write lock, and their writes land together, as one record, or not at all. The gain is one round trip instead of N, no other writer slipping in between, and nothing half done.

Both sides roll back. A batch that is refused lands nothing on the server, and the local side puts back exactly what it applied optimistically, the last write first, so the two stay one state. A batch whose answer did not come is kept and sent again, whole, as any write is.

Multiple tabs share one stream

Open tabs elect one leader that holds the connection to the server, passes changes to the others and sends every tab's writes, one queue for all.

  • Turn it off with leader: false; without navigator.locks -- outside a secure context, in Safari before 15.4 or Firefox before 96, in a Node without it -- it is off already. Each tab then sends its own writes. With navigator.locks one at a time stores the persist key; without it the last tab started stores it, and those before it nothing from then on (One replica stores a key at a time).
How tabs elect a leader

Every tab has its own wasm instance. If each opened its own subscription there would be N copies and N connections, so a single leader is elected with navigator.locks; the others receive the same batches over BroadcastChannel and apply them to their own local copies. The apply path is identical — only the transport differs.

Writes go through the leader, so one queue keeps them in order. A tab applies its own write to its own copy at once, as the leader does, and hands it to the leader, which keeps it in its queue -- stored with its replica when it persists -- sends it under its key and tells every tab the answer; the tab that made the write lands it or puts it back in its copy. When the leader goes, the lock passes to the next tab, which takes over the queue its predecessor stored and is handed every other tab's unanswered writes again; the key makes a write sent twice land once.

Dropped connections and the horizon

A client that reconnects gets only what changed since it left. If it was away too long, the server sends it a fresh copy instead.

--changes <n>    entries in the ring (default 4096, 24 bytes per entry)
How far behind a client may fall

A client returns with ?since=<cursor> and asks for no seed. If the cursor has fallen behind the ring, the server reseeds by itself rather than silently sending incomplete events.

That number is directly how far behind a subscriber may fall. At 100 writes per second, 4096 entries is roughly a 40 second window. With persist, the image and the cursor are written to IndexedDB, so a reopened tab is not reseeded from scratch — unless its cursor has fallen past the horizon.

A seed writes the shape over the replica and deletes what it does not hold, keeping the rows of writes the server has not answered -- and of those it answered after the seed was taken -- whose copies come later. Written over rather than cleared first, a row that stayed keeps its vector's node.

The server's schema changed. A change says so ("schema": true), or rows come with a field the replica has not got: the replica asks GET /collections again, makes the collection again as the server now declares it, its rows kept in the fields that are left, and is sent the whole shape. A schema declared in code is checked against the server's again, and a difference goes to onError.

When the server restarts, the horizon is set to the counter: a database loaded from a file has no history, only its present state. A cursor standing exactly there, after a quiet restart, gets an empty response; anything behind it is reseeded.

A replica that takes its primary's whole image, having fallen behind what the primary keeps, reseeds every stream open on it, a seed being read included, even where the image stands at the stream's own change.

A seed in parts

A seed whose rows pass 1 MiB of JSON comes in parts, each an event: seed of the same seq (the wire format). The server reads the rows a page at a time beside the writers and never holds the seed whole.

The replica holds the parts aside and lands the seed once its last part came. Until then every read, live query and read of the app's own answers the rows as they were, or none for a shape never seeded. A stream that drops mid-seed leaves the replica as it was, and the next stream seeds again from the start: a seed is not resumed. A write the app makes while parts arrive is applied at once and kept by the seed until the server's copy arrives, as with any seed.

Where the parts wait

Natively the parts wait in the replica's own file, in a collection of the sync's own, _sync_seed, and land in one block. They are deleted when the stream drops and when the replica opens again. In the browser they wait in the page as the text they came as, not in the module, whose memory never shrinks, and land in one task, part by part, so nothing in the page runs between the first write and the last.

A page that ended in the middle of a landing, a replica kept in a file with openFile, finds that on its next open. Before anything reads the shape it empties its rows, keeping those of writes not yet answered, and seeds it again whole.

Cost

The server's change ring is about 96 KB at the default size, subscriptions do not poll, and a large seed does not hold up the writes: it is read beside them.

What the change ring costs

At the default --changes 4096 the ring is about 96 KB and costs one push per entry on the write path. Subscriptions do not poll — see the HTTP endpoint for why — and are counted separately from ordinary requests under --http-max-streams.

Writes while a seed is read

A seed of 10 000 rows or more whose filter no index answers is read as a long /query is: the server takes what the read needs under its lock — the collection's ids, 12 bytes a row — and reads the rows with no lock held, so writes land while it reads. The seed is the shape at the change its seq names, and every write after that change comes in the stream's changes, once. Until the stream has looked past that change the server keeps the ring back to it, past --changes up to 64 times it (6 MB at the default), so a burst of writes beside a long seed does not send the client to be seeded again; past that the seed is read once more under the lock. A shape an index answers, or a short one, is read under the lock as before. Beside a subscriber seeded over and over from a million rows, single writes at 1 000 a second took 0.8 ms at p99, where they took 212 to 231 ms while the seed held the lock, and each seed took as long as it did (make seed-bench).

What a seed costs in the page

The replica writes a seed's rows, and a change's, 500 at a time (a seed in parts lands in one task, still 500 rows a statement), each chunk one parameter (put <collection> $1) whose values are made their fields' types as a statement's would be. From the seed's event to ready(), 100 000 rows of a text, a float and a json field took 192 ms in Node on an M1, against 295 when they went as statement text, and 300 000 took 550 ms against 825; rows holding a point went in twice as fast. A collection with a vector or a bytes field still goes as statement text, which hands its vectors to the module as f32s: as one parameter they are digits read one at a time, and rows of a 32-dim vector took 1.7 times as long.

A seed in parts is parsed a part at a time as it lands. A seed of 300 000 rows of 155 bytes took Node's process to a peak of 260 MB, against 367 MB when it came as one event, and landed in 856 ms against 882; the module held 68.7 MB either way. Natively the same seed took the process to 182 MB against 542.

Limits

A few things sync does not do, or does differently from what you might expect.

  • A shape is not a security boundary on its own; use a per-user token with scoped access.
  • bytes fields cannot be synced.
  • The server has the last word over the local copy.
  • A write that picks its rows — order and limit before an update or a delete, or { returning }, a job queue's claim — is refused on a synced collection: the replica would pick and answer its own rows, and the server its own. Send it to the server itself (db.remote).
  • A named statement — call, create statement or drop statement — is refused on a synced database, before anything of the text runs: the replica holds its shapes' rows, not the server's statements. Call it on the server (db.remote.call(…), or the native SDKs' HTTP client, Named statements), and what it writes comes back through the shapes' streams. A scheduled statement is one: a replica defines and runs none, and what a run writes reaches a synced app through the shapes following its collections, as any server write does. So is a webhook consumer: a replica defines and takes none, and what an event writes reaches a synced app the same way.
What a shape does not guarantee
  • A shape alone is not a security boundary. Under the server's own token, a changed id that does not match the shape is sent as a deletion: harmless locally, but which ids changed leaks. A per-user token with scoped access hides both: the rows outside its rules are filtered out, and it hears only of rows it was sent.
  • bytes fields cannot be synced. In JSON they become number arrays with no way back. That is a limit of the HTTP surface, not something sync introduces.
  • In a projected shape the other fields read as null. With select, the local row carries only those fields — which is all the client knows anyway.
  • batch() does not nest and the calls inside it return no result: writes pile up and go in a single request.
  • Rolling back needs no network, but the server has the last word. A rolled-back local state is overwritten by the server's in the next batch.
  • Rows a @ttl lets go of leave a replica's reads at once -- the replica's collection has the server's @ttl -- and arrive as deletes when the server's sweep takes them.

Persisting the replica

Add persist to keep the copy, its place in the stream and the writes the server has not answered in IndexedDB, so a reopened tab starts from there instead of downloading everything again, and sends what it had not.

import { sync } from './fennec.6b1ff8b969.js';
import type { FennecSchema } from './fennec-schema.js';

const db = await sync<FennecSchema>({
  url: 'https://api.example.com',
  shapes: [{ collection: 'tasks', where: { status: 'open' }, key: 'key' }],
  persist: `tasks:${userId}`, // one account's replica, its cursors and its unsent writes
});
await db.ready();

db.live(db.from('tasks').order('priority', 'desc'), draw);
await db.from('tasks').insert({ title: 'new', status: 'open' });

With cryptoKey the replica is sealed as persist seals a database (Sealed in IndexedDB). Only a key that holds nothing is seeded: a replica whose store is there and does not restore -- sealed with another key or none, changed, written by a later client -- refuses to start, sync rejecting with the reason, and the store stays as it was, with the writes it had not sent. Started again with the key it was sealed with, it sends them; or unpersist(key) deletes that key's store, the writes in it with it, and the next sync seeds anew. A tab that takes the lead from such a store stores nothing in it, tells onError, and status()'s unkept says why; where IndexedDB itself failed the read, the next write reads the store again.

import { unpersist } from './fennec.6b1ff8b969.js';

await unpersist(`tasks:${userId}`);   // refused while a replica keeps it in this browser

unpersist asks navigator.locks whether a replica keeps the key, or the lock manager it is given (unpersist(key, { locks }), the one the replicas were given). It deletes that key's records alone; its chunks are stored under the key, # and nine digits, so another key whose name is <key># followed by nine digits is read as this key's chunk -- avoid such names. Every database's next persist in this page stores its image whole; another page's plain persist of the key is not reached, and goes on in chunks that a restore does not find, so a key one page persists is deleted by that page.

One replica stores a key at a time. It holds the key's lock (navigator.locks) while it stores there, whatever its url and shapes, so two replicas under one key -- other shapes, or tabs with leader: false -- never store over each other: the second stores nothing there, status()'s unkept saying so, and takes the store over, the first's unsent writes with it, once the first lets go. A tab with leader: false leads itself meanwhile; an elected one waits to lead, and its tabs' unkept says so too. Each replica also claims the store as it takes it over, and each of its writes finds that claim in its own IndexedDB transaction or stores nothing, so the store restores whatever the locks did. Without navigator.locks nothing holds a second tab back: the last replica started on a key stores it, and one started before stores nothing there from then on, unkept and onError saying so, its writes still sent. close() stores what was written before it, then lets go of the store; past 5 s it lets go all the same, its persist still out stores nothing once the next replica claimed the store, and onError is told what was not stored: the next tab never reads a store a closed one is still writing.