@pgxsinkit/client 0.2.2 → 0.2.4
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 +259 -392
- 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 +51 -5
- 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/election-coordinator.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/package.json +3 -3
- package/skills/core/SKILL.md +3 -2
- package/skills/operating/SKILL.md +40 -8
- 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 +194 -21
- package/src/worker/define-sync-worker.ts +94 -26
- package/src/worker/election-coordinator.ts +6 -1
- package/src/worker/engine-control.ts +12 -0
- package/src/worker/engine-router.ts +176 -21
- package/dist/adoption.d.ts +0 -118
- package/dist/adoption.d.ts.map +0 -1
- package/src/adoption.ts +0 -275
package/src/store-meta.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
// Store meta record — the first-use authority for browser-side engine placement (ADR-0049 decision 6,
|
|
2
2
|
// invariants 12 & 14; CONTEXT.md § "Language — engine placement", entries "Store meta record" and
|
|
3
|
-
// "Commitment marker").
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
3
|
+
// "Commitment marker"). A store minted under the opfs commitment machinery records at CREATION
|
|
4
|
+
// (candidate-before-directory) and completes before that backend is exposed; a no-grant or registry-forced
|
|
5
|
+
// idbfs mint is deliberately RECORDLESS — recordless-idb is a first-class state, recognised by boot
|
|
6
|
+
// classification 6 — and gains its `idb-authoritative` record on the first pass that MUST write authority (a
|
|
7
|
+
// granted classification-6 boot, a `deleting` handoff, a candidate retirement). The meta record is a TOTAL
|
|
8
|
+
// phase machine — one of
|
|
9
|
+
// `idb-authoritative | opfs-candidate | opfs-committed | deleting` — with `deleting` taking precedence over
|
|
10
|
+
// EVERYTHING (a committed store mid-destruction resumes deletion, never the committed verdict). It lives in a
|
|
11
|
+
// small dedicated IndexedDB database so it is readable in every engine home (SharedWorker-direct or elected
|
|
12
|
+
// worker).
|
|
9
13
|
//
|
|
10
14
|
// This module SEPARATES the pure boot decision (part A — `classifyStoreBoot`, total and unit-testable) from
|
|
11
15
|
// the IndexedDB IO (part B — the record's own database) and the recordless-idb detection (part C — a non-creating
|
|
@@ -21,11 +25,11 @@ import { storeIdentityComponent, storeIndexedDbDatabaseName } from "./store-path
|
|
|
21
25
|
// =========================================================================================================
|
|
22
26
|
|
|
23
27
|
/**
|
|
24
|
-
* The one total phase of the store meta record (invariant 12). `deleting` has precedence over everything
|
|
25
|
-
*
|
|
26
|
-
*
|
|
28
|
+
* The one total phase of the store meta record (invariant 12). `deleting` has precedence over everything.
|
|
29
|
+
* There is deliberately NO boolean cross-product (`committed` + `deletionIntent`) — that left precedence
|
|
30
|
+
* ambiguous; the phase is total (CONTEXT § "Store meta record").
|
|
27
31
|
*/
|
|
28
|
-
export type StoreMetaPhase = "idb-authoritative" | "opfs-candidate" | "
|
|
32
|
+
export type StoreMetaPhase = "idb-authoritative" | "opfs-candidate" | "opfs-committed" | "deleting";
|
|
29
33
|
|
|
30
34
|
/** One store's meta record: its total {@link StoreMetaPhase} plus a last-write timestamp. */
|
|
31
35
|
export interface StoreMetaRecord {
|
|
@@ -63,11 +67,9 @@ export interface StoreBootObservations {
|
|
|
63
67
|
export type StoreBootVerdict =
|
|
64
68
|
// phase `deleting` — highest precedence; resume the destructive lifecycle.
|
|
65
69
|
| { action: "resume-deletion" }
|
|
66
|
-
// phase `adopting` — the adoption crash-recovery table (plan) owns the next steps.
|
|
67
|
-
| { action: "adoption-recovery" }
|
|
68
70
|
// phase `opfs-committed`, or the sentinel repair path — open the committed store (hard-open handles failure).
|
|
69
71
|
| { action: "open-committed" }
|
|
70
|
-
// no
|
|
72
|
+
// no record but a commitment sentinel is present (record loss) — repair the record, then open committed.
|
|
71
73
|
| { action: "repair-record-then-open-committed" }
|
|
72
74
|
// phase `opfs-candidate`, or a recordless candidate directory — an unexposed candidate has no authority.
|
|
73
75
|
| { action: "delete-candidate-and-rebuild" }
|
|
@@ -77,21 +79,21 @@ export type StoreBootVerdict =
|
|
|
77
79
|
| { action: "virgin-create" };
|
|
78
80
|
|
|
79
81
|
/**
|
|
80
|
-
* The PURE boot classifier — plan boot classification 1–
|
|
82
|
+
* The PURE boot classifier — plan boot classification 1–6 EXACTLY (invariant 12). Total over every phase and
|
|
81
83
|
* every observation combination; no IO. Precedence, in order:
|
|
82
84
|
*
|
|
83
85
|
* 1. `deleting` → `resume-deletion` (precedence over EVERYTHING, including a committed-looking OPFS).
|
|
84
|
-
* 2. `
|
|
85
|
-
* 3. `opfs-committed` → `open-committed` (opfs observations are IRRELEVANT here — the hard-open path handles
|
|
86
|
+
* 2. `opfs-committed` → `open-committed` (opfs observations are IRRELEVANT here — the hard-open path handles
|
|
86
87
|
* any failure, including an unreachable root; a committed store never re-derives its verdict from OPFS).
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
88
|
+
* 3. `opfs-candidate` → `delete-candidate-and-rebuild` (an unexposed candidate has no authority).
|
|
89
|
+
* 4. `idb-authoritative` → `boot-idb-authoritative`.
|
|
90
|
+
* 5. record `undefined`, OPFS observable: `sentinelPresent` → `repair-record-then-open-committed` (sentinel
|
|
90
91
|
* authority — a sentinel-without-record is a real crash state that reads as committed); else a candidate
|
|
91
|
-
* directory without a sentinel → `delete-candidate-and-rebuild`; neither → fall through to
|
|
92
|
-
*
|
|
93
|
-
* `idbStoreExists` → `boot-idb-authoritative` (an existing recordless idb store — NEVER virgin
|
|
94
|
-
* is
|
|
92
|
+
* directory without a sentinel → `delete-candidate-and-rebuild`; neither → fall through to 6.
|
|
93
|
+
* 6. record `undefined` and (OPFS unobservable OR nothing present): the RECORDLESS-IDB CHECK —
|
|
94
|
+
* `idbStoreExists` → `boot-idb-authoritative` (an existing recordless idb store — NEVER virgin). This arm
|
|
95
|
+
* is a TERMINUS: a store's storage backend is fixed at first mint, so an idb store stays idb-authoritative
|
|
96
|
+
* for its whole life. The only route to a different backend is a deliberate destroy + a fresh boot.
|
|
95
97
|
*
|
|
96
98
|
* NOTE (the caller's nuance, not the classifier's): when OPFS is unobservable and the verdict is
|
|
97
99
|
* `virgin-create`, the caller creates an IDB store (a main thread / no-handle scope cannot hold sync-access
|
|
@@ -106,8 +108,6 @@ export function classifyStoreBoot(obs: StoreBootObservations): StoreBootVerdict
|
|
|
106
108
|
switch (record.phase) {
|
|
107
109
|
case "deleting":
|
|
108
110
|
return { action: "resume-deletion" };
|
|
109
|
-
case "adopting":
|
|
110
|
-
return { action: "adoption-recovery" };
|
|
111
111
|
case "opfs-committed":
|
|
112
112
|
return { action: "open-committed" };
|
|
113
113
|
case "opfs-candidate":
|
|
@@ -122,14 +122,14 @@ export function classifyStoreBoot(obs: StoreBootObservations): StoreBootVerdict
|
|
|
122
122
|
}
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
// No record. Classification
|
|
125
|
+
// No record. Classification 5: OPFS observable → decide from the commitment namespace.
|
|
126
126
|
if (opfs !== "unobservable") {
|
|
127
127
|
if (opfs.sentinelPresent) return { action: "repair-record-then-open-committed" };
|
|
128
128
|
if (opfs.storeDirectoryPresent) return { action: "delete-candidate-and-rebuild" };
|
|
129
129
|
// Nothing present in OPFS → fall through to the recordless-idb check.
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
-
// Classification
|
|
132
|
+
// Classification 6 (also when OPFS is NOT observable): the recordless-idb check.
|
|
133
133
|
return idbStoreExists ? { action: "boot-idb-authoritative" } : { action: "virgin-create" };
|
|
134
134
|
}
|
|
135
135
|
|
|
@@ -251,7 +251,6 @@ function defaultDelay(ms: number): Promise<void> {
|
|
|
251
251
|
const VALID_PHASES: ReadonlySet<string> = new Set<StoreMetaPhase>([
|
|
252
252
|
"idb-authoritative",
|
|
253
253
|
"opfs-candidate",
|
|
254
|
-
"adopting",
|
|
255
254
|
"opfs-committed",
|
|
256
255
|
"deleting",
|
|
257
256
|
]);
|
|
@@ -365,8 +364,9 @@ export async function readStoreMetaRecord(
|
|
|
365
364
|
}
|
|
366
365
|
|
|
367
366
|
/**
|
|
368
|
-
* Write (create or overwrite) a store's meta record —
|
|
369
|
-
*
|
|
367
|
+
* Write (create or overwrite) a store's meta record — written at CREATION for a store minted under the opfs
|
|
368
|
+
* commitment machinery, at the first pass that must write authority for a recordless idb store, and at each
|
|
369
|
+
* phase transition (invariant 12). A no-IDB environment cannot hold a record, so this is a
|
|
370
370
|
* best-effort no-op there (consistent with {@link readStoreMetaRecord} returning {@link META_STORE_UNAVAILABLE}).
|
|
371
371
|
*/
|
|
372
372
|
export async function writeStoreMetaRecord(
|
|
@@ -408,9 +408,9 @@ export async function deleteStoreMetaRecord(storePath: string, deps?: StoreMetaD
|
|
|
408
408
|
|
|
409
409
|
/**
|
|
410
410
|
* Does PGlite's idb database for this store ALREADY exist, WITHOUT creating it? The recordless-idb recognition
|
|
411
|
-
* check (invariant 14): no meta record + an existing idb store → `idb-authoritative`, never virgin.
|
|
412
|
-
*
|
|
413
|
-
*
|
|
411
|
+
* check (invariant 14): no meta record + an existing idb store → `idb-authoritative`, never virgin. An
|
|
412
|
+
* existing idb store's data is never overwritten by a fresh opfs mint — it is opened IN PLACE, whatever the
|
|
413
|
+
* booting home's capabilities, because a store's storage backend is fixed at first mint.
|
|
414
414
|
*
|
|
415
415
|
* Technique (per ADR-0049 D6 — NEVER `indexedDB.databases()`, which is absent on some engines): open the
|
|
416
416
|
* database with NO version. If `onupgradeneeded` fires, the database did NOT exist — flag it and ABORT the
|
|
@@ -45,6 +45,7 @@ import {
|
|
|
45
45
|
} from "../index";
|
|
46
46
|
import type { LocalStoreVersionEvent } from "../local-store";
|
|
47
47
|
import { createOpfsEffects, type OpfsEffectsDeps } from "../opfs-effects";
|
|
48
|
+
import { committedStoreUnreachableFromWire } from "../store-boot";
|
|
48
49
|
import { type DestructionEffects, runDestruction } from "../store-lifecycle";
|
|
49
50
|
import { deleteStoreMetaRecord, type StoreMetaDeps, writeStoreMetaRecord } from "../store-meta";
|
|
50
51
|
import { storeIndexedDbDatabaseName } from "../store-path";
|
|
@@ -213,6 +214,51 @@ export class ElectedEngineUnconstructibleError extends Error {
|
|
|
213
214
|
}
|
|
214
215
|
}
|
|
215
216
|
|
|
217
|
+
/**
|
|
218
|
+
* A {@link provisionSyncWorker} that never settled inside its bounded window (`provisionExpiryMs`, default 60000).
|
|
219
|
+
* The provision's three ordinary outcomes all depend on the SharedWorker connection being alive — the
|
|
220
|
+
* `provision-ack`, a storage-declaration refusal, an unconstructible elected engine — so a connection that DIES
|
|
221
|
+
* before any of them (the SharedWorker crashed, its port was never serviced, the elected engine never came up)
|
|
222
|
+
* would otherwise leave the caller pending FOREVER. The deadline settles it loudly instead.
|
|
223
|
+
*
|
|
224
|
+
* The guarantee is narrow, deliberately: it bounds THIS CALLER'S promise. What becomes of the worker-side create
|
|
225
|
+
* attempt is decided by PLACEMENT, and the two homes differ:
|
|
226
|
+
*
|
|
227
|
+
* - **SW-direct.** The attempt lives in the SharedWorker and is left running (an in-flight store open cannot be
|
|
228
|
+
* safely abandoned — a second open against the same store is an ownership conflict). A later
|
|
229
|
+
* {@link attachSyncClient} ADOPTS it if it completed and WAITS on it if it is genuinely stuck; a retried
|
|
230
|
+
* provision re-acks against the SAME attempt, so a second open never starts. A stuck storage open blocks that
|
|
231
|
+
* store whether or not it was ever provisioned, and expiring this promise neither causes nor cures that.
|
|
232
|
+
* - **Elected.** This deadline is ALSO the provision claim's expiry, so the claim releases here too. When it is
|
|
233
|
+
* the LAST claim on the store's coordinator, that release runs last-claim retirement (`engine-retiring` →
|
|
234
|
+
* `engine-teardown` → terminate), taking the elected engine and the attempt inside it — agent termination
|
|
235
|
+
* releases the VFS ownership — and the next attach elects a FRESH engine that opens the store again. An attach
|
|
236
|
+
* that adopted the coordinator BEFORE the expiry holds its own claim, which keeps the engine (and its attempt)
|
|
237
|
+
* alive: the SW-direct adopt-or-wait shape then applies here too.
|
|
238
|
+
*
|
|
239
|
+
* `[pgxsinkit]`-prefixed like the repo's other typed errors so a consumer can `instanceof`-branch it.
|
|
240
|
+
*/
|
|
241
|
+
export class ProvisionExpiredError extends Error {
|
|
242
|
+
/** The store whose provision expired — the `storePath` the call was made for. */
|
|
243
|
+
readonly storePath: string;
|
|
244
|
+
/** The window that elapsed without a settlement, in ms (the effective `provisionExpiryMs`). */
|
|
245
|
+
readonly expiryMs: number;
|
|
246
|
+
constructor(storePath: string, expiryMs: number) {
|
|
247
|
+
super(
|
|
248
|
+
`[pgxsinkit] provisionSyncWorker("${storePath}"): the provision did not settle within ${expiryMs}ms — the ` +
|
|
249
|
+
`SharedWorker connection may be dead or the elected engine never came up. The deadline bounds THIS ` +
|
|
250
|
+
`promise; the worker-side create attempt follows the placement. SW-direct: the attempt is left running, ` +
|
|
251
|
+
`so a later attach adopts it if it completed and waits on it if it is stuck, and a retry re-acks the ` +
|
|
252
|
+
`same attempt rather than starting a second open. Elected: this deadline also releases the provision ` +
|
|
253
|
+
`claim, and a LAST-claim release retires and terminates the engine, so the next attach elects a fresh ` +
|
|
254
|
+
`one. Retrying is safe either way.`,
|
|
255
|
+
);
|
|
256
|
+
this.name = "ProvisionExpiredError";
|
|
257
|
+
this.storePath = storePath;
|
|
258
|
+
this.expiryMs = expiryMs;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
216
262
|
/** The minimal `indexedDB.deleteDatabase` surface (no DOM lib) — mirrors `store-boot.ts`'s idb delete seam. */
|
|
217
263
|
interface IdbDeleteSurface {
|
|
218
264
|
deleteDatabase(name: string): {
|
|
@@ -809,19 +855,39 @@ const sharedCoordinators = new Map<
|
|
|
809
855
|
releaseProvision?: () => void;
|
|
810
856
|
/**
|
|
811
857
|
* The provision's live engine pipe, held for HANDOVER (ADR-0049 step 8). The router mints exactly ONE proxy
|
|
812
|
-
* pipe per SW connection; when provision and attach share one port (the documented
|
|
813
|
-
* e.g. the board), that pipe is delivered during provisioning — so the adopting
|
|
814
|
-
* rather than wait for a `connect-port` that
|
|
858
|
+
* pipe per SW connection PER ENGINE GENERATION; when provision and attach share one port (the documented
|
|
859
|
+
* ordered-messages contract, e.g. the board), that pipe is delivered during provisioning — so the adopting
|
|
860
|
+
* attach must receive THIS pipe rather than wait for a `connect-port` that may never be re-sent. Always the
|
|
861
|
+
* NEWEST pipe the provision was handed (ADR-0053 R3 — a later `connect-port` supersedes, never a corpse).
|
|
862
|
+
* Cleared on take; closed if never taken.
|
|
815
863
|
*/
|
|
816
864
|
provisionPipe?: { pipe: BridgePort; identity: EngineIdentity };
|
|
817
865
|
}
|
|
818
866
|
>();
|
|
819
867
|
|
|
868
|
+
/**
|
|
869
|
+
* Provision pipes delivered BEFORE their store's coordinator entry exists (ADR-0053 R3). A SharedWorker that
|
|
870
|
+
* survived its last tab (Chromium `extendedLifetime`) keeps an engine registered, so the router pipes a fresh
|
|
871
|
+
* connection the moment it is routed — i.e. on the DECLARATION, one task AHEAD of the placement reply that
|
|
872
|
+
* registers the coordinator. A stash that requires a registered entry drops exactly those pipes, and that pipe IS
|
|
873
|
+
* the handover an adopting attach on this port waits for (no `connect-port` re-send is owed to an already-piped
|
|
874
|
+
* connection). Held here until {@link adoptOrRegisterCoordinator} folds them into the entry it creates; closed
|
|
875
|
+
* with the entry so an unadopted provision leaks nothing.
|
|
876
|
+
*/
|
|
877
|
+
const pendingProvisionPipes = new Map<string, { pipe: BridgePort; identity: EngineIdentity }>();
|
|
878
|
+
|
|
820
879
|
/** Adopt an existing per-store coordinator (incrementing its ref), or register a freshly-built one. */
|
|
821
880
|
function adoptOrRegisterCoordinator(storePath: string, build: () => ElectionCoordinator): ElectionCoordinator {
|
|
822
881
|
let entry = sharedCoordinators.get(storePath);
|
|
823
882
|
if (entry === undefined) {
|
|
824
883
|
entry = { coordinator: build(), refs: 0 };
|
|
884
|
+
// Fold any pre-registry stash into the entry the placement reply is creating right now — from here on the
|
|
885
|
+
// entry is the single home of the handover pipe (one slot, so `takeProvisionPipe` can never see two).
|
|
886
|
+
const pending = pendingProvisionPipes.get(storePath);
|
|
887
|
+
if (pending !== undefined) {
|
|
888
|
+
pendingProvisionPipes.delete(storePath);
|
|
889
|
+
entry.provisionPipe = pending;
|
|
890
|
+
}
|
|
825
891
|
sharedCoordinators.set(storePath, entry);
|
|
826
892
|
}
|
|
827
893
|
entry.refs += 1;
|
|
@@ -847,21 +913,62 @@ function releaseSharedCoordinator(storePath: string): void {
|
|
|
847
913
|
if (entry.refs <= 0) {
|
|
848
914
|
entry.provisionPipe?.pipe.close?.();
|
|
849
915
|
sharedCoordinators.delete(storePath);
|
|
916
|
+
// Invariant: no stash for this store may outlive its coordinator entry. The fold at registration normally
|
|
917
|
+
// empties the pre-registry map, so this sweep is belt-and-braces — but it is the ONLY lifecycle hook a
|
|
918
|
+
// never-adopted provision (expiry retirement) passes through, so an unclaimed pipe is closed here or nowhere.
|
|
919
|
+
const pending = pendingProvisionPipes.get(storePath);
|
|
920
|
+
if (pending !== undefined) {
|
|
921
|
+
pendingProvisionPipes.delete(storePath);
|
|
922
|
+
pending.pipe.close?.();
|
|
923
|
+
}
|
|
850
924
|
}
|
|
851
925
|
}
|
|
852
926
|
|
|
853
|
-
/**
|
|
927
|
+
/**
|
|
928
|
+
* Stash the provision's engine pipe for the adopting attach's handover — into the registered coordinator entry
|
|
929
|
+
* when one exists, else into {@link pendingProvisionPipes} (the pipe can legitimately arrive BEFORE the placement
|
|
930
|
+
* reply registers the entry, ADR-0053 R3).
|
|
931
|
+
*
|
|
932
|
+
* NEWEST WINS for the SLOT, but closing the superseded pipe is gated on the ENGINE IDENTITY, not on pipe
|
|
933
|
+
* identity. A second pipe is not proof of a new engine: the router mints one pipe per CONNECTION, so two
|
|
934
|
+
* concurrent {@link provisionSyncWorker} calls for the same store (React StrictMode double-effects firing a warm
|
|
935
|
+
* twice, two eager warms) are piped separately for the SAME generation.
|
|
936
|
+
*
|
|
937
|
+
* - **Same identity** → the previous pipe stays OPEN. Both pipes are equivalent conduits to one live engine, and
|
|
938
|
+
* the un-stashed one is still the only route its own caller's `provision-ack` can ride; closing it strands that
|
|
939
|
+
* provision promise forever (the claim expiry retires the claim, it does not settle the promise). It carries
|
|
940
|
+
* that one ack and then settles idle — bounded, and the price of never stranding a caller.
|
|
941
|
+
* - **Changed identity** → the previous pipe's engine is gone or being replaced, so nothing may ride it again:
|
|
942
|
+
* close it, as before.
|
|
943
|
+
*
|
|
944
|
+
* A pipe already HANDED OVER is no longer in the slot (take clears it), so this never closes the pipe an attach is
|
|
945
|
+
* running on: that pipe's owner closes it on its own swap.
|
|
946
|
+
*/
|
|
854
947
|
function stashProvisionPipe(storePath: string, pipe: BridgePort, identity: EngineIdentity): void {
|
|
855
948
|
const entry = sharedCoordinators.get(storePath);
|
|
949
|
+
const previous = entry !== undefined ? entry.provisionPipe : pendingProvisionPipes.get(storePath);
|
|
950
|
+
if (previous !== undefined && previous.pipe !== pipe && !engineIdentityEquals(previous.identity, identity)) {
|
|
951
|
+
previous.pipe.close?.();
|
|
952
|
+
}
|
|
856
953
|
if (entry !== undefined) entry.provisionPipe = { pipe, identity };
|
|
954
|
+
else pendingProvisionPipes.set(storePath, { pipe, identity });
|
|
857
955
|
}
|
|
858
956
|
|
|
859
|
-
/**
|
|
957
|
+
/**
|
|
958
|
+
* Take (and clear) the stashed provision pipe — exactly one adopting attach may consume it. Consults the
|
|
959
|
+
* registered entry first, then the pre-registry stash: an attach can adopt a coordinator whose entry was created
|
|
960
|
+
* by a path that never folded (or before the fold), and the handover must still find the pipe.
|
|
961
|
+
*/
|
|
860
962
|
function takeProvisionPipe(storePath: string): { pipe: BridgePort; identity: EngineIdentity } | undefined {
|
|
861
963
|
const entry = sharedCoordinators.get(storePath);
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
964
|
+
if (entry?.provisionPipe !== undefined) {
|
|
965
|
+
const stashed = entry.provisionPipe;
|
|
966
|
+
delete entry.provisionPipe;
|
|
967
|
+
return stashed;
|
|
968
|
+
}
|
|
969
|
+
const pending = pendingProvisionPipes.get(storePath);
|
|
970
|
+
if (pending !== undefined) pendingProvisionPipes.delete(storePath);
|
|
971
|
+
return pending;
|
|
865
972
|
}
|
|
866
973
|
|
|
867
974
|
/** Record the provision claim's explicit release companion on its shared coordinator entry. */
|
|
@@ -2349,10 +2456,21 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2349
2456
|
| "timers"
|
|
2350
2457
|
> & {
|
|
2351
2458
|
/**
|
|
2352
|
-
*
|
|
2353
|
-
*
|
|
2459
|
+
* The provision's ONE bounded window (ms), default 60000. It governs two things at the same deadline:
|
|
2460
|
+
*
|
|
2461
|
+
* - **The returned promise, in BOTH modes.** A provision that has not settled by then rejects with the typed
|
|
2462
|
+
* {@link ProvisionExpiredError} — never a promise that hangs forever behind a dead SharedWorker connection.
|
|
2463
|
+
* It bounds the PROMISE; the worker-side create attempt follows the placement split (see
|
|
2464
|
+
* {@link ProvisionExpiredError}).
|
|
2465
|
+
* - **The elected-mode claim** (and its shared-coordinator ref): an abandoned warmed provision auto-retires
|
|
2466
|
+
* (ADR-0049 step 8, "abandoned warmed provision → claim expiry"). Releasing the LAST claim runs last-claim
|
|
2467
|
+
* retirement — notice, teardown, terminate — so the elected engine, and any create still open inside it, goes
|
|
2468
|
+
* with the claim. Inert on SW-direct, which elects nothing.
|
|
2469
|
+
*
|
|
2354
2470
|
* A later {@link attachSyncClient} on the same store ADOPTS the grant within this window (adding its own claim,
|
|
2355
|
-
* so the engine outlives the expiry).
|
|
2471
|
+
* so the engine outlives the expiry). After an expiry that attach meets what the placement left it: an
|
|
2472
|
+
* SW-direct attempt is still there to adopt or wait on — expiring the promise never frees a stuck store —
|
|
2473
|
+
* while a retired elected engine is replaced by a fresh election that opens the store again.
|
|
2356
2474
|
*/
|
|
2357
2475
|
provisionExpiryMs?: number;
|
|
2358
2476
|
};
|
|
@@ -2361,8 +2479,12 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2361
2479
|
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
|
|
2362
2480
|
* freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the raw store idle
|
|
2363
2481
|
* until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
|
|
2364
|
-
* settled); rejects
|
|
2365
|
-
*
|
|
2482
|
+
* settled); rejects if the worker reports the create failed, if it refuses the storage declaration, if the elected
|
|
2483
|
+
* engine is unconstructible, or — bounding the whole thing — with {@link ProvisionExpiredError} once
|
|
2484
|
+
* `provisionExpiryMs` (default 60000) elapses without any of those. The caller treats every outcome as
|
|
2485
|
+
* best-effort: a provision that fails or expires costs the accelerator, not the boot — the attach that follows
|
|
2486
|
+
* meets whatever the worker actually opened (an expiry bounds THIS promise; the worker-side create attempt is
|
|
2487
|
+
* kept or retired by the placement — see {@link ProvisionExpiredError}).
|
|
2366
2488
|
*
|
|
2367
2489
|
* Routed through the SAME placement-query-first flow as {@link attachSyncClient} (ADR-0049 step 8): a SW-direct
|
|
2368
2490
|
* (or declared-idbfs) SharedWorker takes the `provision` bridge envelope on the SW port; a
|
|
@@ -2382,6 +2504,8 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2382
2504
|
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
|
|
2383
2505
|
};
|
|
2384
2506
|
const storePath = options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
|
|
2507
|
+
// ONE deadline, read once and shared by the two timers armed below (settlement window + elected claim expiry).
|
|
2508
|
+
const expiryMs = options.provisionExpiryMs ?? 60_000;
|
|
2385
2509
|
// The testing memory-backend override travels as an explicit wire field (a symbol does not survive structured
|
|
2386
2510
|
// clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
|
|
2387
2511
|
const memoryOverride = readTestStoreMarker(options) === "memory";
|
|
@@ -2398,6 +2522,8 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2398
2522
|
const provision = new Promise<void>((resolve, reject) => {
|
|
2399
2523
|
let settled = false;
|
|
2400
2524
|
const ackRemovers: Array<() => void> = [];
|
|
2525
|
+
/** The settlement-window handle (armed below, cleared by {@link settle}). */
|
|
2526
|
+
let settlementHandle: unknown;
|
|
2401
2527
|
const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }): void => {
|
|
2402
2528
|
const placement = readPlacementResult(event.data);
|
|
2403
2529
|
if (placement !== undefined) {
|
|
@@ -2419,9 +2545,32 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2419
2545
|
settled = true;
|
|
2420
2546
|
port.removeEventListener("message", controlListener);
|
|
2421
2547
|
for (const remove of ackRemovers) remove();
|
|
2548
|
+
timers.clearTimeout(settlementHandle);
|
|
2422
2549
|
fn();
|
|
2423
2550
|
};
|
|
2424
2551
|
|
|
2552
|
+
// THE SETTLEMENT WINDOW — one bounded deadline for this promise in BOTH modes. Every ordinary outcome (the
|
|
2553
|
+
// `provision-ack`, a declaration refusal, an unconstructible elected engine) needs a LIVE SharedWorker
|
|
2554
|
+
// connection, so a connection that dies before any of them arrive (the SW crashed, the port was never
|
|
2555
|
+
// serviced, the elected engine never came up) would leave the caller pending FOREVER. Armed HERE — ahead of
|
|
2556
|
+
// the declaration and the placement query — so even a port nothing ever answers is bounded.
|
|
2557
|
+
//
|
|
2558
|
+
// It bounds the PROMISE; the worker-side attempt is placement-dependent. SW-DIRECT: the create is left
|
|
2559
|
+
// running (an in-flight store open cannot be safely abandoned), so a later attach adopts it if it completes
|
|
2560
|
+
// and waits on it if it is stuck. ELECTED: this deadline's twin below releases the provision claim, and a
|
|
2561
|
+
// LAST-claim release retires and terminates the elected engine with that attempt inside it, so the next
|
|
2562
|
+
// attach elects a fresh engine and opens the store again.
|
|
2563
|
+
//
|
|
2564
|
+
// Deliberately SEPARATE from the elected path's claim expiry (`onPlacement` below). The two share this
|
|
2565
|
+
// deadline by default but own different things: the claim expiry is CONTRACT CLEANUP (release the provision
|
|
2566
|
+
// claim and the shared-coordinator ref so an abandoned warmed provision never pins the leader lock, ADR-0049
|
|
2567
|
+
// step 8), this one is the CALLER'S SETTLEMENT. Merging them would tie settlement to the elected path, which
|
|
2568
|
+
// SW-direct never takes. A `provision-ack` or `connect-port` arriving after expiry is already inert — `settle`
|
|
2569
|
+
// removed every listener and the `settled` guard holds — so a late engine can never re-settle this promise.
|
|
2570
|
+
settlementHandle = timers.setTimeout(() => {
|
|
2571
|
+
settle(() => reject(new ProvisionExpiredError(storePath, expiryMs)));
|
|
2572
|
+
}, expiryMs);
|
|
2573
|
+
|
|
2425
2574
|
// Await `provision-ack` on whichever port carries it: the SW port (SW-direct) or the elected engine's pipe.
|
|
2426
2575
|
// In elected mode the SW-port `provision` is dropped by the router, so its ack never comes — the pipe's does.
|
|
2427
2576
|
const awaitAckOn = (ackPort: BridgePort): void => {
|
|
@@ -2440,14 +2589,25 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2440
2589
|
};
|
|
2441
2590
|
|
|
2442
2591
|
let placementDecided = false;
|
|
2443
|
-
let piped = false;
|
|
2444
2592
|
const onProvisionPipe = (pipe: BridgePort | undefined, identity: EngineIdentity): void => {
|
|
2445
|
-
|
|
2446
|
-
|
|
2593
|
+
// Settled → INERT. `settle` already removed this control listener, so a post-settlement `connect-port` is
|
|
2594
|
+
// structurally unseen; the flag states the invariant rather than relying on that (a re-post after the ack
|
|
2595
|
+
// would double-provision an engine, and re-stashing a pipe nothing awaits would leak it).
|
|
2596
|
+
if (settled || pipe === undefined) return;
|
|
2447
2597
|
// The router piped this provision connection to the elected engine — deliver the `provision` over the pipe,
|
|
2448
|
-
// and STASH
|
|
2449
|
-
//
|
|
2450
|
-
//
|
|
2598
|
+
// and STASH it for the adopting attach's handover (the board's ordered-messages contract: provision and
|
|
2599
|
+
// attach share one port, and the pipe minted during provisioning is the one the attach must ride).
|
|
2600
|
+
//
|
|
2601
|
+
// NEWEST PIPE WINS (ADR-0053 R3). The router mints exactly one pipe per connection PER ENGINE GENERATION, so
|
|
2602
|
+
// a SECOND `connect-port` means the previous pipe's engine is gone or being replaced — it is never a
|
|
2603
|
+
// duplicate to ignore. Latching on the FIRST pipe forfeits the warm-boot accelerator on every reopen under a
|
|
2604
|
+
// SURVIVING SharedWorker (Chromium `extendedLifetime`): its still-registered DEAD engine is piped ahead of
|
|
2605
|
+
// the placement reply and swallows the envelope, so refusing the election's fresh pipe leaves the provision
|
|
2606
|
+
// promise pending forever and the adopting boot degrades to a plain create. So supersede: stash the new pipe
|
|
2607
|
+
// (closing the replaced one) and post the `provision` again on it. Re-posting is SAFE by the
|
|
2608
|
+
// engine's contract — its provision handler acks `ok` immediately when a boot/provision is already in flight
|
|
2609
|
+
// or done — and the FIRST ack from ANY posted pipe settles this promise (a late ack from a superseded but
|
|
2610
|
+
// still-live engine is benign; `settle` removes every ack listener at once).
|
|
2451
2611
|
stashProvisionPipe(storePath, pipe, identity);
|
|
2452
2612
|
postProvisionOn(pipe);
|
|
2453
2613
|
};
|
|
@@ -2495,8 +2655,16 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2495
2655
|
// The PROVISION CLAIM elects → the coordinator spawns the engine + announces; the router pipes this
|
|
2496
2656
|
// connection (→ `onProvisionPipe`). Bound by expiry: an abandoned warmed provision auto-retires (its claim
|
|
2497
2657
|
// AND its shared-coordinator ref release together), so a store nobody adopts never pins the leader lock.
|
|
2658
|
+
// When this was the LAST claim the coordinator runs the retirement (notice → teardown → terminate), so the
|
|
2659
|
+
// elected engine and any create still open inside it go with the claim; an attach that adopted the
|
|
2660
|
+
// coordinator first holds its own claim and keeps both alive.
|
|
2661
|
+
//
|
|
2662
|
+
// This is the CLAIM half of the deadline, and it stays independent of the settlement window armed at the top
|
|
2663
|
+
// of this executor: both fire at `expiryMs`, but this one owns the ELECTION CONTRACT (claim + coordinator
|
|
2664
|
+
// ref) and that one owns the PROMISE. They are kept apart because their scopes differ — the settlement
|
|
2665
|
+
// window also covers SW-direct, which never reaches this branch, and an ADOPTED provision releases this
|
|
2666
|
+
// claim early (`releaseProvision`) long after its promise resolved.
|
|
2498
2667
|
const releaseProvisionClaim = coordinator.claimForProvision();
|
|
2499
|
-
const expiryMs = options.provisionExpiryMs ?? 60_000;
|
|
2500
2668
|
let released = false;
|
|
2501
2669
|
const expiryHandle = timers.setTimeout(() => {
|
|
2502
2670
|
if (released) return;
|
|
@@ -2584,12 +2752,17 @@ function deriveEngineWorkerFactory(swScriptUrl: string | undefined): (() => Elec
|
|
|
2584
2752
|
/**
|
|
2585
2753
|
* Rebuild an Error from the bridge's serialized {@link BridgeErrorWire} shape, carrying `name` and `detail`
|
|
2586
2754
|
* through. Restoring `name` is what keeps a typed worker-side failure (e.g. a restore refused with
|
|
2587
|
-
* `RestoreTargetExistsError`) detectable by the consumer without message matching
|
|
2755
|
+
* `RestoreTargetExistsError`) detectable by the consumer without message matching; a tagged `detail` does
|
|
2756
|
+
* better still — it rebuilds the CLASS, so `instanceof` holds on the tab side too.
|
|
2588
2757
|
*/
|
|
2589
2758
|
function rebuildError(error: RpcResultPayload["error"]): Error {
|
|
2590
2759
|
if (error && "detail" in error) {
|
|
2591
2760
|
const mismatch = executionLimitMismatchFromWire(error.detail);
|
|
2592
2761
|
if (mismatch !== undefined) return mismatch;
|
|
2762
|
+
// A no-grant engine home refusing an `opfs-committed` store: the consumer branches on the TYPE to offer
|
|
2763
|
+
// the destroy-then-rebuild exit, so it must cross the bridge as the class, not a name-tagged plain Error.
|
|
2764
|
+
const unreachable = committedStoreUnreachableFromWire(error.detail);
|
|
2765
|
+
if (unreachable !== undefined) return unreachable;
|
|
2593
2766
|
}
|
|
2594
2767
|
const rebuilt = new Error(error?.message ?? "worker rpc failed");
|
|
2595
2768
|
if (error?.name !== undefined) {
|