@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.
IndexedDbStorage is a collection storage in IndexedDB. Refer to "The collection storage of a browser".
IndexedDbProgramStore keeps the programs in one database, procedures-programs by default.
IndexedDbQueueStore keeps the queue of a HybridStorage. Give each storage its own database.
hasIndexedDb() tells if the browser has IndexedDB. MemoryProgramStore and MemoryQueueStore are 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
VersionConflictError of @procedures/client, with the code VERSION_CONFLICT.
- An
expectedVersion for a key without a record is a conflict.
null expects no record, as in the collection storages. A put with null writes 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, load and sync use it, and procedure.load defines its programs in the registry.
- The scope "tenant" is a store of each partition.
createProgramProcedures gives the procedures of this scope. They do not define a program in a registry. A view lists the programs, and a caller starts one with client.chain or client.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
null result of the resolver refuses the call with FORBIDDEN, reason partition-not-allowed, as createCollectionProcedures does.
- The function
storeFor gives 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.save checks the record with checkStoredProgram, and the program with the check of procedure.define. It takes the program as data (the tag raw-input), so the save runs nothing of it.
- The option
namespace changes the first segments of the paths. The default is ["programs"]. createProgramProcedures gives the procedures as a list, and createProgramModule gives 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):
ApiStorage and HybridStorage, the collection storages that need a Client. 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. HybridStorage takes a copy of each written value for the local copy, the queue and the remote. The values that ApiStorage sends and reads go through the transport.
-
null. A stored null reads back as null. ApiStorage.get() sends { id, found: true } to the procedure collections.<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 procedure collections.<name>.ids, so the values stay on the server.
-
After close(). Each operation rejects with an error whose message says "closed". A second close() does nothing.
-
The queries. query(selector, { sort, skip, limit }) gives the result of queryEntries() of @procedures/collections. ApiStorage.query() sends the JSON selector to the procedure collections.<name>.find, so the server applies it.
-
The patches. ApiStorage.patch(id, fields) sends a patch to the procedure collections.<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 $remove or $insert is 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 a find gets at most 1000 items.
-
The preconditions. set, delete and setBatch take an expected version of the current item (roadmap CLI-16). ApiStorage sends it to the collection procedures, and the storage of the server tests it. A conflict rejects with VersionConflictError, with the current items. A storage that cannot test it rejects the write.
Notes: