@pgxsinkit/client 0.1.53 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/adoption.d.ts +118 -0
- package/dist/adoption.d.ts.map +1 -0
- package/dist/boot-report.d.ts +54 -15
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/convergence.d.ts +2 -1
- package/dist/convergence.d.ts.map +1 -1
- package/dist/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +270 -52
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4492 -1511
- package/dist/index.js.map +34 -24
- package/dist/live-rows-sql.d.ts +1 -1
- package/dist/local-store.d.ts +16 -31
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +4 -4
- package/dist/mutation.d.ts +12 -15
- package/dist/mutation.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +51 -0
- package/dist/opfs-effects.d.ts.map +1 -0
- package/dist/placement-probe.d.ts +75 -0
- package/dist/placement-probe.d.ts.map +1 -0
- package/dist/schema.d.ts +11 -16
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +77 -0
- package/dist/store-boot.d.ts.map +1 -0
- package/dist/store-lifecycle.d.ts +153 -0
- package/dist/store-lifecycle.d.ts.map +1 -0
- package/dist/store-meta.d.ts +190 -0
- package/dist/store-meta.d.ts.map +1 -0
- package/dist/store-path.d.ts +77 -7
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/shape-inbox.d.ts +1 -1
- package/dist/sync/types.d.ts +3 -3
- package/dist/testing.js.map +3 -3
- package/dist/worker/attach-sync-client.d.ts +235 -12
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +138 -22
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/election-coordinator.d.ts +95 -0
- package/dist/worker/election-coordinator.d.ts.map +1 -0
- package/dist/worker/engine-control.d.ts +265 -0
- package/dist/worker/engine-control.d.ts.map +1 -0
- package/dist/worker/engine-router.d.ts +75 -0
- package/dist/worker/engine-router.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +15 -10
- package/dist/worker/protocol.d.ts.map +1 -1
- package/dist/worker/sw-placement.d.ts +37 -0
- package/dist/worker/sw-placement.d.ts.map +1 -0
- package/package.json +4 -3
- package/skills/core/SKILL.md +15 -12
- package/skills/operating/SKILL.md +103 -46
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1109 -115
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +2 -2
- package/src/mutation.ts +67 -49
- package/src/mutations-api.ts +3 -3
- package/src/opfs-effects.ts +160 -0
- package/src/placement-probe.ts +168 -0
- package/src/schema.ts +17 -22
- package/src/store-boot.ts +343 -0
- package/src/store-lifecycle.ts +227 -0
- package/src/store-meta.ts +459 -0
- package/src/store-path.ts +197 -22
- package/src/sync/apply.ts +63 -63
- package/src/sync/index.ts +2 -2
- package/src/sync/shape-inbox.ts +1 -1
- package/src/sync/types.ts +3 -3
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +1556 -97
- package/src/worker/define-sync-worker.ts +723 -73
- package/src/worker/election-coordinator.ts +462 -0
- package/src/worker/engine-control.ts +379 -0
- package/src/worker/engine-router.ts +355 -0
- package/src/worker/live-query-manager.ts +4 -1
- package/src/worker/protocol.ts +13 -10
- package/src/worker/sw-placement.ts +64 -0
|
@@ -10,11 +10,13 @@
|
|
|
10
10
|
import { type ParserOptions, type QueryOptions, types } from "@electric-sql/pglite";
|
|
11
11
|
|
|
12
12
|
import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
|
|
13
|
+
import { getSyncRegistryStorage } from "@pgxsinkit/contracts";
|
|
13
14
|
|
|
14
15
|
import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
|
|
15
16
|
import { setSyncDebugSink, syncDebug } from "../debug";
|
|
16
17
|
import { describeErrorChain } from "../error-chain";
|
|
17
18
|
import {
|
|
19
|
+
type AdoptionDeclaration,
|
|
18
20
|
type ClientPGlite,
|
|
19
21
|
createClientPGlite,
|
|
20
22
|
type CreateSyncClientOptions,
|
|
@@ -28,7 +30,21 @@ import {
|
|
|
28
30
|
} from "../index";
|
|
29
31
|
import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
|
|
30
32
|
import type { LocalStoreVersionEvent } from "../local-store";
|
|
33
|
+
import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
|
|
34
|
+
import { META_STORE_UNAVAILABLE, readStoreMetaRecord } from "../store-meta";
|
|
31
35
|
import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
|
|
36
|
+
import {
|
|
37
|
+
assertSameExecutionLimit,
|
|
38
|
+
type EngineControlMessage,
|
|
39
|
+
type EngineIdentity,
|
|
40
|
+
ExecutionLimitMismatchError,
|
|
41
|
+
executionLimitMismatchToWire,
|
|
42
|
+
type ExecutionLimitConfig,
|
|
43
|
+
readControlEnvelope,
|
|
44
|
+
shouldApplyControlMessage,
|
|
45
|
+
wrapControlEnvelope as controlEnvelope,
|
|
46
|
+
} from "./engine-control";
|
|
47
|
+
import { createEngineRouter, type EngineRouter, type RouterPort } from "./engine-router";
|
|
32
48
|
import {
|
|
33
49
|
createLiveQueryManager,
|
|
34
50
|
type LiveQueryManager,
|
|
@@ -54,6 +70,7 @@ import {
|
|
|
54
70
|
type SubscribePayload,
|
|
55
71
|
type TokenResponsePayload,
|
|
56
72
|
} from "./protocol";
|
|
73
|
+
import { decideSwPlacement, type SwPlacementResult } from "./sw-placement";
|
|
57
74
|
import { createWorkerTokenCache } from "./token-cache";
|
|
58
75
|
|
|
59
76
|
// The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4). It
|
|
@@ -102,22 +119,18 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
102
119
|
*/
|
|
103
120
|
createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
|
|
104
121
|
/**
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
* asynchronously. Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a
|
|
114
|
-
* crash before BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the
|
|
115
|
-
* scheduled idb flush lands — synced tables are recoverable from the server by construction, so this
|
|
116
|
-
* relaxes flush TIMING, not persistence (ADR-0036). Opt out with `relaxedDurability: false`.
|
|
122
|
+
* ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
|
|
123
|
+
* reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
|
|
124
|
+
* committed OPFS successor. A worker-ENTRY option (baked into the worker file as code, like
|
|
125
|
+
* {@link executionLimit}), NEVER an attach option — a tab cannot set it (adoption DELETES local-only data, so
|
|
126
|
+
* only the code author may authorize it). Forwarded verbatim to the {@link createSyncClient} boot below. DEFAULT
|
|
127
|
+
* OFF (`undefined`): hook absence is never authority — only `"server-reconstructible"` (or the manual
|
|
128
|
+
* `adoptStore` API) authorizes deleting the idb predecessor. Honoured only where the engine home grants OPFS
|
|
129
|
+
* access (SW-direct / elected placement); inert on the browser-idb fallback where there is no opfs successor.
|
|
117
130
|
*/
|
|
118
|
-
|
|
131
|
+
adoption?: AdoptionDeclaration;
|
|
119
132
|
electricUrl: string;
|
|
120
|
-
|
|
133
|
+
batchWriteUrl: string;
|
|
121
134
|
/** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
|
|
122
135
|
requestHeaders?: Record<string, string>;
|
|
123
136
|
/** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
|
|
@@ -138,6 +151,15 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
138
151
|
* (`flush` + `reconcile` queries). Default 15000.
|
|
139
152
|
*/
|
|
140
153
|
convergenceIntervalMs?: number;
|
|
154
|
+
/**
|
|
155
|
+
* The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5), threaded into the ROUTER when this
|
|
156
|
+
* SharedWorker lands in `elected-worker` placement (router-only mode). DISABLED by default (`undefined` /
|
|
157
|
+
* absent `maxDispatchMs`) — no finite worst-case query duration exists, so an absent limit means the router
|
|
158
|
+
* forwards no probe and queries run unbounded; enabling it is a deliberate consumer choice.
|
|
159
|
+
* Elected placement ONLY: on SW-direct (`shared-worker`) the engine home is in-scope and there is no control
|
|
160
|
+
* channel to probe, so an enabled value is rejected as unsupported before engine boot.
|
|
161
|
+
*/
|
|
162
|
+
executionLimit?: ExecutionLimitConfig;
|
|
141
163
|
/** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
|
|
142
164
|
installGlobal?: boolean;
|
|
143
165
|
/** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
|
|
@@ -158,7 +180,7 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
158
180
|
* NOT an attach option: the hook is a function and functions cannot cross the bridge, so a tab can never
|
|
159
181
|
* supply it — the worker owns it. Use it for DDL that must precede the registry's local tables (extensions,
|
|
160
182
|
* a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
|
|
161
|
-
* this runs (that ordering is what distinguishes it from {@link
|
|
183
|
+
* this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
|
|
162
184
|
*
|
|
163
185
|
* Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
|
|
164
186
|
* {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
|
|
@@ -168,7 +190,7 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
168
190
|
prepareLocalDbBeforeSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbBeforeSchema"];
|
|
169
191
|
/**
|
|
170
192
|
* App-level schema prep run IN THE WORKER, against the engine's own local store, AFTER the registry schema
|
|
171
|
-
* exec — forwarded verbatim to {@link CreateSyncClientOptions.
|
|
193
|
+
* exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbAfterSchema}, same timing as the in-process
|
|
172
194
|
* client. Like {@link prepareLocalDbBeforeSchema} this is a worker-ENTRY option, never an attach option (the
|
|
173
195
|
* tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
|
|
174
196
|
* that depend on the registry's local tables, which DO exist by the time this runs.
|
|
@@ -176,15 +198,16 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
176
198
|
* Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
|
|
177
199
|
* {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
|
|
178
200
|
*/
|
|
179
|
-
|
|
201
|
+
prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
|
|
180
202
|
/**
|
|
181
203
|
* Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
|
|
182
204
|
* subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
|
|
183
205
|
* period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
|
|
184
206
|
* re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
|
|
185
|
-
* down the instant its last consumer leaves
|
|
186
|
-
*
|
|
187
|
-
*
|
|
207
|
+
* down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
|
|
208
|
+
* full SQL rerun + diff on every dependent write — PGlite live queries cannot be paused — so retention
|
|
209
|
+
* only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
|
|
210
|
+
* no surprise standing SQL reruns.
|
|
188
211
|
*/
|
|
189
212
|
liveQueries?: {
|
|
190
213
|
/** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
|
|
@@ -225,15 +248,47 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
225
248
|
const codec = options.codec ?? identityCodec;
|
|
226
249
|
const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
|
|
227
250
|
const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
|
|
251
|
+
// ADR-0049 D1: the placement probe's OPFS grant for THIS SharedWorker lifetime. Set true only by a GRANTED
|
|
252
|
+
// `shared-worker` (SW-direct) probe, so both the provision-mint (default `createPglite` factory) and the boot
|
|
253
|
+
// create (below) resolve the OPFS-repacked backend. False is the honest capability-absence invariant — the
|
|
254
|
+
// engine home in this scope opens IDBFS: the registry-declared `backend: "idbfs"` mode (no probe ran), or a
|
|
255
|
+
// capability-absence fallback (every home's probe denied / the OPFS API absent). Read at CALL time — every mint
|
|
256
|
+
// that consults it runs only after a port has connected, and connections are gated on the resolved placement.
|
|
257
|
+
let placementOpfsAccess = false;
|
|
258
|
+
// ADR-0049 D1/D12: the verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (a fallback,
|
|
259
|
+
// not the declared-idbfs mode). Set alongside `placementOpfsAccess = false` by the bootstrap's capability-absence
|
|
260
|
+
// fallback outcome; threaded into the boot's `storageFallbackReason`. Absent for a granted opfs boot AND for the
|
|
261
|
+
// declared `backend: "idbfs"` mode (that is the contract, not a fallback — no reason to report).
|
|
262
|
+
let placementFallbackReason: string | undefined;
|
|
263
|
+
// ADR-0049 decision 12 (diagnostics): the resolved engine home for THIS SharedWorker scope, threaded into the
|
|
264
|
+
// boot's {@link BootReport} (`engineHome`). Set alongside `placementOpfsAccess` when the placement decision
|
|
265
|
+
// resolves. Both the SharedWorker and an elected dedicated-engine worker run the probe; only a plain test/Node
|
|
266
|
+
// scope that has no browser placement omits `engineHome`.
|
|
267
|
+
let placementEngineHome: SwPlacementResult["engineHome"] | undefined;
|
|
268
|
+
// ADR-0049 step 10b (bug fix — elected engine self-probe): the boot's OPFS grant may be decided ASYNCHRONOUSLY
|
|
269
|
+
// (the SharedWorker placement decision, or — for the elected DEDICATED engine — that scope's own OPFS probe).
|
|
270
|
+
// Both resolve BEFORE the first attach in practice, but the elected engine's probe races the incoming
|
|
271
|
+
// `connect-port` pipe, so `boot()` AWAITS this gate before reading `placementOpfsAccess`/`placementEngineHome` —
|
|
272
|
+
// guaranteeing the grant is threaded into the boot options (invariant 8: probed per boot, never assumed). Opened
|
|
273
|
+
// by {@link bootstrapWorkerScope}'s `onPlacement` (SharedWorker decision OR dedicated-engine probe OR the plain
|
|
274
|
+
// test/Node scope's immediate settle); opened immediately when no global bootstrap runs (`installGlobal:false`).
|
|
275
|
+
let openPlacementGate!: () => void;
|
|
276
|
+
const placementGate = new Promise<void>((resolve) => {
|
|
277
|
+
openPlacementGate = resolve;
|
|
278
|
+
});
|
|
279
|
+
// Durability (ADR-0047) is registry-declared. The provision/spare mint does not run through
|
|
280
|
+
// `createSyncClient` (which resolves it for the boot create), so resolve it here off the DEFAULT registry —
|
|
281
|
+
// provision is role-agnostic (the role is settled only at claim/attach), and durability binds every store
|
|
282
|
+
// this worker mints regardless of role — and thread the resolved mode into the internal carrier.
|
|
283
|
+
const provisionDurability = getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
|
|
228
284
|
const createPglite =
|
|
229
285
|
options.createPglite ??
|
|
230
286
|
((storePath: string, backendOverride?: "memory") =>
|
|
231
|
-
// Relaxed durability (ADR-0047): the default factory forwards the worker-entry choice into
|
|
232
|
-
// `createClientPGlite`, which resolves the `?? true` default. A store minted for a spare/provision
|
|
233
|
-
// (`provision` handler) is thus created under the same durability mode the boot create uses.
|
|
234
287
|
createClientPGlite(storePath, {
|
|
235
288
|
...(backendOverride ? { backendOverride } : {}),
|
|
236
|
-
|
|
289
|
+
durability: provisionDurability,
|
|
290
|
+
// SW-direct placement grant (ADR-0049 D1): a spare minted in-scope opens OPFS-repacked, matching the boot.
|
|
291
|
+
...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
237
292
|
}));
|
|
238
293
|
// A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
|
|
239
294
|
// non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
|
|
@@ -289,6 +344,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
289
344
|
pglite: Promise<ClientPGlite>;
|
|
290
345
|
stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
|
|
291
346
|
} | null = null;
|
|
347
|
+
// A provision request performs a bounded authority read before it may mint. An attach that arrives during
|
|
348
|
+
// that read waits for the attempt to settle, then either adopts the minted store or runs the ordinary boot
|
|
349
|
+
// path. This keeps provision a pure accelerator without racing a replacement underneath live deletion.
|
|
350
|
+
let provisionAttempt: Promise<void> | null = null;
|
|
292
351
|
|
|
293
352
|
// ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
|
|
294
353
|
// The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
|
|
@@ -420,7 +479,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
420
479
|
...(stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}),
|
|
421
480
|
});
|
|
422
481
|
|
|
423
|
-
const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
|
|
482
|
+
const boot = async (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
|
|
483
|
+
await placementGate;
|
|
484
|
+
// Provision owns no recovery policy. Wait only for its bounded pre-mint check/create attempt; a declined
|
|
485
|
+
// attempt leaves `provisioned` null and this attach continues through createSyncClient's full phase machine.
|
|
486
|
+
await provisionAttempt?.catch(() => undefined);
|
|
487
|
+
const attachLimit = attach.executionLimit?.maxDispatchMs;
|
|
488
|
+
if (placementEngineHome === "shared-worker" && attachLimit !== undefined) {
|
|
489
|
+
throw new Error(
|
|
490
|
+
"[pgxsinkit] executionLimit is unsupported for SharedWorker-direct placement; it is available only " +
|
|
491
|
+
"when the engine runs in elected-worker placement (ADR-0049 D5).",
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
assertSameExecutionLimit(options.executionLimit?.maxDispatchMs, attachLimit);
|
|
424
495
|
if (bootPromise) return bootPromise;
|
|
425
496
|
// The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
|
|
426
497
|
tokenCache.push(attach.token);
|
|
@@ -465,10 +536,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
465
536
|
if (restoreFrom) {
|
|
466
537
|
syncDebug("worker restoring store from backup", { storePath, byteLength: attach.restore!.buffer.byteLength });
|
|
467
538
|
}
|
|
539
|
+
// Gate the store create on the resolved placement grant (ADR-0049 step 10b, elected-engine self-probe fix):
|
|
540
|
+
// `placementOpfsAccess` / `placementEngineHome` are read INSIDE this `.then`, after the probe settles, so the
|
|
541
|
+
// elected dedicated engine boots the OPFS-repacked backend it actually holds instead of racing to `idbfs`.
|
|
468
542
|
bootPromise = createSyncClient<TRegistry>({
|
|
469
543
|
registry,
|
|
470
544
|
electricUrl: options.electricUrl,
|
|
471
|
-
|
|
545
|
+
batchWriteUrl: options.batchWriteUrl,
|
|
472
546
|
storePath,
|
|
473
547
|
// Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
|
|
474
548
|
// memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —
|
|
@@ -480,20 +554,35 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
480
554
|
// Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an
|
|
481
555
|
// adopted spare's initdb cost is reported rather than a create this boot never ran.
|
|
482
556
|
bootMode: "worker",
|
|
557
|
+
// ADR-0049 decision 12 diagnostics: stamp the resolved engine home into the BootReport. This is
|
|
558
|
+
// `"shared-worker"` for the in-scope host or `"elected-worker"` for the elected dedicated engine; it is
|
|
559
|
+
// omitted only for a plain test/Node scope with no browser placement.
|
|
560
|
+
...(placementEngineHome ? { engineHome: placementEngineHome } : {}),
|
|
483
561
|
...(provisionStamp ? { provisionStamp } : {}),
|
|
484
562
|
...(precreatedPglite ? { precreatedPglite } : {}),
|
|
485
563
|
...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
|
|
486
564
|
// App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
|
|
487
565
|
// the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
|
|
488
566
|
...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
|
|
489
|
-
...(options.
|
|
490
|
-
//
|
|
491
|
-
//
|
|
492
|
-
//
|
|
493
|
-
|
|
567
|
+
...(options.prepareLocalDbAfterSchema ? { prepareLocalDbAfterSchema: options.prepareLocalDbAfterSchema } : {}),
|
|
568
|
+
// Durability (ADR-0047) is registry-declared: `createSyncClient` resolves it from `registry` at its own
|
|
569
|
+
// mint seam, so this boot needs no durability forward — the same `registry` decides the boot create's mode.
|
|
570
|
+
// SW-direct placement grant (ADR-0049 D1): thread a GRANTED probe's grant into the boot create so the engine
|
|
571
|
+
// home in this SharedWorker scope opens the OPFS-repacked backend. Absent (false) is the honest IDBFS home —
|
|
572
|
+
// the declared `backend: "idbfs"` mode or a capability-absence fallback. `createSyncClient` forwards it to
|
|
573
|
+
// its `createClientPGlite` boot create.
|
|
574
|
+
...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
575
|
+
// ADR-0049 D1/D12: on a capability-absence fallback (OPFS was capable but no home could hold handles) the
|
|
576
|
+
// engine boots IDBFS and stamps this verbatim reason into the BootReport's `storageFallbackReason`. Absent
|
|
577
|
+
// on a granted opfs boot and on the declared-idbfs mode (which is the contract, not a fallback).
|
|
578
|
+
...(placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {}),
|
|
579
|
+
// Adoption declaration (ADR-0049 D7, step 11b): a worker-entry option (never attach-controlled). When the
|
|
580
|
+
// engine home grants OPFS access, an existing idb-authoritative store is migrated to a committed opfs
|
|
581
|
+
// successor at boot. Default off (absent) — nothing is ever deleted without this explicit declaration.
|
|
582
|
+
...(options.adoption ? { adoption: options.adoption } : {}),
|
|
494
583
|
// Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
|
|
495
584
|
// spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
|
|
496
|
-
// journal recovery +
|
|
585
|
+
// journal recovery + registry reconciliation. Never inferred from "adopting a provisioned store": the board
|
|
497
586
|
// provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim
|
|
498
587
|
// path's explicit hint distinguishes them.
|
|
499
588
|
...(attach.config?.freshStore === true ? { freshStore: true } : {}),
|
|
@@ -711,7 +800,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
711
800
|
|
|
712
801
|
// Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
|
|
713
802
|
// creation (`column "title" specified more than once`) unless every output column has a unique alias.
|
|
714
|
-
// No `fields` → SQL unchanged (
|
|
803
|
+
// No `fields` → SQL unchanged (the default name-keyed row shape; the aliased path keys by alias). The
|
|
715
804
|
// wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.
|
|
716
805
|
const materialSql = wrapLiveQueryForMaterialization(sql, fields);
|
|
717
806
|
// Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):
|
|
@@ -809,7 +898,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
809
898
|
// The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
|
|
810
899
|
// survive structured clone, so the store's backend selection travels here and is passed to createPglite.
|
|
811
900
|
const backendOverride = provision.testStoreBackend;
|
|
812
|
-
if (bootPromise != null || provisioned != null) {
|
|
901
|
+
if (bootPromise != null || provisioned != null || provisionAttempt != null) {
|
|
813
902
|
postBridgeMessage(port, codec, "provision-ack", {
|
|
814
903
|
ok: true,
|
|
815
904
|
...(provision.storeId ? { storeId: provision.storeId } : {}),
|
|
@@ -817,19 +906,48 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
817
906
|
break;
|
|
818
907
|
}
|
|
819
908
|
// Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,
|
|
820
|
-
// so an adopting boot can compute how long it sat idle before adoption.
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
909
|
+
// so an adopting boot can compute how long it sat idle before adoption. Gated on the placement grant
|
|
910
|
+
// (ADR-0049 elected engine self-probe): the elected dedicated engine pre-spawns the OPFS-repacked store it
|
|
911
|
+
// holds access to, not idbfs, so the adopting boot backend matches its engine home. Opens the gate at
|
|
912
|
+
// once for SW-direct / plain scopes (already settled before any port connects).
|
|
913
|
+
const attempt = placementGate.then(async () => {
|
|
914
|
+
// Provision is only an accelerator, never an authority-recovery path. Read the meta record on EVERY
|
|
915
|
+
// persistent placement before minting. If deletion is live, decline the pre-mint and let the first
|
|
916
|
+
// attach run createSyncClient's full ordinary phase machine. This closes both granted and denied lanes:
|
|
917
|
+
// no replacement (and therefore no journal) can be created beneath a record a later boot must delete.
|
|
918
|
+
if (backendOverride !== "memory") {
|
|
919
|
+
const record = await readStoreMetaRecord(storePath);
|
|
920
|
+
if (record !== META_STORE_UNAVAILABLE && record?.phase === "deleting") {
|
|
921
|
+
syncDebug("worker provision declined — deletion authority is live", { storePath });
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
// An attach or another completed provision may have won while the bounded read was in flight.
|
|
926
|
+
if (bootPromise != null || provisioned != null) return;
|
|
927
|
+
|
|
928
|
+
const provisionStartedAt = nowStamp();
|
|
929
|
+
const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
|
|
930
|
+
const stamp = pglite.then(() => {
|
|
931
|
+
const readyAt = nowStamp();
|
|
932
|
+
return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
|
|
933
|
+
});
|
|
934
|
+
provisioned = { storePath, pglite, stamp };
|
|
935
|
+
// Guard unobserved rejections when no attach ever adopts the spare (the page navigated away).
|
|
936
|
+
void pglite.catch(() => undefined);
|
|
937
|
+
void stamp.catch(() => undefined);
|
|
938
|
+
syncDebug("worker store provisioned", { storePath });
|
|
939
|
+
await pglite;
|
|
826
940
|
});
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
941
|
+
provisionAttempt = attempt;
|
|
942
|
+
void attempt.then(
|
|
943
|
+
() => {
|
|
944
|
+
if (provisionAttempt === attempt) provisionAttempt = null;
|
|
945
|
+
},
|
|
946
|
+
() => {
|
|
947
|
+
if (provisionAttempt === attempt) provisionAttempt = null;
|
|
948
|
+
},
|
|
949
|
+
);
|
|
950
|
+
void attempt.then(
|
|
833
951
|
() =>
|
|
834
952
|
postBridgeMessage(port, codec, "provision-ack", {
|
|
835
953
|
ok: true,
|
|
@@ -937,7 +1055,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
937
1055
|
// hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
|
|
938
1056
|
// boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on
|
|
939
1057
|
// that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
|
|
940
|
-
bootPromise = null;
|
|
1058
|
+
if (!alreadyBooted) bootPromise = null;
|
|
941
1059
|
postBridgeMessage(port, codec, "attach-ack", {
|
|
942
1060
|
alreadyBooted,
|
|
943
1061
|
error: serializeError(error),
|
|
@@ -1046,35 +1164,75 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1046
1164
|
port.start?.();
|
|
1047
1165
|
};
|
|
1048
1166
|
|
|
1167
|
+
const closeHost = async (): Promise<void> => {
|
|
1168
|
+
// Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
|
|
1169
|
+
// `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
|
|
1170
|
+
// This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
|
|
1171
|
+
// subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
|
|
1172
|
+
closing = true;
|
|
1173
|
+
for (const pending of pendingSubscribes.values()) pending.cancelled = true;
|
|
1174
|
+
await Promise.allSettled([...inFlightSubscribes]);
|
|
1175
|
+
// Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
|
|
1176
|
+
// registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
|
|
1177
|
+
// engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
|
|
1178
|
+
liveSubs.clear();
|
|
1179
|
+
await liveManager?.dispose();
|
|
1180
|
+
ports.clear();
|
|
1181
|
+
setSyncDebugSink(undefined);
|
|
1182
|
+
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
1183
|
+
await active?.stop();
|
|
1184
|
+
};
|
|
1185
|
+
|
|
1049
1186
|
// ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────
|
|
1050
|
-
|
|
1187
|
+
// ADR-0049 D1: a SharedWorker scope routes through the PLACEMENT bootstrap — it decides its engine home once at
|
|
1188
|
+
// startup (an UNCONDITIONAL probe) and gates every `onconnect` port on that decision (SW-direct host connect vs
|
|
1189
|
+
// router-only `attachTab`). The ONE exception is a registry that DECLARES `backend: "idbfs"` (read below): no
|
|
1190
|
+
// probe runs and the engine boots in-SharedWorker on idbfs — the declared mode, not a fallback. A dedicated
|
|
1191
|
+
// engine worker still delegates to `bindGlobalScope` (the step-9 control plane); a plain test/Node scope is a no-op.
|
|
1192
|
+
//
|
|
1193
|
+
// The declared backend is read off the DEFAULT registry (placement is decided once at startup, before any
|
|
1194
|
+
// attach settles a role) — the same seam `provisionDurability` above reads. Storage is a data-contract property,
|
|
1195
|
+
// so role variants baked into one worker file share it.
|
|
1196
|
+
const declaredIdbfs = getSyncRegistryStorage(options.registry)?.backend === "idbfs";
|
|
1197
|
+
if (options.installGlobal === false) {
|
|
1198
|
+
// No global bootstrap runs (a plain host driven via `connect` in tests) — open the placement gate at once so
|
|
1199
|
+
// the first boot proceeds with no OPFS grant and no engine home (a plain scope has no browser placement).
|
|
1200
|
+
openPlacementGate();
|
|
1201
|
+
} else {
|
|
1202
|
+
bootstrapWorkerScope({
|
|
1203
|
+
connect,
|
|
1204
|
+
closeHost,
|
|
1205
|
+
peerCount: () => ports.size,
|
|
1206
|
+
// ADR-0049 D1: `backend: "idbfs"` is the one declared opt-out — no probe, no election, in-SW idbfs engine.
|
|
1207
|
+
declaredIdbfs,
|
|
1208
|
+
...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
|
|
1209
|
+
onPlacement: (outcome) => {
|
|
1210
|
+
// The resolved OPFS grant + engine home for THIS scope: the SharedWorker placement decision (`shared-worker`
|
|
1211
|
+
// ⇒ granted in-scope engine, or a capability-absence idbfs fallback carrying `storageFallbackReason`), the
|
|
1212
|
+
// elected DEDICATED engine's OWN-scope probe (`elected-worker` carrying its real probe verdict), or a plain
|
|
1213
|
+
// test/Node scope (no home, no grant). Threaded into the boot's grant/BootReport and OPENS the boot gate.
|
|
1214
|
+
// ADR-0049 decision 12: `placementEngineHome` stamps the report; `placementFallbackReason` stamps the
|
|
1215
|
+
// capability-absence idbfs fallback's `storageFallbackReason`.
|
|
1216
|
+
placementOpfsAccess = outcome.opfsGranted;
|
|
1217
|
+
placementEngineHome = outcome.engineHome;
|
|
1218
|
+
placementFallbackReason = outcome.storageFallbackReason;
|
|
1219
|
+
openPlacementGate();
|
|
1220
|
+
},
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1051
1223
|
|
|
1052
1224
|
return {
|
|
1053
1225
|
connect,
|
|
1054
1226
|
whenBooted,
|
|
1055
|
-
close:
|
|
1056
|
-
// Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
|
|
1057
|
-
// `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
|
|
1058
|
-
// This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
|
|
1059
|
-
// subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
|
|
1060
|
-
closing = true;
|
|
1061
|
-
for (const pending of pendingSubscribes.values()) pending.cancelled = true;
|
|
1062
|
-
await Promise.allSettled([...inFlightSubscribes]);
|
|
1063
|
-
// Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
|
|
1064
|
-
// registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
|
|
1065
|
-
// engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
|
|
1066
|
-
liveSubs.clear();
|
|
1067
|
-
await liveManager?.dispose();
|
|
1068
|
-
ports.clear();
|
|
1069
|
-
setSyncDebugSink(undefined);
|
|
1070
|
-
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
1071
|
-
await active?.stop();
|
|
1072
|
-
},
|
|
1227
|
+
close: closeHost,
|
|
1073
1228
|
};
|
|
1074
1229
|
}
|
|
1075
1230
|
|
|
1076
1231
|
/** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */
|
|
1077
1232
|
function serializeError(error: unknown): { message: string; detail?: unknown } {
|
|
1233
|
+
if (error instanceof ExecutionLimitMismatchError) {
|
|
1234
|
+
return { message: error.message, detail: executionLimitMismatchToWire(error) };
|
|
1235
|
+
}
|
|
1078
1236
|
if (error instanceof Error) {
|
|
1079
1237
|
const detail = (error as Error & { detail?: unknown }).detail;
|
|
1080
1238
|
return { message: error.message, ...(detail !== undefined ? { detail } : {}) };
|
|
@@ -1085,11 +1243,127 @@ function serializeError(error: unknown): { message: string; detail?: unknown } {
|
|
|
1085
1243
|
interface SharedWorkerConnectEvent {
|
|
1086
1244
|
ports: BridgePort[];
|
|
1087
1245
|
}
|
|
1246
|
+
/**
|
|
1247
|
+
* A message event that may carry transferred `MessagePort`s (the `ports` array). The engine-entry control plane
|
|
1248
|
+
* (ADR-0049 step 9) reads it for the delivered control channel and for each dynamically transferred pipe end.
|
|
1249
|
+
*/
|
|
1250
|
+
interface ScopeMessageEvent {
|
|
1251
|
+
data: unknown;
|
|
1252
|
+
ports?: readonly ControlPortLike[];
|
|
1253
|
+
}
|
|
1088
1254
|
interface WorkerGlobalScopeLike {
|
|
1089
1255
|
onconnect?: (event: SharedWorkerConnectEvent) => void;
|
|
1090
1256
|
postMessage?: (message: unknown) => void;
|
|
1091
|
-
addEventListener?: (type: "message", listener: (event:
|
|
1257
|
+
addEventListener?: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
|
|
1092
1258
|
removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
1259
|
+
/** Present on a real `DedicatedWorkerGlobalScope` (`self.close()`); the entry self-closes on teardown. */
|
|
1260
|
+
close?: () => void;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/**
|
|
1264
|
+
* The structural `MessagePort` shape the engine-entry control plane needs: the control channel end delivered on
|
|
1265
|
+
* the implicit port, and each transferred pipe end wrapped into a {@link BridgePort}. No DOM lib — structural
|
|
1266
|
+
* typing only, matching the router's `RouterPort` discipline.
|
|
1267
|
+
*/
|
|
1268
|
+
interface ControlPortLike {
|
|
1269
|
+
postMessage: (message: unknown, transfer?: unknown[]) => void;
|
|
1270
|
+
addEventListener: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
|
|
1271
|
+
removeEventListener?: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
|
|
1272
|
+
start?: () => void;
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
/**
|
|
1276
|
+
* The literal key of the CONTROL-CHANNEL DELIVERY message (ADR-0049 step 9). The spawning coordinator's step-10
|
|
1277
|
+
* wiring posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }` on the elected engine worker's IMPLICIT port WITH the
|
|
1278
|
+
* engine end of the announce control channel as a transferred `MessagePort`. The engine entry starts that port
|
|
1279
|
+
* and runs its control plane on it. Distinct namespace from the data-path bridge envelope and the `pgx0049`
|
|
1280
|
+
* control envelope, so it is unambiguous on the shared implicit-port transport.
|
|
1281
|
+
*/
|
|
1282
|
+
export const CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort" as const;
|
|
1283
|
+
|
|
1284
|
+
/** Is this a control-channel DELIVERY message (`{ [CONTROL_PORT_DELIVERY_KEY]: true }`)? */
|
|
1285
|
+
function isControlPortDelivery(data: unknown): boolean {
|
|
1286
|
+
return (
|
|
1287
|
+
typeof data === "object" &&
|
|
1288
|
+
data !== null &&
|
|
1289
|
+
(data as { [CONTROL_PORT_DELIVERY_KEY]?: unknown })[CONTROL_PORT_DELIVERY_KEY] === true
|
|
1290
|
+
);
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
/**
|
|
1294
|
+
* The elected-engine-worker CONTROL PLANE (ADR-0049 step 9) — grown on the dedicated-worker ENTRY, leaving the
|
|
1295
|
+
* engine CORE (`SyncWorkerHost.connect`) untouched. Runs on the delivered control channel:
|
|
1296
|
+
*
|
|
1297
|
+
* - `assign-identity` → remember it (gates every subsequent tagged message) and reply `engine-ready`. That
|
|
1298
|
+
* signals CONTROL-plane readiness, NOT engine boot — the engine still boots lazily on the FIRST attach, as
|
|
1299
|
+
* today (the first `connect-port` pipe's traffic drives `boot`).
|
|
1300
|
+
* - `connect-port` (matching identity) + a transferred port → wrap it into a {@link BridgePort} (started if it
|
|
1301
|
+
* exposes `start()`, exactly as the implicit scope port is wrapped) and feed it to the SAME `connect(...)`
|
|
1302
|
+
* the entry already uses N times — dynamic per-tab pipe acceptance (ADR D4).
|
|
1303
|
+
* - `control-ping` → reply `control-ack` with the assigned identity (or the ping's, pre-assignment) and the
|
|
1304
|
+
* SAME `pingId`. Answered on the event loop, so a WASM-blocked engine cannot answer — which is exactly the
|
|
1305
|
+
* execution-limit's liveness signal.
|
|
1306
|
+
* - `engine-retiring` (matching) → a no-op hook for now (flush opportunities are engine-CORE concerns wired in
|
|
1307
|
+
* a later step).
|
|
1308
|
+
* - `engine-teardown` (matching) → reply `control-ack` with `pingId: -1` (the teardown ack the router relays)
|
|
1309
|
+
* then self-close the scope AFTER a microtask, so the ack flushes before the worker goes.
|
|
1310
|
+
*
|
|
1311
|
+
* Stale (post-assignment mismatch) tagged messages are discarded via {@link shouldApplyControlMessage}.
|
|
1312
|
+
*/
|
|
1313
|
+
function startEngineControlPlane(
|
|
1314
|
+
controlPort: ControlPortLike,
|
|
1315
|
+
connect: (port: BridgePort) => void,
|
|
1316
|
+
closeScope: () => void,
|
|
1317
|
+
): () => void {
|
|
1318
|
+
let assigned: EngineIdentity | undefined;
|
|
1319
|
+
const post = (message: EngineControlMessage): void => controlPort.postMessage(controlEnvelope(message));
|
|
1320
|
+
const listener = (event: ScopeMessageEvent): void => {
|
|
1321
|
+
const message = readControlEnvelope(event.data);
|
|
1322
|
+
if (message === undefined) return;
|
|
1323
|
+
switch (message.type) {
|
|
1324
|
+
case "assign-identity":
|
|
1325
|
+
assigned = message.identity;
|
|
1326
|
+
post({ type: "engine-ready", identity: message.identity });
|
|
1327
|
+
return;
|
|
1328
|
+
case "control-ping":
|
|
1329
|
+
post({ type: "control-ack", identity: assigned ?? message.identity, pingId: message.pingId });
|
|
1330
|
+
return;
|
|
1331
|
+
case "connect-port": {
|
|
1332
|
+
if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
|
|
1333
|
+
const transferred = event.ports?.[0];
|
|
1334
|
+
if (!transferred) return;
|
|
1335
|
+
connect(wrapControlPortAsBridge(transferred));
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
case "engine-retiring":
|
|
1339
|
+
// No-op hook for now (matching-identity only) — later steps wire the engine-core flush opportunity.
|
|
1340
|
+
void shouldApplyControlMessage(assigned, message);
|
|
1341
|
+
return;
|
|
1342
|
+
case "engine-teardown":
|
|
1343
|
+
if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
|
|
1344
|
+
post({ type: "control-ack", identity: message.identity, pingId: -1 });
|
|
1345
|
+
// Defer the close a microtask so the teardown ack flushes before the scope goes.
|
|
1346
|
+
void Promise.resolve().then(closeScope);
|
|
1347
|
+
return;
|
|
1348
|
+
default:
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
};
|
|
1352
|
+
controlPort.addEventListener("message", listener);
|
|
1353
|
+
controlPort.start?.();
|
|
1354
|
+
// Return a disposer that detaches THIS plane's listener, so a repeat control-port delivery (the keepalive
|
|
1355
|
+
// SW-reconstruction re-announce, step 11b follow-up 2) can REPLACE this channel and have the old one ignored.
|
|
1356
|
+
return () => controlPort.removeEventListener?.("message", listener);
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
/** Wrap a transferred raw port into the {@link BridgePort} the engine's `connect(...)` consumes (started if able). */
|
|
1360
|
+
function wrapControlPortAsBridge(port: ControlPortLike): BridgePort {
|
|
1361
|
+
port.start?.();
|
|
1362
|
+
return {
|
|
1363
|
+
postMessage: (message, transfer) => port.postMessage(message, transfer),
|
|
1364
|
+
addEventListener: (type, listener) => port.addEventListener(type, listener),
|
|
1365
|
+
removeEventListener: (type, listener) => port.removeEventListener?.(type, listener),
|
|
1366
|
+
};
|
|
1093
1367
|
}
|
|
1094
1368
|
|
|
1095
1369
|
/**
|
|
@@ -1097,13 +1371,16 @@ interface WorkerGlobalScopeLike {
|
|
|
1097
1371
|
* tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the
|
|
1098
1372
|
* single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,
|
|
1099
1373
|
* where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.
|
|
1374
|
+
*
|
|
1375
|
+
* `globalScope` defaults to `globalThis` (the real worker binding); tests inject a fake scope to exercise the
|
|
1376
|
+
* dedicated-worker control-plane arm (ADR-0049 step 9) without a real Worker.
|
|
1100
1377
|
*/
|
|
1101
|
-
function bindGlobalScope(connect: (port: BridgePort) => void): void {
|
|
1102
|
-
const scope =
|
|
1378
|
+
export function bindGlobalScope(connect: (port: BridgePort) => void, globalScope: unknown = globalThis): void {
|
|
1379
|
+
const scope = globalScope as WorkerGlobalScopeLike;
|
|
1103
1380
|
const hasSharedWorkerScope =
|
|
1104
|
-
typeof (
|
|
1381
|
+
typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
|
|
1105
1382
|
const hasDedicatedWorkerScope =
|
|
1106
|
-
typeof (
|
|
1383
|
+
typeof (globalScope as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
|
|
1107
1384
|
|
|
1108
1385
|
if (hasSharedWorkerScope) {
|
|
1109
1386
|
scope.onconnect = (event: SharedWorkerConnectEvent) => {
|
|
@@ -1113,11 +1390,384 @@ function bindGlobalScope(connect: (port: BridgePort) => void): void {
|
|
|
1113
1390
|
return;
|
|
1114
1391
|
}
|
|
1115
1392
|
if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {
|
|
1116
|
-
// The dedicated worker's own global scope IS the single port.
|
|
1117
|
-
connect
|
|
1393
|
+
// The dedicated worker's own global scope IS the single implicit port (the tab's engine port). Wrap it as a
|
|
1394
|
+
// bridge port and connect it — the same engine serves that one port for the worker's whole lifetime.
|
|
1395
|
+
const scopePort: BridgePort = {
|
|
1118
1396
|
postMessage: (message: unknown) => scope.postMessage!(message),
|
|
1119
1397
|
addEventListener: (type, listener) => scope.addEventListener!(type, listener),
|
|
1120
1398
|
removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),
|
|
1399
|
+
};
|
|
1400
|
+
connect(scopePort);
|
|
1401
|
+
// ADR-0049 step 9 (elected engine home): the implicit port ALSO carries the control-channel DELIVERY
|
|
1402
|
+
// message. On it, start the engine's control plane — dynamic pipe acceptance, probe replies, and
|
|
1403
|
+
// retirement/teardown — all identity-tagged. The engine CORE is untouched: transferred pipes flow into the
|
|
1404
|
+
// SAME `connect` above. The scope port's own baseline connect is unchanged.
|
|
1405
|
+
// A repeat delivery REPLACES the live control plane (ADR-0049 step 11b follow-up 2): when the leader-keepalive
|
|
1406
|
+
// reconstructs a dead SharedWorker it re-announces with a FRESH control channel and re-delivers this engine's
|
|
1407
|
+
// end. Dispose the previous plane's listener first so stale traffic on the dead old channel is ignored; the
|
|
1408
|
+
// engine CORE (`connect`) is untouched — pipes still flow into the same engine.
|
|
1409
|
+
let disposeControlPlane: (() => void) | undefined;
|
|
1410
|
+
scope.addEventListener("message", (event: ScopeMessageEvent) => {
|
|
1411
|
+
if (!isControlPortDelivery(event.data)) return;
|
|
1412
|
+
const controlPort = event.ports?.[0];
|
|
1413
|
+
if (!controlPort) return;
|
|
1414
|
+
disposeControlPlane?.();
|
|
1415
|
+
disposeControlPlane = startEngineControlPlane(controlPort, connect, () => scope.close?.());
|
|
1121
1416
|
});
|
|
1122
1417
|
}
|
|
1123
1418
|
}
|
|
1419
|
+
|
|
1420
|
+
// ─── ADR-0049 D1: the SharedWorker placement bootstrap ───────────────────────────────────────────────
|
|
1421
|
+
// The SharedWorker arm decides its ENGINE HOME once at startup and gates each tab connection on that decision:
|
|
1422
|
+
// `shared-worker` (SW-direct) connects the port to the in-scope engine host; `elected-worker` (router-only)
|
|
1423
|
+
// hands the port to a `createEngineRouter` and NEVER boots the engine in-scope. The probe is UNCONDITIONAL —
|
|
1424
|
+
// every scope runs `decideSwPlacement` — with ONE exception: a registry declaring `backend: "idbfs"`
|
|
1425
|
+
// (`deps.declaredIdbfs`) skips the probe and binds the in-SW engine host on idbfs (the declared mode). Both modes
|
|
1426
|
+
// answer a tab's PLACEMENT query and DESTROY peer-count query; SW-direct additionally answers `pgx0049` keepalive
|
|
1427
|
+
// pings on each port (the router owns those in elected mode). A dedicated-worker scope (the elected engine worker)
|
|
1428
|
+
// still routes through `bindGlobalScope` (the step-9 control plane), unchanged.
|
|
1429
|
+
|
|
1430
|
+
/**
|
|
1431
|
+
* The PLACEMENT-QUERY envelope key: a tab posts `{ [PLACEMENT_QUERY_KEY]: true }` on its SharedWorker
|
|
1432
|
+
* connection to learn the engine home; the SharedWorker replies `{ [PLACEMENT_RESULT_KEY]: PlacementQueryResult }`.
|
|
1433
|
+
* A distinct namespace from the data-path bridge envelope and the `pgx0049` control envelope, so it is
|
|
1434
|
+
* unambiguous on the shared tab↔SharedWorker transport (the attach client reads it off the raw message).
|
|
1435
|
+
*/
|
|
1436
|
+
export const PLACEMENT_QUERY_KEY = "pgx0049Placement" as const;
|
|
1437
|
+
/** The reply to a {@link PLACEMENT_QUERY_KEY} query — carries the engine home, `electionRequired`, and SW id. */
|
|
1438
|
+
export const PLACEMENT_RESULT_KEY = "pgx0049PlacementResult" as const;
|
|
1439
|
+
/**
|
|
1440
|
+
* The DESTROY peer-count query key (ADR-0049 D8, plan fault row "`destroy()` with peers attached → refused").
|
|
1441
|
+
* A tab about to destroy the store posts `{ [DESTROY_QUERY_KEY]: true }`; the SharedWorker — which alone knows
|
|
1442
|
+
* the attached-tab count — replies `{ [DESTROY_VERDICT_KEY]: { peers } }`. `peers` INCLUDES the querying tab, so
|
|
1443
|
+
* `peers > 1` means other tabs still hold the store and destruction is refused.
|
|
1444
|
+
*/
|
|
1445
|
+
export const DESTROY_QUERY_KEY = "pgx0049DestroyQuery" as const;
|
|
1446
|
+
/** The reply to a {@link DESTROY_QUERY_KEY} query — the attached-tab count (querying tab included). */
|
|
1447
|
+
export const DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict" as const;
|
|
1448
|
+
|
|
1449
|
+
/** The placement a tab learns from the SharedWorker (the reply payload under {@link PLACEMENT_RESULT_KEY}). */
|
|
1450
|
+
export interface PlacementQueryResult {
|
|
1451
|
+
engineHome: SwPlacementResult["engineHome"];
|
|
1452
|
+
/** True in `elected-worker` mode — the tab's election coordinator must spawn the engine worker. */
|
|
1453
|
+
electionRequired: boolean;
|
|
1454
|
+
swInstanceId: string;
|
|
1455
|
+
/**
|
|
1456
|
+
* The SharedWorker's OWN script URL (`self.location.href`, ADR-0049 D5). In `elected-worker` mode the winning
|
|
1457
|
+
* tab constructs the elected engine as `new Worker(swScriptUrl, { type: "module" })` — the worker entry is
|
|
1458
|
+
* dual-scope (one file serves both homes), so no consumer wiring is needed; a `createEngineWorker` override is
|
|
1459
|
+
* only for entries that cannot be reconstructed from their URL as a module worker. Absent when the scope cannot
|
|
1460
|
+
* report its location (a plain test scope) — then a tab with no override fails attach with a typed wiring error.
|
|
1461
|
+
*/
|
|
1462
|
+
swScriptUrl?: string;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
/** The SharedWorker placement bootstrap's dependencies (all injected so it is unit-testable off-worker). */
|
|
1466
|
+
export interface SharedWorkerBootstrapDeps {
|
|
1467
|
+
/** The engine host `connect` — used in SW-direct (`shared-worker`) placement to pipe a port to the in-scope engine. */
|
|
1468
|
+
connect: (port: BridgePort) => void;
|
|
1469
|
+
/** Quiesce and close the in-scope host before SW-direct destruction acknowledges handle release. */
|
|
1470
|
+
closeHost?: () => Promise<void>;
|
|
1471
|
+
/** Current attached-tab count for the DESTROY verdict in SW-direct mode (the host's own port set). */
|
|
1472
|
+
peerCount: () => number;
|
|
1473
|
+
/** The opt-in execution limit, threaded into the router in `elected-worker` (router-only) placement. */
|
|
1474
|
+
executionLimit?: ExecutionLimitConfig;
|
|
1475
|
+
/**
|
|
1476
|
+
* The registry declared `backend: "idbfs"` (ADR-0049 D1) — the ONE opt-out. TRUE: skip the probe entirely and
|
|
1477
|
+
* bind the in-SharedWorker engine host on the idbfs backend (the declared mode, not a fallback; the placement
|
|
1478
|
+
* query answers `electionRequired: false`). FALSE (the default, `backend: "opfs"`): run the UNCONDITIONAL
|
|
1479
|
+
* placement probe — a granted verdict boots the engine in-scope on OPFS-repacked, a denied one goes router-only
|
|
1480
|
+
* and each tab elects a dedicated engine worker.
|
|
1481
|
+
*/
|
|
1482
|
+
declaredIdbfs?: boolean;
|
|
1483
|
+
/** Test seam: inject the placement decision (a fake probe result) instead of the real {@link decideSwPlacement}. */
|
|
1484
|
+
decidePlacement?: () => Promise<SwPlacementResult>;
|
|
1485
|
+
/** Defaults to `globalThis`; tests inject a fake SharedWorker scope. */
|
|
1486
|
+
globalScope?: unknown;
|
|
1487
|
+
/**
|
|
1488
|
+
* Notified once the placement grant for THIS scope resolves (SharedWorker decision, dedicated-engine probe, or
|
|
1489
|
+
* the plain-scope immediate settle). The entry threads `opfsGranted` into its `hasOpfsSyncAccess` boot grant and
|
|
1490
|
+
* `engineHome` into the BootReport, and opens its boot gate. `engineHome` is `undefined` for a plain test/Node
|
|
1491
|
+
* scope (no home) so the report omits it, exactly as before placement.
|
|
1492
|
+
*/
|
|
1493
|
+
onPlacement?: (outcome: PlacementBootstrapOutcome) => void;
|
|
1494
|
+
/**
|
|
1495
|
+
* Test seam: inject the DEDICATED elected-engine scope's OPFS probe (a fake verdict) instead of the real
|
|
1496
|
+
* {@link probeOpfsSyncAccess}. Defaults to the real probe (invariant 8 — a real `createSyncAccessHandle` open in
|
|
1497
|
+
* the engine's own scope, per boot, never sniffed or cached).
|
|
1498
|
+
*/
|
|
1499
|
+
probe?: () => Promise<PlacementProbeResult>;
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
/** The resolved placement grant for a worker scope, threaded to the entry's boot grant + BootReport engine home. */
|
|
1503
|
+
export interface PlacementBootstrapOutcome {
|
|
1504
|
+
/** The engine home for this scope; `undefined` for a plain test/Node scope (the report then omits it). */
|
|
1505
|
+
engineHome: SwPlacementResult["engineHome"] | undefined;
|
|
1506
|
+
/** True when THIS scope actually holds OPFS sync-access (in-scope SW-direct, or the elected engine's own probe). */
|
|
1507
|
+
opfsGranted: boolean;
|
|
1508
|
+
/**
|
|
1509
|
+
* The verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (ADR-0049 D1/D12, a
|
|
1510
|
+
* capability-absence fallback) — stamped into the boot's `storageFallbackReason`. Absent on a granted opfs boot
|
|
1511
|
+
* AND on the declared `backend: "idbfs"` mode (the contract, not a fallback).
|
|
1512
|
+
*/
|
|
1513
|
+
storageFallbackReason?: string;
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
/** Is this a raw `{ [PLACEMENT_QUERY_KEY]: true }` placement query? */
|
|
1517
|
+
function isPlacementQuery(data: unknown): boolean {
|
|
1518
|
+
return (
|
|
1519
|
+
typeof data === "object" &&
|
|
1520
|
+
data !== null &&
|
|
1521
|
+
(data as { [PLACEMENT_QUERY_KEY]?: unknown })[PLACEMENT_QUERY_KEY] === true
|
|
1522
|
+
);
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
/** Is this a raw `{ [DESTROY_QUERY_KEY]: true }` destroy peer-count query? */
|
|
1526
|
+
function isDestroyQuery(data: unknown): boolean {
|
|
1527
|
+
return (
|
|
1528
|
+
typeof data === "object" && data !== null && (data as { [DESTROY_QUERY_KEY]?: unknown })[DESTROY_QUERY_KEY] === true
|
|
1529
|
+
);
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* Bootstrap the running worker scope for ADR-0049 placement. A SharedWorker scope runs the placement decision
|
|
1534
|
+
* and gates every `onconnect` port on it ({@link wireSharedWorkerPlacement}); any other scope (the dedicated
|
|
1535
|
+
* elected-engine worker, or a plain test/Node scope) delegates to {@link bindGlobalScope} unchanged. Called by
|
|
1536
|
+
* `defineSyncWorker` in place of the old direct `bindGlobalScope(connect)`.
|
|
1537
|
+
*/
|
|
1538
|
+
export function bootstrapWorkerScope(deps: SharedWorkerBootstrapDeps): void {
|
|
1539
|
+
const globalScope = deps.globalScope ?? globalThis;
|
|
1540
|
+
const hasSharedWorkerScope =
|
|
1541
|
+
typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
|
|
1542
|
+
if (hasSharedWorkerScope) {
|
|
1543
|
+
if (deps.declaredIdbfs) {
|
|
1544
|
+
// ADR-0049 D1 declared opt-out (`backend: "idbfs"`): NEVER probe, NEVER go router-only — bind the in-SW
|
|
1545
|
+
// engine host on the idbfs backend (no OPFS grant). This is the store's DECLARED mode, not a fallback, so it
|
|
1546
|
+
// carries no `storageFallbackReason`. The meta listener answers the placement query `electionRequired: false`,
|
|
1547
|
+
// so a tab keeps the SW-port attach path.
|
|
1548
|
+
wireSharedWorkerPlacement(
|
|
1549
|
+
{
|
|
1550
|
+
...deps,
|
|
1551
|
+
decidePlacement: () => Promise.resolve({ engineHome: "shared-worker", swInstanceId: crypto.randomUUID() }),
|
|
1552
|
+
},
|
|
1553
|
+
globalScope,
|
|
1554
|
+
false,
|
|
1555
|
+
);
|
|
1556
|
+
} else {
|
|
1557
|
+
// ADR-0049 D1 default (`backend: "opfs"`): run the UNCONDITIONAL placement probe. A granted probe boots the
|
|
1558
|
+
// engine in-SW on OPFS-repacked (SW-direct); a denied one goes router-only + election; a capability-absence
|
|
1559
|
+
// decision (`shared-worker` carrying `storageFallbackReason`) boots the in-SW idbfs fallback.
|
|
1560
|
+
wireSharedWorkerPlacement(deps, globalScope, true);
|
|
1561
|
+
}
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1564
|
+
const hasDedicatedWorkerScope =
|
|
1565
|
+
typeof (globalScope as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
|
|
1566
|
+
if (hasDedicatedWorkerScope) {
|
|
1567
|
+
// ADR-0049 D1 (elected engine self-probe): the elected DEDICATED engine holds OPFS access in its OWN scope, so
|
|
1568
|
+
// it probes THIS scope's real `createSyncAccessHandle` (invariant 8 — per boot, never sniffed/cached) and
|
|
1569
|
+
// threads the verdict as the `elected-worker` home's OPFS grant, opening the boot gate. The step-9 control plane
|
|
1570
|
+
// (dynamic pipe acceptance, probe replies, teardown) is still wired by `bindGlobalScope`, unchanged. A DENIED
|
|
1571
|
+
// dedicated probe is capability absence in this home: the engine opens idbfs, and the outcome carries a verbatim
|
|
1572
|
+
// `storageFallbackReason` so the boot's BootReport shows the fallback (decision 12) rather than a silent idb.
|
|
1573
|
+
bindGlobalScope(deps.connect, globalScope);
|
|
1574
|
+
const probe = deps.probe ?? probeOpfsSyncAccess;
|
|
1575
|
+
void probe().then(
|
|
1576
|
+
(result) =>
|
|
1577
|
+
deps.onPlacement?.({
|
|
1578
|
+
engineHome: "elected-worker",
|
|
1579
|
+
opfsGranted: result.granted,
|
|
1580
|
+
...(result.granted
|
|
1581
|
+
? {}
|
|
1582
|
+
: { storageFallbackReason: `elected engine OPFS probe denied (${result.error ?? "no attribution"})` }),
|
|
1583
|
+
}),
|
|
1584
|
+
// The probe answers (never rejects); this guard only protects against an injected fake that throws — still
|
|
1585
|
+
// open the gate with no grant so the boot cannot deadlock, falling back to the honest idb backend.
|
|
1586
|
+
() =>
|
|
1587
|
+
deps.onPlacement?.({
|
|
1588
|
+
engineHome: "elected-worker",
|
|
1589
|
+
opfsGranted: false,
|
|
1590
|
+
storageFallbackReason: "elected engine OPFS probe threw",
|
|
1591
|
+
}),
|
|
1592
|
+
);
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
// A plain test/Node scope: no engine home, no OPFS grant — settle the gate immediately (no browser placement).
|
|
1596
|
+
bindGlobalScope(deps.connect, globalScope);
|
|
1597
|
+
deps.onPlacement?.({ engineHome: undefined, opfsGranted: false });
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
/**
|
|
1601
|
+
* Wire the SharedWorker arm for placement (ADR-0049 D1). Decides the engine home ONCE, then per `onconnect` port:
|
|
1602
|
+
* installs a meta listener answering the placement + destroy-peer queries (and, on SW-direct, the `pgx0049`
|
|
1603
|
+
* keepalive ping), and routes the port to the engine host (`shared-worker`) or the router (`elected-worker`).
|
|
1604
|
+
* Ports that connect BEFORE the (async) decision resolves are buffered and drained on resolve — the engine host is
|
|
1605
|
+
* never touched in `elected-worker` mode until (and unless) the capability-absence fallback flips it to SW-direct.
|
|
1606
|
+
*/
|
|
1607
|
+
function wireSharedWorkerPlacement(
|
|
1608
|
+
deps: SharedWorkerBootstrapDeps,
|
|
1609
|
+
globalScope: unknown,
|
|
1610
|
+
/** Whether a GRANTED `shared-worker` home holds the OPFS grant — TRUE in the default probing mode (a granted
|
|
1611
|
+
probe placed the engine in-scope on OPFS-repacked), FALSE in the declared `backend: "idbfs"` mode (no probe
|
|
1612
|
+
ran). A capability-absence fallback (`shared-worker` carrying `storageFallbackReason`) is idbfs regardless. */
|
|
1613
|
+
opfsGrantedForSharedHome: boolean,
|
|
1614
|
+
): void {
|
|
1615
|
+
const scope = globalScope as WorkerGlobalScopeLike;
|
|
1616
|
+
const decide = deps.decidePlacement ?? (() => decideSwPlacement());
|
|
1617
|
+
// The SharedWorker's own script URL (ADR-0049 D5) — reported in the placement reply so the winning tab can
|
|
1618
|
+
// construct the elected engine as `new Worker(swScriptUrl, { type: "module" })` with no consumer wiring. Absent
|
|
1619
|
+
// when the scope cannot report its location (a plain test scope); a tab with no override then fails attach typed.
|
|
1620
|
+
const swScriptUrl = (globalScope as { location?: { href?: string } }).location?.href;
|
|
1621
|
+
let placement: SwPlacementResult | undefined;
|
|
1622
|
+
let router: EngineRouter | undefined;
|
|
1623
|
+
const pendingPorts: BridgePort[] = [];
|
|
1624
|
+
let sharedHostTeardown: Promise<{ error?: { message: string; detail?: unknown } }> | undefined;
|
|
1625
|
+
|
|
1626
|
+
const currentPeerCount = (): number =>
|
|
1627
|
+
placement?.engineHome === "elected-worker" ? (router?.tabCount() ?? 0) : deps.peerCount();
|
|
1628
|
+
|
|
1629
|
+
const attachPort = (port: BridgePort): void => {
|
|
1630
|
+
const current = placement!;
|
|
1631
|
+
// The meta listener answers the placement + destroy-peer queries on EVERY port (both modes) and, per mode:
|
|
1632
|
+
// - SW-direct: the `pgx0049` keepalive control-ping (the router owns that in elected mode).
|
|
1633
|
+
// - elected: the tab's `engine-announce` — the SW-side translation into `router.announceEngine`, handing
|
|
1634
|
+
// the transferred router-end control port to the router so it stamps an identity + pipes the tabs (the
|
|
1635
|
+
// router itself does not react to `engine-announce`; the SharedWorker scope drives it).
|
|
1636
|
+
// It coexists with the host's / router's own listener on the same port: each ignores the other's traffic.
|
|
1637
|
+
const metaListener = (event: { data: unknown; ports?: readonly ControlPortLike[] }): void => {
|
|
1638
|
+
const data = event.data;
|
|
1639
|
+
if (isPlacementQuery(data)) {
|
|
1640
|
+
// Read `placement` LIVE (not the captured `current`): a capability-absence fallback can flip a router-only
|
|
1641
|
+
// scope to `shared-worker` after this port attached, and the reply must reflect the current home + carry
|
|
1642
|
+
// the SharedWorker's own script URL (ADR-0049 D5) for the tab's engine auto-derivation.
|
|
1643
|
+
const live = placement ?? current;
|
|
1644
|
+
port.postMessage({
|
|
1645
|
+
[PLACEMENT_RESULT_KEY]: {
|
|
1646
|
+
engineHome: live.engineHome,
|
|
1647
|
+
electionRequired: live.engineHome === "elected-worker",
|
|
1648
|
+
swInstanceId: live.swInstanceId,
|
|
1649
|
+
...(swScriptUrl !== undefined ? { swScriptUrl } : {}),
|
|
1650
|
+
} satisfies PlacementQueryResult,
|
|
1651
|
+
});
|
|
1652
|
+
return;
|
|
1653
|
+
}
|
|
1654
|
+
if (isDestroyQuery(data)) {
|
|
1655
|
+
port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const control = readControlEnvelope(data);
|
|
1659
|
+
if (current.engineHome === "shared-worker") {
|
|
1660
|
+
if (control?.type === "control-ping") {
|
|
1661
|
+
port.postMessage(
|
|
1662
|
+
controlEnvelope({ type: "control-ack", identity: control.identity, pingId: control.pingId }),
|
|
1663
|
+
);
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
if (control?.type === "engine-teardown") {
|
|
1667
|
+
const sharedIdentity: EngineIdentity = { swInstanceId: current.swInstanceId, generation: 0 };
|
|
1668
|
+
if (!shouldApplyControlMessage(sharedIdentity, control)) return;
|
|
1669
|
+
// SW-direct destruction is supervised by the tab, but the exclusive store handles live here. Close
|
|
1670
|
+
// the in-scope host first; only the reserved teardown ack proves that quiescence to the tab. The
|
|
1671
|
+
// SharedWorker scope then closes itself so a later attach starts a fresh, rebootable host even when
|
|
1672
|
+
// `extendedLifetime` would otherwise retain this closed scope.
|
|
1673
|
+
sharedHostTeardown ??= Promise.resolve()
|
|
1674
|
+
.then(() => deps.closeHost?.())
|
|
1675
|
+
.then(
|
|
1676
|
+
() => ({}),
|
|
1677
|
+
(error: unknown) => ({ error: serializeError(error) }),
|
|
1678
|
+
);
|
|
1679
|
+
void sharedHostTeardown.then((result) => {
|
|
1680
|
+
port.postMessage(
|
|
1681
|
+
controlEnvelope({
|
|
1682
|
+
type: "control-ack",
|
|
1683
|
+
identity: sharedIdentity,
|
|
1684
|
+
pingId: -1,
|
|
1685
|
+
...(result.error ? { error: result.error } : {}),
|
|
1686
|
+
}),
|
|
1687
|
+
);
|
|
1688
|
+
// A task boundary, not merely a microtask: give the posted success/failure acknowledgement a delivery
|
|
1689
|
+
// turn before closing the SharedWorker global. A close failure poisons this lifetime just as surely as
|
|
1690
|
+
// a successful close retires it; never retain a rejected teardown promise in a live scope.
|
|
1691
|
+
globalThis.setTimeout(() => scope.close?.(), 0);
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
// elected-worker (router-only): the tab's coordinator drives leadership over this port.
|
|
1697
|
+
// - `leader-granted`: the newly-granted leader is about to (re)spawn its engine. Open the router's handoff
|
|
1698
|
+
// window NOW (fan `leader-granted` to EVERY tab) so in-flight ops settle by outcome and new ops QUEUE
|
|
1699
|
+
// across the spawn→announce→pipe gap, then flush onto the fresh pipe (invariants 5 + 9). Without this the
|
|
1700
|
+
// coordinator's `leader-granted` was DROPPED here, so on a leadership change (succession) a tab kept
|
|
1701
|
+
// dispatching onto the DEAD engine's pipe until the replacement pipe arrived — the elected-flow gap the
|
|
1702
|
+
// step-12 succession/relocation lanes surfaced (the router already owned `openHandoff`; nothing called it).
|
|
1703
|
+
// - `engine-announce`: translate into `router.announceEngine`, handing the transferred router-end control
|
|
1704
|
+
// port to the router so it stamps an identity + pipes the tabs (the router does not react to it itself).
|
|
1705
|
+
if (control?.type === "leader-granted") {
|
|
1706
|
+
router!.openHandoff("leader-granted");
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
if (control?.type === "engine-announce") {
|
|
1710
|
+
const announced = event.ports?.[0];
|
|
1711
|
+
if (announced) router!.announceEngine(announced as unknown as RouterPort);
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
// ADR-0049 D1 capability-absence fallback: the tab's elected DEDICATED engine probed its OWN scope and was
|
|
1715
|
+
// DENIED — no home on this platform can hold sync-access handles. Abandon election and boot the IN-SCOPE
|
|
1716
|
+
// idbfs engine here (with the registry-declared durability), stamping the reported reason into the fallback
|
|
1717
|
+
// boot's `storageFallbackReason` (decision 12). This tab's port is connected to the in-scope host now; other
|
|
1718
|
+
// tabs re-establish through their placement re-query on reconnect.
|
|
1719
|
+
if (control?.type === "engine-fallback") {
|
|
1720
|
+
fallBackToIdbfs(control.reason, port);
|
|
1721
|
+
}
|
|
1722
|
+
};
|
|
1723
|
+
port.addEventListener("message", metaListener);
|
|
1724
|
+
port.start?.();
|
|
1725
|
+
if (current.engineHome === "shared-worker") {
|
|
1726
|
+
deps.connect(port);
|
|
1727
|
+
} else {
|
|
1728
|
+
router!.attachTab(port as unknown as RouterPort);
|
|
1729
|
+
}
|
|
1730
|
+
};
|
|
1731
|
+
|
|
1732
|
+
// ADR-0049 D1: flip a router-only (`elected-worker`) scope to the in-SharedWorker IDBFS fallback when the elected
|
|
1733
|
+
// engine reports its own probe was denied (capability absence in every home). Idempotent — the first report wins.
|
|
1734
|
+
// Re-threads the placement onto the entry (so the lazily-booting in-scope engine opens idbfs with the fallback
|
|
1735
|
+
// reason) and connects the reporting tab's port to the in-scope host. Peer tabs re-establish via placement re-query.
|
|
1736
|
+
let fellBack = false;
|
|
1737
|
+
const fallBackToIdbfs = (reason: string, reportingPort: BridgePort): void => {
|
|
1738
|
+
if (fellBack) return;
|
|
1739
|
+
fellBack = true;
|
|
1740
|
+
placement = { engineHome: "shared-worker", swInstanceId: placement?.swInstanceId ?? crypto.randomUUID() };
|
|
1741
|
+
deps.onPlacement?.({ engineHome: "shared-worker", opfsGranted: false, storageFallbackReason: reason });
|
|
1742
|
+
deps.connect(reportingPort);
|
|
1743
|
+
};
|
|
1744
|
+
|
|
1745
|
+
void decide().then((result) => {
|
|
1746
|
+
placement = result;
|
|
1747
|
+
// `shared-worker` ⇒ the engine boots in-scope: holding OPFS access on a GRANTED probe, or on IDBFS with a
|
|
1748
|
+
// `storageFallbackReason` when the decision is a capability-absence fallback. `elected-worker` ⇒ router-only, no
|
|
1749
|
+
// in-scope grant (each tab's elected DEDICATED engine probes its own scope). Thread grant + home + fallback
|
|
1750
|
+
// reason, open the boot gate. The fallback is idbfs regardless of `opfsGrantedForSharedHome`.
|
|
1751
|
+
const isSharedFallback = result.engineHome === "shared-worker" && result.storageFallbackReason !== undefined;
|
|
1752
|
+
deps.onPlacement?.({
|
|
1753
|
+
engineHome: result.engineHome,
|
|
1754
|
+
opfsGranted: result.engineHome === "shared-worker" && opfsGrantedForSharedHome && !isSharedFallback,
|
|
1755
|
+
...(isSharedFallback ? { storageFallbackReason: result.storageFallbackReason } : {}),
|
|
1756
|
+
});
|
|
1757
|
+
if (result.engineHome === "elected-worker") {
|
|
1758
|
+
router = createEngineRouter({
|
|
1759
|
+
swInstanceId: result.swInstanceId,
|
|
1760
|
+
...(deps.executionLimit ? { executionLimit: deps.executionLimit } : {}),
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
for (const port of pendingPorts) attachPort(port);
|
|
1764
|
+
pendingPorts.length = 0;
|
|
1765
|
+
});
|
|
1766
|
+
|
|
1767
|
+
scope.onconnect = (event: SharedWorkerConnectEvent) => {
|
|
1768
|
+
const port = event.ports[0];
|
|
1769
|
+
if (!port) return;
|
|
1770
|
+
if (placement === undefined) pendingPorts.push(port);
|
|
1771
|
+
else attachPort(port);
|
|
1772
|
+
};
|
|
1773
|
+
}
|