@pgxsinkit/client 0.1.51 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/adoption.d.ts +118 -0
- package/dist/adoption.d.ts.map +1 -0
- package/dist/boot-report.d.ts +54 -15
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/convergence.d.ts +2 -1
- package/dist/convergence.d.ts.map +1 -1
- package/dist/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +309 -38
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4628 -1489
- package/dist/index.js.map +36 -24
- package/dist/live-rows-sql.d.ts +1 -1
- package/dist/local-store.d.ts +16 -31
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +10 -4
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +12 -15
- package/dist/mutation.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +51 -0
- package/dist/opfs-effects.d.ts.map +1 -0
- package/dist/placement-probe.d.ts +75 -0
- package/dist/placement-probe.d.ts.map +1 -0
- package/dist/schema.d.ts +11 -16
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +77 -0
- package/dist/store-boot.d.ts.map +1 -0
- package/dist/store-lifecycle.d.ts +153 -0
- package/dist/store-lifecycle.d.ts.map +1 -0
- package/dist/store-meta.d.ts +190 -0
- package/dist/store-meta.d.ts.map +1 -0
- package/dist/store-path.d.ts +77 -7
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/shape-inbox.d.ts +1 -1
- package/dist/sync/types.d.ts +3 -3
- package/dist/testing.js.map +3 -3
- package/dist/worker/attach-sync-client.d.ts +239 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +162 -5
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/election-coordinator.d.ts +95 -0
- package/dist/worker/election-coordinator.d.ts.map +1 -0
- package/dist/worker/engine-control.d.ts +265 -0
- package/dist/worker/engine-control.d.ts.map +1 -0
- package/dist/worker/engine-router.d.ts +75 -0
- package/dist/worker/engine-router.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +32 -11
- package/dist/worker/protocol.d.ts.map +1 -1
- package/dist/worker/sw-placement.d.ts +37 -0
- package/dist/worker/sw-placement.d.ts.map +1 -0
- package/package.json +4 -3
- package/skills/core/SKILL.md +15 -8
- package/skills/operating/SKILL.md +114 -34
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1246 -118
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +9 -2
- package/src/mutation.ts +67 -49
- package/src/mutations-api.ts +3 -3
- package/src/opfs-effects.ts +160 -0
- package/src/placement-probe.ts +168 -0
- package/src/schema.ts +17 -22
- package/src/store-boot.ts +343 -0
- package/src/store-lifecycle.ts +227 -0
- package/src/store-meta.ts +459 -0
- package/src/store-path.ts +197 -22
- package/src/sync/apply.ts +227 -89
- package/src/sync/index.ts +33 -9
- package/src/sync/shape-inbox.ts +1 -1
- package/src/sync/types.ts +3 -3
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +1675 -117
- package/src/worker/define-sync-worker.ts +810 -50
- package/src/worker/election-coordinator.ts +462 -0
- package/src/worker/engine-control.ts +379 -0
- package/src/worker/engine-router.ts +355 -0
- package/src/worker/live-query-manager.ts +10 -1
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +41 -10
- package/src/worker/sw-placement.ts +64 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// Store boot resolution — assemble the boot observations and EXECUTE the classifier's verdict with real
|
|
2
|
+
// effects (ADR-0049 capability-driven engine placement, plan step 10a). `store-meta.ts` owns the PURE
|
|
3
|
+
// classifier ({@link classifyStoreBoot}, boot classification 1–7) and the meta-record IO; `store-lifecycle.ts`
|
|
4
|
+
// owns the PURE, effect-injected destruction/adoption/fresh-candidate machines; `opfs-effects.ts` owns the
|
|
5
|
+
// concrete OPFS side. This module is the WIRING that reads the meta record, observes the commitment namespace
|
|
6
|
+
// and the recordless idb fact, classifies, and then runs the destructive/candidate/adoption effects BEFORE
|
|
7
|
+
// returning the resolved `dataDir` + `storageBackend` a caller opens the store at.
|
|
8
|
+
//
|
|
9
|
+
// It never assembles a storage URL itself — every `dataDir` comes from `store-path.ts`'s
|
|
10
|
+
// {@link resolveStoreDataDir}, which stays the toolkit's only URL assembler. It carries no DOM lib dependency
|
|
11
|
+
// and takes injectable deps (meta IO, OPFS root, the recordless idb existence check) so Bun unit tests fake the
|
|
12
|
+
// whole surface with no real IndexedDB / OPFS / WASM.
|
|
13
|
+
//
|
|
14
|
+
// THE COMMITMENT BARRIER IS NOT HERE. When the verdict stands up a fresh opfs CANDIDATE (`virgin-create` /
|
|
15
|
+
// `delete-candidate-and-rebuild` with opfs access), this function returns with the candidate's record at
|
|
16
|
+
// `opfs-candidate` and its directory created but UNCOMMITTED. The strict-sync → sentinel → `opfs-committed`
|
|
17
|
+
// barrier that promotes it (invariant 3 — an uncommitted candidate is never exposed to writes) is the mint
|
|
18
|
+
// seam's post-open work, wired in plan step 10b/11. The returned {@link StoreBootResolution.verdict} tells the
|
|
19
|
+
// caller a candidate is uncommitted and needs that barrier.
|
|
20
|
+
|
|
21
|
+
import { createOpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
22
|
+
import { beginFreshCandidate, classifyAdoptionRecovery, completeAdoption, resumeDeletion } from "./store-lifecycle";
|
|
23
|
+
import {
|
|
24
|
+
classifyStoreBoot,
|
|
25
|
+
deleteStoreMetaRecord,
|
|
26
|
+
idbStoreExists as defaultIdbStoreExists,
|
|
27
|
+
META_STORE_UNAVAILABLE,
|
|
28
|
+
readStoreMetaRecord,
|
|
29
|
+
type StoreBootVerdict,
|
|
30
|
+
type StoreMetaDeps,
|
|
31
|
+
type StoreMetaPhase,
|
|
32
|
+
writeStoreMetaRecord,
|
|
33
|
+
} from "./store-meta";
|
|
34
|
+
import { resolveStoreDataDir, storeIndexedDbDatabaseName } from "./store-path";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The resolved storage backend a boot lands on. `opfs-repacked` (the elected/SW-direct opfs engine home),
|
|
38
|
+
* `idbfs` (browser, no sync-access handles), `filesystem` (Bun/Node), or `memory` (the sanctioned
|
|
39
|
+
* test/ephemeral lane). Surfaced on the BootReport as an additive field under the ADR-0034 reportVersion
|
|
40
|
+
* rule (additive fields keep `reportVersion: 1`); ADR-0049 named the backends.
|
|
41
|
+
*/
|
|
42
|
+
export type ResolvedStorageBackend = "opfs-repacked" | "idbfs" | "filesystem" | "memory";
|
|
43
|
+
|
|
44
|
+
/** The outcome of {@link resolveStoreBoot}: the URL to open the store at, its backend, and the boot verdict. */
|
|
45
|
+
export interface StoreBootResolution {
|
|
46
|
+
/** The PGlite dataDir URL, always assembled by {@link resolveStoreDataDir} (the one URL assembler). */
|
|
47
|
+
dataDir: string;
|
|
48
|
+
/** The resolved backend, for diagnostics. */
|
|
49
|
+
storageBackend: ResolvedStorageBackend;
|
|
50
|
+
/**
|
|
51
|
+
* The executed boot verdict. Absent on the passthrough backends (`memory` / `filesystem`), which have NO
|
|
52
|
+
* meta machinery. Present on every browser classification — in particular it is the signal that an opfs
|
|
53
|
+
* CANDIDATE was stood up UNCOMMITTED (`virgin-create` / `delete-candidate-and-rebuild`): the mint seam must
|
|
54
|
+
* run the commitment barrier before exposing that store to writes (plan step 10b/11).
|
|
55
|
+
*/
|
|
56
|
+
verdict?: StoreBootVerdict;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Options for {@link resolveStoreBoot}. */
|
|
60
|
+
export interface ResolveStoreBootOptions {
|
|
61
|
+
/** The placement probe's result, injected by the caller (invariant 8 — probe per boot, never cached here). */
|
|
62
|
+
hasOpfsSyncAccess: boolean;
|
|
63
|
+
/** The internal test-only memory backend override (ADR-0036), carried through from the mint seam. */
|
|
64
|
+
backendOverride?: "memory";
|
|
65
|
+
/** Injectable IO seams so Bun unit tests fake the whole browser surface. */
|
|
66
|
+
deps?: {
|
|
67
|
+
/** The store-meta IndexedDB seam (defaults to `globalThis.indexedDB` inside store-meta). */
|
|
68
|
+
meta?: StoreMetaDeps;
|
|
69
|
+
/** The OPFS root seam (defaults to `navigator.storage.getDirectory` inside opfs-effects). */
|
|
70
|
+
opfs?: OpfsEffectsDeps;
|
|
71
|
+
/** The recordless idb existence check (defaults to store-meta's non-creating {@link idbStoreExists}). */
|
|
72
|
+
idbExists?: (storePath: string) => Promise<boolean>;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Bounded re-classification budget. Only `resume-deletion` re-runs the loop: it completes the destructive
|
|
78
|
+
* lifecycle (delete sentinel → backend store → meta record), which leaves a CLEAN state whose next
|
|
79
|
+
* classification is necessarily terminal (`virgin-create` or, if an idb store somehow lingers, an idb boot).
|
|
80
|
+
* One resume is enough; the small budget is a guard against an unexpected non-terminating cycle.
|
|
81
|
+
*/
|
|
82
|
+
const MAX_DELETION_RECLASSIFY = 4;
|
|
83
|
+
|
|
84
|
+
/** The minimal structural shape of the `indexedDB.deleteDatabase` surface (no DOM lib). */
|
|
85
|
+
interface IdbDeleteSurface {
|
|
86
|
+
deleteDatabase(name: string): {
|
|
87
|
+
error?: unknown;
|
|
88
|
+
onsuccess: (() => void) | null;
|
|
89
|
+
onerror: (() => void) | null;
|
|
90
|
+
onblocked?: (() => void) | null;
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Resolve the `deleteDatabase` surface: injected meta deps first (tests), else structural off `globalThis`. */
|
|
95
|
+
function resolveDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undefined {
|
|
96
|
+
if (meta != null && "indexedDB" in meta) return meta.indexedDB as unknown as IdbDeleteSurface | undefined;
|
|
97
|
+
return (globalThis as { indexedDB?: IdbDeleteSurface }).indexedDB;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Delete-if-present the PGlite idb database for a store (`indexedDB.deleteDatabase`), backend-agnostic and
|
|
102
|
+
* idempotent: absent counts as deleted, while a real failure rejects. The database name comes
|
|
103
|
+
* ONLY from {@link storeIndexedDbDatabaseName} (store-path's sole owner of PGlite's `/pglite/` naming).
|
|
104
|
+
*/
|
|
105
|
+
function deleteIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
|
|
106
|
+
const idb = resolveDeleteSurface(meta);
|
|
107
|
+
if (idb?.deleteDatabase == null) return Promise.resolve();
|
|
108
|
+
const name = storeIndexedDbDatabaseName(storePath);
|
|
109
|
+
return new Promise<void>((resolve, reject) => {
|
|
110
|
+
let settled = false;
|
|
111
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
112
|
+
const finish = (error?: unknown) => {
|
|
113
|
+
if (settled) return;
|
|
114
|
+
settled = true;
|
|
115
|
+
if (timeout !== undefined) clearTimeout(timeout);
|
|
116
|
+
if (error === undefined) resolve();
|
|
117
|
+
else reject(error);
|
|
118
|
+
};
|
|
119
|
+
let request: {
|
|
120
|
+
error?: unknown;
|
|
121
|
+
onsuccess: (() => void) | null;
|
|
122
|
+
onerror: (() => void) | null;
|
|
123
|
+
onblocked?: (() => void) | null;
|
|
124
|
+
};
|
|
125
|
+
try {
|
|
126
|
+
request = idb.deleteDatabase(name);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
finish(error);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
request.onsuccess = () => finish();
|
|
132
|
+
request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
|
|
133
|
+
request.onblocked = () => undefined;
|
|
134
|
+
timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5_000);
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Is IndexedDB present (a browser/worker scope)? Injected meta deps win so tests select the browser branch. */
|
|
139
|
+
function resolveHasIndexedDb(meta?: StoreMetaDeps): boolean {
|
|
140
|
+
if (meta != null && "indexedDB" in meta) return meta.indexedDB != null;
|
|
141
|
+
return typeof (globalThis as { indexedDB?: unknown }).indexedDB !== "undefined";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* A probe-denied browser still has to honour an existing `deleting` phase before it may create a replacement
|
|
146
|
+
* IDB store. The old cache is already explicitly destructible; the only authority handoff required is to
|
|
147
|
+
* remove the OPFS commitment sentinel, then publish `idb-authoritative` before the replacement is exposed.
|
|
148
|
+
* Any sentinel-less directory is disposable residue and is removed before a later OPFS candidate is minted.
|
|
149
|
+
*/
|
|
150
|
+
export async function recoverDeniedBootDeletion(
|
|
151
|
+
storePath: string,
|
|
152
|
+
deps?: ResolveStoreBootOptions["deps"],
|
|
153
|
+
): Promise<boolean> {
|
|
154
|
+
const meta = deps?.meta;
|
|
155
|
+
const record = await readStoreMetaRecord(storePath, meta);
|
|
156
|
+
if (record === META_STORE_UNAVAILABLE || record?.phase !== "deleting") return false;
|
|
157
|
+
|
|
158
|
+
const effects = createOpfsEffects(storePath, deps?.opfs);
|
|
159
|
+
// If the namespace cannot be observed, sentinel deletion cannot be confirmed. Keep `deleting` authoritative
|
|
160
|
+
// and fail closed rather than publish a conflicting replacement.
|
|
161
|
+
if ((await effects.observeCommitmentNamespace()) === "unobservable") {
|
|
162
|
+
throw new Error(
|
|
163
|
+
`[pgxsinkit] cannot resume deletion for ${JSON.stringify(storePath)}: the OPFS commitment namespace is ` +
|
|
164
|
+
"unobservable in this scope, so sentinel removal cannot be confirmed.",
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
await deleteIdbDatabase(storePath, meta);
|
|
168
|
+
await effects.deleteSentinel();
|
|
169
|
+
await writeStoreMetaRecord(storePath, { phase: "idb-authoritative", updatedAt: Date.now() }, meta);
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Resolve where a store boots and finish any destructive/candidate/adoption work the verdict demands, then
|
|
175
|
+
* return the `dataDir` + `storageBackend` the mint seam opens at. The full plan boot classification 1–7,
|
|
176
|
+
* EXECUTED:
|
|
177
|
+
*
|
|
178
|
+
* - **memory override** → `memory://` passthrough, no classification (the sanctioned test/ephemeral lane has
|
|
179
|
+
* no meta machinery).
|
|
180
|
+
* - **non-browser** (no idb, no opfs handles) → `file://` passthrough, no classification (the filesystem
|
|
181
|
+
* backend has no meta machinery either).
|
|
182
|
+
* - **browser** → read the meta record ({@link readStoreMetaRecord}; {@link StoreMetaUnreadableError}
|
|
183
|
+
* propagates = fail closed, invariant 12), map {@link META_STORE_UNAVAILABLE} to a provable absence
|
|
184
|
+
* (no idb ⇒ no record and no existing idb store), observe the commitment namespace and the recordless idb fact,
|
|
185
|
+
* classify, and execute:
|
|
186
|
+
* - `resume-deletion` → complete the destructive lifecycle, then RE-CLASSIFY from the now-clean state
|
|
187
|
+
* (bounded by {@link MAX_DELETION_RECLASSIFY}).
|
|
188
|
+
* - `delete-candidate-and-rebuild` → delete the stale sentinel AND the candidate directory (a barrier-gap
|
|
189
|
+
* crash's sentinel must never survive), then rebuild per placement (the virgin path).
|
|
190
|
+
* - `repair-record-then-open-committed` → write `opfs-committed`, then open committed.
|
|
191
|
+
* - `open-committed` → open the committed opfs store (open failures are HARD at mint time; the bounded
|
|
192
|
+
* retries for transient UnknownError-class failures live in the mint seam's factory-call wrapper).
|
|
193
|
+
* - `boot-idb-authoritative` → write `idb-authoritative` FIRST when there is no record yet (recordless idb), then
|
|
194
|
+
* `idb://`.
|
|
195
|
+
* - `adoption-recovery` → {@link classifyAdoptionRecovery}: `complete-adoption` finishes the barrier
|
|
196
|
+
* (`opfs-committed` + delete the idb predecessor) → `opfs://`; `teardown-and-restart` tears the candidate
|
|
197
|
+
* down, sets `idb-authoritative`, and boots `idb://` (adoption re-runs later, plan step 11).
|
|
198
|
+
* - `virgin-create` → with opfs access, {@link beginFreshCandidate} (record `opfs-candidate` BEFORE the
|
|
199
|
+
* directory) → `opfs://` UNCOMMITTED (barrier is step 10b/11); without opfs access, `idb-authoritative` →
|
|
200
|
+
* `idb://`.
|
|
201
|
+
*/
|
|
202
|
+
export async function resolveStoreBoot(storePath: string, opts: ResolveStoreBootOptions): Promise<StoreBootResolution> {
|
|
203
|
+
const meta = opts.deps?.meta;
|
|
204
|
+
|
|
205
|
+
// Memory override: the sanctioned test/ephemeral lane. No meta machinery — a memory store lives only for the
|
|
206
|
+
// instance about to be created (documented in store-path's `storeTargetExists`).
|
|
207
|
+
if (opts.backendOverride === "memory") {
|
|
208
|
+
return { dataDir: resolveStoreDataDir(storePath, "memory"), storageBackend: "memory" };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Non-browser (no IndexedDB, no opfs handles): the filesystem backend has no meta machinery. Passthrough.
|
|
212
|
+
const hasIndexedDb = resolveHasIndexedDb(meta);
|
|
213
|
+
if (!hasIndexedDb && !opts.hasOpfsSyncAccess) {
|
|
214
|
+
return {
|
|
215
|
+
dataDir: resolveStoreDataDir(storePath, undefined, { hasIndexedDb: false }),
|
|
216
|
+
storageBackend: "filesystem",
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const effects = createOpfsEffects(storePath, opts.deps?.opfs);
|
|
221
|
+
const idbExists = opts.deps?.idbExists ?? ((sp: string) => defaultIdbStoreExists(sp, meta));
|
|
222
|
+
|
|
223
|
+
// The two browser dataDir forms — always via store-path (the one URL assembler). A COMMITTED opfs store
|
|
224
|
+
// opens on opfs regardless of THIS boot's probe result (the committed store is opfs by construction); an
|
|
225
|
+
// open failure in a scope without handles is a hard mint-time failure, not a re-derivation.
|
|
226
|
+
const opfsDataDir = resolveStoreDataDir(storePath, undefined, { hasIndexedDb: true, hasOpfsSyncAccess: true });
|
|
227
|
+
const idbDataDir = resolveStoreDataDir(storePath, undefined, { hasIndexedDb: true, hasOpfsSyncAccess: false });
|
|
228
|
+
|
|
229
|
+
const writePhase = (phase: StoreMetaPhase): Promise<void> =>
|
|
230
|
+
writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, meta);
|
|
231
|
+
|
|
232
|
+
// The virgin creation path — reused by `virgin-create` and by `delete-candidate-and-rebuild`'s rebuild.
|
|
233
|
+
const finishVirginCreate = async (verdict: StoreBootVerdict): Promise<StoreBootResolution> => {
|
|
234
|
+
if (opts.hasOpfsSyncAccess) {
|
|
235
|
+
// Record-first authority (invariant 12): the `opfs-candidate` record is written BEFORE the directory, so
|
|
236
|
+
// a crash between them leaves a candidate a later boot deletes and rebuilds. Returned UNCOMMITTED — the
|
|
237
|
+
// commitment barrier is the mint seam's post-open work (plan step 10b/11).
|
|
238
|
+
await beginFreshCandidate({
|
|
239
|
+
writeCandidateRecord: () => writePhase("opfs-candidate"),
|
|
240
|
+
createStoreDirectory: async () => {
|
|
241
|
+
await effects.getStoreDirectoryHandle();
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
|
|
245
|
+
}
|
|
246
|
+
// No opfs handles in this scope: create an idb store instead (classification 7). Record first.
|
|
247
|
+
await writePhase("idb-authoritative");
|
|
248
|
+
return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
// Only `resume-deletion` loops; every other verdict returns. Deletion → clean state → a terminal verdict.
|
|
252
|
+
for (let iteration = 0; iteration < MAX_DELETION_RECLASSIFY; iteration += 1) {
|
|
253
|
+
// A failed meta read is an ERROR, never "no record" (invariant 12): StoreMetaUnreadableError propagates
|
|
254
|
+
// here and fails the boot closed.
|
|
255
|
+
const metaResult = await readStoreMetaRecord(storePath, meta);
|
|
256
|
+
// META_STORE_UNAVAILABLE means IndexedDB is entirely absent — a no-idb scope cannot hold a record, so
|
|
257
|
+
// absence is PROVABLE (record undefined) and there can be no existing idb store either (idbStoreExists
|
|
258
|
+
// false). Faithful to store-meta's documented mapping.
|
|
259
|
+
const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
|
|
260
|
+
const record = metaUnavailable ? undefined : metaResult;
|
|
261
|
+
const opfsObservation = await effects.observeCommitmentNamespace();
|
|
262
|
+
const idbPresent = metaUnavailable ? false : await idbExists(storePath);
|
|
263
|
+
const verdict = classifyStoreBoot({ record, opfs: opfsObservation, idbStoreExists: idbPresent });
|
|
264
|
+
|
|
265
|
+
switch (verdict.action) {
|
|
266
|
+
case "resume-deletion":
|
|
267
|
+
// Complete the destructive lifecycle. `deleteBackendStore` is backend-agnostic: a `deleting` record
|
|
268
|
+
// does not say which backend, so we delete-if-present BOTH the opfs directory and the idb database
|
|
269
|
+
// (idempotent). Then re-classify from the now-clean state.
|
|
270
|
+
await resumeDeletion({
|
|
271
|
+
setPhase: writePhase,
|
|
272
|
+
deleteSentinel: () => effects.deleteSentinel(),
|
|
273
|
+
deleteBackendStore: async () => {
|
|
274
|
+
await effects.deleteStoreDirectory();
|
|
275
|
+
await deleteIdbDatabase(storePath, meta);
|
|
276
|
+
},
|
|
277
|
+
deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta),
|
|
278
|
+
});
|
|
279
|
+
continue;
|
|
280
|
+
|
|
281
|
+
case "delete-candidate-and-rebuild":
|
|
282
|
+
// An unexposed candidate has no authority. The stale sentinel MUST go alongside the directory — a
|
|
283
|
+
// barrier-gap crash's published sentinel must never survive into the rebuilt candidate's lifetime
|
|
284
|
+
// (plan fresh/restore crash table). Then rebuild per placement.
|
|
285
|
+
await effects.deleteSentinel();
|
|
286
|
+
await effects.deleteStoreDirectory();
|
|
287
|
+
return finishVirginCreate(verdict);
|
|
288
|
+
|
|
289
|
+
case "repair-record-then-open-committed":
|
|
290
|
+
// Sentinel present without a record (record loss): the sentinel is committed authority. Repair the
|
|
291
|
+
// record, then open committed.
|
|
292
|
+
await writePhase("opfs-committed");
|
|
293
|
+
if (idbPresent) await deleteIdbDatabase(storePath, meta);
|
|
294
|
+
return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
|
|
295
|
+
|
|
296
|
+
case "open-committed":
|
|
297
|
+
// Adoption may have committed before its predecessor deletion completed. Finish that cleanup
|
|
298
|
+
// idempotently before publishing the committed store to this boot.
|
|
299
|
+
if (idbPresent) await deleteIdbDatabase(storePath, meta);
|
|
300
|
+
return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
|
|
301
|
+
|
|
302
|
+
case "boot-idb-authoritative":
|
|
303
|
+
// Recordless idb store (no record yet, an existing idb store): write the record FIRST (invariant 14). A
|
|
304
|
+
// present `idb-authoritative` record is left as-is.
|
|
305
|
+
if (record == null) await writePhase("idb-authoritative");
|
|
306
|
+
return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
|
|
307
|
+
|
|
308
|
+
case "adoption-recovery": {
|
|
309
|
+
// Disambiguate purely from the sentinel (plan adoption crash rows). "unobservable" ⇒ no sentinel.
|
|
310
|
+
const sentinelPresent = opfsObservation !== "unobservable" && opfsObservation.sentinelPresent;
|
|
311
|
+
const recovery = classifyAdoptionRecovery({ sentinelPresent });
|
|
312
|
+
if (recovery.action === "complete-adoption") {
|
|
313
|
+
// The barrier had published before the crash: set `opfs-committed`, delete the idb predecessor.
|
|
314
|
+
await completeAdoption({
|
|
315
|
+
setPhase: writePhase,
|
|
316
|
+
deleteIdbPredecessor: () => deleteIdbDatabase(storePath, meta),
|
|
317
|
+
});
|
|
318
|
+
return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
|
|
319
|
+
}
|
|
320
|
+
// Nothing committed: tear the candidate down and fall back to the still-authoritative idb store.
|
|
321
|
+
// Adoption re-runs later from step 1 (plan step 11).
|
|
322
|
+
await effects.deleteSentinel();
|
|
323
|
+
await effects.deleteStoreDirectory();
|
|
324
|
+
await writePhase("idb-authoritative");
|
|
325
|
+
return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
case "virgin-create":
|
|
329
|
+
return finishVirginCreate(verdict);
|
|
330
|
+
|
|
331
|
+
default: {
|
|
332
|
+
// Exhaustiveness guard: a new verdict MUST be wired explicitly, never silently ignored.
|
|
333
|
+
const unreachable: never = verdict;
|
|
334
|
+
throw new Error(`[pgxsinkit] unhandled store boot verdict: ${JSON.stringify(unreachable)}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Only reachable if deletion never leaves a clean, terminal state — a guard against a non-terminating cycle.
|
|
340
|
+
throw new Error(
|
|
341
|
+
"[pgxsinkit] store boot did not settle after resuming a deletion (bounded re-classification exhausted).",
|
|
342
|
+
);
|
|
343
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Store lifecycle machines — ADR-0049 (capability-driven engine placement) step 3. The fresh/restore
|
|
2
|
+
// COMMITMENT BARRIER (decision 7), the ADOPTION recovery + completion ordering (decision 7's adoption
|
|
3
|
+
// sequence), and the DESTRUCTIVE lifecycle (decision 8) as PURE, EFFECT-DRIVEN modules over the plan's three
|
|
4
|
+
// crash tables. CONTEXT § "Language — engine placement" terms used exactly: "Commitment marker",
|
|
5
|
+
// "Adoption gate", "Adoption-bootstrap gate", "Drain predicate", "Destructive lifecycle".
|
|
6
|
+
//
|
|
7
|
+
// EFFECT-INJECTED BY CONSTRUCTION. None of these machines touches IndexedDB, OPFS, or PGlite: every side
|
|
8
|
+
// effect is a method on an injected effects object. Plan step 10 wires the REAL effects (the meta record IO
|
|
9
|
+
// from `store-meta.ts`, the OPFS namespace builders from `store-path.ts`, the live engine's `strictSync()`);
|
|
10
|
+
// unit tests inject fakes and simulate a crash by making one effect throw, then re-run the resume path from
|
|
11
|
+
// the observed state. Because of that, EVERY step must be IDEMPOTENT under resume — each effect's contract
|
|
12
|
+
// below states the idempotency the wirer must provide (delete-if-present, create-if-absent, set-phase-again).
|
|
13
|
+
//
|
|
14
|
+
// The three PROVENANCE GATES themselves (fresh = successful local initialization/recovery; restore =
|
|
15
|
+
// successful backup load + restore recovery; adoption = authorized online reconstruction of the eager
|
|
16
|
+
// Consistency groups — the "Adoption-bootstrap gate") are CALLER facts, not modelled here: the caller invokes
|
|
17
|
+
// the barrier only AFTER its provenance gate has passed. This module owns the shared data-before-authority
|
|
18
|
+
// SEQUENCE, not the gates that authorize entering it.
|
|
19
|
+
|
|
20
|
+
import type { StoreMetaPhase } from "./store-meta";
|
|
21
|
+
|
|
22
|
+
// =========================================================================================================
|
|
23
|
+
// A. The shared commitment barrier (ADR-0049 decision 7 — one strict data-before-authority sequence)
|
|
24
|
+
// =========================================================================================================
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The effects the shared commitment barrier drives, in the one order it always runs them. The barrier is the
|
|
28
|
+
* SINGLE data-before-authority sequence every provenance shares (fresh, restore, adoption): the caller has
|
|
29
|
+
* already passed its provenance gate; the barrier makes the data durable, THEN publishes authority.
|
|
30
|
+
*/
|
|
31
|
+
export interface CommitmentBarrierEffects {
|
|
32
|
+
/**
|
|
33
|
+
* The explicit `strictSync()` on the live engine. MUST resolve ONLY when the sync returned AND VFS health
|
|
34
|
+
* is good (data-before-authority — required even under relaxed runtime durability, ADR-0049 D7/D9).
|
|
35
|
+
* Throwing ABORTS the barrier: nothing downstream runs, so nothing publishes. No idempotency requirement —
|
|
36
|
+
* it is the first step and is never resumed past.
|
|
37
|
+
*/
|
|
38
|
+
strictSyncReturns(): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Publish the commitment sentinel (`pgxsinkit/commitments/<identity>`, the "Commitment marker"). Published
|
|
41
|
+
* BEFORE the record's committed phase, so a crash between the two reads as committed off the sentinel
|
|
42
|
+
* (store-meta's `repair-record-then-open-committed`). Idempotency required: CREATE-IF-ABSENT (a resume that
|
|
43
|
+
* finds the sentinel already there is a no-op success).
|
|
44
|
+
*/
|
|
45
|
+
publishSentinel(): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Advance the store meta record phase. The barrier only ever calls it with `"opfs-committed"`. Idempotency
|
|
48
|
+
* required: SET-PHASE-AGAIN is a no-op success (writing the same phase twice is harmless).
|
|
49
|
+
*/
|
|
50
|
+
setPhase(phase: StoreMetaPhase): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Run the shared commitment barrier (ADR-0049 decision 7): `strictSync()` returns with VFS health good →
|
|
55
|
+
* publish the sentinel → set the `opfs-committed` phase. The caller invokes this ONLY after its provenance
|
|
56
|
+
* gate has passed (fresh: local init/recovery; restore: backup load + restore recovery; adoption: the
|
|
57
|
+
* Adoption-bootstrap gate). Any throw propagates and later steps NEVER run — so a failed barrier publishes
|
|
58
|
+
* NOTHING and an uncommitted candidate is never granted authority (invariant 3). After it resolves the caller
|
|
59
|
+
* exposes the store (fresh/restore) or deletes the predecessor (adoption).
|
|
60
|
+
*/
|
|
61
|
+
export async function runCommitmentBarrier(effects: CommitmentBarrierEffects): Promise<void> {
|
|
62
|
+
await effects.strictSyncReturns();
|
|
63
|
+
await effects.publishSentinel();
|
|
64
|
+
await effects.setPhase("opfs-committed");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// =========================================================================================================
|
|
68
|
+
// E. Fresh/restore candidate flow helper (record-first — invariant 12)
|
|
69
|
+
// =========================================================================================================
|
|
70
|
+
// (Declared here, before the barrier's downstream machines, because it is the barrier's UPSTREAM half: it
|
|
71
|
+
// builds the uncommitted candidate the barrier later commits.)
|
|
72
|
+
|
|
73
|
+
/** The effects that stand up a fresh/restore candidate before the commitment barrier commits it. */
|
|
74
|
+
export interface FreshCandidateEffects {
|
|
75
|
+
/**
|
|
76
|
+
* Write the store meta record at `{ phase: "opfs-candidate" }`. Written FIRST — the record is the first-use
|
|
77
|
+
* authority (invariant 12), so a crash after this but before the directory leaves a state the boot
|
|
78
|
+
* classifier maps to `delete-candidate-and-rebuild` (an unexposed candidate has no authority). Idempotency
|
|
79
|
+
* required: overwrite-if-present.
|
|
80
|
+
*/
|
|
81
|
+
writeCandidateRecord(): Promise<void>;
|
|
82
|
+
/** Create the store's OPFS directory (`pgxsinkit/stores/<identity>`). Idempotency required: create-if-absent. */
|
|
83
|
+
createStoreDirectory(): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Begin a fresh/restore candidate: write the `opfs-candidate` meta record BEFORE creating the store
|
|
88
|
+
* directory. Order is load-bearing (record-first authority, invariant 12) — a crash between the two leaves an
|
|
89
|
+
* `opfs-candidate` record whose directory may be absent, which the boot classifier deletes and rebuilds
|
|
90
|
+
* fresh. The forward path from here is the shared {@link runCommitmentBarrier} (after the caller's provenance
|
|
91
|
+
* gate). Full fresh/restore wiring is plan step 10.
|
|
92
|
+
*/
|
|
93
|
+
export async function beginFreshCandidate(effects: FreshCandidateEffects): Promise<void> {
|
|
94
|
+
await effects.writeCandidateRecord();
|
|
95
|
+
await effects.createStoreDirectory();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// =========================================================================================================
|
|
99
|
+
// B. Destruction machine (ADR-0049 decision 8; plan "Destructive lifecycle")
|
|
100
|
+
// =========================================================================================================
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The effects the destructive lifecycle drives. ONE backend-agnostic machine: {@link deleteBackendStore} is a
|
|
104
|
+
* single effect the wirer (plan step 10) branches by backend (OPFS store directory OR the idb database) — the
|
|
105
|
+
* machine never knows which. The supervisor-level REFUSALS that guard this machine (owed mutations unless
|
|
106
|
+
* `force`; other tabs still holding claims — close the peers first) live OUTSIDE it, in the coordinator/
|
|
107
|
+
* communication-centre supervisor that survives engine shutdown (ADR-0049 D8, plan step 10). This module owns
|
|
108
|
+
* only the resumable delete SEQUENCE once destruction is authorized and the engine is quiesced/closed.
|
|
109
|
+
*/
|
|
110
|
+
export interface DestructionEffects {
|
|
111
|
+
/** Advance the meta record phase; the machine only ever calls it with `"deleting"`. Idempotency: set-again. */
|
|
112
|
+
setPhase(phase: StoreMetaPhase): Promise<void>;
|
|
113
|
+
/** Delete the commitment sentinel. Idempotency required: ABSENT COUNTS AS DELETED (delete-if-present). */
|
|
114
|
+
deleteSentinel(): Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* Delete the backend store — the OPFS store directory OR the idb database, chosen by the wirer; the machine
|
|
117
|
+
* is backend-agnostic. Idempotency required: absent counts as deleted (delete-if-present).
|
|
118
|
+
*/
|
|
119
|
+
deleteBackendStore(): Promise<void>;
|
|
120
|
+
/** Delete the store meta record — the terminal step. Idempotency required: absent counts as deleted. */
|
|
121
|
+
deleteMetaRecord(): Promise<void>;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The resume path of the destructive lifecycle, entered from an observed `deleting` phase (a boot that finds
|
|
126
|
+
* `deleting` completes the deletion first — invariant 13): delete sentinel → delete backend store → delete
|
|
127
|
+
* meta record. Every step is idempotent, so a crash at any boundary and a re-run from the top completes
|
|
128
|
+
* cleanly (plan's destruction crash table — each row is `resume-deletion` until the record is gone).
|
|
129
|
+
*/
|
|
130
|
+
export async function resumeDeletion(effects: DestructionEffects): Promise<void> {
|
|
131
|
+
await effects.deleteSentinel();
|
|
132
|
+
await effects.deleteBackendStore();
|
|
133
|
+
await effects.deleteMetaRecord();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Run the full destructive lifecycle from an already-quiesced engine (ADR-0049 D8): record the `deleting`
|
|
138
|
+
* phase (highest-precedence commitment that survives a crash), then {@link resumeDeletion}. The upstream steps
|
|
139
|
+
* (refuse owed mutations unless `force`, stop admissions, quiesce/close the engine) and the supervision that
|
|
140
|
+
* lets the initiating `destroy()` resolve from a context surviving engine shutdown are plan step 10 — this
|
|
141
|
+
* machine begins once destruction is authorized and the engine is down.
|
|
142
|
+
*/
|
|
143
|
+
export async function runDestruction(effects: DestructionEffects): Promise<void> {
|
|
144
|
+
await effects.setPhase("deleting");
|
|
145
|
+
await resumeDeletion(effects);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// =========================================================================================================
|
|
149
|
+
// C. Adoption recovery (pure verdict over the plan's adoption crash rows) + completion executor
|
|
150
|
+
// =========================================================================================================
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The recovery verdict for a store found mid-adoption (phase `adopting`) at boot. Disambiguated purely by
|
|
154
|
+
* whether the commitment sentinel was published before the crash (plan's adoption crash table).
|
|
155
|
+
*/
|
|
156
|
+
export type AdoptionRecoveryVerdict =
|
|
157
|
+
// Sentinel present: the barrier committed before the crash — set `opfs-committed`, delete the idb
|
|
158
|
+
// predecessor, done ({@link completeAdoption}).
|
|
159
|
+
| { action: "complete-adoption" }
|
|
160
|
+
// No sentinel: nothing committed — tear the candidate down and re-run adoption from step 1 (the idb store
|
|
161
|
+
// is still authoritative, so no write is stranded).
|
|
162
|
+
| { action: "teardown-and-restart" };
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Classify an interrupted adoption purely from the observed sentinel presence (ADR-0049 D7 adoption sequence;
|
|
166
|
+
* plan adoption crash rows). Sentinel present → `complete-adoption` (the commitment barrier had published,
|
|
167
|
+
* so the opfs store is committed); sentinel absent → `teardown-and-restart` (idb remains authoritative — the
|
|
168
|
+
* predecessor is deleted ONLY after commitment, so nothing is lost). This owns RECOVERY only; the full
|
|
169
|
+
* forward adoption transition (pre-expose idb boot, the drain predicate, strict-sync close of the
|
|
170
|
+
* never-exposed engine, phase `adopting`, server bootstrap through the Adoption-bootstrap gate) is plan
|
|
171
|
+
* step 11's wiring.
|
|
172
|
+
*/
|
|
173
|
+
export function classifyAdoptionRecovery(obs: { sentinelPresent: boolean }): AdoptionRecoveryVerdict {
|
|
174
|
+
return obs.sentinelPresent ? { action: "complete-adoption" } : { action: "teardown-and-restart" };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The effects the adoption completion executor drives (the `complete-adoption` verdict). */
|
|
178
|
+
export interface AdoptionCompletionEffects {
|
|
179
|
+
/** Advance the meta record phase; the executor only ever calls it with `"opfs-committed"`. Idempotency: set-again. */
|
|
180
|
+
setPhase(phase: StoreMetaPhase): Promise<void>;
|
|
181
|
+
/** Delete the idb predecessor now the opfs store is committed. Idempotency required: absent counts as deleted. */
|
|
182
|
+
deleteIdbPredecessor(): Promise<void>;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Complete an adoption whose commitment barrier already published the sentinel (the `complete-adoption`
|
|
187
|
+
* verdict): set `opfs-committed`, then delete the idb predecessor. Ordered committed-flag-BEFORE-deletion so
|
|
188
|
+
* a crash between them re-enters as `opfs-committed` with the idb store lingering — the committed-boot path
|
|
189
|
+
* idempotently finishes the deletion (plan adoption crash row 3). The predecessor is deleted ONLY after
|
|
190
|
+
* commitment, never before (invariant 4 — no silent local-only data loss).
|
|
191
|
+
*/
|
|
192
|
+
export async function completeAdoption(effects: AdoptionCompletionEffects): Promise<void> {
|
|
193
|
+
await effects.setPhase("opfs-committed");
|
|
194
|
+
await effects.deleteIdbPredecessor();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// =========================================================================================================
|
|
198
|
+
// D. Drain predicate (canonical journal status terms — CONTEXT "Drain predicate")
|
|
199
|
+
// =========================================================================================================
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The per-status row counts of the Mutation journal the drain predicate reads. Names + semantics mirror the
|
|
203
|
+
* canonical journal status machine in `packages/contracts/src/mutation.ts` (`mutationStatusSchema`), but this
|
|
204
|
+
* takes COUNTS as plain input rather than coupling to the journal schema — the predicate is pure and
|
|
205
|
+
* unit-testable without a journal.
|
|
206
|
+
*/
|
|
207
|
+
export interface JournalStatusCounts {
|
|
208
|
+
pending: number;
|
|
209
|
+
sending: number;
|
|
210
|
+
acked: number;
|
|
211
|
+
failed: number;
|
|
212
|
+
quarantined: number;
|
|
213
|
+
conflicted: number;
|
|
214
|
+
rejected: number;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The DRAIN PREDICATE (CONTEXT § "Drain predicate"; ADR-0049 D7): the idb store owes nothing to the server
|
|
219
|
+
* iff no row is `pending`, `sending`, `failed`, `quarantined`, or `conflicted`. `acked` and `rejected` rows
|
|
220
|
+
* are PERMITTED — both are settled (rejection is terminal, ADR-0022). Evaluated PRE-EXPOSE in the adoption
|
|
221
|
+
* transition so no mutation can race it. Echo-landing is deliberately NOT required (the opfs successor is
|
|
222
|
+
* rebuilt from the server, which already holds every acked write) — this is weaker than Data export's
|
|
223
|
+
* "drained", which reads local tables.
|
|
224
|
+
*/
|
|
225
|
+
export function journalOwesNothing(counts: JournalStatusCounts): boolean {
|
|
226
|
+
return counts.pending + counts.sending + counts.failed + counts.quarantined + counts.conflicted === 0;
|
|
227
|
+
}
|