@crubal/postgres 0.0.0-stage → 0.4.1
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.
- package/README.md +126 -2
- package/dist/bin/crubal-pg.d.ts +2 -0
- package/dist/bin/crubal-pg.js +115 -0
- package/dist/bin/crubal-pg.js.map +1 -0
- package/dist/src/border.d.ts +126 -0
- package/dist/src/border.js +442 -0
- package/dist/src/border.js.map +1 -0
- package/dist/src/db.d.ts +27 -0
- package/dist/src/db.js +74 -0
- package/dist/src/db.js.map +1 -0
- package/dist/src/definitions.d.ts +25 -0
- package/dist/src/definitions.js +243 -0
- package/dist/src/definitions.js.map +1 -0
- package/dist/src/index.d.ts +9 -0
- package/dist/src/index.js +9 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/projector.d.ts +24 -0
- package/dist/src/projector.js +182 -0
- package/dist/src/projector.js.map +1 -0
- package/dist/src/schema.sql +335 -0
- package/dist/src/state.d.ts +16 -0
- package/dist/src/state.js +165 -0
- package/dist/src/state.js.map +1 -0
- package/dist/src/store.d.ts +375 -0
- package/dist/src/store.js +1603 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/working.d.ts +64 -0
- package/dist/src/working.js +315 -0
- package/dist/src/working.js.map +1 -0
- package/package.json +44 -4
|
@@ -0,0 +1,1603 @@
|
|
|
1
|
+
// store.ts: one owner's store on Postgres (docs/design/store.md). An entry is one transaction: lock the
|
|
2
|
+
// chain, build the entry, apply it with the engine's applyEntry, persist the difference, append the log.
|
|
3
|
+
// The log is the truth; `rebuild` gives every other table back from it.
|
|
4
|
+
import { compareVersions } from "@crubal/engine";
|
|
5
|
+
import { recordAt } from "@crubal/engine";
|
|
6
|
+
import { applyEntry, diffWrites, differs, MemoryRecords } from "@crubal/engine";
|
|
7
|
+
import { proposalMet, quorumHolds } from "@crubal/engine";
|
|
8
|
+
/** A commit refused by a contract's quorum (7.6): the contract, and the proposal cited if any. */
|
|
9
|
+
export class QuorumRefused extends Error {
|
|
10
|
+
contract;
|
|
11
|
+
cited;
|
|
12
|
+
constructor(contract, cited) {
|
|
13
|
+
super(cited ? `${contract} needs a met proposal; ${cited} is not one` : `${contract} needs a met proposal`);
|
|
14
|
+
this.name = "QuorumRefused";
|
|
15
|
+
this.contract = contract;
|
|
16
|
+
this.cited = cited;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
import { Engine, serialize } from "@crubal/engine";
|
|
20
|
+
import { CrubalError } from "@crubal/engine";
|
|
21
|
+
import { Access } from "@crubal/engine";
|
|
22
|
+
import { apply, pending } from "@crubal/engine";
|
|
23
|
+
import { entryHash, verifyChain, writeHash } from "@crubal/engine";
|
|
24
|
+
import { transaction } from "./db.js";
|
|
25
|
+
import { isObj, loadState, persist, wipeState, recordOf } from "./state.js";
|
|
26
|
+
import { readBundle, readBundleOnto, verifyBundle } from "@crubal/engine";
|
|
27
|
+
import { classify } from "@crubal/engine";
|
|
28
|
+
import { dryRun, restamp } from "@crubal/engine";
|
|
29
|
+
import { installsInForce, checkAll, definitionsOf, unitsExtensionOf, workingBundle } from "./definitions.js";
|
|
30
|
+
import { decideReview, openItems } from "@crubal/engine";
|
|
31
|
+
import { land, receive } from "@crubal/engine";
|
|
32
|
+
import { entriesSince, markStale, publish } from "./projector.js";
|
|
33
|
+
import { copyWorking, loadWhole, Needs, settle, workingState } from "./working.js";
|
|
34
|
+
/** A state's maps copied, so a draft can be changed without touching what was loaded. */
|
|
35
|
+
function draftOf(state) {
|
|
36
|
+
// A copy of the working state is itself a working state, so the draft notes what it lacks.
|
|
37
|
+
const s = copyWorking(state);
|
|
38
|
+
return { records: s.records, bindings: s.bindings, instructions: s.instructions, edges: s.edges, review: s.reviews };
|
|
39
|
+
}
|
|
40
|
+
/** What two definitions of one key must agree on (11.4): the type, the unit, how many, the list of values. */
|
|
41
|
+
function facetShape(f) {
|
|
42
|
+
const values = Array.isArray(f.values) ? f.values.map((v) => v.value).join("|") : "";
|
|
43
|
+
const pick = f.pick !== undefined && String(f.pick) !== "1" ? `pick ${String(f.pick)}` : "";
|
|
44
|
+
return [f.type, f.unit ?? "", pick, values].filter(Boolean).join(" ");
|
|
45
|
+
}
|
|
46
|
+
/** Is a record the package's own (10.4): of a kind it defines, or wearing a class it defines? */
|
|
47
|
+
function ownRecord(own, r) {
|
|
48
|
+
return own.dict.kinds.has(r.kind) || (r.wears ?? []).some((w) => own.dict.classes.has(w));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The records a package's recipes restamp (10.4), asked for by name from a working set: the records of
|
|
52
|
+
* each kind it defines and the wearers of each class, so a draft loads those and nothing else. Reading the
|
|
53
|
+
* catalog whole and filtering it down read a million records into memory for a recipe over a dozen
|
|
54
|
+
* (Media Encyclopedia's storefront install, 2026-10-22).
|
|
55
|
+
*/
|
|
56
|
+
function ownRecordsOf(records, own) {
|
|
57
|
+
const seen = new Set();
|
|
58
|
+
const out = [];
|
|
59
|
+
for (const name of [...own.dict.kinds.keys(), ...own.dict.classes.keys()]) {
|
|
60
|
+
for (const r of records.forTarget(name)) {
|
|
61
|
+
if (seen.has(r.id) || !ownRecord(own, r))
|
|
62
|
+
continue;
|
|
63
|
+
seen.add(r.id);
|
|
64
|
+
out.push(r);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The views a pin move can have changed, so only those are marked stale (12.6): a view whose own
|
|
71
|
+
* definition, a shape or a filter it names changed between the two versions, or that reads a facet that
|
|
72
|
+
* changed (in its order, pins, index, a slot, a filter, its condition); every view when a rule or the
|
|
73
|
+
* permissions changed, since rows carry what rules produce and are cut per audience. What the recipes
|
|
74
|
+
* restamped the commit marked itself. Marking every view of a million-record store for a version that
|
|
75
|
+
* moved nothing queued 2.4 million rows to rebuild (Media Encyclopedia's storefront install, 2026-10-22).
|
|
76
|
+
*/
|
|
77
|
+
function viewsChangedBy(previous, next, p) {
|
|
78
|
+
if (serialize((previous.permissions ?? {})) !== serialize((next.permissions ?? {})))
|
|
79
|
+
return "all";
|
|
80
|
+
const changed = classify(previous, next).filter((c) => c.kind !== "unchanged").map((c) => c.member);
|
|
81
|
+
if (!changed.length)
|
|
82
|
+
return [];
|
|
83
|
+
const of = (member) => new Set(changed.filter((m) => m.startsWith(`${member}:`)).map((m) => m.slice(member.length + 1)));
|
|
84
|
+
const facets = of("facet");
|
|
85
|
+
// A rule that changed names its facets in its words (`then: note shown to staff`, `when: qty is 0`): the
|
|
86
|
+
// views reading those facets rebuild; a rule naming no facet of the dictionary marks nothing more.
|
|
87
|
+
const members = new Map();
|
|
88
|
+
for (const b of [previous, next])
|
|
89
|
+
for (const r of b.rules ?? [])
|
|
90
|
+
if (r && typeof r.rule === "string")
|
|
91
|
+
members.set(`rule:${r.rule}`, r);
|
|
92
|
+
const keys = new Set([...p.dict.facets.keys()]);
|
|
93
|
+
for (const name of of("rule")) {
|
|
94
|
+
const r = members.get(`rule:${name}`);
|
|
95
|
+
const words = JSON.stringify(r ?? {}).match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
|
|
96
|
+
for (const w of words)
|
|
97
|
+
if (keys.has(w))
|
|
98
|
+
facets.add(w);
|
|
99
|
+
}
|
|
100
|
+
const shapes = of("shape");
|
|
101
|
+
const filters = of("filter");
|
|
102
|
+
const views = of("view");
|
|
103
|
+
// The facet an address starts from: `audioTracks[*].language` reads audioTracks.
|
|
104
|
+
const keyOf = (address) => address.split(/[.[]/)[0] ?? address;
|
|
105
|
+
const touched = (v) => {
|
|
106
|
+
if (views.has(v.name) || v.shapes.some((n) => shapes.has(n)) || v.filters.some((n) => filters.has(n)))
|
|
107
|
+
return true;
|
|
108
|
+
if (!facets.size)
|
|
109
|
+
return false;
|
|
110
|
+
const reads = new Set([...v.order.map((o) => keyOf(o.key)), ...v.pin.map(keyOf), ...v.hide.map(keyOf), ...v.index.map(keyOf)]);
|
|
111
|
+
if (v.list)
|
|
112
|
+
reads.add(keyOf(v.list));
|
|
113
|
+
for (const n of v.shapes)
|
|
114
|
+
for (const slot of p.views.shapes.get(n)?.slots ?? [])
|
|
115
|
+
reads.add(keyOf(slot.from));
|
|
116
|
+
for (const n of v.filters) {
|
|
117
|
+
const f = p.views.filters.get(n);
|
|
118
|
+
if (!f)
|
|
119
|
+
continue;
|
|
120
|
+
reads.add(f.facet);
|
|
121
|
+
for (const x of [...f.sums, ...f.dependent])
|
|
122
|
+
reads.add(keyOf(x));
|
|
123
|
+
}
|
|
124
|
+
for (const k of reads)
|
|
125
|
+
if (facets.has(k))
|
|
126
|
+
return true;
|
|
127
|
+
return !!v.when && [...facets].some((k) => new RegExp(`(^|[^A-Za-z0-9_])${k}([^A-Za-z0-9_]|$)`).test(v.when));
|
|
128
|
+
};
|
|
129
|
+
return [...p.views.views.values()].filter(touched);
|
|
130
|
+
}
|
|
131
|
+
/** The recipes of a package that lie between two versions, oldest first (10.1): `from` at or after the installed version, `to` at or before the new one. */
|
|
132
|
+
function recipesBetween(recipes, pkg, installed, target) {
|
|
133
|
+
const version = (s) => s.slice(s.lastIndexOf("/") + 1);
|
|
134
|
+
return recipes
|
|
135
|
+
.filter((r) => r.from.startsWith(`${pkg} /`) && compareVersions(version(r.from), installed) >= 0 && compareVersions(version(r.to), target) <= 0)
|
|
136
|
+
.sort((a, b) => compareVersions(version(a.from), version(b.from)));
|
|
137
|
+
}
|
|
138
|
+
/** The records an entry's writes name (revision 50), each once. */
|
|
139
|
+
function touchedBy(entry) {
|
|
140
|
+
const out = new Set();
|
|
141
|
+
for (const w of Array.isArray(entry.writes) ? entry.writes : [])
|
|
142
|
+
if (w && typeof w === "object" && !Array.isArray(w) && typeof w.record === "string")
|
|
143
|
+
out.add(w.record);
|
|
144
|
+
return [...out];
|
|
145
|
+
}
|
|
146
|
+
export class PgStore {
|
|
147
|
+
pool;
|
|
148
|
+
owner;
|
|
149
|
+
chain;
|
|
150
|
+
options;
|
|
151
|
+
constructor(pool, owner, options = {}) {
|
|
152
|
+
this.pool = pool;
|
|
153
|
+
this.owner = owner;
|
|
154
|
+
this.options = typeof options === "string" ? { chain: options } : options;
|
|
155
|
+
this.chain = this.options.chain ?? "main";
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Publish the views whose rows a write made stale (12.6): every view, or the named one, for its own
|
|
159
|
+
* audience or the one given. Runs outside any write transaction. Returns the stream entries published.
|
|
160
|
+
*/
|
|
161
|
+
async project(view, audience, only) {
|
|
162
|
+
const p = await this.projecting();
|
|
163
|
+
if (!p)
|
|
164
|
+
throw new Error("the store has no views to project");
|
|
165
|
+
const names = view ? [view] : [...p.views.views.values()].filter((v) => !only || only(v)).map((v) => v.name);
|
|
166
|
+
const out = [];
|
|
167
|
+
// Appended one by one: a first publish of a large view is hundreds of thousands of entries, more than a spread takes.
|
|
168
|
+
for (const name of names)
|
|
169
|
+
for (const e of await transaction(this.pool, (client) => publish(client, this.owner, p, name, audience)))
|
|
170
|
+
out.push(e);
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Publish every view whole next time, with a reset on each stream (12.6.2): an index that lost rows, or
|
|
175
|
+
* kept rows nothing removed, is brought back to what the store holds. The named view alone when given.
|
|
176
|
+
*/
|
|
177
|
+
async republish(view) {
|
|
178
|
+
const p = await this.projecting();
|
|
179
|
+
if (!p)
|
|
180
|
+
return;
|
|
181
|
+
for (const v of p.views.views.values()) {
|
|
182
|
+
if (view && v.name !== view)
|
|
183
|
+
continue;
|
|
184
|
+
await this.pool.query("insert into published (owner, view, audience, version) values ($1, $2, $3, '*') on conflict (owner, view, audience) do update set version = '*'", [this.owner, v.name, v.show]);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** The head of a view's stream for an audience (12.6.2): the last sequence number published, 0 when none. */
|
|
188
|
+
async streamHead(view, audience) {
|
|
189
|
+
const p = await this.projecting();
|
|
190
|
+
const v = p?.views.views.get(view);
|
|
191
|
+
if (!v)
|
|
192
|
+
throw new Error(`no view ${view}`);
|
|
193
|
+
const { rows } = await this.pool.query("select coalesce(max(seq), 0) as seq from projection_stream where owner = $1 and view = $2 and audience = $3 and version = $4", [this.owner, view, audience ?? v.show, v.version ?? ""]);
|
|
194
|
+
return Number(rows[0].seq);
|
|
195
|
+
}
|
|
196
|
+
/** The entries of a view's stream after `seq` (12.6.2). */
|
|
197
|
+
async entriesSince(view, seq, audience, limit) {
|
|
198
|
+
const p = await this.projecting();
|
|
199
|
+
if (!p)
|
|
200
|
+
throw new Error("the store has no views");
|
|
201
|
+
const client = await this.pool.connect();
|
|
202
|
+
try {
|
|
203
|
+
return await entriesSince(client, this.owner, p, view, seq, audience, limit);
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
client.release();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** After a persist: mark what the entry made stale, inside the same transaction. */
|
|
210
|
+
async afterPersist(client, before, after, seq, parsed) {
|
|
211
|
+
const p = this.options.projecting ?? (parsed ? projectingOf(parsed) : await this.projectingFrom(client));
|
|
212
|
+
if (p?.views.views.size && !this.skipStale)
|
|
213
|
+
await markStale(client, this.owner, p, before, after, seq);
|
|
214
|
+
}
|
|
215
|
+
async freshen() {
|
|
216
|
+
if (this.quiet)
|
|
217
|
+
return;
|
|
218
|
+
// Views with `fresh: write` publish now (12.6); a view with a delay waits for the loop.
|
|
219
|
+
if (this.options.fresh === "write" && (await this.projecting())?.views.views.size)
|
|
220
|
+
await this.project(undefined, undefined, (v) => v.fresh === "write");
|
|
221
|
+
}
|
|
222
|
+
/** Set while a bulk load runs: the per-commit publish waits for the one publish at the end. */
|
|
223
|
+
quiet = false;
|
|
224
|
+
/** A bulk load that republishes at the end marks nothing stale per batch (load, `stale: false`). */
|
|
225
|
+
skipStale = false;
|
|
226
|
+
/**
|
|
227
|
+
* Load many records as the owner's own, in batches: one entry per batch, each record set whole with its
|
|
228
|
+
* `sources` (or the `origin` given), the checks, rules and stale marks of a commit applying to every one;
|
|
229
|
+
* the views publish once at the end. For a conversion or a migration (brief 18 step 1): a million rows
|
|
230
|
+
* in an afternoon, not a day per hundred thousand through arrivals.
|
|
231
|
+
*/
|
|
232
|
+
async load(records, by, opts = {}) {
|
|
233
|
+
const size = Math.max(1, Math.floor(opts.batch ?? 500));
|
|
234
|
+
const entries = [];
|
|
235
|
+
this.quiet = true;
|
|
236
|
+
// `stale: false` marks nothing stale per batch: a conversion republishes every view at the end (12.6), and
|
|
237
|
+
// marking a million rows one write at a time is the slowest thing a bulk load would do.
|
|
238
|
+
this.skipStale = opts.stale === false;
|
|
239
|
+
try {
|
|
240
|
+
for (let i = 0; i < records.length; i += size) {
|
|
241
|
+
const slice = records.slice(i, i + size);
|
|
242
|
+
// Each record's values cite the entry that lands them (8.5), unless the record brings its own sources.
|
|
243
|
+
const { rows } = await this.pool.query("select head_seq from chains where owner = $1 and chain = $2", [this.owner, this.chain]);
|
|
244
|
+
const via = `L-${(rows.length ? Number(rows[0].head_seq) : 0) + 1}`;
|
|
245
|
+
const e = await this.commit(by, (d) => {
|
|
246
|
+
for (const r of slice) {
|
|
247
|
+
const sources = r.sources ?? { "*": { origin: opts.origin ?? "reported", via } };
|
|
248
|
+
d.records.set(r.id, { ...r, owner: r.owner ?? this.owner, sources });
|
|
249
|
+
}
|
|
250
|
+
}, opts.at);
|
|
251
|
+
if (e)
|
|
252
|
+
entries.push(String(e.log));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
this.quiet = false;
|
|
257
|
+
this.skipStale = false;
|
|
258
|
+
}
|
|
259
|
+
const published = opts.publish === false ? 0 : (await this.project()).length;
|
|
260
|
+
return { entries, records: records.length, published };
|
|
261
|
+
}
|
|
262
|
+
// ─── Definitions from the store (docs/design/publishing.md) ────────────────
|
|
263
|
+
defsCache;
|
|
264
|
+
/** The definitions in force: installed bundles in order, then the owner's define writes. Cached per chain head. */
|
|
265
|
+
async definitions(fresh = false) {
|
|
266
|
+
const client = await this.pool.connect();
|
|
267
|
+
try {
|
|
268
|
+
return await this.definitionsFrom(client, fresh);
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
client.release();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** `fresh` builds the caller's own copy to try a change on (a trial reads onto it and must not touch the shared cache). */
|
|
275
|
+
async definitionsFrom(client, fresh = false) {
|
|
276
|
+
if (fresh)
|
|
277
|
+
return definitionsOf(client, this.owner, [], true);
|
|
278
|
+
const { rows } = await client.query("select head_seq from chains where owner = $1 and chain = $2", [this.owner, this.chain]);
|
|
279
|
+
const seq = rows.length ? Number(rows[0].head_seq) : 0;
|
|
280
|
+
if (this.defsCache && this.defsCache.seq === seq)
|
|
281
|
+
return this.defsCache.parsed;
|
|
282
|
+
const parsed = await definitionsOf(client, this.owner);
|
|
283
|
+
this.defsCache = { seq, parsed };
|
|
284
|
+
return parsed;
|
|
285
|
+
}
|
|
286
|
+
/** What the store projects with: handed in, else built from its definitions. */
|
|
287
|
+
async projecting() {
|
|
288
|
+
if (this.options.projecting)
|
|
289
|
+
return this.options.projecting;
|
|
290
|
+
const client = await this.pool.connect();
|
|
291
|
+
try {
|
|
292
|
+
return await this.projectingFrom(client);
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
client.release();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async projectingFrom(client) {
|
|
299
|
+
if (this.options.projecting)
|
|
300
|
+
return this.options.projecting;
|
|
301
|
+
return projectingOf(await this.definitionsFrom(client));
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Install a published version (docs/design/publishing.md): verify the hash and signature, require the
|
|
305
|
+
* language version at or below ours and every extended package installed at its pinned version, write
|
|
306
|
+
* the install entry and keep the bundle, restamp through the recipes when an earlier version was
|
|
307
|
+
* installed, and check the definitions that result. Refused whole on any failure.
|
|
308
|
+
*/
|
|
309
|
+
async install(bundle, keys, at, opts = {}) {
|
|
310
|
+
if (!bundle.sig && !this.options.allowUnsigned)
|
|
311
|
+
throw new Error(`${bundle.id}: unsigned bundles are refused; a store may allow them for development`);
|
|
312
|
+
const v = verifyBundle(bundle, bundle.sig ? keys : undefined);
|
|
313
|
+
if (!v.valid)
|
|
314
|
+
throw new Error(`${bundle.id}: the bundle doesn't verify (${v.reason})`);
|
|
315
|
+
if (Number(bundle.crubal ?? 2) > 2)
|
|
316
|
+
throw new Error(`${bundle.id} is written in CRUBAL ${bundle.crubal}, above this store's`);
|
|
317
|
+
const installed = await this.installed();
|
|
318
|
+
const have = (pkg) => installed.filter((i) => i.package === pkg).map((i) => String(i.version));
|
|
319
|
+
for (const e of bundle.extends ?? []) {
|
|
320
|
+
// Named by short name within the bundle's own publisher, or by id across publishers.
|
|
321
|
+
const dep = String(e.package).includes("/") ? String(e.package) : `${bundle.owner}/${e.package}`;
|
|
322
|
+
// A pin names the least version (11.4): a later one held satisfies it, since a revision only adds.
|
|
323
|
+
if (!have(dep).some((v) => compareVersions(v, String(e.version)) >= 0))
|
|
324
|
+
throw new Error(`${bundle.id} extends ${e.package} /${e.version}, which isn't installed`);
|
|
325
|
+
}
|
|
326
|
+
const previous = have(String(bundle.id)).at(-1);
|
|
327
|
+
if (previous === bundle.version)
|
|
328
|
+
throw new Error(`${bundle.id} /${bundle.version} is already installed`);
|
|
329
|
+
const prevBundle = previous ? (await this.pool.query("select json from bundles where owner = $1 and package = $2 and version = $3", [this.owner, bundle.id, previous])).rows[0]?.json : undefined;
|
|
330
|
+
// The definitions that would result must pass every publish check before anything is written.
|
|
331
|
+
const current = await this.definitions(true);
|
|
332
|
+
const next = readBundleOnto(bundle, current);
|
|
333
|
+
checkAll(next);
|
|
334
|
+
// One dictionary (11.4): a facet another installed package defines with a different type is a collision,
|
|
335
|
+
// refused here rather than letting the later definition silently win.
|
|
336
|
+
const own = readBundle(bundle);
|
|
337
|
+
{
|
|
338
|
+
// Against each other package's version in force; a key this package's installed version already
|
|
339
|
+
// defined the same way is no new collision (so two packages can unwind one, each in its turn).
|
|
340
|
+
const { rows: others } = await this.pool.query("select distinct on (package) package, json from bundles where owner = $1 and package <> $2 order by package, version desc", [this.owner, bundle.id]);
|
|
341
|
+
const before = prevBundle ? readBundle(prevBundle).dict.facets : new Map();
|
|
342
|
+
for (const o of others) {
|
|
343
|
+
const theirs = readBundle(o.json).dict.facets;
|
|
344
|
+
for (const [key, f] of own.dict.facets) {
|
|
345
|
+
const t = theirs.get(key);
|
|
346
|
+
if (!t)
|
|
347
|
+
continue;
|
|
348
|
+
const mine = facetShape(f);
|
|
349
|
+
if (mine !== facetShape(t) && (!before.get(key) || facetShape(before.get(key)) !== mine))
|
|
350
|
+
throw new Error(`${bundle.id} /${bundle.version} defines ${key} as ${mine}, but ${o.package} defines it as ${facetShape(t)}; one dictionary, one key`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// A version may not take away a preset or item that live edges still grant (14.12): lapse or regrant first.
|
|
355
|
+
if (previous) {
|
|
356
|
+
const was = prevBundle ? readBundle(prevBundle).perms : current.perms;
|
|
357
|
+
const own = readBundle(bundle).perms;
|
|
358
|
+
const gone = new Set([...was.presets.keys(), ...was.menu.keys()].filter((n) => !own.presets.has(n) && !own.menu.has(n)));
|
|
359
|
+
if (gone.size) {
|
|
360
|
+
const now = at ?? new Date().toISOString();
|
|
361
|
+
const holding = [...installed.length ? (await this.edges()) : []].filter((e) => (!e.until || String(e.until) > now) && e.grants?.some((g) => gone.has(g)));
|
|
362
|
+
if (holding.length)
|
|
363
|
+
throw new Error(`${bundle.id} /${bundle.version} drops ${[...gone].join(", ")}, which ${holding.map((e) => String(e.edge)).join(", ")} still grant; lapse or regrant them first`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
// A restamp over more records than one batch holds (a package whose kinds are the catalog) does not run
|
|
367
|
+
// inside the install's entry: the pin moves in that entry, and the records are restamped afterwards in
|
|
368
|
+
// batches, each its own entry, resumable after any interruption (`continueRestamp`), so no function ever
|
|
369
|
+
// holds the catalog, and a budget can stop between batches and the next pass carry on.
|
|
370
|
+
const batchSize = Math.max(1, this.options.restampBatch ?? 5000);
|
|
371
|
+
const steppedRecipes = previous ? recipesBetween(next.recipes, String(bundle.package), previous, String(bundle.version)).filter((r) => r.steps.length) : [];
|
|
372
|
+
const deferred = steppedRecipes.length > 0 && (await this.countOwnRecords(own, batchSize + 1)) > batchSize;
|
|
373
|
+
// The bundle goes in first: the entry's own transaction rebuilds definitions from it. A refused install takes it out again.
|
|
374
|
+
await this.pool.query("insert into bundles (owner, package, version, hash, json) values ($1, $2, $3, $4, $5) on conflict (owner, package, version) do update set hash = excluded.hash, json = excluded.json", [this.owner, bundle.id, bundle.version, bundle.hash, bundle]);
|
|
375
|
+
let result;
|
|
376
|
+
this.walking = true;
|
|
377
|
+
try {
|
|
378
|
+
result = await this.commitFrom((draft) => {
|
|
379
|
+
const extra = [{ install: { package: String(bundle.id), version: String(bundle.version), hash: String(bundle.hash) } }];
|
|
380
|
+
// A pin move restamps through every recipe between the installed version and this one (10.1, 10.4),
|
|
381
|
+
// in order: a store two versions behind takes both steps, never only the first.
|
|
382
|
+
if (previous && !deferred) {
|
|
383
|
+
const parsedRecipes = recipesBetween(next.recipes, String(bundle.package), previous, String(bundle.version));
|
|
384
|
+
for (const recipe of parsedRecipes) {
|
|
385
|
+
// A recipe with no steps (a pin move, 10.1) restamps nothing and reads nothing: a package whose kinds
|
|
386
|
+
// are the catalog (994,000 items and works at one owner, 2026-10-23) must not be loaded to move a pin.
|
|
387
|
+
if (!recipe.steps.length)
|
|
388
|
+
continue;
|
|
389
|
+
// A recipe restamps what the store holds for the package (10.4): records of its kinds and records wearing its classes.
|
|
390
|
+
const records = ownRecordsOf(draft.records, own);
|
|
391
|
+
const { records: after, review } = restamp(records, recipe, next.dict);
|
|
392
|
+
for (const r of after)
|
|
393
|
+
draft.records.set(r.id, r);
|
|
394
|
+
for (const item of review)
|
|
395
|
+
draft.review.push({ ...item, step: item.step, migration: `${recipe.from} -> ${recipe.to}` });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// The version's instruction blocks (10.7) are issued here; drain applies them record by record.
|
|
399
|
+
for (const block of bundle.instructions ?? []) {
|
|
400
|
+
const issuer = String(block.issuer);
|
|
401
|
+
const list = block.instructions ?? [];
|
|
402
|
+
if (list.length)
|
|
403
|
+
draft.instructions.set(issuer, [...(draft.instructions.get(issuer) ?? []), ...list.map((i) => ({ ...i, issuer }))]);
|
|
404
|
+
}
|
|
405
|
+
const by = previous ? { migration: `${bundle.package} /${previous} -> ${bundle.package} /${bundle.version}` } : { person: "owner" };
|
|
406
|
+
return { by, extra, out: null };
|
|
407
|
+
}, at);
|
|
408
|
+
}
|
|
409
|
+
catch (e) {
|
|
410
|
+
// The bundle goes only when the entry did not: an install whose projection failed after its entry
|
|
411
|
+
// committed kept the entry and lost the bundle, and the store then read "installed but its bundle is
|
|
412
|
+
// missing" on every definitions read (the brief 37 rehearsal, 2026-10-27).
|
|
413
|
+
const stands = (await this.installed().catch(() => [])).some((i) => i.package === bundle.id && String(i.version) === String(bundle.version));
|
|
414
|
+
if (!stands)
|
|
415
|
+
await this.pool.query("delete from bundles where owner = $1 and package = $2 and version = $3", [this.owner, bundle.id, bundle.version]);
|
|
416
|
+
throw e;
|
|
417
|
+
}
|
|
418
|
+
finally {
|
|
419
|
+
this.walking = false;
|
|
420
|
+
}
|
|
421
|
+
if (!result.entry)
|
|
422
|
+
throw new Error("the install wrote nothing");
|
|
423
|
+
this.defsCache = undefined;
|
|
424
|
+
if (previous) {
|
|
425
|
+
const p = await this.projecting();
|
|
426
|
+
const which = prevBundle && p ? viewsChangedBy(prevBundle, bundle, p) : "all";
|
|
427
|
+
if (which === "all" || which.length)
|
|
428
|
+
await this.staleAll((sql, params) => this.pool.query(sql, params), p, which === "all" ? undefined : which);
|
|
429
|
+
}
|
|
430
|
+
if (deferred && previous) {
|
|
431
|
+
await this.restampsReady();
|
|
432
|
+
await this.pool.query("insert into restamps (owner, package, version, from_version, after_ord, restamped, review, done, started) values ($1, $2, $3, $4, -1, 0, 0, false, $5) on conflict (owner, package, version) do update set from_version = excluded.from_version, after_ord = -1, restamped = 0, review = 0, done = false, started = excluded.started, finished = null", [this.owner, bundle.id, bundle.version, previous, at ?? new Date().toISOString()]);
|
|
433
|
+
await this.continueRestamp(String(bundle.id), String(bundle.version), { ...(opts.budgetMs !== undefined ? { budgetMs: opts.budgetMs } : {}), ...(at ? { at } : {}) });
|
|
434
|
+
}
|
|
435
|
+
return result.entry;
|
|
436
|
+
}
|
|
437
|
+
/** How many records the package's recipes would restamp, up to a limit: enough to know whether one batch holds them. */
|
|
438
|
+
async countOwnRecords(own, limit) {
|
|
439
|
+
const kinds = [...own.dict.kinds.keys()];
|
|
440
|
+
const classes = [...own.dict.classes.keys()];
|
|
441
|
+
if (!kinds.length && !classes.length)
|
|
442
|
+
return 0;
|
|
443
|
+
const { rows } = await this.pool.query("select count(*)::int as n from (select 1 from records where owner = $1 and (kind = any($2::text[]) or wears && $3::text[]) limit $4) t", [this.owner, kinds, classes, limit]);
|
|
444
|
+
return Number(rows[0].n);
|
|
445
|
+
}
|
|
446
|
+
/** The table of restamps in progress, made once per process for a store migrated before it existed. */
|
|
447
|
+
restampsTable;
|
|
448
|
+
restampsReady() {
|
|
449
|
+
this.restampsTable ??= this.pool
|
|
450
|
+
.query("create table if not exists restamps (owner text not null, package text not null, version text not null, from_version text not null, after_ord bigint not null default -1, restamped integer not null default 0, review integer not null default 0, done boolean not null default false, started text, finished text, primary key (owner, package, version))")
|
|
451
|
+
.then(() => undefined);
|
|
452
|
+
return this.restampsTable;
|
|
453
|
+
}
|
|
454
|
+
/** The restamps this owner has not finished: an install whose records are still being walked. */
|
|
455
|
+
async pendingRestamps() {
|
|
456
|
+
await this.restampsReady();
|
|
457
|
+
const { rows } = await this.pool.query("select package, version, from_version, after_ord, restamped, review, started from restamps where owner = $1 and not done order by started", [this.owner]);
|
|
458
|
+
return rows.map((r) => ({ package: r.package, version: r.version, from: r.from_version, afterOrd: Number(r.after_ord), restamped: Number(r.restamped), review: Number(r.review), ...(r.started ? { started: r.started } : {}) }));
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Carry a deferred restamp on (10.4): the package's own records after the last one done, in batches by ord,
|
|
462
|
+
* each batch through every stepped recipe between the versions and committed as one entry (the records
|
|
463
|
+
* that changed and the items for review), the progress written after each; it stops when the budget is
|
|
464
|
+
* spent and picks up where it left off next time. Done when a batch comes up short.
|
|
465
|
+
*/
|
|
466
|
+
async continueRestamp(pkg, version, opts = {}) {
|
|
467
|
+
await this.restampsReady();
|
|
468
|
+
const { rows: progress } = await this.pool.query("select from_version, after_ord, restamped, review, done from restamps where owner = $1 and package = $2 and version = $3", [this.owner, pkg, version]);
|
|
469
|
+
const row = progress[0];
|
|
470
|
+
if (!row)
|
|
471
|
+
throw new Error(`${pkg} /${version}: no restamp is pending for ${this.owner}`);
|
|
472
|
+
let restamped = Number(row.restamped);
|
|
473
|
+
let review = Number(row.review);
|
|
474
|
+
if (row.done)
|
|
475
|
+
return { done: true, restamped, review, batches: 0 };
|
|
476
|
+
const { rows: bundles } = await this.pool.query("select json from bundles where owner = $1 and package = $2 and version = $3", [this.owner, pkg, version]);
|
|
477
|
+
const bundle = bundles[0]?.json;
|
|
478
|
+
if (!bundle)
|
|
479
|
+
throw new Error(`${pkg} /${version} is not installed for ${this.owner}`);
|
|
480
|
+
const p = await this.definitions(true);
|
|
481
|
+
const own = readBundle(bundle);
|
|
482
|
+
const recipes = recipesBetween(p.recipes, String(bundle.package), row.from_version, version).filter((r) => r.steps.length);
|
|
483
|
+
const kinds = [...own.dict.kinds.keys()];
|
|
484
|
+
const classes = [...own.dict.classes.keys()];
|
|
485
|
+
const size = Math.max(1, this.options.restampBatch ?? 5000);
|
|
486
|
+
const migration = `${bundle.package} /${row.from_version} -> ${bundle.package} /${version}`;
|
|
487
|
+
const started = Date.now();
|
|
488
|
+
let after = Number(row.after_ord);
|
|
489
|
+
let batches = 0;
|
|
490
|
+
const finish = async (done) => {
|
|
491
|
+
await this.pool.query("update restamps set after_ord = $4, restamped = $5, review = $6, done = $7, finished = case when $7 then $8 else null end where owner = $1 and package = $2 and version = $3", [this.owner, pkg, version, after, restamped, review, done, opts.at ?? new Date().toISOString()]);
|
|
492
|
+
return { done, restamped, review, batches };
|
|
493
|
+
};
|
|
494
|
+
this.walking = true;
|
|
495
|
+
try {
|
|
496
|
+
for (;;) {
|
|
497
|
+
if (opts.budgetMs !== undefined && batches > 0 && Date.now() - started >= opts.budgetMs)
|
|
498
|
+
return await finish(false);
|
|
499
|
+
const { rows } = await this.pool.query("select * from records where owner = $1 and (kind = any($2::text[]) or wears && $3::text[]) and ord > $4 order by ord limit $5", [this.owner, kinds, classes, after, size]);
|
|
500
|
+
if (!rows.length)
|
|
501
|
+
return await finish(true);
|
|
502
|
+
const list = rows;
|
|
503
|
+
const before = list.map((r) => recordOf(r));
|
|
504
|
+
// A record counts as changed by its values, its classes or its parts (a parts recipe adds rows, 2026-10-27).
|
|
505
|
+
const was = new Map(before.map((r) => [r.id, JSON.stringify([r.values, r.wears ?? [], r.parts ?? []])]));
|
|
506
|
+
let current = before;
|
|
507
|
+
const items = [];
|
|
508
|
+
for (const recipe of recipes) {
|
|
509
|
+
const r = restamp(current, recipe, p.dict);
|
|
510
|
+
current = r.records;
|
|
511
|
+
for (const item of r.review)
|
|
512
|
+
items.push({ ...item, step: item.step, migration });
|
|
513
|
+
}
|
|
514
|
+
const changed = current.filter((r) => was.get(r.id) !== JSON.stringify([r.values, r.wears ?? [], r.parts ?? []]));
|
|
515
|
+
if (changed.length || items.length)
|
|
516
|
+
await this.commit({ migration }, (d) => {
|
|
517
|
+
// The record is read into the working set before it is set, so the entry's writes are the change and not a creation.
|
|
518
|
+
// The restamped members land on the record as the commit finds it, not on the copy the batch read a
|
|
519
|
+
// moment ago: another hand (the drain stamping `applied`, a form) may have written it between the two,
|
|
520
|
+
// and a draft built on the stale copy failed the log's own check and stalled the walk (2026-10-27).
|
|
521
|
+
// So the recipes run again here, on the live record (restamp is pure and cheap per record); a record
|
|
522
|
+
// the working set has not loaded yet comes on the next pass of the settle.
|
|
523
|
+
const seen = [];
|
|
524
|
+
for (const r of changed) {
|
|
525
|
+
const live = d.records.get(r.id);
|
|
526
|
+
if (!live)
|
|
527
|
+
continue;
|
|
528
|
+
let cur = [live];
|
|
529
|
+
for (const recipe of recipes) {
|
|
530
|
+
const out = restamp(cur, recipe, p.dict);
|
|
531
|
+
cur = out.records;
|
|
532
|
+
for (const item of out.review)
|
|
533
|
+
seen.push({ ...item, step: item.step, migration });
|
|
534
|
+
}
|
|
535
|
+
d.records.set(r.id, cur[0]);
|
|
536
|
+
}
|
|
537
|
+
for (const item of seen)
|
|
538
|
+
d.review.push(item);
|
|
539
|
+
}, opts.at);
|
|
540
|
+
restamped += changed.length;
|
|
541
|
+
review += items.length;
|
|
542
|
+
batches += 1;
|
|
543
|
+
after = Number(list[list.length - 1]?.ord);
|
|
544
|
+
if (rows.length < size)
|
|
545
|
+
return await finish(true);
|
|
546
|
+
await finish(false);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
finally {
|
|
550
|
+
this.walking = false;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Mark every row of every view stale: after a reinstall or a rebuild the next publish rebuilds and
|
|
555
|
+
* compares every row and announces what left, and the stream keeps its numbering. (Wiping the stored
|
|
556
|
+
* rows instead, as before 0.1.16, made the next publish a first one, which announces no removals, so an
|
|
557
|
+
* index kept rows nothing ever removed: ME's index held three versions of its shop.)
|
|
558
|
+
*/
|
|
559
|
+
async staleAll(run, p, only) {
|
|
560
|
+
if (!p)
|
|
561
|
+
return;
|
|
562
|
+
for (const v of only ?? p.views.views.values()) {
|
|
563
|
+
await run(`insert into stale (owner, view, record, since) select $1, $2, id, 0 from records where owner = $1${v.level ? " and level = $3" : ""} on conflict do nothing`, v.level ? [this.owner, v.name, v.level] : [this.owner, v.name]);
|
|
564
|
+
await run("insert into stale (owner, view, record, since) select owner, view, record, 0 from projections where owner = $1 and view = $2 on conflict do nothing", [this.owner, v.name]);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
/** Well-formed access (14.12) on what an entry changed: ownership, wearing, within, and every edge written. */
|
|
568
|
+
/**
|
|
569
|
+
* What the rules produce for the records an operation changed, and for their ancestors (6.4): a plain
|
|
570
|
+
* write runs the productions as a border run does, so a rollup over units follows a unit written by the
|
|
571
|
+
* owner's own commit. Derived values land in the draft with their rule as source, so the entry's writes
|
|
572
|
+
* carry them like any other value; a person's value is never overwritten.
|
|
573
|
+
*/
|
|
574
|
+
/** Records a `rederive` asks for, derived whether or not the operation changed them. */
|
|
575
|
+
alsoDerive;
|
|
576
|
+
/**
|
|
577
|
+
* Run the productions over records as they stand (6.4), for records written before a rule existed: one
|
|
578
|
+
* entry per call, holding only the derived values that changed. The ids are loaded into the working set
|
|
579
|
+
* and derived with their ancestors; nothing else is written.
|
|
580
|
+
*/
|
|
581
|
+
async rederive(ids, by = { platform: "rederive" }, at) {
|
|
582
|
+
if (!ids.length)
|
|
583
|
+
return null;
|
|
584
|
+
this.alsoDerive = new Set(ids);
|
|
585
|
+
try {
|
|
586
|
+
return (await this.commitFrom((d) => { for (const id of ids)
|
|
587
|
+
d.records.get(id); return { by, extra: [], out: null }; }, at)).entry;
|
|
588
|
+
}
|
|
589
|
+
finally {
|
|
590
|
+
this.alsoDerive = undefined;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
derive(p, before, draft) {
|
|
594
|
+
if (!p.rules.some((r) => r.produces))
|
|
595
|
+
return;
|
|
596
|
+
const changed = [];
|
|
597
|
+
for (const [id, r] of draft.records) {
|
|
598
|
+
const was = before.records.get(id);
|
|
599
|
+
if (!was || serialize(was.values) !== serialize(r.values) || serialize(was.status ?? {}) !== serialize(r.status ?? {}))
|
|
600
|
+
changed.push(id);
|
|
601
|
+
}
|
|
602
|
+
for (const id of this.alsoDerive ?? [])
|
|
603
|
+
if (!changed.includes(id))
|
|
604
|
+
changed.push(id);
|
|
605
|
+
if (!changed.length)
|
|
606
|
+
return;
|
|
607
|
+
const engine = new Engine(p.dict, p.rules, () => draft.records);
|
|
608
|
+
for (const [, r] of draft.records)
|
|
609
|
+
engine.put(r);
|
|
610
|
+
const land = (id) => {
|
|
611
|
+
const rec = draft.records.get(id);
|
|
612
|
+
if (!rec || rec.status?.state === "archived")
|
|
613
|
+
return false;
|
|
614
|
+
// What the record reads from above (1.7) must be in the engine: the chain up along `of`, asked for by
|
|
615
|
+
// id so a working set loads just those, never the catalog.
|
|
616
|
+
const seen = new Set([id]);
|
|
617
|
+
for (let up = rec.of ? draft.records.get(rec.of) : undefined; up && !seen.has(up.id); up = up.of ? draft.records.get(up.of) : undefined) {
|
|
618
|
+
seen.add(up.id);
|
|
619
|
+
engine.put(up);
|
|
620
|
+
}
|
|
621
|
+
engine.put(rec);
|
|
622
|
+
const derived = engine.reproduce(id).filter((x) => (x.result === "derived" || x.result === "filled") && x.address && x.value !== undefined && x.rule);
|
|
623
|
+
let moved = false;
|
|
624
|
+
const values = { ...rec.values };
|
|
625
|
+
const sources = { ...(rec.sources ?? {}) };
|
|
626
|
+
for (const x of derived) {
|
|
627
|
+
const address = x.address;
|
|
628
|
+
if (serialize(values[address] ?? "∅") === serialize(x.value))
|
|
629
|
+
continue;
|
|
630
|
+
values[address] = x.value;
|
|
631
|
+
sources[address] = { origin: "derived", via: x.rule };
|
|
632
|
+
moved = true;
|
|
633
|
+
}
|
|
634
|
+
if (!moved)
|
|
635
|
+
return false;
|
|
636
|
+
const next = { ...rec, values, sources };
|
|
637
|
+
draft.records.set(id, next);
|
|
638
|
+
engine.put(next);
|
|
639
|
+
return true;
|
|
640
|
+
};
|
|
641
|
+
for (const id of changed) {
|
|
642
|
+
land(id);
|
|
643
|
+
if (engine.readsLowerLevels)
|
|
644
|
+
for (const up of engine.ancestorsOf(id))
|
|
645
|
+
land(up);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
checkWrites(p, entry, after) {
|
|
649
|
+
const writes = (Array.isArray(entry.writes) ? entry.writes : []);
|
|
650
|
+
const touched = new Set(writes.map((w) => (typeof w.record === "string" ? w.record : "")).filter(Boolean));
|
|
651
|
+
const edges = writes.filter((w) => isObj(w.edge)).map((w) => w.edge);
|
|
652
|
+
if (!touched.size && !edges.length)
|
|
653
|
+
return;
|
|
654
|
+
const access = new Access(p.dict, p.perms, after.records, [...after.edges.values()], this.owner);
|
|
655
|
+
for (const id of touched) {
|
|
656
|
+
const r = after.records.get(id);
|
|
657
|
+
if (!r)
|
|
658
|
+
continue;
|
|
659
|
+
access.checkOwnership(r);
|
|
660
|
+
access.checkWears(r);
|
|
661
|
+
// Within: the chain up from this record only, never a scan of the catalog.
|
|
662
|
+
const seen = new Set([id]);
|
|
663
|
+
let cur = r.within;
|
|
664
|
+
while (cur) {
|
|
665
|
+
if (seen.has(cur))
|
|
666
|
+
throw new CrubalError(`${id} is within itself through ${cur}`);
|
|
667
|
+
seen.add(cur);
|
|
668
|
+
const up = after.records.get(cur);
|
|
669
|
+
if (up && up.owner !== r.owner)
|
|
670
|
+
throw new CrubalError(`${id} is within ${cur}, which belongs to ${up.owner}: within never crosses owners`);
|
|
671
|
+
cur = up?.within;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
// An emergency edge is checked by the host against the platform's published terms (14.13), not here.
|
|
675
|
+
for (const e of edges)
|
|
676
|
+
if (e.relation !== "emergency")
|
|
677
|
+
access.checkEdge(e);
|
|
678
|
+
}
|
|
679
|
+
/** One record by id, from its row alone (no whole state): undefined when there is none. */
|
|
680
|
+
async get(id) {
|
|
681
|
+
const { rows } = await this.pool.query("select * from records where owner = $1 and id = $2", [this.owner, id]);
|
|
682
|
+
return rows[0] ? recordOf(rows[0]) : undefined;
|
|
683
|
+
}
|
|
684
|
+
/** Several records by id in one statement, in no particular order; ids with no record are left out. */
|
|
685
|
+
async getMany(ids) {
|
|
686
|
+
if (!ids.length)
|
|
687
|
+
return [];
|
|
688
|
+
const { rows } = await this.pool.query("select * from records where owner = $1 and id = any($2)", [this.owner, ids]);
|
|
689
|
+
return rows.map((r) => recordOf(r));
|
|
690
|
+
}
|
|
691
|
+
/** The review items still open (9.5). */
|
|
692
|
+
async review() {
|
|
693
|
+
const { rows } = await this.pool.query("select json from review where owner = $1 order by ord", [this.owner]);
|
|
694
|
+
return openItems(rows.map((r) => r.json));
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* A review decision (9.5, 11.9, 14.7, runs.md): one entry holding the review write and what it causes;
|
|
698
|
+
* then the intakes the decision affects are replayed (9.6), each its own entry.
|
|
699
|
+
*/
|
|
700
|
+
async decide(d, by = { person: "owner" }, at) {
|
|
701
|
+
const p = await this.definitions(true);
|
|
702
|
+
// The operation may run more than once while the working set loads (working.ts): each run changes a copy.
|
|
703
|
+
const fresh = () => ({ dict: { ...p.dict, facets: new Map(p.dict.facets) }, contracts: new Map(p.contracts.map((c) => [c.name, c])), units: [...(p.units ?? [])] });
|
|
704
|
+
const result = await this.commitFrom((draft) => {
|
|
705
|
+
const extra = decideReview(d, draft, fresh());
|
|
706
|
+
return { by, extra, out: null };
|
|
707
|
+
}, at);
|
|
708
|
+
this.defsCache = undefined;
|
|
709
|
+
const replayed = await this.replayFor(d, at);
|
|
710
|
+
return { entry: result.entry, replayed };
|
|
711
|
+
}
|
|
712
|
+
/** Replay the kept intakes a decision reaches: by facet, by contract field, or by unit spelling (9.6). */
|
|
713
|
+
async replayFor(d, at) {
|
|
714
|
+
const key = d.key;
|
|
715
|
+
const reaches = (o) => (key.startsWith("facet:") && o.to === key.slice(6) && o.outcome === "new") ||
|
|
716
|
+
(key.startsWith("contract:") && o.from === d.field && o.outcome === "unknown") ||
|
|
717
|
+
(key.startsWith("unit:") && isObj(o.cites) && o.cites.unit === key.slice(5));
|
|
718
|
+
if (!key.startsWith("facet:") && !key.startsWith("contract:") && !key.startsWith("unit:"))
|
|
719
|
+
return [];
|
|
720
|
+
if (d.decision === "reject" || d.decision === "ignore" || d.decision === "not a unit")
|
|
721
|
+
return [];
|
|
722
|
+
const p = await this.definitions(true);
|
|
723
|
+
const { rows } = await this.pool.query("select intake, contract, \"for\", raw, json from intake where owner = $1 order by received", [this.owner]);
|
|
724
|
+
const out = [];
|
|
725
|
+
for (const row of rows) {
|
|
726
|
+
const outcomes = row.json.outcomes ?? [];
|
|
727
|
+
if (!outcomes.some(reaches) || !row.for)
|
|
728
|
+
continue;
|
|
729
|
+
const c = p.contracts.find((x) => x.name === row.contract);
|
|
730
|
+
if (!c)
|
|
731
|
+
continue;
|
|
732
|
+
const body = Buffer.from(row.raw).toString("utf8");
|
|
733
|
+
const again = receive(c, body, row.for, p.dict, row.intake);
|
|
734
|
+
const recordId = row.for;
|
|
735
|
+
const earlier = `L-${row.intake.slice(2)}`;
|
|
736
|
+
const entry = await this.commitFrom((draft) => {
|
|
737
|
+
const r = draft.records.get(recordId);
|
|
738
|
+
if (!r)
|
|
739
|
+
return { by: { migration: "replay" }, out: null };
|
|
740
|
+
// What this intake landed before is replaced by its replay, never left to a tie with itself.
|
|
741
|
+
const values = { ...r.values };
|
|
742
|
+
const sources = { ...(r.sources ?? {}) };
|
|
743
|
+
for (const [k, s] of Object.entries(sources))
|
|
744
|
+
if (s.via === earlier || s.via === row.intake) {
|
|
745
|
+
delete values[k];
|
|
746
|
+
delete sources[k];
|
|
747
|
+
}
|
|
748
|
+
const cleared = { ...r, values, sources };
|
|
749
|
+
draft.records.set(recordId, land(cleared, { outcomes: again.outcomes, contract: c.name }, { origin: c.origin || "reported", via: row.intake }, p.dict.trust, p.dict.facetTrust, transitionsOf(p.dict)));
|
|
750
|
+
return { by: { migration: "replay" }, extra: [], out: null };
|
|
751
|
+
}, at);
|
|
752
|
+
await this.pool.query("update intake set json = $3 where owner = $1 and intake = $2", [this.owner, row.intake, { ...row.json, replays: [...(row.json.replays ?? []), { outcomes: again.outcomes, contract: c.name, ...(entry.entry ? { entry: String(entry.entry.log) } : {}) }] }]);
|
|
753
|
+
out.push(row.intake);
|
|
754
|
+
}
|
|
755
|
+
return out;
|
|
756
|
+
}
|
|
757
|
+
/** 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. */
|
|
758
|
+
compactTable;
|
|
759
|
+
compactReady() {
|
|
760
|
+
this.compactTable ??= (async () => {
|
|
761
|
+
await this.pool.query("create table if not exists compaction_cursors (owner text not null, view text not null, version text not null, audience text not null, seq bigint not null default 0, done boolean not null default false, head bigint not null default 0, primary key (owner, view, version, audience))");
|
|
762
|
+
await this.pool.query("create table if not exists compaction_removed (owner text not null, view text not null, version text not null, audience text not null, record text not null, seq bigint not null, primary key (owner, view, version, audience, record))");
|
|
763
|
+
})();
|
|
764
|
+
return this.compactTable;
|
|
765
|
+
}
|
|
766
|
+
/** The drain's walk: its cursor per owner, and the record-order index it reads by; made once per process. */
|
|
767
|
+
drainTable;
|
|
768
|
+
drainReady() {
|
|
769
|
+
this.drainTable ??= (async () => {
|
|
770
|
+
await this.pool.query("create table if not exists drain_cursors (owner text primary key, ord bigint not null default 0)");
|
|
771
|
+
// Built concurrently when a store from before lacks it, never by the schema at connect: a plain create
|
|
772
|
+
// over a catalog of a million records would hold the table for the build (brief 40). On its own
|
|
773
|
+
// connection with no statement timeout, since a build over a million rows outlasts one; a build cut
|
|
774
|
+
// short leaves an invalid index behind, which is dropped and made again.
|
|
775
|
+
const { rows } = await this.pool.query("select x.indisvalid as valid from pg_index x join pg_class c on c.oid = x.indexrelid join pg_namespace n on n.oid = c.relnamespace where n.nspname = current_schema() and c.relname = 'records_ord'");
|
|
776
|
+
const state = rows[0]?.valid;
|
|
777
|
+
if (state === true)
|
|
778
|
+
return;
|
|
779
|
+
const client = await this.pool.connect();
|
|
780
|
+
try {
|
|
781
|
+
await client.query("set statement_timeout = 0");
|
|
782
|
+
if (state === false)
|
|
783
|
+
await client.query("drop index if exists records_ord");
|
|
784
|
+
await client.query("create index concurrently if not exists records_ord on records (owner, ord)");
|
|
785
|
+
}
|
|
786
|
+
catch {
|
|
787
|
+
// Left for the next process to try again.
|
|
788
|
+
}
|
|
789
|
+
finally {
|
|
790
|
+
await client.query("reset statement_timeout").catch(() => undefined);
|
|
791
|
+
client.release();
|
|
792
|
+
}
|
|
793
|
+
})();
|
|
794
|
+
return this.drainTable;
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Drain (docs/design/store.md, completion.md P): apply pending instructions to the records that have
|
|
798
|
+
* them, at most `rate` records per call, fifty to an entry `by: migration: drain`; the ids done and
|
|
799
|
+
* whether any still wait (brief 40: a walk by cursor in record order, never a count of what remains).
|
|
800
|
+
*/
|
|
801
|
+
async drain(rate = 100, at, budgetMs) {
|
|
802
|
+
const started = Date.now();
|
|
803
|
+
// Nothing pending at all: no walk. The planner cannot tell that an empty issuer list makes the exists
|
|
804
|
+
// below false for every row, so it read ME's 994,000 records for 27 s a tick for nothing (2026-10-26).
|
|
805
|
+
if (!(await this.pool.query("select 1 from instructions where owner = $1 limit 1", [this.owner])).rows.length)
|
|
806
|
+
return { applied: [], remaining: 0 };
|
|
807
|
+
await this.drainReady();
|
|
808
|
+
const dict = (await this.definitions()).dict;
|
|
809
|
+
const from0 = Number((await this.pool.query("select ord from drain_cursors where owner = $1", [this.owner])).rows[0]?.ord ?? 0);
|
|
810
|
+
// The records with an instruction still to apply, found by the tables (lifecycle.ts issuersFor: the
|
|
811
|
+
// parent's instructions, a kind's, a class's worn by the record or its parent), in record order after the
|
|
812
|
+
// cursor; a page at a time, so a tick reads `rate` matching records and what it skips, never the catalog
|
|
813
|
+
// (brief 18, the scale rule). Counting what remained read every record twice a tick (2026-10-26).
|
|
814
|
+
// The walk by issuer (0.3.30): one indexable branch per issuer, each carrying its own "still to apply"
|
|
815
|
+
// test inline, in a union ordered by ord; no correlated test per candidate row (the exists over every
|
|
816
|
+
// candidate with a lookup of the parent's classes ran 33 s a tick at Media Encyclopedia, 2026-10-28). A
|
|
817
|
+
// class issuer reaches its wearers and the records of its wearers (lifecycle.ts issuersFor); a kind
|
|
818
|
+
// issuer its kind's records; a record issuer the records of it.
|
|
819
|
+
const issuers = (await this.pool.query("select issuer, count(*)::int as n from instructions where owner = $1 group by issuer", [this.owner])).rows;
|
|
820
|
+
// Each branch carries its own parameters: Postgres refuses a bind that supplies more than the statement
|
|
821
|
+
// names (0.3.31 handed every branch the whole list and the drain applied nothing, 2026-10-28).
|
|
822
|
+
const branches = [];
|
|
823
|
+
const base = `r.owner = $1 and r.ord > $3 and coalesce(r.status ->> 'state', '') <> 'archived'`;
|
|
824
|
+
const branch = (where, issuer, n) => {
|
|
825
|
+
const ps = [this.owner, rate, from0];
|
|
826
|
+
const w = where(ps);
|
|
827
|
+
ps.push(issuer, n);
|
|
828
|
+
branches.push({ sql: `select r.id, r.ord from records r where ${base} and ${w} and coalesce((r.applied ->> $${ps.length - 1})::int, 0) < $${ps.length} order by r.ord limit $2`, ps });
|
|
829
|
+
};
|
|
830
|
+
for (const { issuer, n } of issuers) {
|
|
831
|
+
if (issuer.startsWith("class:")) {
|
|
832
|
+
const name = issuer.slice(6).split("/")[0];
|
|
833
|
+
branch((ps) => { ps.push([name]); return `r.wears && $${ps.length}::text[]`; }, issuer, n);
|
|
834
|
+
branch((ps) => { ps.push([name]); return `r."of" in (select p.id from records p where p.owner = $1 and p.wears && $${ps.length}::text[])`; }, issuer, n);
|
|
835
|
+
}
|
|
836
|
+
else if (issuer.startsWith("kind:")) {
|
|
837
|
+
branch((ps) => { ps.push(issuer.slice(5).split("/")[0]); return `r.kind = $${ps.length}`; }, issuer, n);
|
|
838
|
+
}
|
|
839
|
+
else {
|
|
840
|
+
branch((ps) => { ps.push(issuer); return `r."of" = $${ps.length}`; }, issuer, n);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
// One branch at a time, each walked by the record-order index with the page's limit, the first that
|
|
844
|
+
// yields past the cursor taken: a union sorted every candidate before its limit (28 s a tick), and a
|
|
845
|
+
// branch with nothing to give costs its scan once a tick, not once a row (0.3.31). A branch's records
|
|
846
|
+
// behind the cursor are reached on the next pass from the start, which the walk owes until a pass finds
|
|
847
|
+
// nothing.
|
|
848
|
+
const from = from0;
|
|
849
|
+
let rows = [];
|
|
850
|
+
for (const b of branches) {
|
|
851
|
+
rows = (await this.pool.query(b.sql, b.ps)).rows;
|
|
852
|
+
if (rows.length)
|
|
853
|
+
break;
|
|
854
|
+
}
|
|
855
|
+
const applied = [];
|
|
856
|
+
let last = from;
|
|
857
|
+
let cut = false;
|
|
858
|
+
// Fifty records a commit: a commit's fixed cost (the chain lock, the base, the definitions, the entry)
|
|
859
|
+
// is most of a record's three hundred milliseconds one by one, which made 139 a tick (2026-10-28). A
|
|
860
|
+
// batch that fails is retried one record at a time, so one bad record never holds the others.
|
|
861
|
+
const page = rows;
|
|
862
|
+
for (let i = 0; i < page.length; i += 50) {
|
|
863
|
+
// Within a budget when given: the rest of the page waits for the next tick, the cursor left on the last done.
|
|
864
|
+
if (budgetMs !== undefined && Date.now() - started > budgetMs) {
|
|
865
|
+
cut = true;
|
|
866
|
+
break;
|
|
867
|
+
}
|
|
868
|
+
const group = page.slice(i, i + 50);
|
|
869
|
+
const ids = group.map((row) => String(row.id));
|
|
870
|
+
const batched = await this.commit({ migration: "drain" }, (d) => { for (const id of ids)
|
|
871
|
+
apply(d, id, dict); }, at).then((e) => (e ? true : false), () => undefined);
|
|
872
|
+
if (batched === undefined) {
|
|
873
|
+
for (const id of ids) {
|
|
874
|
+
const entry = await this.commit({ migration: "drain" }, (d) => { apply(d, id, dict); }, at);
|
|
875
|
+
if (entry)
|
|
876
|
+
applied.push(id);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
else if (batched)
|
|
880
|
+
applied.push(...ids);
|
|
881
|
+
last = Number(group[group.length - 1].ord);
|
|
882
|
+
}
|
|
883
|
+
// A full page may have more behind it: the cursor moves on. A short page reached the end of the walk: the
|
|
884
|
+
// cursor returns to the start, and one more pass is owed unless this one began there and found nothing.
|
|
885
|
+
const full = rows.length >= rate || cut;
|
|
886
|
+
await this.pool.query("insert into drain_cursors (owner, ord) values ($1, $2) on conflict (owner) do update set ord = excluded.ord", [this.owner, full ? last : 0]);
|
|
887
|
+
return { applied, remaining: full || from > 0 ? 1 : 0 };
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Compact the projection streams (12.6.2): an entry a later entry for the same record superseded is
|
|
891
|
+
* dropped. Each record's latest entry stays, a removal among them, as does every `reset` marker, and the
|
|
892
|
+
* head keeps its number, so an index resuming from any cursor lands the same rows. A pass walks every
|
|
893
|
+
* current view's stream from its head DOWN in windows of `window` entries: walked that way, a record's
|
|
894
|
+
* latest entry is met before its earlier ones, so an earlier entry is superseded when the stored row's seq
|
|
895
|
+
* (a record in the view) or a removal met on the way (one that left) is above it; nothing scans ahead.
|
|
896
|
+
* Each window is one read of the entries' records, a lookup of their stored rows and of the removals met,
|
|
897
|
+
* and one delete by seq. A call stops at the budget and the next continues the pass from the cursors; when
|
|
898
|
+
* every stream has been walked the pass is done and the next call begins another, skipping any stream whose
|
|
899
|
+
* head has not moved since. Media Encyclopedia's four big streams held 2.3 million entries, 980,000 of them
|
|
900
|
+
* superseded, 2.3 GB of 21 (2026-10-28).
|
|
901
|
+
*/
|
|
902
|
+
async compact(budgetMs = 20_000, window = 10_000) {
|
|
903
|
+
const p = await this.projecting();
|
|
904
|
+
if (!p)
|
|
905
|
+
return { deleted: 0, done: true };
|
|
906
|
+
await this.compactReady();
|
|
907
|
+
const started = Date.now();
|
|
908
|
+
const streams = [...p.views.views.values()].map((v) => [this.owner, v.name, v.version ?? "", v.show]);
|
|
909
|
+
const cursorOf = async (key) => (await this.pool.query("select seq, done, head from compaction_cursors where owner = $1 and view = $2 and version = $3 and audience = $4", [...key])).rows[0];
|
|
910
|
+
// A pass is over when every current stream is done: the next call starts a fresh one from every head.
|
|
911
|
+
const cursors = await Promise.all(streams.map(cursorOf));
|
|
912
|
+
const fresh = streams.length > 0 && cursors.every((c) => c?.done);
|
|
913
|
+
if (fresh)
|
|
914
|
+
await this.pool.query("update compaction_cursors set seq = 0, done = false where owner = $1", [this.owner]);
|
|
915
|
+
let deleted = 0;
|
|
916
|
+
for (const [i, key] of streams.entries()) {
|
|
917
|
+
const c = cursors[i];
|
|
918
|
+
const was = fresh && c ? { ...c, seq: 0, done: false } : c;
|
|
919
|
+
if (was?.done)
|
|
920
|
+
continue;
|
|
921
|
+
const head = Number((await this.pool.query("select coalesce(max(seq), 0) as seq from projection_stream where owner = $1 and view = $2 and version = $3 and audience = $4", [...key])).rows[0].seq);
|
|
922
|
+
const mark = (seq, done, at = head) => this.pool.query("insert into compaction_cursors (owner, view, version, audience, seq, done, head) values ($1, $2, $3, $4, $5, $6, $7) on conflict (owner, view, version, audience) do update set seq = excluded.seq, done = excluded.done, head = excluded.head", [...key, seq, done, at]);
|
|
923
|
+
// The cursor is the seq the walk is below; 0 means the stream's walk has not started. A stream unmoved
|
|
924
|
+
// since the last pass, or empty, is done at once: nothing new can have superseded anything.
|
|
925
|
+
let from = Number(was?.seq ?? 0);
|
|
926
|
+
// The head the pass began at, kept with the cursor: entries published during a pass wait for the next.
|
|
927
|
+
let top = Number(was?.head ?? 0);
|
|
928
|
+
if (from === 0) {
|
|
929
|
+
if (head === 0 || head === top) {
|
|
930
|
+
await mark(0, true, head);
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
await this.pool.query("delete from compaction_removed where owner = $1 and view = $2 and version = $3 and audience = $4", [...key]);
|
|
934
|
+
top = head;
|
|
935
|
+
from = head + 1;
|
|
936
|
+
}
|
|
937
|
+
for (;;) {
|
|
938
|
+
if (Date.now() - started > budgetMs)
|
|
939
|
+
return { deleted, done: false };
|
|
940
|
+
const rows = (await this.pool.query("select seq, json ->> 'record' as record, (json ? 'reset') as reset, (json ? 'removed') as removed from projection_stream where owner = $1 and view = $2 and version = $3 and audience = $4 and seq < $5 order by seq desc limit $6", [...key, from, window])).rows;
|
|
941
|
+
if (rows.length) {
|
|
942
|
+
const records = [...new Set(rows.map((r) => r.record))];
|
|
943
|
+
// The removals met, this window's first: the highest seq per record, which is the one met first.
|
|
944
|
+
const gone = rows.filter((r) => r.removed).map((r) => ({ record: r.record, seq: Number(r.seq) }));
|
|
945
|
+
if (gone.length)
|
|
946
|
+
await this.pool.query("insert into compaction_removed (owner, view, version, audience, record, seq) select $1, $2, $3, $4, e ->> 'record', (e ->> 'seq')::bigint from jsonb_array_elements($5::jsonb) as t(e) on conflict (owner, view, version, audience, record) do update set seq = greatest(compaction_removed.seq, excluded.seq)", [...key, JSON.stringify(gone)]);
|
|
947
|
+
const above = new Map();
|
|
948
|
+
for (const r of (await this.pool.query("select record, seq from projections where owner = $1 and view = $2 and version = $3 and audience = $4 and record = any($5)", [...key, records])).rows)
|
|
949
|
+
above.set(r.record, Number(r.seq));
|
|
950
|
+
for (const r of (await this.pool.query("select record, seq from compaction_removed where owner = $1 and view = $2 and version = $3 and audience = $4 and record = any($5)", [...key, records])).rows)
|
|
951
|
+
above.set(r.record, Math.max(above.get(r.record) ?? 0, Number(r.seq)));
|
|
952
|
+
const superseded = rows.filter((r) => !r.reset && (above.get(r.record) ?? 0) > Number(r.seq)).map((r) => Number(r.seq));
|
|
953
|
+
if (superseded.length)
|
|
954
|
+
deleted += (await this.pool.query("delete from projection_stream where owner = $1 and view = $2 and version = $3 and audience = $4 and seq = any($5::bigint[])", [...key, superseded])).rowCount ?? 0;
|
|
955
|
+
from = Number(rows[rows.length - 1]?.seq ?? from);
|
|
956
|
+
}
|
|
957
|
+
const finished = rows.length < window;
|
|
958
|
+
await mark(finished ? 0 : from, finished, top);
|
|
959
|
+
if (finished)
|
|
960
|
+
break;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return { deleted, done: true };
|
|
964
|
+
}
|
|
965
|
+
/** What installing a version would restamp (10.4): per recipe and step, how many values change and how many go to review. */
|
|
966
|
+
async dryRun(bundle) {
|
|
967
|
+
const installed = await this.installed();
|
|
968
|
+
const previous = installed.filter((i) => i.package === bundle.id).map((i) => String(i.version)).at(-1);
|
|
969
|
+
if (!previous)
|
|
970
|
+
return { recipes: [], records: 0 };
|
|
971
|
+
const next = readBundleOnto(bundle, await this.definitions(true));
|
|
972
|
+
const own = readBundle(bundle);
|
|
973
|
+
const between = recipesBetween(next.recipes, String(bundle.package), previous, String(bundle.version));
|
|
974
|
+
// A recipe with no steps (a pin move) restamps nothing, so no record is read for it, however many the package
|
|
975
|
+
// owns. With steps, the package's own records are walked in batches by ord and each recipe's figures are
|
|
976
|
+
// summed over the batches: never all of them in memory at once.
|
|
977
|
+
const stepped = between.filter((r) => r.steps.length);
|
|
978
|
+
const out = new Map(between.map((r) => [r, { from: r.from, to: r.to, steps: [], review: 0 }]));
|
|
979
|
+
let records = 0;
|
|
980
|
+
if (stepped.length)
|
|
981
|
+
await this.walkOwnRecords(own, (batch) => {
|
|
982
|
+
records += batch.length;
|
|
983
|
+
for (const r of stepped) {
|
|
984
|
+
const d = dryRun(batch, r, next.dict);
|
|
985
|
+
const sum = out.get(r);
|
|
986
|
+
sum.review += d.review;
|
|
987
|
+
d.steps.forEach((st, i) => {
|
|
988
|
+
const have = sum.steps[i];
|
|
989
|
+
if (have) {
|
|
990
|
+
have.changed += st.changed;
|
|
991
|
+
have.review += st.review;
|
|
992
|
+
}
|
|
993
|
+
else
|
|
994
|
+
sum.steps[i] = { ...st };
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
return { recipes: between.map((r) => out.get(r)), records };
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* The records the package's recipes restamp (10.4): of its kinds or wearing its classes, read on the kind and
|
|
1002
|
+
* wears indexes in batches by ord, never the catalog whole and never all of them at once.
|
|
1003
|
+
*/
|
|
1004
|
+
async walkOwnRecords(own, fn) {
|
|
1005
|
+
const kinds = [...own.dict.kinds.keys()];
|
|
1006
|
+
const classes = [...own.dict.classes.keys()];
|
|
1007
|
+
if (!kinds.length && !classes.length)
|
|
1008
|
+
return;
|
|
1009
|
+
const size = Math.max(1, this.options.restampBatch ?? 5000);
|
|
1010
|
+
let after = -1;
|
|
1011
|
+
for (;;) {
|
|
1012
|
+
const { rows } = await this.pool.query("select * from records where owner = $1 and (kind = any($2::text[]) or wears && $3::text[]) and ord > $4 order by ord limit $5", [this.owner, kinds, classes, after, size]);
|
|
1013
|
+
if (!rows.length)
|
|
1014
|
+
return;
|
|
1015
|
+
const list = rows;
|
|
1016
|
+
fn(list.map((r) => recordOf(r)));
|
|
1017
|
+
after = Number(list[list.length - 1]?.ord);
|
|
1018
|
+
if (rows.length < size)
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
/** A define write (8.5, 11.4): one member of the working package as it now stands, checked with the rest first. */
|
|
1023
|
+
async define(member, by = { person: "owner" }, at) {
|
|
1024
|
+
// The trial is the package as it would stand with this write (a redefinition replacing, a retired member
|
|
1025
|
+
// gone), checked whole; only then does the write land.
|
|
1026
|
+
const client = await this.pool.connect();
|
|
1027
|
+
try {
|
|
1028
|
+
checkAll(await definitionsOf(client, this.owner, [member]));
|
|
1029
|
+
}
|
|
1030
|
+
finally {
|
|
1031
|
+
client.release();
|
|
1032
|
+
}
|
|
1033
|
+
const e = (await this.commitFrom(() => ({ by, extra: [{ define: member }], out: null }), at)).entry;
|
|
1034
|
+
this.defsCache = undefined;
|
|
1035
|
+
return e;
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* The owner's state as the tables hold it, kept per chain head: the same head answers from memory; a
|
|
1039
|
+
* head a little further on replays the entries since onto a copy (the engine's own replay), so a write
|
|
1040
|
+
* never costs a reload of every record; a gap over 200 entries, or an entry the replay can't take,
|
|
1041
|
+
* reads the tables whole. A commit works on a copy of the loaded state, so a kept state is never shared
|
|
1042
|
+
* with a draft. (G6: Cashierfu carried this around the store until 0.1.15.)
|
|
1043
|
+
*/
|
|
1044
|
+
async state() {
|
|
1045
|
+
if (this.options.wholeState === "refuse")
|
|
1046
|
+
throw new Error(`${this.owner}: the whole state is refused on a request path; read what is needed with read(), records(), installed(), edges() or openReview()`);
|
|
1047
|
+
return this.wholeState();
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* The whole state regardless of the option: for a rebuild, an erase, an install's restamp, an export and a
|
|
1051
|
+
* test's assertions. Never on a request path: `state()` is the guarded door, this one says what it is.
|
|
1052
|
+
*/
|
|
1053
|
+
async wholeState() {
|
|
1054
|
+
const client = await this.pool.connect();
|
|
1055
|
+
try {
|
|
1056
|
+
const { rows } = await client.query("select head_seq from chains where owner = $1 and chain = $2", [this.owner, this.chain]);
|
|
1057
|
+
const seq = rows.length ? Number(rows[0].head_seq) : -1;
|
|
1058
|
+
// A hosted person's writes go to their own chain (14.1) and move no head of ours, so the key the
|
|
1059
|
+
// state is kept under takes every hosted head along: one of theirs moving reads the tables whole.
|
|
1060
|
+
const hostedRows = await client.query("select coalesce(sum(head_seq), 0)::text as total, count(*)::text as n from chains where owner like $1 and chain = $2", [`${this.owner}:%`, this.chain]);
|
|
1061
|
+
const hosted = `${hostedRows.rows[0].n}/${hostedRows.rows[0].total}`;
|
|
1062
|
+
const kept = this.keptState;
|
|
1063
|
+
if (kept && kept.seq === seq && kept.hosted === hosted)
|
|
1064
|
+
return kept.state;
|
|
1065
|
+
if (kept && kept.hosted === hosted && seq > kept.seq && seq - kept.seq <= 200) {
|
|
1066
|
+
const since = await client.query("select seq, entry from log where owner = $1 and chain = $2 and seq > $3 order by seq", [this.owner, this.chain, kept.seq]);
|
|
1067
|
+
const entries = since.rows;
|
|
1068
|
+
const contiguous = entries.length === seq - kept.seq && entries.every((e, i) => Number(e.seq) === kept.seq + i + 1);
|
|
1069
|
+
if (contiguous) {
|
|
1070
|
+
const next = copyState(kept.state);
|
|
1071
|
+
try {
|
|
1072
|
+
for (const e of entries)
|
|
1073
|
+
applyEntry(next, e.entry);
|
|
1074
|
+
this.keptState = { seq, hosted, state: next };
|
|
1075
|
+
return next;
|
|
1076
|
+
}
|
|
1077
|
+
catch {
|
|
1078
|
+
// an entry the replay can't take: the tables, below
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
const state = await loadState(client, this.owner);
|
|
1083
|
+
this.keptState = { seq, hosted, state };
|
|
1084
|
+
return state;
|
|
1085
|
+
}
|
|
1086
|
+
finally {
|
|
1087
|
+
client.release();
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
// ─── Reads that never load the whole state (brief 18, the scale rule) ─────
|
|
1091
|
+
/**
|
|
1092
|
+
* A read on a working set: `fn` runs on a state whose records, bindings and runs load as it asks for them
|
|
1093
|
+
* (by id, level, parent, target or key), and runs again until it asked for nothing new; edges,
|
|
1094
|
+
* instructions and the working package are loaded whole (they are small). The lists (reviews,
|
|
1095
|
+
* observations, installed, reads) are not loaded here: the readers below serve them. `fn` MUST be pure.
|
|
1096
|
+
*/
|
|
1097
|
+
async read(fn, opts = {}) {
|
|
1098
|
+
const client = await this.pool.connect();
|
|
1099
|
+
try {
|
|
1100
|
+
const needs = new Needs();
|
|
1101
|
+
if (this.options.wholeState === "refuse" && !opts.allowAll)
|
|
1102
|
+
needs.refuseAll = `${this.owner}: records.all() asks for the whole catalog on a request path; ask by level, parent, target or key`;
|
|
1103
|
+
const base = workingState(needs);
|
|
1104
|
+
await loadWhole(client, this.owner, base);
|
|
1105
|
+
const { out } = await settle(client, this.owner, base, fn);
|
|
1106
|
+
return out;
|
|
1107
|
+
}
|
|
1108
|
+
finally {
|
|
1109
|
+
client.release();
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
/** Records by level, kind, parent, placement or one key's value, in log order; paged by `ord`. */
|
|
1113
|
+
async records(where = {}, opts = {}) {
|
|
1114
|
+
const conds = ["owner = $1"];
|
|
1115
|
+
const params = [this.owner];
|
|
1116
|
+
const add = (sql, v) => { params.push(v); conds.push(sql.replace("?", `$${params.length}`)); };
|
|
1117
|
+
if (where.level)
|
|
1118
|
+
add("level = ?", where.level);
|
|
1119
|
+
if (where.kind)
|
|
1120
|
+
add("kind = ?", where.kind);
|
|
1121
|
+
if (where.of)
|
|
1122
|
+
add('"of" = ?', where.of);
|
|
1123
|
+
if (where.within)
|
|
1124
|
+
add("within = ?", where.within);
|
|
1125
|
+
// Containment, so the GIN on the values document answers (an equality on `->` would not).
|
|
1126
|
+
if (where.key)
|
|
1127
|
+
add("doc -> 'values' @> ?::jsonb", JSON.stringify({ [where.key[0]]: where.key[1] }));
|
|
1128
|
+
if (opts.archived === false)
|
|
1129
|
+
add("coalesce(status ->> 'state', '') <> ?", "archived");
|
|
1130
|
+
if (opts.after !== undefined)
|
|
1131
|
+
add("ord > ?", opts.after);
|
|
1132
|
+
const limit = opts.limit ? ` limit ${Math.max(1, Math.floor(opts.limit))}` : "";
|
|
1133
|
+
const { rows } = await this.pool.query(`select * from records where ${conds.join(" and ")} order by ord${limit}`, params);
|
|
1134
|
+
return rows.map((r) => recordOf(r));
|
|
1135
|
+
}
|
|
1136
|
+
/** Every edge of the owner (small: people and their grants). */
|
|
1137
|
+
async edges() {
|
|
1138
|
+
const { rows } = await this.pool.query("select json from edges where owner = $1 order by ord", [this.owner]);
|
|
1139
|
+
return rows.map((r) => r.json);
|
|
1140
|
+
}
|
|
1141
|
+
/** The install log as what is in force: every version taken, in order, less the packages that left (11.4). */
|
|
1142
|
+
async installed() {
|
|
1143
|
+
return installsInForce(await this.installLog());
|
|
1144
|
+
}
|
|
1145
|
+
/** The install log whole: every version taken and every leaving, in order. */
|
|
1146
|
+
async installLog() {
|
|
1147
|
+
const { rows } = await this.pool.query("select json from installed where owner = $1 order by ord", [this.owner]);
|
|
1148
|
+
return rows.map((r) => r.json);
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* A package leaves (11.4, revision 30): refused while a package in force extends it, a utility in force needs it
|
|
1152
|
+
* (its own excepted), or a record holds a value under a key it alone declares; else the log takes an install
|
|
1153
|
+
* write with `left`, and the set in force is read without it.
|
|
1154
|
+
*/
|
|
1155
|
+
async leave(pkg, at) {
|
|
1156
|
+
const inForce = await this.installed();
|
|
1157
|
+
const mine = inForce.filter((i) => i.package === pkg);
|
|
1158
|
+
if (!mine.length)
|
|
1159
|
+
throw new Error(`${pkg} isn't in force here`);
|
|
1160
|
+
const version = String(mine.at(-1)?.version);
|
|
1161
|
+
const others = [...new Map(inForce.filter((i) => i.package !== pkg).map((i) => [String(i.package), String(i.version)])).entries()];
|
|
1162
|
+
const bundleOf = async (p, v) => (await this.pool.query("select json from bundles where owner = $1 and package = $2 and version = $3", [this.owner, p, v])).rows[0]?.json;
|
|
1163
|
+
const own = await bundleOf(pkg, version);
|
|
1164
|
+
if (!own)
|
|
1165
|
+
throw new Error(`${pkg} /${version} is installed but its bundle is missing`);
|
|
1166
|
+
const theirFacets = new Set();
|
|
1167
|
+
for (const [p, v] of others) {
|
|
1168
|
+
const b = await bundleOf(p, v);
|
|
1169
|
+
if (!b)
|
|
1170
|
+
continue;
|
|
1171
|
+
for (const e of b.extends ?? []) {
|
|
1172
|
+
const dep = String(e.package).includes("/") ? String(e.package) : `${b.owner}/${e.package}`;
|
|
1173
|
+
if (dep === pkg)
|
|
1174
|
+
throw new Error(`${pkg} can't leave: ${b.id} extends it; it leaves first`);
|
|
1175
|
+
}
|
|
1176
|
+
for (const k of readBundle(b).dict.facets.keys())
|
|
1177
|
+
theirFacets.add(k);
|
|
1178
|
+
}
|
|
1179
|
+
const parsedOwn = readBundle(own);
|
|
1180
|
+
const ownUtilities = new Set(parsedOwn.info.utilities.map((u) => u.name));
|
|
1181
|
+
const defs = await this.definitions(true);
|
|
1182
|
+
const needing = defs.info.utilities.filter((u) => !ownUtilities.has(u.name) && u.needs.some((n) => n.name === pkg)).map((u) => u.name);
|
|
1183
|
+
if (needing.length)
|
|
1184
|
+
throw new Error(`${pkg} can't leave: ${needing.join(", ")} need${needing.length === 1 ? "s" : ""} it; switch ${needing.length === 1 ? "it" : "them"} off first`);
|
|
1185
|
+
// The package's own keys: not the standard's (`crubal:`), not another package's in force.
|
|
1186
|
+
const ownKeys = [...parsedOwn.dict.facets.keys()].filter((k) => !k.startsWith("crubal:") && !theirFacets.has(k));
|
|
1187
|
+
if (ownKeys.length) {
|
|
1188
|
+
const { rows } = await this.pool.query("select count(*)::int as n from records where owner = $1 and doc -> 'values' ?| $2::text[]", [this.owner, ownKeys]);
|
|
1189
|
+
const n = Number(rows[0]?.n ?? 0);
|
|
1190
|
+
if (n > 0)
|
|
1191
|
+
throw new Error(`${pkg} can't leave: ${n} record${n === 1 ? " holds" : "s hold"} values under ${ownKeys.join(", ")}; hand or cut them first (10.3)`);
|
|
1192
|
+
}
|
|
1193
|
+
const r = await this.commitFrom(() => ({ by: { person: "owner" }, extra: [{ install: { package: pkg, version, left: true } }], out: null }), at);
|
|
1194
|
+
if (!r.entry)
|
|
1195
|
+
throw new Error(`${pkg}: the leaving wrote no entry`);
|
|
1196
|
+
return r.entry;
|
|
1197
|
+
}
|
|
1198
|
+
/** The record a binding (`contract|ref`) names, if any. */
|
|
1199
|
+
async binding(key) {
|
|
1200
|
+
const { rows } = await this.pool.query("select record from bindings where owner = $1 and key = $2", [this.owner, key]);
|
|
1201
|
+
return rows[0] ? String(rows[0].record) : undefined;
|
|
1202
|
+
}
|
|
1203
|
+
/** The owner's working package (11.4): `<member>:<name>` → the definition as it now stands. */
|
|
1204
|
+
async defines() {
|
|
1205
|
+
const { rows } = await this.pool.query("select key, json from definitions where owner = $1 order by ord", [this.owner]);
|
|
1206
|
+
return new Map(rows.map((r) => [String(r.key), r.json]));
|
|
1207
|
+
}
|
|
1208
|
+
/** Every review item ever written, decided or not, in order (9.5); `review()` is the open ones. */
|
|
1209
|
+
async reviews() {
|
|
1210
|
+
const { rows } = await this.pool.query("select json from review where owner = $1 order by ord", [this.owner]);
|
|
1211
|
+
return rows.map((r) => r.json);
|
|
1212
|
+
}
|
|
1213
|
+
/** The records several bindings name, by key: one query for an import's references. */
|
|
1214
|
+
async bindings(keys) {
|
|
1215
|
+
if (!keys.length)
|
|
1216
|
+
return new Map();
|
|
1217
|
+
const { rows } = await this.pool.query("select key, record from bindings where owner = $1 and key = any($2)", [this.owner, keys]);
|
|
1218
|
+
return new Map(rows.map((r) => [String(r.key), String(r.record)]));
|
|
1219
|
+
}
|
|
1220
|
+
/** The log of reads under an emergency edge (14.13), in order. */
|
|
1221
|
+
async emergencyReads() {
|
|
1222
|
+
const { rows } = await this.pool.query("select json from reads where owner = $1 order by ord", [this.owner]);
|
|
1223
|
+
return rows.map((r) => r.json);
|
|
1224
|
+
}
|
|
1225
|
+
/** The observations on one record, or on or supporting any of several (9.7). */
|
|
1226
|
+
async observationsOn(id) {
|
|
1227
|
+
return this.observations({ on: id });
|
|
1228
|
+
}
|
|
1229
|
+
/** Observations by what they are on or support, their evidence type and their address (9.7); never all of them unasked. */
|
|
1230
|
+
async observations(where) {
|
|
1231
|
+
const conds = ["owner = $1"];
|
|
1232
|
+
const params = [this.owner];
|
|
1233
|
+
const add = (sql, v) => { params.push(v); conds.push(sql.replace("?", `$${params.length}`)); };
|
|
1234
|
+
if (where.on !== undefined) {
|
|
1235
|
+
const ids = Array.isArray(where.on) ? where.on : [where.on];
|
|
1236
|
+
params.push(ids);
|
|
1237
|
+
conds.push(`(json ->> 'on' = any($${params.length}) or json ->> 'supports' = any($${params.length}))`);
|
|
1238
|
+
}
|
|
1239
|
+
if (where.evidenceType)
|
|
1240
|
+
add("json ->> 'evidence-type' = ?", where.evidenceType);
|
|
1241
|
+
if (where.address)
|
|
1242
|
+
add("json ->> 'address' = ?", where.address);
|
|
1243
|
+
if (conds.length === 1)
|
|
1244
|
+
throw new Error(`${this.owner}: observations() wants what they are on, their evidence type or their address`);
|
|
1245
|
+
const { rows } = await this.pool.query(`select json from observations where ${conds.join(" and ")} order by ord`, params);
|
|
1246
|
+
return rows.map((r) => r.json);
|
|
1247
|
+
}
|
|
1248
|
+
keptState;
|
|
1249
|
+
/** Forget the kept state: after a rewrite of history that moves no head (an erase, a rebuild). */
|
|
1250
|
+
forgetState() {
|
|
1251
|
+
this.keptState = undefined;
|
|
1252
|
+
}
|
|
1253
|
+
/** The owner's entries, in chain order. */
|
|
1254
|
+
async entries() {
|
|
1255
|
+
const { rows } = await this.pool.query("select entry from log where owner = $1 and chain = $2 order by seq", [this.owner, this.chain]);
|
|
1256
|
+
return rows.map((r) => r.entry);
|
|
1257
|
+
}
|
|
1258
|
+
/** Lock the chain for this transaction and return its head. Writers to one chain serialize here. */
|
|
1259
|
+
async lockChain(client) {
|
|
1260
|
+
await client.query("insert into chains (owner, chain) values ($1, $2) on conflict do nothing", [this.owner, this.chain]);
|
|
1261
|
+
const { rows } = await client.query("select head_seq, head_hash from chains where owner = $1 and chain = $2 for update", [this.owner, this.chain]);
|
|
1262
|
+
const head = rows[0];
|
|
1263
|
+
return { seq: Number(head.head_seq), hash: head.head_hash };
|
|
1264
|
+
}
|
|
1265
|
+
/** Link an entry to the chain's head, insert it, and move the head. The entry gets its `prev`. */
|
|
1266
|
+
async link(client, entry, head, owner = this.owner, signer = this.options.signer) {
|
|
1267
|
+
const linked = { ...entry };
|
|
1268
|
+
if (head.hash)
|
|
1269
|
+
linked.prev = `sha256:${head.hash}`;
|
|
1270
|
+
else
|
|
1271
|
+
delete linked.prev;
|
|
1272
|
+
const hash = entryHash(linked);
|
|
1273
|
+
if (signer)
|
|
1274
|
+
linked.sig = signer(hash);
|
|
1275
|
+
const seq = head.seq + 1;
|
|
1276
|
+
await client.query("insert into log (owner, chain, seq, log_id, prev, hash, at, witnessed, entry) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)", [owner, this.chain, seq, String(linked.log), linked.prev ?? null, hash, typeof linked.at === "string" ? linked.at : null, linked.witnessed === true, linked]);
|
|
1277
|
+
await client.query("update chains set head_seq = $3, head_hash = $4 where owner = $1 and chain = $2", [owner, this.chain, seq, hash]);
|
|
1278
|
+
// Revision 50: the records this entry touches, indexed as it lands; the index is whole through this entry
|
|
1279
|
+
// where it was whole through the one before.
|
|
1280
|
+
await this.touchesReady();
|
|
1281
|
+
const touched = touchedBy(linked);
|
|
1282
|
+
if (touched.length)
|
|
1283
|
+
await client.query("insert into log_touches (owner, chain, record, seq) select $1, $2, r, $3 from unnest($4::text[]) as r on conflict do nothing", [owner, this.chain, seq, touched]);
|
|
1284
|
+
await client.query("insert into log_touch_cursors (owner, chain, seq) values ($1, $2, 0) on conflict do nothing", [owner, this.chain]);
|
|
1285
|
+
await client.query("update log_touch_cursors set seq = $3 where owner = $1 and chain = $2 and seq = $3 - 1", [owner, this.chain, seq]);
|
|
1286
|
+
return linked;
|
|
1287
|
+
}
|
|
1288
|
+
/** The index of the records each entry touches, and how far it is whole (revision 50); made once per process. */
|
|
1289
|
+
touchTable;
|
|
1290
|
+
touchesReady() {
|
|
1291
|
+
this.touchTable ??= (async () => {
|
|
1292
|
+
await this.pool.query("create table if not exists log_touches (owner text not null, chain text not null, record text not null, seq bigint not null, primary key (owner, chain, record, seq))");
|
|
1293
|
+
await this.pool.query("create table if not exists log_touch_cursors (owner text not null, chain text not null, seq bigint not null default 0, primary key (owner, chain))");
|
|
1294
|
+
})();
|
|
1295
|
+
return this.touchTable;
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Revision 50: index the entries of a log from before the index, a bounded batch at a time, oldest first.
|
|
1299
|
+
* The chain is held for the batch, as a write holds it, so no entry lands between the read and the cursor.
|
|
1300
|
+
* Answers how far the index is whole and the chain's head; they are equal when there is nothing left.
|
|
1301
|
+
*/
|
|
1302
|
+
async indexTouches(limit = 500) {
|
|
1303
|
+
await this.touchesReady();
|
|
1304
|
+
return transaction(this.pool, async (client) => {
|
|
1305
|
+
const head = await this.lockChain(client);
|
|
1306
|
+
await client.query("insert into log_touch_cursors (owner, chain, seq) values ($1, $2, 0) on conflict do nothing", [this.owner, this.chain]);
|
|
1307
|
+
const cur = await client.query("select seq from log_touch_cursors where owner = $1 and chain = $2", [this.owner, this.chain]);
|
|
1308
|
+
let through = Math.max(0, Number(cur.rows[0]?.seq ?? 0));
|
|
1309
|
+
if (through >= head.seq)
|
|
1310
|
+
return { through: head.seq, head: head.seq };
|
|
1311
|
+
const { rows } = await client.query("select seq, entry from log where owner = $1 and chain = $2 and seq > $3 order by seq limit $4", [this.owner, this.chain, through, Math.max(1, Math.floor(limit))]);
|
|
1312
|
+
for (const row of rows) {
|
|
1313
|
+
const touched = touchedBy(row.entry);
|
|
1314
|
+
if (touched.length)
|
|
1315
|
+
await client.query("insert into log_touches (owner, chain, record, seq) select $1, $2, r, $3 from unnest($4::text[]) as r on conflict do nothing", [this.owner, this.chain, Number(row.seq), touched]);
|
|
1316
|
+
through = Number(row.seq);
|
|
1317
|
+
}
|
|
1318
|
+
await client.query("update log_touch_cursors set seq = $3 where owner = $1 and chain = $2", [this.owner, this.chain, through]);
|
|
1319
|
+
return { through, head: head.seq };
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Revision 50: one record as it stood at a moment (as it stands, when none is said), and when each of its
|
|
1324
|
+
* values last changed. Read by the index where it is whole; else by the log itself, which is slower and
|
|
1325
|
+
* answers the same.
|
|
1326
|
+
*/
|
|
1327
|
+
async recordAt(id, until) {
|
|
1328
|
+
await this.touchesReady();
|
|
1329
|
+
const { rows: at } = await this.pool.query("select c.head_seq as head, coalesce(t.seq, 0) as through from chains c left join log_touch_cursors t on t.owner = c.owner and t.chain = c.chain where c.owner = $1 and c.chain = $2", [this.owner, this.chain]);
|
|
1330
|
+
const where = at[0];
|
|
1331
|
+
if (!where)
|
|
1332
|
+
return { changed: {} };
|
|
1333
|
+
const whole = Number(where.through) >= Number(where.head);
|
|
1334
|
+
const { rows } = whole
|
|
1335
|
+
? await this.pool.query("select l.entry from log l join log_touches t on t.owner = l.owner and t.chain = l.chain and t.seq = l.seq where t.owner = $1 and t.chain = $2 and t.record = $3 order by l.seq", [this.owner, this.chain, id])
|
|
1336
|
+
: await this.pool.query("select entry from log where owner = $1 and chain = $2 and entry->'writes' @> $3::jsonb order by seq", [this.owner, this.chain, JSON.stringify([{ record: id }])]);
|
|
1337
|
+
return recordAt(rows.map((r) => r.entry), id, until);
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* A hosted person's records live in their own chain (14.1): the writes to records owned `<owner>:<id>`
|
|
1341
|
+
* leave the owner's entry and become one entry per person, linked and signed in the same transaction.
|
|
1342
|
+
* The chains lock in a fixed order (the owner's first, then the persons' by name).
|
|
1343
|
+
*/
|
|
1344
|
+
async linkSplit(client, entry, head, after) {
|
|
1345
|
+
const prefix = `${this.owner}:`;
|
|
1346
|
+
const byOwner = new Map();
|
|
1347
|
+
const own = [];
|
|
1348
|
+
for (const w of (Array.isArray(entry.writes) ? entry.writes : [])) {
|
|
1349
|
+
const rec = typeof w.record === "string" ? after.records.get(w.record) : undefined;
|
|
1350
|
+
const o = rec?.owner;
|
|
1351
|
+
if (o && o.startsWith(prefix))
|
|
1352
|
+
byOwner.set(o, [...(byOwner.get(o) ?? []), w]);
|
|
1353
|
+
else
|
|
1354
|
+
own.push(w);
|
|
1355
|
+
}
|
|
1356
|
+
const hosted = [];
|
|
1357
|
+
for (const person of [...byOwner.keys()].sort()) {
|
|
1358
|
+
await client.query("insert into chains (owner, chain) values ($1, $2) on conflict do nothing", [person, this.chain]);
|
|
1359
|
+
const { rows } = await client.query("select head_seq, head_hash from chains where owner = $1 and chain = $2 for update", [person, this.chain]);
|
|
1360
|
+
const h = rows[0];
|
|
1361
|
+
const ph = { seq: Number(h.head_seq), hash: h.head_hash };
|
|
1362
|
+
const signer = this.options.hostedSigner ? await this.options.hostedSigner(person) : undefined;
|
|
1363
|
+
const e = { ...entry, log: `L-${ph.seq + 1}`, owner: person, writes: byOwner.get(person) };
|
|
1364
|
+
hosted.push(await this.link(client, e, ph, person, signer));
|
|
1365
|
+
}
|
|
1366
|
+
if (!own.length)
|
|
1367
|
+
return { entry: null, hosted };
|
|
1368
|
+
return { entry: await this.link(client, { ...entry, writes: own }, head), hosted };
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Append an entry made elsewhere (a rebuilt log, a hosted person's chain the host carries): it is
|
|
1372
|
+
* linked to this chain's head, applied with the engine's applyEntry, and its effects persisted.
|
|
1373
|
+
*/
|
|
1374
|
+
async append(entry) {
|
|
1375
|
+
return transaction(this.pool, async (client) => {
|
|
1376
|
+
const head = await this.lockChain(client);
|
|
1377
|
+
const base = await this.base(client);
|
|
1378
|
+
const linked = await this.link(client, entry, head);
|
|
1379
|
+
const { state: after } = await settle(client, this.owner, base, (s) => applyEntry(s, linked));
|
|
1380
|
+
await persist(client, this.owner, base, after);
|
|
1381
|
+
await this.afterPersist(client, base, after, head.seq + 1);
|
|
1382
|
+
return linked;
|
|
1383
|
+
}).then(async (e) => {
|
|
1384
|
+
await this.freshen();
|
|
1385
|
+
return e;
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
/** An empty working state with the whole small tables in it; records, bindings and runs load as needed. */
|
|
1389
|
+
async base(client) {
|
|
1390
|
+
const needs = new Needs();
|
|
1391
|
+
if (this.options.wholeState === "refuse" && !this.walking)
|
|
1392
|
+
needs.refuseAll = `${this.owner}: records.all() asks for the whole catalog inside a commit on a request path; ask by level, parent, target or key`;
|
|
1393
|
+
this.trace = needs;
|
|
1394
|
+
const base = workingState(needs);
|
|
1395
|
+
await loadWhole(client, this.owner, base);
|
|
1396
|
+
return base;
|
|
1397
|
+
}
|
|
1398
|
+
/** What the last operation loaded, for tests and for watching a store's cost. */
|
|
1399
|
+
trace;
|
|
1400
|
+
/** Set while an install restamps: its commit walks the package's records by design, whatever `wholeState` says. */
|
|
1401
|
+
walking = false;
|
|
1402
|
+
/**
|
|
1403
|
+
* One operation, one entry (8.5): the engine runs on a draft of the state, what it changed becomes the
|
|
1404
|
+
* entry's writes (plus `extra` writes the diff can't see), and the entry is applied and persisted in the
|
|
1405
|
+
* same transaction. Nothing happens when nothing changed; a throw inside `mutate` rolls everything back.
|
|
1406
|
+
*/
|
|
1407
|
+
/**
|
|
1408
|
+
* A quorum (7.6) holds a commit by hand to the same rule as a run: a cause naming a contract whose quorum
|
|
1409
|
+
* holds must cite a met proposal (`by.proposal`), or the commit is refused before anything is written.
|
|
1410
|
+
*/
|
|
1411
|
+
quorumGate(p, d, by) {
|
|
1412
|
+
const name = typeof by.contract === "string" ? by.contract : undefined;
|
|
1413
|
+
if (!name)
|
|
1414
|
+
return;
|
|
1415
|
+
const c = p.contracts.find((x) => x.name === name);
|
|
1416
|
+
if (!c || !quorumHolds(c, d.records))
|
|
1417
|
+
return;
|
|
1418
|
+
const cite = typeof by.proposal === "string" ? by.proposal : undefined;
|
|
1419
|
+
if (!proposalMet(d.records, cite, name))
|
|
1420
|
+
throw new QuorumRefused(name, cite);
|
|
1421
|
+
}
|
|
1422
|
+
async commit(by, mutate, at, extra = []) {
|
|
1423
|
+
return (await this.commitFrom((d) => { mutate(d); return { by, extra, out: undefined }; }, at)).entry;
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* The same, for an operation that decides its own cause and extra writes as it runs (a border run): it
|
|
1427
|
+
* returns `by`, `extra` and an outcome, and the outcome comes back beside the entry.
|
|
1428
|
+
*/
|
|
1429
|
+
async commitFrom(run, at, mark = {}) {
|
|
1430
|
+
return transaction(this.pool, async (client) => {
|
|
1431
|
+
// CRUBAL_TRACE_COMMIT=1 prints each phase's time to stderr, for a probe or a slow commit in the field.
|
|
1432
|
+
const T0 = Date.now();
|
|
1433
|
+
const tr = (label) => { if (process.env.CRUBAL_TRACE_COMMIT)
|
|
1434
|
+
console.error(`commit ${this.owner} ${label} ${Date.now() - T0} ms`); };
|
|
1435
|
+
const head = await this.lockChain(client);
|
|
1436
|
+
const before = await this.base(client);
|
|
1437
|
+
tr("base");
|
|
1438
|
+
const needs = before.records;
|
|
1439
|
+
// The operation runs until the working set holds everything it asked for (working.ts); so does the
|
|
1440
|
+
// entry's application. Both run on copies of the same base, so the draft and the applied state
|
|
1441
|
+
// hold the same records and `differs` compares like with like.
|
|
1442
|
+
let draft;
|
|
1443
|
+
let after;
|
|
1444
|
+
let entry;
|
|
1445
|
+
let result;
|
|
1446
|
+
const p = await this.definitionsFrom(client, false);
|
|
1447
|
+
tr("definitions");
|
|
1448
|
+
for (;;) {
|
|
1449
|
+
const had = needs.needs.loaded.size;
|
|
1450
|
+
({ draft, result } = (await settle(client, this.owner, before, (s) => { const d = draftOf(s); const r = run(d); this.quorumGate(p, d, r.by); this.derive(p, before, d); return { draft: d, result: r }; })).out);
|
|
1451
|
+
const writes = [...diffWrites(before, draft), ...(result.extra ?? [])];
|
|
1452
|
+
if (!writes.length)
|
|
1453
|
+
return { entry: null, out: result.out };
|
|
1454
|
+
entry = { log: `L-${head.seq + 1}`, owner: this.owner, at: at ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), by: result.by, writes, ...(mark.witnessed ? { witnessed: true } : {}) };
|
|
1455
|
+
const e = entry;
|
|
1456
|
+
// The entry applied, then checked in the same run (14.12, 5.5, 14.1), so what the check reads loads too.
|
|
1457
|
+
after = (await settle(client, this.owner, before, (s) => { applyEntry(s, e); this.checkWrites(p, e, s); })).state;
|
|
1458
|
+
if (needs.needs.loaded.size === had)
|
|
1459
|
+
break;
|
|
1460
|
+
}
|
|
1461
|
+
tr(`settled, ${needs.needs.loaded.size} records loaded`);
|
|
1462
|
+
const { entry: linked, hosted } = await this.linkSplit(client, entry, head, after);
|
|
1463
|
+
const problem = differs(after, draft);
|
|
1464
|
+
if (problem)
|
|
1465
|
+
throw new Error(`the log doesn't describe the change: ${problem}`);
|
|
1466
|
+
await persist(client, this.owner, before, after);
|
|
1467
|
+
tr("persisted");
|
|
1468
|
+
await this.afterPersist(client, before, after, head.seq + (linked ? 1 : 0), p);
|
|
1469
|
+
tr("stale marked");
|
|
1470
|
+
// The definitions in force are unchanged by an entry with no define write (an install clears the
|
|
1471
|
+
// cache itself), so the cache follows the head: parsing them again cost every commit, and the first
|
|
1472
|
+
// read after it, ~110 ms on ME.
|
|
1473
|
+
if (linked && this.defsCache?.seq === head.seq && !(Array.isArray(entry.writes) ? entry.writes : []).some((w) => isObj(w) && isObj(w.define)))
|
|
1474
|
+
this.defsCache = { seq: head.seq + 1, parsed: this.defsCache.parsed };
|
|
1475
|
+
return { entry: linked ?? hosted[0], out: result.out };
|
|
1476
|
+
}).then(async (r) => {
|
|
1477
|
+
if (r.entry)
|
|
1478
|
+
await this.freshen();
|
|
1479
|
+
return r;
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
/**
|
|
1483
|
+
* Erase a record's values from the log (8.5.2): every value write to it, and every observation on it, in
|
|
1484
|
+
* every entry, is redacted in place; creations, envelopes and everything else stay. The state is rebuilt.
|
|
1485
|
+
*/
|
|
1486
|
+
async erase(recordId) {
|
|
1487
|
+
const witnessed = [];
|
|
1488
|
+
let redacted = 0;
|
|
1489
|
+
await transaction(this.pool, async (client) => {
|
|
1490
|
+
await this.lockChain(client);
|
|
1491
|
+
const { rows } = await client.query("select owner, log_id, entry from log where (owner = $1 or owner like $1 || ':%') and chain = $2 and not (entry ? 'redacted') order by ord for update", [this.owner, this.chain]);
|
|
1492
|
+
for (const row of rows) {
|
|
1493
|
+
const writes = Array.isArray(row.entry.writes) ? row.entry.writes : [];
|
|
1494
|
+
const hits = writes.map((w, i) => (isObj(w) && ((w.record === recordId && typeof w.address === "string") || (isObj(w.observation) && w.observation.on === recordId)) ? i : -1)).filter((i) => i >= 0);
|
|
1495
|
+
if (!hits.length)
|
|
1496
|
+
continue;
|
|
1497
|
+
if (row.entry.witnessed === true) {
|
|
1498
|
+
witnessed.push(row.log_id);
|
|
1499
|
+
continue;
|
|
1500
|
+
}
|
|
1501
|
+
const next = [...writes];
|
|
1502
|
+
for (const i of hits)
|
|
1503
|
+
next[i] = { redacted: `sha256:${writeHash(writes[i])}` };
|
|
1504
|
+
await client.query("update log set entry = $3 where owner = $1 and log_id = $2", [row.owner, row.log_id, { ...row.entry, writes: next }]);
|
|
1505
|
+
redacted += hits.length;
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
// What is kept beside the log for the record goes too: the payloads sent about it.
|
|
1509
|
+
await this.pool.query("delete from outtake where owner = $1 and record = $2", [this.owner, recordId]);
|
|
1510
|
+
if (redacted)
|
|
1511
|
+
await this.rebuild();
|
|
1512
|
+
return { redacted, witnessed };
|
|
1513
|
+
}
|
|
1514
|
+
/** Check the chain's links and, with the owner's key, its signatures (8.5). */
|
|
1515
|
+
async verify(keys) {
|
|
1516
|
+
return verifyChain((await this.entries()), keys);
|
|
1517
|
+
}
|
|
1518
|
+
/** Empty the owner's state tables and apply the log again, in order (8.5.3). */
|
|
1519
|
+
async rebuild() {
|
|
1520
|
+
return transaction(this.pool, async (client) => {
|
|
1521
|
+
await this.lockChain(client);
|
|
1522
|
+
await wipeState(client, this.owner);
|
|
1523
|
+
// The owner's chain and the chains of the people it hosts (14.1), in the order they were written.
|
|
1524
|
+
const { rows } = await client.query("select entry from log where (owner = $1 or owner like $1 || ':%') and chain = $2 order by ord", [this.owner, this.chain]);
|
|
1525
|
+
for (const row of rows) {
|
|
1526
|
+
const base = await this.base(client);
|
|
1527
|
+
const { state } = await settle(client, this.owner, base, (s) => applyEntry(s, row.entry));
|
|
1528
|
+
await persist(client, this.owner, base, state);
|
|
1529
|
+
}
|
|
1530
|
+
// Projections follow: every row of every view is marked stale, so the next publish rebuilds and
|
|
1531
|
+
// compares them all and announces what left.
|
|
1532
|
+
await this.staleAll((sql, params) => client.query(sql, params), await this.projectingFrom(client));
|
|
1533
|
+
return loadState(client, this.owner);
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
/**
|
|
1537
|
+
* Redact one write of an entry, or the whole entry (8.5.2): the log's one update, which the trigger
|
|
1538
|
+
* admits and nothing else. The state is then rebuilt, so the cache forgets what the log forgot.
|
|
1539
|
+
*/
|
|
1540
|
+
async redact(logId, writeIndex) {
|
|
1541
|
+
await transaction(this.pool, async (client) => {
|
|
1542
|
+
await this.lockChain(client);
|
|
1543
|
+
const { rows } = await client.query("select entry from log where owner = $1 and log_id = $2 for update", [this.owner, logId]);
|
|
1544
|
+
const entry = rows[0]?.entry;
|
|
1545
|
+
if (!entry)
|
|
1546
|
+
throw new Error(`no entry ${logId}`);
|
|
1547
|
+
if (entry.witnessed === true)
|
|
1548
|
+
throw new Error("a witnessed entry is never redacted");
|
|
1549
|
+
let next;
|
|
1550
|
+
if (writeIndex === undefined) {
|
|
1551
|
+
const writes = Array.isArray(entry.writes) ? entry.writes : [];
|
|
1552
|
+
for (const w of writes)
|
|
1553
|
+
if (isObj(w) && !(typeof w.record === "string" && typeof w.address === "string") && !isObj(w.observation) && typeof w.read !== "string" && typeof w.redacted !== "string")
|
|
1554
|
+
throw new Error("an entry holding a write that is never redacted is redacted write by write, never whole");
|
|
1555
|
+
next = { log: String(entry.log), redacted: `sha256:${entryHash(entry)}` };
|
|
1556
|
+
if (entry.prev !== undefined)
|
|
1557
|
+
next.prev = entry.prev;
|
|
1558
|
+
if (entry.chain !== undefined)
|
|
1559
|
+
next.chain = entry.chain;
|
|
1560
|
+
if (entry.sig !== undefined)
|
|
1561
|
+
next.sig = entry.sig;
|
|
1562
|
+
}
|
|
1563
|
+
else {
|
|
1564
|
+
const writes = Array.isArray(entry.writes) ? [...entry.writes] : [];
|
|
1565
|
+
const w = writes[writeIndex];
|
|
1566
|
+
if (!isObj(w))
|
|
1567
|
+
throw new Error(`no write ${writeIndex} in ${logId}`);
|
|
1568
|
+
if (!(typeof w.record === "string" && typeof w.address === "string") && !isObj(w.observation) && typeof w.read !== "string")
|
|
1569
|
+
throw new Error("a write that created a record, changed its envelope or a definition, or wrote an edge, binding, review, instruction, run or install is never redacted");
|
|
1570
|
+
writes[writeIndex] = { redacted: `sha256:${writeHash(w)}` };
|
|
1571
|
+
next = { ...entry, writes };
|
|
1572
|
+
}
|
|
1573
|
+
await client.query("update log set entry = $3 where owner = $1 and log_id = $2", [this.owner, logId, next]);
|
|
1574
|
+
});
|
|
1575
|
+
await this.rebuild();
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
/** The facets a dictionary declares `transitions: yes` (4.2). */
|
|
1579
|
+
function transitionsOf(dict) {
|
|
1580
|
+
return new Set([...dict.facets.values()].filter((f) => f.transitions).map((f) => f.key));
|
|
1581
|
+
}
|
|
1582
|
+
/** A state copied one level down, so replayed entries apply to a fresh object while readers keep theirs. */
|
|
1583
|
+
function copyState(st) {
|
|
1584
|
+
return {
|
|
1585
|
+
records: new MemoryRecords(st.records),
|
|
1586
|
+
edges: new Map(st.edges),
|
|
1587
|
+
bindings: new Map(st.bindings),
|
|
1588
|
+
instructions: new Map([...st.instructions].map(([k, v]) => [k, [...v]])),
|
|
1589
|
+
observations: [...st.observations],
|
|
1590
|
+
reviews: [...st.reviews],
|
|
1591
|
+
runs: new Map(st.runs),
|
|
1592
|
+
installed: [...st.installed],
|
|
1593
|
+
reads: [...st.reads],
|
|
1594
|
+
definitions: new Map(st.definitions),
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
/** What a store projects with, from the definitions in force: nothing when there is nothing to project. */
|
|
1598
|
+
function projectingOf(p) {
|
|
1599
|
+
if (!p.views.views.size && !p.dict.facets.size)
|
|
1600
|
+
return undefined;
|
|
1601
|
+
return { dict: p.dict, views: p.views, perms: p.perms };
|
|
1602
|
+
}
|
|
1603
|
+
//# sourceMappingURL=store.js.map
|