@pgxsinkit/client 0.1.51 → 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/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.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 +309 -38
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4628 -1489
- package/dist/index.js.map +36 -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 +10 -4
- package/dist/local-tables.d.ts.map +1 -1
- 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 +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.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 +239 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +162 -5
- 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/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +32 -11
- 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 -8
- package/skills/operating/SKILL.md +114 -34
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1246 -118
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +9 -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 +227 -89
- package/src/sync/index.ts +33 -9
- 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 +1675 -117
- package/src/worker/define-sync-worker.ts +810 -50
- 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 +10 -1
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +41 -10
- package/src/worker/sw-placement.ts +64 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// The ROUTER (ADR-0049 step 6): the SharedWorker-side placement machinery — the "communication centre"
|
|
2
|
+
// (CONTEXT.md § "Language — engine placement"). This module runs INSIDE the SharedWorker and is the single
|
|
3
|
+
// role that never moves whatever the engine's home is. It owns exactly four things:
|
|
4
|
+
// - the ATTACH REGISTRY (every tab's bridge port),
|
|
5
|
+
// - the CURRENT engine identity + the engine CONTROL CHANNEL,
|
|
6
|
+
// - relocation-notice FAN-OUT to every tab, and
|
|
7
|
+
// - execution-limit PROBE FORWARDING (tab-reported overdue dispatch → control-channel pings → verdict).
|
|
8
|
+
//
|
|
9
|
+
// It deliberately does NOT: spawn workers, decide leadership, or ever inspect RPC payloads. Per attached tab
|
|
10
|
+
// it mints a proxy pipe and TRANSFERS one end to the engine and the other to the tab; from then on that tab's
|
|
11
|
+
// RPC/live-query traffic flows tab↔engine DIRECTLY on the pipe (invariant 6 — the SharedWorker is not in the
|
|
12
|
+
// data path). Because it is transport-agnostic (a `RouterPort`, never a real `SharedWorker`/`Worker`), the
|
|
13
|
+
// whole thing is unit-testable over hand-rolled recording ports with no worker at all — the same discipline
|
|
14
|
+
// `protocol.ts` and `engine-control.ts` follow.
|
|
15
|
+
//
|
|
16
|
+
// WIRE ENVELOPE. The control plane shares the same tab↔SharedWorker transport as today's data-path bridge
|
|
17
|
+
// (`protocol.ts`). To coexist WITHOUT touching `protocol.ts`, every control message travels inside a
|
|
18
|
+
// NAMESPACED envelope `{ [ENGINE_CONTROL_ENVELOPE_KEY]: <EngineControlMessage> }` (`pgx0049`). A bridge
|
|
19
|
+
// envelope (`{ ch: "pgxsinkit-bridge", … }`) has no such key and is ignored here; a control envelope has no
|
|
20
|
+
// `ch`/`v` and is ignored by the bridge router. Step 7's attach client speaks this SAME envelope.
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
mintEngineIdentity,
|
|
24
|
+
readControlEnvelope,
|
|
25
|
+
shouldApplyControlMessage,
|
|
26
|
+
type EngineControlMessage,
|
|
27
|
+
type EngineIdentity,
|
|
28
|
+
type ExecutionLimitConfig,
|
|
29
|
+
wrapControlEnvelope as envelope,
|
|
30
|
+
} from "./engine-control";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The namespaced key under which every ADR-0049 control message rides the tab↔SharedWorker transport, so the
|
|
34
|
+
* control plane coexists with the data-path bridge envelope (`protocol.ts`) without any change to it. The tab
|
|
35
|
+
* side (step 7) sends/reads the identical envelope.
|
|
36
|
+
*/
|
|
37
|
+
export { ENGINE_CONTROL_ENVELOPE_KEY } from "./engine-control";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The minimal MessagePort-shaped transport the router needs — the intersection of a real `MessagePort`, a
|
|
41
|
+
* `SharedWorker` connection port, and the pipe ends it mints. Modeled on `protocol.ts`'s `BridgePort` (kept
|
|
42
|
+
* local, not imported, because the router's transfer list is plain `unknown[]` and it never `close()`s a tab
|
|
43
|
+
* port). Injected everywhere so the router is exercised with plain recording ports (no worker) in tests.
|
|
44
|
+
*/
|
|
45
|
+
export interface RouterPort {
|
|
46
|
+
postMessage: (message: unknown, transfer?: unknown[]) => void;
|
|
47
|
+
addEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
48
|
+
removeEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
49
|
+
start?: () => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The setTimeout/clearTimeout pair the probe loop schedules on — injectable for deterministic tests. */
|
|
53
|
+
export interface RouterTimers {
|
|
54
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
55
|
+
clearTimeout(handle: unknown): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface EngineRouterOptions {
|
|
59
|
+
/** The opaque id of THIS SharedWorker instance — scopes every minted {@link EngineIdentity}'s generation. */
|
|
60
|
+
swInstanceId: string;
|
|
61
|
+
/**
|
|
62
|
+
* Engine-construction execution limit (`undefined`/absent `maxDispatchMs` = DISABLED, ADR D5). The router
|
|
63
|
+
* only FORWARDS tab-reported overdue dispatches into control-channel probes when enabled; the verdict
|
|
64
|
+
* threshold is {@link probeMissThreshold}. Disabled → overdue reports are ignored entirely.
|
|
65
|
+
*/
|
|
66
|
+
executionLimit?: ExecutionLimitConfig;
|
|
67
|
+
/** Consecutive unanswered probe pings before an engine-loss verdict (default 3). */
|
|
68
|
+
probeMissThreshold?: number;
|
|
69
|
+
/** Injectable pipe factory (default `() => new MessageChannel()`) so tests can observe both minted ends. */
|
|
70
|
+
createPipe?: () => { port1: RouterPort; port2: RouterPort };
|
|
71
|
+
/** Injectable timers for probe scheduling (default `globalThis`) for deterministic tests. */
|
|
72
|
+
timers?: RouterTimers;
|
|
73
|
+
/** Milliseconds between probe pings once a dispatch is reported overdue (default 2000). */
|
|
74
|
+
probeIntervalMs?: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface EngineRouter {
|
|
78
|
+
/**
|
|
79
|
+
* Register a tab's bridge port. Returns an unregister fn. If an engine is CURRENT and already ready, this
|
|
80
|
+
* late joiner is piped IMMEDIATELY; otherwise it is piped when the current engine's `engine-ready` fans out.
|
|
81
|
+
*/
|
|
82
|
+
attachTab(tabPort: RouterPort): () => void;
|
|
83
|
+
/**
|
|
84
|
+
* tab→SW: the leader coordinator announces a fresh engine control channel. Stamps the next
|
|
85
|
+
* {@link EngineIdentity} ({@link mintEngineIdentity}), stores the control channel, and returns the identity.
|
|
86
|
+
* On the engine's `engine-ready` for THIS identity it pipes every attached tab. Any prior engine's control
|
|
87
|
+
* listener/probe is cleared first (this does not itself fan a notice).
|
|
88
|
+
*/
|
|
89
|
+
announceEngine(controlPort: RouterPort): EngineIdentity;
|
|
90
|
+
/**
|
|
91
|
+
* Fan a relocation notice to every tab: `leader-granted` (untagged) or `engine-retiring` (tagged with the
|
|
92
|
+
* retired identity). BOTH clear the current identity + control channel. Engine-loss verdicts fan
|
|
93
|
+
* `engine-retiring` internally the same way.
|
|
94
|
+
*/
|
|
95
|
+
openHandoff(reason: "leader-granted" | "engine-retiring"): void;
|
|
96
|
+
/** The current identity, or `undefined` before the first announce / while relocating. */
|
|
97
|
+
currentIdentity(): EngineIdentity | undefined;
|
|
98
|
+
/** Total attached-tab count (used later for destroy peer-refusal). */
|
|
99
|
+
tabCount(): number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface TabEntry {
|
|
103
|
+
port: RouterPort;
|
|
104
|
+
listener: (event: { data: unknown }) => void;
|
|
105
|
+
/** A `close`-event listener, present only where the platform supports the MessagePort `close` event (D8). */
|
|
106
|
+
closeListener?: () => void;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The optional MessagePort `close`-event surface — feature-detected, not part of the structural {@link RouterPort}. */
|
|
110
|
+
interface ClosableRouterPort {
|
|
111
|
+
onclose?: unknown;
|
|
112
|
+
addEventListener: (type: "close", listener: () => void) => void;
|
|
113
|
+
removeEventListener?: (type: "close", listener: () => void) => void;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
|
|
117
|
+
const { swInstanceId, executionLimit } = options;
|
|
118
|
+
const probeMissThreshold = options.probeMissThreshold ?? 3;
|
|
119
|
+
const probeIntervalMs = options.probeIntervalMs ?? 2000;
|
|
120
|
+
const createPipe =
|
|
121
|
+
options.createPipe ?? (() => new MessageChannel() as unknown as { port1: RouterPort; port2: RouterPort });
|
|
122
|
+
const timers: RouterTimers = options.timers ?? {
|
|
123
|
+
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
|
|
124
|
+
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const tabs = new Set<TabEntry>();
|
|
128
|
+
|
|
129
|
+
// Current engine state. `lastMinted` survives a handoff (unlike `currentIdentity`) so the next announce mints
|
|
130
|
+
// the SUCCESSOR generation (gen+1) under this SharedWorker instance, per mintEngineIdentity's contract.
|
|
131
|
+
let currentIdentity: EngineIdentity | undefined;
|
|
132
|
+
let lastMinted: EngineIdentity | undefined;
|
|
133
|
+
let controlPort: RouterPort | undefined;
|
|
134
|
+
let controlListener: ((event: { data: unknown }) => void) | undefined;
|
|
135
|
+
let engineReady = false;
|
|
136
|
+
|
|
137
|
+
// Execution-limit probe loop (one timer at a time; the whole loop keys on `currentIdentity`).
|
|
138
|
+
let probeRunning = false;
|
|
139
|
+
let probeHandle: unknown;
|
|
140
|
+
let missCount = 0;
|
|
141
|
+
let pingSeq = 0;
|
|
142
|
+
let pendingPingId: number | undefined;
|
|
143
|
+
|
|
144
|
+
function fanToTabs(message: EngineControlMessage): void {
|
|
145
|
+
for (const tab of tabs) {
|
|
146
|
+
tab.port.postMessage(envelope(message));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Mint a fresh proxy pipe: engine end → the control channel, tab end → the tab (both TRANSFERRED). */
|
|
151
|
+
function deliverPipe(tab: TabEntry): void {
|
|
152
|
+
if (currentIdentity === undefined || controlPort === undefined) return;
|
|
153
|
+
const { port1, port2 } = createPipe();
|
|
154
|
+
controlPort.postMessage(envelope({ type: "connect-port", identity: currentIdentity }), [port1]);
|
|
155
|
+
tab.port.postMessage(envelope({ type: "connect-port", identity: currentIdentity }), [port2]);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function resetProbe(): void {
|
|
159
|
+
probeRunning = false;
|
|
160
|
+
missCount = 0;
|
|
161
|
+
pendingPingId = undefined;
|
|
162
|
+
if (probeHandle !== undefined) {
|
|
163
|
+
timers.clearTimeout(probeHandle);
|
|
164
|
+
probeHandle = undefined;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Detach the engine control channel + probe state WITHOUT fanning any notice (used by announce/handoff). */
|
|
169
|
+
function clearEngine(): void {
|
|
170
|
+
resetProbe();
|
|
171
|
+
if (controlPort !== undefined && controlListener !== undefined) {
|
|
172
|
+
controlPort.removeEventListener("message", controlListener);
|
|
173
|
+
}
|
|
174
|
+
controlPort = undefined;
|
|
175
|
+
controlListener = undefined;
|
|
176
|
+
currentIdentity = undefined;
|
|
177
|
+
engineReady = false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The engine-loss path: capture the retiring identity, tear down, and fan `engine-retiring` to every tab. */
|
|
181
|
+
function retireCurrentEngine(): void {
|
|
182
|
+
const retiring = currentIdentity;
|
|
183
|
+
clearEngine();
|
|
184
|
+
if (retiring !== undefined) {
|
|
185
|
+
fanToTabs({ type: "engine-retiring", identity: retiring });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function scheduleProbe(): void {
|
|
190
|
+
probeHandle = timers.setTimeout(() => {
|
|
191
|
+
probeHandle = undefined;
|
|
192
|
+
// The engine went away between ticks (handoff/verdict) — abandon the loop silently.
|
|
193
|
+
if (currentIdentity === undefined || controlPort === undefined) {
|
|
194
|
+
resetProbe();
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const pingId = ++pingSeq;
|
|
198
|
+
pendingPingId = pingId;
|
|
199
|
+
controlPort.postMessage(envelope({ type: "control-ping", identity: currentIdentity, pingId }));
|
|
200
|
+
missCount += 1;
|
|
201
|
+
if (missCount >= probeMissThreshold) {
|
|
202
|
+
// Threshold consecutive unanswered pings → ENGINE-LOSS VERDICT (the router never terminates anything;
|
|
203
|
+
// the leader coordinator reacts to the fanned `engine-retiring`).
|
|
204
|
+
resetProbe();
|
|
205
|
+
retireCurrentEngine();
|
|
206
|
+
} else {
|
|
207
|
+
scheduleProbe();
|
|
208
|
+
}
|
|
209
|
+
}, probeIntervalMs);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function startProbe(): void {
|
|
213
|
+
if (probeRunning) return;
|
|
214
|
+
probeRunning = true;
|
|
215
|
+
missCount = 0;
|
|
216
|
+
scheduleProbe();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ─── Engine control-channel inbound ──────────────────────────────────────────
|
|
220
|
+
function onControlMessage(data: unknown): void {
|
|
221
|
+
const message = readControlEnvelope(data);
|
|
222
|
+
if (message === undefined) return;
|
|
223
|
+
switch (message.type) {
|
|
224
|
+
case "engine-ready":
|
|
225
|
+
// Gate on the exact identity pair — a stale engine-ready from a superseded generation is discarded.
|
|
226
|
+
if (shouldApplyControlMessage(currentIdentity, message)) {
|
|
227
|
+
engineReady = true;
|
|
228
|
+
for (const tab of tabs) deliverPipe(tab);
|
|
229
|
+
}
|
|
230
|
+
return;
|
|
231
|
+
case "control-ack":
|
|
232
|
+
// A live-but-slow engine answered the PROBE: reset the miss count and STOP the loop (below-threshold
|
|
233
|
+
// probing is never a verdict). Only the pending ping's id for the current identity counts — that ack
|
|
234
|
+
// is CONSUMED here (never fanned to tabs).
|
|
235
|
+
if (shouldApplyControlMessage(currentIdentity, message) && message.pingId === pendingPingId) {
|
|
236
|
+
resetProbe();
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
// Any OTHER engine ack (pingId mismatch or no probe loop running) is the engine's teardown ack
|
|
240
|
+
// (`pingId: -1`, ADR-0049 step 9) — relay it VERBATIM to every tab so the coordinator's identity-matched
|
|
241
|
+
// teardown wait settles. The router never inspects it beyond forwarding.
|
|
242
|
+
fanToTabs(message);
|
|
243
|
+
return;
|
|
244
|
+
default:
|
|
245
|
+
// The engine control channel emits nothing else the router acts on here.
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ─── Tab bridge-port inbound ──────────────────────────────────────────────────
|
|
251
|
+
function onTabMessage(tab: TabEntry, data: unknown): void {
|
|
252
|
+
const message = readControlEnvelope(data);
|
|
253
|
+
if (message === undefined) return;
|
|
254
|
+
switch (message.type) {
|
|
255
|
+
case "control-ping":
|
|
256
|
+
// Keepalive: reply IMMEDIATELY on the same tab, echoing the PING's identity (there may be no current
|
|
257
|
+
// engine yet, and the keepalive is a liveness check of the SharedWorker itself, not of an engine).
|
|
258
|
+
tab.port.postMessage(envelope({ type: "control-ack", identity: message.identity, pingId: message.pingId }));
|
|
259
|
+
return;
|
|
260
|
+
case "overdue-dispatch":
|
|
261
|
+
// Execution limit (ADR D5): only when enabled AND the report is for the CURRENT engine identity.
|
|
262
|
+
if (executionLimit?.maxDispatchMs === undefined) return; // disabled → ignored entirely
|
|
263
|
+
if (!shouldApplyControlMessage(currentIdentity, message)) return; // stale / no engine
|
|
264
|
+
startProbe();
|
|
265
|
+
return;
|
|
266
|
+
case "engine-teardown":
|
|
267
|
+
// The coordinator's teardown handshake (ADR-0049 step 9): forward it VERBATIM to the engine's control
|
|
268
|
+
// channel for the CURRENT identity, so the engine acks + self-closes. A stale teardown is discarded.
|
|
269
|
+
if (!shouldApplyControlMessage(currentIdentity, message)) return;
|
|
270
|
+
controlPort?.postMessage(envelope(message));
|
|
271
|
+
return;
|
|
272
|
+
case "tab-detach":
|
|
273
|
+
// The tab is detaching (ADR-0049 D8): unregister it so `tabCount` (the destroy peer-refusal input) falls.
|
|
274
|
+
// The `detach` bridge envelope rides the tab's pipe (invisible here), so this control signal on the SW
|
|
275
|
+
// port is the router's only view of the departure. Its minted pipe end is simply dropped.
|
|
276
|
+
removeTab(tab);
|
|
277
|
+
return;
|
|
278
|
+
default:
|
|
279
|
+
// Any other control type from a tab is not the router's concern.
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Unregister a tab: drop it from the registry and detach its listeners (the minted pipe end is dropped). */
|
|
285
|
+
function removeTab(entry: TabEntry): void {
|
|
286
|
+
if (!tabs.has(entry)) return;
|
|
287
|
+
tabs.delete(entry);
|
|
288
|
+
entry.port.removeEventListener("message", entry.listener);
|
|
289
|
+
if (entry.closeListener !== undefined) {
|
|
290
|
+
(entry.port as unknown as ClosableRouterPort).removeEventListener?.("close", entry.closeListener);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function attachTab(tabPort: RouterPort): () => void {
|
|
295
|
+
const entry: TabEntry = {
|
|
296
|
+
port: tabPort,
|
|
297
|
+
listener: (event) => onTabMessage(entry, event.data),
|
|
298
|
+
};
|
|
299
|
+
tabPort.addEventListener("message", entry.listener);
|
|
300
|
+
tabPort.start?.();
|
|
301
|
+
// Belt-and-braces peer-departure detection (ADR-0049 D8): where the platform supports the MessagePort
|
|
302
|
+
// `close` event, a CRASHED tab that never sent `tab-detach` is still dropped (its port closes on agent
|
|
303
|
+
// teardown). Feature-detected via `onclose` so the structural `RouterPort` (and unit fakes) need not expose
|
|
304
|
+
// it. RESIDUAL: where the `close` event is UNSUPPORTED, a crashed peer that never sent `tab-detach` leaves a
|
|
305
|
+
// stale `tabCount` until the SharedWorker restarts — a `destroy()` then stays refused; the caller resolves it
|
|
306
|
+
// with `destroy({ force: true })` (the documented escape). A clean `stop()`/`pagehide` always sends `tab-detach`.
|
|
307
|
+
const closable = tabPort as unknown as ClosableRouterPort;
|
|
308
|
+
if ("onclose" in closable) {
|
|
309
|
+
const closeListener = () => removeTab(entry);
|
|
310
|
+
entry.closeListener = closeListener;
|
|
311
|
+
closable.addEventListener("close", closeListener);
|
|
312
|
+
}
|
|
313
|
+
tabs.add(entry);
|
|
314
|
+
// Late joiner: an already-ready engine pipes this tab immediately; otherwise it is piped on engine-ready.
|
|
315
|
+
if (currentIdentity !== undefined && engineReady) {
|
|
316
|
+
deliverPipe(entry);
|
|
317
|
+
}
|
|
318
|
+
return () => removeTab(entry);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function announceEngine(port: RouterPort): EngineIdentity {
|
|
322
|
+
clearEngine(); // detach any prior engine's listener/probe (no notice fanned by an announce).
|
|
323
|
+
const minted = mintEngineIdentity(swInstanceId, lastMinted);
|
|
324
|
+
lastMinted = minted;
|
|
325
|
+
currentIdentity = minted;
|
|
326
|
+
controlPort = port;
|
|
327
|
+
controlListener = (event) => onControlMessage(event.data);
|
|
328
|
+
port.addEventListener("message", controlListener);
|
|
329
|
+
port.start?.();
|
|
330
|
+
engineReady = false;
|
|
331
|
+
// ADR-0049 step 9: hand the freshly-minted identity to the engine's control plane FIRST — before any
|
|
332
|
+
// `connect-port` pipe. The engine remembers it (gating every subsequent tagged message) and replies
|
|
333
|
+
// `engine-ready`, which drives the pipe fan-out below.
|
|
334
|
+
port.postMessage(envelope({ type: "assign-identity", identity: minted }));
|
|
335
|
+
return minted;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function openHandoff(reason: "leader-granted" | "engine-retiring"): void {
|
|
339
|
+
if (reason === "engine-retiring") {
|
|
340
|
+
retireCurrentEngine();
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
// leader-granted: a fresh engine is about to be spawned — clear the current one and open the window.
|
|
344
|
+
clearEngine();
|
|
345
|
+
fanToTabs({ type: "leader-granted" });
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
return {
|
|
349
|
+
attachTab,
|
|
350
|
+
announceEngine,
|
|
351
|
+
openHandoff,
|
|
352
|
+
currentIdentity: () => currentIdentity,
|
|
353
|
+
tabCount: () => tabs.size,
|
|
354
|
+
};
|
|
355
|
+
}
|
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
// BOUNDED ZERO-SUBSCRIBER KEEP-ALIVE (decision 4): when the last subscriber of an entry leaves, a nonzero
|
|
6
6
|
// effective keep-alive retains the registration for a grace period so a matching resubscribe reuses it
|
|
7
7
|
// verbatim (no ~400 ms re-materialization); retention is bounded by explicit count/row budgets and defaults
|
|
8
|
-
// to OFF (keep-alive 0 → tear down
|
|
8
|
+
// to OFF (keep-alive 0 → tear down the instant the last subscriber leaves). The 0 default is deliberate:
|
|
9
|
+
// a retained entry still pays a full SQL rerun + diff on every dependent write (PGlite live queries cannot
|
|
10
|
+
// be paused), so keeping one alive is only worthwhile for a genuinely hot, re-mounted query — the default
|
|
11
|
+
// keeps worker memory bounded and never runs surprise standing SQL.
|
|
9
12
|
//
|
|
10
13
|
// What stays with the CALLER (`defineSyncWorker`), never this manager (ADR-0040 decision 3): lazy-relation
|
|
11
14
|
// activation (`prepareQuery`), hydration accounting (`hydratingTablesFor` → `groupReady`), the
|
|
@@ -19,6 +22,7 @@ import type { LiveNamespace, LiveQuery, LiveQueryResults } from "@electric-sql/p
|
|
|
19
22
|
import { syncDebug } from "../debug";
|
|
20
23
|
import { computeLiveDiff, type LiveDiffState, seedLiveDiffState } from "./live-diff";
|
|
21
24
|
import { fingerprintLiveQuery } from "./live-query-fingerprint";
|
|
25
|
+
import { assertLiveQueryParamsSafe } from "./live-query-params-guard";
|
|
22
26
|
import type { LiveDiffPayload } from "./protocol";
|
|
23
27
|
|
|
24
28
|
type Row = Record<string, unknown>;
|
|
@@ -452,6 +456,11 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
452
456
|
`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`,
|
|
453
457
|
);
|
|
454
458
|
}
|
|
459
|
+
// Reject a param shape that would trip PGlite bug #1055's broken live-query param inlining BEFORE any
|
|
460
|
+
// fingerprinting or registration (see live-query-params-guard.ts). Synchronous, so every subscriber —
|
|
461
|
+
// in-process and worker alike — fails loudly rather than binding wrong rows or hitting a cryptic
|
|
462
|
+
// `format()` error deep inside PGlite.
|
|
463
|
+
assertLiveQueryParamsSafe(spec.materialSql, spec.params);
|
|
455
464
|
const keepAliveMs = hint ?? 0;
|
|
456
465
|
const scope = opts?.scope;
|
|
457
466
|
// Track this whole call so `dispose()` can drain the post-await join before it settles the teardown set —
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// A defensive guard against PGlite upstream bug https://github.com/electric-sql/pglite/issues/1055 on the
|
|
2
|
+
// live-query path. WHY this exists:
|
|
3
|
+
//
|
|
4
|
+
// PGlite 0.5.4's `live.query` / `live.incrementalQuery` inline bound params into a `CREATE TEMP VIEW`
|
|
5
|
+
// (via `formatQuery`) WHENEVER `params.length > 0`. That inlining rewrites every `$N` placeholder with
|
|
6
|
+
// `sql.replace(/\$([0-9]+)/g, (_, n) => "%" + n + "L")` — emitting `%NL`, which is Postgres `format()`'s
|
|
7
|
+
// "pad to width N, consume the NEXT argument sequentially" directive, NOT the positional `%N$L` it means to
|
|
8
|
+
// emit. Empirically confirmed consequences:
|
|
9
|
+
// - out-of-order placeholders (`… $2 … $1 …`) silently bind params in TEXTUAL order → wrong rows;
|
|
10
|
+
// - a repeated placeholder (`$1 … $1`) throws `too few arguments for format()`;
|
|
11
|
+
// - a skipped placeholder silently mis-binds.
|
|
12
|
+
// The ONLY input shape under which PGlite's broken inlining is still correct: the placeholders, read in
|
|
13
|
+
// textual order, are exactly `$1, $2, …, $n` (n = params.length) — each appearing exactly once, strictly
|
|
14
|
+
// ascending. Drizzle-compiled SQL always satisfies this (its serializer numbers params in the same
|
|
15
|
+
// left-to-right pass that emits them); hand-written raw SQL may not.
|
|
16
|
+
//
|
|
17
|
+
// So this guard fails LOUDLY at the client boundary for any other shape, turning a silent wrong-rows /
|
|
18
|
+
// cryptic-`format()` failure into an actionable error naming the upstream bug. It can be DELETED once
|
|
19
|
+
// transcrobes/pgxsinkit pin a PGlite release whose `formatQuery` emits the positional `%N$L`.
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Throw if `sql` + `params` would hit PGlite bug #1055's broken param inlining (see the module header).
|
|
23
|
+
*
|
|
24
|
+
* `params.length === 0` returns immediately: PGlite skips `formatQuery` entirely in that case, so any `$N`
|
|
25
|
+
* tokens are Postgres's own concern, not this guard's. Otherwise the SQL is scanned with the SAME regex
|
|
26
|
+
* PGlite's rewrite uses (`/\$(\d+)/g`) — deliberately, so the guard sees EXACTLY the tokens PGlite would
|
|
27
|
+
* touch. That includes a `$1` sitting inside a string literal: PGlite would corrupt that too, so a loud
|
|
28
|
+
* false positive here is a feature, not a bug — it flags SQL PGlite cannot inline safely regardless.
|
|
29
|
+
*
|
|
30
|
+
* Safe iff the collected numbers (in textual order) are exactly `[1, 2, …, params.length]`. Anything else —
|
|
31
|
+
* out-of-order, repeated, skipped, or a count mismatch in either direction — throws.
|
|
32
|
+
*/
|
|
33
|
+
export function assertLiveQueryParamsSafe(sql: string, params: readonly unknown[]): void {
|
|
34
|
+
// No params → PGlite never calls formatQuery, so its broken inlining never runs. Placeholders without
|
|
35
|
+
// params are Postgres's problem to report, not this guard's.
|
|
36
|
+
if (params.length === 0) return;
|
|
37
|
+
|
|
38
|
+
// The SAME regex PGlite's `formatQuery` applies — so we see exactly the tokens its rewrite would touch,
|
|
39
|
+
// including any `$N` inside a string literal (which PGlite would corrupt too; flagging it is intentional).
|
|
40
|
+
const numbers: number[] = [];
|
|
41
|
+
for (const match of sql.matchAll(/\$(\d+)/g)) numbers.push(Number(match[1]));
|
|
42
|
+
|
|
43
|
+
const expected = params.length;
|
|
44
|
+
const safe = numbers.length === expected && numbers.every((n, i) => n === i + 1);
|
|
45
|
+
if (safe) return;
|
|
46
|
+
|
|
47
|
+
const found = numbers.length === 0 ? "(none)" : numbers.map((n) => `$${n}`).join(", ");
|
|
48
|
+
throw new Error(
|
|
49
|
+
`[pgxsinkit] live query hits PGlite bug #1055 ` +
|
|
50
|
+
`(https://github.com/electric-sql/pglite/issues/1055): its live-query param inlining binds $N ` +
|
|
51
|
+
`placeholders SEQUENTIALLY (in textual order), not positionally, so anything but a strictly ` +
|
|
52
|
+
`ascending $1..$n each used once silently mis-binds or throws. Found placeholders [${found}] for ` +
|
|
53
|
+
`${expected} param${expected === 1 ? "" : "s"}, expected exactly [$1..$${expected}]. Renumber the ` +
|
|
54
|
+
`placeholders to a strictly sequential $1..$${expected}, each used once — or pass the query as a ` +
|
|
55
|
+
`Drizzle builder, which always compiles to that shape.`,
|
|
56
|
+
);
|
|
57
|
+
}
|
package/src/worker/protocol.ts
CHANGED
|
@@ -19,7 +19,8 @@ export const BRIDGE_PROTOCOL_VERSION = 1 as const;
|
|
|
19
19
|
/**
|
|
20
20
|
* A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib
|
|
21
21
|
* dependency (like the convergence triggers), so this is the toolkit's own name for the type a future
|
|
22
|
-
* columnar codec would hand to `postMessage`'s transfer list.
|
|
22
|
+
* columnar codec would hand to `postMessage`'s transfer list. The wire-format-1 identity codec
|
|
23
|
+
* ({@link BRIDGE_PROTOCOL_VERSION}) never produces one.
|
|
23
24
|
*/
|
|
24
25
|
export type BridgeTransferable = unknown;
|
|
25
26
|
|
|
@@ -147,6 +148,8 @@ export interface AttachPayload {
|
|
|
147
148
|
* memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.
|
|
148
149
|
*/
|
|
149
150
|
testStoreBackend?: "memory";
|
|
151
|
+
/** ADR-0049 D5: the tab's engine-construction limit, checked by the host before it acknowledges attach. */
|
|
152
|
+
executionLimit?: { maxDispatchMs?: number };
|
|
150
153
|
/**
|
|
151
154
|
* Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of
|
|
152
155
|
* `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`
|
|
@@ -253,10 +256,23 @@ export type RpcOp =
|
|
|
253
256
|
| "discardQuarantined"
|
|
254
257
|
| "desync"
|
|
255
258
|
| "discardEphemeral"
|
|
259
|
+
// Lazy activation (ADR-0021): start the consistency groups of the given relation keys on the shared engine.
|
|
260
|
+
// Engine-WIDE but additive/idempotent (unlike `desync`), so it is a plain fire-and-await RPC — carries
|
|
261
|
+
// `[keys]`, resolves once the streams are started (catch-up may still be in flight).
|
|
262
|
+
| "ensureSynced"
|
|
256
263
|
| "readMutationDetails"
|
|
257
264
|
| "diagnostics"
|
|
258
265
|
| "rawQuery"
|
|
259
266
|
| "rawExec"
|
|
267
|
+
// Guarded one-shot Drizzle read (ADR-0032 decision 4): the attach client's Drizzle-over-bridge compiles a
|
|
268
|
+
// read to SQL on the tab and routes it here as the {@link GuardedQueryWireArgs} tuple
|
|
269
|
+
// `[sql, params?, { rowMode? }, use?]`. Unlike `rawQuery` (raw inspection, no guard), the worker runs the
|
|
270
|
+
// engine's `guardedRawQuery` — the ADR-0041 read gate + the ADR-0021 lazy-group guard (activating any lazy
|
|
271
|
+
// relation the SQL/`use` reference) — then returns the full PGlite `Results` over `rpc-result`, so Drizzle's
|
|
272
|
+
// own result mapping runs on the tab. Only `rowMode` crosses in the options: drizzle's `parsers` map is
|
|
273
|
+
// FUNCTIONS (non-serializable) and is stripped tab-side, then re-applied worker-side so the identity-parsed
|
|
274
|
+
// OIDs (drizzle's identity parsers — temporal OIDs + numeric[]) round-trip as raw strings exactly as in-process.
|
|
275
|
+
| "guardedQuery"
|
|
260
276
|
// Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the
|
|
261
277
|
// stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.
|
|
262
278
|
| "bootReport"
|
|
@@ -273,6 +289,21 @@ export type RpcOp =
|
|
|
273
289
|
// clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.
|
|
274
290
|
| "exportData";
|
|
275
291
|
|
|
292
|
+
/**
|
|
293
|
+
* The positional wire tuple the `guardedQuery` {@link RpcOp} carries: a guarded one-shot Drizzle read compiled
|
|
294
|
+
* to SQL on the tab. Encoded identically by both tab-side senders (`attachSyncClient`'s bridge executor and
|
|
295
|
+
* `guardedRawQuery`) and decoded against this same type worker-side (`defineSyncWorker`'s dispatch), so encoder
|
|
296
|
+
* and decoder share ONE contract. `options` carries only `rowMode` — drizzle's `parsers` map is stripped
|
|
297
|
+
* tab-side (see the `guardedQuery` op above) and re-applied worker-side. The optional trailing `use` lists the
|
|
298
|
+
* raw-fragment lazy relations (ADR-0021) the SQL scan cannot see.
|
|
299
|
+
*/
|
|
300
|
+
export type GuardedQueryWireArgs = [
|
|
301
|
+
sql: string,
|
|
302
|
+
params: unknown[] | undefined,
|
|
303
|
+
options: { rowMode?: "array" | "object" },
|
|
304
|
+
use?: readonly string[],
|
|
305
|
+
];
|
|
306
|
+
|
|
276
307
|
/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */
|
|
277
308
|
export interface RpcPayload {
|
|
278
309
|
op: RpcOp;
|
|
@@ -315,9 +346,9 @@ export interface SubscribePayload {
|
|
|
315
346
|
params: unknown[];
|
|
316
347
|
/**
|
|
317
348
|
* The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE
|
|
318
|
-
* (one per output column, in the compiled SQL's column order).
|
|
319
|
-
*
|
|
320
|
-
*
|
|
349
|
+
* (one per output column, in the compiled SQL's column order). When omitted, the worker leaves the SQL
|
|
350
|
+
* untouched and returns name-keyed rows; supply it for a JOIN with same-named columns, which
|
|
351
|
+
* `live.query`/`live.incrementalQuery` otherwise
|
|
321
352
|
* refuse to materialise (`column "title" specified more than once`). When present, result columns are
|
|
322
353
|
* the aliases, so {@link pkColumns} must name a PK by its alias.
|
|
323
354
|
*/
|
|
@@ -333,9 +364,8 @@ export interface SubscribePayload {
|
|
|
333
364
|
/**
|
|
334
365
|
* Per-subscription keep-alive hint (ms) for the worker's live-query manager (ADR-0040 decision 4): how long
|
|
335
366
|
* the shared registration should be retained after this subscription's last consumer leaves, so a matching
|
|
336
|
-
* resubscribe reuses it verbatim.
|
|
337
|
-
*
|
|
338
|
-
* means "no hint".
|
|
367
|
+
* resubscribe reuses it verbatim. When omitted, the worker falls back to
|
|
368
|
+
* `liveQueries.defaultKeepAliveMs`; absent means "no hint".
|
|
339
369
|
*/
|
|
340
370
|
keepAliveMs?: number;
|
|
341
371
|
}
|
|
@@ -436,9 +466,10 @@ export interface BridgeCodec {
|
|
|
436
466
|
}
|
|
437
467
|
|
|
438
468
|
/**
|
|
439
|
-
* The
|
|
440
|
-
*
|
|
441
|
-
* only this object, never the message types or
|
|
469
|
+
* The identity codec, wire-format version 1 ({@link BRIDGE_PROTOCOL_VERSION}): the body IS the payload,
|
|
470
|
+
* and the transport's structured clone does the real copying. No transferables. The sole codec at this
|
|
471
|
+
* wire version — swapping in a columnar codec later touches only this object, never the message types or
|
|
472
|
+
* the router.
|
|
442
473
|
*/
|
|
443
474
|
export const identityCodec: BridgeCodec = {
|
|
444
475
|
encode: (payload) => ({ payload }),
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// The SharedWorker startup PLACEMENT DECISION (ADR-0049 decision 1/2, plan step 10b). A SharedWorker decides
|
|
2
|
+
// its ENGINE HOME by running the placement probe (`placement-probe.ts`) ONCE at startup — a real
|
|
3
|
+
// `createSyncAccessHandle` open in its own scope — and turns the probe's verdict into a placement result the
|
|
4
|
+
// bootstrap gates every tab connection on. Granted → the engine lives IN the SharedWorker (`shared-worker`,
|
|
5
|
+
// SW-direct, election disabled this lifetime); denied → the SharedWorker is ROUTER-ONLY (`elected-worker`) and
|
|
6
|
+
// each tab's election coordinator spawns the real engine in a dedicated worker.
|
|
7
|
+
//
|
|
8
|
+
// This module is the PURE decision only — it boots NO engine and creates NO router. It is testable off-worker
|
|
9
|
+
// (no real OPFS) via the injectable `probe`/`mintInstanceId` seams, the same discipline `placement-probe.ts`,
|
|
10
|
+
// `engine-router.ts`, and `election-coordinator.ts` follow. The probe is NEVER cached across SW lifetimes
|
|
11
|
+
// (invariant 8): a fresh SharedWorker runs a fresh decision.
|
|
12
|
+
|
|
13
|
+
import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The SharedWorker's engine-home decision (ADR-0049 D1). `shared-worker` = the engine boots in this
|
|
17
|
+
* SharedWorker scope (granted OPFS sync access, SW-direct, election never engages); `elected-worker` = the
|
|
18
|
+
* SharedWorker is router-only and each tab elects a dedicated engine worker. `probeError` carries the probe's
|
|
19
|
+
* verbatim denial attribution when NOT granted (diagnostics only, never parsed). `swInstanceId` scopes every
|
|
20
|
+
* minted engine identity's generation (`engine-router.ts`).
|
|
21
|
+
*/
|
|
22
|
+
export interface SwPlacementResult {
|
|
23
|
+
engineHome: "shared-worker" | "elected-worker";
|
|
24
|
+
probeError?: string;
|
|
25
|
+
swInstanceId: string;
|
|
26
|
+
/**
|
|
27
|
+
* Present ONLY on a `shared-worker` home that is a CAPABILITY-ABSENCE fallback (ADR-0049 D1), not an OPFS
|
|
28
|
+
* grant: the platform cannot hold sync-access handles in any home, so the engine boots in-SharedWorker on the
|
|
29
|
+
* IDBFS backend with the registry-declared durability. Carries the verbatim probe attribution the fallback
|
|
30
|
+
* boot stamps into `storageFallbackReason` (decision 12). Absent on a granted `shared-worker` (SW-direct OPFS)
|
|
31
|
+
* and on `elected-worker` — an OPFS-capable elected home is not a fallback.
|
|
32
|
+
*/
|
|
33
|
+
storageFallbackReason?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Injectable seams so the decision is deterministic in a Bun unit test (no real OPFS, no real crypto needed). */
|
|
37
|
+
export interface DecideSwPlacementDeps {
|
|
38
|
+
/** The placement probe; defaults to {@link probeOpfsSyncAccess}. Injected in tests to drive both verdicts. */
|
|
39
|
+
probe?: () => Promise<PlacementProbeResult>;
|
|
40
|
+
/** Mint the opaque SharedWorker instance id; defaults to `crypto.randomUUID()`. Injected for deterministic tests. */
|
|
41
|
+
mintInstanceId?: () => string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Decide the SharedWorker's engine home ONCE at startup (ADR-0049 D1, invariant 8 — probe per boot, never
|
|
46
|
+
* cached). Runs the placement probe; a granted verdict places the engine in-scope (`shared-worker`), a denied
|
|
47
|
+
* one puts the SharedWorker in router-only mode (`elected-worker`) and carries the probe's verbatim error for
|
|
48
|
+
* diagnostics. This is a PURE decision — no engine boots and no router is created here; the bootstrap
|
|
49
|
+
* (`define-sync-worker.ts`) acts on the result.
|
|
50
|
+
*/
|
|
51
|
+
export async function decideSwPlacement(deps?: DecideSwPlacementDeps): Promise<SwPlacementResult> {
|
|
52
|
+
const probe = deps?.probe ?? probeOpfsSyncAccess;
|
|
53
|
+
const mintInstanceId = deps?.mintInstanceId ?? (() => crypto.randomUUID());
|
|
54
|
+
const swInstanceId = mintInstanceId();
|
|
55
|
+
const result = await probe();
|
|
56
|
+
if (result.granted) {
|
|
57
|
+
return { engineHome: "shared-worker", swInstanceId };
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
engineHome: "elected-worker",
|
|
61
|
+
swInstanceId,
|
|
62
|
+
...(result.error !== undefined ? { probeError: result.error } : {}),
|
|
63
|
+
};
|
|
64
|
+
}
|