@pgxsinkit/client 0.2.1 → 0.2.3
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/dist/boot-report.d.ts +3 -3
- package/dist/index.d.ts +35 -119
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +254 -391
- package/dist/index.js.map +14 -15
- package/dist/opfs-effects.d.ts +1 -1
- package/dist/store-boot.d.ts +82 -18
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-lifecycle.d.ts +5 -66
- package/dist/store-lifecycle.d.ts.map +1 -1
- package/dist/store-meta.d.ts +20 -21
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +53 -7
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +1 -12
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +13 -0
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/dist/worker/engine-router.d.ts +21 -5
- package/dist/worker/engine-router.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +1 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +3 -3
- package/skills/core/SKILL.md +3 -2
- package/skills/operating/SKILL.md +50 -12
- package/src/boot-report.ts +3 -3
- package/src/index.ts +159 -486
- package/src/opfs-effects.ts +2 -2
- package/src/store-boot.ts +183 -71
- package/src/store-lifecycle.ts +12 -96
- package/src/store-meta.ts +33 -33
- package/src/worker/attach-sync-client.ts +199 -22
- package/src/worker/define-sync-worker.ts +94 -26
- package/src/worker/engine-control.ts +12 -0
- package/src/worker/engine-router.ts +176 -21
- package/src/worker/protocol.ts +8 -1
- package/dist/adoption.d.ts +0 -118
- package/dist/adoption.d.ts.map +0 -1
- package/src/adoption.ts +0 -275
package/src/index.ts
CHANGED
|
@@ -34,15 +34,6 @@ import {
|
|
|
34
34
|
// mocking `@electric-sql/pglite` never evaluates the factory's `class ... extends PGlite` module top level.
|
|
35
35
|
import type { CreateOpfsRepackedPGliteOptions, OpfsRepackedPGlite } from "@pgxsinkit/pglite-opfs-repacked";
|
|
36
36
|
|
|
37
|
-
import {
|
|
38
|
-
type AdoptionDeclaration,
|
|
39
|
-
type AdoptionEffects,
|
|
40
|
-
adoptionEligible,
|
|
41
|
-
type AdoptionOutcome,
|
|
42
|
-
buildAdoptionEffects,
|
|
43
|
-
runAdoptionTransition,
|
|
44
|
-
runManualAdoption,
|
|
45
|
-
} from "./adoption";
|
|
46
37
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
47
38
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
48
39
|
import { syncDebug, timeAsync } from "./debug";
|
|
@@ -91,17 +82,18 @@ import {
|
|
|
91
82
|
} from "./schema";
|
|
92
83
|
import { startConfiguredSync } from "./shape-sync";
|
|
93
84
|
import {
|
|
94
|
-
|
|
85
|
+
resolveDeniedBootAuthority,
|
|
86
|
+
type ResolveStoreBootOptions,
|
|
95
87
|
resolveStoreBoot,
|
|
96
88
|
type ResolvedStorageBackend,
|
|
97
89
|
type StoreBootResolution,
|
|
98
90
|
} from "./store-boot";
|
|
99
91
|
import { runCommitmentBarrier } from "./store-lifecycle";
|
|
100
92
|
import {
|
|
101
|
-
|
|
93
|
+
META_STORE_UNAVAILABLE,
|
|
94
|
+
readStoreMetaRecord,
|
|
102
95
|
type StoreBootVerdict,
|
|
103
96
|
type StoreMetaDeps,
|
|
104
|
-
type StoreMetaPhase,
|
|
105
97
|
writeStoreMetaRecord,
|
|
106
98
|
} from "./store-meta";
|
|
107
99
|
import {
|
|
@@ -111,7 +103,6 @@ import {
|
|
|
111
103
|
readTestStoreMarker,
|
|
112
104
|
resolveStoreDataDir,
|
|
113
105
|
RestoreTargetExistsError,
|
|
114
|
-
storeIndexedDbDatabaseName,
|
|
115
106
|
storeTargetExists,
|
|
116
107
|
type StorePathInput,
|
|
117
108
|
} from "./store-path";
|
|
@@ -160,19 +151,12 @@ export {
|
|
|
160
151
|
type StoreExportOptions,
|
|
161
152
|
type StoreExportResult,
|
|
162
153
|
} from "./export-store";
|
|
163
|
-
export {
|
|
164
|
-
type AdoptionDeclaration,
|
|
165
|
-
type AdoptionEffects,
|
|
166
|
-
adoptionEligible,
|
|
167
|
-
type AdoptionOutcome,
|
|
168
|
-
runAdoptionTransition,
|
|
169
|
-
runManualAdoption,
|
|
170
|
-
} from "./adoption";
|
|
171
154
|
export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
|
|
172
155
|
export {
|
|
173
156
|
destroyStoreArtifacts,
|
|
174
157
|
type ElectedEngineWorker,
|
|
175
158
|
ElectedEngineUnconstructibleError,
|
|
159
|
+
ProvisionExpiredError,
|
|
176
160
|
quiesceStoreWorker,
|
|
177
161
|
StoreDestroyRefusedError,
|
|
178
162
|
type StoreDestructionRetryOptions,
|
|
@@ -189,6 +173,10 @@ export {
|
|
|
189
173
|
} from "./worker/engine-control";
|
|
190
174
|
export { createOpfsEffects, type OpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
191
175
|
export {
|
|
176
|
+
COMMITTED_STORE_UNREACHABLE_CODE,
|
|
177
|
+
CommittedStoreUnreachableError,
|
|
178
|
+
committedStoreUnreachableFromWire,
|
|
179
|
+
type CommittedStoreUnreachableWire,
|
|
192
180
|
resolveStoreBoot,
|
|
193
181
|
type ResolvedStorageBackend,
|
|
194
182
|
type ResolveStoreBootOptions,
|
|
@@ -423,6 +411,15 @@ const OPFS_STORE_EXTENT_SIZE = 65536;
|
|
|
423
411
|
*/
|
|
424
412
|
const OPFS_REPACKED_PERSISTENT = Symbol.for("pgxsinkit.opfsRepackedPersistent");
|
|
425
413
|
|
|
414
|
+
/**
|
|
415
|
+
* Was this instance minted by the opfs-repacked factory ({@link OPFS_REPACKED_PERSISTENT})? The brand is the
|
|
416
|
+
* ONLY proof available for an adopted instance: an opfs-repacked store reports no `dataDir`, so nothing else
|
|
417
|
+
* distinguishes it from a BYO idb/file/memory instance — which carries no OPFS commitment machinery at all.
|
|
418
|
+
*/
|
|
419
|
+
function isOpfsRepackedPersistent(instance: ClientPGlite): boolean {
|
|
420
|
+
return (instance as Record<symbol, unknown>)[OPFS_REPACKED_PERSISTENT] === true;
|
|
421
|
+
}
|
|
422
|
+
|
|
426
423
|
/**
|
|
427
424
|
* Open the opfs-repacked factory with bounded retries (3) and a small linear backoff for transient failures,
|
|
428
425
|
* then propagate the last error — a committed store's final failure is HARD, and an uncommitted candidate's
|
|
@@ -475,12 +472,15 @@ export async function createClientPGlite(
|
|
|
475
472
|
const normalised = normaliseStorePathInput(store);
|
|
476
473
|
const storePath = normalised.storePath;
|
|
477
474
|
const backendOverride = options?.backendOverride ?? normalised.backendOverride;
|
|
478
|
-
// An eager precreate is itself a store mint
|
|
479
|
-
//
|
|
480
|
-
//
|
|
481
|
-
//
|
|
475
|
+
// An eager precreate is itself a store mint, so it passes the SAME pre-mint meta gate the ordinary
|
|
476
|
+
// createSyncClient path does before a denied browser home opens an IDB store: settle any durable `deleting`
|
|
477
|
+
// authority, retire an unexposed `opfs-candidate`, and REFUSE an `opfs-committed` store outright ({@link
|
|
478
|
+
// CommittedStoreUnreachableError}) — an eager tab-side precreate must never be the thing that mints an empty
|
|
479
|
+
// sibling over the committed store, nor one exposed beneath a record still claiming a candidate.
|
|
480
|
+
// Keeping this at the documented precreate factory protects callers outside defineSyncWorker; the worker
|
|
481
|
+
// provision handler carries the same guard separately because it permits a caller-supplied createPglite factory.
|
|
482
482
|
if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
|
|
483
|
-
await
|
|
483
|
+
await resolveDeniedBootAuthority(storePath);
|
|
484
484
|
}
|
|
485
485
|
// Derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. Browser/worker → `idb://`,
|
|
486
486
|
// Bun/Node → `file://`, the sanctioned test lane → `memory://`. A scheme-bearing/empty storePath throws here.
|
|
@@ -589,303 +589,21 @@ export async function createClientPGlite(
|
|
|
589
589
|
return pglite;
|
|
590
590
|
}
|
|
591
591
|
|
|
592
|
-
// ─── ADR-0049 step 11b: adoption boot wiring (declaration-gated) ──────────────────────────────────────
|
|
593
|
-
// The pure adoption orchestrator (`adoption.ts`, step 11a) is effect-injected; here we build the REAL effects
|
|
594
|
-
// and CALL the transition at the right point in the boot. The transition runs BEFORE any engine is exposed
|
|
595
|
-
// (invariant 3 — pre-expose exclusivity), consults the declaration FIRST (invariant 4 — default off), and
|
|
596
|
-
// deletes the idb predecessor ONLY after the commitment barrier publishes (invariants 3/4).
|
|
597
|
-
|
|
598
|
-
/**
|
|
599
|
-
* A store is being actively held by a live in-process client. The manual {@link adoptStore} API is a
|
|
600
|
-
* CREATION-PATH operation (like `restoreFrom`): it must be called INSTEAD of {@link createSyncClient}, never
|
|
601
|
-
* against a store an open client already owns — an idb→opfs migration under a live engine would strand the
|
|
602
|
-
* engine's writes. Detected via a module-level live-store registry (every {@link createSyncClient} that mints a
|
|
603
|
-
* client-owned store registers its path and unregisters on `stop()`/`destroy()`).
|
|
604
|
-
*/
|
|
605
|
-
export class StoreInUseError extends Error {
|
|
606
|
-
constructor(storePath: string) {
|
|
607
|
-
super(
|
|
608
|
-
`[pgxsinkit] adoptStore(${JSON.stringify(storePath)}) refused: a live client is currently holding this ` +
|
|
609
|
-
"store. Adoption is a creation-path migration — call it INSTEAD of createSyncClient, before any client " +
|
|
610
|
-
"opens the store (stop/destroy the existing client first).",
|
|
611
|
-
);
|
|
612
|
-
this.name = "StoreInUseError";
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/** The paths of stores currently held by a live in-process client — the {@link adoptStore} live-store guard. */
|
|
617
|
-
const liveStorePaths = new Set<string>();
|
|
618
|
-
|
|
619
|
-
/** Internal-only marker for the live adoption executor's inner candidate boot. Never exported or consumer-set. */
|
|
620
|
-
const ADOPTION_CANDIDATE_BUILD: unique symbol = Symbol("pgxsinkit.adoptionCandidateBuild");
|
|
621
|
-
type AdoptionCandidateBuildOptions = { [ADOPTION_CANDIDATE_BUILD]?: true };
|
|
622
|
-
/** Internal-only PGlite boundary used by the real adoption recursion test; never exported or consumer-set. */
|
|
623
|
-
const INTERNAL_PGLITE_CREATE: unique symbol = Symbol("pgxsinkit.internalPgliteCreate");
|
|
624
|
-
type InternalPgliteCreateOptions = { [INTERNAL_PGLITE_CREATE]?: typeof createClientPGlite };
|
|
625
|
-
|
|
626
|
-
/**
|
|
627
|
-
* @internal Injectable seams for the boot-time adoption decision (step 11b). Real defaults in production; unit
|
|
628
|
-
* tests inject fakes so the wiring is exercised without real IndexedDB/OPFS/WASM. Shared by the automatic boot
|
|
629
|
-
* path ({@link runBootAdoption}) and the manual {@link adoptStore} API.
|
|
630
|
-
*/
|
|
631
|
-
export interface AdoptionWiringSeams {
|
|
632
|
-
/** Non-creating recordless idb existence check (adoption only ever migrates an EXISTING idb store). */
|
|
633
|
-
idbStoreExists?: (storePath: string) => Promise<boolean>;
|
|
634
|
-
/** The boot classifier + executor (`store-boot.ts`) — its verdict drives {@link adoptionEligible}. */
|
|
635
|
-
resolveStoreBoot?: (storePath: string) => Promise<StoreBootResolution>;
|
|
636
|
-
/** The real {@link AdoptionEffects} factory; injected in tests with recording fakes. */
|
|
637
|
-
buildEffects?: (storePath: string) => AdoptionEffects;
|
|
638
|
-
/** Diagnostics sink; defaults to the boot debug rail. */
|
|
639
|
-
log?: (message: string, data?: Record<string, unknown>) => void;
|
|
640
|
-
/** The store-meta IndexedDB seam (defaults to `globalThis.indexedDB`). */
|
|
641
|
-
meta?: StoreMetaDeps;
|
|
642
|
-
/** The OPFS root seam (defaults to `navigator.storage.getDirectory`). */
|
|
643
|
-
opfs?: OpfsEffectsDeps;
|
|
644
|
-
/** The external PGlite create boundary; the real adoption transition and inner createSyncClient remain intact. */
|
|
645
|
-
createPglite?: typeof createClientPGlite;
|
|
646
|
-
/** The live-store guard the manual {@link adoptStore} consults (defaults to the module-level registry). */
|
|
647
|
-
isStoreLive?: (storePath: string) => boolean;
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
/** The bootstrap context an adoption transition's real effects need (registry + endpoints + auth + gate). */
|
|
651
|
-
interface AdoptionBootContext<TRegistry extends SyncTableRegistry> {
|
|
652
|
-
registry: TRegistry;
|
|
653
|
-
electricUrl: string;
|
|
654
|
-
batchWriteUrl: string;
|
|
655
|
-
getAuthToken?: () => Promise<string | undefined>;
|
|
656
|
-
requestHeaders?: Record<string, string>;
|
|
657
|
-
/** The effective app-level sync toggle — a `false` here fails the gate (adoption cannot reconstruct offline-by-config). */
|
|
658
|
-
syncEnabled: boolean;
|
|
659
|
-
/** Bounded wait for the eager Consistency groups' initial catch-up before the gate fails (offline/unauthorized). */
|
|
660
|
-
gateDeadlineMs?: number;
|
|
661
|
-
meta?: StoreMetaDeps;
|
|
662
|
-
opfs?: OpfsEffectsDeps;
|
|
663
|
-
createPglite?: typeof createClientPGlite;
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
/** Delete-if-present the store's PGlite idb database; only `onsuccess` proves completion. */
|
|
667
|
-
function deleteAdoptionIdbPredecessor(storePath: string, meta?: StoreMetaDeps): Promise<void> {
|
|
668
|
-
const idb =
|
|
669
|
-
meta != null && "indexedDB" in meta
|
|
670
|
-
? (meta.indexedDB as unknown as IdbDeleteLike | undefined)
|
|
671
|
-
: (globalThis as { indexedDB?: IdbDeleteLike }).indexedDB;
|
|
672
|
-
if (idb?.deleteDatabase == null) return Promise.resolve();
|
|
673
|
-
const name = storeIndexedDbDatabaseName(storePath);
|
|
674
|
-
return new Promise<void>((resolve, reject) => {
|
|
675
|
-
let settled = false;
|
|
676
|
-
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
677
|
-
const finish = (error?: unknown) => {
|
|
678
|
-
if (settled) return;
|
|
679
|
-
settled = true;
|
|
680
|
-
if (timeout !== undefined) clearTimeout(timeout);
|
|
681
|
-
if (error === undefined) resolve();
|
|
682
|
-
else reject(error);
|
|
683
|
-
};
|
|
684
|
-
let request: {
|
|
685
|
-
error?: unknown;
|
|
686
|
-
onsuccess: (() => void) | null;
|
|
687
|
-
onerror: (() => void) | null;
|
|
688
|
-
onblocked?: (() => void) | null;
|
|
689
|
-
};
|
|
690
|
-
try {
|
|
691
|
-
request = idb.deleteDatabase(name);
|
|
692
|
-
} catch (error) {
|
|
693
|
-
finish(error);
|
|
694
|
-
return;
|
|
695
|
-
}
|
|
696
|
-
request.onsuccess = () => finish();
|
|
697
|
-
request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
|
|
698
|
-
// `blocked` is nonterminal: the queued request may still succeed after the blocker closes. Do not lie to
|
|
699
|
-
// the adoption transition by reporting predecessor cleanup complete before `onsuccess`.
|
|
700
|
-
request.onblocked = () => undefined;
|
|
701
|
-
timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5_000);
|
|
702
|
-
});
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
/** The minimal structural `indexedDB.deleteDatabase` surface (no DOM lib) — mirrors `store-boot.ts`. */
|
|
706
|
-
interface IdbDeleteLike {
|
|
707
|
-
deleteDatabase(name: string): {
|
|
708
|
-
error?: unknown;
|
|
709
|
-
onsuccess: (() => void) | null;
|
|
710
|
-
onerror: (() => void) | null;
|
|
711
|
-
onblocked?: (() => void) | null;
|
|
712
|
-
};
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
/**
|
|
716
|
-
* Build the REAL {@link AdoptionEffects} the transition drives (step 11b). The idb engine is booted PRE-EXPOSE
|
|
717
|
-
* (never surfaced) solely to read the drain journal; the opfs candidate is built via the normal server bootstrap
|
|
718
|
-
* (`createSyncClient` with `syncEnabled: true`, `freshStore: true`, adoption OFF so it never recurses) and gated
|
|
719
|
-
* on the eager Consistency groups' catch-up; the shared commitment barrier (`runCommitmentBarrier`) commits it;
|
|
720
|
-
* only THEN is the idb predecessor deleted.
|
|
721
|
-
*/
|
|
722
|
-
function buildRealAdoptionEffects<TRegistry extends SyncTableRegistry>(
|
|
723
|
-
storePath: string,
|
|
724
|
-
ctx: AdoptionBootContext<TRegistry>,
|
|
725
|
-
): AdoptionEffects {
|
|
726
|
-
const opfs = createOpfsEffects(storePath, ctx.opfs);
|
|
727
|
-
const createPglite = ctx.createPglite ?? createClientPGlite;
|
|
728
|
-
const setPhase = (phase: StoreMetaPhase): Promise<void> =>
|
|
729
|
-
writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, ctx.meta);
|
|
730
|
-
return buildAdoptionEffects({
|
|
731
|
-
async readIdbJournal() {
|
|
732
|
-
// Open the idb engine PRE-EXPOSE (strict durability, no opfs grant → idb backend) solely to read the drain
|
|
733
|
-
// journal. Never surfaced to tabs (invariant 3). Because this is a READ-ONLY drain probe (no write ever
|
|
734
|
-
// reaches it), the engine is CLOSED here — releasing every idb handle so a deferred (`journal-owed`) boot
|
|
735
|
-
// can re-open the store cleanly, and so the drained path deletes the idb database with nothing holding it.
|
|
736
|
-
// `strictSyncAndCloseIdb` is therefore a no-op below: the "strict close" is trivially satisfied — an
|
|
737
|
-
// unwritten engine has nothing to flush, and the handle is already released.
|
|
738
|
-
const idbPglite = await createPglite(storePath, { durability: "strict" });
|
|
739
|
-
try {
|
|
740
|
-
const runtime = createMutationRuntime({
|
|
741
|
-
db: idbPglite,
|
|
742
|
-
registry: ctx.registry,
|
|
743
|
-
batchWriteUrl: ctx.batchWriteUrl,
|
|
744
|
-
ownsMetaTable: true,
|
|
745
|
-
});
|
|
746
|
-
const stats = await runtime.readMutationStats();
|
|
747
|
-
return {
|
|
748
|
-
pending: stats.pendingCount,
|
|
749
|
-
sending: stats.sendingCount,
|
|
750
|
-
acked: stats.ackedCount,
|
|
751
|
-
failed: stats.failedCount,
|
|
752
|
-
quarantined: stats.quarantinedCount,
|
|
753
|
-
conflicted: stats.conflictedCount,
|
|
754
|
-
rejected: stats.rejectedCount,
|
|
755
|
-
};
|
|
756
|
-
} finally {
|
|
757
|
-
await idbPglite.close();
|
|
758
|
-
}
|
|
759
|
-
},
|
|
760
|
-
setPhase,
|
|
761
|
-
async buildCandidate() {
|
|
762
|
-
// Adoption reconstructs from the server — a sync-disabled boot cannot: fail the gate BEFORE minting.
|
|
763
|
-
if (!ctx.syncEnabled) {
|
|
764
|
-
throw new Error(
|
|
765
|
-
"[pgxsinkit] adoption gate unmet: sync is disabled (`syncEnabled: false`), so the opfs successor " +
|
|
766
|
-
"cannot be reconstructed online. The idb store stays authoritative.",
|
|
767
|
-
);
|
|
768
|
-
}
|
|
769
|
-
// Build the opfs candidate via the NORMAL server bootstrap path (its own `createClientPGlite` mints the
|
|
770
|
-
// opfs store at the store directory). `freshStore: true` overlaps catch-up with the local phases; adoption
|
|
771
|
-
// is OFF so this never recurses; the phase stays `adopting` (set by the caller) for crash recovery.
|
|
772
|
-
const candidate = await createSyncClient<TRegistry>({
|
|
773
|
-
registry: ctx.registry,
|
|
774
|
-
electricUrl: ctx.electricUrl,
|
|
775
|
-
batchWriteUrl: ctx.batchWriteUrl,
|
|
776
|
-
storePath,
|
|
777
|
-
hasOpfsSyncAccess: true,
|
|
778
|
-
freshStore: true,
|
|
779
|
-
syncEnabled: true,
|
|
780
|
-
// Durability is registry-declared (ADR-0047): this candidate boot resolves it from `ctx.registry`, the
|
|
781
|
-
// SAME registry as the store it succeeds, so the opfs successor is minted under the declared mode.
|
|
782
|
-
[ADOPTION_CANDIDATE_BUILD]: true,
|
|
783
|
-
[INTERNAL_PGLITE_CREATE]: createPglite,
|
|
784
|
-
...(ctx.getAuthToken ? { getAuthToken: ctx.getAuthToken } : {}),
|
|
785
|
-
...(ctx.requestHeaders ? { requestHeaders: ctx.requestHeaders } : {}),
|
|
786
|
-
} as CreateSyncClientOptions<TRegistry> & AdoptionCandidateBuildOptions & InternalPgliteCreateOptions);
|
|
787
|
-
const strictSync = (candidate.pglite as unknown as { strictSync?: () => Promise<void> }).strictSync;
|
|
788
|
-
if (typeof strictSync !== "function") {
|
|
789
|
-
await candidate.stop().catch(() => undefined);
|
|
790
|
-
throw new Error(
|
|
791
|
-
"[pgxsinkit] adoption: the candidate store does not expose `strictSync()` — the commitment barrier " +
|
|
792
|
-
"requires an OPFS-repacked engine (data-before-authority, invariant 3).",
|
|
793
|
-
);
|
|
794
|
-
}
|
|
795
|
-
return {
|
|
796
|
-
ready: candidate.ready,
|
|
797
|
-
strictSync: () => strictSync.call(candidate.pglite),
|
|
798
|
-
close: () => candidate.stop(),
|
|
799
|
-
};
|
|
800
|
-
},
|
|
801
|
-
publishSentinel: () => opfs.publishSentinel(),
|
|
802
|
-
deleteSentinel: () => opfs.deleteSentinel(),
|
|
803
|
-
deleteStoreDirectory: () => opfs.deleteStoreDirectory(),
|
|
804
|
-
deleteIdbPredecessor: () => deleteAdoptionIdbPredecessor(storePath, ctx.meta),
|
|
805
|
-
...(ctx.gateDeadlineMs != null ? { gateDeadlineMs: ctx.gateDeadlineMs } : {}),
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
/** The default real seams for the adoption boot decision (production wiring). */
|
|
810
|
-
function realAdoptionSeams<TRegistry extends SyncTableRegistry>(
|
|
811
|
-
ctx: AdoptionBootContext<TRegistry>,
|
|
812
|
-
seams?: AdoptionWiringSeams,
|
|
813
|
-
): Required<Pick<AdoptionWiringSeams, "idbStoreExists" | "resolveStoreBoot" | "buildEffects" | "log">> {
|
|
814
|
-
return {
|
|
815
|
-
idbStoreExists: seams?.idbStoreExists ?? ((sp: string) => defaultIdbStoreExists(sp, ctx.meta)),
|
|
816
|
-
resolveStoreBoot:
|
|
817
|
-
seams?.resolveStoreBoot ??
|
|
818
|
-
((sp: string) =>
|
|
819
|
-
resolveStoreBoot(sp, {
|
|
820
|
-
hasOpfsSyncAccess: true,
|
|
821
|
-
...(ctx.meta || ctx.opfs
|
|
822
|
-
? { deps: { ...(ctx.meta ? { meta: ctx.meta } : {}), ...(ctx.opfs ? { opfs: ctx.opfs } : {}) } }
|
|
823
|
-
: {}),
|
|
824
|
-
})),
|
|
825
|
-
buildEffects: seams?.buildEffects ?? ((sp: string) => buildRealAdoptionEffects(sp, ctx)),
|
|
826
|
-
log: seams?.log ?? ((message, data) => syncDebug(message, data)),
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
/**
|
|
831
|
-
* @internal The boot-time AUTOMATIC adoption decision (step 11b). Returns whether the subsequent client-owned
|
|
832
|
-
* mint should open the OPFS backend (`bootHasOpfs`) after any adoption transition ran. Adoption ONLY ever
|
|
833
|
-
* migrates an EXISTING idb store (a committed-opfs or virgin store has no idb predecessor), so a non-creating
|
|
834
|
-
* idb existence check gates the whole path; then the boot classifier's verdict drives {@link adoptionEligible}.
|
|
835
|
-
* On `adopted: true` the opfs successor is committed and the mint opens it; on any `adopted: false` (owed
|
|
836
|
-
* journal / gate unmet / barrier failed) the idb store stays authoritative and the mint opens idb.
|
|
837
|
-
*/
|
|
838
|
-
export async function runBootAdoption<TRegistry extends SyncTableRegistry>(
|
|
839
|
-
storePath: string,
|
|
840
|
-
declaration: AdoptionDeclaration,
|
|
841
|
-
ctx: AdoptionBootContext<TRegistry>,
|
|
842
|
-
seamsOverride?: AdoptionWiringSeams,
|
|
843
|
-
): Promise<{ bootHasOpfs: boolean; outcome?: AdoptionOutcome }> {
|
|
844
|
-
const seams = realAdoptionSeams(ctx, seamsOverride);
|
|
845
|
-
// Adoption migrates an EXISTING idb store; nothing to adopt otherwise (committed-opfs / virgin have no idb).
|
|
846
|
-
if (!(await seams.idbStoreExists(storePath))) return { bootHasOpfs: true };
|
|
847
|
-
const resolution = await seams.resolveStoreBoot(storePath);
|
|
848
|
-
const verdict = resolution.verdict;
|
|
849
|
-
if (verdict === undefined || !adoptionEligible(declaration, verdict, true)) {
|
|
850
|
-
// The classifier already executed any recovery (e.g. an interrupted adoption). Honour its resolved backend.
|
|
851
|
-
const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
|
|
852
|
-
seams.log("boot adoption not eligible — using the classifier's resolved backend", {
|
|
853
|
-
action: verdict?.action,
|
|
854
|
-
storageBackend: resolution.storageBackend,
|
|
855
|
-
});
|
|
856
|
-
return { bootHasOpfs };
|
|
857
|
-
}
|
|
858
|
-
const outcome = await runAdoptionTransition(declaration, seams.buildEffects(storePath));
|
|
859
|
-
if (outcome.adopted) {
|
|
860
|
-
seams.log("boot adoption committed the opfs successor; idb predecessor deleted", {
|
|
861
|
-
...(outcome.predecessorCleanupPending ? { predecessorCleanupPending: outcome.predecessorCleanupPending } : {}),
|
|
862
|
-
});
|
|
863
|
-
return { bootHasOpfs: true, outcome };
|
|
864
|
-
}
|
|
865
|
-
seams.log("boot adoption deferred/failed — idb stays authoritative", {
|
|
866
|
-
reason: outcome.reason,
|
|
867
|
-
...(outcome.error ? { error: outcome.error } : {}),
|
|
868
|
-
});
|
|
869
|
-
return { bootHasOpfs: false, outcome };
|
|
870
|
-
}
|
|
871
|
-
|
|
872
592
|
// ─── ADR-0049 step 11c: FRESH/RESTORE commitment boot wiring ───────────────────────────────────────────
|
|
873
|
-
//
|
|
874
|
-
//
|
|
875
|
-
//
|
|
876
|
-
//
|
|
877
|
-
//
|
|
878
|
-
//
|
|
879
|
-
//
|
|
880
|
-
// runs only when the opfs grant survives it (so an already-committed successor resolves `open-committed` with
|
|
881
|
-
// no re-commit, and a deferred adoption's `false` grant short-circuits to idb).
|
|
593
|
+
// A virgin (or restored) opfs boot must never mint `opfs://` straight through `resolveStoreDataDir` WITHOUT
|
|
594
|
+
// the phase machine — no candidate record, no commitment barrier, no sentinel. That would violate invariant 3
|
|
595
|
+
// (an uncommitted candidate is never exposed to writes; commitment precedes exposure — D7) and invariant 12
|
|
596
|
+
// (record written at creation, completed before exposure). So EVERY browser opfs boot the client owns routes
|
|
597
|
+
// through the boot phase machine, and a fresh/restore candidate is committed by the shared barrier BEFORE
|
|
598
|
+
// exposure (an already-committed store resolves `open-committed` with no re-commit; a `false` grant
|
|
599
|
+
// short-circuits to idb).
|
|
882
600
|
|
|
883
601
|
/**
|
|
884
602
|
* @internal Injectable seams for the FRESH/RESTORE commitment boot wiring (step 11c). Real defaults in
|
|
885
603
|
* production (`globalThis.indexedDB` / `navigator.storage`); unit tests inject fakes so the phase machine and
|
|
886
|
-
* the commitment barrier are exercised without real IndexedDB / OPFS / WASM
|
|
887
|
-
* the
|
|
888
|
-
*
|
|
604
|
+
* the commitment barrier are exercised without real IndexedDB / OPFS / WASM: the IO surfaces are faked, while
|
|
605
|
+
* the barrier runs over the REAL `resolveStoreBoot` / `createOpfsEffects` / `writeStoreMetaRecord` so the
|
|
606
|
+
* record-before-directory ordering and the sentinel/phase writes are real.
|
|
889
607
|
*/
|
|
890
608
|
export interface FreshCommitmentSeams {
|
|
891
609
|
/** The boot classifier + executor (`store-boot.ts`); its verdict decides whether a candidate needs the barrier. */
|
|
@@ -945,12 +663,12 @@ function verdictNeedsCommitmentBarrier(
|
|
|
945
663
|
/**
|
|
946
664
|
* @internal ADR-0049 step 11c — Phase 1 (PRE-MINT). Route a client-owned OPFS-home boot through the boot phase
|
|
947
665
|
* machine ({@link resolveStoreBoot}) so: a virgin/restore boot stands up an UNCOMMITTED opfs candidate (record
|
|
948
|
-
* BEFORE directory, invariant 12); a committed store resolves `open-committed` (no barrier re-run);
|
|
949
|
-
* idb store
|
|
950
|
-
*
|
|
951
|
-
* whether the mint opens opfs and whether the local-init milestone must run the
|
|
952
|
-
* `hasOpfsSyncAccess` SHORT-CIRCUITS
|
|
953
|
-
*
|
|
666
|
+
* BEFORE directory, invariant 12); a committed store resolves `open-committed` (no barrier re-run); an EXISTING
|
|
667
|
+
* recordless idb store downgrades to idb (invariant 14 — never a fresh opfs mint over an existing idb store's
|
|
668
|
+
* data; the backend is fixed at first mint); and an interrupted destruction/candidate is recovered by the
|
|
669
|
+
* classifier itself. Returns whether the mint opens opfs and whether the local-init milestone must run the
|
|
670
|
+
* commitment barrier. A `false` `hasOpfsSyncAccess` SHORT-CIRCUITS — an idbfs/file home opens directly, without
|
|
671
|
+
* the opfs commitment phase machine.
|
|
954
672
|
*/
|
|
955
673
|
export async function resolveFreshBoot(
|
|
956
674
|
storePath: string,
|
|
@@ -958,11 +676,22 @@ export async function resolveFreshBoot(
|
|
|
958
676
|
backendOverride: "memory" | undefined,
|
|
959
677
|
seams?: FreshCommitmentSeams,
|
|
960
678
|
): Promise<FreshBootResolution> {
|
|
679
|
+
// The injected IO seams, in the shape both arms below take them (unit tests fake the whole browser surface;
|
|
680
|
+
// production passes none and every default reads the real globals).
|
|
681
|
+
const bootDeps: NonNullable<ResolveStoreBootOptions["deps"]> = {
|
|
682
|
+
...(seams?.meta ? { meta: seams.meta } : {}),
|
|
683
|
+
...(seams?.opfs ? { opfs: seams.opfs } : {}),
|
|
684
|
+
...(seams?.idbExists ? { idbExists: seams.idbExists } : {}),
|
|
685
|
+
};
|
|
961
686
|
// Guard: only the browser opfs engine home routes through the phase machine. No grant (or the memory test
|
|
962
|
-
// lane, which has no meta machinery) → the idb/file/memory path is untouched except
|
|
963
|
-
//
|
|
687
|
+
// lane, which has no meta machinery) → the idb/file/memory path is untouched except for the denied boot's
|
|
688
|
+
// PRE-MINT meta gate: it must finish an already-authorized `deleting` handoff, RETIRE an unexposed
|
|
689
|
+
// `opfs-candidate` (nothing is exposed beneath a record still claiming one), and it REFUSES an
|
|
690
|
+
// `opfs-committed` store ({@link CommittedStoreUnreachableError} — this home cannot open the committed
|
|
691
|
+
// store, and the idb store at the same path would be an empty sibling). The memory test lane short-circuits
|
|
692
|
+
// BEFORE the gate: it has no meta record to honour at all.
|
|
964
693
|
if (!hasOpfsSyncAccess || backendOverride === "memory") {
|
|
965
|
-
if (!hasOpfsSyncAccess && backendOverride !== "memory") await
|
|
694
|
+
if (!hasOpfsSyncAccess && backendOverride !== "memory") await resolveDeniedBootAuthority(storePath, bootDeps);
|
|
966
695
|
return {
|
|
967
696
|
bootHasOpfs: false,
|
|
968
697
|
storageBackend: backendOverride === "memory" ? "memory" : "idbfs",
|
|
@@ -974,15 +703,7 @@ export async function resolveFreshBoot(
|
|
|
974
703
|
((sp: string) =>
|
|
975
704
|
resolveStoreBoot(sp, {
|
|
976
705
|
hasOpfsSyncAccess: true,
|
|
977
|
-
...(seams?.meta || seams?.opfs || seams?.idbExists
|
|
978
|
-
? {
|
|
979
|
-
deps: {
|
|
980
|
-
...(seams?.meta ? { meta: seams.meta } : {}),
|
|
981
|
-
...(seams?.opfs ? { opfs: seams.opfs } : {}),
|
|
982
|
-
...(seams?.idbExists ? { idbExists: seams.idbExists } : {}),
|
|
983
|
-
},
|
|
984
|
-
}
|
|
985
|
-
: {}),
|
|
706
|
+
...(seams?.meta || seams?.opfs || seams?.idbExists ? { deps: bootDeps } : {}),
|
|
986
707
|
}));
|
|
987
708
|
const resolution = await runResolve(storePath);
|
|
988
709
|
const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
|
|
@@ -1012,9 +733,9 @@ export async function resolveFreshBoot(
|
|
|
1012
733
|
* for unit tests via {@link FreshCommitmentSeams}.
|
|
1013
734
|
*/
|
|
1014
735
|
/**
|
|
1015
|
-
* Extract the live engine's `strictSync()` from an opfs-repacked store for the commitment barrier
|
|
1016
|
-
*
|
|
1017
|
-
*
|
|
736
|
+
* Extract the live engine's `strictSync()` from an opfs-repacked store for the commitment barrier. The barrier
|
|
737
|
+
* requires it (data-before-authority, invariant 3); a store that does not expose it is not an OPFS-repacked
|
|
738
|
+
* engine, which is a boot invariant violation.
|
|
1018
739
|
*/
|
|
1019
740
|
function resolveEngineStrictSync(pglite: ClientPGlite): () => Promise<void> {
|
|
1020
741
|
const strictSync = (pglite as unknown as { strictSync?: () => Promise<void> }).strictSync;
|
|
@@ -1046,6 +767,39 @@ export async function runFreshCommitmentBarrier(
|
|
|
1046
767
|
);
|
|
1047
768
|
}
|
|
1048
769
|
|
|
770
|
+
/**
|
|
771
|
+
* @internal The ADOPTED-boot commitment gate. A boot that ADOPTS an instance (`pgliteInstance` /
|
|
772
|
+
* `precreatedPglite` — the provision→adopt accelerator, ADR-0032 decision 5) never enters `openOwnedStore`, so
|
|
773
|
+
* {@link resolveFreshBoot} never runs and nothing flags the barrier. Left alone, an adopted OPFS store therefore
|
|
774
|
+
* stays UNCOMMITTED for its whole life: no sentinel, and a record still at `opfs-candidate` (or absent, when the
|
|
775
|
+
* adopted instance was built outside the mint seam — a BYO `pgliteInstance`). That state is INDISTINGUISHABLE
|
|
776
|
+
* from a torn candidate, so the next client-owned boot classifies `delete-candidate-and-rebuild` and DESTROYS a
|
|
777
|
+
* populated store — offline, with nothing to rebuild from. An adopted opfs boot therefore owes the SAME barrier
|
|
778
|
+
* ({@link runFreshCommitmentBarrier}) a fresh one does, pre-expose (invariant 3).
|
|
779
|
+
*
|
|
780
|
+
* Exactly two states are this gate's to own: RECORDLESS and `opfs-candidate`. `opfs-committed` needs nothing
|
|
781
|
+
* (the warm-reopen accelerator), and every other phase belongs to another authority — `deleting` to the
|
|
782
|
+
* deletion authority, `idb-authoritative` to the idb lane — which an adopted-boot barrier must not fight. A
|
|
783
|
+
* scope with no meta store has nowhere to record commitment, so it declines. An UNREADABLE record PROPAGATES:
|
|
784
|
+
* a failed meta read is an error, never "no record" (invariant 12).
|
|
785
|
+
*/
|
|
786
|
+
export async function resolveAdoptedCommitmentBarrier(
|
|
787
|
+
storePath: string,
|
|
788
|
+
seams?: FreshCommitmentSeams,
|
|
789
|
+
): Promise<boolean> {
|
|
790
|
+
const metaResult = await readStoreMetaRecord(storePath, seams?.meta);
|
|
791
|
+
const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
|
|
792
|
+
const record = metaUnavailable ? undefined : metaResult;
|
|
793
|
+
const needsCommitmentBarrier = !metaUnavailable && (record === undefined || record.phase === "opfs-candidate");
|
|
794
|
+
(seams?.log ?? ((message, data) => syncDebug(message, data)))("boot adopted store commitment resolved", {
|
|
795
|
+
storePath,
|
|
796
|
+
phase: record?.phase ?? null,
|
|
797
|
+
...(metaUnavailable ? { metaStoreUnavailable: true } : {}),
|
|
798
|
+
needsCommitmentBarrier,
|
|
799
|
+
});
|
|
800
|
+
return needsCommitmentBarrier;
|
|
801
|
+
}
|
|
802
|
+
|
|
1049
803
|
/**
|
|
1050
804
|
* Format an opfs open failure into the VERBATIM `Name: message` the `storageFallbackReason` diagnostic carries
|
|
1051
805
|
* (ADR-0049 decision 12). A non-Error throw is stringified.
|
|
@@ -1078,12 +832,12 @@ function formatOpenFailureReason(error: unknown): string {
|
|
|
1078
832
|
*
|
|
1079
833
|
* STICKINESS (reconciling the plan's D6 "non-sticky, opfs retried next boot" verdict with the LATER phase
|
|
1080
834
|
* machine): the record is the first-use authority, and an idb fallback store IS a recorded idb store (boot
|
|
1081
|
-
* classification
|
|
1082
|
-
* `idb-authoritative`). So the next boot classifies `boot-idb-authoritative` (classification
|
|
1083
|
-
* it does NOT loop through virgin re-creation each boot
|
|
1084
|
-
*
|
|
1085
|
-
*
|
|
1086
|
-
* written") and the fault-row semantics honest for the composition actually shipped.
|
|
835
|
+
* classification 6's caution / invariant 14 — the same as the no-handle virgin path, which already records
|
|
836
|
+
* `idb-authoritative`). So the next boot classifies `boot-idb-authoritative` (classification 4) and boots idb;
|
|
837
|
+
* it does NOT loop through virgin re-creation each boot, and it never re-probes destructively — a store's
|
|
838
|
+
* storage backend is fixed at first mint, and the only route to a different one is a deliberate
|
|
839
|
+
* `destroyStoreArtifacts()` / `client.destroy()` followed by a fresh boot on a fresh path. This keeps the fault
|
|
840
|
+
* row true ("record written") and the fault-row semantics honest for the composition actually shipped.
|
|
1087
841
|
*/
|
|
1088
842
|
export async function fallbackVirginCandidateToIdb(
|
|
1089
843
|
storePath: string,
|
|
@@ -1102,53 +856,6 @@ export async function fallbackVirginCandidateToIdb(
|
|
|
1102
856
|
return reason;
|
|
1103
857
|
}
|
|
1104
858
|
|
|
1105
|
-
/** Options for the manual {@link adoptStore} API — the creation-path adoption trigger. */
|
|
1106
|
-
export interface AdoptStoreOptions<TRegistry extends SyncTableRegistry> {
|
|
1107
|
-
registry: TRegistry;
|
|
1108
|
-
electricUrl: string;
|
|
1109
|
-
batchWriteUrl: string;
|
|
1110
|
-
/** The store to adopt (a plain path/name; the idb predecessor is migrated to a committed OPFS successor). */
|
|
1111
|
-
storePath?: string;
|
|
1112
|
-
getAuthToken?: () => Promise<string | undefined>;
|
|
1113
|
-
requestHeaders?: Record<string, string>;
|
|
1114
|
-
syncEnabled?: boolean;
|
|
1115
|
-
/** Bounded wait (ms) for the eager Consistency groups' catch-up before the gate fails closed. */
|
|
1116
|
-
gateDeadlineMs?: number;
|
|
1117
|
-
/** @internal test seams (fake effects / idb existence / meta+opfs IO). */
|
|
1118
|
-
seams?: AdoptionWiringSeams;
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
/**
|
|
1122
|
-
* The MANUAL adoption API (ADR-0049 D7, plan step 11b): migrate an EXISTING idb-authoritative store into a
|
|
1123
|
-
* committed OPFS successor ON DEMAND, without the automatic {@link CreateSyncClientOptions.adoption} declaration
|
|
1124
|
-
* — the consumer's explicit call IS the authorization (they were told to export/migrate any local-only data
|
|
1125
|
-
* first). Like `restoreFrom` it is a CREATION-PATH operation: call it INSTEAD of {@link createSyncClient},
|
|
1126
|
-
* before any client opens the store — it REFUSES with {@link StoreInUseError} while a live in-process client
|
|
1127
|
-
* holds the store. The drain predicate still gates it (a store that owes the server work is not adoptable), and
|
|
1128
|
-
* every failure recovery is identical to the automatic path (idb stays authoritative; nothing strands).
|
|
1129
|
-
*/
|
|
1130
|
-
export async function adoptStore<const TRegistry extends SyncTableRegistry>(
|
|
1131
|
-
options: AdoptStoreOptions<TRegistry>,
|
|
1132
|
-
): Promise<AdoptionOutcome> {
|
|
1133
|
-
const storePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
1134
|
-
const isStoreLive = options.seams?.isStoreLive ?? ((sp: string) => liveStorePaths.has(sp));
|
|
1135
|
-
if (isStoreLive(storePath)) throw new StoreInUseError(storePath);
|
|
1136
|
-
const ctx: AdoptionBootContext<TRegistry> = {
|
|
1137
|
-
registry: options.registry,
|
|
1138
|
-
electricUrl: options.electricUrl,
|
|
1139
|
-
batchWriteUrl: options.batchWriteUrl,
|
|
1140
|
-
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
1141
|
-
...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
|
|
1142
|
-
syncEnabled: options.syncEnabled ?? true,
|
|
1143
|
-
...(options.gateDeadlineMs != null ? { gateDeadlineMs: options.gateDeadlineMs } : {}),
|
|
1144
|
-
...(options.seams?.meta ? { meta: options.seams.meta } : {}),
|
|
1145
|
-
...(options.seams?.opfs ? { opfs: options.seams.opfs } : {}),
|
|
1146
|
-
...(options.seams?.createPglite ? { createPglite: options.seams.createPglite } : {}),
|
|
1147
|
-
};
|
|
1148
|
-
const effects = options.seams?.buildEffects?.(storePath) ?? buildRealAdoptionEffects(storePath, ctx);
|
|
1149
|
-
return runManualAdoption(effects);
|
|
1150
|
-
}
|
|
1151
|
-
|
|
1152
859
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
1153
860
|
registry: TRegistry;
|
|
1154
861
|
electricUrl: string;
|
|
@@ -1200,20 +907,6 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1200
907
|
* resolves the actual dataDir from it.
|
|
1201
908
|
*/
|
|
1202
909
|
hasOpfsSyncAccess?: boolean;
|
|
1203
|
-
/**
|
|
1204
|
-
* ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
|
|
1205
|
-
* reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
|
|
1206
|
-
* committed OPFS successor. DEFAULT OFF (`undefined`) — hook absence is NEVER authority (`rawExec` writes
|
|
1207
|
-
* documented local-only state on any store), so only this explicit `"server-reconstructible"` value (or the
|
|
1208
|
-
* manual {@link adoptStore} API) authorizes deleting the idb predecessor. Honoured ONLY on the browser
|
|
1209
|
-
* OPFS-home boot path (when {@link hasOpfsSyncAccess} is granted and the client owns the create — never the
|
|
1210
|
-
* BYO-instance / restore paths): a boot that finds an idb-authoritative store runs the pre-expose drain check,
|
|
1211
|
-
* reconstructs the successor through the Adoption-bootstrap gate (authorized online reconstruction — the eager
|
|
1212
|
-
* Consistency groups' initial catch-up), commits it via the strict barrier, and only then deletes the idb
|
|
1213
|
-
* predecessor. Any deferral/failure (owed journal, gate unmet, barrier failed) leaves the idb store
|
|
1214
|
-
* authoritative and boots it normally.
|
|
1215
|
-
*/
|
|
1216
|
-
adoption?: AdoptionDeclaration;
|
|
1217
910
|
/**
|
|
1218
911
|
* Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
|
|
1219
912
|
* into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
|
|
@@ -1378,7 +1071,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1378
1071
|
* @internal Capability-absence fallback reason stamped into the {@link BootReport} (ADR-0049 D1/D12). Threaded
|
|
1379
1072
|
* by `defineSyncWorker` when the placement bootstrap opened the in-SharedWorker IDBFS engine because OPFS was
|
|
1380
1073
|
* CAPABLE but no home could hold sync-access handles (every probe denied / the OPFS API absent). Unlike the
|
|
1381
|
-
* client's own internal fallback reasons (
|
|
1074
|
+
* client's own internal fallback reasons (recordless-idb, opfs-uncreatable — set only under a granted probe),
|
|
1382
1075
|
* this externally-supplied reason is stamped verbatim on an idbfs boot. Absent on a granted opfs boot and on the
|
|
1383
1076
|
* declared `backend: "idbfs"` mode (that is the data contract, not a fallback). Report-label only.
|
|
1384
1077
|
*/
|
|
@@ -1937,14 +1630,6 @@ export function replAdapter(
|
|
|
1937
1630
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
1938
1631
|
options: CreateSyncClientOptions<TRegistry>,
|
|
1939
1632
|
): Promise<SyncClient<TRegistry>> {
|
|
1940
|
-
// The outer adoption transition owns the durable `adopting` phase and final commitment barrier. Its inner
|
|
1941
|
-
// candidate boot must mint only candidate bytes; re-entering the ordinary phase machine would classify the
|
|
1942
|
-
// live `adopting` record as crash recovery and tear the candidate down underneath itself.
|
|
1943
|
-
const adoptionCandidateBuild =
|
|
1944
|
-
(options as CreateSyncClientOptions<TRegistry> & AdoptionCandidateBuildOptions)[ADOPTION_CANDIDATE_BUILD] === true;
|
|
1945
|
-
const createPglite =
|
|
1946
|
-
(options as CreateSyncClientOptions<TRegistry> & InternalPgliteCreateOptions)[INTERNAL_PGLITE_CREATE] ??
|
|
1947
|
-
createClientPGlite;
|
|
1948
1633
|
// Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
|
|
1949
1634
|
validateLiveQueryPolicy(options.liveQueries);
|
|
1950
1635
|
const status: SyncRuntimeStatus = {
|
|
@@ -2057,10 +1742,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2057
1742
|
|
|
2058
1743
|
// Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
|
|
2059
1744
|
// `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.
|
|
2060
|
-
// ADR-0049 step
|
|
2061
|
-
// value and is ADJUSTED DOWN to `false` by
|
|
2062
|
-
//
|
|
2063
|
-
//
|
|
1745
|
+
// ADR-0049 step 11c: the OPFS-home grant the client-owned mint opens under. Starts at the placement probe's
|
|
1746
|
+
// value and is ADJUSTED DOWN to `false` by the pre-mint phase machine (an existing idb store is opened in
|
|
1747
|
+
// place — the backend is fixed at first mint). Read at mint time by `timedCreate` below, so the phase machine
|
|
1748
|
+
// can settle it before the create runs.
|
|
2064
1749
|
let bootHasOpfsSyncAccess = options.hasOpfsSyncAccess === true;
|
|
2065
1750
|
// ADR-0049 step 11c: set by the pre-mint fresh-boot phase machine when it stands up an UNCOMMITTED opfs
|
|
2066
1751
|
// candidate (virgin/restore) that the shared commitment barrier must promote BEFORE exposure. Read at the
|
|
@@ -2069,7 +1754,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2069
1754
|
let commitmentBarrierPending = false;
|
|
2070
1755
|
// ADR-0049 decision 12 `storageFallbackReason`: the verbatim reason an opfs-CAPABLE boot (the probe granted)
|
|
2071
1756
|
// nonetheless opened idb. `probeGranted` is the entering grant; a fallback is `probeGranted && !bootHasOpfs...`
|
|
2072
|
-
// once the
|
|
1757
|
+
// once the fresh phase machine has settled (never on a plain idb boot, where `probeGranted` is false).
|
|
2073
1758
|
const probeGranted = options.hasOpfsSyncAccess === true;
|
|
2074
1759
|
let storageFallbackReason: string | undefined;
|
|
2075
1760
|
// Durability (ADR-0047 D2 + ADR-0050): resolve the store's declared mode ONCE here — this is the single
|
|
@@ -2112,16 +1797,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2112
1797
|
// caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
|
|
2113
1798
|
const timedCreate = async (): Promise<ClientPGlite> => {
|
|
2114
1799
|
const startedAt = performance.now();
|
|
2115
|
-
// ADR-0049 step 10b/
|
|
2116
|
-
// so
|
|
2117
|
-
// opfs
|
|
1800
|
+
// ADR-0049 step 10b/11c: the OPFS-home grant is spread in at MINT time (not baked into `createClientOptions`),
|
|
1801
|
+
// so the pre-mint phase machine that ran just above can settle `bootHasOpfsSyncAccess` first — opening the
|
|
1802
|
+
// committed opfs store or the existing idb store. Default absent keeps today's backend.
|
|
2118
1803
|
// ADR-0049 decision 12: this is the SINGLE client-owned mint seam, so stamp `storageBackend` from the resolved
|
|
2119
1804
|
// dataDir scheme here — the same resolution `createClientPGlite` performs, so the diagnostic never diverges
|
|
2120
1805
|
// from the backend actually opened. Covers every client-owned mint (in-process, worker, precreated-fallback).
|
|
2121
1806
|
const resolvedDataDir = bootHasOpfsSyncAccess
|
|
2122
1807
|
? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true })
|
|
2123
1808
|
: resolveStoreDataDir(fallbackStorePath, backendOverride);
|
|
2124
|
-
const created = await
|
|
1809
|
+
const created = await createClientPGlite(fallbackStorePath, {
|
|
2125
1810
|
...createClientOptions,
|
|
2126
1811
|
...(bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
2127
1812
|
});
|
|
@@ -2137,30 +1822,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2137
1822
|
return created;
|
|
2138
1823
|
};
|
|
2139
1824
|
|
|
2140
|
-
// ADR-0049 step 11b — AUTOMATIC adoption (declaration-gated, default off). Honoured ONLY on the client-owned
|
|
2141
|
-
// storePath create in a browser OPFS engine home (`bootHasOpfsSyncAccess`), never the BYO / restore paths: a
|
|
2142
|
-
// boot that finds an existing idb-authoritative store runs the pre-expose drain check, reconstructs the opfs
|
|
2143
|
-
// successor through the Adoption-bootstrap gate, commits it, and deletes the idb predecessor. Any deferral or
|
|
2144
|
-
// failure leaves the idb store authoritative — `bootHasOpfsSyncAccess` is flipped to false so the mint opens
|
|
2145
|
-
// idb. Runs before the create, so `timedCreate` opens whichever backend the transition settled on.
|
|
2146
|
-
const runBootAdoptionIfDeclared = async (): Promise<void> => {
|
|
2147
|
-
if (!bootHasOpfsSyncAccess || options.adoption !== "server-reconstructible" || restoreBoot) return;
|
|
2148
|
-
const { bootHasOpfs, outcome } = await runBootAdoption(fallbackStorePath, options.adoption, {
|
|
2149
|
-
registry: options.registry,
|
|
2150
|
-
electricUrl: options.electricUrl,
|
|
2151
|
-
batchWriteUrl: options.batchWriteUrl,
|
|
2152
|
-
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
2153
|
-
...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
|
|
2154
|
-
syncEnabled: options.syncEnabled ?? true,
|
|
2155
|
-
});
|
|
2156
|
-
bootHasOpfsSyncAccess = bootHasOpfs;
|
|
2157
|
-
// ADR-0049 decision 12: a declared adoption that DEFERRED/FAILED left idb authoritative — an opfs-capable boot
|
|
2158
|
-
// that opened idb. Record the verbatim reason (the outcome's own classification) as the fallback reason.
|
|
2159
|
-
if (!bootHasOpfs && outcome && outcome.adopted === false) {
|
|
2160
|
-
storageFallbackReason = `adoption deferred (${outcome.reason})`;
|
|
2161
|
-
}
|
|
2162
|
-
};
|
|
2163
|
-
|
|
2164
1825
|
// Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
|
|
2165
1826
|
// acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the
|
|
2166
1827
|
// `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are
|
|
@@ -2172,7 +1833,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2172
1833
|
// An opfs-repacked instance is PROVABLY persistent (a dedicated OPFS directory) yet reports no `dataDir`
|
|
2173
1834
|
// (custom VFS), so honour its brand before the dataDir classification — otherwise adopting a provisioned
|
|
2174
1835
|
// opfs store (provision-then-attach, ADR-0049) would be wrongly refused as an in-memory default.
|
|
2175
|
-
if ((instance
|
|
1836
|
+
if (isOpfsRepackedPersistent(instance)) return;
|
|
2176
1837
|
const observedDataDir = (instance as { dataDir?: string }).dataDir;
|
|
2177
1838
|
// The two provably-non-persistent shapes: an undefined dataDir (a raw `new PGlite()` in-memory default)
|
|
2178
1839
|
// and a `memory://` store. Every store the funnel mints carries a real `idb://`/`file://` dataDir string.
|
|
@@ -2181,41 +1842,30 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2181
1842
|
};
|
|
2182
1843
|
|
|
2183
1844
|
// The complete client-owned open path. Both an ordinary `storePath` boot and a rejected precreated
|
|
2184
|
-
// accelerator MUST enter here: recovery/
|
|
2185
|
-
//
|
|
2186
|
-
//
|
|
1845
|
+
// accelerator MUST enter here: recovery/classification precede every persistent mint. Keeping the flow in one
|
|
1846
|
+
// closure prevents a rejected eager create from bypassing live `deleting` authority or the OPFS commitment
|
|
1847
|
+
// phase machine by jumping straight to `timedCreate()`.
|
|
2187
1848
|
const openOwnedStore = async (): Promise<ClientPGlite> => {
|
|
2188
|
-
// A capability-denied browser may inherit an interrupted destroy
|
|
2189
|
-
//
|
|
2190
|
-
//
|
|
1849
|
+
// A capability-denied browser may inherit an interrupted destroy or an unexposed candidate from an earlier
|
|
1850
|
+
// granted engine home, and it may be looking at a store that lives in OPFS it cannot open at all. ONE
|
|
1851
|
+
// bounded meta read settles all three before any replacement IDB store is minted: a `deleting` handoff
|
|
1852
|
+
// completes, an `opfs-candidate` is retired (sentinel + directory, then idb authority), an `opfs-committed`
|
|
1853
|
+
// store is REFUSED typed ({@link CommittedStoreUnreachableError} — never an empty idb sibling minted over
|
|
1854
|
+
// it), and every other state (including no meta store at all) proceeds exactly as before.
|
|
2191
1855
|
if (!bootHasOpfsSyncAccess && backendOverride !== "memory") {
|
|
2192
|
-
await
|
|
1856
|
+
await resolveDeniedBootAuthority(fallbackStorePath);
|
|
2193
1857
|
}
|
|
2194
|
-
// ADR-0049 step
|
|
2195
|
-
//
|
|
2196
|
-
//
|
|
2197
|
-
//
|
|
2198
|
-
|
|
2199
|
-
//
|
|
2200
|
-
|
|
2201
|
-
// BEFORE directory) and flags the commitment barrier for the local-init milestone; a committed store resolves
|
|
2202
|
-
// `open-committed` (no re-run — composes with an adoption that just committed); a recordless idb store (adoption
|
|
2203
|
-
// not declared) downgrades to idb (never a fresh opfs mint over an existing idb store's data). A `false` grant (probe denied
|
|
2204
|
-
// OR adoption deferred/failed) SHORT-CIRCUITS — the idbfs home opens directly, without the opfs commitment phase machine.
|
|
2205
|
-
if (adoptionCandidateBuild) {
|
|
2206
|
-
// The predecessor remains authoritative and its journal was proven drained before the outer transition
|
|
2207
|
-
// entered `adopting`. Remove any sentinel-less residue from an earlier authorized destruction, then create
|
|
2208
|
-
// the directory the candidate factory will open. No meta write and no commitment here: the outer adoption
|
|
2209
|
-
// transition owns both.
|
|
2210
|
-
const opfs = createOpfsEffects(fallbackStorePath);
|
|
2211
|
-
await opfs.deleteSentinel();
|
|
2212
|
-
await opfs.deleteStoreDirectory();
|
|
2213
|
-
await opfs.getStoreDirectoryHandle();
|
|
2214
|
-
} else if (bootHasOpfsSyncAccess) {
|
|
1858
|
+
// ADR-0049 step 11c: route the client-owned mint through the boot PHASE MACHINE (invariants 3/12/14). A
|
|
1859
|
+
// virgin/restore boot stands up an UNCOMMITTED opfs candidate (record BEFORE directory) and flags the
|
|
1860
|
+
// commitment barrier for the local-init milestone; a committed store resolves `open-committed` (no re-run);
|
|
1861
|
+
// an EXISTING recordless idb store downgrades to idb (never a fresh opfs mint over an existing idb store's
|
|
1862
|
+
// data — the backend is fixed at first mint). A `false` grant (probe denied) SHORT-CIRCUITS: the idbfs home
|
|
1863
|
+
// opens directly, without the opfs commitment phase machine.
|
|
1864
|
+
if (bootHasOpfsSyncAccess) {
|
|
2215
1865
|
const fresh = await resolveFreshBoot(fallbackStorePath, bootHasOpfsSyncAccess, backendOverride);
|
|
2216
1866
|
// ADR-0049 decision 12: the phase machine downgraded a granted opfs boot to idb (invariant 14 — an existing
|
|
2217
1867
|
// idb store is opened in place, never overwritten by a fresh opfs mint). That is an opfs-capable-boot-on-idb
|
|
2218
|
-
// fallback; record its verbatim verdict as the reason
|
|
1868
|
+
// fallback; record its verbatim verdict as the reason.
|
|
2219
1869
|
if (!fresh.bootHasOpfs && storageFallbackReason == null) {
|
|
2220
1870
|
storageFallbackReason = `recordless idb store opened in place (invariant 14; verdict ${fresh.verdict?.action ?? "unknown"})`;
|
|
2221
1871
|
}
|
|
@@ -2279,7 +1929,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2279
1929
|
pglite = await openOwnedStore();
|
|
2280
1930
|
}
|
|
2281
1931
|
// ADR-0049 decision 12: stamp the fallback reason once the mint's backend is settled. Guarded on `probeGranted`
|
|
2282
|
-
// (an opfs-capable boot) — a plain idb boot never enters the
|
|
1932
|
+
// (an opfs-capable boot) — a plain idb boot never enters the fresh phase machine, so it never sets one.
|
|
2283
1933
|
if (probeGranted && !bootHasOpfsSyncAccess && backendOverride !== "memory" && storageFallbackReason != null) {
|
|
2284
1934
|
bootReportBuilder.setStorageFallbackReason(storageFallbackReason);
|
|
2285
1935
|
}
|
|
@@ -2300,11 +1950,24 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2300
1950
|
bootReportBuilder.setStorageBackend(byoBackend);
|
|
2301
1951
|
}
|
|
2302
1952
|
}
|
|
2303
|
-
//
|
|
2304
|
-
//
|
|
2305
|
-
//
|
|
1953
|
+
// An ADOPTED opfs store owes the SAME commitment barrier a fresh one does ({@link resolveAdoptedCommitmentBarrier}):
|
|
1954
|
+
// the adopt paths skip `openOwnedStore`, so the pre-mint phase machine never ran and `commitmentBarrierPending` is
|
|
1955
|
+
// still false — leaving a provision-adopted store uncommitted, which the NEXT client-owned boot reads as a torn
|
|
1956
|
+
// candidate and destroys. Gated on the opfs-repacked brand: an idb/file BYO instance has no commitment machinery to
|
|
1957
|
+
// run, and the memory test lane has no meta machinery at all. The bounded meta read is kicked off HERE and folded
|
|
1958
|
+
// into `commitmentBarrierPending` at the milestone below, so it overlaps schema exec instead of preceding it.
|
|
1959
|
+
const adoptedCommitmentGate =
|
|
1960
|
+
(options.pgliteInstance != null || adoptedPrecreated) &&
|
|
1961
|
+
backendOverride !== "memory" &&
|
|
1962
|
+
isOpfsRepackedPersistent(pglite)
|
|
1963
|
+
? resolveAdoptedCommitmentBarrier(fallbackStorePath)
|
|
1964
|
+
: null;
|
|
1965
|
+
// The gate's rejection is observed at the milestone (fail closed, invariant 12); this only keeps an unrelated
|
|
1966
|
+
// earlier boot failure from surfacing it as an unhandled rejection in the meantime.
|
|
1967
|
+
if (adoptedCommitmentGate) void adoptedCommitmentGate.catch(() => undefined);
|
|
1968
|
+
// Whether THIS client owns the store's lifecycle (so `destroy()` may run the supervised destruction machine
|
|
1969
|
+
// over it). A BYO `pgliteInstance` is the caller's to dispose of; every other provenance is ours.
|
|
2306
1970
|
const ownsStoreLifecycle = !options.pgliteInstance;
|
|
2307
|
-
if (ownsStoreLifecycle) liveStorePaths.add(fallbackStorePath);
|
|
2308
1971
|
|
|
2309
1972
|
// Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
|
|
2310
1973
|
// its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`
|
|
@@ -2485,9 +2148,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2485
2148
|
|
|
2486
2149
|
if (storedFingerprint === currentFingerprint) {
|
|
2487
2150
|
// (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.
|
|
2151
|
+
// Named on the rail: whether a warm boot took the fast path is the first thing a latency reading needs,
|
|
2152
|
+
// and the BootReport only surfaces it after finalize (too late to read against the phase timings).
|
|
2153
|
+
syncDebug("boot local schema fingerprint match — durable exec skipped");
|
|
2488
2154
|
bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
|
|
2489
2155
|
} else {
|
|
2490
2156
|
// (4b) Absent/mismatch → replay the durable schema, then stamp the fingerprint after success.
|
|
2157
|
+
// `hadStored` separates the two very different causes: no stored fingerprint at all (a fresh/rebuilt
|
|
2158
|
+
// store — a replay is expected) versus a stored one that DISAGREES (a registry shape change, or an
|
|
2159
|
+
// unexpected fingerprint drift worth investigating).
|
|
2160
|
+
syncDebug("boot local schema fingerprint mismatch — replaying durable schema", {
|
|
2161
|
+
hadStored: storedFingerprint != null,
|
|
2162
|
+
});
|
|
2491
2163
|
await pglite.exec(generateDurableLocalSchemaSql(options.registry));
|
|
2492
2164
|
await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
|
|
2493
2165
|
bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
|
|
@@ -2630,9 +2302,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2630
2302
|
// manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
|
|
2631
2303
|
const quiesceTailForTeardown = async (): Promise<void> => {
|
|
2632
2304
|
disposed = true;
|
|
2633
|
-
// ADR-0049 step 11b: release the live-store guard so a later manual `adoptStore` on this path is permitted
|
|
2634
|
-
// once this client is torn down (delete-if-present; a BYO-instance boot never registered, so it is a no-op).
|
|
2635
|
-
liveStorePaths.delete(fallbackStorePath);
|
|
2636
2305
|
// FIX 2: a stopped client can never reach `writeReady` / `ready`, so reject them (idempotent — a race with
|
|
2637
2306
|
// the tail's own resolve is settled first-wins; a normal stop AFTER boot is a no-op on the already-resolved
|
|
2638
2307
|
// promises) so a parked mutation or an `await ready` / `start()` fails FAST rather than hanging past
|
|
@@ -3550,6 +3219,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3550
3219
|
// does — see `localReadReady`'s no-reject-binding rationale above): the returned promise rejects, the client
|
|
3551
3220
|
// is NEVER exposed, nothing is published, the `opfs-candidate` record survives, and the next boot's classifier
|
|
3552
3221
|
// tears the candidate down and rebuilds (invariant 3 — an uncommitted candidate is never exposed to writes).
|
|
3222
|
+
// An ADOPTED boot arrives here with the same debt: fold its gate in (kicked off back at the adopt branch, so the
|
|
3223
|
+
// meta read overlapped the phases above). Plain assignment, not `||=`: the adopt paths never enter
|
|
3224
|
+
// `openOwnedStore`, so the fresh flag is necessarily false whenever the gate ran.
|
|
3225
|
+
if (adoptedCommitmentGate) commitmentBarrierPending = await adoptedCommitmentGate;
|
|
3553
3226
|
if (commitmentBarrierPending) {
|
|
3554
3227
|
await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pglite));
|
|
3555
3228
|
}
|