@crubal/postgres 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,375 @@
1
+ import { type Draft, type Entry, type State } from "@crubal/engine";
2
+ /** A commit refused by a contract's quorum (7.6): the contract, and the proposal cited if any. */
3
+ export declare class QuorumRefused extends Error {
4
+ readonly contract: string;
5
+ readonly cited: string | undefined;
6
+ constructor(contract: string, cited?: string);
7
+ }
8
+ import { type Edge } from "@crubal/engine";
9
+ import type { View } from "@crubal/engine";
10
+ import type { Json, JsonObject, Record } from "@crubal/engine";
11
+ import { verifyChain, type Keys } from "@crubal/engine";
12
+ import { type Pool } from "./db.ts";
13
+ import { type Parsed } from "@crubal/engine";
14
+ import { type StepStats } from "@crubal/engine";
15
+ import { type Decision } from "@crubal/engine";
16
+ import { type Projecting } from "./projector.ts";
17
+ import { Needs } from "./working.ts";
18
+ import type { StreamEntry } from "@crubal/engine";
19
+ export type StoreOptions = {
20
+ /**
21
+ * Whether `state()` and `records.all()` may load an owner's whole state. `refuse` is for a host serving
22
+ * requests: nothing on a request path may be proportional to the catalog (brief 18, the scale rule);
23
+ * rebuild, erase and an install's restamp read whole regardless, since they are what they are.
24
+ */
25
+ wholeState?: "allow" | "refuse";
26
+ chain?: string;
27
+ /** Definitions handed in instead of read from the store's installed bundles and define writes (tests). */
28
+ projecting?: Projecting;
29
+ /** Install an unsigned bundle (development only; refused by default, docs/design/publishing.md). */
30
+ allowUnsigned?: boolean;
31
+ /** How many of the package's own records a dry run reads at a time (5,000 unless said). */
32
+ restampBatch?: number;
33
+ /** Sign each entry's hash with the owner's key (8.5): the host holds the key, the store never sees it. */
34
+ signer?: (hash: string) => string;
35
+ /** Publish every view right after each write commits (`fresh: write`); else the host calls `project`. */
36
+ fresh?: "write" | "asked";
37
+ /** The signer for a person this owner hosts (14.1), made on their first write; the host holds the key. */
38
+ hostedSigner?: (owner: string) => Promise<((hash: string) => string) | undefined>;
39
+ };
40
+ export declare class PgStore {
41
+ readonly pool: Pool;
42
+ readonly owner: string;
43
+ readonly chain: string;
44
+ readonly options: StoreOptions;
45
+ constructor(pool: Pool, owner: string, options?: StoreOptions | string);
46
+ /**
47
+ * Publish the views whose rows a write made stale (12.6): every view, or the named one, for its own
48
+ * audience or the one given. Runs outside any write transaction. Returns the stream entries published.
49
+ */
50
+ project(view?: string, audience?: string, only?: (v: View) => boolean): Promise<StreamEntry[]>;
51
+ /**
52
+ * Publish every view whole next time, with a reset on each stream (12.6.2): an index that lost rows, or
53
+ * kept rows nothing removed, is brought back to what the store holds. The named view alone when given.
54
+ */
55
+ republish(view?: string): Promise<void>;
56
+ /** The head of a view's stream for an audience (12.6.2): the last sequence number published, 0 when none. */
57
+ streamHead(view: string, audience?: string): Promise<number>;
58
+ /** The entries of a view's stream after `seq` (12.6.2). */
59
+ entriesSince(view: string, seq: number, audience?: string, limit?: number): Promise<StreamEntry[]>;
60
+ /** After a persist: mark what the entry made stale, inside the same transaction. */
61
+ private afterPersist;
62
+ private freshen;
63
+ /** Set while a bulk load runs: the per-commit publish waits for the one publish at the end. */
64
+ private quiet;
65
+ /** A bulk load that republishes at the end marks nothing stale per batch (load, `stale: false`). */
66
+ private skipStale;
67
+ /**
68
+ * Load many records as the owner's own, in batches: one entry per batch, each record set whole with its
69
+ * `sources` (or the `origin` given), the checks, rules and stale marks of a commit applying to every one;
70
+ * the views publish once at the end. For a conversion or a migration (brief 18 step 1): a million rows
71
+ * in an afternoon, not a day per hundred thousand through arrivals.
72
+ */
73
+ load(records: Record[], by: JsonObject, opts?: {
74
+ batch?: number;
75
+ at?: string;
76
+ origin?: string;
77
+ publish?: boolean;
78
+ stale?: boolean;
79
+ }): Promise<{
80
+ entries: string[];
81
+ records: number;
82
+ published: number;
83
+ }>;
84
+ private defsCache;
85
+ /** The definitions in force: installed bundles in order, then the owner's define writes. Cached per chain head. */
86
+ definitions(fresh?: boolean): Promise<Parsed>;
87
+ /** `fresh` builds the caller's own copy to try a change on (a trial reads onto it and must not touch the shared cache). */
88
+ private definitionsFrom;
89
+ /** What the store projects with: handed in, else built from its definitions. */
90
+ projecting(): Promise<Projecting | undefined>;
91
+ private projectingFrom;
92
+ /**
93
+ * Install a published version (docs/design/publishing.md): verify the hash and signature, require the
94
+ * language version at or below ours and every extended package installed at its pinned version, write
95
+ * the install entry and keep the bundle, restamp through the recipes when an earlier version was
96
+ * installed, and check the definitions that result. Refused whole on any failure.
97
+ */
98
+ install(bundle: JsonObject, keys?: Keys, at?: string, opts?: {
99
+ budgetMs?: number;
100
+ }): Promise<Entry>;
101
+ /** How many records the package's recipes would restamp, up to a limit: enough to know whether one batch holds them. */
102
+ private countOwnRecords;
103
+ /** The table of restamps in progress, made once per process for a store migrated before it existed. */
104
+ private restampsTable;
105
+ private restampsReady;
106
+ /** The restamps this owner has not finished: an install whose records are still being walked. */
107
+ pendingRestamps(): Promise<{
108
+ package: string;
109
+ version: string;
110
+ from: string;
111
+ afterOrd: number;
112
+ restamped: number;
113
+ review: number;
114
+ started?: string;
115
+ }[]>;
116
+ /**
117
+ * Carry a deferred restamp on (10.4): the package's own records after the last one done, in batches by ord,
118
+ * each batch through every stepped recipe between the versions and committed as one entry (the records
119
+ * that changed and the items for review), the progress written after each; it stops when the budget is
120
+ * spent and picks up where it left off next time. Done when a batch comes up short.
121
+ */
122
+ continueRestamp(pkg: string, version: string, opts?: {
123
+ budgetMs?: number;
124
+ at?: string;
125
+ }): Promise<{
126
+ done: boolean;
127
+ restamped: number;
128
+ review: number;
129
+ batches: number;
130
+ }>;
131
+ /**
132
+ * Mark every row of every view stale: after a reinstall or a rebuild the next publish rebuilds and
133
+ * compares every row and announces what left, and the stream keeps its numbering. (Wiping the stored
134
+ * rows instead, as before 0.1.16, made the next publish a first one, which announces no removals, so an
135
+ * index kept rows nothing ever removed: ME's index held three versions of its shop.)
136
+ */
137
+ private staleAll;
138
+ /** Well-formed access (14.12) on what an entry changed: ownership, wearing, within, and every edge written. */
139
+ /**
140
+ * What the rules produce for the records an operation changed, and for their ancestors (6.4): a plain
141
+ * write runs the productions as a border run does, so a rollup over units follows a unit written by the
142
+ * owner's own commit. Derived values land in the draft with their rule as source, so the entry's writes
143
+ * carry them like any other value; a person's value is never overwritten.
144
+ */
145
+ /** Records a `rederive` asks for, derived whether or not the operation changed them. */
146
+ private alsoDerive?;
147
+ /**
148
+ * Run the productions over records as they stand (6.4), for records written before a rule existed: one
149
+ * entry per call, holding only the derived values that changed. The ids are loaded into the working set
150
+ * and derived with their ancestors; nothing else is written.
151
+ */
152
+ rederive(ids: string[], by?: JsonObject, at?: string): Promise<Entry | null>;
153
+ private derive;
154
+ private checkWrites;
155
+ /** One record by id, from its row alone (no whole state): undefined when there is none. */
156
+ get(id: string): Promise<Record | undefined>;
157
+ /** Several records by id in one statement, in no particular order; ids with no record are left out. */
158
+ getMany(ids: string[]): Promise<Record[]>;
159
+ /** The review items still open (9.5). */
160
+ review(): Promise<JsonObject[]>;
161
+ /**
162
+ * A review decision (9.5, 11.9, 14.7, runs.md): one entry holding the review write and what it causes;
163
+ * then the intakes the decision affects are replayed (9.6), each its own entry.
164
+ */
165
+ decide(d: Decision, by?: JsonObject, at?: string): Promise<{
166
+ entry: Entry | null;
167
+ replayed: string[];
168
+ }>;
169
+ /** Replay the kept intakes a decision reaches: by facet, by contract field, or by unit spelling (9.6). */
170
+ private replayFor;
171
+ /** The compaction's two tables (schema.sql), made once per process: a store from before 0.3.33 lacks them, and the schema file is applied only to a new one. */
172
+ private compactTable;
173
+ private compactReady;
174
+ /** The drain's walk: its cursor per owner, and the record-order index it reads by; made once per process. */
175
+ private drainTable;
176
+ private drainReady;
177
+ /**
178
+ * Drain (docs/design/store.md, completion.md P): apply pending instructions to the records that have
179
+ * them, at most `rate` records per call, fifty to an entry `by: migration: drain`; the ids done and
180
+ * whether any still wait (brief 40: a walk by cursor in record order, never a count of what remains).
181
+ */
182
+ drain(rate?: number, at?: string, budgetMs?: number): Promise<{
183
+ applied: string[];
184
+ remaining: number;
185
+ }>;
186
+ /**
187
+ * Compact the projection streams (12.6.2): an entry a later entry for the same record superseded is
188
+ * dropped. Each record's latest entry stays, a removal among them, as does every `reset` marker, and the
189
+ * head keeps its number, so an index resuming from any cursor lands the same rows. A pass walks every
190
+ * current view's stream from its head DOWN in windows of `window` entries: walked that way, a record's
191
+ * latest entry is met before its earlier ones, so an earlier entry is superseded when the stored row's seq
192
+ * (a record in the view) or a removal met on the way (one that left) is above it; nothing scans ahead.
193
+ * Each window is one read of the entries' records, a lookup of their stored rows and of the removals met,
194
+ * and one delete by seq. A call stops at the budget and the next continues the pass from the cursors; when
195
+ * every stream has been walked the pass is done and the next call begins another, skipping any stream whose
196
+ * head has not moved since. Media Encyclopedia's four big streams held 2.3 million entries, 980,000 of them
197
+ * superseded, 2.3 GB of 21 (2026-10-28).
198
+ */
199
+ compact(budgetMs?: number, window?: number): Promise<{
200
+ deleted: number;
201
+ done: boolean;
202
+ }>;
203
+ /** What installing a version would restamp (10.4): per recipe and step, how many values change and how many go to review. */
204
+ dryRun(bundle: JsonObject): Promise<{
205
+ recipes: {
206
+ from: string;
207
+ to: string;
208
+ steps: StepStats[];
209
+ review: number;
210
+ }[];
211
+ records: number;
212
+ }>;
213
+ /**
214
+ * The records the package's recipes restamp (10.4): of its kinds or wearing its classes, read on the kind and
215
+ * wears indexes in batches by ord, never the catalog whole and never all of them at once.
216
+ */
217
+ private walkOwnRecords;
218
+ /** A define write (8.5, 11.4): one member of the working package as it now stands, checked with the rest first. */
219
+ define(member: JsonObject, by?: JsonObject, at?: string): Promise<Entry | null>;
220
+ /**
221
+ * The owner's state as the tables hold it, kept per chain head: the same head answers from memory; a
222
+ * head a little further on replays the entries since onto a copy (the engine's own replay), so a write
223
+ * never costs a reload of every record; a gap over 200 entries, or an entry the replay can't take,
224
+ * reads the tables whole. A commit works on a copy of the loaded state, so a kept state is never shared
225
+ * with a draft. (G6: Cashierfu carried this around the store until 0.1.15.)
226
+ */
227
+ state(): Promise<State>;
228
+ /**
229
+ * The whole state regardless of the option: for a rebuild, an erase, an install's restamp, an export and a
230
+ * test's assertions. Never on a request path: `state()` is the guarded door, this one says what it is.
231
+ */
232
+ wholeState(): Promise<State>;
233
+ /**
234
+ * A read on a working set: `fn` runs on a state whose records, bindings and runs load as it asks for them
235
+ * (by id, level, parent, target or key), and runs again until it asked for nothing new; edges,
236
+ * instructions and the working package are loaded whole (they are small). The lists (reviews,
237
+ * observations, installed, reads) are not loaded here: the readers below serve them. `fn` MUST be pure.
238
+ */
239
+ read<T>(fn: (s: State) => T, opts?: {
240
+ allowAll?: boolean;
241
+ }): Promise<T>;
242
+ /** Records by level, kind, parent, placement or one key's value, in log order; paged by `ord`. */
243
+ records(where?: {
244
+ level?: string;
245
+ kind?: string;
246
+ of?: string;
247
+ within?: string;
248
+ key?: [string, Json];
249
+ }, opts?: {
250
+ limit?: number;
251
+ after?: number;
252
+ archived?: boolean;
253
+ }): Promise<Record[]>;
254
+ /** Every edge of the owner (small: people and their grants). */
255
+ edges(): Promise<Edge[]>;
256
+ /** The install log as what is in force: every version taken, in order, less the packages that left (11.4). */
257
+ installed(): Promise<JsonObject[]>;
258
+ /** The install log whole: every version taken and every leaving, in order. */
259
+ installLog(): Promise<JsonObject[]>;
260
+ /**
261
+ * A package leaves (11.4, revision 30): refused while a package in force extends it, a utility in force needs it
262
+ * (its own excepted), or a record holds a value under a key it alone declares; else the log takes an install
263
+ * write with `left`, and the set in force is read without it.
264
+ */
265
+ leave(pkg: string, at?: string): Promise<Entry>;
266
+ /** The record a binding (`contract|ref`) names, if any. */
267
+ binding(key: string): Promise<string | undefined>;
268
+ /** The owner's working package (11.4): `<member>:<name>` → the definition as it now stands. */
269
+ defines(): Promise<Map<string, JsonObject>>;
270
+ /** Every review item ever written, decided or not, in order (9.5); `review()` is the open ones. */
271
+ reviews(): Promise<JsonObject[]>;
272
+ /** The records several bindings name, by key: one query for an import's references. */
273
+ bindings(keys: string[]): Promise<Map<string, string>>;
274
+ /** The log of reads under an emergency edge (14.13), in order. */
275
+ emergencyReads(): Promise<JsonObject[]>;
276
+ /** The observations on one record, or on or supporting any of several (9.7). */
277
+ observationsOn(id: string | string[]): Promise<JsonObject[]>;
278
+ /** Observations by what they are on or support, their evidence type and their address (9.7); never all of them unasked. */
279
+ observations(where: {
280
+ on?: string | string[];
281
+ evidenceType?: string;
282
+ address?: string;
283
+ }): Promise<JsonObject[]>;
284
+ private keptState;
285
+ /** Forget the kept state: after a rewrite of history that moves no head (an erase, a rebuild). */
286
+ forgetState(): void;
287
+ /** The owner's entries, in chain order. */
288
+ entries(): Promise<Entry[]>;
289
+ /** Lock the chain for this transaction and return its head. Writers to one chain serialize here. */
290
+ private lockChain;
291
+ /** Link an entry to the chain's head, insert it, and move the head. The entry gets its `prev`. */
292
+ private link;
293
+ /** The index of the records each entry touches, and how far it is whole (revision 50); made once per process. */
294
+ private touchTable;
295
+ private touchesReady;
296
+ /**
297
+ * Revision 50: index the entries of a log from before the index, a bounded batch at a time, oldest first.
298
+ * The chain is held for the batch, as a write holds it, so no entry lands between the read and the cursor.
299
+ * Answers how far the index is whole and the chain's head; they are equal when there is nothing left.
300
+ */
301
+ indexTouches(limit?: number): Promise<{
302
+ through: number;
303
+ head: number;
304
+ }>;
305
+ /**
306
+ * Revision 50: one record as it stood at a moment (as it stands, when none is said), and when each of its
307
+ * values last changed. Read by the index where it is whole; else by the log itself, which is slower and
308
+ * answers the same.
309
+ */
310
+ recordAt(id: string, until?: string): Promise<{
311
+ record?: Record;
312
+ changed: {
313
+ [address: string]: string;
314
+ };
315
+ }>;
316
+ /**
317
+ * A hosted person's records live in their own chain (14.1): the writes to records owned `<owner>:<id>`
318
+ * leave the owner's entry and become one entry per person, linked and signed in the same transaction.
319
+ * The chains lock in a fixed order (the owner's first, then the persons' by name).
320
+ */
321
+ private linkSplit;
322
+ /**
323
+ * Append an entry made elsewhere (a rebuilt log, a hosted person's chain the host carries): it is
324
+ * linked to this chain's head, applied with the engine's applyEntry, and its effects persisted.
325
+ */
326
+ append(entry: Entry): Promise<Entry>;
327
+ /** An empty working state with the whole small tables in it; records, bindings and runs load as needed. */
328
+ private base;
329
+ /** What the last operation loaded, for tests and for watching a store's cost. */
330
+ trace: Needs | undefined;
331
+ /** Set while an install restamps: its commit walks the package's records by design, whatever `wholeState` says. */
332
+ private walking;
333
+ /**
334
+ * One operation, one entry (8.5): the engine runs on a draft of the state, what it changed becomes the
335
+ * entry's writes (plus `extra` writes the diff can't see), and the entry is applied and persisted in the
336
+ * same transaction. Nothing happens when nothing changed; a throw inside `mutate` rolls everything back.
337
+ */
338
+ /**
339
+ * A quorum (7.6) holds a commit by hand to the same rule as a run: a cause naming a contract whose quorum
340
+ * holds must cite a met proposal (`by.proposal`), or the commit is refused before anything is written.
341
+ */
342
+ private quorumGate;
343
+ commit(by: JsonObject, mutate: (draft: Draft) => void, at?: string, extra?: JsonObject[]): Promise<Entry | null>;
344
+ /**
345
+ * The same, for an operation that decides its own cause and extra writes as it runs (a border run): it
346
+ * returns `by`, `extra` and an outcome, and the outcome comes back beside the entry.
347
+ */
348
+ commitFrom<T>(run: (draft: Draft) => {
349
+ by: JsonObject;
350
+ extra?: JsonObject[];
351
+ out: T;
352
+ }, at?: string, mark?: {
353
+ witnessed?: true;
354
+ }): Promise<{
355
+ entry: Entry | null;
356
+ out: T;
357
+ }>;
358
+ /**
359
+ * Erase a record's values from the log (8.5.2): every value write to it, and every observation on it, in
360
+ * every entry, is redacted in place; creations, envelopes and everything else stay. The state is rebuilt.
361
+ */
362
+ erase(recordId: string): Promise<{
363
+ redacted: number;
364
+ witnessed: string[];
365
+ }>;
366
+ /** Check the chain's links and, with the owner's key, its signatures (8.5). */
367
+ verify(keys?: Keys): Promise<ReturnType<typeof verifyChain>>;
368
+ /** Empty the owner's state tables and apply the log again, in order (8.5.3). */
369
+ rebuild(): Promise<State>;
370
+ /**
371
+ * Redact one write of an entry, or the whole entry (8.5.2): the log's one update, which the trigger
372
+ * admits and nothing else. The state is then rebuilt, so the cache forgets what the log forgot.
373
+ */
374
+ redact(logId: string, writeIndex?: number): Promise<void>;
375
+ }