@pgxsinkit/client 0.2.0 → 0.2.2
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 +83 -22
- 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 +33 -22
- 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 +57 -12
- package/src/index.ts +55 -7
- package/src/mutation.ts +48 -4
- package/src/worker/attach-sync-client.ts +327 -131
- package/src/worker/define-sync-worker.ts +445 -132
- package/src/worker/engine-control.ts +2 -2
- package/src/worker/protocol.ts +41 -7
|
@@ -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,
|
|
@@ -100,7 +106,11 @@ import {
|
|
|
100
106
|
/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */
|
|
101
107
|
interface WorkerLike {
|
|
102
108
|
port?: BridgePort;
|
|
103
|
-
|
|
109
|
+
// `transfer: any` for the same reason `BridgePort.postMessage` uses it — so a DOM `Worker` (whose overloaded
|
|
110
|
+
// `postMessage(message, transfer: Transferable[])` is contravariantly stricter than any DOM-lib-free array
|
|
111
|
+
// type) is assignable to `WorkerLike` without a cast. See the note on `BridgePort` in `protocol.ts`.
|
|
112
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- DOM-postMessage contravariance escape hatch
|
|
113
|
+
postMessage?: (message: unknown, transfer?: any) => void;
|
|
104
114
|
addEventListener?: (
|
|
105
115
|
type: "message" | "error",
|
|
106
116
|
listener: (event: { data?: unknown; message?: unknown }) => void,
|
|
@@ -277,6 +287,134 @@ export function createStoreDestructionEffects(
|
|
|
277
287
|
};
|
|
278
288
|
}
|
|
279
289
|
|
|
290
|
+
/**
|
|
291
|
+
* Destroy every local artifact of a store BY PATH (ADR-0050 stage 2; the public face of the ADR-0049 D8
|
|
292
|
+
* destruction machinery): the OPFS store directory, the commitment sentinel, the meta record, AND the idb
|
|
293
|
+
* database — backend-agnostic (delete-if-present on both backends), with the bounded VFS-ownership-lag retry.
|
|
294
|
+
*
|
|
295
|
+
* **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
|
|
296
|
+
* supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
|
|
297
|
+
* `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
|
|
298
|
+
* behind, a wipe of known store paths. Called on a path a live engine still holds, the backend delete throws
|
|
299
|
+
* an ownership error after the bounded retry — loud, and safely RE-RUNNABLE: the destruction sequence is
|
|
300
|
+
* idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
|
|
301
|
+
* completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
|
|
302
|
+
* already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
|
|
303
|
+
*/
|
|
304
|
+
export function destroyStoreArtifacts(storePath: string, opts?: StoreDestructionRetryOptions): Promise<void> {
|
|
305
|
+
return runStoreDestruction(createStoreDestructionEffects(storePath), opts);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Options for {@link quiesceStoreWorker} (ADR-0050). */
|
|
309
|
+
export interface StoreWorkerQuiesceOptions {
|
|
310
|
+
/** The ADR-0050 storage declaration to post on the port. Omit (or `{}`) to state NO opinion — always
|
|
311
|
+
* compatible with whatever declaration the live worker already bound, so it can never be refused. Passing a
|
|
312
|
+
* concrete declaration risks a `StorageDeclarationRefusedError` if it disagrees with the bound one. */
|
|
313
|
+
storage?: SyncStorageDeclaration;
|
|
314
|
+
/** Bound on the whole handshake (declaration → placement reply → teardown ack). Default 6000ms. On timeout
|
|
315
|
+
* the returned promise REJECTS — the caller keeps the path on its retry list; it is NOT proof of teardown. */
|
|
316
|
+
timeoutMs?: number;
|
|
317
|
+
/** Injectable timers (tests); defaults to real `setTimeout`/`clearTimeout`. */
|
|
318
|
+
timers?: AttachClientTimers;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** The outcome of {@link quiesceStoreWorker}. */
|
|
322
|
+
export interface StoreWorkerQuiesceOutcome {
|
|
323
|
+
/** The store's engine home as reported by its placement reply. */
|
|
324
|
+
engineHome: PlacementQueryResult["engineHome"];
|
|
325
|
+
/** True iff an SW-direct engine was torn down here (its host closed, releasing the backend connection).
|
|
326
|
+
* `false` for an `elected-worker` home — there is no in-SharedWorker engine to close from this router-only
|
|
327
|
+
* connection; the elected dedicated engine dies with its owning tab (the browser terminates it on document
|
|
328
|
+
* teardown), releasing its store, so no active teardown is needed before a path-addressed destroy. */
|
|
329
|
+
toreDown: boolean;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Quiesce the SharedWorker HOSTING a store, by path, so its backend connection is released BEFORE a
|
|
334
|
+
* {@link destroyStoreArtifacts} on the same path (ADR-0050). The gap it closes: the board's workers are
|
|
335
|
+
* `extendedLifetime`, so a store's SharedWorker OUTLIVES the document that spawned it — and the idbfs backend
|
|
336
|
+
* holds its IndexedDB connection open for the engine's whole life. So after a reload, an idbfs store's worker
|
|
337
|
+
* is still alive and still holding the connection; `deleteDatabase` blocks and `destroyStoreArtifacts` fails,
|
|
338
|
+
* boot after boot, until the browser eventually reaps the worker. OPFS releases its handles when idle, so it
|
|
339
|
+
* never had this problem — this is the idbfs (SW-direct) fix.
|
|
340
|
+
*
|
|
341
|
+
* `worker` is a factory (or instance), exactly like {@link attachSyncClient}'s `worker` — the caller constructs
|
|
342
|
+
* `new SharedWorker(url, { name: storePath })`, so the library stays DOM-free. Connecting by that name reaches
|
|
343
|
+
* the LIVE worker (if any) or spawns a fresh one; either way the sequence is: post the declaration, query
|
|
344
|
+
* placement, and — for a `shared-worker` home — send `engine-teardown` and await its reserved ack, which the
|
|
345
|
+
* host posts only after `closeHost()` has stopped the engine and released the backend connection (it then
|
|
346
|
+
* closes its own scope). An `elected-worker` home resolves immediately with `toreDown: false` (see the field).
|
|
347
|
+
*
|
|
348
|
+
* Idempotent and safe on an already-dead store: a fresh spawn boots no engine, and its teardown closes an empty
|
|
349
|
+
* host. Compose it as `await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)` — a
|
|
350
|
+
* quiesce failure (timeout) must NOT abort the destroy, whose own ownership-lag handling reports honestly and
|
|
351
|
+
* leaves the path re-runnable.
|
|
352
|
+
*/
|
|
353
|
+
export function quiesceStoreWorker(
|
|
354
|
+
worker: (() => WorkerLike) | WorkerLike,
|
|
355
|
+
opts?: StoreWorkerQuiesceOptions,
|
|
356
|
+
): Promise<StoreWorkerQuiesceOutcome> {
|
|
357
|
+
const timers: AttachClientTimers = opts?.timers ?? {
|
|
358
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
359
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
360
|
+
};
|
|
361
|
+
const timeoutMs = opts?.timeoutMs ?? 6000;
|
|
362
|
+
const port = resolvePort({ worker });
|
|
363
|
+
return new Promise<StoreWorkerQuiesceOutcome>((resolve, reject) => {
|
|
364
|
+
let settled = false;
|
|
365
|
+
let teardownIdentity: EngineIdentity | undefined;
|
|
366
|
+
const finish = (run: () => void): void => {
|
|
367
|
+
if (settled) return;
|
|
368
|
+
settled = true;
|
|
369
|
+
timers.clearTimeout(timeout);
|
|
370
|
+
port.removeEventListener("message", listener);
|
|
371
|
+
run();
|
|
372
|
+
};
|
|
373
|
+
const timeout = timers.setTimeout(
|
|
374
|
+
() => finish(() => reject(new Error(`[pgxsinkit] quiesceStoreWorker timed out after ${timeoutMs}ms`))),
|
|
375
|
+
timeoutMs,
|
|
376
|
+
);
|
|
377
|
+
const listener = (event: { data: unknown }): void => {
|
|
378
|
+
const placement = readPlacementResult(event.data);
|
|
379
|
+
if (placement !== undefined) {
|
|
380
|
+
if (placement.engineHome !== "shared-worker") {
|
|
381
|
+
finish(() => resolve({ engineHome: placement.engineHome, toreDown: false }));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
// SW-direct: ask the in-scope host to quiesce+close, then await its reserved teardown ack (pingId -1),
|
|
385
|
+
// which proves the engine stopped and the backend connection was released (define-sync-worker).
|
|
386
|
+
teardownIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
|
|
387
|
+
port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity: teardownIdentity }));
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
const refusal = readDeclarationRefusal(event.data);
|
|
391
|
+
if (refusal !== undefined) {
|
|
392
|
+
finish(() => reject(new StorageDeclarationRefusedError(refusal.message)));
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
const control = readControlEnvelope(event.data);
|
|
396
|
+
if (
|
|
397
|
+
control?.type === "control-ack" &&
|
|
398
|
+
control.pingId === -1 &&
|
|
399
|
+
teardownIdentity !== undefined &&
|
|
400
|
+
control.identity?.swInstanceId === teardownIdentity.swInstanceId
|
|
401
|
+
) {
|
|
402
|
+
if (control.error) {
|
|
403
|
+
finish(() => reject(new Error(`[pgxsinkit] store-worker teardown failed: ${control.error?.message}`)));
|
|
404
|
+
} else {
|
|
405
|
+
finish(() => resolve({ engineHome: "shared-worker", toreDown: true }));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
port.addEventListener("message", listener);
|
|
410
|
+
port.start?.();
|
|
411
|
+
// Declaration FIRST (ADR-0050), then the placement query. If the worker's placement is still pending (a
|
|
412
|
+
// fresh spawn), the queued-traffic path redelivers the follow-up teardown after routing (ADR-0050 W1).
|
|
413
|
+
port.postMessage({ [DECLARATION_KEY]: opts?.storage ?? {} });
|
|
414
|
+
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
280
418
|
/** The bounded ownership-retry options for {@link runStoreDestruction} (the VFS-lock-lag guard, D8/fault row). */
|
|
281
419
|
export interface StoreDestructionRetryOptions {
|
|
282
420
|
/** Max retries of `deleteBackendStore` on an ownership-lock-lag error before giving up (default 5). */
|
|
@@ -349,6 +487,15 @@ function readDestroyVerdict(data: unknown): number | undefined {
|
|
|
349
487
|
return typeof peers === "number" ? peers : undefined;
|
|
350
488
|
}
|
|
351
489
|
|
|
490
|
+
/** Narrow a raw storage-declaration refusal (`{ [DECLARATION_REFUSED_KEY]: { message, name } }`), or `undefined`. */
|
|
491
|
+
function readDeclarationRefusal(data: unknown): DeclarationRefusedWire | undefined {
|
|
492
|
+
if (typeof data !== "object" || data === null) return undefined;
|
|
493
|
+
const refusal = (data as { [DECLARATION_REFUSED_KEY]?: unknown })[DECLARATION_REFUSED_KEY];
|
|
494
|
+
if (typeof refusal !== "object" || refusal === null) return undefined;
|
|
495
|
+
const message = (refusal as { message?: unknown }).message;
|
|
496
|
+
return typeof message === "string" ? (refusal as unknown as DeclarationRefusedWire) : undefined;
|
|
497
|
+
}
|
|
498
|
+
|
|
352
499
|
/**
|
|
353
500
|
* The `setTimeout`/`clearTimeout` pair the handoff-queue deadline and the bridge-silence reconnect schedule on
|
|
354
501
|
* (ADR-0049 step 7) — injectable for deterministic tests, exactly the discipline `engine-router.ts` follows so
|
|
@@ -430,11 +577,27 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
430
577
|
* Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.
|
|
431
578
|
* A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred
|
|
432
579
|
* `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.
|
|
433
|
-
* Restore rides the
|
|
434
|
-
*
|
|
435
|
-
*
|
|
580
|
+
* Restore rides the one handshake that reaches the ENGINE HOME: a restore-bearing attach awaits the
|
|
581
|
+
* placement reply, then carries the artifact on the SW-port handshake when the in-scope host is the engine
|
|
582
|
+
* (SW-direct / declared-idbfs) or on the first per-tab PIPE handshake when the engine is elected — the
|
|
583
|
+
* router-only SharedWorker is payload-blind, so a restore posted there would be dropped and destroyed.
|
|
584
|
+
* Passing it when the engine has ALREADY booted rejects the attach with a typed error
|
|
585
|
+
* (`RestoreIntoRunningStoreError` by name — you cannot restore into a running store). The restored engine
|
|
586
|
+
* boots offline and its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on
|
|
587
|
+
* `createSyncClient`.
|
|
436
588
|
*/
|
|
437
589
|
restoreFrom?: File | Blob;
|
|
590
|
+
/**
|
|
591
|
+
* The tab's WIRE storage declaration for this store (ADR-0050) — posted as the declaration message on the
|
|
592
|
+
* worker port BEFORE the placement query (so `backend: "idbfs"` can skip the probe), and carried on the
|
|
593
|
+
* provision/attach payloads so the engine binds it (durability included). Omit (or `{}`) for "no opinion":
|
|
594
|
+
* a registry-attached static declaration, else the capability defaults, decide. A registry-attached
|
|
595
|
+
* declaration is AUTHORITATIVE — an explicit field here that disagrees with it (or with the declaration
|
|
596
|
+
* another tab already bound) is a typed refusal (`StorageDeclarationRefusedError`), never silently
|
|
597
|
+
* overridden: a store's declaration is immutable, and a preference change mints a fresh store under a
|
|
598
|
+
* fresh path instead.
|
|
599
|
+
*/
|
|
600
|
+
storage?: SyncStorageDeclaration;
|
|
438
601
|
codec?: BridgeCodec;
|
|
439
602
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
440
603
|
onConflict?: (details: MutationDetail[]) => void;
|
|
@@ -562,6 +725,9 @@ interface ElectedCoordinatorParams {
|
|
|
562
725
|
/** The SharedWorker reconstruction factory (ADR-0049 D5) — drives the keepalive SW-death recovery. Absent for a
|
|
563
726
|
bare-instance input, where reconstruction is structurally unavailable. */
|
|
564
727
|
swFactory?: () => WorkerLike;
|
|
728
|
+
/** The tab's wire storage declaration (ADR-0050) — posted FIRST on every reconstructed SW port, before the
|
|
729
|
+
coordinator's announce/keepalive traffic, so a fresh bootstrap binds and routes instead of refusing. */
|
|
730
|
+
storage?: SyncStorageDeclaration;
|
|
565
731
|
electionIo?: AttachSyncClientOptions<SyncTableRegistry>["electionIo"];
|
|
566
732
|
awaitOwnershipRelease?: () => Promise<void>;
|
|
567
733
|
timers: AttachClientTimers;
|
|
@@ -606,7 +772,15 @@ function buildElectedCoordinator(params: ElectedCoordinatorParams): ElectionCoor
|
|
|
606
772
|
},
|
|
607
773
|
swPort: params.controlPort as unknown as SwBridgePort,
|
|
608
774
|
...(params.swFactory
|
|
609
|
-
? {
|
|
775
|
+
? {
|
|
776
|
+
reconstructSw: () => {
|
|
777
|
+
const port = resolvePort({ worker: params.swFactory! });
|
|
778
|
+
// ADR-0050: the reconstructed SharedWorker is a fresh bootstrap — declare before the coordinator's
|
|
779
|
+
// announce rides this port, or the bootstrap refuses/queues nothing and recovery hangs.
|
|
780
|
+
port.postMessage({ [DECLARATION_KEY]: params.storage ?? {} });
|
|
781
|
+
return port as unknown as SwBridgePort;
|
|
782
|
+
},
|
|
783
|
+
}
|
|
610
784
|
: {}),
|
|
611
785
|
awaitOwnershipRelease: params.awaitOwnershipRelease ?? resolvedOwnershipRelease,
|
|
612
786
|
timers: params.timers,
|
|
@@ -631,6 +805,8 @@ const sharedCoordinators = new Map<
|
|
|
631
805
|
{
|
|
632
806
|
coordinator: ElectionCoordinator;
|
|
633
807
|
refs: number;
|
|
808
|
+
/** Release the provision claim and cancel its expiry after an explicit construction-identity retirement. */
|
|
809
|
+
releaseProvision?: () => void;
|
|
634
810
|
/**
|
|
635
811
|
* The provision's live engine pipe, held for HANDOVER (ADR-0049 step 8). The router mints exactly ONE proxy
|
|
636
812
|
* pipe per SW connection; when provision and attach share one port (the documented ordered-messages contract,
|
|
@@ -688,6 +864,12 @@ function takeProvisionPipe(storePath: string): { pipe: BridgePort; identity: Eng
|
|
|
688
864
|
return stashed;
|
|
689
865
|
}
|
|
690
866
|
|
|
867
|
+
/** Record the provision claim's explicit release companion on its shared coordinator entry. */
|
|
868
|
+
function setProvisionRelease(storePath: string, release: () => void): void {
|
|
869
|
+
const entry = sharedCoordinators.get(storePath);
|
|
870
|
+
if (entry !== undefined) entry.releaseProvision = release;
|
|
871
|
+
}
|
|
872
|
+
|
|
691
873
|
export async function attachSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
692
874
|
options: AttachSyncClientOptions<TRegistry>,
|
|
693
875
|
): Promise<AttachedSyncClient<TRegistry>> {
|
|
@@ -735,13 +917,27 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
735
917
|
let releaseElectionClaim: (() => void) | undefined;
|
|
736
918
|
let destroyVerdictResolver: ((peers: number) => void) | undefined;
|
|
737
919
|
let placementResult: PlacementQueryResult | undefined;
|
|
738
|
-
let swTeardownAckResolver: ((error?:
|
|
920
|
+
let swTeardownAckResolver: ((error?: BridgeErrorWire) => void) | undefined;
|
|
739
921
|
let swTeardownIdentity: EngineIdentity | undefined;
|
|
740
922
|
// Set to the store path when this attach ADOPTED a shared (provision-registered) coordinator — so detach
|
|
741
923
|
// releases the shared ref (ref-counted registry cleanup). Undefined when this tab built its own coordinator.
|
|
742
924
|
let adoptedSharedCoordinatorStore: string | undefined;
|
|
743
925
|
// The placement decision is single-shot: once we act on the first `electionRequired` reply we ignore any repeat.
|
|
744
926
|
let placementDecided = false;
|
|
927
|
+
// Settles when the FIRST placement reply arrives (the bootstrap meta listener answers the query in BOTH SW
|
|
928
|
+
// modes) — or REJECTS typed when the worker refuses this tab's storage declaration (ADR-0050), which arrives
|
|
929
|
+
// in place of the placement reply. Every boot awaits it before the first handshake — see the send site.
|
|
930
|
+
let resolvePlacementKnown: (() => void) | undefined;
|
|
931
|
+
let rejectPlacementKnown: ((error: Error) => void) | undefined;
|
|
932
|
+
const placementKnown = new Promise<void>((resolve, reject) => {
|
|
933
|
+
resolvePlacementKnown = resolve;
|
|
934
|
+
rejectPlacementKnown = reject;
|
|
935
|
+
});
|
|
936
|
+
// A refusal may land after a detach already settled the boot path — never an unhandled rejection.
|
|
937
|
+
void placementKnown.catch(() => undefined);
|
|
938
|
+
// The restore artifact rides EXACTLY ONE handshake — its ArrayBuffer detaches on first post, so a resend
|
|
939
|
+
// would carry an empty buffer. Set the moment a handshake actually carries it (see `runAttachHandshake`).
|
|
940
|
+
let restoreConsumed = false;
|
|
745
941
|
|
|
746
942
|
// ─── ADR-0049 first-attach gate (placement-query-FIRST ordering — elected-mode ack routing) ───────
|
|
747
943
|
// `attachSyncClient` no longer gates on the SW-port attach ack: a router-only SharedWorker (elected-worker home)
|
|
@@ -1019,6 +1215,16 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1019
1215
|
onPlacementResult(placementResult);
|
|
1020
1216
|
return;
|
|
1021
1217
|
}
|
|
1218
|
+
// ADR-0050: the worker refused this tab's storage declaration (explicit conflict with the bound/static
|
|
1219
|
+
// declaration, or engine-bound traffic before the declaration). It arrives IN PLACE of the placement
|
|
1220
|
+
// reply, so fail the boot typed and loudly — never a hang, never a silently different storage mode.
|
|
1221
|
+
const declarationRefusal = readDeclarationRefusal(event.data);
|
|
1222
|
+
if (declarationRefusal !== undefined) {
|
|
1223
|
+
const refusal = new StorageDeclarationRefusedError(declarationRefusal.message);
|
|
1224
|
+
rejectPlacementKnown?.(refusal);
|
|
1225
|
+
failFirstAttach(refusal);
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1022
1228
|
const destroyPeers = readDestroyVerdict(event.data);
|
|
1023
1229
|
if (destroyPeers !== undefined) {
|
|
1024
1230
|
destroyVerdictResolver?.(destroyPeers);
|
|
@@ -1164,7 +1370,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1164
1370
|
swapDataPort(pipe, replacing);
|
|
1165
1371
|
hasPipe = true;
|
|
1166
1372
|
try {
|
|
1167
|
-
|
|
1373
|
+
// `includeRestore: true` — in elected mode THIS is the engine's boot attach, so the restore artifact
|
|
1374
|
+
// (withheld from the router-dropped SW-port handshake) rides here, over the direct tab↔engine pipe.
|
|
1375
|
+
// The `restoreConsumed` guard makes it first-carry-only: a pipe REPLACEMENT re-attach never re-sends.
|
|
1376
|
+
await runAttachHandshake(pipe, true);
|
|
1168
1377
|
} catch {
|
|
1169
1378
|
// A failed re-attach leaves the window open; a later notice / connect-port can retry. Never auto-retried.
|
|
1170
1379
|
return;
|
|
@@ -1216,6 +1425,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1216
1425
|
newPort.addEventListener("message", listener);
|
|
1217
1426
|
newPort.addEventListener("message", controlListener);
|
|
1218
1427
|
newPort.start?.();
|
|
1428
|
+
// ADR-0050: the reconstructed SharedWorker may be a FRESH bootstrap whose placement is still pending —
|
|
1429
|
+
// every port must declare before any engine-bound message. The declaration precedes the attach on the same
|
|
1430
|
+
// port, and the bootstrap queues the attach until placement resolves (no placement round-trip needed here).
|
|
1431
|
+
newPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
1219
1432
|
try {
|
|
1220
1433
|
await runAttachHandshake(newPort, false);
|
|
1221
1434
|
} catch {
|
|
@@ -1248,6 +1461,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1248
1461
|
if (detached || placementDecided) return;
|
|
1249
1462
|
placementDecided = true;
|
|
1250
1463
|
placementResult = result;
|
|
1464
|
+
resolvePlacementKnown?.();
|
|
1251
1465
|
// SW-direct / declared-idbfs (or a non-placement transport that never replies): the SW-port attach ack gates the flow.
|
|
1252
1466
|
if (!result.electionRequired) return;
|
|
1253
1467
|
// Elected-worker (router-only): resolve the engine factory. Auto-derivation from the reported script URL is the
|
|
@@ -1337,6 +1551,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1337
1551
|
controlPort,
|
|
1338
1552
|
createEngineWorker: electedEngineFactory!,
|
|
1339
1553
|
...(workerFactory ? { swFactory: workerFactory } : {}),
|
|
1554
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
1340
1555
|
...(options.electionIo ? { electionIo: options.electionIo } : {}),
|
|
1341
1556
|
...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
|
|
1342
1557
|
timers,
|
|
@@ -1428,14 +1643,19 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1428
1643
|
let pendingAttachAck: { resolve: (ack: AttachAckPayload) => void; reject: (error: Error) => void } | null = null;
|
|
1429
1644
|
const runAttachHandshake = (target: BridgePort, includeRestore: boolean): Promise<AttachAckPayload> =>
|
|
1430
1645
|
new Promise<AttachAckPayload>((resolve, reject) => {
|
|
1646
|
+
// The restore artifact rides at most ONE handshake ever (`restoreConsumed`): posting transfers (detaches)
|
|
1647
|
+
// its ArrayBuffer, so any later handshake would carry an empty husk. The caller chooses the target that
|
|
1648
|
+
// actually reaches the engine home; this guard makes a second carry structurally impossible.
|
|
1649
|
+
const carryRestore = includeRestore && restoreWire !== undefined && !restoreConsumed;
|
|
1650
|
+
if (carryRestore) restoreConsumed = true;
|
|
1431
1651
|
pendingAttachAck = { resolve, reject };
|
|
1432
1652
|
postBridgeMessage(
|
|
1433
1653
|
target,
|
|
1434
1654
|
codec,
|
|
1435
1655
|
"attach",
|
|
1436
|
-
buildAttachPayload(
|
|
1656
|
+
buildAttachPayload(carryRestore),
|
|
1437
1657
|
undefined,
|
|
1438
|
-
|
|
1658
|
+
carryRestore && restoreWire ? [restoreWire.buffer] : undefined,
|
|
1439
1659
|
);
|
|
1440
1660
|
});
|
|
1441
1661
|
|
|
@@ -1619,13 +1839,17 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1619
1839
|
}
|
|
1620
1840
|
: undefined;
|
|
1621
1841
|
// The attach payload builder — reused by the FIRST attach and every re-attach (pipe swap / reconnect). Restore
|
|
1622
|
-
// rides ONLY the
|
|
1623
|
-
//
|
|
1842
|
+
// rides ONLY the one handshake that reaches the engine home (SW port in SW-direct, first pipe attach when
|
|
1843
|
+
// elected — see the send sites); `runAttachHandshake`'s `restoreConsumed` guard makes any later carry
|
|
1844
|
+
// structurally impossible (the buffer is transferred/detached, and you cannot restore into a running store).
|
|
1624
1845
|
function buildAttachPayload(includeRestore: boolean): AttachPayload {
|
|
1625
1846
|
return {
|
|
1626
1847
|
token: initialToken,
|
|
1627
1848
|
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
1628
1849
|
...(options.storePath ? { storePath: options.storePath } : {}),
|
|
1850
|
+
// ADR-0050: the wire storage declaration also rides the attach payload, so the ENGINE binds it
|
|
1851
|
+
// (durability included) wherever it runs — the pre-placement declaration message only steers placement.
|
|
1852
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
1629
1853
|
...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
|
|
1630
1854
|
...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
|
|
1631
1855
|
...(includeRestore && restoreWire ? { restore: restoreWire } : {}),
|
|
@@ -1640,19 +1864,46 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1640
1864
|
: {}),
|
|
1641
1865
|
};
|
|
1642
1866
|
}
|
|
1643
|
-
// ─── ADR-
|
|
1644
|
-
// Post the
|
|
1645
|
-
//
|
|
1646
|
-
//
|
|
1647
|
-
//
|
|
1648
|
-
// `
|
|
1867
|
+
// ─── ADR-0050 declaration-FIRST, then placement-query, then handshake ─────────────────────────────
|
|
1868
|
+
// Post the storage DECLARATION MESSAGE first — always, even empty (`{}` = "no opinion") — because a
|
|
1869
|
+
// registry-silent worker DEFERS its placement decision until the first declaration arrives (`backend:
|
|
1870
|
+
// "idbfs"` must skip the probe, so the declaration must precede the decision). Then the placement query
|
|
1871
|
+
// (ADR-0049): a router-only SharedWorker (elected-worker home) is payload-blind and DROPS the bridge
|
|
1872
|
+
// `attach`, so an SW-port ack could never gate the flow — but the bootstrap meta listener answers the
|
|
1873
|
+
// placement query in BOTH SW modes, so this reliably drives election. In SW-direct / declared-idbfs (and
|
|
1874
|
+
// the no-placement / plain-port case) the reply is `electionRequired: false` (or absent) and the SW-port
|
|
1875
|
+
// attach below acks normally — a plain in-scope host attach.
|
|
1876
|
+
controlPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
1649
1877
|
controlPort.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
1650
|
-
//
|
|
1651
|
-
//
|
|
1652
|
-
//
|
|
1653
|
-
//
|
|
1654
|
-
//
|
|
1655
|
-
|
|
1878
|
+
// EVERY boot awaits the placement reply before the first handshake (ADR-0050). The worker only installs the
|
|
1879
|
+
// engine listener on this port once placement resolves and the port's declaration is accepted, so an attach
|
|
1880
|
+
// posted earlier would be refused as a protocol violation — and the reply's slot is also where a storage
|
|
1881
|
+
// DECLARATION REFUSAL arrives (typed boot failure instead of a reply). This costs no real latency: the old
|
|
1882
|
+
// fire-and-forget attach queued browser-side behind the very same placement decision. Restore-bearing boots
|
|
1883
|
+
// additionally depend on this ordering for artifact routing: the restore's ArrayBuffer detaches on first
|
|
1884
|
+
// post, and in elected mode the router-only SharedWorker silently DROPS bridge `attach` envelopes — so the
|
|
1885
|
+
// restore is carried on the SW-port handshake only when the in-scope host IS the engine (SW-direct /
|
|
1886
|
+
// declared-idbfs), and on the first per-tab PIPE handshake (`onConnectPort`) when the engine is elected.
|
|
1887
|
+
try {
|
|
1888
|
+
await placementKnown;
|
|
1889
|
+
} catch (error) {
|
|
1890
|
+
// A typed declaration refusal (never a plain transport error): run the full detach so both listeners and
|
|
1891
|
+
// the pagehide handler are removed, then propagate — the boot fails loudly with the refusal.
|
|
1892
|
+
detachFromWorker();
|
|
1893
|
+
throw error;
|
|
1894
|
+
}
|
|
1895
|
+
// Send the tab's attach handshake — placement is KNOWN here (awaited above). SW-direct / plain / no-reply:
|
|
1896
|
+
// the current data port reaches the in-scope engine, which acks it (restore included). Elected
|
|
1897
|
+
// (`electionRequired`): the engine-reaching handshake is the per-tab PIPE one (`onConnectPort`, or the
|
|
1898
|
+
// adoption handover of a stashed provision pipe); the SW-port post below is the router-dropped
|
|
1899
|
+
// fire-and-forget (payload-blind — never taught to answer bridge envelopes), kept so `firstAttachReady` can
|
|
1900
|
+
// settle off whichever port answers first. The ONE case that must not post is elected mode with the data
|
|
1901
|
+
// path ALREADY swapped onto an adopted pipe — there the post would reach the live engine as a DUPLICATE
|
|
1902
|
+
// attach (a second boot) instead of being dropped.
|
|
1903
|
+
const handshakePort = currentDataPort();
|
|
1904
|
+
if (placementResult?.electionRequired !== true || handshakePort === controlPort) {
|
|
1905
|
+
void runAttachHandshake(handshakePort, placementResult?.electionRequired !== true).catch(() => undefined);
|
|
1906
|
+
}
|
|
1656
1907
|
try {
|
|
1657
1908
|
await firstAttachReady;
|
|
1658
1909
|
} catch (error) {
|
|
@@ -1840,6 +2091,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1840
2091
|
start: async () => {
|
|
1841
2092
|
await ready;
|
|
1842
2093
|
},
|
|
2094
|
+
// The tab facade holds no local engine — its "activity" is the worker bridge. Synchronously detaching it
|
|
2095
|
+
// (idempotent, no await) IS the tab-side halt: it stops posting/subscribing on the pipe and settles every
|
|
2096
|
+
// pending promise, the analogue of aborting the in-process engine's streams. `stop()` does the same.
|
|
2097
|
+
haltActivity: () => {
|
|
2098
|
+
detachFromWorker();
|
|
2099
|
+
},
|
|
1843
2100
|
stop: async () => {
|
|
1844
2101
|
detachFromWorker();
|
|
1845
2102
|
},
|
|
@@ -2084,6 +2341,7 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2084
2341
|
| "port"
|
|
2085
2342
|
| "storeId"
|
|
2086
2343
|
| "storePath"
|
|
2344
|
+
| "storage"
|
|
2087
2345
|
| "codec"
|
|
2088
2346
|
| "createEngineWorker"
|
|
2089
2347
|
| "electionIo"
|
|
@@ -2099,105 +2357,6 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2099
2357
|
provisionExpiryMs?: number;
|
|
2100
2358
|
};
|
|
2101
2359
|
|
|
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
2360
|
/**
|
|
2202
2361
|
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
|
|
2203
2362
|
* freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the raw store idle
|
|
@@ -2229,11 +2388,14 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2229
2388
|
const provisionPayload = {
|
|
2230
2389
|
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
2231
2390
|
...(options.storePath ? { storePath: options.storePath } : {}),
|
|
2391
|
+
// ADR-0050: the wire storage declaration rides the provision payload too, so the mint's durability comes
|
|
2392
|
+
// from the store's bound declaration wherever the engine runs.
|
|
2393
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
2232
2394
|
...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
|
|
2233
2395
|
};
|
|
2234
2396
|
const pageLifecycle = readDefaultPageLifecycle();
|
|
2235
2397
|
|
|
2236
|
-
|
|
2398
|
+
const provision = new Promise<void>((resolve, reject) => {
|
|
2237
2399
|
let settled = false;
|
|
2238
2400
|
const ackRemovers: Array<() => void> = [];
|
|
2239
2401
|
const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }): void => {
|
|
@@ -2242,6 +2404,13 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2242
2404
|
onPlacement(placement);
|
|
2243
2405
|
return;
|
|
2244
2406
|
}
|
|
2407
|
+
// ADR-0050: the worker refused this provision's storage declaration — it arrives in place of the
|
|
2408
|
+
// placement reply, so the provision fails typed and loudly (never a hang, never a silent mode).
|
|
2409
|
+
const declarationRefusal = readDeclarationRefusal(event.data);
|
|
2410
|
+
if (declarationRefusal !== undefined) {
|
|
2411
|
+
settle(() => reject(new StorageDeclarationRefusedError(declarationRefusal.message)));
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2245
2414
|
const control = readControlEnvelope(event.data);
|
|
2246
2415
|
if (control?.type === "connect-port") onProvisionPipe(event.ports?.[0], control.identity);
|
|
2247
2416
|
};
|
|
@@ -2286,8 +2455,13 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2286
2455
|
const onPlacement = (result: PlacementQueryResult): void => {
|
|
2287
2456
|
if (placementDecided) return;
|
|
2288
2457
|
placementDecided = true;
|
|
2289
|
-
// SW-direct (or a
|
|
2290
|
-
|
|
2458
|
+
// SW-direct (or a plain host, which answers the placement query itself): the worker installs the engine
|
|
2459
|
+
// listener on this port only once placement resolves and the declaration is accepted (ADR-0050), so the
|
|
2460
|
+
// `provision` is posted NOW — on the reply — never fire-and-forget before it.
|
|
2461
|
+
if (!result.electionRequired) {
|
|
2462
|
+
postProvisionOn(port);
|
|
2463
|
+
return;
|
|
2464
|
+
}
|
|
2291
2465
|
// Elected (router-only): the SW drops the `provision` bridge envelope, so ELECT and provision over the pipe.
|
|
2292
2466
|
// Resolve the engine factory exactly as attach does — the `createEngineWorker` override, else the default
|
|
2293
2467
|
// derived from the SharedWorker's reported script URL (dual-scope entry). Neither available → a WIRING failure.
|
|
@@ -2311,6 +2485,7 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2311
2485
|
controlPort: port,
|
|
2312
2486
|
createEngineWorker: engineFactory,
|
|
2313
2487
|
...(provisionSwFactory ? { swFactory: provisionSwFactory } : {}),
|
|
2488
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
2314
2489
|
...(options.electionIo ? { electionIo: options.electionIo } : {}),
|
|
2315
2490
|
...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
|
|
2316
2491
|
timers,
|
|
@@ -2322,20 +2497,34 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2322
2497
|
// AND its shared-coordinator ref release together), so a store nobody adopts never pins the leader lock.
|
|
2323
2498
|
const releaseProvisionClaim = coordinator.claimForProvision();
|
|
2324
2499
|
const expiryMs = options.provisionExpiryMs ?? 60_000;
|
|
2325
|
-
|
|
2500
|
+
let released = false;
|
|
2501
|
+
const expiryHandle = timers.setTimeout(() => {
|
|
2502
|
+
if (released) return;
|
|
2503
|
+
released = true;
|
|
2504
|
+
const entry = sharedCoordinators.get(storePath);
|
|
2505
|
+
if (entry?.releaseProvision === releaseProvision) delete entry.releaseProvision;
|
|
2326
2506
|
releaseProvisionClaim();
|
|
2327
2507
|
releaseSharedCoordinator(storePath);
|
|
2328
2508
|
}, expiryMs);
|
|
2509
|
+
const releaseProvision = (): void => {
|
|
2510
|
+
if (released) return;
|
|
2511
|
+
released = true;
|
|
2512
|
+
timers.clearTimeout(expiryHandle);
|
|
2513
|
+
releaseProvisionClaim();
|
|
2514
|
+
};
|
|
2515
|
+
setProvisionRelease(storePath, releaseProvision);
|
|
2329
2516
|
};
|
|
2330
2517
|
|
|
2331
2518
|
port.addEventListener("message", controlListener);
|
|
2332
2519
|
port.start?.();
|
|
2333
|
-
//
|
|
2334
|
-
//
|
|
2335
|
-
//
|
|
2520
|
+
// Declaration-FIRST, then placement query (ADR-0050, mirroring attach): the declaration message unblocks a
|
|
2521
|
+
// registry-silent worker's deferred placement decision, and the query is answered in BOTH SW modes by the
|
|
2522
|
+
// bootstrap meta listener. The `provision` itself is posted ON the placement reply (`onPlacement`): SW-direct
|
|
2523
|
+
// takes it on this port; a router-only SW would drop it, so elected mode delivers it over the pipe instead.
|
|
2524
|
+
port.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
|
|
2336
2525
|
port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
|
|
2337
|
-
postProvisionOn(port);
|
|
2338
2526
|
});
|
|
2527
|
+
return provision;
|
|
2339
2528
|
}
|
|
2340
2529
|
|
|
2341
2530
|
/** Resolve the default page-lifecycle subscription off `globalThis.window` (structural, no DOM lib) — for the
|
|
@@ -2392,13 +2581,20 @@ function deriveEngineWorkerFactory(swScriptUrl: string | undefined): (() => Elec
|
|
|
2392
2581
|
return () => wrapEngineWorker(new WorkerCtor(swScriptUrl, { type: "module" }));
|
|
2393
2582
|
}
|
|
2394
2583
|
|
|
2395
|
-
/**
|
|
2584
|
+
/**
|
|
2585
|
+
* Rebuild an Error from the bridge's serialized {@link BridgeErrorWire} shape, carrying `name` and `detail`
|
|
2586
|
+
* through. Restoring `name` is what keeps a typed worker-side failure (e.g. a restore refused with
|
|
2587
|
+
* `RestoreTargetExistsError`) detectable by the consumer without message matching.
|
|
2588
|
+
*/
|
|
2396
2589
|
function rebuildError(error: RpcResultPayload["error"]): Error {
|
|
2397
2590
|
if (error && "detail" in error) {
|
|
2398
2591
|
const mismatch = executionLimitMismatchFromWire(error.detail);
|
|
2399
2592
|
if (mismatch !== undefined) return mismatch;
|
|
2400
2593
|
}
|
|
2401
2594
|
const rebuilt = new Error(error?.message ?? "worker rpc failed");
|
|
2595
|
+
if (error?.name !== undefined) {
|
|
2596
|
+
rebuilt.name = error.name;
|
|
2597
|
+
}
|
|
2402
2598
|
if (error && "detail" in error && error.detail !== undefined) {
|
|
2403
2599
|
(rebuilt as Error & { detail?: unknown }).detail = error.detail;
|
|
2404
2600
|
}
|