@sewdn/workflow-store-localstorage
v0.1.1
Published
Browser adapters for every port of the workflow runtime, on localStorage or IndexedDB.
Readme
@sewdn/workflow-store-localstorage
Browser adapters for the ports of @sewdn/workflow-runtime. Use IndexedDB for growing workspaces in a
secure browser context. Native transactions commit whole batches, Web Locks serialize cross-tab updates, and
BroadcastChannel wakes subscriptions. The localStorage adapter also works with injected storage for tests.
import { layerIndexedDb } from "@sewdn/workflow-store-localstorage";
const stores = layerIndexedDb({ namespace: "my-app", directory: { people } });
program.pipe(Effect.provide(stores));| Export | Provides |
| -------------------------------------------- | --------------------------------------------------------- |
| layerIndexedDb({ namespace, directory? }) | every port on IndexedDB, plus StoredNotifications |
| layer(options) | every port, plus StoredNotifications |
| layerEventStore(options) | EventStore |
| layerSnapshotStore(options) | SnapshotStore |
| layerReadModelStore(options) | ReadModelStore |
| layerCommandLog(options) | CommandLog |
| layerOutbox(options) | Outbox |
| layerScheduler(options) | Scheduler |
| layerNotifier(options) | Notifier and StoredNotifications (what was delivered) |
| layerDirectory(seed) | Directory, from people and groups given, held in memory |
| clear(namespace, storage?) | removes every key of a namespace |
| @sewdn/workflow-store-localstorage/testing | makeFakeStorage, a Storage for tests |
Options: { namespace, storage?, external?, locks?, migrations? }. namespace is required, non-empty and
has no :. Layers built on one storage and namespace share its contents; layers with different namespaces
share nothing. A layer opens its namespace when built and fails with StoreUnavailable (storage not
reachable), StorageFull or UnsupportedLayout (see "Layout version"). A write past the browser's quota
fails with the runtime's StorageFull (with the key that did not fit) and leaves the store as it was.
It is built on Effect's KeyValueStore (layerStorage over the Storage API, prefix for the namespace);
the source gave no reason not to. What KeyValueStore does not give, and this package adds on top, is
everything between one setItem and the next: batches that are all or nothing, a check-and-write that cannot
be interleaved, and the mapping of a quota error to StorageFull.
Keys
Every key starts with <namespace>:. Segments that are free text (read model names and keys, command, outbox,
timer and notification ids) have % and / escaped.
| Key | Holds |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| layout | { "version": 1 }, the stored layout |
| pos | the last global position handed out |
| h/<stream> | a stream's head { sequence, chunks: [[firstSequence, lastPosition], …] }; the set of heads is the stream index |
| e/<stream>/<firstSequence> | one chunk: the events of one append, each as { position, event } |
| si/<stream>, sv/<stream>/<seq> | a stream's snapshot index (sequences) and each snapshot |
| m/<model>/<key> | one read model row |
| c/<commandId> | a command record |
| o/<id>, o-order | an outbox row and the enqueue counter; an acknowledged row keeps only its order |
| t/<timerId>, t-order | a timer and its scheduling order, and the counter |
| n/<id>, n-order | a delivered notification and its order, and the counter |
Why one chunk per append and not one key per stream: an event with a small payload is about 410 characters
stored (measured, 1 000 single-event appends: 409 000 characters, 0.14 ms per append). localStorage holds
about 5 million characters per origin, so a stream of a few hundred events is routine, and rewriting the
whole stream on every append would cost its full size each time. A chunk is written once; only the head, which
grows by about ten characters per append, is rewritten. The head is also what bounds the stream: a run with
tens of thousands of appends needs IndexedDB, which this package does not cover (an IndexedDB adapter would
also lift the 5 MB limit and the synchronous API).
Consistency
- A write is all or nothing. An append writes
pos, the chunk, then the head. A failed write restores what the earlier writes of the batch replaced, so a stream is either as before or longer by the whole batch. The same holds for every multi-key operation. - Within a tab a read-modify-write runs as one synchronous section, so concurrent fibers, and two layers on one storage in one tab, never interleave inside it.
- Across tabs the section holds a Web Lock (
navigator.locks, named after the namespace).appendalso re-reads the head inside the lock and compares it with what it read before stamping: a changed head is aSequenceConflict. Of two appends with the same expected sequence, at most one succeeds. Without the Web Locks API (locks: false, or an old browser) only the re-read remains, and a window of microseconds is open: two tabs writing in exactly that window can both pass. Use a browser with Web Locks for several tabs. - Global position is the counter
pos, bumped in the same commit as the events, so positions increase in commit order. A failed append restores the counter; a failure that could not restore leaves a gap, which is allowed. subscribescans for events above a cursor whenever something may have changed: after this layer's own appends and when another tab writes (the window'sstorageevent for thisStorage, orexternal). Catch-up and live parts are one scan loop, so there is no gap or duplicate. Events are delivered in position order; a subscription started withfrom: "now"begins at the current counter.
Quota
If storage runs out of space, the write fails with StorageFull and the adapter rolls back the batch.
IndexedDB has a separate browser quota and supports workspaces that exceed localStorage capacity. The
application controls which data to remove when a workspace needs more space.
What is kept, and what it costs
Events, read models and the command log are kept. Snapshots are not history: SnapshotStore.save keeps the
newest keep per stream (default 1; the runtime passes snapshotsKept) and removes the older ones in the
same commit that writes the new one, so a stream holds one sv/ key and its si/ index.
Measured with scripts/measure-retention.ts (bun scripts/measure-retention.ts): the memory runtime decides
the docket test plugin's commands, they are seeded into a runtime over this adapter on a fake storage without
quota, snapshotEvery 100, one workspace stream. Characters, keys plus values:
| runs | plugin records | events | snapshots kept | snapshots | read models | events | command log | total | | ---- | -------------- | ------ | -------------- | --------- | ----------- | ------ | ----------- | ------ | | 60 | 33 | 832 | 1 | 0.09M | 0.11M | 0.35M | 0.02M | 0.56M | | 60 | 33 | 832 | all | 0.38M | 0.11M | 0.35M | 0.02M | 0.85M | | 200 | 108 | 2758 | 1 | 0.31M | 0.36M | 1.16M | 0.06M | 1.89M | | 200 | 108 | 2758 | all | 4.32M | 0.36M | 1.16M | 0.06M | 5.90M | | 600 | 330 | 8309 | 1 | 0.93M | 1.09M | 3.53M | 0.18M | 5.73M | | 600 | 330 | 8309 | all | 38.85M | 1.09M | 3.53M | 0.18M | 43.65M |
Without retention, snapshots grow with the square of the history (each is the whole fold). With it, the total
grows linearly, but a browser allows about 5M characters: 600 runs still come to 5.73M (events and read
models alone 4.62M), so a workspace of that size does not fit in localStorage.
A draft with many edits
Run bun scripts/measure-draft-edits.ts 4000 to edit the sample route 4,000 times, with 80 undo and redo pairs.
The fixture retains one snapshot, taken every 100 events. Storage figures count characters in keys and values
on quota-free fake localStorage.
| 4,000-step measure | Before | With receipts and indexed history | | --- | ---: | ---: | | Total storage | 5.28M characters | 5.06M characters | | Events, including durable command receipts | 2.50M characters | 3.30M characters | | Command log | 1.68M characters | 0.61M characters | | Draft history | 0.98M characters | 1.02M characters | | Reopen | 25.86 ms | 24.76 ms, 61 stored events read | | Full history, 4,161 lines | 34.20 ms | 32.85 ms | | Last 50 lines | 28.85 ms | 7.74 ms | | Rebuild with intact derived data | 984.35 ms | 10.42 ms, 0 stored events read |
A near-head rollback took 19.91 ms and read 51 stored events. A rollback before the newest eligible snapshot can still require folding from genesis. Removing one index row forced a repair that read all 4,161 stored events and took 2.27 s during a run alongside other checks. The history keeps lines from abandoned branches because a later rollback can restore those branches.
bun browser/run.ts --scale ran the same workload in Chromium in 11.94 s. Chromium estimated 10,009,389 bytes
for the origin. A new Chromium process using the same profile read back identical draft, history and undo state
in 173.60 ms. The browser estimate includes database overhead and uses bytes.
Layout version and migrations
layout holds the layout version, layoutVersion in this build (2). An empty namespace is stamped with it.
A namespace at an older version runs options.migrations ({ from, run(rawStore) }, one step per version,
each followed by a stamp) before the layer is usable; a missing step, or a namespace newer than this build,
fails with UnsupportedLayout { found, supported } and writes nothing. rawStore is get, keys(prefix, after?),
count(prefix) and an all-or-nothing commit over keys relative to the namespace. This repository ships
no upgrade to layout 2. Use a fresh namespace or clear disposable data. IndexedDB rejects an older
layout and uses its own database version.
Not stored, or not covered
- The directory is the application's people: it is given as
directoryand held in memory. - The notifier has no channel in a browser: it stores each notification once and
StoredNotifications.deliveredlists them for the application to show. - A read of a value that is not valid JSON or not the expected shape fails with
StoreUnavailable. - The outbox keeps the id of every acknowledged entry (without its payload), so an id is never enqueued twice.
Tests
src/localstorage.test.ts runs the adapter suite on makeFakeStorage (each build in a namespace of its own)
and covers two tabs (never both succeed on one expected sequence, the compare-before-write window, positions
shared, subscribe seeing another tab), the Web Locks path, a full store (the store unchanged afterwards, half
a batch undone), persistence across builds, namespaces, layout and migrations, corrupt values.
makeFakeStorage({ quota? }) returns a Storage and tab() for further views of the same data; a write
through one view reaches the other views' external listeners. failNextWrites(n) makes writes throw.
Dispose the runtime before calling clearIndexedDb(namespace).
After building workflow-runtime, run bun browser/run.ts from this directory to check both browser
adapters in Chromium. The runner uses a disposable loopback server and opens separate tabs for writing,
subscribing, cancellation and reload.
bun run typecheck
bun run test # bun test src
bun run build