@pgxsinkit/client 0.1.53 → 0.2.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 +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/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +286 -51
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4795 -1519
- package/dist/index.js.map +34 -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 +4 -4
- package/dist/mutation.d.ts +18 -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.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 +300 -16
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +164 -23
- 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 +266 -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/protocol.d.ts +47 -31
- 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 -12
- package/skills/operating/SKILL.md +142 -46
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1157 -115
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +2 -2
- package/src/mutation.ts +115 -53
- 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 +63 -63
- package/src/sync/index.ts +2 -2
- 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 +1753 -102
- package/src/worker/define-sync-worker.ts +1034 -71
- 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 +4 -1
- package/src/worker/protocol.ts +46 -16
- package/src/worker/sw-placement.ts +64 -0
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PGlite, type QueryOptions, type Results } from "@electric-sql/pglite";
|
|
1
|
+
import { PGlite, type PGliteOptions, type QueryOptions, type Results } from "@electric-sql/pglite";
|
|
2
2
|
import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
|
|
3
3
|
import type { PgliteDatabase } from "drizzle-orm/pglite";
|
|
4
4
|
import { drizzle } from "drizzle-orm/pglite";
|
|
@@ -15,13 +15,34 @@ import type {
|
|
|
15
15
|
SyncRuntimeStatus,
|
|
16
16
|
SyncTableCreateInput,
|
|
17
17
|
SyncTableEntry,
|
|
18
|
+
SyncStorageDeclaration,
|
|
18
19
|
SyncTableName,
|
|
19
20
|
SyncTableRegistry,
|
|
20
21
|
SyncTableUpdateInput,
|
|
22
|
+
StorageDurability,
|
|
21
23
|
WriteMode,
|
|
22
24
|
} from "@pgxsinkit/contracts";
|
|
23
|
-
import {
|
|
25
|
+
import {
|
|
26
|
+
fingerprintRegistry,
|
|
27
|
+
getSyncRegistrySchema,
|
|
28
|
+
getSyncRegistryStorage,
|
|
29
|
+
isClaimsDependentRowFilter,
|
|
30
|
+
resolveStorageDeclaration,
|
|
31
|
+
} from "@pgxsinkit/contracts";
|
|
32
|
+
// Type-only import (erased at runtime): the opfs-repacked factory's option/return types for the `opfs://`
|
|
33
|
+
// branch. The factory VALUE is loaded lazily via dynamic `import()` inside that branch so a Bun unit test
|
|
34
|
+
// mocking `@electric-sql/pglite` never evaluates the factory's `class ... extends PGlite` module top level.
|
|
35
|
+
import type { CreateOpfsRepackedPGliteOptions, OpfsRepackedPGlite } from "@pgxsinkit/pglite-opfs-repacked";
|
|
24
36
|
|
|
37
|
+
import {
|
|
38
|
+
type AdoptionDeclaration,
|
|
39
|
+
type AdoptionEffects,
|
|
40
|
+
adoptionEligible,
|
|
41
|
+
type AdoptionOutcome,
|
|
42
|
+
buildAdoptionEffects,
|
|
43
|
+
runAdoptionTransition,
|
|
44
|
+
runManualAdoption,
|
|
45
|
+
} from "./adoption";
|
|
25
46
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
26
47
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
27
48
|
import { syncDebug, timeAsync } from "./debug";
|
|
@@ -54,6 +75,7 @@ import {
|
|
|
54
75
|
type WriteUnit,
|
|
55
76
|
} from "./mutation";
|
|
56
77
|
import { createMutationsApi, type MutationsApi } from "./mutations-api";
|
|
78
|
+
import { createOpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
57
79
|
import {
|
|
58
80
|
buildDataExportCloneCleanupSql,
|
|
59
81
|
buildDataExportEnumHeaderSql,
|
|
@@ -68,6 +90,20 @@ import {
|
|
|
68
90
|
generateLocalSchemaSql,
|
|
69
91
|
} from "./schema";
|
|
70
92
|
import { startConfiguredSync } from "./shape-sync";
|
|
93
|
+
import {
|
|
94
|
+
recoverDeniedBootDeletion,
|
|
95
|
+
resolveStoreBoot,
|
|
96
|
+
type ResolvedStorageBackend,
|
|
97
|
+
type StoreBootResolution,
|
|
98
|
+
} from "./store-boot";
|
|
99
|
+
import { runCommitmentBarrier } from "./store-lifecycle";
|
|
100
|
+
import {
|
|
101
|
+
idbStoreExists as defaultIdbStoreExists,
|
|
102
|
+
type StoreBootVerdict,
|
|
103
|
+
type StoreMetaDeps,
|
|
104
|
+
type StoreMetaPhase,
|
|
105
|
+
writeStoreMetaRecord,
|
|
106
|
+
} from "./store-meta";
|
|
71
107
|
import {
|
|
72
108
|
classifyNonPersistentDataDir,
|
|
73
109
|
NonPersistentStoreError,
|
|
@@ -75,6 +111,7 @@ import {
|
|
|
75
111
|
readTestStoreMarker,
|
|
76
112
|
resolveStoreDataDir,
|
|
77
113
|
RestoreTargetExistsError,
|
|
114
|
+
storeIndexedDbDatabaseName,
|
|
78
115
|
storeTargetExists,
|
|
79
116
|
type StorePathInput,
|
|
80
117
|
} from "./store-path";
|
|
@@ -123,7 +160,40 @@ export {
|
|
|
123
160
|
type StoreExportOptions,
|
|
124
161
|
type StoreExportResult,
|
|
125
162
|
} from "./export-store";
|
|
163
|
+
export {
|
|
164
|
+
type AdoptionDeclaration,
|
|
165
|
+
type AdoptionEffects,
|
|
166
|
+
adoptionEligible,
|
|
167
|
+
type AdoptionOutcome,
|
|
168
|
+
runAdoptionTransition,
|
|
169
|
+
runManualAdoption,
|
|
170
|
+
} from "./adoption";
|
|
126
171
|
export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
|
|
172
|
+
export {
|
|
173
|
+
destroyStoreArtifacts,
|
|
174
|
+
type ElectedEngineWorker,
|
|
175
|
+
ElectedEngineUnconstructibleError,
|
|
176
|
+
quiesceStoreWorker,
|
|
177
|
+
StoreDestroyRefusedError,
|
|
178
|
+
type StoreDestructionRetryOptions,
|
|
179
|
+
type StoreWorkerQuiesceOptions,
|
|
180
|
+
type StoreWorkerQuiesceOutcome,
|
|
181
|
+
wrapEngineWorker,
|
|
182
|
+
} from "./worker/attach-sync-client";
|
|
183
|
+
export {
|
|
184
|
+
ENGINE_RELOCATED_CODE,
|
|
185
|
+
EngineRelocatedError,
|
|
186
|
+
type EngineRelocatedOutcome,
|
|
187
|
+
type ExecutionLimitConfig,
|
|
188
|
+
ExecutionLimitMismatchError,
|
|
189
|
+
} from "./worker/engine-control";
|
|
190
|
+
export { createOpfsEffects, type OpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
191
|
+
export {
|
|
192
|
+
resolveStoreBoot,
|
|
193
|
+
type ResolvedStorageBackend,
|
|
194
|
+
type ResolveStoreBootOptions,
|
|
195
|
+
type StoreBootResolution,
|
|
196
|
+
} from "./store-boot";
|
|
127
197
|
export {
|
|
128
198
|
InvalidStorePathError,
|
|
129
199
|
NonPersistentStoreError,
|
|
@@ -169,6 +239,7 @@ export {
|
|
|
169
239
|
type BridgeEvent,
|
|
170
240
|
type BridgeMessageType,
|
|
171
241
|
type BridgePort,
|
|
242
|
+
type BridgeTransferable,
|
|
172
243
|
encodeEnvelope,
|
|
173
244
|
type ExportArtefactWire,
|
|
174
245
|
identityCodec,
|
|
@@ -278,20 +349,18 @@ export interface CreateClientPGliteOptions {
|
|
|
278
349
|
*/
|
|
279
350
|
bootAssets?: Promise<PgliteBootAssets>;
|
|
280
351
|
/**
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
* (ADR-0036), so relaxing their flush TIMING — not their persistence — costs nothing durable; consumer
|
|
292
|
-
* local-only tables carry whatever risk the consumer accepts. Opt out with `relaxedDurability: false`.
|
|
352
|
+
* @internal Toolkit-internal durability carrier (ADR-0047), NOT a public per-open knob. Durability is
|
|
353
|
+
* registry-declared: {@link createSyncClient} resolves `storage.durability ?? "relaxed"` off its registry
|
|
354
|
+
* and threads the resolved mode in here — the ONE resolution point — for every mint it funnels through this
|
|
355
|
+
* factory (its own boot, the worker provision/spare mint, the pre-expose idb drain read). Defaults to
|
|
356
|
+
* `"relaxed"` when absent and is stamped onto the `boot pglite.create` rail (ADR-0047 D3). On idb, relaxed
|
|
357
|
+
* returns before the whole-datadir snapshot flush and schedules it asynchronously; strict keeps that
|
|
358
|
+
* synchronous snapshot (~100–200ms per statement). On OPFS-repacked the package factory keeps PGlite on its
|
|
359
|
+
* awaited host path: relaxed routine sync asserts health without an ordinary physical flush, while strict
|
|
360
|
+
* flushes arena data before metadata. Initialization, activation, and open-state close retain strict
|
|
361
|
+
* ordering in both OPFS modes.
|
|
293
362
|
*/
|
|
294
|
-
|
|
363
|
+
durability?: StorageDurability;
|
|
295
364
|
/**
|
|
296
365
|
* @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
|
|
297
366
|
* scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
|
|
@@ -306,6 +375,73 @@ export interface CreateClientPGliteOptions {
|
|
|
306
375
|
* freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.
|
|
307
376
|
*/
|
|
308
377
|
restoreFrom?: File | Blob;
|
|
378
|
+
/**
|
|
379
|
+
* @internal ADR-0049 (capability-driven engine placement) step 10a: the placement probe's result, threaded
|
|
380
|
+
* from the caller (the boot path resolves it via {@link resolveStoreBoot}). Default `false` keeps today's
|
|
381
|
+
* behavior BYTE-IDENTICAL — the store resolves to `idb://` / `file://` / `memory://` exactly as before.
|
|
382
|
+
* `true` resolves the browser store to `opfs://`, which routes to the opfs-repacked factory below.
|
|
383
|
+
*/
|
|
384
|
+
hasOpfsSyncAccess?: boolean;
|
|
385
|
+
/**
|
|
386
|
+
* @internal ADR-0049 step 10a: the opfs-repacked factory + store-directory seam, injectable so Bun unit
|
|
387
|
+
* tests exercise the `opfs://` branch WITHOUT loading real WASM/OPFS. In production both default to the real
|
|
388
|
+
* implementations (`createOpfsRepackedPGlite` via a lazy `import()`, and the OPFS effects' store directory
|
|
389
|
+
* handle). Never consumer-facing.
|
|
390
|
+
*/
|
|
391
|
+
pgliteFactories?: {
|
|
392
|
+
/** The opfs-repacked PGlite factory; defaults to a lazily-imported `createOpfsRepackedPGlite`. */
|
|
393
|
+
createOpfsRepacked?: (options: CreateOpfsRepackedPGliteOptions) => Promise<OpfsRepackedPGlite>;
|
|
394
|
+
/** The create-if-absent store directory handle for the factory; defaults to the real OPFS effects. */
|
|
395
|
+
getStoreDirectoryHandle?: () => Promise<unknown>;
|
|
396
|
+
/** Backoff between bounded open retries (ms); defaults to a small real delay. Tests pass `0`. */
|
|
397
|
+
retryDelayMs?: number;
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Bounded open-retry budget for the opfs-repacked factory. Covers BOTH transient UnknownError-class failures AND
|
|
403
|
+
* the ADR-0049 fault-matrix "VFS ownership-lock release lag → successor open retries on contention until clear,
|
|
404
|
+
* bounded, then boot failure": when a leader engine is DELIBERATELY terminated (execution-limit verdict) while
|
|
405
|
+
* BUSY, `worker.terminate()` cannot interrupt synchronous WASM, so the dying worker holds its EXCLUSIVE OPFS
|
|
406
|
+
* sync-access handle until its in-flight op finishes and the agent tears down — the successor (respawned in the
|
|
407
|
+
* same tab, immediately, since `awaitOwnershipRelease` is the documented no-op) must retry its open across that
|
|
408
|
+
* lag. The budget below (linear backoff: 100·(1+…+9) ≈ 4.5 s) spans a realistic release lag; a hang longer than
|
|
409
|
+
* the budget still fails closed (bounded), never a stranded half-open store.
|
|
410
|
+
*/
|
|
411
|
+
const OPFS_OPEN_ATTEMPTS = 10;
|
|
412
|
+
/** Default backoff between opfs open retries (ms); grows linearly per attempt (ADR-0049 ownership-release lag). */
|
|
413
|
+
const OPFS_OPEN_BACKOFF_MS = 100;
|
|
414
|
+
/** The opfs-repacked store extent size (ADR-0049 step 10a). */
|
|
415
|
+
const OPFS_STORE_EXTENT_SIZE = 65536;
|
|
416
|
+
/**
|
|
417
|
+
* Non-enumerable brand stamped on an opfs-repacked instance {@link createClientPGlite} mints (ADR-0049): the
|
|
418
|
+
* opfs-repacked VFS owns its store on a dedicated OPFS directory and reports NO `dataDir` (a custom VFS, the
|
|
419
|
+
* field is honestly `undefined`), so the BYO "non-persistent" guard ({@link classifyNonPersistentDataDir},
|
|
420
|
+
* which reads only `dataDir`) would wrongly reject it as an in-memory default when it is adopted as a
|
|
421
|
+
* `precreatedPglite` (the provision-then-attach path). This brand lets the guard recognise it as PROVABLY
|
|
422
|
+
* persistent. `Symbol.for` so the brand survives even if the instance is inspected via a different module copy.
|
|
423
|
+
*/
|
|
424
|
+
const OPFS_REPACKED_PERSISTENT = Symbol.for("pgxsinkit.opfsRepackedPersistent");
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Open the opfs-repacked factory with bounded retries (3) and a small linear backoff for transient failures,
|
|
428
|
+
* then propagate the last error — a committed store's final failure is HARD, and an uncommitted candidate's
|
|
429
|
+
* likewise propagates (the caller never exposes an unopened store). Kept simple: retry the whole factory call,
|
|
430
|
+
* always, then throw.
|
|
431
|
+
*/
|
|
432
|
+
async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: number): Promise<T> {
|
|
433
|
+
let lastError: unknown;
|
|
434
|
+
for (let attempt = 1; attempt <= OPFS_OPEN_ATTEMPTS; attempt += 1) {
|
|
435
|
+
try {
|
|
436
|
+
return await open();
|
|
437
|
+
} catch (error) {
|
|
438
|
+
lastError = error;
|
|
439
|
+
if (attempt < OPFS_OPEN_ATTEMPTS && backoffMs > 0) {
|
|
440
|
+
await new Promise<void>((resolve) => setTimeout(resolve, backoffMs * attempt));
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
throw lastError;
|
|
309
445
|
}
|
|
310
446
|
|
|
311
447
|
/**
|
|
@@ -314,16 +450,17 @@ export interface CreateClientPGliteOptions {
|
|
|
314
450
|
* consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
|
|
315
451
|
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
316
452
|
* instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
|
|
317
|
-
* hooks, journal recovery and
|
|
453
|
+
* hooks, journal recovery, and registry reconciliation, exactly as its own `storePath` path does.
|
|
318
454
|
*
|
|
319
|
-
* Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED
|
|
320
|
-
* browser
|
|
455
|
+
* Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED from the engine home
|
|
456
|
+
* (capability-selected opfs-repacked with IndexedDB fallback in a browser, or the filesystem on Bun/Node);
|
|
457
|
+
* a scheme-bearing path throws {@link InvalidStorePathError}.
|
|
321
458
|
* Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests("x"))`) so a test can
|
|
322
459
|
* mint a memory store without naming a backend.
|
|
323
460
|
*
|
|
324
461
|
* The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
|
|
325
462
|
* dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
|
|
326
|
-
* initdb (+
|
|
463
|
+
* initdb (+ persistent-store open), which is the dominant cold-boot cost once the WASM is pre-warmed.
|
|
327
464
|
*
|
|
328
465
|
* `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
|
|
329
466
|
* rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
|
|
@@ -336,30 +473,94 @@ export async function createClientPGlite(
|
|
|
336
473
|
// then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
|
|
337
474
|
// empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
|
|
338
475
|
const normalised = normaliseStorePathInput(store);
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
//
|
|
476
|
+
const storePath = normalised.storePath;
|
|
477
|
+
const backendOverride = options?.backendOverride ?? normalised.backendOverride;
|
|
478
|
+
// An eager precreate is itself a store mint. Before a denied browser home opens its replacement IDB store,
|
|
479
|
+
// settle any durable `deleting` authority exactly as the ordinary createSyncClient path does. Keeping this at
|
|
480
|
+
// the documented precreate factory protects callers outside defineSyncWorker; the worker provision handler
|
|
481
|
+
// carries the same guard separately because it permits a caller-supplied createPglite factory.
|
|
482
|
+
if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
|
|
483
|
+
await recoverDeniedBootDeletion(storePath);
|
|
484
|
+
}
|
|
485
|
+
// Derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. Browser/worker → `idb://`,
|
|
486
|
+
// Bun/Node → `file://`, the sanctioned test lane → `memory://`. A scheme-bearing/empty storePath throws here.
|
|
487
|
+
// ADR-0049 step 10a: when the caller threads the placement probe's grant (`hasOpfsSyncAccess`), the browser
|
|
488
|
+
// store resolves to `opfs://` and routes to the opfs-repacked factory below. Default (undefined/false) leaves
|
|
489
|
+
// this call BYTE-IDENTICAL to today (`resolveStoreDataDir(storePath, backendOverride)`), so no baseline shifts.
|
|
490
|
+
const dataDir = options?.hasOpfsSyncAccess
|
|
491
|
+
? resolveStoreDataDir(storePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true })
|
|
492
|
+
: resolveStoreDataDir(storePath, backendOverride);
|
|
493
|
+
// Stamp the store's scheme on the boot rail (never the full path — it can carry an identity-specific store
|
|
494
|
+
// name): "idb:" / "file:" / "memory:".
|
|
342
495
|
const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
|
|
343
496
|
// Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the
|
|
344
497
|
// fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled
|
|
345
498
|
// result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
|
|
346
499
|
// pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
|
|
347
500
|
const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
|
|
348
|
-
//
|
|
349
|
-
// (createSyncClient's own create, the
|
|
350
|
-
//
|
|
501
|
+
// Durability (ADR-0047) is registry-declared and resolved by createSyncClient; the resolved mode is threaded
|
|
502
|
+
// in via the internal `durability` carrier. Every store minting path (createSyncClient's own create, the
|
|
503
|
+
// worker's default createPglite factory, spare/prewarm mints) funnels through this function, so the
|
|
504
|
+
// `?? "relaxed"` here is the terminal fallback when no mode was threaded (e.g. an eager caller-owned
|
|
505
|
+
// precreate). Maps to PGlite's `relaxedDurability` boolean (`"strict"` → false). On idb the per-query
|
|
351
506
|
// synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
|
|
352
|
-
const relaxedDurability = options?.
|
|
353
|
-
|
|
507
|
+
const relaxedDurability = (options?.durability ?? "relaxed") !== "strict";
|
|
508
|
+
|
|
509
|
+
// ADR-0049 step 10a — the `opfs://` branch. PGlite does NOT accept `opfs://` as a dataDir; instead the
|
|
510
|
+
// opfs-repacked factory owns the store on a dedicated OPFS directory. The factory is loaded LAZILY (a
|
|
511
|
+
// dynamic `import()`) and both it and the store-directory handle are injectable (`pgliteFactories`) so a Bun
|
|
512
|
+
// unit test drives this branch with no real WASM/OPFS. Durability maps from the same `relaxedDurability`
|
|
513
|
+
// resolution above (ADR-0047's default logic is untouched): `relaxed` → the factory's `"relaxed"`, else
|
|
514
|
+
// `"strict"`. The open is retried a bounded number of times for transient failures, then propagates.
|
|
515
|
+
if (dataDir.startsWith("opfs://")) {
|
|
516
|
+
const opfsPglite = (await timeAsync(
|
|
517
|
+
"boot pglite.create",
|
|
518
|
+
async () => {
|
|
519
|
+
const createOpfsRepacked =
|
|
520
|
+
options?.pgliteFactories?.createOpfsRepacked ??
|
|
521
|
+
(await import("@pgxsinkit/pglite-opfs-repacked")).createOpfsRepackedPGlite;
|
|
522
|
+
const getStoreDirectoryHandle =
|
|
523
|
+
options?.pgliteFactories?.getStoreDirectoryHandle ??
|
|
524
|
+
(() => createOpfsEffects(storePath).getStoreDirectoryHandle());
|
|
525
|
+
const directory = await getStoreDirectoryHandle();
|
|
526
|
+
return openWithBoundedRetries(
|
|
527
|
+
() =>
|
|
528
|
+
createOpfsRepacked({
|
|
529
|
+
directory: directory as CreateOpfsRepackedPGliteOptions["directory"],
|
|
530
|
+
durability: relaxedDurability ? "relaxed" : "strict",
|
|
531
|
+
extentSize: OPFS_STORE_EXTENT_SIZE,
|
|
532
|
+
// The store is engine-less by construction (only `live` is a create-time extension); the sync
|
|
533
|
+
// engine attaches post-create (ADR-0032 S1). Restore + pre-warmed boot assets ride the same
|
|
534
|
+
// `pglite` sub-options the idb path uses.
|
|
535
|
+
pglite: {
|
|
536
|
+
...(bootAssets ?? {}),
|
|
537
|
+
...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
|
|
538
|
+
extensions: { live },
|
|
539
|
+
},
|
|
540
|
+
}),
|
|
541
|
+
options?.pgliteFactories?.retryDelayMs ?? OPFS_OPEN_BACKOFF_MS,
|
|
542
|
+
);
|
|
543
|
+
},
|
|
544
|
+
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
545
|
+
)) as unknown as ClientPGlite;
|
|
546
|
+
// Brand it PROVABLY persistent: the opfs-repacked VFS reports no `dataDir`, so without this the BYO
|
|
547
|
+
// non-persistent guard would reject it when it is adopted as a `precreatedPglite` (provision-then-attach).
|
|
548
|
+
try {
|
|
549
|
+
Object.defineProperty(opfsPglite, OPFS_REPACKED_PERSISTENT, {
|
|
550
|
+
value: true,
|
|
551
|
+
enumerable: false,
|
|
552
|
+
configurable: true,
|
|
553
|
+
});
|
|
554
|
+
} catch {
|
|
555
|
+
// A frozen/exotic instance — the guard still falls back to its dataDir classification (best-effort brand).
|
|
556
|
+
}
|
|
557
|
+
return opfsPglite;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const pglite = (await timeAsync(
|
|
354
561
|
"boot pglite.create",
|
|
355
|
-
() =>
|
|
356
|
-
|
|
357
|
-
// (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So
|
|
358
|
-
// a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.
|
|
359
|
-
// the board's login-screen mint) carries no engine, no shape streams, and no Electric connections
|
|
360
|
-
// until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the
|
|
361
|
-
// `electric` namespace is provisioned later, exactly as the registry-derived schema is.
|
|
362
|
-
PGlite.create(dataDir, {
|
|
562
|
+
() => {
|
|
563
|
+
const createOptions: PGliteOptions = {
|
|
363
564
|
...(bootAssets ?? {}),
|
|
364
565
|
relaxedDurability,
|
|
365
566
|
// Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
|
|
@@ -367,22 +568,591 @@ export async function createClientPGlite(
|
|
|
367
568
|
// the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
|
|
368
569
|
// create (the store initdbs empty).
|
|
369
570
|
...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
|
|
571
|
+
// Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT
|
|
572
|
+
// (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So
|
|
573
|
+
// a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.
|
|
574
|
+
// the board's login-screen mint) carries no engine, no shape streams, and no Electric connections
|
|
575
|
+
// until it is claimed and handed to `createSyncClient`.
|
|
370
576
|
extensions: {
|
|
371
577
|
live,
|
|
372
578
|
},
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
579
|
+
};
|
|
580
|
+
// idb/file/memory take the dataDir-string form; upstream PGlite's own scheme parser selects the backend.
|
|
581
|
+
return PGlite.create(dataDir, createOptions);
|
|
582
|
+
},
|
|
583
|
+
// Stamp the resolved durability mode + store scheme so every boot-rail capture shows the mode and lane the
|
|
584
|
+
// store was created under (ADR-0047 diagnosability).
|
|
585
|
+
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
377
586
|
// `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time
|
|
378
587
|
// extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).
|
|
379
588
|
)) as unknown as ClientPGlite;
|
|
589
|
+
return pglite;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// ─── ADR-0049 step 11b: adoption boot wiring (declaration-gated) ──────────────────────────────────────
|
|
593
|
+
// The pure adoption orchestrator (`adoption.ts`, step 11a) is effect-injected; here we build the REAL effects
|
|
594
|
+
// and CALL the transition at the right point in the boot. The transition runs BEFORE any engine is exposed
|
|
595
|
+
// (invariant 3 — pre-expose exclusivity), consults the declaration FIRST (invariant 4 — default off), and
|
|
596
|
+
// deletes the idb predecessor ONLY after the commitment barrier publishes (invariants 3/4).
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* A store is being actively held by a live in-process client. The manual {@link adoptStore} API is a
|
|
600
|
+
* CREATION-PATH operation (like `restoreFrom`): it must be called INSTEAD of {@link createSyncClient}, never
|
|
601
|
+
* against a store an open client already owns — an idb→opfs migration under a live engine would strand the
|
|
602
|
+
* engine's writes. Detected via a module-level live-store registry (every {@link createSyncClient} that mints a
|
|
603
|
+
* client-owned store registers its path and unregisters on `stop()`/`destroy()`).
|
|
604
|
+
*/
|
|
605
|
+
export class StoreInUseError extends Error {
|
|
606
|
+
constructor(storePath: string) {
|
|
607
|
+
super(
|
|
608
|
+
`[pgxsinkit] adoptStore(${JSON.stringify(storePath)}) refused: a live client is currently holding this ` +
|
|
609
|
+
"store. Adoption is a creation-path migration — call it INSTEAD of createSyncClient, before any client " +
|
|
610
|
+
"opens the store (stop/destroy the existing client first).",
|
|
611
|
+
);
|
|
612
|
+
this.name = "StoreInUseError";
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** The paths of stores currently held by a live in-process client — the {@link adoptStore} live-store guard. */
|
|
617
|
+
const liveStorePaths = new Set<string>();
|
|
618
|
+
|
|
619
|
+
/** Internal-only marker for the live adoption executor's inner candidate boot. Never exported or consumer-set. */
|
|
620
|
+
const ADOPTION_CANDIDATE_BUILD: unique symbol = Symbol("pgxsinkit.adoptionCandidateBuild");
|
|
621
|
+
type AdoptionCandidateBuildOptions = { [ADOPTION_CANDIDATE_BUILD]?: true };
|
|
622
|
+
/** Internal-only PGlite boundary used by the real adoption recursion test; never exported or consumer-set. */
|
|
623
|
+
const INTERNAL_PGLITE_CREATE: unique symbol = Symbol("pgxsinkit.internalPgliteCreate");
|
|
624
|
+
type InternalPgliteCreateOptions = { [INTERNAL_PGLITE_CREATE]?: typeof createClientPGlite };
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* @internal Injectable seams for the boot-time adoption decision (step 11b). Real defaults in production; unit
|
|
628
|
+
* tests inject fakes so the wiring is exercised without real IndexedDB/OPFS/WASM. Shared by the automatic boot
|
|
629
|
+
* path ({@link runBootAdoption}) and the manual {@link adoptStore} API.
|
|
630
|
+
*/
|
|
631
|
+
export interface AdoptionWiringSeams {
|
|
632
|
+
/** Non-creating recordless idb existence check (adoption only ever migrates an EXISTING idb store). */
|
|
633
|
+
idbStoreExists?: (storePath: string) => Promise<boolean>;
|
|
634
|
+
/** The boot classifier + executor (`store-boot.ts`) — its verdict drives {@link adoptionEligible}. */
|
|
635
|
+
resolveStoreBoot?: (storePath: string) => Promise<StoreBootResolution>;
|
|
636
|
+
/** The real {@link AdoptionEffects} factory; injected in tests with recording fakes. */
|
|
637
|
+
buildEffects?: (storePath: string) => AdoptionEffects;
|
|
638
|
+
/** Diagnostics sink; defaults to the boot debug rail. */
|
|
639
|
+
log?: (message: string, data?: Record<string, unknown>) => void;
|
|
640
|
+
/** The store-meta IndexedDB seam (defaults to `globalThis.indexedDB`). */
|
|
641
|
+
meta?: StoreMetaDeps;
|
|
642
|
+
/** The OPFS root seam (defaults to `navigator.storage.getDirectory`). */
|
|
643
|
+
opfs?: OpfsEffectsDeps;
|
|
644
|
+
/** The external PGlite create boundary; the real adoption transition and inner createSyncClient remain intact. */
|
|
645
|
+
createPglite?: typeof createClientPGlite;
|
|
646
|
+
/** The live-store guard the manual {@link adoptStore} consults (defaults to the module-level registry). */
|
|
647
|
+
isStoreLive?: (storePath: string) => boolean;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** The bootstrap context an adoption transition's real effects need (registry + endpoints + auth + gate). */
|
|
651
|
+
interface AdoptionBootContext<TRegistry extends SyncTableRegistry> {
|
|
652
|
+
registry: TRegistry;
|
|
653
|
+
electricUrl: string;
|
|
654
|
+
batchWriteUrl: string;
|
|
655
|
+
getAuthToken?: () => Promise<string | undefined>;
|
|
656
|
+
requestHeaders?: Record<string, string>;
|
|
657
|
+
/** The effective app-level sync toggle — a `false` here fails the gate (adoption cannot reconstruct offline-by-config). */
|
|
658
|
+
syncEnabled: boolean;
|
|
659
|
+
/** Bounded wait for the eager Consistency groups' initial catch-up before the gate fails (offline/unauthorized). */
|
|
660
|
+
gateDeadlineMs?: number;
|
|
661
|
+
meta?: StoreMetaDeps;
|
|
662
|
+
opfs?: OpfsEffectsDeps;
|
|
663
|
+
createPglite?: typeof createClientPGlite;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** Delete-if-present the store's PGlite idb database; only `onsuccess` proves completion. */
|
|
667
|
+
function deleteAdoptionIdbPredecessor(storePath: string, meta?: StoreMetaDeps): Promise<void> {
|
|
668
|
+
const idb =
|
|
669
|
+
meta != null && "indexedDB" in meta
|
|
670
|
+
? (meta.indexedDB as unknown as IdbDeleteLike | undefined)
|
|
671
|
+
: (globalThis as { indexedDB?: IdbDeleteLike }).indexedDB;
|
|
672
|
+
if (idb?.deleteDatabase == null) return Promise.resolve();
|
|
673
|
+
const name = storeIndexedDbDatabaseName(storePath);
|
|
674
|
+
return new Promise<void>((resolve, reject) => {
|
|
675
|
+
let settled = false;
|
|
676
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
677
|
+
const finish = (error?: unknown) => {
|
|
678
|
+
if (settled) return;
|
|
679
|
+
settled = true;
|
|
680
|
+
if (timeout !== undefined) clearTimeout(timeout);
|
|
681
|
+
if (error === undefined) resolve();
|
|
682
|
+
else reject(error);
|
|
683
|
+
};
|
|
684
|
+
let request: {
|
|
685
|
+
error?: unknown;
|
|
686
|
+
onsuccess: (() => void) | null;
|
|
687
|
+
onerror: (() => void) | null;
|
|
688
|
+
onblocked?: (() => void) | null;
|
|
689
|
+
};
|
|
690
|
+
try {
|
|
691
|
+
request = idb.deleteDatabase(name);
|
|
692
|
+
} catch (error) {
|
|
693
|
+
finish(error);
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
request.onsuccess = () => finish();
|
|
697
|
+
request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
|
|
698
|
+
// `blocked` is nonterminal: the queued request may still succeed after the blocker closes. Do not lie to
|
|
699
|
+
// the adoption transition by reporting predecessor cleanup complete before `onsuccess`.
|
|
700
|
+
request.onblocked = () => undefined;
|
|
701
|
+
timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5_000);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** The minimal structural `indexedDB.deleteDatabase` surface (no DOM lib) — mirrors `store-boot.ts`. */
|
|
706
|
+
interface IdbDeleteLike {
|
|
707
|
+
deleteDatabase(name: string): {
|
|
708
|
+
error?: unknown;
|
|
709
|
+
onsuccess: (() => void) | null;
|
|
710
|
+
onerror: (() => void) | null;
|
|
711
|
+
onblocked?: (() => void) | null;
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Build the REAL {@link AdoptionEffects} the transition drives (step 11b). The idb engine is booted PRE-EXPOSE
|
|
717
|
+
* (never surfaced) solely to read the drain journal; the opfs candidate is built via the normal server bootstrap
|
|
718
|
+
* (`createSyncClient` with `syncEnabled: true`, `freshStore: true`, adoption OFF so it never recurses) and gated
|
|
719
|
+
* on the eager Consistency groups' catch-up; the shared commitment barrier (`runCommitmentBarrier`) commits it;
|
|
720
|
+
* only THEN is the idb predecessor deleted.
|
|
721
|
+
*/
|
|
722
|
+
function buildRealAdoptionEffects<TRegistry extends SyncTableRegistry>(
|
|
723
|
+
storePath: string,
|
|
724
|
+
ctx: AdoptionBootContext<TRegistry>,
|
|
725
|
+
): AdoptionEffects {
|
|
726
|
+
const opfs = createOpfsEffects(storePath, ctx.opfs);
|
|
727
|
+
const createPglite = ctx.createPglite ?? createClientPGlite;
|
|
728
|
+
const setPhase = (phase: StoreMetaPhase): Promise<void> =>
|
|
729
|
+
writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, ctx.meta);
|
|
730
|
+
return buildAdoptionEffects({
|
|
731
|
+
async readIdbJournal() {
|
|
732
|
+
// Open the idb engine PRE-EXPOSE (strict durability, no opfs grant → idb backend) solely to read the drain
|
|
733
|
+
// journal. Never surfaced to tabs (invariant 3). Because this is a READ-ONLY drain probe (no write ever
|
|
734
|
+
// reaches it), the engine is CLOSED here — releasing every idb handle so a deferred (`journal-owed`) boot
|
|
735
|
+
// can re-open the store cleanly, and so the drained path deletes the idb database with nothing holding it.
|
|
736
|
+
// `strictSyncAndCloseIdb` is therefore a no-op below: the "strict close" is trivially satisfied — an
|
|
737
|
+
// unwritten engine has nothing to flush, and the handle is already released.
|
|
738
|
+
const idbPglite = await createPglite(storePath, { durability: "strict" });
|
|
739
|
+
try {
|
|
740
|
+
const runtime = createMutationRuntime({
|
|
741
|
+
db: idbPglite,
|
|
742
|
+
registry: ctx.registry,
|
|
743
|
+
batchWriteUrl: ctx.batchWriteUrl,
|
|
744
|
+
ownsMetaTable: true,
|
|
745
|
+
});
|
|
746
|
+
const stats = await runtime.readMutationStats();
|
|
747
|
+
return {
|
|
748
|
+
pending: stats.pendingCount,
|
|
749
|
+
sending: stats.sendingCount,
|
|
750
|
+
acked: stats.ackedCount,
|
|
751
|
+
failed: stats.failedCount,
|
|
752
|
+
quarantined: stats.quarantinedCount,
|
|
753
|
+
conflicted: stats.conflictedCount,
|
|
754
|
+
rejected: stats.rejectedCount,
|
|
755
|
+
};
|
|
756
|
+
} finally {
|
|
757
|
+
await idbPglite.close();
|
|
758
|
+
}
|
|
759
|
+
},
|
|
760
|
+
setPhase,
|
|
761
|
+
async buildCandidate() {
|
|
762
|
+
// Adoption reconstructs from the server — a sync-disabled boot cannot: fail the gate BEFORE minting.
|
|
763
|
+
if (!ctx.syncEnabled) {
|
|
764
|
+
throw new Error(
|
|
765
|
+
"[pgxsinkit] adoption gate unmet: sync is disabled (`syncEnabled: false`), so the opfs successor " +
|
|
766
|
+
"cannot be reconstructed online. The idb store stays authoritative.",
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
// Build the opfs candidate via the NORMAL server bootstrap path (its own `createClientPGlite` mints the
|
|
770
|
+
// opfs store at the store directory). `freshStore: true` overlaps catch-up with the local phases; adoption
|
|
771
|
+
// is OFF so this never recurses; the phase stays `adopting` (set by the caller) for crash recovery.
|
|
772
|
+
const candidate = await createSyncClient<TRegistry>({
|
|
773
|
+
registry: ctx.registry,
|
|
774
|
+
electricUrl: ctx.electricUrl,
|
|
775
|
+
batchWriteUrl: ctx.batchWriteUrl,
|
|
776
|
+
storePath,
|
|
777
|
+
hasOpfsSyncAccess: true,
|
|
778
|
+
freshStore: true,
|
|
779
|
+
syncEnabled: true,
|
|
780
|
+
// Durability is registry-declared (ADR-0047): this candidate boot resolves it from `ctx.registry`, the
|
|
781
|
+
// SAME registry as the store it succeeds, so the opfs successor is minted under the declared mode.
|
|
782
|
+
[ADOPTION_CANDIDATE_BUILD]: true,
|
|
783
|
+
[INTERNAL_PGLITE_CREATE]: createPglite,
|
|
784
|
+
...(ctx.getAuthToken ? { getAuthToken: ctx.getAuthToken } : {}),
|
|
785
|
+
...(ctx.requestHeaders ? { requestHeaders: ctx.requestHeaders } : {}),
|
|
786
|
+
} as CreateSyncClientOptions<TRegistry> & AdoptionCandidateBuildOptions & InternalPgliteCreateOptions);
|
|
787
|
+
const strictSync = (candidate.pglite as unknown as { strictSync?: () => Promise<void> }).strictSync;
|
|
788
|
+
if (typeof strictSync !== "function") {
|
|
789
|
+
await candidate.stop().catch(() => undefined);
|
|
790
|
+
throw new Error(
|
|
791
|
+
"[pgxsinkit] adoption: the candidate store does not expose `strictSync()` — the commitment barrier " +
|
|
792
|
+
"requires an OPFS-repacked engine (data-before-authority, invariant 3).",
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
return {
|
|
796
|
+
ready: candidate.ready,
|
|
797
|
+
strictSync: () => strictSync.call(candidate.pglite),
|
|
798
|
+
close: () => candidate.stop(),
|
|
799
|
+
};
|
|
800
|
+
},
|
|
801
|
+
publishSentinel: () => opfs.publishSentinel(),
|
|
802
|
+
deleteSentinel: () => opfs.deleteSentinel(),
|
|
803
|
+
deleteStoreDirectory: () => opfs.deleteStoreDirectory(),
|
|
804
|
+
deleteIdbPredecessor: () => deleteAdoptionIdbPredecessor(storePath, ctx.meta),
|
|
805
|
+
...(ctx.gateDeadlineMs != null ? { gateDeadlineMs: ctx.gateDeadlineMs } : {}),
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** The default real seams for the adoption boot decision (production wiring). */
|
|
810
|
+
function realAdoptionSeams<TRegistry extends SyncTableRegistry>(
|
|
811
|
+
ctx: AdoptionBootContext<TRegistry>,
|
|
812
|
+
seams?: AdoptionWiringSeams,
|
|
813
|
+
): Required<Pick<AdoptionWiringSeams, "idbStoreExists" | "resolveStoreBoot" | "buildEffects" | "log">> {
|
|
814
|
+
return {
|
|
815
|
+
idbStoreExists: seams?.idbStoreExists ?? ((sp: string) => defaultIdbStoreExists(sp, ctx.meta)),
|
|
816
|
+
resolveStoreBoot:
|
|
817
|
+
seams?.resolveStoreBoot ??
|
|
818
|
+
((sp: string) =>
|
|
819
|
+
resolveStoreBoot(sp, {
|
|
820
|
+
hasOpfsSyncAccess: true,
|
|
821
|
+
...(ctx.meta || ctx.opfs
|
|
822
|
+
? { deps: { ...(ctx.meta ? { meta: ctx.meta } : {}), ...(ctx.opfs ? { opfs: ctx.opfs } : {}) } }
|
|
823
|
+
: {}),
|
|
824
|
+
})),
|
|
825
|
+
buildEffects: seams?.buildEffects ?? ((sp: string) => buildRealAdoptionEffects(sp, ctx)),
|
|
826
|
+
log: seams?.log ?? ((message, data) => syncDebug(message, data)),
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* @internal The boot-time AUTOMATIC adoption decision (step 11b). Returns whether the subsequent client-owned
|
|
832
|
+
* mint should open the OPFS backend (`bootHasOpfs`) after any adoption transition ran. Adoption ONLY ever
|
|
833
|
+
* migrates an EXISTING idb store (a committed-opfs or virgin store has no idb predecessor), so a non-creating
|
|
834
|
+
* idb existence check gates the whole path; then the boot classifier's verdict drives {@link adoptionEligible}.
|
|
835
|
+
* On `adopted: true` the opfs successor is committed and the mint opens it; on any `adopted: false` (owed
|
|
836
|
+
* journal / gate unmet / barrier failed) the idb store stays authoritative and the mint opens idb.
|
|
837
|
+
*/
|
|
838
|
+
export async function runBootAdoption<TRegistry extends SyncTableRegistry>(
|
|
839
|
+
storePath: string,
|
|
840
|
+
declaration: AdoptionDeclaration,
|
|
841
|
+
ctx: AdoptionBootContext<TRegistry>,
|
|
842
|
+
seamsOverride?: AdoptionWiringSeams,
|
|
843
|
+
): Promise<{ bootHasOpfs: boolean; outcome?: AdoptionOutcome }> {
|
|
844
|
+
const seams = realAdoptionSeams(ctx, seamsOverride);
|
|
845
|
+
// Adoption migrates an EXISTING idb store; nothing to adopt otherwise (committed-opfs / virgin have no idb).
|
|
846
|
+
if (!(await seams.idbStoreExists(storePath))) return { bootHasOpfs: true };
|
|
847
|
+
const resolution = await seams.resolveStoreBoot(storePath);
|
|
848
|
+
const verdict = resolution.verdict;
|
|
849
|
+
if (verdict === undefined || !adoptionEligible(declaration, verdict, true)) {
|
|
850
|
+
// The classifier already executed any recovery (e.g. an interrupted adoption). Honour its resolved backend.
|
|
851
|
+
const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
|
|
852
|
+
seams.log("boot adoption not eligible — using the classifier's resolved backend", {
|
|
853
|
+
action: verdict?.action,
|
|
854
|
+
storageBackend: resolution.storageBackend,
|
|
855
|
+
});
|
|
856
|
+
return { bootHasOpfs };
|
|
857
|
+
}
|
|
858
|
+
const outcome = await runAdoptionTransition(declaration, seams.buildEffects(storePath));
|
|
859
|
+
if (outcome.adopted) {
|
|
860
|
+
seams.log("boot adoption committed the opfs successor; idb predecessor deleted", {
|
|
861
|
+
...(outcome.predecessorCleanupPending ? { predecessorCleanupPending: outcome.predecessorCleanupPending } : {}),
|
|
862
|
+
});
|
|
863
|
+
return { bootHasOpfs: true, outcome };
|
|
864
|
+
}
|
|
865
|
+
seams.log("boot adoption deferred/failed — idb stays authoritative", {
|
|
866
|
+
reason: outcome.reason,
|
|
867
|
+
...(outcome.error ? { error: outcome.error } : {}),
|
|
868
|
+
});
|
|
869
|
+
return { bootHasOpfs: false, outcome };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// ─── ADR-0049 step 11c: FRESH/RESTORE commitment boot wiring ───────────────────────────────────────────
|
|
873
|
+
// Step 11b wired the DECLARATION-gated adoption transition; it left one gap (its own commit message names it):
|
|
874
|
+
// a virgin (or restored) opfs boot minted `opfs://` straight through `resolveStoreDataDir` WITHOUT the phase
|
|
875
|
+
// machine — no candidate record, no commitment barrier, no sentinel. That violated invariant 3 (an uncommitted
|
|
876
|
+
// candidate is never exposed to writes; commitment precedes exposure — D7) and invariant 12 (record written at
|
|
877
|
+
// creation, completed before exposure). This wiring closes it: EVERY browser opfs boot the client owns now
|
|
878
|
+
// routes through the boot phase machine, and a fresh/restore candidate is committed by the shared barrier
|
|
879
|
+
// BEFORE exposure. It COMPOSES with 11b — the declared-adoption-on-idb-store decision runs FIRST; this path
|
|
880
|
+
// runs only when the opfs grant survives it (so an already-committed successor resolves `open-committed` with
|
|
881
|
+
// no re-commit, and a deferred adoption's `false` grant short-circuits to idb).
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* @internal Injectable seams for the FRESH/RESTORE commitment boot wiring (step 11c). Real defaults in
|
|
885
|
+
* production (`globalThis.indexedDB` / `navigator.storage`); unit tests inject fakes so the phase machine and
|
|
886
|
+
* the commitment barrier are exercised without real IndexedDB / OPFS / WASM. Mirrors {@link AdoptionWiringSeams}:
|
|
887
|
+
* the IO surfaces are faked, the barrier runs over the REAL `resolveStoreBoot` / `createOpfsEffects` /
|
|
888
|
+
* `writeStoreMetaRecord` so the record-before-directory ordering and the sentinel/phase writes are real.
|
|
889
|
+
*/
|
|
890
|
+
export interface FreshCommitmentSeams {
|
|
891
|
+
/** The boot classifier + executor (`store-boot.ts`); its verdict decides whether a candidate needs the barrier. */
|
|
892
|
+
resolveStoreBoot?: (storePath: string) => Promise<StoreBootResolution>;
|
|
893
|
+
/** Diagnostics sink; defaults to the boot debug rail. */
|
|
894
|
+
log?: (message: string, data?: Record<string, unknown>) => void;
|
|
895
|
+
/** The store-meta IndexedDB seam (defaults to `globalThis.indexedDB`). */
|
|
896
|
+
meta?: StoreMetaDeps;
|
|
897
|
+
/** The OPFS root seam (defaults to `navigator.storage.getDirectory`). */
|
|
898
|
+
opfs?: OpfsEffectsDeps;
|
|
899
|
+
/** The recordless non-creating idb existence check (defaults to store-meta's `idbStoreExists`). */
|
|
900
|
+
idbExists?: (storePath: string) => Promise<boolean>;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** The PRE-MINT outcome of {@link resolveFreshBoot}: the resolved backend and whether the milestone owes a barrier. */
|
|
904
|
+
export interface FreshBootResolution {
|
|
905
|
+
/** Whether the client-owned mint should open the OPFS backend (a classification landing on idb flips this false). */
|
|
906
|
+
bootHasOpfs: boolean;
|
|
907
|
+
/** The resolved backend, for diagnostics (ADR-0049). */
|
|
908
|
+
storageBackend: ResolvedStorageBackend;
|
|
909
|
+
/** The executed boot verdict (absent on the short-circuited non-opfs path). */
|
|
910
|
+
verdict?: StoreBootVerdict;
|
|
911
|
+
/**
|
|
912
|
+
* Whether an UNCOMMITTED opfs candidate was stood up that the shared commitment barrier must promote at the
|
|
913
|
+
* local-init milestone ({@link runFreshCommitmentBarrier}) BEFORE exposure. True only for the two fresh
|
|
914
|
+
* candidate verdicts (`virgin-create` / `delete-candidate-and-rebuild`) landing on `opfs-repacked`; a
|
|
915
|
+
* committed store (`open-committed` / `repair-record-then-open-committed`) is already committed (no re-run).
|
|
916
|
+
*/
|
|
917
|
+
needsCommitmentBarrier: boolean;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* Map a resolved PGlite dataDir URL to the ADR-0049 decision 12 `storageBackend` diagnostic — the inverse of
|
|
922
|
+
* {@link resolveStoreDataDir}'s scheme selection (`opfs://` → opfs-repacked, `idb://` → idbfs, `file://` →
|
|
923
|
+
* filesystem, `memory://` → memory). Used to stamp the BootReport at the single client-owned mint seam. Returns
|
|
924
|
+
* `undefined` for an unrecognised scheme (a BYO instance whose dataDir the toolkit never minted — e.g. an
|
|
925
|
+
* opfs-repacked wrapper that does not self-report an `opfs://` dataDir), so the field is then honestly omitted.
|
|
926
|
+
*/
|
|
927
|
+
function storageBackendFromDataDir(dataDir: string | undefined): NonNullable<BootReport["storageBackend"]> | undefined {
|
|
928
|
+
if (dataDir == null) return undefined;
|
|
929
|
+
if (dataDir.startsWith("opfs://")) return "opfs-repacked";
|
|
930
|
+
if (dataDir.startsWith("idb://")) return "idbfs";
|
|
931
|
+
if (dataDir.startsWith("file://")) return "filesystem";
|
|
932
|
+
if (dataDir.startsWith("memory://")) return "memory";
|
|
933
|
+
return undefined;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** Does a boot verdict stand up an UNCOMMITTED opfs candidate the commitment barrier must promote (invariant 3)? */
|
|
937
|
+
function verdictNeedsCommitmentBarrier(
|
|
938
|
+
verdict: StoreBootVerdict | undefined,
|
|
939
|
+
storageBackend: ResolvedStorageBackend,
|
|
940
|
+
): boolean {
|
|
941
|
+
if (storageBackend !== "opfs-repacked") return false;
|
|
942
|
+
return verdict?.action === "virgin-create" || verdict?.action === "delete-candidate-and-rebuild";
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* @internal ADR-0049 step 11c — Phase 1 (PRE-MINT). Route a client-owned OPFS-home boot through the boot phase
|
|
947
|
+
* machine ({@link resolveStoreBoot}) so: a virgin/restore boot stands up an UNCOMMITTED opfs candidate (record
|
|
948
|
+
* BEFORE directory, invariant 12); a committed store resolves `open-committed` (no barrier re-run); a recordless
|
|
949
|
+
* idb store (adoption not declared) downgrades to idb (invariant 14 — never a fresh opfs mint over an existing
|
|
950
|
+
* idb store's data); and an interrupted destruction/adoption/candidate is recovered by the classifier itself. Returns
|
|
951
|
+
* whether the mint opens opfs and whether the local-init milestone must run the commitment barrier. A `false`
|
|
952
|
+
* `hasOpfsSyncAccess` SHORT-CIRCUITS (an idbfs/file home opens directly — the opfs commitment phase machine never
|
|
953
|
+
* runs), which is also how this composes with 11b: a deferred/failed adoption flips the grant to `false`.
|
|
954
|
+
*/
|
|
955
|
+
export async function resolveFreshBoot(
|
|
956
|
+
storePath: string,
|
|
957
|
+
hasOpfsSyncAccess: boolean,
|
|
958
|
+
backendOverride: "memory" | undefined,
|
|
959
|
+
seams?: FreshCommitmentSeams,
|
|
960
|
+
): Promise<FreshBootResolution> {
|
|
961
|
+
// Guard: only the browser opfs engine home routes through the phase machine. No grant (or the memory test
|
|
962
|
+
// lane, which has no meta machinery) → the idb/file/memory path is untouched except that a browser denied
|
|
963
|
+
// boot must finish an already-authorized `deleting` handoff before it creates a replacement IDB store.
|
|
964
|
+
if (!hasOpfsSyncAccess || backendOverride === "memory") {
|
|
965
|
+
if (!hasOpfsSyncAccess && backendOverride !== "memory") await recoverDeniedBootDeletion(storePath);
|
|
966
|
+
return {
|
|
967
|
+
bootHasOpfs: false,
|
|
968
|
+
storageBackend: backendOverride === "memory" ? "memory" : "idbfs",
|
|
969
|
+
needsCommitmentBarrier: false,
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
const runResolve =
|
|
973
|
+
seams?.resolveStoreBoot ??
|
|
974
|
+
((sp: string) =>
|
|
975
|
+
resolveStoreBoot(sp, {
|
|
976
|
+
hasOpfsSyncAccess: true,
|
|
977
|
+
...(seams?.meta || seams?.opfs || seams?.idbExists
|
|
978
|
+
? {
|
|
979
|
+
deps: {
|
|
980
|
+
...(seams?.meta ? { meta: seams.meta } : {}),
|
|
981
|
+
...(seams?.opfs ? { opfs: seams.opfs } : {}),
|
|
982
|
+
...(seams?.idbExists ? { idbExists: seams.idbExists } : {}),
|
|
983
|
+
},
|
|
984
|
+
}
|
|
985
|
+
: {}),
|
|
986
|
+
}));
|
|
987
|
+
const resolution = await runResolve(storePath);
|
|
988
|
+
const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
|
|
989
|
+
const needsCommitmentBarrier = verdictNeedsCommitmentBarrier(resolution.verdict, resolution.storageBackend);
|
|
990
|
+
(seams?.log ?? ((message, data) => syncDebug(message, data)))("boot fresh commitment resolved the boot backend", {
|
|
991
|
+
action: resolution.verdict?.action,
|
|
992
|
+
storageBackend: resolution.storageBackend,
|
|
993
|
+
needsCommitmentBarrier,
|
|
994
|
+
});
|
|
995
|
+
return {
|
|
996
|
+
bootHasOpfs,
|
|
997
|
+
storageBackend: resolution.storageBackend,
|
|
998
|
+
...(resolution.verdict ? { verdict: resolution.verdict } : {}),
|
|
999
|
+
needsCommitmentBarrier,
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* @internal ADR-0049 step 11c — Phase 2 (LOCAL-INIT MILESTONE, PRE-EXPOSE). Run the shared commitment barrier
|
|
1005
|
+
* ({@link runCommitmentBarrier}: `strictSync()` returns with VFS health good → publish the sentinel →
|
|
1006
|
+
* `opfs-committed` phase) over the live engine's `strictSync()`. The caller invokes this ONLY after the
|
|
1007
|
+
* FRESH/RESTORE provenance gate has passed (successful local initialization/recovery — the local-read core is
|
|
1008
|
+
* proven; D7 requires NO server for fresh/restore) and BEFORE exposure. A throw PROPAGATES out of the boot: the
|
|
1009
|
+
* barrier is all-or-nothing, so nothing is published, the `opfs-candidate` record survives, and the next boot's
|
|
1010
|
+
* classifier tears the candidate down and rebuilds (`delete-candidate-and-rebuild`) — nothing was ever exposed,
|
|
1011
|
+
* nothing strands (invariant 3). Real effects run over `createOpfsEffects` + `writeStoreMetaRecord`, injectable
|
|
1012
|
+
* for unit tests via {@link FreshCommitmentSeams}.
|
|
1013
|
+
*/
|
|
1014
|
+
/**
|
|
1015
|
+
* Extract the live engine's `strictSync()` from an opfs-repacked store for the commitment barrier (mirrors the
|
|
1016
|
+
* adoption path's `commitCandidate`). The commitment barrier requires it (data-before-authority, invariant 3);
|
|
1017
|
+
* a store that does not expose it is not an OPFS-repacked engine, which is a boot invariant violation.
|
|
1018
|
+
*/
|
|
1019
|
+
function resolveEngineStrictSync(pglite: ClientPGlite): () => Promise<void> {
|
|
1020
|
+
const strictSync = (pglite as unknown as { strictSync?: () => Promise<void> }).strictSync;
|
|
1021
|
+
if (typeof strictSync !== "function") {
|
|
1022
|
+
throw new Error(
|
|
1023
|
+
"[pgxsinkit] fresh commitment: the opfs store does not expose `strictSync()` — the commitment barrier " +
|
|
1024
|
+
"requires an OPFS-repacked engine (data-before-authority, invariant 3).",
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
return () => strictSync.call(pglite);
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
export async function runFreshCommitmentBarrier(
|
|
1031
|
+
storePath: string,
|
|
1032
|
+
strictSyncReturns: () => Promise<void>,
|
|
1033
|
+
seams?: FreshCommitmentSeams,
|
|
1034
|
+
): Promise<void> {
|
|
1035
|
+
const opfs = createOpfsEffects(storePath, seams?.opfs);
|
|
1036
|
+
await runCommitmentBarrier({
|
|
1037
|
+
strictSyncReturns,
|
|
1038
|
+
publishSentinel: () => opfs.publishSentinel(),
|
|
1039
|
+
setPhase: (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, seams?.meta),
|
|
1040
|
+
});
|
|
1041
|
+
(seams?.log ?? ((message, data) => syncDebug(message, data)))(
|
|
1042
|
+
"boot fresh commitment barrier committed the opfs store",
|
|
1043
|
+
{
|
|
1044
|
+
storePath,
|
|
1045
|
+
},
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/**
|
|
1050
|
+
* Format an opfs open failure into the VERBATIM `Name: message` the `storageFallbackReason` diagnostic carries
|
|
1051
|
+
* (ADR-0049 decision 12). A non-Error throw is stringified.
|
|
1052
|
+
*/
|
|
1053
|
+
function formatOpenFailureReason(error: unknown): string {
|
|
1054
|
+
if (error instanceof Error) return `${error.name || "Error"}: ${error.message}`;
|
|
1055
|
+
return String(error);
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/**
|
|
1059
|
+
* @internal ADR-0049 D6 — the VIRGIN-UNCREATABLE session idbfs fallback (plan step 13 gap; plan fault row "opfs
|
|
1060
|
+
* uncreatable, virgin → Session idbfs fallback after bounded retries, record written"). The COUNTERPART to
|
|
1061
|
+
* {@link runFreshCommitmentBarrier}: instead of committing a candidate that opened, this handles a candidate
|
|
1062
|
+
* that could NOT open. When the client-owned opfs mint exhausts {@link openWithBoundedRetries} on a
|
|
1063
|
+
* VIRGIN/candidate boot, tear the never-committed candidate down and re-mint on idbfs FOR THIS SESSION. Returns
|
|
1064
|
+
* the verbatim open-failure reason (`Name: message`) the caller stamps via the step-13 `storageFallbackReason`
|
|
1065
|
+
* seam.
|
|
1066
|
+
*
|
|
1067
|
+
* APPLIES ONLY to the positive-absence virgin/candidate path. {@link createSyncClient} gates this on
|
|
1068
|
+
* `commitmentBarrierPending` (= {@link FreshBootResolution.needsCommitmentBarrier}), which is true ONLY for
|
|
1069
|
+
* `virgin-create` / `delete-candidate-and-rebuild` landing on opfs — a boot that published NO sentinel and holds
|
|
1070
|
+
* an unexposed candidate. A COMMITTED store (record `opfs-committed`, or a present sentinel reading committed →
|
|
1071
|
+
* `open-committed` / `repair-record-then-open-committed`) owes NO barrier, so the gate is false and its open
|
|
1072
|
+
* failure PROPAGATES HARD (CONTEXT § "Commitment marker": "once committed, any opfs boot failure is a hard
|
|
1073
|
+
* failure"; accepted-risk register). This function is therefore never reached for a committed store.
|
|
1074
|
+
*
|
|
1075
|
+
* Teardown: delete-if-present the sentinel (a stale sentinel is impossible before the barrier, but symmetric
|
|
1076
|
+
* with `delete-candidate-and-rebuild`) AND the candidate directory, then set the meta record to
|
|
1077
|
+
* `idb-authoritative` — NOT delete it.
|
|
1078
|
+
*
|
|
1079
|
+
* STICKINESS (reconciling the plan's D6 "non-sticky, opfs retried next boot" verdict with the LATER phase
|
|
1080
|
+
* machine): the record is the first-use authority, and an idb fallback store IS a recorded idb store (boot
|
|
1081
|
+
* classification 7's caution / invariant 14 — the same as the no-handle virgin path, which already records
|
|
1082
|
+
* `idb-authoritative`). So the next boot classifies `boot-idb-authoritative` (classification 5) and boots idb;
|
|
1083
|
+
* it does NOT loop through virgin re-creation each boot. Retry-to-opfs is the DESIGNED non-destructive ADOPTION
|
|
1084
|
+
* re-entry (a declared consumer re-adopts to opfs on a later drained boot) — the phase machine's intended,
|
|
1085
|
+
* supervised re-entry — rather than a destructive per-boot re-probe. This keeps the fault row true ("record
|
|
1086
|
+
* written") and the fault-row semantics honest for the composition actually shipped.
|
|
1087
|
+
*/
|
|
1088
|
+
export async function fallbackVirginCandidateToIdb(
|
|
1089
|
+
storePath: string,
|
|
1090
|
+
openError: unknown,
|
|
1091
|
+
seams?: FreshCommitmentSeams,
|
|
1092
|
+
): Promise<string> {
|
|
1093
|
+
const opfs = createOpfsEffects(storePath, seams?.opfs);
|
|
1094
|
+
await opfs.deleteSentinel();
|
|
1095
|
+
await opfs.deleteStoreDirectory();
|
|
1096
|
+
await writeStoreMetaRecord(storePath, { phase: "idb-authoritative", updatedAt: Date.now() }, seams?.meta);
|
|
1097
|
+
const reason = formatOpenFailureReason(openError);
|
|
1098
|
+
(seams?.log ?? ((message, data) => syncDebug(message, data)))(
|
|
1099
|
+
"boot fresh commitment: opfs candidate uncreatable after bounded retries — session idbfs fallback",
|
|
1100
|
+
{ storePath, reason },
|
|
1101
|
+
);
|
|
1102
|
+
return reason;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/** Options for the manual {@link adoptStore} API — the creation-path adoption trigger. */
|
|
1106
|
+
export interface AdoptStoreOptions<TRegistry extends SyncTableRegistry> {
|
|
1107
|
+
registry: TRegistry;
|
|
1108
|
+
electricUrl: string;
|
|
1109
|
+
batchWriteUrl: string;
|
|
1110
|
+
/** The store to adopt (a plain path/name; the idb predecessor is migrated to a committed OPFS successor). */
|
|
1111
|
+
storePath?: string;
|
|
1112
|
+
getAuthToken?: () => Promise<string | undefined>;
|
|
1113
|
+
requestHeaders?: Record<string, string>;
|
|
1114
|
+
syncEnabled?: boolean;
|
|
1115
|
+
/** Bounded wait (ms) for the eager Consistency groups' catch-up before the gate fails closed. */
|
|
1116
|
+
gateDeadlineMs?: number;
|
|
1117
|
+
/** @internal test seams (fake effects / idb existence / meta+opfs IO). */
|
|
1118
|
+
seams?: AdoptionWiringSeams;
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* The MANUAL adoption API (ADR-0049 D7, plan step 11b): migrate an EXISTING idb-authoritative store into a
|
|
1123
|
+
* committed OPFS successor ON DEMAND, without the automatic {@link CreateSyncClientOptions.adoption} declaration
|
|
1124
|
+
* — the consumer's explicit call IS the authorization (they were told to export/migrate any local-only data
|
|
1125
|
+
* first). Like `restoreFrom` it is a CREATION-PATH operation: call it INSTEAD of {@link createSyncClient},
|
|
1126
|
+
* before any client opens the store — it REFUSES with {@link StoreInUseError} while a live in-process client
|
|
1127
|
+
* holds the store. The drain predicate still gates it (a store that owes the server work is not adoptable), and
|
|
1128
|
+
* every failure recovery is identical to the automatic path (idb stays authoritative; nothing strands).
|
|
1129
|
+
*/
|
|
1130
|
+
export async function adoptStore<const TRegistry extends SyncTableRegistry>(
|
|
1131
|
+
options: AdoptStoreOptions<TRegistry>,
|
|
1132
|
+
): Promise<AdoptionOutcome> {
|
|
1133
|
+
const storePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
1134
|
+
const isStoreLive = options.seams?.isStoreLive ?? ((sp: string) => liveStorePaths.has(sp));
|
|
1135
|
+
if (isStoreLive(storePath)) throw new StoreInUseError(storePath);
|
|
1136
|
+
const ctx: AdoptionBootContext<TRegistry> = {
|
|
1137
|
+
registry: options.registry,
|
|
1138
|
+
electricUrl: options.electricUrl,
|
|
1139
|
+
batchWriteUrl: options.batchWriteUrl,
|
|
1140
|
+
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
1141
|
+
...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
|
|
1142
|
+
syncEnabled: options.syncEnabled ?? true,
|
|
1143
|
+
...(options.gateDeadlineMs != null ? { gateDeadlineMs: options.gateDeadlineMs } : {}),
|
|
1144
|
+
...(options.seams?.meta ? { meta: options.seams.meta } : {}),
|
|
1145
|
+
...(options.seams?.opfs ? { opfs: options.seams.opfs } : {}),
|
|
1146
|
+
...(options.seams?.createPglite ? { createPglite: options.seams.createPglite } : {}),
|
|
1147
|
+
};
|
|
1148
|
+
const effects = options.seams?.buildEffects?.(storePath) ?? buildRealAdoptionEffects(storePath, ctx);
|
|
1149
|
+
return runManualAdoption(effects);
|
|
380
1150
|
}
|
|
381
1151
|
|
|
382
1152
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
383
1153
|
registry: TRegistry;
|
|
384
1154
|
electricUrl: string;
|
|
385
|
-
|
|
1155
|
+
batchWriteUrl: string;
|
|
386
1156
|
getAuthToken?: () => Promise<string | undefined>;
|
|
387
1157
|
/**
|
|
388
1158
|
* Static headers added to **every** read-shape and write request, alongside the per-request
|
|
@@ -405,13 +1175,45 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
405
1175
|
syncEnabled?: boolean;
|
|
406
1176
|
/**
|
|
407
1177
|
* The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
|
|
408
|
-
* is DERIVED from the
|
|
1178
|
+
* is DERIVED from the engine home (capability-selected opfs-repacked with IndexedDB fallback in a browser,
|
|
1179
|
+
* or the filesystem on Bun/Node); a
|
|
409
1180
|
* scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
|
|
410
1181
|
* at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product
|
|
411
1182
|
* configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from
|
|
412
1183
|
* `@pgxsinkit/client/testing` instead of naming one here.
|
|
413
1184
|
*/
|
|
414
1185
|
storePath?: string;
|
|
1186
|
+
/**
|
|
1187
|
+
* @internal Toolkit-internal WIRE-declaration carrier (ADR-0050), NOT a public per-boot knob. The worker
|
|
1188
|
+
* host threads the store's BOUND storage declaration (registry static + the first payload's wire
|
|
1189
|
+
* declaration + defaults) in here, and this boot's single storage resolution point folds it with the
|
|
1190
|
+
* registry's own static declaration — an explicit disagreement is a typed
|
|
1191
|
+
* `StorageDeclarationRefusedError` (the worker handlers refuse conflicts before this ever throws).
|
|
1192
|
+
* In-process consumers never set it: their registry IS the declaration.
|
|
1193
|
+
*/
|
|
1194
|
+
storage?: SyncStorageDeclaration;
|
|
1195
|
+
/**
|
|
1196
|
+
* ADR-0049 D1: the placement probe's OPFS-sync-access grant, threaded from the SharedWorker's engine home
|
|
1197
|
+
* (`defineSyncWorker`'s SW-direct bootstrap) into this boot so the client-owned create opens the OPFS-repacked
|
|
1198
|
+
* backend. Absent/false is the honest IDBFS home — the declared `backend: "idbfs"` mode or a capability-absence
|
|
1199
|
+
* fallback (a main thread can never hold handles either). Forwarded verbatim to {@link createClientPGlite}, which
|
|
1200
|
+
* resolves the actual dataDir from it.
|
|
1201
|
+
*/
|
|
1202
|
+
hasOpfsSyncAccess?: boolean;
|
|
1203
|
+
/**
|
|
1204
|
+
* ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
|
|
1205
|
+
* reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
|
|
1206
|
+
* committed OPFS successor. DEFAULT OFF (`undefined`) — hook absence is NEVER authority (`rawExec` writes
|
|
1207
|
+
* documented local-only state on any store), so only this explicit `"server-reconstructible"` value (or the
|
|
1208
|
+
* manual {@link adoptStore} API) authorizes deleting the idb predecessor. Honoured ONLY on the browser
|
|
1209
|
+
* OPFS-home boot path (when {@link hasOpfsSyncAccess} is granted and the client owns the create — never the
|
|
1210
|
+
* BYO-instance / restore paths): a boot that finds an idb-authoritative store runs the pre-expose drain check,
|
|
1211
|
+
* reconstructs the successor through the Adoption-bootstrap gate (authorized online reconstruction — the eager
|
|
1212
|
+
* Consistency groups' initial catch-up), commits it via the strict barrier, and only then deletes the idb
|
|
1213
|
+
* predecessor. Any deferral/failure (owed journal, gate unmet, barrier failed) leaves the idb store
|
|
1214
|
+
* authoritative and boots it normally.
|
|
1215
|
+
*/
|
|
1216
|
+
adoption?: AdoptionDeclaration;
|
|
415
1217
|
/**
|
|
416
1218
|
* Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
|
|
417
1219
|
* into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
|
|
@@ -423,33 +1225,20 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
423
1225
|
* falls back to loading its own assets, so this is a pure best-effort accelerator.
|
|
424
1226
|
*/
|
|
425
1227
|
pgliteBootAssets?: Promise<PgliteBootAssets>;
|
|
426
|
-
/**
|
|
427
|
-
* Relax PGlite's per-query durability for the client-owned store create (default `true`; ADR-0047).
|
|
428
|
-
* Forwarded verbatim to {@link createClientPGlite}, where the default is resolved — on the idb backend the
|
|
429
|
-
* per-query synchronous flush to IndexedDB dominates local write latency, so the toolkit defaults to
|
|
430
|
-
* relaxed (the query returns before the flush; the flush is scheduled asynchronously).
|
|
431
|
-
*
|
|
432
|
-
* Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a crash before
|
|
433
|
-
* BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the scheduled idb
|
|
434
|
-
* flush lands. Synced tables are recoverable from the server by construction, so this relaxes flush
|
|
435
|
-
* TIMING, not persistence (ADR-0036); consumer local-only tables carry whatever risk the consumer
|
|
436
|
-
* accepts. Ignored on the {@link pgliteInstance} path (the caller owns that store's create). Opt out with
|
|
437
|
-
* `relaxedDurability: false`.
|
|
438
|
-
*/
|
|
439
|
-
relaxedDurability?: boolean;
|
|
440
1228
|
resetSubscriptionKeys?: string[];
|
|
441
1229
|
prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
442
|
-
|
|
1230
|
+
prepareLocalDbAfterSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
443
1231
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
444
1232
|
onTableInitialSync?: (tableKey: string) => void;
|
|
445
1233
|
/**
|
|
446
1234
|
* A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
|
|
447
|
-
* post-create boot steps against it — no schema exec, prepare hooks, or
|
|
1235
|
+
* post-create boot steps against it — no schema exec, prepare hooks, or registry reconciliation
|
|
448
1236
|
* (journal recovery still runs, as it does on every path). Use it only when the caller has already
|
|
449
1237
|
* applied the registry schema itself. Contrast the three PGlite-provenance seams:
|
|
450
1238
|
* - {@link storePath} (default) — the client creates the store AND runs every post-create step.
|
|
451
1239
|
* - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
|
|
452
|
-
* the client still runs every post-create step (schema
|
|
1240
|
+
* the client still runs every post-create step (schema, prepare hooks, and reconciliation), exactly as
|
|
1241
|
+
* `storePath` does.
|
|
453
1242
|
* - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
|
|
454
1243
|
*
|
|
455
1244
|
* A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
|
|
@@ -463,9 +1252,10 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
463
1252
|
/**
|
|
464
1253
|
* A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
|
|
465
1254
|
* earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
|
|
466
|
-
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and
|
|
467
|
-
*
|
|
468
|
-
* {@link pgliteInstance} (which skips schema
|
|
1255
|
+
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and registry
|
|
1256
|
+
* reconciliation all run exactly as on the {@link storePath} path. This is the difference from
|
|
1257
|
+
* {@link pgliteInstance} (which skips schema, prepare hooks, and reconciliation because the caller owns
|
|
1258
|
+
* them); see that
|
|
469
1259
|
* option's JSDoc for the three-way distinction.
|
|
470
1260
|
*
|
|
471
1261
|
* The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
|
|
@@ -509,8 +1299,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
509
1299
|
* PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
|
|
510
1300
|
* and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
|
|
511
1301
|
* is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
|
|
512
|
-
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery,
|
|
513
|
-
*
|
|
1302
|
+
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery, and registry
|
|
1303
|
+
* reconciliation) and buffered in memory, with commits gated until those phases finish — so the network
|
|
514
1304
|
* catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
|
|
515
1305
|
* boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.
|
|
516
1306
|
*
|
|
@@ -546,10 +1336,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
546
1336
|
*/
|
|
547
1337
|
onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
|
|
548
1338
|
/**
|
|
549
|
-
* Invoked
|
|
550
|
-
*
|
|
551
|
-
* new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is
|
|
552
|
-
* postponed (and retried on a later boot) rather than dropping owed data.
|
|
1339
|
+
* Invoked when a supported store's registry fingerprint changes. `rebuilt` means the clean read cache was
|
|
1340
|
+
* rebuilt at the new shape; `deferred` means local mutations are still owed and must drain first.
|
|
553
1341
|
*/
|
|
554
1342
|
onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
|
|
555
1343
|
/**
|
|
@@ -579,6 +1367,22 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
579
1367
|
* absent → `"in-process"`. Not a behavior knob — it only labels the report.
|
|
580
1368
|
*/
|
|
581
1369
|
bootMode?: BootReport["mode"];
|
|
1370
|
+
/**
|
|
1371
|
+
* @internal Engine home stamped into the {@link BootReport} (ADR-0049 decision 12). Threaded by
|
|
1372
|
+
* `defineSyncWorker` from the SharedWorker placement decision — `"shared-worker"` (SW-direct) or
|
|
1373
|
+
* `"elected-worker"`. Absent only for a plain non-worker scope that cannot derive a browser engine home; the
|
|
1374
|
+
* in-process client stamps `"in-process"` itself. Report-label only.
|
|
1375
|
+
*/
|
|
1376
|
+
engineHome?: BootReport["engineHome"];
|
|
1377
|
+
/**
|
|
1378
|
+
* @internal Capability-absence fallback reason stamped into the {@link BootReport} (ADR-0049 D1/D12). Threaded
|
|
1379
|
+
* by `defineSyncWorker` when the placement bootstrap opened the in-SharedWorker IDBFS engine because OPFS was
|
|
1380
|
+
* CAPABLE but no home could hold sync-access handles (every probe denied / the OPFS API absent). Unlike the
|
|
1381
|
+
* client's own internal fallback reasons (adoption-deferred, recordless-idb — set only under a granted probe),
|
|
1382
|
+
* this externally-supplied reason is stamped verbatim on an idbfs boot. Absent on a granted opfs boot and on the
|
|
1383
|
+
* declared `backend: "idbfs"` mode (that is the data contract, not a fallback). Report-label only.
|
|
1384
|
+
*/
|
|
1385
|
+
storageFallbackReason?: string;
|
|
582
1386
|
/**
|
|
583
1387
|
* @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
|
|
584
1388
|
* minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
|
|
@@ -709,7 +1513,7 @@ export interface SubscribeLiveRowsInput {
|
|
|
709
1513
|
* same-named columns even in a plain query. When supplied, the seam wraps the query so every output
|
|
710
1514
|
* column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
|
|
711
1515
|
* by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then
|
|
712
|
-
* leaves the SQL untouched and rows stay keyed by the underlying column names
|
|
1516
|
+
* leaves the SQL untouched and rows stay keyed by the underlying column names.
|
|
713
1517
|
*/
|
|
714
1518
|
fields?: readonly string[];
|
|
715
1519
|
/**
|
|
@@ -779,8 +1583,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
779
1583
|
[TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
|
|
780
1584
|
};
|
|
781
1585
|
/**
|
|
782
|
-
* Local-read readiness (ADR-0041): resolves once PGlite is open, the durable schema is
|
|
783
|
-
*
|
|
1586
|
+
* Local-read readiness (ADR-0041): resolves once PGlite is open, the durable schema is ready, registry
|
|
1587
|
+
* reconciliation has completed, and the drizzle read
|
|
784
1588
|
* facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync
|
|
785
1589
|
* start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract
|
|
786
1590
|
* `createSyncClient()` (and, in stage 2, `attachSyncClient()`) resolves at exactly this stage; the write and
|
|
@@ -805,6 +1609,14 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
805
1609
|
ready: Promise<void>;
|
|
806
1610
|
status: SyncRuntimeStatus;
|
|
807
1611
|
start: () => Promise<void>;
|
|
1612
|
+
/**
|
|
1613
|
+
* Synchronously abort all sync/write activity (in-flight write fetches, shape-stream long-polls, convergence
|
|
1614
|
+
* scheduling) without awaiting. Idempotent. The first action of every teardown path — stop()/destroy() call it,
|
|
1615
|
+
* and the SharedWorker host calls it before draining subscribes / disposing live queries so no teardown step
|
|
1616
|
+
* races a still-live engine. Not a substitute for stop()/destroy(): the awaited teardown (unsubscribe, dispose,
|
|
1617
|
+
* pglite.close) still follows. Callers rarely invoke it directly.
|
|
1618
|
+
*/
|
|
1619
|
+
haltActivity: () => void;
|
|
808
1620
|
stop: () => Promise<void>;
|
|
809
1621
|
/**
|
|
810
1622
|
* Wipe the entire local store (synced cache + overlay + journal) and close the handle
|
|
@@ -865,7 +1677,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
865
1677
|
) => Promise<void>;
|
|
866
1678
|
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;
|
|
867
1679
|
/**
|
|
868
|
-
* The registry-wide reactive mutation-status surface
|
|
1680
|
+
* The registry-wide reactive mutation-status surface: a global per-status summary and a
|
|
869
1681
|
* filtered normalized detail list over EVERY writable journal, each available one-shot or as a live
|
|
870
1682
|
* subscription. Identical on the in-process and worker-attached client. Render a global sync indicator with
|
|
871
1683
|
* ONE `subscribeSummary` instead of one journal live query per writable table; consumers never touch the
|
|
@@ -1125,6 +1937,14 @@ export function replAdapter(
|
|
|
1125
1937
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
1126
1938
|
options: CreateSyncClientOptions<TRegistry>,
|
|
1127
1939
|
): Promise<SyncClient<TRegistry>> {
|
|
1940
|
+
// The outer adoption transition owns the durable `adopting` phase and final commitment barrier. Its inner
|
|
1941
|
+
// candidate boot must mint only candidate bytes; re-entering the ordinary phase machine would classify the
|
|
1942
|
+
// live `adopting` record as crash recovery and tear the candidate down underneath itself.
|
|
1943
|
+
const adoptionCandidateBuild =
|
|
1944
|
+
(options as CreateSyncClientOptions<TRegistry> & AdoptionCandidateBuildOptions)[ADOPTION_CANDIDATE_BUILD] === true;
|
|
1945
|
+
const createPglite =
|
|
1946
|
+
(options as CreateSyncClientOptions<TRegistry> & InternalPgliteCreateOptions)[INTERNAL_PGLITE_CREATE] ??
|
|
1947
|
+
createClientPGlite;
|
|
1128
1948
|
// Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
|
|
1129
1949
|
validateLiveQueryPolicy(options.liveQueries);
|
|
1130
1950
|
const status: SyncRuntimeStatus = {
|
|
@@ -1140,7 +1960,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1140
1960
|
});
|
|
1141
1961
|
|
|
1142
1962
|
// Staged boot readiness (ADR-0041). Three monotonic, idempotent stages resolved as the boot crosses them:
|
|
1143
|
-
// - `localReadReady`: local-read core done (schema
|
|
1963
|
+
// - `localReadReady`: local-read core done (schema + registry reconcile + drizzle facade) — zero network.
|
|
1144
1964
|
// - `writeReady`: mutation runtime + boot recovery (+ restore quarantine) done — enqueue is safe.
|
|
1145
1965
|
// - `bootSettled`: today's full resolution point (sync START done). The worker bridge awaits it (stage 1).
|
|
1146
1966
|
// Under the Option B contract this function RESOLVES at `localReadReady` and runs the write/sync tail in the
|
|
@@ -1169,7 +1989,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1169
1989
|
|
|
1170
1990
|
if (options.pgliteInstance && options.precreatedPglite) {
|
|
1171
1991
|
throw new Error(
|
|
1172
|
-
"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks,
|
|
1992
|
+
"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, and registry reconciliation).",
|
|
1173
1993
|
);
|
|
1174
1994
|
}
|
|
1175
1995
|
|
|
@@ -1199,12 +2019,19 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1199
2019
|
// everything else is a warm (existing persisted) store. Restore wins — a restore boot is never "fresh".
|
|
1200
2020
|
const storeKind: BootReport["storeKind"] = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
|
|
1201
2021
|
|
|
2022
|
+
// Engine home for the report (ADR-0049 decision 12): the in-process client is always `"in-process"`; a worker
|
|
2023
|
+
// boot carries the placement `engineHome` the worker threaded in (`"shared-worker"` / `"elected-worker"`), or
|
|
2024
|
+
// omits it (undefined) when that scope never ran the placement probe (a dedicated elected-engine worker).
|
|
2025
|
+
const bootMode: BootReport["mode"] = options.bootMode ?? "in-process";
|
|
2026
|
+
const engineHome: BootReport["engineHome"] | undefined = bootMode === "worker" ? options.engineHome : "in-process";
|
|
2027
|
+
|
|
1202
2028
|
// Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
|
|
1203
2029
|
// sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
|
|
1204
2030
|
const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
|
|
1205
|
-
mode:
|
|
2031
|
+
mode: bootMode,
|
|
1206
2032
|
freshStore: options.freshStore === true,
|
|
1207
2033
|
storeKind,
|
|
2034
|
+
...(engineHome != null ? { engineHome } : {}),
|
|
1208
2035
|
overlapPrefetch,
|
|
1209
2036
|
registryFingerprint: fingerprintRegistry(options.registry),
|
|
1210
2037
|
});
|
|
@@ -1230,24 +2057,54 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1230
2057
|
|
|
1231
2058
|
// Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
|
|
1232
2059
|
// `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.
|
|
2060
|
+
// ADR-0049 step 11b: the OPFS-home grant the client-owned mint opens under. Starts at the placement probe's
|
|
2061
|
+
// value and is ADJUSTED DOWN to `false` by a deferred/failed adoption (the idb store stays authoritative), or
|
|
2062
|
+
// kept `true` when adoption commits the opfs successor (the mint opens the now-committed store). Read at mint
|
|
2063
|
+
// time by `timedCreate` below, so the adoption block can settle it before the create runs.
|
|
2064
|
+
let bootHasOpfsSyncAccess = options.hasOpfsSyncAccess === true;
|
|
2065
|
+
// ADR-0049 step 11c: set by the pre-mint fresh-boot phase machine when it stands up an UNCOMMITTED opfs
|
|
2066
|
+
// candidate (virgin/restore) that the shared commitment barrier must promote BEFORE exposure. Read at the
|
|
2067
|
+
// local-init milestone below, so a fresh/restore boot commits (strictSync → sentinel → opfs-committed) before
|
|
2068
|
+
// `localReadReady` resolves and the client is handed out (invariant 3 — commitment precedes exposure).
|
|
2069
|
+
let commitmentBarrierPending = false;
|
|
2070
|
+
// ADR-0049 decision 12 `storageFallbackReason`: the verbatim reason an opfs-CAPABLE boot (the probe granted)
|
|
2071
|
+
// nonetheless opened idb. `probeGranted` is the entering grant; a fallback is `probeGranted && !bootHasOpfs...`
|
|
2072
|
+
// once the adoption + fresh phase machine has settled (never on a plain idb boot, where `probeGranted` is false).
|
|
2073
|
+
const probeGranted = options.hasOpfsSyncAccess === true;
|
|
2074
|
+
let storageFallbackReason: string | undefined;
|
|
2075
|
+
// Durability (ADR-0047 D2 + ADR-0050): resolve the store's declared mode ONCE here — this is the single
|
|
2076
|
+
// resolution point — from the registry's static declaration folded with the worker-threaded wire
|
|
2077
|
+
// declaration (`options.storage`, the ADR-0050 internal carrier; absent for in-process consumers). An
|
|
2078
|
+
// explicit disagreement is a typed refusal (the worker handlers refuse conflicts before this throws).
|
|
2079
|
+
// The resolved mode threads into every client-owned mint (its own boot create and the precreated-reject
|
|
2080
|
+
// fallback) via the internal carrier on `createClientPGlite`; no open site takes a durability option, so
|
|
2081
|
+
// no mint can contradict the data contract.
|
|
2082
|
+
const resolvedDurability: StorageDurability = resolveStorageDeclaration(
|
|
2083
|
+
getSyncRegistryStorage(options.registry),
|
|
2084
|
+
options.storage,
|
|
2085
|
+
).durability;
|
|
1233
2086
|
const createClientOptions: CreateClientPGliteOptions = {
|
|
1234
2087
|
...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
|
|
1235
2088
|
...(backendOverride ? { backendOverride } : {}),
|
|
1236
|
-
|
|
1237
|
-
// `?? true` default. Passed only when set, so the default lives at exactly one point.
|
|
1238
|
-
...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
|
|
2089
|
+
durability: resolvedDurability,
|
|
1239
2090
|
// Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
|
|
1240
2091
|
// mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned
|
|
1241
2092
|
// create — never the adopt paths, which leave `restoreFrom` unread.
|
|
1242
2093
|
...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),
|
|
1243
2094
|
};
|
|
1244
2095
|
const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
2096
|
+
let openedStorageBackend: NonNullable<BootReport["storageBackend"]> | undefined;
|
|
1245
2097
|
|
|
1246
2098
|
// Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
|
|
1247
2099
|
// brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
|
|
1248
|
-
// half-write) an existing datadir
|
|
2100
|
+
// half-write) an existing datadir. The memory test lane is fresh by construction, so the probe is a no-op.
|
|
1249
2101
|
if (restoreBoot) {
|
|
1250
|
-
|
|
2102
|
+
const targetExists = await storeTargetExists(
|
|
2103
|
+
fallbackStorePath,
|
|
2104
|
+
backendOverride,
|
|
2105
|
+
bootHasOpfsSyncAccess ? { hasIndexedDb: true, hasOpfsSyncAccess: true } : undefined,
|
|
2106
|
+
);
|
|
2107
|
+
if (targetExists) {
|
|
1251
2108
|
throw new RestoreTargetExistsError(fallbackStorePath);
|
|
1252
2109
|
}
|
|
1253
2110
|
}
|
|
@@ -1255,11 +2112,55 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1255
2112
|
// caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
|
|
1256
2113
|
const timedCreate = async (): Promise<ClientPGlite> => {
|
|
1257
2114
|
const startedAt = performance.now();
|
|
1258
|
-
|
|
2115
|
+
// ADR-0049 step 10b/11b: the OPFS-home grant is spread in at MINT time (not baked into `createClientOptions`),
|
|
2116
|
+
// so a boot adoption that ran just above can settle `bootHasOpfsSyncAccess` first — opening the committed
|
|
2117
|
+
// opfs successor (adopted) or the idb store (adoption deferred/failed). Default absent keeps today's backend.
|
|
2118
|
+
// ADR-0049 decision 12: this is the SINGLE client-owned mint seam, so stamp `storageBackend` from the resolved
|
|
2119
|
+
// dataDir scheme here — the same resolution `createClientPGlite` performs, so the diagnostic never diverges
|
|
2120
|
+
// from the backend actually opened. Covers every client-owned mint (in-process, worker, precreated-fallback).
|
|
2121
|
+
const resolvedDataDir = bootHasOpfsSyncAccess
|
|
2122
|
+
? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true })
|
|
2123
|
+
: resolveStoreDataDir(fallbackStorePath, backendOverride);
|
|
2124
|
+
const created = await createPglite(fallbackStorePath, {
|
|
2125
|
+
...createClientOptions,
|
|
2126
|
+
...(bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
2127
|
+
});
|
|
2128
|
+
// ADR-0049 decision 12: stamp `storageBackend` only AFTER a SUCCESSFUL open (first-wins). A failed opfs open
|
|
2129
|
+
// — the virgin-uncreatable session idbfs fallback below re-mints on idb — therefore never stamps
|
|
2130
|
+
// `opfs-repacked`; the idb re-mint's `idbfs` is the one that lands, honestly reflecting the backend opened.
|
|
2131
|
+
const mintedBackend = storageBackendFromDataDir(resolvedDataDir);
|
|
2132
|
+
if (mintedBackend) {
|
|
2133
|
+
openedStorageBackend = mintedBackend;
|
|
2134
|
+
bootReportBuilder.setStorageBackend(mintedBackend);
|
|
2135
|
+
}
|
|
1259
2136
|
bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
|
|
1260
2137
|
return created;
|
|
1261
2138
|
};
|
|
1262
2139
|
|
|
2140
|
+
// ADR-0049 step 11b — AUTOMATIC adoption (declaration-gated, default off). Honoured ONLY on the client-owned
|
|
2141
|
+
// storePath create in a browser OPFS engine home (`bootHasOpfsSyncAccess`), never the BYO / restore paths: a
|
|
2142
|
+
// boot that finds an existing idb-authoritative store runs the pre-expose drain check, reconstructs the opfs
|
|
2143
|
+
// successor through the Adoption-bootstrap gate, commits it, and deletes the idb predecessor. Any deferral or
|
|
2144
|
+
// failure leaves the idb store authoritative — `bootHasOpfsSyncAccess` is flipped to false so the mint opens
|
|
2145
|
+
// idb. Runs before the create, so `timedCreate` opens whichever backend the transition settled on.
|
|
2146
|
+
const runBootAdoptionIfDeclared = async (): Promise<void> => {
|
|
2147
|
+
if (!bootHasOpfsSyncAccess || options.adoption !== "server-reconstructible" || restoreBoot) return;
|
|
2148
|
+
const { bootHasOpfs, outcome } = await runBootAdoption(fallbackStorePath, options.adoption, {
|
|
2149
|
+
registry: options.registry,
|
|
2150
|
+
electricUrl: options.electricUrl,
|
|
2151
|
+
batchWriteUrl: options.batchWriteUrl,
|
|
2152
|
+
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
2153
|
+
...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
|
|
2154
|
+
syncEnabled: options.syncEnabled ?? true,
|
|
2155
|
+
});
|
|
2156
|
+
bootHasOpfsSyncAccess = bootHasOpfs;
|
|
2157
|
+
// ADR-0049 decision 12: a declared adoption that DEFERRED/FAILED left idb authoritative — an opfs-capable boot
|
|
2158
|
+
// that opened idb. Record the verbatim reason (the outcome's own classification) as the fallback reason.
|
|
2159
|
+
if (!bootHasOpfs && outcome && outcome.adopted === false) {
|
|
2160
|
+
storageFallbackReason = `adoption deferred (${outcome.reason})`;
|
|
2161
|
+
}
|
|
2162
|
+
};
|
|
2163
|
+
|
|
1263
2164
|
// Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
|
|
1264
2165
|
// acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the
|
|
1265
2166
|
// `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are
|
|
@@ -1268,17 +2169,89 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1268
2169
|
// `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).
|
|
1269
2170
|
const refuseIfNonPersistent = (instance: ClientPGlite): void => {
|
|
1270
2171
|
if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
|
|
1271
|
-
|
|
2172
|
+
// An opfs-repacked instance is PROVABLY persistent (a dedicated OPFS directory) yet reports no `dataDir`
|
|
2173
|
+
// (custom VFS), so honour its brand before the dataDir classification — otherwise adopting a provisioned
|
|
2174
|
+
// opfs store (provision-then-attach, ADR-0049) would be wrongly refused as an in-memory default.
|
|
2175
|
+
if ((instance as Record<symbol, unknown>)[OPFS_REPACKED_PERSISTENT] === true) return;
|
|
2176
|
+
const observedDataDir = (instance as { dataDir?: string }).dataDir;
|
|
2177
|
+
// The two provably-non-persistent shapes: an undefined dataDir (a raw `new PGlite()` in-memory default)
|
|
2178
|
+
// and a `memory://` store. Every store the funnel mints carries a real `idb://`/`file://` dataDir string.
|
|
2179
|
+
const observed = classifyNonPersistentDataDir(observedDataDir);
|
|
1272
2180
|
if (observed !== null) throw new NonPersistentStoreError(observed);
|
|
1273
2181
|
};
|
|
1274
2182
|
|
|
2183
|
+
// The complete client-owned open path. Both an ordinary `storePath` boot and a rejected precreated
|
|
2184
|
+
// accelerator MUST enter here: recovery/adoption/classification precede every persistent mint. Keeping the
|
|
2185
|
+
// flow in one closure prevents a rejected eager create from bypassing live `deleting` authority or the OPFS
|
|
2186
|
+
// commitment phase machine by jumping straight to `timedCreate()`.
|
|
2187
|
+
const openOwnedStore = async (): Promise<ClientPGlite> => {
|
|
2188
|
+
// A capability-denied browser may inherit an interrupted destroy from an earlier granted engine home.
|
|
2189
|
+
// Resolve that authority before any replacement IDB store is minted; ordinary denied boots with no
|
|
2190
|
+
// `deleting` record remain unchanged apart from the bounded meta read.
|
|
2191
|
+
if (!bootHasOpfsSyncAccess && backendOverride !== "memory") {
|
|
2192
|
+
await recoverDeniedBootDeletion(fallbackStorePath);
|
|
2193
|
+
}
|
|
2194
|
+
// ADR-0049 step 11b: run the declaration-gated automatic adoption BEFORE the client-owned mint, so the mint
|
|
2195
|
+
// opens the committed opfs successor (adopted) or the still-authoritative idb store (deferred/failed). This
|
|
2196
|
+
// COMPOSES with step 11c below: adoption (declared, on an existing idb store) settles `bootHasOpfsSyncAccess`
|
|
2197
|
+
// FIRST; only then does the fresh/restore phase machine run.
|
|
2198
|
+
if (!adoptionCandidateBuild) await runBootAdoptionIfDeclared();
|
|
2199
|
+
// ADR-0049 step 11c: when the opfs grant survives adoption, route the client-owned mint through the boot
|
|
2200
|
+
// PHASE MACHINE (invariants 3/12/14). A virgin/restore boot stands up an UNCOMMITTED opfs candidate (record
|
|
2201
|
+
// BEFORE directory) and flags the commitment barrier for the local-init milestone; a committed store resolves
|
|
2202
|
+
// `open-committed` (no re-run — composes with an adoption that just committed); a recordless idb store (adoption
|
|
2203
|
+
// not declared) downgrades to idb (never a fresh opfs mint over an existing idb store's data). A `false` grant (probe denied
|
|
2204
|
+
// OR adoption deferred/failed) SHORT-CIRCUITS — the idbfs home opens directly, without the opfs commitment phase machine.
|
|
2205
|
+
if (adoptionCandidateBuild) {
|
|
2206
|
+
// The predecessor remains authoritative and its journal was proven drained before the outer transition
|
|
2207
|
+
// entered `adopting`. Remove any sentinel-less residue from an earlier authorized destruction, then create
|
|
2208
|
+
// the directory the candidate factory will open. No meta write and no commitment here: the outer adoption
|
|
2209
|
+
// transition owns both.
|
|
2210
|
+
const opfs = createOpfsEffects(fallbackStorePath);
|
|
2211
|
+
await opfs.deleteSentinel();
|
|
2212
|
+
await opfs.deleteStoreDirectory();
|
|
2213
|
+
await opfs.getStoreDirectoryHandle();
|
|
2214
|
+
} else if (bootHasOpfsSyncAccess) {
|
|
2215
|
+
const fresh = await resolveFreshBoot(fallbackStorePath, bootHasOpfsSyncAccess, backendOverride);
|
|
2216
|
+
// ADR-0049 decision 12: the phase machine downgraded a granted opfs boot to idb (invariant 14 — an existing
|
|
2217
|
+
// idb store is opened in place, never overwritten by a fresh opfs mint). That is an opfs-capable-boot-on-idb
|
|
2218
|
+
// fallback; record its verbatim verdict as the reason (only when adoption did not already set one).
|
|
2219
|
+
if (!fresh.bootHasOpfs && storageFallbackReason == null) {
|
|
2220
|
+
storageFallbackReason = `recordless idb store opened in place (invariant 14; verdict ${fresh.verdict?.action ?? "unknown"})`;
|
|
2221
|
+
}
|
|
2222
|
+
bootHasOpfsSyncAccess = fresh.bootHasOpfs;
|
|
2223
|
+
commitmentBarrierPending = fresh.needsCommitmentBarrier;
|
|
2224
|
+
}
|
|
2225
|
+
// ADR-0049 D6 — the VIRGIN-UNCREATABLE session idbfs fallback (plan step 13 gap; fault row "opfs uncreatable,
|
|
2226
|
+
// virgin → Session idbfs fallback after bounded retries, record written"). A VIRGIN/candidate opfs boot
|
|
2227
|
+
// (`commitmentBarrierPending` true — phase opfs-candidate, NO sentinel ever published) that cannot OPEN the
|
|
2228
|
+
// opfs store after `openWithBoundedRetries` exhausts tears the never-committed candidate down and re-mints on
|
|
2229
|
+
// idbfs FOR THIS SESSION ({@link fallbackVirginCandidateToIdb}: record → idb-authoritative, directory
|
|
2230
|
+
// deleted). A COMMITTED store's open failure is HARD: `commitmentBarrierPending` is false for
|
|
2231
|
+
// `open-committed` / `repair-record-then-open-committed` (record committed OR sentinel present), so the catch
|
|
2232
|
+
// is not even entered and the failure propagates. The fallback is thus reachable ONLY on positive proof of
|
|
2233
|
+
// absence (the virgin/candidate path), never over a committed store.
|
|
2234
|
+
if (commitmentBarrierPending) {
|
|
2235
|
+
try {
|
|
2236
|
+
return await timedCreate();
|
|
2237
|
+
} catch (openError) {
|
|
2238
|
+
storageFallbackReason = await fallbackVirginCandidateToIdb(fallbackStorePath, openError);
|
|
2239
|
+
bootHasOpfsSyncAccess = false;
|
|
2240
|
+
commitmentBarrierPending = false;
|
|
2241
|
+
return timedCreate();
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
return timedCreate();
|
|
2245
|
+
};
|
|
2246
|
+
|
|
1275
2247
|
let pglite: ClientPGlite;
|
|
1276
2248
|
// Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates
|
|
1277
2249
|
// whether the provision stamp is honoured (ADR-0034).
|
|
1278
2250
|
let adoptedPrecreated = false;
|
|
1279
2251
|
if (options.pgliteInstance) {
|
|
1280
2252
|
// The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
|
|
1281
|
-
// (schema
|
|
2253
|
+
// (schema, prepare hooks, and reconciliation) — see the `pgliteInstance` JSDoc. No create here →
|
|
2254
|
+
// `pgliteCreateMs` null.
|
|
1282
2255
|
refuseIfNonPersistent(options.pgliteInstance);
|
|
1283
2256
|
pglite = options.pgliteInstance;
|
|
1284
2257
|
} else if (options.precreatedPglite) {
|
|
@@ -1300,11 +2273,38 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1300
2273
|
syncDebug("boot precreated pglite rejected — falling back to storePath create", {
|
|
1301
2274
|
error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
|
|
1302
2275
|
});
|
|
1303
|
-
pglite = await
|
|
2276
|
+
pglite = await openOwnedStore();
|
|
1304
2277
|
}
|
|
1305
2278
|
} else {
|
|
1306
|
-
pglite = await
|
|
2279
|
+
pglite = await openOwnedStore();
|
|
2280
|
+
}
|
|
2281
|
+
// ADR-0049 decision 12: stamp the fallback reason once the mint's backend is settled. Guarded on `probeGranted`
|
|
2282
|
+
// (an opfs-capable boot) — a plain idb boot never enters the adoption/fresh phase machine, so it never sets one.
|
|
2283
|
+
if (probeGranted && !bootHasOpfsSyncAccess && backendOverride !== "memory" && storageFallbackReason != null) {
|
|
2284
|
+
bootReportBuilder.setStorageFallbackReason(storageFallbackReason);
|
|
2285
|
+
}
|
|
2286
|
+
// ADR-0049 D1/D12 capability-absence fallback: `defineSyncWorker`'s placement bootstrap opened the in-SW IDBFS
|
|
2287
|
+
// engine because OPFS was CAPABLE but no home could hold handles. That boot enters here with `hasOpfsSyncAccess`
|
|
2288
|
+
// FALSE (so the internal `probeGranted` guard above never fires), so stamp the externally-supplied reason here on
|
|
2289
|
+
// the idbfs mint. `setStorageFallbackReason` is first-wins, so an internal reason already set is never clobbered.
|
|
2290
|
+
if (options.storageFallbackReason != null && backendOverride !== "memory" && !bootHasOpfsSyncAccess) {
|
|
2291
|
+
bootReportBuilder.setStorageFallbackReason(options.storageFallbackReason);
|
|
2292
|
+
}
|
|
2293
|
+
// ADR-0049 decision 12: a BYO instance / adopted-precreated store was created OUTSIDE the mint seam, so derive
|
|
2294
|
+
// its `storageBackend` from the instance's own dataDir where recognisable; an opfs-repacked wrapper (or an
|
|
2295
|
+
// unknown scheme) leaves it omitted (`setStorageBackend` is first-wins, so a fallback-create is never clobbered).
|
|
2296
|
+
if (options.pgliteInstance != null || adoptedPrecreated) {
|
|
2297
|
+
const byoBackend = storageBackendFromDataDir((pglite as { dataDir?: string }).dataDir);
|
|
2298
|
+
if (byoBackend) {
|
|
2299
|
+
openedStorageBackend = byoBackend;
|
|
2300
|
+
bootReportBuilder.setStorageBackend(byoBackend);
|
|
2301
|
+
}
|
|
1307
2302
|
}
|
|
2303
|
+
// ADR-0049 step 11b: register the client-owned store path in the live-store guard so the manual `adoptStore`
|
|
2304
|
+
// API refuses to migrate a store an open client already holds (`StoreInUseError`). BYO instances the caller
|
|
2305
|
+
// owns are not registered (the caller manages their lifecycle). Unregistered on `stop()`/`destroy()` below.
|
|
2306
|
+
const ownsStoreLifecycle = !options.pgliteInstance;
|
|
2307
|
+
if (ownsStoreLifecycle) liveStorePaths.add(fallbackStorePath);
|
|
1308
2308
|
|
|
1309
2309
|
// Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
|
|
1310
2310
|
// its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`
|
|
@@ -1324,7 +2324,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1324
2324
|
// extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
|
|
1325
2325
|
// `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
|
|
1326
2326
|
// structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
|
|
1327
|
-
// BEFORE the schema/prepare steps below so a `
|
|
2327
|
+
// BEFORE the schema/prepare steps below so a `prepareLocalDbAfterSchema` hook sees the same `.electric` it did when
|
|
1328
2328
|
// the extension provided it at create time. `engine.close` (the former extension close hook — abort every
|
|
1329
2329
|
// shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment
|
|
1330
2330
|
// `pglite.close()` used to trigger it.
|
|
@@ -1342,7 +2342,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1342
2342
|
// ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────
|
|
1343
2343
|
// On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape
|
|
1344
2344
|
// catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which
|
|
1345
|
-
// we resolve once schema exec + journal recovery +
|
|
2345
|
+
// we resolve once schema exec + journal recovery + registry reconciliation complete. The network then
|
|
1346
2346
|
// overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the
|
|
1347
2347
|
// `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact
|
|
1348
2348
|
// sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).
|
|
@@ -1472,7 +2472,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1472
2472
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
1473
2473
|
}
|
|
1474
2474
|
|
|
1475
|
-
// Durable-schema fingerprint fast path
|
|
2475
|
+
// Durable-schema fingerprint fast path. The whole block stays inside the
|
|
1476
2476
|
// `schemaExec` phase so `schemaExecMs` remains comparable across the fast (skip) and full (replay) paths.
|
|
1477
2477
|
await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
|
|
1478
2478
|
// (2) The minimal bootstrap first — one small crossing so the `local_schema_fingerprint` read/write
|
|
@@ -1487,8 +2487,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1487
2487
|
// (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.
|
|
1488
2488
|
bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
|
|
1489
2489
|
} else {
|
|
1490
|
-
// (4b) Absent/mismatch → replay the durable schema, then stamp the fingerprint
|
|
1491
|
-
// (exec and stamp travel together — a throw here leaves the old/absent fingerprint for a retry).
|
|
2490
|
+
// (4b) Absent/mismatch → replay the durable schema, then stamp the fingerprint after success.
|
|
1492
2491
|
await pglite.exec(generateDurableLocalSchemaSql(options.registry));
|
|
1493
2492
|
await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
|
|
1494
2493
|
bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
|
|
@@ -1502,9 +2501,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1502
2501
|
}
|
|
1503
2502
|
});
|
|
1504
2503
|
|
|
1505
|
-
if (options.
|
|
1506
|
-
const
|
|
1507
|
-
await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () =>
|
|
2504
|
+
if (options.prepareLocalDbAfterSchema) {
|
|
2505
|
+
const prepareLocalDbAfterSchema = options.prepareLocalDbAfterSchema;
|
|
2506
|
+
await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDbAfterSchema(pglite));
|
|
1508
2507
|
}
|
|
1509
2508
|
}
|
|
1510
2509
|
|
|
@@ -1524,9 +2523,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1524
2523
|
const mutationRuntime = createMutationRuntime({
|
|
1525
2524
|
db: pglite,
|
|
1526
2525
|
registry: options.registry,
|
|
1527
|
-
|
|
2526
|
+
batchWriteUrl: options.batchWriteUrl,
|
|
1528
2527
|
// pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
|
|
1529
|
-
// supplied their own PGlite — then the marker is never touched and recovery
|
|
2528
|
+
// supplied their own PGlite — then the marker is never touched and recovery runs unconditionally.
|
|
1530
2529
|
ownsMetaTable: !options.pgliteInstance,
|
|
1531
2530
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
1532
2531
|
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
@@ -1549,7 +2548,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1549
2548
|
// Boot recovery (ADR-0005) driven by the durable recovery marker (slice 2), PLUS the restore quarantine
|
|
1550
2549
|
// (ADR-0035 decision 6, gated on `restoreBoot` inside `runBootRecovery`). Hoisted so the restore path runs
|
|
1551
2550
|
// it BEFORE read exposure (the ADR-0041 invariant) and the normal path defers it to the background write
|
|
1552
|
-
// tail. `runBootRecovery` owns the full decision — marker read, skip/
|
|
2551
|
+
// tail. `runBootRecovery` owns the full decision — marker read, skip/unconditional/transactional recovery, restore
|
|
1553
2552
|
// quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).
|
|
1554
2553
|
const runBootRecoveryStage = async (): Promise<void> => {
|
|
1555
2554
|
const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () =>
|
|
@@ -1558,9 +2557,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1558
2557
|
bootReportBuilder.setJournalRecovery(recoveryOutcome);
|
|
1559
2558
|
};
|
|
1560
2559
|
|
|
1561
|
-
// Store-version reconcile against the current registry fingerprint (ADR-0006). It reads the runtime's
|
|
1562
|
-
// journal stats to decide rebuild-vs-defer and `runtime.registryVersion` (static), so it needs only the
|
|
1563
|
-
// CONSTRUCTED runtime — not a completed recovery pass.
|
|
1564
2560
|
const runReconcileStage = async (): Promise<void> => {
|
|
1565
2561
|
if (options.pgliteInstance) return;
|
|
1566
2562
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
|
|
@@ -1574,12 +2570,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1574
2570
|
};
|
|
1575
2571
|
|
|
1576
2572
|
if (restoreBoot) {
|
|
1577
|
-
// Restore invariant (ADR-0041):
|
|
1578
|
-
//
|
|
1579
|
-
// every recovered row counts toward `owedMutations` (pending+sending+failed+quarantined) inside
|
|
1580
|
-
// `rebuildReadCacheOrDefer`, so a stale-fingerprint restore DEFERS the read-cache rebuild rather than
|
|
1581
|
-
// dropping the quarantined writes — unchanged from the pre-ADR-0041 recover→quarantine→reconcile order.
|
|
1582
|
-
// `localReadReady` and `writeReady` therefore coincide on a restore boot (both resolved after this point).
|
|
2573
|
+
// Restore invariant (ADR-0041): quarantine every recovered write before exposing a read facade.
|
|
2574
|
+
// `localReadReady` and `writeReady` therefore coincide on a restore boot.
|
|
1583
2575
|
await runBootRecoveryStage();
|
|
1584
2576
|
|
|
1585
2577
|
// ADR-0046: with recovery + quarantine complete, decide whether this restore comes online. The restore
|
|
@@ -1600,10 +2592,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1600
2592
|
}
|
|
1601
2593
|
await runReconcileStage();
|
|
1602
2594
|
} else {
|
|
1603
|
-
// Normal boot (ADR-0041): reconcile is part of the local-read core and runs BEFORE recovery (which moves
|
|
1604
|
-
// to the write tail). The owed count already includes `sending`, so an UNRECOVERED crash journal defers a
|
|
1605
|
-
// rebuild exactly as a recovered one would (recovery only lifts `sending → pending`, both counted) — the
|
|
1606
|
-
// deferral outcome is byte-identical to the pre-ADR-0041 recover-then-reconcile order.
|
|
1607
2595
|
await runReconcileStage();
|
|
1608
2596
|
}
|
|
1609
2597
|
|
|
@@ -1642,6 +2630,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1642
2630
|
// manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
|
|
1643
2631
|
const quiesceTailForTeardown = async (): Promise<void> => {
|
|
1644
2632
|
disposed = true;
|
|
2633
|
+
// ADR-0049 step 11b: release the live-store guard so a later manual `adoptStore` on this path is permitted
|
|
2634
|
+
// once this client is torn down (delete-if-present; a BYO-instance boot never registered, so it is a no-op).
|
|
2635
|
+
liveStorePaths.delete(fallbackStorePath);
|
|
1645
2636
|
// FIX 2: a stopped client can never reach `writeReady` / `ready`, so reject them (idempotent — a race with
|
|
1646
2637
|
// the tail's own resolve is settled first-wins; a normal stop AFTER boot is a no-op on the already-resolved
|
|
1647
2638
|
// promises) so a parked mutation or an `await ready` / `start()` fails FAST rather than hanging past
|
|
@@ -1654,6 +2645,21 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1654
2645
|
await bootSettled.catch(() => undefined);
|
|
1655
2646
|
};
|
|
1656
2647
|
|
|
2648
|
+
// Synchronously halt ALL sync/write ACTIVITY without awaiting anything — the first action of every teardown
|
|
2649
|
+
// entry point (stop()/destroy() here, and the SharedWorker host's closeHost, which calls this before it drains
|
|
2650
|
+
// pending subscribes or disposes live queries). Abort the mutation runtime's in-flight write fetches + any
|
|
2651
|
+
// stalled auth resolve, abort every shape-stream long-poll (engine.close's AbortControllers fire synchronously),
|
|
2652
|
+
// and stop convergence scheduling (the in-flight pass then settles fast — its fetch is aborted). Idempotent.
|
|
2653
|
+
// Without this, a teardown step that runs BEFORE the streams are aborted (live-query dispose, pending-subscribe
|
|
2654
|
+
// drain) races an engine still committing shape data and never settles. The full AWAITED teardown still runs
|
|
2655
|
+
// after; this only guarantees the network + scheduling are already dead when it does.
|
|
2656
|
+
const haltActivity = (): void => {
|
|
2657
|
+
disposed = true;
|
|
2658
|
+
mutationRuntime.abortInFlight();
|
|
2659
|
+
void engine.close();
|
|
2660
|
+
void convergenceDriver?.stop();
|
|
2661
|
+
};
|
|
2662
|
+
|
|
1657
2663
|
// The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after
|
|
1658
2664
|
// `localReadReady` resolves, so `createSyncClient` resolves at `localReadReady` (the Option B contract). On a
|
|
1659
2665
|
// restore boot recovery already ran in the core, so the tail only opens the (unused) gate and settles. It
|
|
@@ -1693,11 +2699,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1693
2699
|
bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
|
|
1694
2700
|
bootReportBuilder.markSyncStartDone();
|
|
1695
2701
|
} else {
|
|
1696
|
-
// Sequential path (warm store / no fresh hint):
|
|
1697
|
-
//
|
|
1698
|
-
// After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
|
|
1699
|
-
// dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
|
|
1700
|
-
// fresh re-stream (ADR-0006).
|
|
2702
|
+
// Sequential path (warm store / no fresh hint): apply any explicit subscription resets, promote
|
|
2703
|
+
// durable lazy groups, then start (catch-up strictly after the local phases).
|
|
1701
2704
|
const resetKeys =
|
|
1702
2705
|
versionEvent?.status === "rebuilt"
|
|
1703
2706
|
? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
|
|
@@ -2218,7 +3221,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2218
3221
|
start: async () => {
|
|
2219
3222
|
await ready;
|
|
2220
3223
|
},
|
|
3224
|
+
haltActivity,
|
|
2221
3225
|
stop: async () => {
|
|
3226
|
+
// Halt all activity FIRST (see haltActivity) — before any await.
|
|
3227
|
+
haltActivity();
|
|
2222
3228
|
// ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
|
|
2223
3229
|
// and await its settlement — so no shape stream is left running and nothing execs against the closing
|
|
2224
3230
|
// PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
|
|
@@ -2244,6 +3250,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2244
3250
|
// LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
|
|
2245
3251
|
// inside the slot run.
|
|
2246
3252
|
lifecycleSlot.run("destroy", async () => {
|
|
3253
|
+
// Halt all activity FIRST (see haltActivity) — before any await.
|
|
3254
|
+
haltActivity();
|
|
2247
3255
|
// ADR-0041: quiesce the background boot tail BEFORE the owed-mutations read and the wipe, so neither
|
|
2248
3256
|
// races the tail's recovery journal updates / sync start (BLOCKER 2). After this the tail has settled.
|
|
2249
3257
|
await quiesceTailForTeardown();
|
|
@@ -2277,6 +3285,26 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2277
3285
|
// `stop()` (ADR-0040 decisions 1 & 6).
|
|
2278
3286
|
await liveManager.dispose();
|
|
2279
3287
|
await pglite.close();
|
|
3288
|
+
// ADR-0049 step 10b: phase-aware destructive lifecycle. The wipe + close above cleared the local store;
|
|
3289
|
+
// now finish the store-meta / OPFS-namespace side. Every recorded browser store runs the full destructive
|
|
3290
|
+
// lifecycle (set `deleting` → delete commitment
|
|
3291
|
+
// sentinel → delete both possible backend stores → delete meta). Wiping application tables and closing
|
|
3292
|
+
// PGlite do NOT delete its IndexedDB database; retaining that shell would make the next granted boot
|
|
3293
|
+
// classify it as an existing recordless idb store instead of a genuinely fresh path. A recordless lifecycle-owned
|
|
3294
|
+
// IDB store therefore enters the same machine; memory, filesystem, non-browser, and caller-owned stores
|
|
3295
|
+
// have no toolkit browser authority to finish.
|
|
3296
|
+
const { readStoreMetaRecord } = await import("./store-meta");
|
|
3297
|
+
const metaResult = await readStoreMetaRecord(fallbackStorePath);
|
|
3298
|
+
// A recordless fixed IDB store is still lifecycle-owned: wiping tables does not delete its
|
|
3299
|
+
// database shell, so it must enter the same supervised deletion machine. Memory/filesystem and
|
|
3300
|
+
// caller-owned instances stay outside this browser authority mechanism.
|
|
3301
|
+
if (
|
|
3302
|
+
(typeof metaResult === "object" && metaResult !== null) ||
|
|
3303
|
+
(ownsStoreLifecycle && openedStorageBackend === "idbfs")
|
|
3304
|
+
) {
|
|
3305
|
+
const { runStoreDestruction, createStoreDestructionEffects } = await import("./worker/attach-sync-client");
|
|
3306
|
+
await runStoreDestruction(createStoreDestructionEffects(fallbackStorePath));
|
|
3307
|
+
}
|
|
2280
3308
|
}),
|
|
2281
3309
|
dropReadCache: async () => {
|
|
2282
3310
|
// ADR-0041 (SHOULD-FIX 5): the drop+rebuild resets subscriptions and rewrites the read cache, so it must
|
|
@@ -2380,7 +3408,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2380
3408
|
await localReadReady;
|
|
2381
3409
|
// Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
|
|
2382
3410
|
// temp-view creation (`column "title" specified more than once`) unless every output column has a
|
|
2383
|
-
// unique alias. No `fields` → SQL unchanged (
|
|
3411
|
+
// unique alias. No `fields` → SQL unchanged (the default name-keyed row shape). The wrap stays
|
|
2384
3412
|
// caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.
|
|
2385
3413
|
const materialSql = wrapLiveQueryForMaterialization(sql, fields);
|
|
2386
3414
|
// Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;
|
|
@@ -2512,8 +3540,22 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2512
3540
|
query: (sql, params) => pglite.query<Record<string, unknown>>(sql, params),
|
|
2513
3541
|
});
|
|
2514
3542
|
|
|
3543
|
+
// ─── ADR-0049 step 11c: FRESH/RESTORE commitment barrier — the LOCAL-INIT MILESTONE, PRE-EXPOSE ──────────
|
|
3544
|
+
// This is the earliest airtight local-initialization milestone (the FRESH/RESTORE provenance gate, D7 — NO
|
|
3545
|
+
// server): the durable schema and registry reconciliation (and, on a restore boot, recovery + quarantine)
|
|
3546
|
+
// have completed, and the drizzle read facade + client are built — the store is proven initialized. If
|
|
3547
|
+
// the pre-mint phase machine stood up an uncommitted opfs candidate, run the shared commitment barrier
|
|
3548
|
+
// (strictSync → sentinel → opfs-committed) NOW, BEFORE `resolveLocalReadReady()` resolves and the client is
|
|
3549
|
+
// handed out. A throw propagates straight out of this async function (exactly as a local-read-core failure
|
|
3550
|
+
// does — see `localReadReady`'s no-reject-binding rationale above): the returned promise rejects, the client
|
|
3551
|
+
// is NEVER exposed, nothing is published, the `opfs-candidate` record survives, and the next boot's classifier
|
|
3552
|
+
// tears the candidate down and rebuilds (invariant 3 — an uncommitted candidate is never exposed to writes).
|
|
3553
|
+
if (commitmentBarrierPending) {
|
|
3554
|
+
await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pglite));
|
|
3555
|
+
}
|
|
3556
|
+
|
|
2515
3557
|
// ─── Local-read core complete → resolve `localReadReady`, then run the write/sync tail in the background ──
|
|
2516
|
-
// (ADR-0041 Option B.) The durable schema
|
|
3558
|
+
// (ADR-0041 Option B.) The durable schema and registry reconciliation are complete, and the drizzle
|
|
2517
3559
|
// read facade + client are built — cached reads are safe now, with ZERO network. Stamp + resolve
|
|
2518
3560
|
// `localReadReady`; on a restore boot `writeReady` coincides (recovery + quarantine already ran in the core,
|
|
2519
3561
|
// before this read exposure — the ADR-0041 invariant). This function then RESOLVES at `localReadReady`.
|