Docs Packages
@procedures/store
The program store of the client ecosystem. A program is procedure-as-data: the aggregation that procedure.define turns into a procedure. The store keeps programs after the process ends, and procedure.load defines them again.
npm install @procedures/client @procedures/store
Example#
import { Client, LocalTransport, PROCEDURE_REGISTRY, allCoreProcedures } from "@procedures/client";
import { attachProgramStore, FileProgramStore } from "@procedures/store";
PROCEDURE_REGISTRY.registerAll(allCoreProcedures, { override: true });
attachProgramStore(PROCEDURE_REGISTRY, new FileProgramStore("./programs.json"));
const client = new Client(new LocalTransport({ registry: PROCEDURE_REGISTRY }));
// Define a program, then store it
await client.exec({
$proc: ["procedure", "define"],
input: { path: ["math", "addTen"], aggregation: { $proc: ["client", "add"], input: { a: { $ref: "input.x" }, b: 10 } } },
});
await client.exec(["procedure", "store"], { path: "math.addTen" });
// After a restart: load the stored programs, then call them
await client.exec(["procedure", "load"], { all: true });
console.log(await client.exec(["math", "addTen"], { x: 5 })); // 15
The program store#
| Backend | Where the programs are |
|---|---|
MemoryProgramStore | In the memory of the process |
FileProgramStore | In one JSON file. A lock file and an atomic rename keep the programs of two processes. |
CollectionProgramStore | In a collection storage: InMemoryStorage of @procedures/collections, ApiStorage (the collection procedures of a server) or HybridStorage (a local cache with a remote copy) |
IndexedDbProgramStore | In the IndexedDB of a browser. It is in @procedures/store/indexeddb. |
The stores of a browser#
The entry @procedures/store/indexeddb has the stores of a browser. The package root does not import it. It does not import the root of the client or zod.
IndexedDbStorageis a collection storage in IndexedDB. Refer to "The collection storage of a browser".IndexedDbProgramStorekeeps the programs in one database,procedures-programsby default.IndexedDbQueueStorekeeps the queue of aHybridStorage. Give each storage its own database.hasIndexedDb()tells if the browser has IndexedDB.MemoryProgramStoreandMemoryQueueStoreare the fallbacks.- A browser can refuse to open a database, for example in a private window. Then the first operation of a store fails.
- The store checks each record that it reads. A record of an old version or of another application is an error.
import { IndexedDbProgramStore, MemoryProgramStore, hasIndexedDb } from "@procedures/store/indexeddb";
const programs = hasIndexedDb() ? new IndexedDbProgramStore("my-app-programs") : new MemoryProgramStore();
await programs.put({ key: "reports.weekly", path: ["reports", "weekly"], program, storedAt: Date.now() });
The Composer of the site saves programs with IndexedDbProgramStore. It loads the store only when the reader opens the saved programs.
A host gives a registry its store with attachProgramStore(registry, store). The procedures use the store of the caller's registry:
| Procedure | What it does |
|---|---|
procedure.store | Writes the program of a procedure that procedure.define made. A code procedure is the error NOT_A_PROGRAM. |
procedure.load | Defines the stored programs of a path, a prefix or all. A program at the path of a code procedure is a conflict: the code stays. |
procedure.sync | push writes the programs of the registry. pull defines the stored programs. both pushes, then pulls the programs that the registry does not have. |
procedure.remote | status gives the kind of the store. connect and disconnect are NOT_IMPLEMENTED: the host makes the store. |
Without a store, procedure.store, load and sync fail with the code NOT_CONFIGURED.
A loaded program is a runtime-defined procedure, so it is data-driven: a server with an expose rule lets it call only the exposed procedures. Load programs only from a store that you trust. A host with no expose rule does not limit the calls of a program.
The versions of a program#
A stored program has the optional fields name, description and version. The store sets version on each put. It ignores the version of the input. The value is opaque: compare it, and give it back as expectedVersion.
put(program, { expectedVersion }) and delete(key, { expectedVersion }) are optimistic writes (decision D11):
- When the current record has another version, the write changes nothing. It rejects with
VersionConflictErrorof@procedures/client, with the codeVERSION_CONFLICT. - An
expectedVersionfor a key without a record is a conflict. nullexpects no record, as in the collection storages. Aputwithnullwrites only a new program.- Without
expectedVersion, the last write wins, as before.
| Backend | The version |
|---|---|
MemoryProgramStore | A counter of the store, a number. A deleted program does not get an old version back. |
FileProgramStore | A counter in the field counter of the file, a number. The lock of the file holds the test and the write together. |
IndexedDbProgramStore | One more than the highest version in the database, a number. The test and the write are one transaction. After a delete of the record with the highest version, a later put can give that version again. |
CollectionProgramStore | A revision string, for example "3-k2j9x0aq". The storage tests the version itself, with its own versionOf. |
Give the storage of a CollectionProgramStore the option versionOf: storedProgramVersion. A storage without versionOf refuses a write with expectedVersion (the code PRECONDITION_NOT_SUPPORTED).
A ProgramStore of another package can ignore the second argument of put and delete. It keeps working, but it gives no conflict check: its writes always win.
The programs of a tenant#
One program store has two scopes:
- The scope "host" is the store of a registry (
attachProgramStore).procedure.store,loadandsyncuse it, andprocedure.loaddefines its programs in the registry. - The scope "tenant" is a store of each partition.
createProgramProceduresgives the procedures of this scope. They do not define a program in a registry. A view lists the programs, and a caller starts one withclient.chainorclient.exec.
import { createRegistry, type PartitionResolver } from "@procedures/client";
import { createProgramModule, MemoryProgramStore, type ProgramStore } from "@procedures/store";
// The tenant comes from the principal. The input only selects a scope under it.
const partition: PartitionResolver = (ctx, requested) => {
const tenant = ctx.principal?.claims?.["tenant"];
if (typeof tenant !== "string") return null;
return requested === undefined ? tenant : `${tenant}/${requested}`;
};
const stores = new Map<string | undefined, ProgramStore>();
const storeFor = (name: string | undefined): ProgramStore => {
if (!stores.has(name)) stores.set(name, new MemoryProgramStore());
return stores.get(name)!;
};
const registry = createRegistry(createProgramModule({ partition, storeFor }));
| Procedure | What it does | Effects |
|---|---|---|
programs.save | Writes { path, program, name?, description?, expectedVersion? }. It gives the stored record with its new version. | It reads and writes programs. |
programs.get | Reads { path } or { key }. A missing program is the error NOT_FOUND. | It reads programs, and writes nothing. |
programs.list | Reads the programs of { prefix? }, sorted by key. | It reads programs, and writes nothing. |
programs.remove | Deletes { path, expectedVersion? }. It gives { removed, key }. | It writes programs, and it is destructive. |
- Each procedure takes an optional
partition, which only selects. The resolver gets the context and the requested partition, and it decides. - A
nullresult of the resolver refuses the call withFORBIDDEN, reasonpartition-not-allowed, ascreateCollectionProceduresdoes. - The function
storeForgives the store of a partition. Give the same store for the same partition each time, and a store of its own to each tenant. Thus one tenant does not read the programs of another tenant. programs.savechecks the record withcheckStoredProgram, and the program with the check ofprocedure.define. It takes the program as data (the tagraw-input), so the save runs nothing of it.- The option
namespacechanges the first segments of the paths. The default is["programs"].createProgramProceduresgives the procedures as a list, andcreateProgramModulegives them as a module. - An import registers nothing. The entry is the package root only, because a host serves the programs. A browser uses the procedures of its server.
Under a read-only capability ({ effects: { writes: [] } }, or hostPolicy({ readOnly: true })), programs.get and programs.list work. programs.save and programs.remove are refused with FORBIDDEN, reason effects-exceeded. A saved program that a read-only caller starts with client.chain gets the same refusal at each step that writes.
The storage layer#
These parts moved here from @procedures/client (roadmap 3.2):
ApiStorageandHybridStorage, the collection storages that need aClient. Before, they were in@procedures/client/collections.- The synced registry (
createSyncedRegistry(),SyncedProcedureRegistry), the serialization of procedures, and the dynamic handler loader with an allowlist (createDynamicHandlerLoader). procedure.register, which registers a procedure from a handler reference.
An import of @procedures/store/register registers its procedures. An import of the package root registers nothing.
The contract of ApiStorage and HybridStorage#
The contract suite of @procedures/collections/testing tests ApiStorage, and HybridStorage in each mode. The two storages agree with InMemoryStorage and SqliteStorage:
Copies. A change of a written or a read value does not change the stored item.
HybridStoragetakes a copy of each written value for the local copy, the queue and the remote. The values thatApiStoragesends and reads go through the transport.null. A storednullreads back asnull.ApiStorage.get()sends{ id, found: true }to the procedurecollections.<name>.get. The procedure then gives{ found, value }in one call.The order of a delta.
getChangesSince()follows the order of the last change of each id.The ids.
getIds()gives the ids in the order of the entries.ApiStorage.getIds()uses the procedurecollections.<name>.ids, so the values stay on the server.After
close(). Each operation rejects with an error whose message says "closed". A secondclose()does nothing.The queries.
query(selector, { sort, skip, limit })gives the result ofqueryEntries()of@procedures/collections.ApiStorage.query()sends the JSON selector to the procedurecollections.<name>.find, so the server applies it.The patches.
ApiStorage.patch(id, fields)sends a patch to the procedurecollections.<name>.patch. The server changes the item in one step. A patch is a JSON Merge Patch, or the operations{ $set, $unset, $remove, $insert }. An index of$removeor$insertis a position at the time of the patch. A client that works from an older read uses the version check of the collection, where the collection has one.The query policy. The server applies the policy of its host to each
find. The default policy does not permit$regex, and afindgets at most 1000 items.The preconditions.
set,deleteandsetBatchtake an expected version of the current item (roadmap CLI-16).ApiStoragesends it to the collection procedures, and the storage of the server tests it. A conflict rejects withVersionConflictError, with the current items. A storage that cannot test it rejects the write.
Notes:
- A custom
serviceor a customgetoperation gets the input{ id }, as before. Itsnullreads back asundefined. - A custom
servicegets no expected version.ApiStoragerejects a write with one, so the precondition is not lost. HybridStoragegives the expected version of a caller to its local copy. The default local copy gets the optionversionOfof the storage. Inwrite-throughmode, the remote write gets it too. Inremote-onlymode, only the remote tests it.- A server before the procedure
findanswersNOT_FOUND. ThenApiStorage.query()reads the entries and applies the query in the client, with the same result. ApiStorage.find(predicate)reads each item, because a function cannot go over the network. Usequery()with a selector to filter on the server.HybridStorage.query()reads the local copy, or the remote inremote-onlymode. Its optionqueryPolicygoes to the storage under it.ApiStorage.query()examines the form of a selector before it sends it. Its optionqueryPolicyadds the limits of the client.- A host turns
$regexon withserver.registerCollectionProcedures(name, { queryPolicy })orcreateCollectionProcedures(name, { queryPolicy }). - A server before
foundignores it and gives the item. Then a storednullreads back asundefined, as before. - A server before the procedure
idsanswersNOT_FOUND. ThenApiStorage.getIds()reads the ids from the entries, and it does not ask foridsagain. HybridStorage.close()waits for the operations, the switch and the syncs that run. Then it sends the queue, and it closes the remote and the local copy.SyncedProcedureRegistry.close()closes its storage. After it,register()andunregister()change only the registry in memory.
The collection storage of a browser#
IndexedDbStorage of @procedures/store/indexeddb keeps the items of one collection in IndexedDB (roadmap CLI-22). It is the durable local copy of a HybridStorage in a browser app without SignalDB.
- Give each collection its own database. The storage makes the database at the first operation.
- The items stay after
close()and after a reload of the page. A new storage of the same database reads them. - The entries keep the order of the first set of each id, as a
Mapdoes. Each record keeps the number of its first set. getChangesSince()gives the changes after a version. A version stays valid after a reload.- Each write is one transaction of IndexedDB. A batch that fails changes nothing. Two patches at the same time keep each field.
query()applies a selector.patch()changes an item in one transaction.observe()tells each write of this storage before the write resolves. It does not tell the writes of another tab.- With the option
versionOf, a write can expect the version of the current item. The test and the write are one transaction. - The storage checks each record that it reads. A record of another application or of another version is an error.
- The contract suite of
@procedures/collections/testingtests the storage, and aHybridStoragewith the storage as its local copy. InMemoryStorageof@procedures/collectionsis the fallback for a browser without IndexedDB.
import { ApiStorage, HybridStorage, IndexedDbQueueStore, IndexedDbStorage, IndexedDbSyncStateStore } from "@procedures/store/browser";
const versionOf = (user: User) => user.rev;
const users = new HybridStorage(new ApiStorage(client, { collection: "users" }), {
local: new IndexedDbStorage<User>("users", { versionOf }),
versionOf,
queueStore: new IndexedDbQueueStore("users-queue"),
syncState: new IndexedDbSyncStateStore("users-sync"),
});
The db of an artifact page#
ArtifactDbStorage gives one collection of the db of an artifact page as a CollectionStorage. The page gets the db from its host with window.claude.use("db").
- Each item is one document
<collection>/<id>with the body{ value, order }. The storage ignores a document of another writer. - An id with characters outside the path grammar of the db is escaped as
~XXfor each byte of UTF-8. A list gives the id back. - The entries keep the order of the first set of each id. The field
orderkeeps it on the db. - The db has no versions. A write with an expected version rejects with a
TypeError. - An error with the code
unavailableorresource_exhaustedgivesArtifactDbErrorwith the codeUNAVAILABLEandretryable: true. AHybridStoragethen keeps its queue. - An error with the code
invalid_argumentgives the codeVALIDATION_ERROR, and the write leaves the queue of aHybridStorage. - The module imports nothing at run time. The contract suite of
@procedures/collections/testingtests it.
import { ArtifactDbStorage, HybridStorage, IndexedDbQueueStore, IndexedDbStorage } from "@procedures/store/browser";
import { ms } from "@procedures/client/browser";
const db = await window.claude.use("db");
const notes = new HybridStorage(new ArtifactDbStorage<Note>(db, { collection: "notes" }), {
mode: "write-back",
local: new IndexedDbStorage<Note>("notes"),
queueStore: new IndexedDbQueueStore("notes-queue"),
syncInterval: ms(3000),
});
The modes of HybridStorage#
HybridStorage keeps a local copy of a remote collection storage. It has five modes, and setMode() changes the mode while the storage operates.
| Mode | Reads | Writes | Remote calls |
|---|---|---|---|
local-only | The local copy | The local copy and the queue | None |
write-through | The local copy, and the remote on a miss | The local copy, then the remote | Yes |
write-back | The local copy, and the remote on a miss | The local copy and the queue. A timer sends the queue. | Yes |
remote-only | The remote | The remote | Yes. The storage keeps no local copy. |
read-only | The local copy, and the remote on a miss | Refused with ReadOnlyError | Reads and pulls only |
import { minutes } from "@procedures/client";
import { ApiStorage, HybridStorage } from "@procedures/store";
import { FileQueueStore } from "@procedures/store/file-queue";
const users = new HybridStorage(new ApiStorage(client, { collection: "users" }), {
mode: "write-back",
queueStore: new FileQueueStore("./users.queue.jsonl"),
versionOf: (user) => user.etag,
conflictResolution: "remote",
pullInterval: minutes(1),
});
await users.setMode("local-only"); // No remote call. The writes wait in the queue.
await users.setMode("write-through"); // The switch sends the queue, then syncs the local copy.
The switch#
- A switch waits for the operations that run. An operation that starts during the switch waits for the switch.
- A switch to a remote mode sends the queue first. When the remote fails, the mode stays, and
setMode()throwsModeSwitchError. - A switch to
local-onlymakes no remote call. The queue stays until the next switch to a remote mode. - A switch to
remote-onlydrops the local copy after the queue arrives at the remote. - A switch from
local-onlyorremote-onlyto a mode with a local copy syncs the local copy. The reads wait for the sync. - The switches and the syncs run one at a time.
The queue#
- In the modes
local-onlyandwrite-back, each write goes in the queue. - In the mode
write-through, a write that the remote cannot take goes in the queue, and the write throwsPendingWriteError. - By default, a write that the remote cannot take is an error with
retryable: true, an error without acode, or aTIMEOUT. The optionisUnavailablechanges it. - The mode
read-onlyrefuses each write withReadOnlyErrorat once. The local copy, the queue and the remote do not change. - A switch to
read-onlysends the queue first, and a failed send keeps the old mode. A queue that a store loads or thatcaptureadds in this mode waits for a mode that writes. - A full queue refuses the next write with
QueueFullError. The limit ismaxOfflineOps, 1000 by default. - A push keeps a write that the remote cannot take at this time (
isUnavailablegives true). This write and the later writes stay in the queue. - A queued write that the remote refuses leaves the queue, and the push goes on with the next write.
- A refusal is an error for which
isRefusalgives true. The default codes areFORBIDDEN,VALIDATION_ERROR,INVALID_REQUEST,NOT_EXPOSEDandNOT_DECLARED. - Another error, for example
TIMEOUTorUNAUTHORIZED, keeps the write at the head of the queue. The next push sends it again. - After a refusal, the local copy gets the remote values of its ids again. An id that a later queued write changes keeps its local value.
- The option
onRefusedgets each refusal: the write, its ids, the error, andrestored. An error of the hook does not stop the push. - The option
onDroppedgets each queued write that leaves the queue with no send that the remote took. The causes are a conflict that the policyremotedecides, a delete of the remote, and a refusal. It gets one call for each id, with the value, the reason and the sync.getMetadata()gives the count asstats.dropped. - The hook can write the value again. The sync waits for the hook, and an error of the hook does not stop the sync. After a crash, the hook can get a write again.
- The option
queueStorekeeps the queue. The storage writes each change to the store before the write ends. - A new storage with the same store loads the queue, shows its writes, and sends them.
MemoryQueueStoreis the default.FileQueueStorekeeps the queue in a JSON Lines file, for Node.FileQueueStoreis in@procedures/store/file-queue, because it usesnode:fs. The package root does not import it.IndexedDbQueueStorekeeps the queue in IndexedDB, for a browser. It is in@procedures/store/indexeddb.
The local copy#
- The option
localgives the storage of the local copy. The default is a newInMemoryStorage. - A durable local copy keeps the items after a restart.
SqliteStorageof@procedures/sqlitekeeps them in a SQLite file. IndexedDbStorageof@procedures/store/indexeddbkeeps them in the IndexedDB of a browser.- With a durable local copy, a new storage in
local-onlymode reads the items of the last run. It makes no remote call. - Give a durable
queueStorewith a durable local copy. A restart applies the loaded queue to the local copy again, and the result does not change. - The first sync after a restart reads all remote items. It removes each local item that the remote deleted and that no queued write changes.
- A full sync reads the local ids with
getIds()of the local copy.InMemoryStorage,SqliteStorageandIndexedDbStoragegive the ids without a copy of the values. A local copy withoutgetIds()gives its entries. HybridStorage.getIds()gives the ids of the local copy, or of the remote inremote-onlymode.close()closes the local copy and the remote. A durable local copy keeps its items. A remote stays open when its ownclose()leaves it open, asApiStorage.close()leaves the server.
import { ApiStorage, HybridStorage } from "@procedures/store";
import { FileQueueStore } from "@procedures/store/file-queue";
import { SqliteStorage } from "@procedures/sqlite/storage";
const users = new HybridStorage(new ApiStorage(client, { collection: "users" }), {
mode: "write-back",
local: new SqliteStorage({ path: "./users.db", table: "users" }),
queueStore: new FileQueueStore("./users.queue.jsonl"),
});
The sync, the versions and the conflicts#
- A sync asks the remote for the changes since the version of the last sync.
ApiStorageuses the procedurecollections.<name>.changes. - A remote without a change log gives all its entries.
- The option
versionOfgives the version of an item, for example its ETag. - With versions, a conflict is a queued local write of an id whose remote version changed. The option
conflictResolutiongives the result. - The values of
conflictResolutionarelocal,remote,mergewithmergeFn, anderror. Witherror, the sync throwsConflictError.
The conflict policies#
The default policy is remote. A change of the default changes the behavior of each caller, so the default stays remote (roadmap CLI-109).
Each example below starts from the same conflict. The remote holds { n: 1, rev: "1" }. The storage queues the local write { n: 5 } with the base version "1". Before the push, another writer writes { n: 9, rev: "2" }.
| Policy | Result | Example |
|---|---|---|
remote (the default) | The remote item replaces the local item. onDropped gets the local value and the remote value. | The local copy and the remote hold { n: 9 }. The hook gets { value: { n: 5 }, remote: { n: 9 }, reason: "conflict" }. |
local | The queued write replaces the remote item. The write of the other writer goes. | The remote holds { n: 5 }. |
merge | mergeFn(local, remote, base) gives the item, and a new queued write sends it. | A merge that adds the changes of both sides gives { n: 13 }: 1 + (5 - 1) + (9 - 1). |
error | The sync throws ConflictError with the ids. The queue and the remote keep their items. | The application reads error.ids, which is ["a"], and decides. |
type Counter = { n: number; rev: string };
const mergeCounters = (local: Counter, remote: Counter, base: Counter | null | undefined): Counter => ({
...remote,
n: local.n + remote.n - (base?.n ?? 0),
});
const storage = new HybridStorage<Counter>(remote, {
versionOf: (item) => item.rev,
conflictResolution: "merge",
// The option type is generic over the item: a merge of one item type needs the cast
mergeFn: mergeCounters as NonNullable<HybridStorageOptions["mergeFn"]>,
});
- Without versions, a queued write always wins. A local value that differs from the remote value is a conflict.
- A pull reads a local item only when the result depends on it. A pull does not read the item of a queued write that wins.
- With versions, the storage knows the version of each local item that it wrote or read. Then a pull reads a local item only for a conflict, or when the version is not known.
- Without versions, a pull reads each local item without a queued write. It compares the JSON of the local item and the remote item.
- The option
pullIntervalstarts a periodic pull in the modeswrite-through,write-backandread-only.close()stops it.
The base versions on the server#
With versionOf, the push of a queued write sends its base version as the expected version (roadmap CLI-16, decision D11). The base version is the remote version of the id when the local write went in the queue. The server then refuses a write over a change of another writer.
- The remote answers
VERSION_CONFLICTwith the current item. The storage gives the conflict toconflictResolution, as a conflict of a pull. remote: the remote item replaces the local item, and the queued writes of the id go.merge:mergeFngives the item. A new queued write sends it, with the current version as its base.local: the current version becomes the base, and the push sends the queued write again. It replaces the remote item.error: the push throwsConflictErrorwith the ids. The queue and the remote keep their items, and the next push tries again.- A remote item that is the value of the queued write is not a conflict. An earlier send reached the remote, and its answer was lost. A queued delete that finds no remote item is also not a conflict.
- When each id of the queued write is such an echo, the write leaves the queue with no further send. Thus a subscriber of the remote gets no second change event (roadmap O69).
- When only some ids of a batch are echoes, the batch does not leave the queue. The policy decides for the other ids, as before.
- An id without a known base version gets no expected version. Its queued write wins, as before.
- The remote must test the precondition: an
ApiStorageof the collection procedures over a storage with the sameversionOf. A remote that cannot test it refuses each push.
The base value of a three-way merge#
With versionOf and the policy merge, a queued write also keeps its base value (roadmap CLI-109). The base value is the remote item at the base version.
mergeFn(local, remote, base)gets the base value as its third argument. Thus a merge can keep the changes of both sides.baseisnullwhen the remote had no item at the base version.baseis undefined when the storage does not know the item at the base version. An example is a write after a restart, before a sync reads the item.- The queue store keeps the base values with the queued writes. A restart does not lose them.
- An operation that an older version queued has no base value. It loads, and its merge gets undefined.
- A merge function with two parameters works as before.
- The other policies keep no base value.
- A write of the storage reads its base value from the local copy before the write.
- A captured change of
capture: "observe"has no value before it. Thus with capture, the storage keeps in memory the remote value of each id that a sync reads. - The option
sendBaseVersions: falsestops the expected versions. Then a queued write replaces the remote item, as before CLI-16. - A write of the mode
write-throughgoes to the remote directly. It sends only the expected version of its caller.
The overlaps of a merge#
A merge can keep only one side of a path. mergeFn reports these paths with its fourth argument, context (roadmap CLI-109).
context.overlap(paths)reports the paths where the merge kept only one side, for example["title"].- Each call during the merge gives one call of
onDroppedwith the reasonoverlap. - The report holds the local value,
remote,base,mergedandpaths, and the sync of the conflict. baseis undefined when the storage does not know the base value, for example for an operation from an older version.- The merged write of an overlap stays in the queue, and the push sends it.
getMetadata()counts the reports asstats.overlaps, not asstats.dropped. - A call of
context.overlapafter the end of the merge changes nothing. - A merge function with two or three parameters works as before, and gives no report.
const mergeTitle = (local: Note, remote: Note, base: Note | null | undefined, context: MergeContext): Note => {
if (base && local.title !== base.title && remote.title !== base.title) context.overlap(["title"]);
return { ...remote, body: local.body };
};
The clock, the backoff and the status#
The timers and the retries run on a clock: Clock of @mark1russell7/service/clock. A test gives fakeClock of @mark1russell7/service/testing, and the times are then exact.
- The option
clockofHybridStorageand ofApiStoragegives the clock. The default isrealClockof@procedures/client. - The timers of
HybridStoragedo not keep a Node process alive. These timers are the push ofwrite-back, the periodic pull, and the send of the queue after a failure. - After a failed run of a timer, the next delay grows with
backoffDelayof@mark1russell7/service/backoff. The optionbackoffgives thefactor, themaxDelayand thejitter. - A run that succeeds sets the delay back to its interval.
ApiStoragewaitsbackoffDelaybetween its tries, with full jitter. The options areretryDelay,retryFactor,maxRetryDelayandretryJitter.- An error with
retryAfterMsgets at least that wait. - The timeout of each call of
ApiStorageuses the clock too.
HybridStorage.getStatus() gives the state of the sync. onStatus(listener) sends the status at each change. The storages of this package do not write to the console.
| Field | Value |
|---|---|
connected | False after a remote call failed, until a remote call succeeds |
pendingChanges | The number of operations in the queue |
syncing | True while a push or a pull runs |
lastSync | The time of the last pull that succeeded |
mode | The mode of the storage |
error | The newest failure of a load, a push, a pull, the queue store or the sync state store, with its operation and its error. A later success of the same work clears it. |
const stop = users.onStatus((status) => {
if (status.error) showBanner(`The sync failed: ${String(status.error.error)}`);
else if (status.pendingChanges > 0) showBanner(`${status.pendingChanges} changes wait for the server`);
});
SyncedProcedureRegistry takes the option clock for its auto-sync. Its getStatus() and onStatus() give the failures of the auto-sync and of the write-through writes.
The changes, the capture, the sync state and the push feed#
HybridStorage is a sync engine for each local copy: InMemoryStorage, SqliteStorage, IndexedDbStorage or a SignalDB collection (server stack D9, CLI-21, CLI-15).
observe(observer)gives one batch ofset,deleteandclearchanges for each change of the storage.- A write of the storage gives its batch with the
originof its options. A pull and a delta of the feed give their changes with the originsyncOrigin,"sync"by default. - The option
originis the tag of the storage. Each write of the storage to the local copy and to the remote has it. - With
capture: "observe", the storage observes the local copy. It puts each change with another origin in the queue. Thus the application can write to the local copy directly. - A captured change always goes in the queue, because the application made it already. In
write-throughmode, the storage sends it at once. - The option
syncStatekeeps the cursor and the base versions. A new storage with the same store asks only for the changes since the cursor. MemorySyncStateStorekeeps the state in memory.IndexedDbSyncStateStoreof@procedures/store/indexeddbkeeps it in a browser.- The storage uses a loaded cursor only with the option
localand a local copy that has items. Give the state store with a durable local copy. - The option
feedtakes a push feed of the remote changes, for exampleEventsChangeFeed. The storage subscribes in the modeswrite-through,read-onlyandwrite-back. - A delta whose
sinceis the cursor of the storage applies without a read of the remote. - A gap, a lost event, a new subscription or another delta makes the storage pull the changes since its cursor.
- A delta that comes during a pull applies after the pull. Thus a pull does not erase a change that came during it.
- In
write-throughmode, a pull or a delta does not write over an own write that waits for the remote. After the write, the storage reads the id again, and the rules of a pull decide. - With
versionOf, the storage keeps the versions of its own writes until their echoes come. The echo of an older own write does not write over a newer local write. - The option
echoWindowgives the time that the storage waits for an echo. The default is 30 seconds.
EventsChangeFeed subscribes to the change events of the core collection procedures. Each write of collections.<name>.* publishes { since, version, changed, deleted, origin } on the topic collections.<name>.
- An event has the ids and the versions, and no value. The storage reads the values with
changes, so the checks of a read apply. A hint with only deletes applies without a read. - A subscriber must have a capability that reads
collection:<name>, as for a read. - With
changeEvents: { values: true }on the server, the events also have the values. Each row passes the output filter of the host for each subscriber, and a refused id goes inwithheld. - An event with a value for each changed id applies without a read. An event with a withheld id makes the storage pull.
- The syncs of one storage run one at a time: the deltas, the hints, the pulls, the pushes and the mode switches. Thus a remote delta and a full sync do not run at the same time.
import { ApiStorage, EventsChangeFeed, HybridStorage } from "@procedures/store";
import { IndexedDbQueueStore, IndexedDbSyncStateStore } from "@procedures/store/indexeddb";
const users = new HybridStorage(new ApiStorage(client, { collection: "users" }), {
local: signalDbStorage,
capture: "observe",
versionOf: (user) => user.rev,
queueStore: new IndexedDbQueueStore("users-queue"),
syncState: new IndexedDbSyncStateStore("users-sync"),
feed: new EventsChangeFeed(client, { collection: "users" }),
});
- The source of an
EventsChangeFeedis aClient, aWebSocketTransport, or another transport of@procedures/client.Client.subscribe()sends the subscription through the middleware of the client. - The delivery of the events is at most once. Thus the feed gives each loss to the storage, and the storage pulls.
- The server serves the events with the option
eventsofProcedureServer, for example{ topics: ["collections.*"] }. Without a subscriber, the procedures publish nothing. ApiStoragesends theoriginof a write to the procedure. Thus the storage of the server and the event have it.
The hook around a remote apply#
The option aroundRemoteApply puts each apply of the remote changes inside a hook. For example, the hook starts a span of a trace with the traceparent of the server.
- The hook gets
hint,applyandcontext. It startsapplyone time and gives back its promise. context.causeis"delta","hint","gap"or"pull".context.hintshas the hints of the apply.- A delta and a hint of the feed give their hint. A gap and a pull of the storage give the hint
undefined. - A pull of the storage is the timer of
pullInterval,syncFromRemote(),sync()or the first sync. - A pull that many hints asked for runs one time. Its hint is the last hint, and
context.hintshas the last 128 hints. EventsChangeFeedputs the other fields of a change event inhint.extra, for exampletraceparentandtracestate.- An error of
applyor of the hook makes the pull fail. The status keeps the error until a pull succeeds. - When the hook does not start
applyone time, the pull fails withRemoteApplyHookError. The changes apply one time all the same. - Only the leader of a
TabCoordinatoror aTabGroupuses the hook. Give the hook in the optionhybrid. - Without the hook, the storage applies the changes as before.
import { context, propagation, trace } from "@opentelemetry/api";
const tracer = trace.getTracer("app");
const users = new HybridStorage(new ApiStorage(client, { collection: "users" }), {
feed: new EventsChangeFeed(client, { collection: "users" }),
aroundRemoteApply: (hint, apply, { cause }) => {
const traceparent = hint?.extra?.["traceparent"];
const parent = typeof traceparent === "string" ? propagation.extract(context.active(), { traceparent }) : context.active();
return tracer.startActiveSpan("users.apply", { attributes: { cause } }, parent, async (span) => {
try {
await apply();
} finally {
span.end();
}
});
},
});
The tabs of a browser#
TabCoordinator of @procedures/store/browser lets one leader tab run the sync of a HybridStorage (roadmap CLI-25). The other tabs copy its changes. Without it, each tab pulls and pushes, and each tab writes over the queue of the other tabs.
- The election uses the Web Locks API. The tab that holds the lock of the coordinator is the leader.
- Only the leader makes the
HybridStorage, withcapture: "observe"on its local copy. The followers make no remote call and start no timer. - The application writes to the local copy in each tab. A tab sends the change batches of its local copy to the other tabs on a
BroadcastChannel. observe()gives the batches of this tab and of the other tabs, each batch one time, with the origin of each change.- The leader also sends the changes of its sync. They have the origin
syncOrigin,"sync"by default. - A tab does not send again a batch of another tab.
- The leader captures the batches of the followers: its
HybridStoragequeues them and pushes them. Thus a write of a follower reaches the remote one time. - Only the leader writes to the queue store and to the store of the sync state. Give the same
IndexedDbQueueStoreandIndexedDbSyncStateStorein each tab.
The option copy tells the kind of the local copy:
"shared": the tabs open the same durable local copy, for example anIndexedDbStorageof one database. A tab gives the batches of the other tabs only to its observers."tab": each tab has its own local copy, for example a SignalDB collection. A tab writes the batches of the other tabs to its copy, and then gives them to its observers.- In the mode
"tab", a new tab gets only the changes after its start. Its local copy loads the older items itself, for example from its persistence. The optionsnapshotgives it the entries of the leader (roadmap CLI-66). - In the mode
"shared", a pull of the leader can come between the write of a follower and its capture. The tabs agree again after the push and the next pull.
A new leader and a closed tab:
- A follower keeps each own batch until the leader acknowledges it. The leader acknowledges a batch when its queue store holds it.
- A new leader tells the other tabs. Each follower then sends the batches that no leader acknowledged. Thus a write during the change of the leader reaches the new leader.
close()of the leader sends the queue, and then it releases the lock. The queue store keeps the operations that the remote did not take.- When the browser closes the tab of the leader, the browser releases the lock. The next leader loads the shared queue store and pushes the queue.
- When the leader stops during a push, the next leader sends the operation again. A set or a delete gives the same result two times.
- The load of the queue writes the queued operations to the local copy again. Thus the observers can get them again, with the origin
syncOrigin. close()of a follower stops its lock request.close()does not close the local copy, because the application owns it.
A setup that fails (roadmap CLI-67):
- A tab becomes the leader only after its
HybridStorageloaded the queue. Until then, the tab is a follower. - When
remote()throws or the load of the queue fails, the tab gives the error toonError. Then it releases the lock, and another tab can lead. - The tab stays a follower, and it asks for the lock again after a backoff. Thus a short failure does not leave the browser without a sync.
- The option
retrysets the backoff:delay(1 second),factor(2),maxDelay(1 minute) andjitter(0.5). - After
nfailures in a row, the wait isdelay × factor^(n − 1), at mostmaxDelay. The jitter makes each wait shorter by up to its fraction. - A setup that succeeds sets the wait back to
delay.close()stops a wait. - In the single mode, the tab tries its setup again after the same backoff.
- The options
clockandrandomtake the clock and the random numbers of the backoff, for examplefakeClockof@mark1russell7/service/testingin a test.
The status of the sync (roadmap CLI-65):
getStatus()gives theSyncStatusin each tab. Before the first status and afterclose(), it givesundefined.onStatus()tells each new status to a listener, one time.- The leader gives the status of its own
HybridStorage. It sends each change to the followers, and it answers the hello of a new tab with its status. - After a change of the leader, a follower keeps the last status until the new leader sends its status.
- A message keeps only values that a structured clone can copy. Thus in a follower,
error.erroris anErrorwith thename, themessageand thecodeof the error of the leader. - A tab of an older release ignores the status messages. It still copies the batches, because the version of the messages stays 1.
Without the Web Locks API or BroadcastChannel, the coordinator is in the single mode. The tab does its own sync, and it opens no channel. A browser has the Web Locks API only in a secure context, for example HTTPS or localhost.
import { ApiStorage, IndexedDbQueueStore, IndexedDbStorage, IndexedDbSyncStateStore, TabCoordinator } from "@procedures/store/browser";
const local = new IndexedDbStorage<User>("users");
const users = new TabCoordinator<User>({
name: "users",
local,
copy: "shared",
remote: () => new ApiStorage(client, { collection: "users" }),
hybrid: {
mode: "write-back",
queueStore: new IndexedDbQueueStore("users-queue"),
syncState: new IndexedDbSyncStateStore("users-sync"),
},
});
users.observe((batch) => render(batch));
users.onStatus((status) => showSync(status)); // The status of the sync, in each tab
await local.set("1", { name: "Ada" });
users.getStatus(); // The last status, in each tab
roleisfollower,leader,singleorclosed.onRole()tells each change.- The options
locksandchanneltake a lock manager and a channel factory, for example the ones of a test.nullsets the single mode. HybridStorage.whenQueued()resolves when the queue store holds the queue. The leader acknowledges the batches of the followers after it.
Many collections in one group (roadmap CLI-64):
TabGroup does the sync of many collections with one lock and one channel, for example all the collections of a tenant. With a TabCoordinator for each collection, each tab holds one lock and one channel for each collection.
collection(name, options)adds a collection to the group and gives itsTabCollection. A second use with the same name gives the same collection.- A
TabCollectionhasobserve(),onRole(),getStatus(),onStatus(),role,isLeaderandsyncStorage, as aTabCoordinator. - The options of a collection are
local,copy,remote,hybridandsnapshot, as the options of aTabCoordinator. Give a differentqueueStoreto each collection. - The leader of the group has one
HybridStoragefor each collection. Each message has the name of its collection. Each collection has its own batches, acknowledgements and status. - Each collection leads when its own queue loaded. It tells the other tabs at once, and the followers then send their batches of that collection. Thus a slow collection does not stop the batches of the other collections.
- A collection whose setup fails tries again alone after its backoff, and the other collections keep their sync.
- After a failed setup, the tab sends a status of the collection with the error (operation
load) to the other tabs. Thus a follower does not show the status of an old leader. - When no collection of the group leads or loads its queue, the tab releases the lock. It asks for the lock again after the backoff, as a
TabCoordinatordoes. - This rule also applies to a collection that the application adds after the tab got the lock. A group without collections keeps the lock until its first collection.
- The option
opengives the options of a collection from its name.collection(name)uses it. The leader also uses it for a collection that only another tab opened. - Without
open, the leader does the sync of its own collections only. A write of a follower to another collection waits in the follower until a leader has that collection. close()of the group closes each collection. A collection has noclose()of its own.- The lock and the channel of a group have the name
@procedures/store/tabs:<name>. ATabCoordinatoruses@procedures/store/tab:<name>. Thus a group and a coordinator do not share a lock or a channel. - A
TabCoordinatorsends its messages without the name of a collection, as before. Thus it works with a tab of an older release.
Warning: A
TabCoordinatorand aTabGroupdo not see each other. Thus, when you move a collection from aTabCoordinatorto aTabGroup, a tab of the older release can stay open. Then two tabs lead the collection, with one queue store and one remote. To prevent this, give new names to the queue store and the sync state store of that collection. Or close the tabs of the older release before the new release opens. The operations in the old queue store stay there until a tab loads that store.
import { ApiStorage, IndexedDbQueueStore, TabGroup } from "@procedures/store/browser";
const tenant = new TabGroup({
name: tenantId,
open: (collection) => ({
local: localCopyOf(collection),
copy: "tab",
remote: () => new ApiStorage(client, { collection }),
hybrid: { queueStore: new IndexedDbQueueStore(`${tenantId}-${collection}-queue`) },
snapshot: true,
}),
});
const notes = tenant.collection<Note>("notes");
notes.observe((batch) => render(batch));
notes.onStatus((status) => showSync("notes", status)); // The status of the sync of notes, in each tab
A snapshot for a new tab (roadmap CLI-66):
- In the mode
"tab", the optionsnapshot: truelets a new tab ask the leader for the entries of its local copy. The mode"shared"does not take the option. - The leader reads the entries of its copy with
getEntries(). It sends them in chunks ofsnapshot.chunkentries, 500 by default. - Each chunk has the number of the last batch of each tab that the entries hold.
- The new tab keeps the batches of the other tabs until the last chunk comes. Then it writes the entries to its copy, and then the batches with a later number.
- The snapshot can repeat a set. For example, a write of the leader during
getEntries()can be in the entries and also in a later batch. The second write of the set gives the same state. - The observers get the entries in one batch of sets, with the origin
syncOrigin. - The new tab keeps the values of its own writes after the snapshot. The snapshot does not delete an item that only the new tab has.
- When the leader changes before the last chunk, the tab asks the new leader. It does not use the chunks of the old leader.
- When no chunk comes in the time
snapshot.timeout(10 seconds by default), the tab gives an error toonError. Then it writes the batches that waited, without a snapshot. - In the tab that holds the lock, no other tab sends a snapshot. The snapshot ends when the collection leads. While the collection loads its queue, the wait renews itself, at most 5 times. Thus the batches wait at most 6 ×
snapshot.timeout, also when the load stops. - A leader of an older release does not answer. Thus a new tab with a leader of an older release gets the error after the timeout.
- The leader reads all the entries at one time, and the new tab keeps all the chunks until the last one. Thus a snapshot is for a copy that fits in the memory of a tab.
snapshot.chunklimits the number of entries in a message, not its bytes. Thus large items give large messages.- The snapshot is an option, because the coordinator cannot know if a local copy is durable. A copy with persistence is empty until its load ends, so an empty copy is not a sign.
The change of a storage in a server#
ProcedureServer.useStorage(name, storage, { drain: true, close: true }) first starts flush() of the old storage. Then it uses the new storage and closes the old one. When the flush fails, the old storage stays.
- The new calls use the new storage at once.
- Before the close, the server waits for the calls that took the old storage. A stream holds its storage until its end.
- The option
gracegives the longest wait, for exampleseconds(5). The default is 30 seconds. A plain number is aTypeError. - When the time ends, the server closes the old storage. A call that still uses it then fails with the error of a closed storage.
ProcedureServer.stop() closes each storage one time and removes the storages from the server. A closed storage rejects each operation. Before the server starts again, give it new storages with useStorage().
The mode of a synced registry#
createSyncedRegistry({ type: "hybrid", client, mode }) takes the first mode. setMode() of the registry changes the mode of its storage.
The browser entry#
The entry @procedures/store/browser has the parts of the store that run in a browser (roadmap CLI-19). A page imports this entry and not the package root.
HybridStorage, its errors and its types.ApiStorage, the remote storage over the collection procedures of a server.EventsChangeFeed, the push feed of the remote changes.TabCoordinator: one leader tab does the sync of aHybridStorage, and the other tabs copy its changes.TabGroup: one leader tab does the sync of many collections, with one lock and one channel.- All of
@procedures/store/indexeddb:IndexedDbStorage, the IndexedDB stores and their fallbacks in memory.
No module of the entry imports a module of Node. The modules import @procedures/client/browser and not the root of the client, because the root imports http and ws. The test src/browser.test.ts examines the imports of each module of the entry. The entry is in client.browser of package.json, so the CI check of the browser entries (scripts/check-browser-entries.ts) bundles it for a browser too.
The entry does not have these parts:
FileProgramStoreandFileQueueStore. They usenode:fs.- The procedures, the synced registry and the serialization. They import the root of the client. They are in the package root, for Node.
An import of the entry registers nothing. Its classes are the same as the classes of the package root.
import { ApiStorage, EventsChangeFeed, HybridStorage, IndexedDbQueueStore, IndexedDbSyncStateStore } from "@procedures/store/browser";
const users = new HybridStorage(new ApiStorage(client, { collection: "users" }), {
queueStore: new IndexedDbQueueStore("users-queue"),
syncState: new IndexedDbSyncStateStore("users-sync"),
feed: new EventsChangeFeed(client, { collection: "users" }),
});
The root of the files#
No input of procedure.store, procedure.load and procedure.sync names a file. Under the root of a host (mark --fs-root, procedure-server --fs-root, MCP_FS_ROOT), they use the program store of the host. The host chooses the file of a file store, also outside the root. A loaded program is data-driven, so its nested calls get their own rules.
License#
MIT