Remote / foldkit-remote

Persistence and hydration

A snapshot is the entity cache and the lists named to survive. The rows go; a connection goes only if named, and keeps its edges and its age alone — never a cursor, which may name server state that is gone. Each row and list carries when it expires (see How long a saved read lasts). Session machinery (live cursors, optimistic layers, mutation bookkeeping, gaps, retention roots) is never in one.

ts
import { Option } from 'effect'
import { RemotePersistence } from 'foldkit-remote/persistence'

// A cache carried in the page: prefetch on the server, embed, then hydrate.
// `snapshotOf` names the connections that survive; none, here. For a page
// the browser resumes with foldkit-ssr, see Server rendering below.
const text = RemotePersistence.dehydrate(
  RemotePersistence.snapshotOf(loaded.remote),
  { scope: userId },
)

// None when the text is refused (another scope, version, or a corrupt text).
const restored = Option.getOrElse(
  RemotePersistence.hydrate(text, { scope: userId }),
  () => RemotePersistence.emptySnapshot,
)

Data.reduce(model, RemotePersistence.hydrated(restored, { merge: 'preserve-existing' }))

// Or persist through Effect's KeyValueStore.
RemotePersistence.save(RemotePersistence.snapshotOf(model.remote), {
  key: 'remote-cache',
  scope: userId,
  maxBytes: 512_000,
})

RemotePersistence.restore({
  key: 'remote-cache',
  scope: userId,
  maxBytes: 512_000,
})

Snapshots are deterministic, versioned, scoped, and optionally size-bounded. A snapshot from another version/scope, an oversized snapshot, or malformed data is discarded and the planner refetches. Hydrated is itself a Remote Message, so hydration still changes the application through the reducer.

dehydrate and hydrate drop what has expired by the now they are given, and nothing without one: a snapshot carried into a page is whole. save and restore read Effect's Clock.

A cache kept across reloads: persistence

The calls above are the parts. persistence(Data, …) puts them together as a wiring: it restores the snapshot stored under a key, and saves the cache under that key whenever it changes.

ts
import { persistence } from 'foldkit-remote/persistence'

const cache = persistence(Data, {
  key: model => `remote-cache:${model.userId}`,
  scope: model => model.userId,
  maxBytes: 512_000,
})

// Assembled beside `Data.wiring`; the runtime provides a `KeyValueStore`,
// such as `BrowserKeyValueStore.layerLocalStorage`.
const placements = Page.assemble(Data.wiring(actives), cache)

The first restore belongs before the first frame, or a reload draws Loading until a Subscription brings the stored rows. cache.restore(model) is that restore as an Effect: resolve it as the runtime's flags, which the runtime runs with its resources before init, and start init from the Model it gives (examples/cloudflare/src/browser.ts does):

ts
Runtime.makeElement(
  placements.runtime({
    Model,
    Flags: Model,
    flags: cache.restore(initial(actor)),
    initial: (model: Model) => ({ model }),
    // …
  }),
)

After that the wiring restores only a key the Model is not restored from (a change of principal): restoring emits Hydrated { from: key }, records restoredFrom = key, and saves on each cache change thereafter.

Without restore in init, the wiring restores at start too, a frame late.

  • A restore keeps what the Model already holds. It hydrates with merge: 'preserve-existing', so a fact resumed from the server, or read since the page started, wins over the older snapshot.
  • So a change of principal is Data.forget, in the same update. What one person read, left in memory, would be kept over the next one's snapshot and then saved under their key; forget clears it as the key changes. The scope check refuses a snapshot written for another reader; it cannot see facts that are only in memory.
  • forget never brings back what it forgot. It keeps restoredFrom, so a key that does not change (a sign-out that keeps the key) is not restored again; the emptied cache is saved over its snapshot after the debounce instead. A key that changes is restored as any new key is, so both forget alone and forget with a new key are safe at a change of principal.
  • Nothing is saved before its own key is restored. Hydrated records the key it came from in model.remote.restoredFrom. Until that key is restored, nothing is saved, so the empty store at startup cannot overwrite the snapshot it has not read yet. When the key changes (a different principal), saving stops again until the new key's snapshot is in.
  • A store that cannot be read restores nothing, and so nothing is saved over it. A stored snapshot from another version or scope, or one that will not decode, is removed, and an empty snapshot is restored in its place.
  • Saving is debounced (debounce, 250 ms by default) and best-effort: a full store keeps the snapshot it had, and the next change tries again. The snapshot is built when the write happens, not on each change, so the ages are judged by the clock then.

snapshot replaces snapshotOf when an application keeps something else, such as only the edges a page shows. It is given the wiring's maxAge; build it with RemotePersistence.snapshotOf(remote, { connections, maxAge }) and change what it holds, so the ages and the order come with it.

How long a saved read lasts

A saved row or list expires a fixed time after it was fetched: the maxAge of the call that read it, or the wiring's own (one day by default). Reading it back does not make it younger: a restore keeps when each row was written and when each list's page arrived, so the next save measures from the same moment (fetchedAt + maxAge). When saving, expired entries are dropped first and any entries past maxBytes are evicted least-recently-read first; when restoring, expired entries are dropped while remaining ages stay intact.

ts
const aged = persistence(Data, {
  key: model => `remote-cache:${model.userId}`,
  scope: model => model.userId,
  maxAge: 86_400_000, // a day, the default
  maxBytes: 512_000,
})

// `inbox` and `account` are records of Surfaces, as `Data.subscriptions` takes
// them; `Data.wiring(active, { persist })` takes the same option.
Data.subscriptions(inbox, { persist: { maxAge: 7 * 86_400_000 } }) // a week, for offline
Data.subscriptions(account, { persist: false }) // never written to the device
  • A call says what becomes of what it reads. persist rides on the retention roots the call reads, so it holds for a page left too, not only for the one on screen. A call that names no persist leaves the choice to one that does: where several read the same row or list, false wins, else the longer age. A row another read reaches is kept by that read, so persist: false keeps a row off the device only where nothing else saves it.
  • Past maxBytes, what was read least recently goes first. The order is retention's own (recent): the reads of the Surfaces on screen first, then the Surfaces left, the most recently left first, then what no read reaches. A page left leaves as one batch, so its lists and reads are kept or dropped together. The first batch that does not fit is dropped with every older one, though a smaller older batch might fit, so a snapshot whose newest batch does not fit is written empty. One that cannot be made to fit (a maxBytes below an empty snapshot's size, or a snapshot with no recency to drop by) is not written, and its key is removed, so an older, smaller snapshot cannot outlive it.
  • A row a kept list names stays. A row is dropped only with every batch that reaches it, and lasts as long as the longest-lived list kept that names it, though it was fetched earlier than the list's page.
  • What expired is dropped twice. A save leaves it out, and a restore drops what expired while the snapshot sat in storage, so a page reloaded after a week paints nothing older than its maxAge allows.
  • A snapshot from before ages (version 5) is refused and its key removed, as any other version is: it carries no ages to judge, and the planner refetches.