@pgxsinkit/client 0.1.51 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/adoption.d.ts +118 -0
- package/dist/adoption.d.ts.map +1 -0
- package/dist/boot-report.d.ts +54 -15
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/convergence.d.ts +2 -1
- package/dist/convergence.d.ts.map +1 -1
- package/dist/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +309 -38
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4628 -1489
- package/dist/index.js.map +36 -24
- package/dist/live-rows-sql.d.ts +1 -1
- package/dist/local-store.d.ts +16 -31
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +10 -4
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +12 -15
- package/dist/mutation.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +51 -0
- package/dist/opfs-effects.d.ts.map +1 -0
- package/dist/placement-probe.d.ts +75 -0
- package/dist/placement-probe.d.ts.map +1 -0
- package/dist/schema.d.ts +11 -16
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +77 -0
- package/dist/store-boot.d.ts.map +1 -0
- package/dist/store-lifecycle.d.ts +153 -0
- package/dist/store-lifecycle.d.ts.map +1 -0
- package/dist/store-meta.d.ts +190 -0
- package/dist/store-meta.d.ts.map +1 -0
- package/dist/store-path.d.ts +77 -7
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/shape-inbox.d.ts +1 -1
- package/dist/sync/types.d.ts +3 -3
- package/dist/testing.js.map +3 -3
- package/dist/worker/attach-sync-client.d.ts +239 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +162 -5
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/election-coordinator.d.ts +95 -0
- package/dist/worker/election-coordinator.d.ts.map +1 -0
- package/dist/worker/engine-control.d.ts +265 -0
- package/dist/worker/engine-control.d.ts.map +1 -0
- package/dist/worker/engine-router.d.ts +75 -0
- package/dist/worker/engine-router.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +32 -11
- package/dist/worker/protocol.d.ts.map +1 -1
- package/dist/worker/sw-placement.d.ts +37 -0
- package/dist/worker/sw-placement.d.ts.map +1 -0
- package/package.json +4 -3
- package/skills/core/SKILL.md +15 -8
- package/skills/operating/SKILL.md +114 -34
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1246 -118
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +9 -2
- package/src/mutation.ts +67 -49
- package/src/mutations-api.ts +3 -3
- package/src/opfs-effects.ts +160 -0
- package/src/placement-probe.ts +168 -0
- package/src/schema.ts +17 -22
- package/src/store-boot.ts +343 -0
- package/src/store-lifecycle.ts +227 -0
- package/src/store-meta.ts +459 -0
- package/src/store-path.ts +197 -22
- package/src/sync/apply.ts +227 -89
- package/src/sync/index.ts +33 -9
- package/src/sync/shape-inbox.ts +1 -1
- package/src/sync/types.ts +3 -3
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +1675 -117
- package/src/worker/define-sync-worker.ts +810 -50
- package/src/worker/election-coordinator.ts +462 -0
- package/src/worker/engine-control.ts +379 -0
- package/src/worker/engine-router.ts +355 -0
- package/src/worker/live-query-manager.ts +10 -1
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +41 -10
- package/src/worker/sw-placement.ts +64 -0
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PGlite, 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,13 +18,33 @@ 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";
|
|
47
|
+
import { describeErrorChain } from "./error-chain";
|
|
28
48
|
import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
|
|
29
49
|
import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
|
|
30
50
|
import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
|
|
@@ -53,6 +73,7 @@ import {
|
|
|
53
73
|
type WriteUnit,
|
|
54
74
|
} from "./mutation";
|
|
55
75
|
import { createMutationsApi, type MutationsApi } from "./mutations-api";
|
|
76
|
+
import { createOpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
56
77
|
import {
|
|
57
78
|
buildDataExportCloneCleanupSql,
|
|
58
79
|
buildDataExportEnumHeaderSql,
|
|
@@ -67,6 +88,20 @@ import {
|
|
|
67
88
|
generateLocalSchemaSql,
|
|
68
89
|
} from "./schema";
|
|
69
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";
|
|
70
105
|
import {
|
|
71
106
|
classifyNonPersistentDataDir,
|
|
72
107
|
NonPersistentStoreError,
|
|
@@ -74,6 +109,7 @@ import {
|
|
|
74
109
|
readTestStoreMarker,
|
|
75
110
|
resolveStoreDataDir,
|
|
76
111
|
RestoreTargetExistsError,
|
|
112
|
+
storeIndexedDbDatabaseName,
|
|
77
113
|
storeTargetExists,
|
|
78
114
|
type StorePathInput,
|
|
79
115
|
} from "./store-path";
|
|
@@ -122,7 +158,35 @@ export {
|
|
|
122
158
|
type StoreExportOptions,
|
|
123
159
|
type StoreExportResult,
|
|
124
160
|
} from "./export-store";
|
|
161
|
+
export {
|
|
162
|
+
type AdoptionDeclaration,
|
|
163
|
+
type AdoptionEffects,
|
|
164
|
+
adoptionEligible,
|
|
165
|
+
type AdoptionOutcome,
|
|
166
|
+
runAdoptionTransition,
|
|
167
|
+
runManualAdoption,
|
|
168
|
+
} from "./adoption";
|
|
125
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";
|
|
126
190
|
export {
|
|
127
191
|
InvalidStorePathError,
|
|
128
192
|
NonPersistentStoreError,
|
|
@@ -146,6 +210,8 @@ export {
|
|
|
146
210
|
attachSyncClient,
|
|
147
211
|
type AttachSyncClientOptions,
|
|
148
212
|
provisionSyncWorker,
|
|
213
|
+
retireSyncWorkerHost,
|
|
214
|
+
type RetireSyncWorkerHostOptions,
|
|
149
215
|
} from "./worker/attach-sync-client";
|
|
150
216
|
export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
|
|
151
217
|
export {
|
|
@@ -168,6 +234,7 @@ export {
|
|
|
168
234
|
type BridgeEvent,
|
|
169
235
|
type BridgeMessageType,
|
|
170
236
|
type BridgePort,
|
|
237
|
+
type BridgeTransferable,
|
|
171
238
|
encodeEnvelope,
|
|
172
239
|
type ExportArtefactWire,
|
|
173
240
|
identityCodec,
|
|
@@ -276,6 +343,19 @@ export interface CreateClientPGliteOptions {
|
|
|
276
343
|
* asset load), so it never fails the create.
|
|
277
344
|
*/
|
|
278
345
|
bootAssets?: Promise<PgliteBootAssets>;
|
|
346
|
+
/**
|
|
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.
|
|
357
|
+
*/
|
|
358
|
+
durability?: StorageDurability;
|
|
279
359
|
/**
|
|
280
360
|
* @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
|
|
281
361
|
* scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
|
|
@@ -290,6 +370,73 @@ export interface CreateClientPGliteOptions {
|
|
|
290
370
|
* freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.
|
|
291
371
|
*/
|
|
292
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;
|
|
293
440
|
}
|
|
294
441
|
|
|
295
442
|
/**
|
|
@@ -298,16 +445,17 @@ export interface CreateClientPGliteOptions {
|
|
|
298
445
|
* consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
|
|
299
446
|
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
300
447
|
* instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
|
|
301
|
-
* hooks, journal recovery and
|
|
448
|
+
* hooks, journal recovery, and registry reconciliation, exactly as its own `storePath` path does.
|
|
302
449
|
*
|
|
303
|
-
* Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED
|
|
304
|
-
* 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}.
|
|
305
453
|
* Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests("x"))`) so a test can
|
|
306
454
|
* mint a memory store without naming a backend.
|
|
307
455
|
*
|
|
308
456
|
* The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
|
|
309
457
|
* dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
|
|
310
|
-
* initdb (+
|
|
458
|
+
* initdb (+ persistent-store open), which is the dominant cold-boot cost once the WASM is pre-warmed.
|
|
311
459
|
*
|
|
312
460
|
* `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
|
|
313
461
|
* rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
|
|
@@ -320,45 +468,686 @@ export async function createClientPGlite(
|
|
|
320
468
|
// then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
|
|
321
469
|
// empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
|
|
322
470
|
const normalised = normaliseStorePathInput(store);
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
//
|
|
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:".
|
|
326
490
|
const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
|
|
327
491
|
// Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the
|
|
328
492
|
// fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled
|
|
329
493
|
// result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
|
|
330
494
|
// pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
|
|
331
495
|
const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
|
|
332
|
-
|
|
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
|
|
501
|
+
// synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
|
|
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(
|
|
333
556
|
"boot pglite.create",
|
|
334
|
-
() =>
|
|
335
|
-
|
|
336
|
-
// (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So
|
|
337
|
-
// a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.
|
|
338
|
-
// the board's login-screen mint) carries no engine, no shape streams, and no Electric connections
|
|
339
|
-
// until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the
|
|
340
|
-
// `electric` namespace is provisioned later, exactly as the registry-derived schema is.
|
|
341
|
-
PGlite.create(dataDir, {
|
|
557
|
+
() => {
|
|
558
|
+
const createOptions: PGliteOptions = {
|
|
342
559
|
...(bootAssets ?? {}),
|
|
560
|
+
relaxedDurability,
|
|
343
561
|
// Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
|
|
344
562
|
// `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
|
|
345
563
|
// the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
|
|
346
564
|
// create (the store initdbs empty).
|
|
347
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`.
|
|
348
571
|
extensions: {
|
|
349
572
|
live,
|
|
350
573
|
},
|
|
351
|
-
}
|
|
352
|
-
|
|
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 },
|
|
353
581
|
// `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time
|
|
354
582
|
// extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).
|
|
355
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);
|
|
356
1145
|
}
|
|
357
1146
|
|
|
358
1147
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
359
1148
|
registry: TRegistry;
|
|
360
1149
|
electricUrl: string;
|
|
361
|
-
|
|
1150
|
+
batchWriteUrl: string;
|
|
362
1151
|
getAuthToken?: () => Promise<string | undefined>;
|
|
363
1152
|
/**
|
|
364
1153
|
* Static headers added to **every** read-shape and write request, alongside the per-request
|
|
@@ -381,13 +1170,36 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
381
1170
|
syncEnabled?: boolean;
|
|
382
1171
|
/**
|
|
383
1172
|
* The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
|
|
384
|
-
* 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
|
|
385
1175
|
* scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
|
|
386
1176
|
* at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product
|
|
387
1177
|
* configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from
|
|
388
1178
|
* `@pgxsinkit/client/testing` instead of naming one here.
|
|
389
1179
|
*/
|
|
390
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;
|
|
391
1203
|
/**
|
|
392
1204
|
* Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
|
|
393
1205
|
* into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
|
|
@@ -401,17 +1213,18 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
401
1213
|
pgliteBootAssets?: Promise<PgliteBootAssets>;
|
|
402
1214
|
resetSubscriptionKeys?: string[];
|
|
403
1215
|
prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
404
|
-
|
|
1216
|
+
prepareLocalDbAfterSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
405
1217
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
406
1218
|
onTableInitialSync?: (tableKey: string) => void;
|
|
407
1219
|
/**
|
|
408
1220
|
* A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
|
|
409
|
-
* 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
|
|
410
1222
|
* (journal recovery still runs, as it does on every path). Use it only when the caller has already
|
|
411
1223
|
* applied the registry schema itself. Contrast the three PGlite-provenance seams:
|
|
412
1224
|
* - {@link storePath} (default) — the client creates the store AND runs every post-create step.
|
|
413
1225
|
* - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
|
|
414
|
-
* 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.
|
|
415
1228
|
* - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
|
|
416
1229
|
*
|
|
417
1230
|
* A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
|
|
@@ -425,9 +1238,10 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
425
1238
|
/**
|
|
426
1239
|
* A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
|
|
427
1240
|
* earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
|
|
428
|
-
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and
|
|
429
|
-
*
|
|
430
|
-
* {@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
|
|
431
1245
|
* option's JSDoc for the three-way distinction.
|
|
432
1246
|
*
|
|
433
1247
|
* The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
|
|
@@ -450,15 +1264,17 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
450
1264
|
* - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the
|
|
451
1265
|
* resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the
|
|
452
1266
|
* remedy is a deliberate {@link SyncClient.destroy} of the existing store first.
|
|
453
|
-
* - **
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
*
|
|
1267
|
+
* - **Comes online iff the recovered journal is clean (ADR-0046).** If journal recovery found NOTHING to
|
|
1268
|
+
* quarantine — an empty recovered journal, the guaranteed-clean server-built bootstrap-artifact case — the
|
|
1269
|
+
* restore boots ONLINE, honouring {@link syncEnabled}/{@link autoSync} exactly as a normal boot (streams,
|
|
1270
|
+
* flush, convergence). If recovered mutations were quarantined, the boot stays OFFLINE (no shape streams,
|
|
1271
|
+
* no read fetch, no flush): the app inspects {@link SyncClient.diagnostics}, releases/discards the
|
|
1272
|
+
* quarantined rows, then a subsequent NORMAL boot of the (now-persisted) store brings sync online.
|
|
1273
|
+
* `loadDataDir` happens exactly once, on this restore boot. An explicit `syncEnabled: false` keeps it offline.
|
|
458
1274
|
* - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to
|
|
459
1275
|
* `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe
|
|
460
1276
|
* ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
|
|
461
|
-
* (`discardQuarantined`) them explicitly.
|
|
1277
|
+
* (`discardQuarantined`) them explicitly. When this pass quarantines nothing, the restore comes online (above).
|
|
462
1278
|
*
|
|
463
1279
|
* Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
|
|
464
1280
|
* creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
|
|
@@ -469,8 +1285,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
469
1285
|
* PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
|
|
470
1286
|
* and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
|
|
471
1287
|
* is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
|
|
472
|
-
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery,
|
|
473
|
-
*
|
|
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
|
|
474
1290
|
* catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
|
|
475
1291
|
* boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.
|
|
476
1292
|
*
|
|
@@ -506,10 +1322,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
506
1322
|
*/
|
|
507
1323
|
onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
|
|
508
1324
|
/**
|
|
509
|
-
* Invoked
|
|
510
|
-
*
|
|
511
|
-
* new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is
|
|
512
|
-
* 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.
|
|
513
1327
|
*/
|
|
514
1328
|
onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
|
|
515
1329
|
/**
|
|
@@ -539,6 +1353,22 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
539
1353
|
* absent → `"in-process"`. Not a behavior knob — it only labels the report.
|
|
540
1354
|
*/
|
|
541
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;
|
|
542
1372
|
/**
|
|
543
1373
|
* @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
|
|
544
1374
|
* minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
|
|
@@ -669,7 +1499,7 @@ export interface SubscribeLiveRowsInput {
|
|
|
669
1499
|
* same-named columns even in a plain query. When supplied, the seam wraps the query so every output
|
|
670
1500
|
* column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
|
|
671
1501
|
* by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then
|
|
672
|
-
* 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.
|
|
673
1503
|
*/
|
|
674
1504
|
fields?: readonly string[];
|
|
675
1505
|
/**
|
|
@@ -739,8 +1569,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
739
1569
|
[TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
|
|
740
1570
|
};
|
|
741
1571
|
/**
|
|
742
|
-
* Local-read readiness (ADR-0041): resolves once PGlite is open, the durable schema is
|
|
743
|
-
*
|
|
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
|
|
744
1574
|
* facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync
|
|
745
1575
|
* start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract
|
|
746
1576
|
* `createSyncClient()` (and, in stage 2, `attachSyncClient()`) resolves at exactly this stage; the write and
|
|
@@ -825,7 +1655,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
825
1655
|
) => Promise<void>;
|
|
826
1656
|
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;
|
|
827
1657
|
/**
|
|
828
|
-
* The registry-wide reactive mutation-status surface
|
|
1658
|
+
* The registry-wide reactive mutation-status surface: a global per-status summary and a
|
|
829
1659
|
* filtered normalized detail list over EVERY writable journal, each available one-shot or as a live
|
|
830
1660
|
* subscription. Identical on the in-process and worker-attached client. Render a global sync indicator with
|
|
831
1661
|
* ONE `subscribeSummary` instead of one journal live query per writable table; consumers never touch the
|
|
@@ -843,6 +1673,23 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
843
1673
|
rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
844
1674
|
/** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
|
|
845
1675
|
rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
1676
|
+
/**
|
|
1677
|
+
* @internal The worker host's guarded one-shot read seam (ADR-0032 decision 4): {@link rawQuery} PLUS the
|
|
1678
|
+
* ADR-0041 read gate and the ADR-0021 lazy-group guard, sharing one gate+guard core with the in-process
|
|
1679
|
+
* `query`/`queryRaw` builder path so the two entry points can never drift on guard semantics.
|
|
1680
|
+
* `defineSyncWorker` dispatches the `guardedQuery` RpcOp to this on its owned in-process client; the attach
|
|
1681
|
+
* client's Drizzle-over-bridge compiles the SQL on the tab and routes the read here so the guard runs
|
|
1682
|
+
* worker-side. Accepts the full PGlite {@link QueryOptions} (the worker re-applies drizzle's identity
|
|
1683
|
+
* parsers here — temporal OIDs + numeric[]) plus the raw-fragment `use` list. NOT part of the app-facing
|
|
1684
|
+
* read surface — reach for {@link query} / {@link queryRaw} instead; kept `@internal` (above) and excluded
|
|
1685
|
+
* from the generated API docs (typedoc excludeInternal).
|
|
1686
|
+
*/
|
|
1687
|
+
guardedRawQuery: (
|
|
1688
|
+
sql: string,
|
|
1689
|
+
params?: unknown[],
|
|
1690
|
+
options?: QueryOptions,
|
|
1691
|
+
use?: readonly SyncTableName<TRegistry>[],
|
|
1692
|
+
) => Promise<Results>;
|
|
846
1693
|
/**
|
|
847
1694
|
* Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
|
|
848
1695
|
* Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
|
|
@@ -1068,6 +1915,14 @@ export function replAdapter(
|
|
|
1068
1915
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
1069
1916
|
options: CreateSyncClientOptions<TRegistry>,
|
|
1070
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;
|
|
1071
1926
|
// Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
|
|
1072
1927
|
validateLiveQueryPolicy(options.liveQueries);
|
|
1073
1928
|
const status: SyncRuntimeStatus = {
|
|
@@ -1083,7 +1938,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1083
1938
|
});
|
|
1084
1939
|
|
|
1085
1940
|
// Staged boot readiness (ADR-0041). Three monotonic, idempotent stages resolved as the boot crosses them:
|
|
1086
|
-
// - `localReadReady`: local-read core done (schema
|
|
1941
|
+
// - `localReadReady`: local-read core done (schema + registry reconcile + drizzle facade) — zero network.
|
|
1087
1942
|
// - `writeReady`: mutation runtime + boot recovery (+ restore quarantine) done — enqueue is safe.
|
|
1088
1943
|
// - `bootSettled`: today's full resolution point (sync START done). The worker bridge awaits it (stage 1).
|
|
1089
1944
|
// Under the Option B contract this function RESOLVES at `localReadReady` and runs the write/sync tail in the
|
|
@@ -1112,7 +1967,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1112
1967
|
|
|
1113
1968
|
if (options.pgliteInstance && options.precreatedPglite) {
|
|
1114
1969
|
throw new Error(
|
|
1115
|
-
"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).",
|
|
1116
1971
|
);
|
|
1117
1972
|
}
|
|
1118
1973
|
|
|
@@ -1126,30 +1981,35 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1126
1981
|
);
|
|
1127
1982
|
}
|
|
1128
1983
|
|
|
1129
|
-
// Restore
|
|
1130
|
-
//
|
|
1131
|
-
//
|
|
1132
|
-
//
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
|
|
1140
|
-
// ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
|
|
1984
|
+
// Restore boots start offline and DEFER the sync-enable decision until AFTER journal recovery (ADR-0046,
|
|
1985
|
+
// refining ADR-0035 decision 6): a restore comes online iff recovery found NOTHING to quarantine — an empty
|
|
1986
|
+
// recovered journal, the guaranteed-clean server-built bootstrap-artifact case — and stays offline (today's
|
|
1987
|
+
// behaviour) when recovered mutations were quarantined, because a replayed write is unsafe without a dedupe
|
|
1988
|
+
// ledger. The decision is taken in the restore recovery block below (it needs the quarantine count) and
|
|
1989
|
+
// honours an explicit `syncEnabled: false`. A normal boot resolves its final value here, up front.
|
|
1990
|
+
let syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
|
|
1991
|
+
// ADR-0032 S4 overlap flag. A restore starts `syncEnabled: false` here, so it never takes the overlap
|
|
1992
|
+
// prefetch path (a restore also never presents a fresh spare store); the flag stays `false` for the whole
|
|
1993
|
+
// boot even when the restore later comes online (which uses the sequential sync-start path, not overlap).
|
|
1141
1994
|
const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
|
|
1142
1995
|
// How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a
|
|
1143
1996
|
// backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;
|
|
1144
1997
|
// everything else is a warm (existing persisted) store. Restore wins — a restore boot is never "fresh".
|
|
1145
1998
|
const storeKind: BootReport["storeKind"] = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
|
|
1146
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
|
+
|
|
1147
2006
|
// Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
|
|
1148
2007
|
// sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
|
|
1149
2008
|
const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
|
|
1150
|
-
mode:
|
|
2009
|
+
mode: bootMode,
|
|
1151
2010
|
freshStore: options.freshStore === true,
|
|
1152
2011
|
storeKind,
|
|
2012
|
+
...(engineHome != null ? { engineHome } : {}),
|
|
1153
2013
|
overlapPrefetch,
|
|
1154
2014
|
registryFingerprint: fingerprintRegistry(options.registry),
|
|
1155
2015
|
});
|
|
@@ -1175,21 +2035,48 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1175
2035
|
|
|
1176
2036
|
// Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
|
|
1177
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";
|
|
1178
2058
|
const createClientOptions: CreateClientPGliteOptions = {
|
|
1179
2059
|
...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
|
|
1180
2060
|
...(backendOverride ? { backendOverride } : {}),
|
|
2061
|
+
durability: resolvedDurability,
|
|
1181
2062
|
// Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
|
|
1182
2063
|
// mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned
|
|
1183
2064
|
// create — never the adopt paths, which leave `restoreFrom` unread.
|
|
1184
2065
|
...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),
|
|
1185
2066
|
};
|
|
1186
2067
|
const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
2068
|
+
let openedStorageBackend: NonNullable<BootReport["storageBackend"]> | undefined;
|
|
1187
2069
|
|
|
1188
2070
|
// Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
|
|
1189
2071
|
// brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
|
|
1190
|
-
// 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.
|
|
1191
2073
|
if (restoreBoot) {
|
|
1192
|
-
|
|
2074
|
+
const targetExists = await storeTargetExists(
|
|
2075
|
+
fallbackStorePath,
|
|
2076
|
+
backendOverride,
|
|
2077
|
+
bootHasOpfsSyncAccess ? { hasIndexedDb: true, hasOpfsSyncAccess: true } : undefined,
|
|
2078
|
+
);
|
|
2079
|
+
if (targetExists) {
|
|
1193
2080
|
throw new RestoreTargetExistsError(fallbackStorePath);
|
|
1194
2081
|
}
|
|
1195
2082
|
}
|
|
@@ -1197,11 +2084,55 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1197
2084
|
// caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
|
|
1198
2085
|
const timedCreate = async (): Promise<ClientPGlite> => {
|
|
1199
2086
|
const startedAt = performance.now();
|
|
1200
|
-
|
|
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
|
+
}
|
|
1201
2108
|
bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
|
|
1202
2109
|
return created;
|
|
1203
2110
|
};
|
|
1204
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
|
+
|
|
1205
2136
|
// Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
|
|
1206
2137
|
// acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the
|
|
1207
2138
|
// `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are
|
|
@@ -1210,17 +2141,89 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1210
2141
|
// `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).
|
|
1211
2142
|
const refuseIfNonPersistent = (instance: ClientPGlite): void => {
|
|
1212
2143
|
if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
|
|
1213
|
-
|
|
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);
|
|
1214
2152
|
if (observed !== null) throw new NonPersistentStoreError(observed);
|
|
1215
2153
|
};
|
|
1216
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
|
+
|
|
1217
2219
|
let pglite: ClientPGlite;
|
|
1218
2220
|
// Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates
|
|
1219
2221
|
// whether the provision stamp is honoured (ADR-0034).
|
|
1220
2222
|
let adoptedPrecreated = false;
|
|
1221
2223
|
if (options.pgliteInstance) {
|
|
1222
2224
|
// The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
|
|
1223
|
-
// (schema
|
|
2225
|
+
// (schema, prepare hooks, and reconciliation) — see the `pgliteInstance` JSDoc. No create here →
|
|
2226
|
+
// `pgliteCreateMs` null.
|
|
1224
2227
|
refuseIfNonPersistent(options.pgliteInstance);
|
|
1225
2228
|
pglite = options.pgliteInstance;
|
|
1226
2229
|
} else if (options.precreatedPglite) {
|
|
@@ -1242,11 +2245,38 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1242
2245
|
syncDebug("boot precreated pglite rejected — falling back to storePath create", {
|
|
1243
2246
|
error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
|
|
1244
2247
|
});
|
|
1245
|
-
pglite = await
|
|
2248
|
+
pglite = await openOwnedStore();
|
|
1246
2249
|
}
|
|
1247
2250
|
} else {
|
|
1248
|
-
pglite = await
|
|
2251
|
+
pglite = await openOwnedStore();
|
|
1249
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);
|
|
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);
|
|
1250
2280
|
|
|
1251
2281
|
// Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
|
|
1252
2282
|
// its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`
|
|
@@ -1266,7 +2296,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1266
2296
|
// extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
|
|
1267
2297
|
// `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
|
|
1268
2298
|
// structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
|
|
1269
|
-
// 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
|
|
1270
2300
|
// the extension provided it at create time. `engine.close` (the former extension close hook — abort every
|
|
1271
2301
|
// shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment
|
|
1272
2302
|
// `pglite.close()` used to trigger it.
|
|
@@ -1284,7 +2314,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1284
2314
|
// ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────
|
|
1285
2315
|
// On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape
|
|
1286
2316
|
// catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which
|
|
1287
|
-
// we resolve once schema exec + journal recovery +
|
|
2317
|
+
// we resolve once schema exec + journal recovery + registry reconciliation complete. The network then
|
|
1288
2318
|
// overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the
|
|
1289
2319
|
// `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact
|
|
1290
2320
|
// sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).
|
|
@@ -1345,7 +2375,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1345
2375
|
// letting the read cache silently diverge from the server. Sticky (see below).
|
|
1346
2376
|
status.phase = "degraded";
|
|
1347
2377
|
degradedReason = "commit";
|
|
1348
|
-
|
|
2378
|
+
// The cause chain, not just the wrapper: a drizzle "Failed query" message hides the actual
|
|
2379
|
+
// database error (SQLSTATE, detail) on `.cause`.
|
|
2380
|
+
status.lastError = describeErrorChain(error);
|
|
1349
2381
|
options.onStatusChange?.(status);
|
|
1350
2382
|
options.onSyncError?.(error);
|
|
1351
2383
|
},
|
|
@@ -1362,7 +2394,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1362
2394
|
// way then another reports the current cause (observability).
|
|
1363
2395
|
status.phase = "degraded";
|
|
1364
2396
|
degradedReason = "stream";
|
|
1365
|
-
status.lastError = error
|
|
2397
|
+
status.lastError = describeErrorChain(error);
|
|
1366
2398
|
options.onStatusChange?.(status);
|
|
1367
2399
|
},
|
|
1368
2400
|
// Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
|
|
@@ -1412,7 +2444,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1412
2444
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
1413
2445
|
}
|
|
1414
2446
|
|
|
1415
|
-
// Durable-schema fingerprint fast path
|
|
2447
|
+
// Durable-schema fingerprint fast path. The whole block stays inside the
|
|
1416
2448
|
// `schemaExec` phase so `schemaExecMs` remains comparable across the fast (skip) and full (replay) paths.
|
|
1417
2449
|
await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
|
|
1418
2450
|
// (2) The minimal bootstrap first — one small crossing so the `local_schema_fingerprint` read/write
|
|
@@ -1427,8 +2459,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1427
2459
|
// (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.
|
|
1428
2460
|
bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
|
|
1429
2461
|
} else {
|
|
1430
|
-
// (4b) Absent/mismatch → replay the durable schema, then stamp the fingerprint
|
|
1431
|
-
// (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.
|
|
1432
2463
|
await pglite.exec(generateDurableLocalSchemaSql(options.registry));
|
|
1433
2464
|
await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
|
|
1434
2465
|
bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
|
|
@@ -1442,9 +2473,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1442
2473
|
}
|
|
1443
2474
|
});
|
|
1444
2475
|
|
|
1445
|
-
if (options.
|
|
1446
|
-
const
|
|
1447
|
-
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));
|
|
1448
2479
|
}
|
|
1449
2480
|
}
|
|
1450
2481
|
|
|
@@ -1464,9 +2495,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1464
2495
|
const mutationRuntime = createMutationRuntime({
|
|
1465
2496
|
db: pglite,
|
|
1466
2497
|
registry: options.registry,
|
|
1467
|
-
|
|
2498
|
+
batchWriteUrl: options.batchWriteUrl,
|
|
1468
2499
|
// pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
|
|
1469
|
-
// 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.
|
|
1470
2501
|
ownsMetaTable: !options.pgliteInstance,
|
|
1471
2502
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
1472
2503
|
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
@@ -1489,7 +2520,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1489
2520
|
// Boot recovery (ADR-0005) driven by the durable recovery marker (slice 2), PLUS the restore quarantine
|
|
1490
2521
|
// (ADR-0035 decision 6, gated on `restoreBoot` inside `runBootRecovery`). Hoisted so the restore path runs
|
|
1491
2522
|
// it BEFORE read exposure (the ADR-0041 invariant) and the normal path defers it to the background write
|
|
1492
|
-
// tail. `runBootRecovery` owns the full decision — marker read, skip/
|
|
2523
|
+
// tail. `runBootRecovery` owns the full decision — marker read, skip/unconditional/transactional recovery, restore
|
|
1493
2524
|
// quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).
|
|
1494
2525
|
const runBootRecoveryStage = async (): Promise<void> => {
|
|
1495
2526
|
const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () =>
|
|
@@ -1498,9 +2529,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1498
2529
|
bootReportBuilder.setJournalRecovery(recoveryOutcome);
|
|
1499
2530
|
};
|
|
1500
2531
|
|
|
1501
|
-
// Store-version reconcile against the current registry fingerprint (ADR-0006). It reads the runtime's
|
|
1502
|
-
// journal stats to decide rebuild-vs-defer and `runtime.registryVersion` (static), so it needs only the
|
|
1503
|
-
// CONSTRUCTED runtime — not a completed recovery pass.
|
|
1504
2532
|
const runReconcileStage = async (): Promise<void> => {
|
|
1505
2533
|
if (options.pgliteInstance) return;
|
|
1506
2534
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
|
|
@@ -1514,19 +2542,28 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1514
2542
|
};
|
|
1515
2543
|
|
|
1516
2544
|
if (restoreBoot) {
|
|
1517
|
-
// Restore invariant (ADR-0041):
|
|
1518
|
-
//
|
|
1519
|
-
// every recovered row counts toward `owedMutations` (pending+sending+failed+quarantined) inside
|
|
1520
|
-
// `rebuildReadCacheOrDefer`, so a stale-fingerprint restore DEFERS the read-cache rebuild rather than
|
|
1521
|
-
// dropping the quarantined writes — unchanged from the pre-ADR-0041 recover→quarantine→reconcile order.
|
|
1522
|
-
// `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.
|
|
1523
2547
|
await runBootRecoveryStage();
|
|
2548
|
+
|
|
2549
|
+
// ADR-0046: with recovery + quarantine complete, decide whether this restore comes online. The restore
|
|
2550
|
+
// quarantine pass parked every recovered non-terminal write (pending/sending/failed) as `quarantined`, so a
|
|
2551
|
+
// zero quarantined count means the backup's journal was CLEAN — the server-built bootstrap-artifact case —
|
|
2552
|
+
// and sync may start exactly as a normal boot would. A non-zero count keeps the boot offline (the protective
|
|
2553
|
+
// ADR-0035 rule, now applied only where it protects) until the app releases the rows; a subsequent normal
|
|
2554
|
+
// boot then brings sync online. An explicit `syncEnabled: false` is always honoured (stays offline).
|
|
2555
|
+
const recoveredQuarantined = (await mutationRuntime.readMutationStats()).quarantinedCount;
|
|
2556
|
+
if (recoveredQuarantined === 0 && options.syncEnabled !== false) {
|
|
2557
|
+
syncEnabled = options.syncEnabled ?? true;
|
|
2558
|
+
syncDebug("boot restore comes online — recovered journal was clean (nothing to quarantine)");
|
|
2559
|
+
} else if (recoveredQuarantined > 0) {
|
|
2560
|
+
syncDebug(
|
|
2561
|
+
"boot restore stays offline — recovered journal mutations were quarantined; release/discard them and a subsequent normal boot brings sync online",
|
|
2562
|
+
{ quarantinedCount: recoveredQuarantined, syncEnabledOption: options.syncEnabled ?? null },
|
|
2563
|
+
);
|
|
2564
|
+
}
|
|
1524
2565
|
await runReconcileStage();
|
|
1525
2566
|
} else {
|
|
1526
|
-
// Normal boot (ADR-0041): reconcile is part of the local-read core and runs BEFORE recovery (which moves
|
|
1527
|
-
// to the write tail). The owed count already includes `sending`, so an UNRECOVERED crash journal defers a
|
|
1528
|
-
// rebuild exactly as a recovered one would (recovery only lifts `sending → pending`, both counted) — the
|
|
1529
|
-
// deferral outcome is byte-identical to the pre-ADR-0041 recover-then-reconcile order.
|
|
1530
2567
|
await runReconcileStage();
|
|
1531
2568
|
}
|
|
1532
2569
|
|
|
@@ -1565,6 +2602,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1565
2602
|
// manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
|
|
1566
2603
|
const quiesceTailForTeardown = async (): Promise<void> => {
|
|
1567
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);
|
|
1568
2608
|
// FIX 2: a stopped client can never reach `writeReady` / `ready`, so reject them (idempotent — a race with
|
|
1569
2609
|
// the tail's own resolve is settled first-wins; a normal stop AFTER boot is a no-op on the already-resolved
|
|
1570
2610
|
// promises) so a parked mutation or an `await ready` / `start()` fails FAST rather than hanging past
|
|
@@ -1616,11 +2656,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1616
2656
|
bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
|
|
1617
2657
|
bootReportBuilder.markSyncStartDone();
|
|
1618
2658
|
} else {
|
|
1619
|
-
// Sequential path (warm store / no fresh hint):
|
|
1620
|
-
//
|
|
1621
|
-
// After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
|
|
1622
|
-
// dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
|
|
1623
|
-
// 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).
|
|
1624
2661
|
const resetKeys =
|
|
1625
2662
|
versionEvent?.status === "rebuilt"
|
|
1626
2663
|
? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
|
|
@@ -1675,11 +2712,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1675
2712
|
resolveSyncWired();
|
|
1676
2713
|
};
|
|
1677
2714
|
|
|
1678
|
-
//
|
|
1679
|
-
//
|
|
1680
|
-
//
|
|
1681
|
-
// online
|
|
1682
|
-
|
|
2715
|
+
// Convergence driver (ADR-0035 decision 6 / ADR-0046): a restore boot that STAYS offline (recovered journal
|
|
2716
|
+
// quarantined) never stands up the driver, so an `autoSync` trigger drives NO flush/reconcile passes — the
|
|
2717
|
+
// quarantined rows must stay put until the app releases them and a normal boot goes online. A restore that
|
|
2718
|
+
// came online (clean recovered journal) is treated exactly like a normal online boot and DOES get the driver.
|
|
2719
|
+
// On every non-restore boot the gate is unchanged (`!restoreBoot` is true regardless of `syncEnabled`).
|
|
2720
|
+
if (options.autoSync && (!restoreBoot || syncEnabled)) {
|
|
1683
2721
|
convergenceDriver = createConvergenceDriver({
|
|
1684
2722
|
client: {
|
|
1685
2723
|
flush: () => mutationRuntime.flush(),
|
|
@@ -2069,19 +3107,41 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2069
3107
|
return { lazyTables };
|
|
2070
3108
|
};
|
|
2071
3109
|
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
): Promise<
|
|
3110
|
+
// The single gate+guard core shared by BOTH one-shot read entry points (the in-process drizzle-builder path
|
|
3111
|
+
// below and the worker-reachable `guardedRawQuery`), so the read gate and lazy-group guard can never drift
|
|
3112
|
+
// between modes. Given the query's compiled SQL (∪ `use`): read gate first, then the lazy-group guard.
|
|
3113
|
+
const gateAndGuardRead = async (sql: string, use?: readonly SyncTableName<TRegistry>[]): Promise<void> => {
|
|
2076
3114
|
// Read gate (ADR-0041): a query must not run against a store whose local-read core has not finished. On
|
|
2077
3115
|
// the in-process client this is a settled-promise await (the client is handed out at `localReadReady`),
|
|
2078
3116
|
// but it is cheap and keeps the read path safe if a caller retained a query builder across the boundary.
|
|
2079
3117
|
await localReadReady;
|
|
3118
|
+
// Lazy-group guard (ADR-0021): scan the compiled SQL (∪ `use`) for lazy relations it reads and activate +
|
|
3119
|
+
// await them before the query runs, so a lazy relation is never read empty/stale.
|
|
3120
|
+
await prepareQuery({ sql, ...(use ? { use } : {}) });
|
|
3121
|
+
};
|
|
3122
|
+
|
|
3123
|
+
const runGuardedQuery = async <TRows extends readonly unknown[]>(
|
|
3124
|
+
build: GuardedQueryFn<TRegistry, TRows>,
|
|
3125
|
+
use?: readonly SyncTableName<TRegistry>[],
|
|
3126
|
+
): Promise<TRows> => {
|
|
3127
|
+
// Building the drizzle query is pure construction (no DB I/O — it only compiles to SQL), so compile first,
|
|
3128
|
+
// then run the shared gate+guard on that SQL, then hand back the still-unexecuted builder (its `await`
|
|
3129
|
+
// executes via the local drizzle exactly as before — return shape unchanged).
|
|
2080
3130
|
const builder = build(client);
|
|
2081
|
-
await
|
|
3131
|
+
await gateAndGuardRead(builder.toSQL().sql, use);
|
|
2082
3132
|
return builder;
|
|
2083
3133
|
};
|
|
2084
3134
|
|
|
3135
|
+
// The worker host's guarded one-shot read (ADR-0032 decision 4) — `rawQuery` PLUS the shared gate+guard.
|
|
3136
|
+
// `defineSyncWorker`'s `guardedQuery` handler calls this on its owned in-process client (re-applying
|
|
3137
|
+
// drizzle's identity parsers — temporal OIDs + numeric[] — in `options` first, since that parser map cannot cross the bridge);
|
|
3138
|
+
// the attach client's Drizzle-over-bridge routes reads here. Returns the full PGlite `Results` so drizzle's
|
|
3139
|
+
// own result mapping runs on the tab.
|
|
3140
|
+
const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
|
|
3141
|
+
await gateAndGuardRead(sql, use);
|
|
3142
|
+
return pglite.query(sql, params as unknown[] | undefined, options);
|
|
3143
|
+
};
|
|
3144
|
+
|
|
2085
3145
|
// The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
|
|
2086
3146
|
// client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
|
|
2087
3147
|
// bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
|
|
@@ -2177,6 +3237,26 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2177
3237
|
// `stop()` (ADR-0040 decisions 1 & 6).
|
|
2178
3238
|
await liveManager.dispose();
|
|
2179
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
|
+
}
|
|
2180
3260
|
}),
|
|
2181
3261
|
dropReadCache: async () => {
|
|
2182
3262
|
// ADR-0041 (SHOULD-FIX 5): the drop+rebuild resets subscriptions and rewrites the read cache, so it must
|
|
@@ -2246,6 +3326,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2246
3326
|
// overlay involvement. The worker facade runs the identical call inside the worker's own client.
|
|
2247
3327
|
rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
|
|
2248
3328
|
rawExec: (sql, options) => pglite.exec(sql, options),
|
|
3329
|
+
// @internal: the guarded raw-SQL read the worker host dispatches `guardedQuery` to (ADR-0032 decision 4).
|
|
3330
|
+
guardedRawQuery,
|
|
2249
3331
|
query: (build) => runGuardedQuery(build),
|
|
2250
3332
|
queryRow: async (build) => {
|
|
2251
3333
|
const rows = await runGuardedQuery(build);
|
|
@@ -2278,7 +3360,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2278
3360
|
await localReadReady;
|
|
2279
3361
|
// Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
|
|
2280
3362
|
// temp-view creation (`column "title" specified more than once`) unless every output column has a
|
|
2281
|
-
// unique alias. No `fields` → SQL unchanged (
|
|
3363
|
+
// unique alias. No `fields` → SQL unchanged (the default name-keyed row shape). The wrap stays
|
|
2282
3364
|
// caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.
|
|
2283
3365
|
const materialSql = wrapLiveQueryForMaterialization(sql, fields);
|
|
2284
3366
|
// Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;
|
|
@@ -2410,8 +3492,22 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2410
3492
|
query: (sql, params) => pglite.query<Record<string, unknown>>(sql, params),
|
|
2411
3493
|
});
|
|
2412
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
|
+
|
|
2413
3509
|
// ─── Local-read core complete → resolve `localReadReady`, then run the write/sync tail in the background ──
|
|
2414
|
-
// (ADR-0041 Option B.) The durable schema
|
|
3510
|
+
// (ADR-0041 Option B.) The durable schema and registry reconciliation are complete, and the drizzle
|
|
2415
3511
|
// read facade + client are built — cached reads are safe now, with ZERO network. Stamp + resolve
|
|
2416
3512
|
// `localReadReady`; on a restore boot `writeReady` coincides (recovery + quarantine already ran in the core,
|
|
2417
3513
|
// before this read exposure — the ADR-0041 invariant). This function then RESOLVES at `localReadReady`.
|
|
@@ -2451,7 +3547,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2451
3547
|
// NIT 8: surface a signal beyond the stage rejections — move the runtime to `degraded` so a consumer
|
|
2452
3548
|
// watching `status`/`onStatusChange` sees the boot failed, not just an awaiter of a stage promise.
|
|
2453
3549
|
status.phase = "degraded";
|
|
2454
|
-
status.lastError =
|
|
3550
|
+
status.lastError = describeErrorChain(error);
|
|
2455
3551
|
options.onStatusChange?.(status);
|
|
2456
3552
|
rejectWriteReady(error);
|
|
2457
3553
|
rejectReady(error);
|
|
@@ -2519,22 +3615,54 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
|
2519
3615
|
}
|
|
2520
3616
|
|
|
2521
3617
|
/**
|
|
2522
|
-
* The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a
|
|
2523
|
-
* plus the registry views.
|
|
2524
|
-
*
|
|
2525
|
-
*
|
|
2526
|
-
*
|
|
3618
|
+
* The tab-side READ handles a worker-attached client exposes (ADR-0032 S2/decision 4): a Drizzle instance
|
|
3619
|
+
* plus the registry views. `createSyncClient`'s SAME builders, so a query built on either client compiles
|
|
3620
|
+
* identically. The `client` argument is the executor Drizzle runs against:
|
|
3621
|
+
* - Omit it (the default `{}` stub) for a BUILD-ONLY instance — Drizzle only compiles to SQL (`.toSQL()`)
|
|
3622
|
+
* and the stub is never invoked; used where execution happens elsewhere (e.g. the live-rows bridge).
|
|
3623
|
+
* - Pass a `ClientPGlite`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
|
|
3624
|
+
* that awaiting a builder executes through the bridge and Drizzle's own result mapping (relational/nested
|
|
3625
|
+
* queries included) runs on the tab — the one-shot read path `attachSyncClient` wires (ADR-0032 decision 4).
|
|
2527
3626
|
*/
|
|
2528
3627
|
export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
2529
3628
|
registry: TRegistry,
|
|
2530
|
-
|
|
2531
|
-
|
|
3629
|
+
client: ClientPGlite = {} as ClientPGlite,
|
|
3630
|
+
): {
|
|
3631
|
+
drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3632
|
+
views: RegistryViews<TRegistry>;
|
|
3633
|
+
/**
|
|
3634
|
+
* A drizzle-database FACTORY over this registry's schema (ADR-0032 decision 4): `(client) => db`, reusing
|
|
3635
|
+
* the schema + relations computed ONCE here so a caller can cheaply build additional per-executor databases
|
|
3636
|
+
* without recomputing them. `attachSyncClient` uses it to give each `queryRaw`/`queryRawRow` its OWN
|
|
3637
|
+
* bridge executor carrying that call's `use` — a scoped db, never a shared mutable stash (no read races).
|
|
3638
|
+
*/
|
|
3639
|
+
drizzleFor: (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3640
|
+
} {
|
|
3641
|
+
const drizzleFor = buildRegistryDrizzleFactory(registry);
|
|
2532
3642
|
return {
|
|
2533
|
-
drizzle:
|
|
3643
|
+
drizzle: drizzleFor(client),
|
|
2534
3644
|
views: buildViews(registry),
|
|
3645
|
+
drizzleFor,
|
|
2535
3646
|
};
|
|
2536
3647
|
}
|
|
2537
3648
|
|
|
3649
|
+
/**
|
|
3650
|
+
* Compute a registry's Drizzle schema + relations ONCE and return a `(client) => db` factory over them
|
|
3651
|
+
* (ADR-0032 decision 4). Splitting this out of {@link buildRegistryReadHandles} lets `attachSyncClient` build
|
|
3652
|
+
* one base bridge database plus a fresh per-read database (each over its own executor) without paying the
|
|
3653
|
+
* schema/relations construction on every read — only the `client` binding differs between them.
|
|
3654
|
+
*/
|
|
3655
|
+
function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
|
|
3656
|
+
registry: TRegistry,
|
|
3657
|
+
): (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>> {
|
|
3658
|
+
const relations = defineRelations(buildSchema(registry)) as RegistryRelations<TRegistry>;
|
|
3659
|
+
const createDatabase = drizzle as unknown as (config: {
|
|
3660
|
+
client: ClientPGlite;
|
|
3661
|
+
relations: RegistryRelations<TRegistry>;
|
|
3662
|
+
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3663
|
+
return (client) => createDatabase({ client, relations });
|
|
3664
|
+
}
|
|
3665
|
+
|
|
2538
3666
|
function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
|
|
2539
3667
|
registry: TRegistry,
|
|
2540
3668
|
electricUrl: string,
|