@pgxsinkit/client 0.2.0 → 0.2.1
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/index.d.ts +20 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +460 -165
- package/dist/index.js.map +8 -8
- package/dist/mutation.d.ts +6 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +81 -20
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +33 -8
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +2 -1
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +32 -21
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +3 -3
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +47 -8
- package/src/index.ts +55 -7
- package/src/mutation.ts +48 -4
- package/src/worker/attach-sync-client.ts +322 -130
- package/src/worker/define-sync-worker.ts +445 -132
- package/src/worker/engine-control.ts +2 -2
- package/src/worker/protocol.ts +33 -6
|
@@ -18,10 +18,12 @@ import type { Results } from "@electric-sql/pglite";
|
|
|
18
18
|
import type {
|
|
19
19
|
MutationDiagnostics,
|
|
20
20
|
SyncRuntimeStatus,
|
|
21
|
+
SyncStorageDeclaration,
|
|
21
22
|
SyncTableName,
|
|
22
23
|
SyncTableRegistry,
|
|
23
24
|
WriteMode,
|
|
24
25
|
} from "@pgxsinkit/contracts";
|
|
26
|
+
import { StorageDeclarationRefusedError } from "@pgxsinkit/contracts";
|
|
25
27
|
|
|
26
28
|
import type { BootReport } from "../boot-report";
|
|
27
29
|
import type { DataExportOptions, DataExportResult } from "../export-data";
|
|
@@ -49,6 +51,9 @@ import { storeIndexedDbDatabaseName } from "../store-path";
|
|
|
49
51
|
import { readTestStoreMarker } from "../store-path";
|
|
50
52
|
import {
|
|
51
53
|
CONTROL_PORT_DELIVERY_KEY,
|
|
54
|
+
DECLARATION_KEY,
|
|
55
|
+
DECLARATION_REFUSED_KEY,
|
|
56
|
+
type DeclarationRefusedWire,
|
|
52
57
|
DESTROY_QUERY_KEY,
|
|
53
58
|
DESTROY_VERDICT_KEY,
|
|
54
59
|
PLACEMENT_RESULT_KEY,
|
|
@@ -85,6 +90,7 @@ import {
|
|
|
85
90
|
type ExportArtefactWire,
|
|
86
91
|
type GuardedQueryWireArgs,
|
|
87
92
|
identityCodec,
|
|
93
|
+
type BridgeErrorWire,
|
|
88
94
|
isBridgeEnvelope,
|
|
89
95
|
type LiveDiffPayload,
|
|
90
96
|
type LiveHydratedPayload,
|
|
@@ -277,6 +283,134 @@ export function createStoreDestructionEffects(
|
|
|
277
283
|
};
|
|
278
284
|
}
|
|
279
285
|
|
|
286
|
+
/**
|
|
287
|
+
* Destroy every local artifact of a store BY PATH (ADR-0050 stage 2; the public face of the ADR-0049 D8
|
|
288
|
+
* destruction machinery): the OPFS store directory, the commitment sentinel, the meta record, AND the idb
|
|
289
|
+
* database — backend-agnostic (delete-if-present on both backends), with the bounded VFS-ownership-lag retry.
|
|
290
|
+
*
|
|
291
|
+
* **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
|
|
292
|
+
* supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
|
|
293
|
+
* `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
|
|
294
|
+
* behind, a wipe of known store paths. Called on a path a live engine still holds, the backend delete throws
|
|
295
|
+
* an ownership error after the bounded retry — loud, and safely RE-RUNNABLE: the destruction sequence is
|
|
296
|
+
* idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
|
|
297
|
+
* completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
|
|
298
|
+
* already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
|
|
299
|
+
*/
|
|
300
|
+
export function destroyStoreArtifacts(storePath: string, opts?: StoreDestructionRetryOptions): Promise<void> {
|
|
301
|
+
return runStoreDestruction(createStoreDestructionEffects(storePath), opts);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Options for {@link quiesceStoreWorker} (ADR-0050). */
|
|
305
|
+
export interface StoreWorkerQuiesceOptions {
|
|
306
|
+
/** The ADR-0050 storage declaration to post on the port. Omit (or `{}`) to state NO opinion — always
|
|
307
|
+
* compatible with whatever declaration the live worker already bound, so it can never be refused. Passing a
|
|
308
|
+
* concrete declaration risks a `StorageDeclarationRefusedError` if it disagrees with the bound one. */
|
|
309
|
+
storage?: SyncStorageDeclaration;
|
|
310
|
+
/** Bound on the whole handshake (declaration → placement reply → teardown ack). Default 6000ms. On timeout
|
|
311
|
+
* the returned promise REJECTS — the caller keeps the path on its retry list; it is NOT proof of teardown. */
|
|
312
|
+
timeoutMs?: number;
|
|
313
|
+
/** Injectable timers (tests); defaults to real `setTimeout`/`clearTimeout`. */
|
|
314
|
+
timers?: AttachClientTimers;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The outcome of {@link quiesceStoreWorker}. */
|
|
318
|
+
export interface StoreWorkerQuiesceOutcome {
|
|
319
|
+
/** The store's engine home as reported by its placement reply. */
|
|
320
|
+
engineHome: PlacementQueryResult["engineHome"];
|
|
321
|
+
/** True iff an SW-direct engine was torn down here (its host closed, releasing the backend connection).
|
|
322
|
+
* `false` for an `elected-worker` home — there is no in-SharedWorker engine to close from this router-only
|
|
323
|
+
* connection; the elected dedicated engine dies with its owning tab (the browser terminates it on document
|
|
324
|
+
* teardown), releasing its store, so no active teardown is needed before a path-addressed destroy. */
|
|
325
|
+
toreDown: boolean;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Quiesce the SharedWorker HOSTING a store, by path, so its backend connection is released BEFORE a
|
|
330
|
+
* {@link destroyStoreArtifacts} on the same path (ADR-0050). The gap it closes: the board's workers are
|
|
331
|
+
* `extendedLifetime`, so a store's SharedWorker OUTLIVES the document that spawned it — and the idbfs backend
|
|
332
|
+
* holds its IndexedDB connection open for the engine's whole life. So after a reload, an idbfs store's worker
|
|
333
|
+
* is still alive and still holding the connection; `deleteDatabase` blocks and `destroyStoreArtifacts` fails,
|
|
334
|
+
* boot after boot, until the browser eventually reaps the worker. OPFS releases its handles when idle, so it
|
|
335
|
+
* never had this problem — this is the idbfs (SW-direct) fix.
|
|
336
|
+
*
|
|
337
|
+
* `worker` is a factory (or instance), exactly like {@link attachSyncClient}'s `worker` — the caller constructs
|
|
338
|
+
* `new SharedWorker(url, { name: storePath })`, so the library stays DOM-free. Connecting by that name reaches
|
|
339
|
+
* the LIVE worker (if any) or spawns a fresh one; either way the sequence is: post the declaration, query
|
|
340
|
+
* placement, and — for a `shared-worker` home — send `engine-teardown` and await its reserved ack, which the
|
|
341
|
+
* host posts only after `closeHost()` has stopped the engine and released the backend connection (it then
|
|
342
|
+
* closes its own scope). An `elected-worker` home resolves immediately with `toreDown: false` (see the field).
|
|
343
|
+
*
|
|
344
|
+
* Idempotent and safe on an already-dead store: a fresh spawn boots no engine, and its teardown closes an empty
|
|
345
|
+
* host. Compose it as `await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)` — a
|
|
346
|
+
* quiesce failure (timeout) must NOT abort the destroy, whose own ownership-lag handling reports honestly and
|
|
347
|
+
* leaves the path re-runnable.
|
|
348
|
+
*/
|
|
349
|
+
export function quiesceStoreWorker(
|
|
350
|
+
worker: (() => WorkerLike) | WorkerLike,
|
|
351
|
+
opts?: StoreWorkerQuiesceOptions,
|
|
352
|
+
): Promise<StoreWorkerQuiesceOutcome> {
|
|
353
|
+
const timers: AttachClientTimers = opts?.timers ?? {
|
|
354
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
355
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
356
|
+
};
|
|
357
|
+
const timeoutMs = opts?.timeoutMs ?? 6000;
|
|
358
|
+
const port = resolvePort({ worker });
|
|
359
|
+
return new Promise<StoreWorkerQuiesceOutcome>((resolve, reject) => {
|
|
360
|
+
let settled = false;
|
|
361
|
+
let teardownIdentity: EngineIdentity | undefined;
|
|
362
|
+
const finish = (run: () => void): void => {
|
|
363
|
+
if (settled) return;
|
|
364
|
+
settled = true;
|
|
365
|
+
timers.clearTimeout(timeout);
|
|
366
|
+
port.removeEventListener("message", listener);
|
|
367
|
+
run();
|
|
368
|
+
};
|
|
369
|
+
const timeout = timers.setTimeout(
|
|
370
|
+
() => finish(() => reject(new Error(`[pgxsinkit] quiesceStoreWorker timed out after ${timeoutMs}ms`))),
|
|
371
|
+
timeoutMs,
|
|
372
|
+
);
|
|
373
|
+
const listener = (event: { data: unknown }): void => {
|
|
374
|
+
const placement = readPlacementResult(event.data);
|
|
375
|
+
if (placement !== undefined) {
|
|
376
|
+
if (placement.engineHome !== "shared-worker") {
|
|
377
|
+
finish(() => resolve({ engineHome: placement.engineHome, toreDown: false }));
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
// SW-direct: ask the in-scope host to quiesce+close, then await its reserved teardown ack (pingId -1),
|
|
381
|
+
// which proves the engine stopped and the backend connection was released (define-sync-worker).
|
|
382
|
+
teardownIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
|
|
383
|
+
port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity: teardownIdentity }));
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const refusal = readDeclarationRefusal(event.data);
|
|
387
|
+
if (refusal !== undefined) {
|
|
388
|
+
finish(() => reject(new StorageDeclarationRefusedError(refusal.message)));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const control = readControlEnvelope(event.data);
|
|
392
|
+
if (
|
|
393
|
+
control?.type === "control-ack" &&
|
|
394
|
+
control.pingId === -1 &&
|
|
395
|
+
teardownIdentity !== undefined &&
|
|
396
|
+
control.identity?.swInstanceId === teardownIdentity.swInstanceId
|
|
397
|
+
) {
|
|
398
|
+
if (control.error) {
|
|
399
|
+
finish(() => reject(new Error(`[pgxsinkit] store-worker teardown failed: ${control.error?.message}`)));
|
|
400
|
+
} else {
|
|
401
|
+
finish(() => resolve({ engineHome: "shared-worker", toreDown: true }));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
port.addEventListener("message", listener);
|
|
406
|
+
port.start?.();
|
|
407
|
+
// Declaration FIRST (ADR-0050), then the placement query. If the worker's placement is still pending (a
|
|
408
|
+
// fresh spawn), the queued-traffic path redelivers the follow-up teardown after routing (ADR-0050 W1).
|
|
409
|
+
port.postMessage({ [DECLARATION_KEY]: opts?.storage ?? {} });
|
|
410
|
+
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
280
414
|
/** The bounded ownership-retry options for {@link runStoreDestruction} (the VFS-lock-lag guard, D8/fault row). */
|
|
281
415
|
export interface StoreDestructionRetryOptions {
|
|
282
416
|
/** Max retries of `deleteBackendStore` on an ownership-lock-lag error before giving up (default 5). */
|
|
@@ -349,6 +483,15 @@ function readDestroyVerdict(data: unknown): number | undefined {
|
|
|
349
483
|
return typeof peers === "number" ? peers : undefined;
|
|
350
484
|
}
|
|
351
485
|
|
|
486
|
+
/** Narrow a raw storage-declaration refusal (`{ [DECLARATION_REFUSED_KEY]: { message, name } }`), or `undefined`. */
|
|
487
|
+
function readDeclarationRefusal(data: unknown): DeclarationRefusedWire | undefined {
|
|
488
|
+
if (typeof data !== "object" || data === null) return undefined;
|
|
489
|
+
const refusal = (data as { [DECLARATION_REFUSED_KEY]?: unknown })[DECLARATION_REFUSED_KEY];
|
|
490
|
+
if (typeof refusal !== "object" || refusal === null) return undefined;
|
|
491
|
+
const message = (refusal as { message?: unknown }).message;
|
|
492
|
+
return typeof message === "string" ? (refusal as unknown as DeclarationRefusedWire) : undefined;
|
|
493
|
+
}
|
|
494
|
+
|
|
352
495
|
/**
|
|
353
496
|
* The `setTimeout`/`clearTimeout` pair the handoff-queue deadline and the bridge-silence reconnect schedule on
|
|
354
497
|
* (ADR-0049 step 7) — injectable for deterministic tests, exactly the discipline `engine-router.ts` follows so
|
|
@@ -430,11 +573,27 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
430
573
|
* Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.
|
|
431
574
|
* A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred
|
|
432
575
|
* `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.
|
|
433
|
-
* Restore rides the
|
|
434
|
-
*
|
|
435
|
-
*
|
|
576
|
+
* Restore rides the one handshake that reaches the ENGINE HOME: a restore-bearing attach awaits the
|
|
577
|
+
* placement reply, then carries the artifact on the SW-port handshake when the in-scope host is the engine
|
|
578
|
+
* (SW-direct / declared-idbfs) or on the first per-tab PIPE handshake when the engine is elected — the
|
|
579
|
+
* router-only SharedWorker is payload-blind, so a restore posted there would be dropped and destroyed.
|
|
580
|
+
* Passing it when the engine has ALREADY booted rejects the attach with a typed error
|
|
581
|
+
* (`RestoreIntoRunningStoreError` by name — you cannot restore into a running store). The restored engine
|
|
582
|
+
* boots offline and its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on
|
|
583
|
+
* `createSyncClient`.
|
|
436
584
|
*/
|
|
437
585
|
restoreFrom?: File | Blob;
|
|
586
|
+
/**
|
|
587
|
+
* The tab's WIRE storage declaration for this store (ADR-0050) — posted as the declaration message on the
|
|
588
|
+
* worker port BEFORE the placement query (so `backend: "idbfs"` can skip the probe), and carried on the
|
|
589
|
+
* provision/attach payloads so the engine binds it (durability included). Omit (or `{}`) for "no opinion":
|
|
590
|
+
* a registry-attached static declaration, else the capability defaults, decide. A registry-attached
|
|
591
|
+
* declaration is AUTHORITATIVE — an explicit field here that disagrees with it (or with the declaration
|
|
592
|
+
* another tab already bound) is a typed refusal (`StorageDeclarationRefusedError`), never silently
|
|
593
|
+
* overridden: a store's declaration is immutable, and a preference change mints a fresh store under a
|
|
594
|
+
* fresh path instead.
|
|
595
|
+
*/
|
|
596
|
+
storage?: SyncStorageDeclaration;
|
|
438
597
|
codec?: BridgeCodec;
|
|
439
598
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
440
599
|
onConflict?: (details: MutationDetail[]) => void;
|
|
@@ -562,6 +721,9 @@ interface ElectedCoordinatorParams {
|
|
|
562
721
|
/** The SharedWorker reconstruction factory (ADR-0049 D5) — drives the keepalive SW-death recovery. Absent for a
|
|
563
722
|
bare-instance input, where reconstruction is structurally unavailable. */
|
|
564
723
|
swFactory?: () => WorkerLike;
|
|
724
|
+
/** The tab's wire storage declaration (ADR-0050) — posted FIRST on every reconstructed SW port, before the
|
|
725
|
+
coordinator's announce/keepalive traffic, so a fresh bootstrap binds and routes instead of refusing. */
|
|
726
|
+
storage?: SyncStorageDeclaration;
|
|
565
727
|
electionIo?: AttachSyncClientOptions<SyncTableRegistry>["electionIo"];
|
|
566
728
|
awaitOwnershipRelease?: () => Promise<void>;
|
|
567
729
|
timers: AttachClientTimers;
|
|
@@ -606,7 +768,15 @@ function buildElectedCoordinator(params: ElectedCoordinatorParams): ElectionCoor
|
|
|
606
768
|
},
|
|
607
769
|
swPort: params.controlPort as unknown as SwBridgePort,
|
|
608
770
|
...(params.swFactory
|
|
609
|
-
? {
|
|
771
|
+
? {
|
|
772
|
+
reconstructSw: () => {
|
|
773
|
+
const port = resolvePort({ worker: params.swFactory! });
|
|
774
|
+
// ADR-0050: the reconstructed SharedWorker is a fresh bootstrap — declare before the coordinator's
|
|
775
|
+
// announce rides this port, or the bootstrap refuses/queues nothing and recovery hangs.
|
|
776
|
+
port.postMessage({ [DECLARATION_KEY]: params.storage ?? {} });
|
|
777
|
+
return port as unknown as SwBridgePort;
|
|
778
|
+
},
|
|
779
|
+
}
|
|
610
780
|
: {}),
|
|
611
781
|
awaitOwnershipRelease: params.awaitOwnershipRelease ?? resolvedOwnershipRelease,
|
|
612
782
|
timers: params.timers,
|
|
@@ -631,6 +801,8 @@ const sharedCoordinators = new Map<
|
|
|
631
801
|
{
|
|
632
802
|
coordinator: ElectionCoordinator;
|
|
633
803
|
refs: number;
|
|
804
|
+
/** Release the provision claim and cancel its expiry after an explicit construction-identity retirement. */
|
|
805
|
+
releaseProvision?: () => void;
|
|
634
806
|
/**
|
|
635
807
|
* The provision's live engine pipe, held for HANDOVER (ADR-0049 step 8). The router mints exactly ONE proxy
|
|
636
808
|
* pipe per SW connection; when provision and attach share one port (the documented ordered-messages contract,
|
|
@@ -688,6 +860,12 @@ function takeProvisionPipe(storePath: string): { pipe: BridgePort; identity: Eng
|
|
|
688
860
|
return stashed;
|
|
689
861
|
}
|
|
690
862
|
|
|
863
|
+
/** Record the provision claim's explicit release companion on its shared coordinator entry. */
|
|
864
|
+
function setProvisionRelease(storePath: string, release: () => void): void {
|
|
865
|
+
const entry = sharedCoordinators.get(storePath);
|
|
866
|
+
if (entry !== undefined) entry.releaseProvision = release;
|
|
867
|
+
}
|
|
868
|
+
|
|
691
869
|
export async function attachSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
692
870
|
options: AttachSyncClientOptions<TRegistry>,
|
|
693
871
|
): Promise<AttachedSyncClient<TRegistry>> {
|
|
@@ -735,13 +913,27 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
735
913
|
let releaseElectionClaim: (() => void) | undefined;
|
|
736
914
|
let destroyVerdictResolver: ((peers: number) => void) | undefined;
|
|
737
915
|
let placementResult: PlacementQueryResult | undefined;
|
|
738
|
-
let swTeardownAckResolver: ((error?:
|
|
916
|
+
let swTeardownAckResolver: ((error?: BridgeErrorWire) => void) | undefined;
|
|
739
917
|
let swTeardownIdentity: EngineIdentity | undefined;
|
|
740
918
|
// Set to the store path when this attach ADOPTED a shared (provision-registered) coordinator — so detach
|
|
741
919
|
// releases the shared ref (ref-counted registry cleanup). Undefined when this tab built its own coordinator.
|
|
742
920
|
let adoptedSharedCoordinatorStore: string | undefined;
|
|
743
921
|
// The placement decision is single-shot: once we act on the first `electionRequired` reply we ignore any repeat.
|
|
744
922
|
let placementDecided = false;
|
|
923
|
+
// Settles when the FIRST placement reply arrives (the bootstrap meta listener answers the query in BOTH SW
|
|
924
|
+
// modes) — or REJECTS typed when the worker refuses this tab's storage declaration (ADR-0050), which arrives
|
|
925
|
+
// in place of the placement reply. Every boot awaits it before the first handshake — see the send site.
|
|
926
|
+
let resolvePlacementKnown: (() => void) | undefined;
|
|
927
|
+
let rejectPlacementKnown: ((error: Error) => void) | undefined;
|
|
928
|
+
const placementKnown = new Promise<void>((resolve, reject) => {
|
|
929
|
+
resolvePlacementKnown = resolve;
|
|
930
|
+
rejectPlacementKnown = reject;
|
|
931
|
+
});
|
|
932
|
+
// A refusal may land after a detach already settled the boot path — never an unhandled rejection.
|
|
933
|
+
void placementKnown.catch(() => undefined);
|
|
934
|
+
// The restore artifact rides EXACTLY ONE handshake — its ArrayBuffer detaches on first post, so a resend
|
|
935
|
+
// would carry an empty buffer. Set the moment a handshake actually carries it (see `runAttachHandshake`).
|
|
936
|
+
let restoreConsumed = false;
|
|
745
937
|
|
|
746
938
|
// ─── ADR-0049 first-attach gate (placement-query-FIRST ordering — elected-mode ack routing) ───────
|
|
747
939
|
// `attachSyncClient` no longer gates on the SW-port attach ack: a router-only SharedWorker (elected-worker home)
|
|
@@ -1019,6 +1211,16 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1019
1211
|
onPlacementResult(placementResult);
|
|
1020
1212
|
return;
|
|
1021
1213
|
}
|
|
1214
|
+
// ADR-0050: the worker refused this tab's storage declaration (explicit conflict with the bound/static
|
|
1215
|
+
// declaration, or engine-bound traffic before the declaration). It arrives IN PLACE of the placement
|
|
1216
|
+
// reply, so fail the boot typed and loudly — never a hang, never a silently different storage mode.
|
|
1217
|
+
const declarationRefusal = readDeclarationRefusal(event.data);
|
|
1218
|
+
if (declarationRefusal !== undefined) {
|
|
1219
|
+
const refusal = new StorageDeclarationRefusedError(declarationRefusal.message);
|
|
1220
|
+
rejectPlacementKnown?.(refusal);
|
|
1221
|
+
failFirstAttach(refusal);
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1022
1224
|
const destroyPeers = readDestroyVerdict(event.data);
|
|
1023
1225
|
if (destroyPeers !== undefined) {
|
|
1024
1226
|
destroyVerdictResolver?.(destroyPeers);
|
|
@@ -1164,7 +1366,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1164
1366
|
swapDataPort(pipe, replacing);
|
|
1165
1367
|
hasPipe = true;
|
|
1166
1368
|
try {
|
|
1167
|
-
|
|
1369
|
+
// `includeRestore: true` — in elected mode THIS is the engine's boot attach, so the restore artifact
|
|
1370
|
+
// (withheld from the router-dropped SW-port handshake) rides here, over the direct tab↔engine pipe.
|
|
1371
|
+
// The `restoreConsumed` guard makes it first-carry-only: a pipe REPLACEMENT re-attach never re-sends.
|
|
1372
|
+
await runAttachHandshake(pipe, true);
|
|
1168
1373
|
} catch {
|
|
1169
1374
|
// A failed re-attach leaves the window open; a later notice / connect-port can retry. Never auto-retried.
|
|
1170
1375
|
return;
|
|
@@ -1216,6 +1421,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1216
1421
|
newPort.addEventListener("message", listener);
|
|
1217
1422
|
newPort.addEventListener("message", controlListener);
|
|
1218
1423
|
newPort.start?.();
|
|
1424
|
+
// ADR-0050: the reconstructed SharedWorker may be a FRESH bootstrap whose placement is still pending —
|
|
1425
|
+
// every port must declare before any engine-bound message. The declaration precedes the attach on the same
|
|
1426
|
+
// port, and the bootstrap queues the attach until placement resolves (no placement round-trip needed here).
|
|
1427
|
+
newPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
1219
1428
|
try {
|
|
1220
1429
|
await runAttachHandshake(newPort, false);
|
|
1221
1430
|
} catch {
|
|
@@ -1248,6 +1457,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1248
1457
|
if (detached || placementDecided) return;
|
|
1249
1458
|
placementDecided = true;
|
|
1250
1459
|
placementResult = result;
|
|
1460
|
+
resolvePlacementKnown?.();
|
|
1251
1461
|
// SW-direct / declared-idbfs (or a non-placement transport that never replies): the SW-port attach ack gates the flow.
|
|
1252
1462
|
if (!result.electionRequired) return;
|
|
1253
1463
|
// Elected-worker (router-only): resolve the engine factory. Auto-derivation from the reported script URL is the
|
|
@@ -1337,6 +1547,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1337
1547
|
controlPort,
|
|
1338
1548
|
createEngineWorker: electedEngineFactory!,
|
|
1339
1549
|
...(workerFactory ? { swFactory: workerFactory } : {}),
|
|
1550
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
1340
1551
|
...(options.electionIo ? { electionIo: options.electionIo } : {}),
|
|
1341
1552
|
...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
|
|
1342
1553
|
timers,
|
|
@@ -1428,14 +1639,19 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1428
1639
|
let pendingAttachAck: { resolve: (ack: AttachAckPayload) => void; reject: (error: Error) => void } | null = null;
|
|
1429
1640
|
const runAttachHandshake = (target: BridgePort, includeRestore: boolean): Promise<AttachAckPayload> =>
|
|
1430
1641
|
new Promise<AttachAckPayload>((resolve, reject) => {
|
|
1642
|
+
// The restore artifact rides at most ONE handshake ever (`restoreConsumed`): posting transfers (detaches)
|
|
1643
|
+
// its ArrayBuffer, so any later handshake would carry an empty husk. The caller chooses the target that
|
|
1644
|
+
// actually reaches the engine home; this guard makes a second carry structurally impossible.
|
|
1645
|
+
const carryRestore = includeRestore && restoreWire !== undefined && !restoreConsumed;
|
|
1646
|
+
if (carryRestore) restoreConsumed = true;
|
|
1431
1647
|
pendingAttachAck = { resolve, reject };
|
|
1432
1648
|
postBridgeMessage(
|
|
1433
1649
|
target,
|
|
1434
1650
|
codec,
|
|
1435
1651
|
"attach",
|
|
1436
|
-
buildAttachPayload(
|
|
1652
|
+
buildAttachPayload(carryRestore),
|
|
1437
1653
|
undefined,
|
|
1438
|
-
|
|
1654
|
+
carryRestore && restoreWire ? [restoreWire.buffer] : undefined,
|
|
1439
1655
|
);
|
|
1440
1656
|
});
|
|
1441
1657
|
|
|
@@ -1619,13 +1835,17 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1619
1835
|
}
|
|
1620
1836
|
: undefined;
|
|
1621
1837
|
// The attach payload builder — reused by the FIRST attach and every re-attach (pipe swap / reconnect). Restore
|
|
1622
|
-
// rides ONLY the
|
|
1623
|
-
//
|
|
1838
|
+
// rides ONLY the one handshake that reaches the engine home (SW port in SW-direct, first pipe attach when
|
|
1839
|
+
// elected — see the send sites); `runAttachHandshake`'s `restoreConsumed` guard makes any later carry
|
|
1840
|
+
// structurally impossible (the buffer is transferred/detached, and you cannot restore into a running store).
|
|
1624
1841
|
function buildAttachPayload(includeRestore: boolean): AttachPayload {
|
|
1625
1842
|
return {
|
|
1626
1843
|
token: initialToken,
|
|
1627
1844
|
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
1628
1845
|
...(options.storePath ? { storePath: options.storePath } : {}),
|
|
1846
|
+
// ADR-0050: the wire storage declaration also rides the attach payload, so the ENGINE binds it
|
|
1847
|
+
// (durability included) wherever it runs — the pre-placement declaration message only steers placement.
|
|
1848
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
1629
1849
|
...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
|
|
1630
1850
|
...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
|
|
1631
1851
|
...(includeRestore && restoreWire ? { restore: restoreWire } : {}),
|
|
@@ -1640,19 +1860,46 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1640
1860
|
: {}),
|
|
1641
1861
|
};
|
|
1642
1862
|
}
|
|
1643
|
-
// ─── ADR-
|
|
1644
|
-
// Post the
|
|
1645
|
-
//
|
|
1646
|
-
//
|
|
1647
|
-
//
|
|
1648
|
-
// `
|
|
1863
|
+
// ─── ADR-0050 declaration-FIRST, then placement-query, then handshake ─────────────────────────────
|
|
1864
|
+
// Post the storage DECLARATION MESSAGE first — always, even empty (`{}` = "no opinion") — because a
|
|
1865
|
+
// registry-silent worker DEFERS its placement decision until the first declaration arrives (`backend:
|
|
1866
|
+
// "idbfs"` must skip the probe, so the declaration must precede the decision). Then the placement query
|
|
1867
|
+
// (ADR-0049): a router-only SharedWorker (elected-worker home) is payload-blind and DROPS the bridge
|
|
1868
|
+
// `attach`, so an SW-port ack could never gate the flow — but the bootstrap meta listener answers the
|
|
1869
|
+
// placement query in BOTH SW modes, so this reliably drives election. In SW-direct / declared-idbfs (and
|
|
1870
|
+
// the no-placement / plain-port case) the reply is `electionRequired: false` (or absent) and the SW-port
|
|
1871
|
+
// attach below acks normally — a plain in-scope host attach.
|
|
1872
|
+
controlPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
1649
1873
|
controlPort.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
1650
|
-
//
|
|
1651
|
-
//
|
|
1652
|
-
//
|
|
1653
|
-
//
|
|
1654
|
-
//
|
|
1655
|
-
|
|
1874
|
+
// EVERY boot awaits the placement reply before the first handshake (ADR-0050). The worker only installs the
|
|
1875
|
+
// engine listener on this port once placement resolves and the port's declaration is accepted, so an attach
|
|
1876
|
+
// posted earlier would be refused as a protocol violation — and the reply's slot is also where a storage
|
|
1877
|
+
// DECLARATION REFUSAL arrives (typed boot failure instead of a reply). This costs no real latency: the old
|
|
1878
|
+
// fire-and-forget attach queued browser-side behind the very same placement decision. Restore-bearing boots
|
|
1879
|
+
// additionally depend on this ordering for artifact routing: the restore's ArrayBuffer detaches on first
|
|
1880
|
+
// post, and in elected mode the router-only SharedWorker silently DROPS bridge `attach` envelopes — so the
|
|
1881
|
+
// restore is carried on the SW-port handshake only when the in-scope host IS the engine (SW-direct /
|
|
1882
|
+
// declared-idbfs), and on the first per-tab PIPE handshake (`onConnectPort`) when the engine is elected.
|
|
1883
|
+
try {
|
|
1884
|
+
await placementKnown;
|
|
1885
|
+
} catch (error) {
|
|
1886
|
+
// A typed declaration refusal (never a plain transport error): run the full detach so both listeners and
|
|
1887
|
+
// the pagehide handler are removed, then propagate — the boot fails loudly with the refusal.
|
|
1888
|
+
detachFromWorker();
|
|
1889
|
+
throw error;
|
|
1890
|
+
}
|
|
1891
|
+
// Send the tab's attach handshake — placement is KNOWN here (awaited above). SW-direct / plain / no-reply:
|
|
1892
|
+
// the current data port reaches the in-scope engine, which acks it (restore included). Elected
|
|
1893
|
+
// (`electionRequired`): the engine-reaching handshake is the per-tab PIPE one (`onConnectPort`, or the
|
|
1894
|
+
// adoption handover of a stashed provision pipe); the SW-port post below is the router-dropped
|
|
1895
|
+
// fire-and-forget (payload-blind — never taught to answer bridge envelopes), kept so `firstAttachReady` can
|
|
1896
|
+
// settle off whichever port answers first. The ONE case that must not post is elected mode with the data
|
|
1897
|
+
// path ALREADY swapped onto an adopted pipe — there the post would reach the live engine as a DUPLICATE
|
|
1898
|
+
// attach (a second boot) instead of being dropped.
|
|
1899
|
+
const handshakePort = currentDataPort();
|
|
1900
|
+
if (placementResult?.electionRequired !== true || handshakePort === controlPort) {
|
|
1901
|
+
void runAttachHandshake(handshakePort, placementResult?.electionRequired !== true).catch(() => undefined);
|
|
1902
|
+
}
|
|
1656
1903
|
try {
|
|
1657
1904
|
await firstAttachReady;
|
|
1658
1905
|
} catch (error) {
|
|
@@ -1840,6 +2087,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1840
2087
|
start: async () => {
|
|
1841
2088
|
await ready;
|
|
1842
2089
|
},
|
|
2090
|
+
// The tab facade holds no local engine — its "activity" is the worker bridge. Synchronously detaching it
|
|
2091
|
+
// (idempotent, no await) IS the tab-side halt: it stops posting/subscribing on the pipe and settles every
|
|
2092
|
+
// pending promise, the analogue of aborting the in-process engine's streams. `stop()` does the same.
|
|
2093
|
+
haltActivity: () => {
|
|
2094
|
+
detachFromWorker();
|
|
2095
|
+
},
|
|
1843
2096
|
stop: async () => {
|
|
1844
2097
|
detachFromWorker();
|
|
1845
2098
|
},
|
|
@@ -2084,6 +2337,7 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2084
2337
|
| "port"
|
|
2085
2338
|
| "storeId"
|
|
2086
2339
|
| "storePath"
|
|
2340
|
+
| "storage"
|
|
2087
2341
|
| "codec"
|
|
2088
2342
|
| "createEngineWorker"
|
|
2089
2343
|
| "electionIo"
|
|
@@ -2099,105 +2353,6 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2099
2353
|
provisionExpiryMs?: number;
|
|
2100
2354
|
};
|
|
2101
2355
|
|
|
2102
|
-
/** Options for deliberately retiring a SW-direct host before changing its construction identity. */
|
|
2103
|
-
export type RetireSyncWorkerHostOptions = Pick<
|
|
2104
|
-
AttachSyncClientOptions<SyncTableRegistry>,
|
|
2105
|
-
"worker" | "port" | "timers"
|
|
2106
|
-
> & {
|
|
2107
|
-
/** Bound for the placement + teardown handshake. Default 5000 ms. */
|
|
2108
|
-
timeoutMs?: number;
|
|
2109
|
-
};
|
|
2110
|
-
|
|
2111
|
-
/**
|
|
2112
|
-
* Quiesce and retire a SW-direct sync host without deleting its store.
|
|
2113
|
-
*
|
|
2114
|
-
* This is the construction-lifecycle companion to {@link provisionSyncWorker}: a caller that must replace a
|
|
2115
|
-
* SharedWorker under a different construction identity (for example, a different durability preference) first
|
|
2116
|
-
* awaits this barrier so the old extended-lifetime worker releases its database handle. Elected placement owns
|
|
2117
|
-
* retirement through its coordinator and is therefore rejected here. Retirement is refused while peer tabs are
|
|
2118
|
-
* attached: changing one tab's construction preference must not terminate a host other tabs are actively using.
|
|
2119
|
-
*/
|
|
2120
|
-
export function retireSyncWorkerHost(options: RetireSyncWorkerHostOptions): Promise<void> {
|
|
2121
|
-
const port = resolvePort(options);
|
|
2122
|
-
const timers: AttachClientTimers = options.timers ?? {
|
|
2123
|
-
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
|
|
2124
|
-
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
|
|
2125
|
-
};
|
|
2126
|
-
|
|
2127
|
-
return new Promise<void>((resolve, reject) => {
|
|
2128
|
-
let identity: EngineIdentity | undefined;
|
|
2129
|
-
let settled = false;
|
|
2130
|
-
const finish = (result: { ok: true } | { ok: false; error: Error }): void => {
|
|
2131
|
-
if (settled) return;
|
|
2132
|
-
settled = true;
|
|
2133
|
-
timers.clearTimeout(timeout);
|
|
2134
|
-
port.removeEventListener("message", listener);
|
|
2135
|
-
if (result.ok) resolve();
|
|
2136
|
-
else reject(result.error);
|
|
2137
|
-
};
|
|
2138
|
-
const listener = (event: { data: unknown }): void => {
|
|
2139
|
-
const placement = readPlacementResult(event.data);
|
|
2140
|
-
if (placement !== undefined) {
|
|
2141
|
-
if (placement.electionRequired) {
|
|
2142
|
-
finish({
|
|
2143
|
-
ok: false,
|
|
2144
|
-
error: new Error(
|
|
2145
|
-
"[pgxsinkit] retireSyncWorkerHost only applies to a SW-direct host; elected placement retires " +
|
|
2146
|
-
"through its election coordinator.",
|
|
2147
|
-
),
|
|
2148
|
-
});
|
|
2149
|
-
return;
|
|
2150
|
-
}
|
|
2151
|
-
identity = { swInstanceId: placement.swInstanceId, generation: 0 };
|
|
2152
|
-
port.postMessage({ [DESTROY_QUERY_KEY]: true });
|
|
2153
|
-
return;
|
|
2154
|
-
}
|
|
2155
|
-
const peers = readDestroyVerdict(event.data);
|
|
2156
|
-
if (peers !== undefined && identity !== undefined) {
|
|
2157
|
-
if (peers > 1) {
|
|
2158
|
-
finish({
|
|
2159
|
-
ok: false,
|
|
2160
|
-
error: new Error(
|
|
2161
|
-
`[pgxsinkit] SW-direct host retirement refused: ${peers} attached tabs still use this store. ` +
|
|
2162
|
-
"Close the peer tabs before changing the worker construction preference.",
|
|
2163
|
-
),
|
|
2164
|
-
});
|
|
2165
|
-
return;
|
|
2166
|
-
}
|
|
2167
|
-
port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity }));
|
|
2168
|
-
return;
|
|
2169
|
-
}
|
|
2170
|
-
const control = readControlEnvelope(event.data);
|
|
2171
|
-
if (
|
|
2172
|
-
identity !== undefined &&
|
|
2173
|
-
control?.type === "control-ack" &&
|
|
2174
|
-
control.pingId === -1 &&
|
|
2175
|
-
engineIdentityEquals(control.identity, identity)
|
|
2176
|
-
) {
|
|
2177
|
-
if (control.error) {
|
|
2178
|
-
finish({
|
|
2179
|
-
ok: false,
|
|
2180
|
-
error: new Error(`[pgxsinkit] SW-direct host teardown failed: ${control.error.message}`),
|
|
2181
|
-
});
|
|
2182
|
-
} else {
|
|
2183
|
-
finish({ ok: true });
|
|
2184
|
-
}
|
|
2185
|
-
}
|
|
2186
|
-
};
|
|
2187
|
-
const timeout = timers.setTimeout(
|
|
2188
|
-
() =>
|
|
2189
|
-
finish({
|
|
2190
|
-
ok: false,
|
|
2191
|
-
error: new Error("[pgxsinkit] timed out while retiring the SW-direct sync host."),
|
|
2192
|
-
}),
|
|
2193
|
-
options.timeoutMs ?? 5_000,
|
|
2194
|
-
);
|
|
2195
|
-
port.addEventListener("message", listener);
|
|
2196
|
-
port.start?.();
|
|
2197
|
-
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
2198
|
-
});
|
|
2199
|
-
}
|
|
2200
|
-
|
|
2201
2356
|
/**
|
|
2202
2357
|
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
|
|
2203
2358
|
* freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the raw store idle
|
|
@@ -2229,11 +2384,14 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2229
2384
|
const provisionPayload = {
|
|
2230
2385
|
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
2231
2386
|
...(options.storePath ? { storePath: options.storePath } : {}),
|
|
2387
|
+
// ADR-0050: the wire storage declaration rides the provision payload too, so the mint's durability comes
|
|
2388
|
+
// from the store's bound declaration wherever the engine runs.
|
|
2389
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
2232
2390
|
...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
|
|
2233
2391
|
};
|
|
2234
2392
|
const pageLifecycle = readDefaultPageLifecycle();
|
|
2235
2393
|
|
|
2236
|
-
|
|
2394
|
+
const provision = new Promise<void>((resolve, reject) => {
|
|
2237
2395
|
let settled = false;
|
|
2238
2396
|
const ackRemovers: Array<() => void> = [];
|
|
2239
2397
|
const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }): void => {
|
|
@@ -2242,6 +2400,13 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2242
2400
|
onPlacement(placement);
|
|
2243
2401
|
return;
|
|
2244
2402
|
}
|
|
2403
|
+
// ADR-0050: the worker refused this provision's storage declaration — it arrives in place of the
|
|
2404
|
+
// placement reply, so the provision fails typed and loudly (never a hang, never a silent mode).
|
|
2405
|
+
const declarationRefusal = readDeclarationRefusal(event.data);
|
|
2406
|
+
if (declarationRefusal !== undefined) {
|
|
2407
|
+
settle(() => reject(new StorageDeclarationRefusedError(declarationRefusal.message)));
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2245
2410
|
const control = readControlEnvelope(event.data);
|
|
2246
2411
|
if (control?.type === "connect-port") onProvisionPipe(event.ports?.[0], control.identity);
|
|
2247
2412
|
};
|
|
@@ -2286,8 +2451,13 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2286
2451
|
const onPlacement = (result: PlacementQueryResult): void => {
|
|
2287
2452
|
if (placementDecided) return;
|
|
2288
2453
|
placementDecided = true;
|
|
2289
|
-
// SW-direct (or a
|
|
2290
|
-
|
|
2454
|
+
// SW-direct (or a plain host, which answers the placement query itself): the worker installs the engine
|
|
2455
|
+
// listener on this port only once placement resolves and the declaration is accepted (ADR-0050), so the
|
|
2456
|
+
// `provision` is posted NOW — on the reply — never fire-and-forget before it.
|
|
2457
|
+
if (!result.electionRequired) {
|
|
2458
|
+
postProvisionOn(port);
|
|
2459
|
+
return;
|
|
2460
|
+
}
|
|
2291
2461
|
// Elected (router-only): the SW drops the `provision` bridge envelope, so ELECT and provision over the pipe.
|
|
2292
2462
|
// Resolve the engine factory exactly as attach does — the `createEngineWorker` override, else the default
|
|
2293
2463
|
// derived from the SharedWorker's reported script URL (dual-scope entry). Neither available → a WIRING failure.
|
|
@@ -2311,6 +2481,7 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2311
2481
|
controlPort: port,
|
|
2312
2482
|
createEngineWorker: engineFactory,
|
|
2313
2483
|
...(provisionSwFactory ? { swFactory: provisionSwFactory } : {}),
|
|
2484
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
2314
2485
|
...(options.electionIo ? { electionIo: options.electionIo } : {}),
|
|
2315
2486
|
...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
|
|
2316
2487
|
timers,
|
|
@@ -2322,20 +2493,34 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2322
2493
|
// AND its shared-coordinator ref release together), so a store nobody adopts never pins the leader lock.
|
|
2323
2494
|
const releaseProvisionClaim = coordinator.claimForProvision();
|
|
2324
2495
|
const expiryMs = options.provisionExpiryMs ?? 60_000;
|
|
2325
|
-
|
|
2496
|
+
let released = false;
|
|
2497
|
+
const expiryHandle = timers.setTimeout(() => {
|
|
2498
|
+
if (released) return;
|
|
2499
|
+
released = true;
|
|
2500
|
+
const entry = sharedCoordinators.get(storePath);
|
|
2501
|
+
if (entry?.releaseProvision === releaseProvision) delete entry.releaseProvision;
|
|
2326
2502
|
releaseProvisionClaim();
|
|
2327
2503
|
releaseSharedCoordinator(storePath);
|
|
2328
2504
|
}, expiryMs);
|
|
2505
|
+
const releaseProvision = (): void => {
|
|
2506
|
+
if (released) return;
|
|
2507
|
+
released = true;
|
|
2508
|
+
timers.clearTimeout(expiryHandle);
|
|
2509
|
+
releaseProvisionClaim();
|
|
2510
|
+
};
|
|
2511
|
+
setProvisionRelease(storePath, releaseProvision);
|
|
2329
2512
|
};
|
|
2330
2513
|
|
|
2331
2514
|
port.addEventListener("message", controlListener);
|
|
2332
2515
|
port.start?.();
|
|
2333
|
-
//
|
|
2334
|
-
//
|
|
2335
|
-
//
|
|
2516
|
+
// Declaration-FIRST, then placement query (ADR-0050, mirroring attach): the declaration message unblocks a
|
|
2517
|
+
// registry-silent worker's deferred placement decision, and the query is answered in BOTH SW modes by the
|
|
2518
|
+
// bootstrap meta listener. The `provision` itself is posted ON the placement reply (`onPlacement`): SW-direct
|
|
2519
|
+
// takes it on this port; a router-only SW would drop it, so elected mode delivers it over the pipe instead.
|
|
2520
|
+
port.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
2336
2521
|
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
2337
|
-
postProvisionOn(port);
|
|
2338
2522
|
});
|
|
2523
|
+
return provision;
|
|
2339
2524
|
}
|
|
2340
2525
|
|
|
2341
2526
|
/** Resolve the default page-lifecycle subscription off `globalThis.window` (structural, no DOM lib) — for the
|
|
@@ -2392,13 +2577,20 @@ function deriveEngineWorkerFactory(swScriptUrl: string | undefined): (() => Elec
|
|
|
2392
2577
|
return () => wrapEngineWorker(new WorkerCtor(swScriptUrl, { type: "module" }));
|
|
2393
2578
|
}
|
|
2394
2579
|
|
|
2395
|
-
/**
|
|
2580
|
+
/**
|
|
2581
|
+
* Rebuild an Error from the bridge's serialized {@link BridgeErrorWire} shape, carrying `name` and `detail`
|
|
2582
|
+
* through. Restoring `name` is what keeps a typed worker-side failure (e.g. a restore refused with
|
|
2583
|
+
* `RestoreTargetExistsError`) detectable by the consumer without message matching.
|
|
2584
|
+
*/
|
|
2396
2585
|
function rebuildError(error: RpcResultPayload["error"]): Error {
|
|
2397
2586
|
if (error && "detail" in error) {
|
|
2398
2587
|
const mismatch = executionLimitMismatchFromWire(error.detail);
|
|
2399
2588
|
if (mismatch !== undefined) return mismatch;
|
|
2400
2589
|
}
|
|
2401
2590
|
const rebuilt = new Error(error?.message ?? "worker rpc failed");
|
|
2591
|
+
if (error?.name !== undefined) {
|
|
2592
|
+
rebuilt.name = error.name;
|
|
2593
|
+
}
|
|
2402
2594
|
if (error && "detail" in error && error.detail !== undefined) {
|
|
2403
2595
|
(rebuilt as Error & { detail?: unknown }).detail = error.detail;
|
|
2404
2596
|
}
|