@jam-overture/ loom/ store
Persisting trees and revisions: the store contract, and an in-memory implementation.
Everything below is exported from that import. The names, the signatures and the sentences are read from the package itself rather than written here, so this page says what the copy of Loom in your node_modules says — and it changes in the same pull request the code does.
148 exports, in 24 modules. Generated from ./dist/store/index.d.ts, which is the declaration file this package publishes for @jam-overture/loom/store. Each comment inside a declaration is shown as its first paragraph. The whole of it is in that file.
Nothing to install first. Everything this import loads arrives with @jam-overture/loom itself.
No import here has everything behind it. @jam-overture/loom/store publishes 148 of the 2,237 names this package publishes. The other 2,089 are behind one of the 19 other imports, and 18 of those 19 publish nothing this one does. The imports do not nest: a name that is not on this page is not a name that does not exist, and the search at the top of the page says which import it comes from.
Some of these names are published elsewhere too: 3 by @jam-overture/loom/live — the same declarations reached through two doors, so either import gives you the same thing.
Application
application/application
The thing a customer registers with Loom, and the unit everything is stored and governed under.
applicationIdSchemaschema
const applicationIdSchema: z.ZodBranded<…>ApplicationIdtype
type ApplicationId = z.infer<typeof applicationIdSchema>;newApplicationIdfunction
A new application's id, minted when somebody registers one.
const newApplicationId: () => ApplicationIdDEFAULT_APPLICATION_IDvalue
The application every row written before applications existed belongs to.
const DEFAULT_APPLICATION_ID: ApplicationIdapplicationSchemaschema
What a deployment knows about one of its applications.
const applicationSchema: z.ZodObject<…>Applicationtype
type Application = z.infer<typeof applicationSchema>;StoreScopetype
The application a store handle speaks for.
type StoreScope = { readonly application?: ApplicationId; };
Memory
application/memory
A ApplicationStore in a Map, for a test and for a deployment with no database.
memoryApplicationStorefunction
const memoryApplicationStore: (seed?: readonly Application[]) => ApplicationStoreStore
application/store
Custody of the applications a deployment has.
ApplicationStoreErrortype
type ApplicationStoreError = /** No application under this id. */ { readonly code: "not-found"; readonly applicationId: ApplicationId; } | { readonly code: "already-exists"; readonly applicationId: ApplicationId; } /** A row the current code cannot parse, which is a row an older one wrote. */ | { readonly code: "unreadable"; readonly applicationId: ApplicationId; readonly detail: string; } | { readonly code: "unavailable"; readonly detail: string; };
ApplicationStoreErrorCodetype
type ApplicationStoreErrorCode = ApplicationStoreError["code"];applicationStoreErrorCodesvalue
The four codes, in the order a deployment meets them, for the same reason storeErrorCodes exists: anything that walks the taxonomy rather than reacting to one member otherwise keeps a copy that is silently wrong the day a fifth lands.
const applicationStoreErrorCodes: readonly ApplicationStoreErrorCode[]describeApplicationStoreErrorfunction
const describeApplicationStoreError: (error: ApplicationStoreError) => stringApplicationStoretype
Six methods, and still **no delete**.
type ApplicationStore = { /** * Record an application. Refuses an id already taken rather than overwriting, * because the thing under that id owns rows. */ readonly create: (application: Application) => Promise<Result<Application, ApplicationStoreError>>; /** One application. */ readonly get: (applicationId: ApplicationId) => Promise<Result<Application, ApplicationStoreError>>; /** * Every application, oldest first. */ readonly list: (listing?: Listing) => Promise<Result<readonly Application[], ApplicationStoreError>>; /** * Change what a person calls it, and where they say it lives. */ readonly rename: (applicationId: ApplicationId, to: { readonly name?: string; readonly host?: Patch<string>; }) => Promise<Result<Application, ApplicationStoreError>>; /** * Stop it, without losing it. Closed by its own id, or by its project * closing — `ProjectStore.close` does this to every application it holds. */ readonly close: (applicationId: ApplicationId, at: string) => Promise<Result<Application, ApplicationStoreError>>; /** The inverse, one application at a time. See `ProjectStore.reopen`. */ readonly reopen: (applicationId: ApplicationId) => Promise<Result<Application, ApplicationStoreError>>; };
Audience
audience/audience
The group of readers a form of a page was served to.
audienceIdSchemaschema
const audienceIdSchema: z.ZodBranded<…>AudienceIdtype
type AudienceId = z.infer<typeof audienceIdSchema>;newAudienceIdfunction
A new audience's id, minted when somebody defines one. Random, as every other is.
const newAudienceId: () => AudienceIdDEFAULT_AUDIENCE_IDvalue
The audience that matches every reader.
const DEFAULT_AUDIENCE_ID: AudienceIdCompose
audience/compose
A page as the reader in front of it gets it: the base tree, plus the deltas the audiences they are in have earned.
AudienceFormtype
The delta one audience earns, against the base it was authored on.
type AudienceForm = { readonly audienceId: AudienceId; readonly delta: TreeDelta; };
AudienceOverlaytype
Everything a deployment needs to serve one page to more than one audience: the rules that sort readers, and the delta each audience earns.
type AudienceOverlay = { readonly rules: readonly AudienceRule[]; readonly forms: readonly AudienceForm[]; };
ComposeErrortype
type ComposeError = /** A rule matched an audience the overlay has no delta for. */ { readonly code: "no-form"; readonly audienceId: AudienceId; } /** The base moved and this delta was authored against an older revision. */ | { readonly code: "stale-form"; readonly audienceId: AudienceId; readonly expected: number; readonly actual: number; } /** The delta is for another page. */ | { readonly code: "form-mismatch"; readonly audienceId: AudienceId; readonly treeId: string; } /** The operations did not apply, or what they produced is not a tree. */ | { readonly code: "unapplicable"; readonly audienceId: AudienceId; readonly detail: string; };
ComposedTreetype
The tree this reader gets, and the audiences that made it that.
type ComposedTree = { readonly tree: LoomTree; /** * In the order the rules gave them, which is the order the deltas were * applied in. A caller names this on the signals the page sends, so that what * was measured and what was served are the same claim. */ readonly audiences: readonly AudienceId[]; };
describeComposeErrorfunction
Shown in use on How a change reaches readers — One call, where you render
const describeComposeError: (error: ComposeError) => stringcomposeTreeForContextfunction
The page this context earns, or why it cannot be served.
const composeTreeForContext: (base: LoomTree, overlay: AudienceOverlay, context: JsonObject | undefined) => Result<ComposedTree, ComposeError>Memory
audience/memory
An AudienceOverlayStore in two Maps, for a test and for a deployment with no database.
memoryAudienceOverlayStorefunction
const memoryAudienceOverlayStore: () => AudienceOverlayStoreOverlay store
audience/overlay-store
Custody of the two things a deployment needs to serve one page to more than one audience: the **rules** that sort readers, and the **form** each audience earns.
AudienceRuleRevisiontype
One recorded state of a page's audience rules.
type AudienceRuleRevision = { readonly treeId: TreeId; readonly revision: number; readonly rules: readonly AudienceRule[]; /** Who made these the rules. Never absent: a rule nobody can be named for is not a decision. */ readonly actor: string; readonly recordedAt: string; };
AudienceFormWithdrawaltype
Who took a form out of service, and when.
type AudienceFormWithdrawal = { /** The person who undid the change, or `Loom` for a rebuild. */ readonly actor: string; readonly at: string; };
StoredAudienceFormtype
One audience's delta, as the store keeps it.
type StoredAudienceForm = { readonly treeId: TreeId; readonly audienceId: AudienceId; readonly delta: TreeDelta; readonly actor: string; /** * Absent while this form is the one its audience is served, which is what * every form `setForm` writes is, and what every form stored before * withdrawal existed is. */ readonly withdrawn: AudienceFormWithdrawal | undefined; };
AudienceFormListingtype
What a screen listing a page's audiences needs, **without the deltas**.
type AudienceFormListing = { readonly audienceId: AudienceId; readonly baseRevision: number; readonly actor: string; /** * Set where this form has been taken out of service, so a screen listing a * page's segments can say *withdrawn by Ana* rather than showing a form the * page is not serving as though it were. */ readonly withdrawn: AudienceFormWithdrawal | undefined; };
AudienceOverlayErrortype
type AudienceOverlayError = /** * Somebody else recorded rules for this page while this caller was editing * the ones they read. Nothing was written. */ { readonly code: "out-of-date"; readonly treeId: TreeId; readonly expected: number; readonly current: number; } /** * The delta is for another page. */ | { readonly code: "tree-mismatch"; readonly treeId: TreeId; readonly delta: string; } /** A row the current code cannot parse, which is a row an older one wrote. */ | { readonly code: "unreadable"; readonly treeId: TreeId; readonly detail: string; } | { readonly code: "unavailable"; readonly detail: string; };
describeAudienceOverlayErrorfunction
const describeAudienceOverlayError: (error: AudienceOverlayError) => stringparseAudienceRuleRevisionfunction
A row on the way out, checked rather than cast — the boundary every stored shape in this repository crosses the same way. These two outlive the code that wrote them by more than most: a rule is edited rarely and read on every request for as long as the page is published.
const parseAudienceRuleRevision: (row: unknown, treeId: TreeId) => Result<AudienceRuleRevision, AudienceOverlayError>parseStoredAudienceFormfunction
const parseStoredAudienceForm: (row: unknown, treeId: TreeId) => Result<StoredAudienceForm, AudienceOverlayError>AudienceRuleHistoryRequesttype
type AudienceRuleHistoryRequest = { /** Clamped by the implementation — see `clampAudienceRuleHistoryLimit`. */ readonly limit?: number; };
RecordAudienceRulesRequesttype
type RecordAudienceRulesRequest = { readonly rules: readonly AudienceRule[]; readonly actor: string; readonly recordedAt: string; /** * The revision the caller believes is current, or `0` for *this page has no * rules yet*. */ readonly expectedRevision?: number; };
AudienceRulesRecordedtype
What recording did, which is not always *appended*.
type AudienceRulesRecorded = { readonly outcome: "recorded"; readonly revision: AudienceRuleRevision; } | { readonly outcome: "unchanged"; readonly revision: AudienceRuleRevision; };
AuthorAudienceFormRequesttype
type AuthorAudienceFormRequest = { readonly audienceId: AudienceId; readonly delta: TreeDelta; readonly actor: string; };
WithdrawAudienceFormRequesttype
type WithdrawAudienceFormRequest = { readonly audienceId: AudienceId; /** Who took it out of service. Never absent, for the reason `actor` never is. */ readonly actor: string; readonly withdrawnAt: string; };
DEFAULT_AUDIENCE_RULE_HISTORY_LIMITvalue
How much of a page's rule history one read answers.
const DEFAULT_AUDIENCE_RULE_HISTORY_LIMIT = 25MAX_AUDIENCE_RULE_HISTORY_LIMITvalue
const MAX_AUDIENCE_RULE_HISTORY_LIMIT = 100clampAudienceRuleHistoryLimitfunction
const clampAudienceRuleHistoryLimit: (limit: number | undefined) => numberaudienceRulesOutcomeOffunction
What a record call should do, given the head it would append after.
const audienceRulesOutcomeOf: (treeId: TreeId, request: RecordAudienceRulesRequest, head: AudienceRuleRevision | undefined) => Result<AudienceRulesRecorded, AudienceOverlayError>AudienceOverlayReaderinterface
The read half, for the render path.
interface AudienceOverlayReader { readonly overlay: (treeId: TreeId) => Promise<Result<AudienceOverlay, AudienceOverlayError>>; /** The current rules with their revision and author, for a screen editing them. */ readonly rules: (treeId: TreeId) => Promise<Result<AudienceRuleRevision | undefined, AudienceOverlayError>>; /** * The edits this page's rules have had, **newest first**. */ readonly history: (treeId: TreeId, request?: AudienceRuleHistoryRequest) => Promise<Result<readonly AudienceRuleRevision[], AudienceOverlayError>>; /** * Every form this page holds, **withdrawn ones included**, with no deltas. */ readonly forms: (treeId: TreeId) => Promise<Result<readonly AudienceFormListing[], AudienceOverlayError>>; }
AudienceOverlayStoreinterface
Four reads and three writes, and **still no delete**, which this store shares with every other one here for a reason of its own: an audience stops being served by leaving the rules, or by having its form withdrawn — never by having its row removed. The form then matches nobody and costs a row, and the day it is wanted again the work is still there. A delete would make *we stopped serving this* and *we threw the work away* one button.
interface AudienceOverlayStore extends AudienceOverlayReader { readonly recordRules: (treeId: TreeId, request: RecordAudienceRulesRequest) => Promise<Result<AudienceRulesRecorded, AudienceOverlayError>>; /** * The form this audience earns, replacing whatever it had. */ readonly setForm: (treeId: TreeId, request: AuthorAudienceFormRequest) => Promise<Result<StoredAudienceForm, AudienceOverlayError>>; /** * Take this audience's form out of service, keeping it and saying who did. */ readonly withdrawForm: (treeId: TreeId, request: WithdrawAudienceFormRequest) => Promise<Result<StoredAudienceForm | undefined, AudienceOverlayError>>; }
audienceOverlayOffunction
The overlay a reader of the two halves assembles, shared so the backends cannot disagree about what *whole* means.
const audienceOverlayOf: (head: AudienceRuleRevision | undefined, forms: readonly AudienceForm[]) => AudienceOverlayservedFormsOffunction
The forms the render path is given: every row that has not been withdrawn, without its attribution.
const servedFormsOf: (stored: readonly StoredAudienceForm[]) => readonly AudienceForm[]audienceFormListingsOffunction
The listing a screen gets: **every** row, withdrawn ones included, with the deltas left behind.
const audienceFormListingsOf: (stored: readonly StoredAudienceForm[]) => readonly AudienceFormListing[]withdrawnFormOffunction
The row a withdrawal leaves, given the one it found.
const withdrawnFormOf: (held: StoredAudienceForm, request: WithdrawAudienceFormRequest) => StoredAudienceFormRule
audience/rule
Which audiences a reader is in, decided in the customer's own process.
AudienceValuetype
The values a clause may compare against.
type AudienceValue = string | number | boolean | null;AudienceClausetype
One context key, and the values of it this clause accepts.
type AudienceClause = { readonly key: string; /** Non-empty: a clause accepting nothing is a rule that can never match. */ readonly anyOf: readonly AudienceValue[]; };
audienceClauseSchemaschema
const audienceClauseSchema: z.ZodObject<…>AudienceRuletype
An audience, and what puts a reader in it.
type AudienceRule = { readonly audienceId: AudienceId; readonly clauses: readonly AudienceClause[]; };
audienceRuleSchemaschema
const audienceRuleSchema: z.ZodObject<…>ruleMatchesfunction
const ruleMatches: (rule: AudienceRule, context: JsonObject) => booleanaudiencesForfunction
Every audience this reader is in, in the order the rules were given.
const audiencesFor: (rules: readonly AudienceRule[], context: JsonObject | undefined) => readonly AudienceId[]Closing
project/closing
Closing a project, and the applications it holds.
ClosingErrortype
type ClosingError = ProjectStoreError /** * The project closed and an application under it did not. */ | { readonly code: "partly-closed"; readonly projectId: ProjectId; readonly detail: string; };
describeClosingErrorfunction
const describeClosingError: (error: ClosingError) => stringcloseProjectfunction
Close the project, then every application in it.
const closeProject: (projects: ProjectStore, applications: ApplicationStore, projectId: ProjectId, at: string) => Promise<Result<undefined, ClosingError>>Memory
project/memory
A ProjectStore in a Map, for a test and for a deployment with no database.
memoryProjectStorefunction
const memoryProjectStore: (seed?: readonly Project[]) => ProjectStoreProject
project/project
The grouping a person puts their applications into.
projectIdSchemaschema
const projectIdSchema: z.ZodBranded<…>ProjectIdtype
type ProjectId = z.infer<typeof projectIdSchema>;newProjectIdfunction
A new project's id, minted when somebody makes one. Random, as an application's is.
const newProjectId: () => ProjectIdDEFAULT_PROJECT_IDvalue
The project every application written before projects existed belongs to.
const DEFAULT_PROJECT_ID: ProjectIdprojectSchemaschema
What a deployment knows about one of its projects, which is as little as a grouping can be and still be one.
const projectSchema: z.ZodObject<…>Projecttype
type Project = z.infer<typeof projectSchema>;Store
project/store
Custody of the projects a deployment has — the grouping, not the thing grouped.
ProjectStoreErrortype
type ProjectStoreError = /** No project under this id. */ { readonly code: "not-found"; readonly projectId: ProjectId; } | { readonly code: "already-exists"; readonly projectId: ProjectId; } /** * Another project already names this repository. */ | { readonly code: "repository-taken"; readonly repository: string; } /** A row the current code cannot parse, which is a row an older one wrote. */ | { readonly code: "unreadable"; readonly projectId: ProjectId; readonly detail: string; } | { readonly code: "unavailable"; readonly detail: string; };
ProjectStoreErrorCodetype
type ProjectStoreErrorCode = ProjectStoreError["code"];projectStoreErrorCodesvalue
The four codes, in the order a deployment meets them, for the same reason storeErrorCodes exists: anything that walks the taxonomy rather than reacting to one member otherwise keeps a copy that is silently wrong the day a fifth lands.
const projectStoreErrorCodes: readonly ProjectStoreErrorCode[]describeProjectStoreErrorfunction
const describeProjectStoreError: (error: ProjectStoreError) => stringListingtype
What a listing is asked for.
type Listing = { /** `true` for closed only, `false` or absent for open only, `"all"` for both. */ readonly closed?: boolean | "all"; };
matchesListingfunction
Whether a row belongs in this listing, as one function both stores and both implementations use.
const matchesListing: (closedAt: string | undefined, listing?: Listing) => booleanProjectStoretype
Six methods, and still **no delete**.
type ProjectStore = { /** * Record a project. Refuses an id already taken rather than overwriting, * because the thing under that id owns rows. */ readonly create: (project: Project) => Promise<Result<Project, ProjectStoreError>>; /** One project. */ readonly get: (projectId: ProjectId) => Promise<Result<Project, ProjectStoreError>>; /** * Every project, oldest first. */ readonly list: (listing?: Listing) => Promise<Result<readonly Project[], ProjectStoreError>>; /** Change what a person calls it. */ readonly rename: (projectId: ProjectId, to: { readonly name: string; }) => Promise<Result<Project, ProjectStoreError>>; /** * Stop it, without losing it. */ readonly close: (projectId: ProjectId, at: string) => Promise<Result<Project, ProjectStoreError>>; /** * The inverse, and **not symmetric**: reopening a project does not reopen its * applications. */ readonly reopen: (projectId: ProjectId) => Promise<Result<Project, ProjectStoreError>>; };
Attribution
store/attribution
Who put this node here.
NodeChangetype
What a revision did to a node that was already in the tree.
type NodeChange = "configured" | "moved";NodeEffecttype
What a revision did to a node that is in the tree now.
type NodeEffect = "placed" | NodeChange;NodeTouchtype
One revision that touched one node, and the whole entry it came from.
type NodeTouch<Effect extends NodeEffect = NodeEffect> = { readonly effect: Effect; /** * Whether the operation named this node, as opposed to carrying it in. */ readonly named: boolean; readonly entry: StoredRevision; };
NodeAttributiontype
What is known about how a node came to be in the tree.
type NodeAttribution = { readonly outcome: "placed"; readonly nodeId: NodeId; readonly placed: NodeTouch; /** * Every touch since it was placed, oldest first. Never a placement: the * walk stops at the one that put the node here, so anything it collected * on the way changed a node that was already there. */ readonly since: readonly NodeTouch<NodeChange>[]; } /** The walk reached the start of the log without finding a placement. */ | { readonly outcome: "seeded"; readonly nodeId: NodeId; readonly since: readonly NodeTouch<NodeChange>[]; } /** The walk ran out of budget first. `since` is what it saw, not all there is. */ | { readonly outcome: "undetermined"; readonly nodeId: NodeId; readonly since: readonly NodeTouch<NodeChange>[]; };
TreeAttributiontype
type TreeAttribution = { readonly nodes: ReadonlyMap<NodeId, NodeAttribution>; /** * The oldest revision the walk read, or null when it read none. */ readonly examinedTo: number | null; /** True when the walk saw the whole log, which is what turns unplaced into seeded. */ readonly reachedStart: boolean; };
AttributionRequesttype
type AttributionRequest = { /** * How many pages of log to read before giving up on whatever is still * unattributed. Every read in Loom is bounded and this one is no exception; a * tree edited for long enough has a history no request path should fold. */ readonly pages?: number; };
DEFAULT_ATTRIBUTION_PAGESvalue
Five pages, which at the store's default page size is five hundred revisions.
const DEFAULT_ATTRIBUTION_PAGES = 5attributeTreefunction
Attributes every node in a tree, walking that tree's log backwards.
Shown in use on When something looks wrong — Who put this here?
const attributeTree: (reader: TreeReader, tree: LoomTree, request?: AttributionRequest) => Promise<Result<TreeAttribution, StoreError>>Cache
store/cache
Serving a stored page without reading its row every time, and being told the moment the row moves.
treeCacheTagfunction
The tag a cached reading of one tree carries.
const treeCacheTag: (treeId: TreeId) => stringTreeCacheinterface
Where a host's cache is reached, and the one obligation on it.
interface TreeCache { readonly readThrough: (key: readonly string[], tags: readonly string[], load: () => Promise<unknown>) => Promise<unknown>; }
cachingTreeStorefunction
A handle whose head is answered from a cache, and whose other reads are not.
const cachingTreeStore: (store: TreeStore, cache: TreeCache) => TreeStoreinvalidatingTreeStorefunction
A handle that tells a cache the log grew, every time it does.
const invalidatingTreeStore: (store: TreeStore, invalidate: (tag: string) => void) => TreeStoreDriver
store/driver
The two things every Postgres-backed store has to do with a driver's error.
isUniqueViolationfunction
Postgres reports a primary-key collision as SQLSTATE 23505, but Drizzle wraps the driver's error, so the code sits somewhere down the cause chain rather than on the error that was thrown. Walking the chain is what makes this work across drivers instead of against whichever one was tested first.
const isUniqueViolation: (cause: unknown) => booleanErrors
store/errors
What persistence can refuse, and how to say it.
StoreErrortype
type StoreError = /** No tree under this id — distinct from a tree with an empty history. */ { readonly code: "not-found"; readonly treeId: TreeId; } | { readonly code: "already-exists"; readonly treeId: TreeId; } /** * The delta names a base revision that is not the current head. This is the * whole of concurrency control: two writers racing at the same base means the * second one is refused rather than silently applied to a tree it never saw. */ | { readonly code: "revision-conflict"; readonly treeId: TreeId; readonly expected: number; readonly found: number; } | { readonly code: "delta-rejected"; readonly treeId: TreeId; readonly error: TreeError; } | { readonly code: "unavailable"; readonly detail: string; };
StoreErrorCodetype
type StoreErrorCode = StoreError["code"];STORE_ERROR_CODESvalue
Every way persistence can refuse, in the order a reader meets them.
const STORE_ERROR_CODES: readonly StoreErrorCode[]describeStoreErrorfunction
Shown in use on Going to production — When the database does not answer, your app is told which thing went wrong
const describeStoreError: (error: StoreError) => stringHistory
store/history
The tree as it was, asked of one handle.
SeedSourcetype
Where a host's trees started, by id, or undefined for a tree it cannot prove the beginning of.
type SeedSource = (treeId: TreeId) => LoomTree | undefined;seedRegistryfunction
A seed source over a fixed set of trees.
const seedRegistry: (seeds: ReadonlyMap<TreeId, () => LoomTree>) => SeedSourceTreeVersiontype
The tree as it was, or why not.
type TreeVersion = TreeAtRevision | { readonly outcome: "unseeded"; readonly treeId: TreeId; readonly revision: number; };
describeTreeVersionfunction
One sentence per answer, extending describeTreeAt with the host's case.
const describeTreeVersion: (version: TreeVersion) => stringTreeHistorytype
A reader and the seeds that make its log foldable.
type TreeHistory = { readonly at: (treeId: TreeId, revision: number) => Promise<Result<TreeVersion, StoreError>>; /** * The same question about several revisions of one tree, folded once. Keyed by * revision, as `treesAt` is, and the two-revision case is what it exists for: * a before-and-after reading is one revision against another. */ readonly atEach: (treeId: TreeId, revisions: readonly number[]) => Promise<Result<ReadonlyMap<number, TreeVersion>, StoreError>>; };
historyOffunction
const historyOf: (reader: TreeReader, seeds: SeedSource) => TreeHistoryMemory
store/memory
A store in memory: the log, the snapshot, and the invariant that ties them.
memoryTreeStorefunction
Shown in use on Testing what you built — Does your policy hold what you meant to hold?, The history of a page — Where this actually runs and Going to production — Three places state lives, and only one of them is your pages
const memoryTreeStore: (scope?: StoreScope) => TreeStoreReplay
store/replay
Replay: folding the log, and the two questions a fold answers.
ReplayMismatchtype
type ReplayMismatch = { readonly code: "delta-rejected"; readonly revision: number; readonly detail: string; } /** A gap or a repeat in the log: revisions must be consecutive from the seed. */ | { readonly code: "revision-gap"; readonly expected: number; readonly found: number; };
ReplayedTreetype
A fold, and what the fold saw on the way past.
type ReplayedTree = { readonly tree: LoomTree; readonly idHistory: IdHistory; };
replayTreefunction
A whole log, from a seed the caller can prove is revision 0.
const replayTree: (seed: LoomTree, entries: readonly StoredRevision[]) => Result<ReplayedTree, ReplayMismatch>SnapshotAudittype
What the fold noticed about ids on the way, whatever the verdict turned out to be.
type SnapshotAudit = { readonly outcome: "agrees"; readonly revision: number; readonly idReturns: readonly IdReturn[]; } /** * The fold produced a different tree — the drift this whole module exists for. */ | { readonly outcome: "diverged"; readonly revision: number; readonly stored: LoomTree; readonly replayed: LoomTree; readonly idReturns: readonly IdReturn[]; } | { readonly outcome: "unreplayable"; readonly mismatch: ReplayMismatch; };
auditSnapshotfunction
Folds a tree's log from a known seed and compares the result to the stored snapshot. A host runs this in a test or a scheduled job; nothing on a request path needs it, which is the point.
Shown in use on The history of a page — The store keeps two things, Going to production — The tables Loom creates and When something looks wrong — Is the page still what its history says?
const auditSnapshot: (store: TreeReader, treeId: TreeId, seed: LoomTree) => Promise<Result<SnapshotAudit, StoreError>>TreeAtTargettype
One revision of one tree, and the seed to reach it from.
type TreeAtTarget = { readonly treeId: TreeId; readonly revision: number; readonly seed: LoomTree; };
TreeAtTargetstype
The same question asked about several revisions of one tree, in one read.
type TreeAtTargets = { readonly treeId: TreeId; readonly revisions: readonly number[]; readonly seed: LoomTree; };
TreeAtRevisiontype
The tree as it was, or why the log cannot say.
type TreeAtRevision = /** * The fold reached the named revision. `replayed.tree.revision` equals the * revision asked for, and `replayed.idHistory` is the tenancy of every id from * the seed up to it — which is the half a caller reading counters by node id * needs, because an id that returned in between names two different nodes * either side of the comparison. */ { readonly outcome: "replayed"; readonly revision: number; readonly replayed: ReplayedTree; } /** * Not a revision this seed and this log can reach: before the seed, after the * head, or not an integer — revisions are dense integers and nothing * lies between two of them, so a fractional one is not a position the log has. */ | { readonly outcome: "out-of-range"; readonly revision: number; readonly earliest: number; readonly headRevision: number; } | { readonly outcome: "unreplayable"; readonly revision: number; readonly mismatch: ReplayMismatch; };
describeTreeAtfunction
const describeTreeAt: (answer: TreeAtRevision) => stringtreeAtfunction
The tree as it was at a chosen revision.
const treeAt: (reader: TreeReader, target: TreeAtTarget) => Promise<Result<TreeAtRevision, StoreError>>treesAtfunction
The same answers for several revisions, from one read of the log.
const treesAt: (reader: TreeReader, targets: TreeAtTargets) => Promise<Result<ReadonlyMap<number, TreeAtRevision>, StoreError>>Reseed
store/reseed
Planning a reseed: what it would take to put a stored page back to the shape its builder produces now.
NodeRevivaltype
A node the authored tree names and the stored page no longer holds.
type NodeRevival = { readonly nodeId: NodeId; readonly label: string; };
NodeRetirementtype
A node the stored page holds that the authored tree does not, so the reseed removes it.
type NodeRetirement = { readonly nodeId: NodeId; readonly label: string; };
PageMismatchtype
Why the authored tree is not a build of the stored page at all.
type PageMismatch = { readonly facet: "treeId"; readonly stored: TreeId; } /** The root is neither detachable nor insertable, so two roots are two pages. */ | { readonly facet: "rootId"; readonly stored: NodeId; readonly authored: NodeId; };
ReseedPlantype
type ReseedPlan = /** * The stored page is already the authored one, so there is nothing to propose. * Its own outcome rather than an empty operation list, because a delta carries * at least one operation and a caller that appended an empty one would * put a revision in the log that changed nothing. */ { readonly outcome: "already-authored"; readonly headRevision: number; } | { readonly outcome: "reseedable"; /** * The reseed, as operations. They become a delta when something proposes * them; the id and base revision belong to that delta, not to this plan. */ readonly operations: readonly TreeOperation[]; /** The head these operations were planned against. */ readonly headRevision: number; readonly revives: readonly NodeRevival[]; /** What the reseed writes over — the changes since seeding that it undoes. */ readonly retires: readonly NodeRetirement[]; } | { readonly outcome: "different-page"; readonly mismatch: PageMismatch; } /** * Some difference between the two trees is not expressible in the four * operations, so no reseed can be proposed. Carries every difference that * stands in the way, named and labelled, which is the half a deployment can * act on: the authored tree has to change, or the page does. */ | { readonly outcome: "unexpressible"; readonly blocking: readonly TreeDifference[]; } /** * An operation this module planned was refused by the tree it was planned * against. Nothing a caller did wrong and nothing it can fix — a bug here, * reported as a value so it surfaces as a refusal rather than a wrong page. */ | { readonly outcome: "unplannable"; readonly operation: TreeOperation; readonly error: TreeError; };
UnreseedablePlantype
type UnreseedablePlan = Exclude<ReseedPlan, { readonly outcome: "reseedable"; }>;
UNRESEEDABLE_FACETSvalue
The facets a configure cannot reach, so no plan can close them.
const UNRESEEDABLE_FACETS: readonly NodeFacet[]planReseedfunction
What it would take to carry a stored page to the tree its builder produces now.
const planReseed: (stored: LoomTree, authored: LoomTree) => ReseedPlandescribeReseedPlanfunction
const describeReseedPlan: (plan: ReseedPlan) => stringReseedDiscardsRequesttype
What a reseed writes over: every entry in the log that touched a node the reseed is about to change.
type ReseedDiscardsRequest = { readonly treeId: TreeId; /** * The reseed's own operations, as `planReseed` produced them. */ readonly operations: readonly TreeOperation[]; };
reseedDiscardsfunction
Reads the whole log once and reports the entries a reseed would write over.
const reseedDiscards: (reader: TreeReader, request: ReseedDiscardsRequest) => Promise<Result<readonly DiscardedWork[], StoreError>>Revert
store/revert
Planning a revert: reading the log to work out what undoing one of its entries would mean, without deciding anything.
RevertPlantype
type RevertPlan = { readonly outcome: "revertable"; readonly target: StoredRevision; /** * The undo, as operations. They become a delta when something applies * them; the id and base revision belong to that delta, not to this plan. */ readonly operations: readonly TreeOperation[]; /** The head these operations were planned against. */ readonly headRevision: number; /** * Revisions after the target that named a node this undo touches, so * applying it writes over what they did. Empty for a clean undo. */ readonly discards: readonly DiscardedWork[]; } /** The revision is outside the span this reader and this seed can reach. */ | { readonly outcome: "out-of-range"; readonly revision: number; /** One past the seed: the oldest revision this seed can replay up to. */ readonly earliest: number; readonly headRevision: number; } | { readonly outcome: "unreplayable"; readonly mismatch: ReplayMismatch; } /** * The target's delta cannot be inverted against the tree the replay produced. * In practice this means the seed is not this tree's history: inversion walks * the delta forward as it inverts, so a delta that applied when it was written * inverts against the state it was written for. */ | { readonly outcome: "uninvertible"; readonly revision: number; readonly error: TreeError; };
UnrevertablePlantype
type UnrevertablePlan = Exclude<RevertPlan, { readonly outcome: "revertable"; }>;
describeRevertPlanfunction
const describeRevertPlan: (plan: RevertPlan) => stringRevertTargettype
type RevertTarget = { readonly treeId: TreeId; /** The revision to undo. Its delta is the one that gets inverted. */ readonly revision: number; /** * A tree whose revision precedes the target's, to replay from. Usually * revision 0; a host that checkpoints may supply a later one. */ readonly seed: LoomTree; };
RevertTargetstype
The same question asked about several revisions of one tree, in one read.
type RevertTargets = { readonly treeId: TreeId; readonly revisions: readonly number[]; readonly seed: LoomTree; };
planRevertfunction
What undoing a revision would take, or what stands in the way.
const planRevert: (reader: TreeReader, target: RevertTarget) => Promise<Result<RevertPlan, StoreError>>planRevertsfunction
The same plans for several revisions, from one read of the log.
const planReverts: (reader: TreeReader, targets: RevertTargets) => Promise<Result<ReadonlyMap<number, RevertPlan>, StoreError>>Reading a tree back
store/source
The adapter that lets the renderer read from the store.
treeSourceFromStorefunction
The store, as the renderer's TreeSource.
const treeSourceFromStore: (store: TreeReader) => TreeSourceAudienceOverlaySourceinterface
Where a deployment's audience rules and audience-scoped deltas come from.
interface AudienceOverlaySource { readonly load: (treeId: TreeId) => Promise<Result<AudienceOverlay, TreeSourceError>>; }
composingTreeSourceFromStorefunction
The composing sibling of treeSourceFromStore — one tree per id stays the right answer for a deployment that wants it, so this is a second function rather than an option on the first.
const composingTreeSourceFromStore: (store: TreeReader, overlays: AudienceOverlaySource) => TreeSourceaudienceOverlaySourceFromStorefunction
The store, as the composition's AudienceOverlaySource.
const audienceOverlaySourceFromStore: (overlays: AudienceOverlayReader) => AudienceOverlaySourceStores
store/store
Persistence: an append-only log of accepted deltas, and the current tree as a materialised view of it.
StoredRevisiontype
type StoredRevision = { readonly treeId: TreeId; /** The revision this entry produced, so `revision - 1` is what it applied to. */ readonly revision: number; readonly proposalId: ProposalId; readonly delta: TreeDelta; readonly provenance: Provenance; /** When the runtime applied it, which is not when the model produced it. */ readonly appliedAt: string; /** * Who allowed it, when a human had to. */ readonly answeredBy?: string; };
AppendRequesttype
type AppendRequest = { readonly proposalId: ProposalId; readonly delta: TreeDelta; readonly provenance: Provenance; readonly appliedAt: string; /** Set only by the confirmation path; see `StoredRevision.answeredBy`. */ readonly answeredBy?: string; };
TreeListingtype
What a listing says about a tree without loading it.
type TreeListing = { readonly treeId: TreeId; readonly revision: number; /** The newest log entry's `appliedAt`; absent when `revision` is 0. */ readonly changedAt?: string; };
ListRequesttype
type ListRequest = { /** * Opaque to the caller: the previous page's `cursor`, passed back unread. * Absent starts at the beginning. A cursor naming a tree that has since been * removed is not an error — listing resumes from the next key after it. */ readonly cursor?: string; /** Clamped by the implementation — see `clampListingLimit`. */ readonly limit?: number; };
TreeListPagetype
type TreeListPage = { readonly trees: readonly TreeListing[]; /** `null` when this was the last page. */ readonly cursor: string | null; };
RevisionStarttype
Where a read begins. Two kinds of position, and they are not interchangeable.
type RevisionStart = { /** A cursor from a previous page's `older`/`newer`, passed back unread. */ readonly cursor?: string; readonly at?: never; } | { /** * A revision to open at. **Inclusive** — the page contains it — which is * the difference that matters: a caller naming this has been sent to a * change and wants to see it, not to resume beside it. */ readonly at?: number; readonly cursor?: never; };
RevisionReadRequesttype
type RevisionReadRequest = RevisionStart & { /** * Default `newer`, which with no cursor is the oldest page — the read a fold * wants, and the one `auditSnapshot` takes. `older` with no cursor is the * newest page, which is what a reader looking at a tree asks for. */ readonly direction?: PageDirection; readonly limit?: number; };
RevisionPagetype
type RevisionPage = PageEnds & { /** * Always ascending by `revision`, whichever end the page was taken from. */ readonly revisions: readonly StoredRevision[]; };
DEFAULT_LISTING_LIMITvalue
const DEFAULT_LISTING_LIMIT = 50MAX_LISTING_LIMITvalue
const MAX_LISTING_LIMIT = 200DEFAULT_REVISION_LIMITvalue
Larger than a tree listing's page and smaller than the journal's. A revision carries a whole delta and its provenance, so a page of these is heavier than a page of listings; but unlike telemetry records, one entry is one complete thing to read, so a page never splits something that has to be folded back together.
const DEFAULT_REVISION_LIMIT = 100MAX_REVISION_LIMITvalue
const MAX_REVISION_LIMIT = 500clampRevisionLimitfunction
const clampRevisionLimit: (limit: number | undefined) => numberFIRST_REVISIONvalue
The revision the first log entry produces. A tree is created at revision 0 and nothing in the log corresponds to that, so 1 is the oldest position a read can reach — and revisions are dense from there, one per accepted delta.
const FIRST_REVISION = 1anchorBoundfunction
An inclusive revision anchor, as the exclusive bound both implementations already page from.
const anchorBound: (at: number, direction: PageDirection) => numberanchorResumesfunction
Whether an anchored page leaves entries on the side it pages away from — the resumed a cursor gets for free and an anchor does not.
const anchorResumes: (at: number, direction: PageDirection, headRevision: number) => booleanclampListingLimitfunction
Every implementation clamps the same way, so a caller cannot ask a store for everything it holds by omitting a limit or naming a large one. The rule is shared with every other listing in Loom; only the bounds are this one's.
const clampListingLimit: (limit: number | undefined) => numberTreeStoreinterface
Three reads and two writes. head is the O(1) read §3 needs; revisions is the one §6 and the portal's provenance view need; list is how a consumer finds a tree it did not create; append is the only way a tree ever changes, so nothing can advance a revision without leaving a record of why.
Shown in use on The history of a page — Where this actually runs
interface TreeStore { readonly create: (tree: LoomTree) => Promise<Result<LoomTree, StoreError>>; readonly head: (treeId: TreeId) => Promise<Result<LoomTree, StoreError>>; readonly revisions: (treeId: TreeId, request?: RevisionReadRequest) => Promise<Result<RevisionPage, StoreError>>; readonly list: (request?: ListRequest) => Promise<Result<TreeListPage, StoreError>>; readonly append: (treeId: TreeId, request: AppendRequest) => Promise<Result<LoomTree, StoreError>>; }
TreeReadertype
The read half, for consumers that never write.
type TreeReader = Pick<TreeStore, "head" | "revisions">;Undone
store/undone
Which changes in a log have been put back.
undoneRevisionsfunction
Which revisions in this stretch of log are put back, and by which entry.
const undoneRevisions: (entries: readonly StoredRevision[]) => ReadonlyMap<number, StoredRevision>