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