@pgxsinkit/client 0.1.31 → 0.1.36
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 +11 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/index.d.ts +421 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7214 -2234
- package/dist/index.js.map +74 -44
- package/dist/lazy-guard.d.ts +58 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +62 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +117 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +49 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +180 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +118 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/worker/attach-sync-client.d.ts +75 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +75 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +260 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +19 -7
- package/skills/core/SKILL.md +197 -0
- package/skills/operating/SKILL.md +243 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/index.ts +1104 -44
- package/src/lazy-guard.ts +121 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +90 -0
- package/src/mutation.ts +1868 -562
- package/src/schema.ts +352 -27
- package/src/shape-sync.ts +477 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1076 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +132 -0
- package/src/sync-auth.ts +117 -0
- package/src/worker/attach-sync-client.ts +558 -0
- package/src/worker/define-sync-worker.ts +596 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +325 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
// The worker entry factory (ADR-0032 S2, decisions 3/4/6/7). `defineSyncWorker` boots ONE sync engine and
|
|
2
|
+
// fans it out to N attached tabs over the bridge. The first attach boots the engine by calling the
|
|
3
|
+
// unchanged `createSyncClient` (the strongest form of "reuse createSyncClient internals" — the in-process
|
|
4
|
+
// boot pipeline runs verbatim, so the unit suite stays its equivalence proof); later attaches join it.
|
|
5
|
+
//
|
|
6
|
+
// It serves BOTH a native `SharedWorker` (`onconnect`, many ports) and a dedicated `Worker` (one implicit
|
|
7
|
+
// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`
|
|
8
|
+
// port, so no real Worker is needed to exercise the whole protocol.
|
|
9
|
+
|
|
10
|
+
import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
|
|
11
|
+
|
|
12
|
+
import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
|
|
13
|
+
import { setSyncDebugSink, syncDebug } from "../debug";
|
|
14
|
+
import {
|
|
15
|
+
type ClientPGlite,
|
|
16
|
+
createClientPGlite,
|
|
17
|
+
type CreateSyncClientOptions,
|
|
18
|
+
createSyncClient,
|
|
19
|
+
type MutationBatchItem,
|
|
20
|
+
type RawQueryOptions,
|
|
21
|
+
type SyncClient,
|
|
22
|
+
} from "../index";
|
|
23
|
+
import type { LocalStoreVersionEvent } from "../local-store";
|
|
24
|
+
import { computeLiveDiff, seedLiveDiffState } from "./live-diff";
|
|
25
|
+
import {
|
|
26
|
+
type AttachPayload,
|
|
27
|
+
type BridgeCodec,
|
|
28
|
+
type BridgeEnvelope,
|
|
29
|
+
type BridgeEvent,
|
|
30
|
+
type BridgePort,
|
|
31
|
+
identityCodec,
|
|
32
|
+
isBridgeEnvelope,
|
|
33
|
+
postBridgeMessage,
|
|
34
|
+
type ProvisionPayload,
|
|
35
|
+
type RpcOp,
|
|
36
|
+
type RpcPayload,
|
|
37
|
+
type SetOnlinePayload,
|
|
38
|
+
type SubscribePayload,
|
|
39
|
+
type TokenResponsePayload,
|
|
40
|
+
} from "./protocol";
|
|
41
|
+
import { createWorkerTokenCache } from "./token-cache";
|
|
42
|
+
|
|
43
|
+
export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
44
|
+
/**
|
|
45
|
+
* The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
|
|
46
|
+
* When {@link resolveRegistry} is also given this is the DEFAULT (used when the attach carries no role
|
|
47
|
+
* or an unknown one).
|
|
48
|
+
*/
|
|
49
|
+
registry: TRegistry;
|
|
50
|
+
/**
|
|
51
|
+
* Resolve the registry to boot from the attach's `config.role` (ADR-0032 S3). A single worker file can
|
|
52
|
+
* bake BOTH role variants (e.g. the board's admin/member registries — same TS shape, different write
|
|
53
|
+
* capability) and pick per-attach, which the spare flow needs: the spare is provisioned role-agnostic
|
|
54
|
+
* (before the user is known) and the role is only settled at claim/attach. Returns `undefined` to fall
|
|
55
|
+
* back to {@link registry}.
|
|
56
|
+
*/
|
|
57
|
+
resolveRegistry?: (role: string | undefined) => TRegistry | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to
|
|
60
|
+
* {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the
|
|
61
|
+
* same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.
|
|
62
|
+
*/
|
|
63
|
+
createPglite?: (dataDir: string) => Promise<ClientPGlite>;
|
|
64
|
+
electricUrl: string;
|
|
65
|
+
writeUrl: string;
|
|
66
|
+
/** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
|
|
67
|
+
requestHeaders?: Record<string, string>;
|
|
68
|
+
/** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
|
|
69
|
+
writeRequestHeaders?: Record<string, string>;
|
|
70
|
+
/** Default PGlite store id if the first attach carries none (`memory://…` in tests, `idb://…` in a browser). */
|
|
71
|
+
dataDir?: string;
|
|
72
|
+
maxMutationAttempts?: number;
|
|
73
|
+
syncEnabled?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull
|
|
76
|
+
* broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.
|
|
77
|
+
*/
|
|
78
|
+
tokenExpiryMarginMs?: number;
|
|
79
|
+
/**
|
|
80
|
+
* The worker's own convergence cadence (ms) — the interval trigger FALLBACK only. Local writes
|
|
81
|
+
* flush immediately via the event-driven `requestPass` seam and tab `wake` signals, so this
|
|
82
|
+
* interval exists purely for retry/recovery sweeps; each idle pass still costs real worker CPU
|
|
83
|
+
* (`flush` + `reconcile` queries). Default 15000.
|
|
84
|
+
*/
|
|
85
|
+
convergenceIntervalMs?: number;
|
|
86
|
+
/** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
|
|
87
|
+
installGlobal?: boolean;
|
|
88
|
+
/** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
|
|
89
|
+
codec?: BridgeCodec;
|
|
90
|
+
/**
|
|
91
|
+
* A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s
|
|
92
|
+
* {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a
|
|
93
|
+
* browser worker the store is minted internally (`dataDir`); this is the seam for a prepopulated store in
|
|
94
|
+
* tests, and the future spare-worker claim (ADR-0032 decision 5).
|
|
95
|
+
*/
|
|
96
|
+
precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
|
|
97
|
+
/** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
|
|
98
|
+
pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The worker-side host: attach ports, await the boot, and (for tests) tear down. */
|
|
102
|
+
export interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {
|
|
103
|
+
/** Bind a transport port (a SharedWorker connection, the dedicated-worker `self`, or a test channel port). */
|
|
104
|
+
connect: (port: BridgePort) => void;
|
|
105
|
+
/** Resolves with the booted in-process engine once the first attach's `createSyncClient` completes. */
|
|
106
|
+
whenBooted: () => Promise<SyncClient<TRegistry>>;
|
|
107
|
+
/** Detach every port and stop the underlying client — for tests and dedicated-worker teardown. */
|
|
108
|
+
close: () => Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface LiveSub {
|
|
112
|
+
unsubscribe: () => void;
|
|
113
|
+
port: BridgePort;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Build a worker host over the given engine config. In a real worker file the consumer calls this at module
|
|
118
|
+
* top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.
|
|
119
|
+
*/
|
|
120
|
+
export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
121
|
+
options: DefineSyncWorkerOptions<TRegistry>,
|
|
122
|
+
): SyncWorkerHost<TRegistry> {
|
|
123
|
+
const codec = options.codec ?? identityCodec;
|
|
124
|
+
const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
|
|
125
|
+
const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
|
|
126
|
+
const createPglite = options.createPglite ?? ((dataDir: string) => createClientPGlite(dataDir));
|
|
127
|
+
|
|
128
|
+
const ports = new Set<BridgePort>();
|
|
129
|
+
const liveSubs = new Map<string, LiveSub>();
|
|
130
|
+
|
|
131
|
+
// ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────
|
|
132
|
+
// A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`
|
|
133
|
+
// adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision
|
|
134
|
+
// is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.
|
|
135
|
+
let provisioned: { dataDir: string; pglite: Promise<ClientPGlite> } | null = null;
|
|
136
|
+
|
|
137
|
+
// ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
|
|
138
|
+
// The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
|
|
139
|
+
// interval trigger's `shouldConverge` returns false (writes stage in the journal, unsent) and a `wake`
|
|
140
|
+
// is ignored; resuming fires one immediate pass so the queue flushes at once.
|
|
141
|
+
let convergenceSuppressed = false;
|
|
142
|
+
let fireConvergence: (() => void) | null = null;
|
|
143
|
+
const baseTrigger = createIntervalConvergenceTrigger(convergenceIntervalMs);
|
|
144
|
+
const gatedTrigger: ConvergenceTrigger = {
|
|
145
|
+
subscribe: (onSignal) => {
|
|
146
|
+
fireConvergence = onSignal;
|
|
147
|
+
const unsubscribe = baseTrigger.subscribe(onSignal);
|
|
148
|
+
return () => {
|
|
149
|
+
fireConvergence = null;
|
|
150
|
+
unsubscribe();
|
|
151
|
+
};
|
|
152
|
+
},
|
|
153
|
+
shouldConverge: () => !convergenceSuppressed && baseTrigger.shouldConverge(),
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// ─── The single auth token cache + pull mechanism (ADR-0032 decision 3) ──────────────────────────
|
|
157
|
+
const tokenCache = createWorkerTokenCache({
|
|
158
|
+
marginMs: tokenExpiryMarginMs,
|
|
159
|
+
broadcastRequest: (requestId) => {
|
|
160
|
+
syncDebug("worker token pull broadcast", { requestId, tabs: ports.size });
|
|
161
|
+
broadcast("token-request", { requestId });
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
const getWorkerAuthToken = () => tokenCache.getToken();
|
|
165
|
+
|
|
166
|
+
// ─── The broadcast event channel (ADR-0032 decision 7) ───────────────────────────────────────────
|
|
167
|
+
const seenReadyGroups = new Set<string>();
|
|
168
|
+
const broadcast = (type: BridgeEnvelope["type"], payload: unknown) => {
|
|
169
|
+
for (const port of ports) postBridgeMessage(port, codec, type, payload);
|
|
170
|
+
};
|
|
171
|
+
const broadcastEvent = (event: BridgeEvent) => broadcast("event", event);
|
|
172
|
+
|
|
173
|
+
const emitStatus = (status: SyncRuntimeStatus) => {
|
|
174
|
+
broadcastEvent({ kind: "status", status });
|
|
175
|
+
// Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the
|
|
176
|
+
// status snapshot (`status.groups`) and a discrete edge to await (ADR-0032 decision 6/7).
|
|
177
|
+
for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {
|
|
178
|
+
if (ready && !seenReadyGroups.has(groupKey)) {
|
|
179
|
+
seenReadyGroups.add(groupKey);
|
|
180
|
+
broadcastEvent({ kind: "groupReady", groupKey });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────
|
|
186
|
+
let client: SyncClient<TRegistry> | null = null;
|
|
187
|
+
let bootPromise: Promise<SyncClient<TRegistry>> | null = null;
|
|
188
|
+
// The role the engine actually booted with (from the FIRST attach's config). Later attaches compare
|
|
189
|
+
// their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.
|
|
190
|
+
let bootedRole: string | undefined;
|
|
191
|
+
// The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase
|
|
192
|
+
// later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether
|
|
193
|
+
// it has fired and tell the ack (ADR-0032 FIX 3).
|
|
194
|
+
let engineReadyFired = false;
|
|
195
|
+
let resolveBooted!: (client: SyncClient<TRegistry>) => void;
|
|
196
|
+
const bootedPromise = new Promise<SyncClient<TRegistry>>((resolve) => {
|
|
197
|
+
resolveBooted = resolve;
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
|
|
201
|
+
if (bootPromise) return bootPromise;
|
|
202
|
+
// The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
|
|
203
|
+
tokenCache.push(attach.token);
|
|
204
|
+
bootedRole = attach.config?.role;
|
|
205
|
+
// Forward the debug rail to tabs, stamped with the WORKER's monotonic clock (decision 7). Installed
|
|
206
|
+
// before boot so the boot rail itself crosses the bridge.
|
|
207
|
+
setSyncDebugSink((line, stamp, data) => {
|
|
208
|
+
broadcastEvent({ kind: "debug", stamp, line, ...(data ? { data } : {}) });
|
|
209
|
+
});
|
|
210
|
+
// Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
|
|
211
|
+
// and the claim/attach settles which one boots — the spare was provisioned before the role was known.
|
|
212
|
+
const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
|
|
213
|
+
// dataDir-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
|
|
214
|
+
// `storeId` (SharedWorker naming, tab-side) AND the real `dataDir` (`idb://pgxsinkit-board-<id>`), and
|
|
215
|
+
// the PGlite store lives at `dataDir` — so the provisioned store's dataDir must be what we adopt on.
|
|
216
|
+
// `storeId` is only a last-ditch fallback for a caller that passes it as the store path.
|
|
217
|
+
const dataDir = attach.dataDir ?? attach.storeId ?? options.dataDir ?? "idb://pgxsinkit-overlay-v1";
|
|
218
|
+
// Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;
|
|
219
|
+
// createSyncClient falls back to a fresh `dataDir` create if that promise rejects — a pure accelerator.
|
|
220
|
+
const precreatedPglite =
|
|
221
|
+
provisioned && provisioned.dataDir === dataDir ? provisioned.pglite : options.precreatedPglite;
|
|
222
|
+
if (precreatedPglite === provisioned?.pglite) {
|
|
223
|
+
syncDebug("worker adopting provisioned store", { dataDir });
|
|
224
|
+
}
|
|
225
|
+
bootPromise = createSyncClient<TRegistry>({
|
|
226
|
+
registry,
|
|
227
|
+
electricUrl: options.electricUrl,
|
|
228
|
+
writeUrl: options.writeUrl,
|
|
229
|
+
dataDir,
|
|
230
|
+
...(precreatedPglite ? { precreatedPglite } : {}),
|
|
231
|
+
...(options.pgliteInstance ? { pgliteInstance: options.pgliteInstance } : {}),
|
|
232
|
+
// Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
|
|
233
|
+
// spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
|
|
234
|
+
// journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
|
|
235
|
+
// provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim
|
|
236
|
+
// path's explicit hint distinguishes them.
|
|
237
|
+
...(attach.config?.freshStore === true ? { freshStore: true } : {}),
|
|
238
|
+
getAuthToken: getWorkerAuthToken,
|
|
239
|
+
// The worker owns convergence via the interval trigger, GATED by the tab's Offline toggle
|
|
240
|
+
// (`set-online`); tabs additionally forward online/visibility as `wake` pass requests (below).
|
|
241
|
+
autoSync: gatedTrigger,
|
|
242
|
+
syncEnabled: attach.config?.syncEnabled ?? options.syncEnabled ?? true,
|
|
243
|
+
...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
|
|
244
|
+
...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),
|
|
245
|
+
...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
|
|
246
|
+
onStatusChange: (status) => emitStatus(status),
|
|
247
|
+
onConflict: (details) => broadcastEvent({ kind: "conflict", details }),
|
|
248
|
+
onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
|
|
249
|
+
onReject: (details) => broadcastEvent({ kind: "reject", details }),
|
|
250
|
+
onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: "schema-change", event }),
|
|
251
|
+
onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message }),
|
|
252
|
+
});
|
|
253
|
+
return bootPromise;
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const whenBooted = () => bootedPromise;
|
|
257
|
+
|
|
258
|
+
// ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
|
|
259
|
+
const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
|
|
260
|
+
type TableKey = SyncTableName<TRegistry>;
|
|
261
|
+
switch (op) {
|
|
262
|
+
case "create":
|
|
263
|
+
return active.mutate.create(args[0] as TableKey, args[1] as never);
|
|
264
|
+
case "update":
|
|
265
|
+
return active.mutate.update(args[0] as TableKey, args[1] as Record<string, string>, args[2] as never);
|
|
266
|
+
case "delete":
|
|
267
|
+
return active.mutate.delete(args[0] as TableKey, args[1] as Record<string, string>);
|
|
268
|
+
case "batch":
|
|
269
|
+
return active.mutate.batch(args[0] as ReadonlyArray<MutationBatchItem<TRegistry>>);
|
|
270
|
+
case "transaction": {
|
|
271
|
+
// The tab collected the unit's mutations (the run callback can't cross the wire); the worker replays
|
|
272
|
+
// the serialized items into a real `client.transaction` so pessimistic acks / optimistic flush match
|
|
273
|
+
// the in-process semantics exactly.
|
|
274
|
+
const { mode, items } = args[0] as { mode: WriteMode; items: MutationBatchItem<TRegistry>[] };
|
|
275
|
+
return active.transaction({ mode }, (tx) => {
|
|
276
|
+
for (const item of items) {
|
|
277
|
+
const handle = tx.tables[item.table];
|
|
278
|
+
if (item.kind === "create") {
|
|
279
|
+
handle.create(item.input as never);
|
|
280
|
+
} else if (item.kind === "update") {
|
|
281
|
+
// ADR-0022 addendum: a `blind` update replays through `updateBlind` (journal-only, no overlay).
|
|
282
|
+
if (item.blind) handle.updateBlind(item.entityKey, item.patch as never);
|
|
283
|
+
else handle.update(item.entityKey, item.patch as never);
|
|
284
|
+
} else {
|
|
285
|
+
handle.delete(item.entityKey);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
case "flush":
|
|
291
|
+
return active.flush(args[0] as TableKey | undefined);
|
|
292
|
+
case "reconcile":
|
|
293
|
+
return active.reconcile(args[0] as TableKey | undefined);
|
|
294
|
+
case "retryFailed":
|
|
295
|
+
return active.retryFailed(args[0] as TableKey | undefined);
|
|
296
|
+
case "recoverSending":
|
|
297
|
+
return active.recoverSending(args[0] as TableKey | undefined);
|
|
298
|
+
case "discardConflict":
|
|
299
|
+
return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);
|
|
300
|
+
case "discardQuarantined":
|
|
301
|
+
return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);
|
|
302
|
+
case "readMutationDetails":
|
|
303
|
+
return active.readMutationDetails(args[0] as TableKey | undefined);
|
|
304
|
+
case "diagnostics":
|
|
305
|
+
return active.diagnostics(args[0] as TableKey | undefined);
|
|
306
|
+
case "rawQuery":
|
|
307
|
+
// Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`
|
|
308
|
+
// exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across
|
|
309
|
+
// the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.
|
|
310
|
+
// The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.
|
|
311
|
+
return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
|
|
312
|
+
case "rawExec":
|
|
313
|
+
return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
|
|
314
|
+
default: {
|
|
315
|
+
const exhaustive: never = op;
|
|
316
|
+
throw new Error(`unknown rpc op ${String(exhaustive)}`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────
|
|
322
|
+
const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {
|
|
323
|
+
const active = client ?? (await bootPromise);
|
|
324
|
+
if (!active) throw new Error("subscribe before attach");
|
|
325
|
+
const { queryId, sql, params, pkColumns, use } = payload;
|
|
326
|
+
// Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker
|
|
327
|
+
// owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.
|
|
328
|
+
await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });
|
|
329
|
+
|
|
330
|
+
const live = active.pglite.live;
|
|
331
|
+
// Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered
|
|
332
|
+
// result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →
|
|
333
|
+
// `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape
|
|
334
|
+
// is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.
|
|
335
|
+
const registered =
|
|
336
|
+
pkColumns && pkColumns.length === 1
|
|
337
|
+
? await live.incrementalQuery<Record<string, unknown>>(sql, params as unknown[], pkColumns[0]!)
|
|
338
|
+
: await live.query<Record<string, unknown>>(sql, params as unknown[]);
|
|
339
|
+
|
|
340
|
+
const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
|
|
341
|
+
// Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
|
|
342
|
+
postBridgeMessage(port, codec, "live-initial", { queryId, rows: registered.initialResults.rows }, id);
|
|
343
|
+
|
|
344
|
+
const listener = (results: { rows: Record<string, unknown>[] }) => {
|
|
345
|
+
// `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.
|
|
346
|
+
const diff = computeLiveDiff(state, results.rows);
|
|
347
|
+
postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
|
|
348
|
+
};
|
|
349
|
+
registered.subscribe(listener);
|
|
350
|
+
liveSubs.set(queryId, {
|
|
351
|
+
port,
|
|
352
|
+
unsubscribe: () => void registered.unsubscribe(listener),
|
|
353
|
+
});
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
// ─── Per-port message routing ────────────────────────────────────────────────────────────────────
|
|
357
|
+
const onPortMessage = (port: BridgePort, data: unknown) => {
|
|
358
|
+
if (!isBridgeEnvelope(data)) return;
|
|
359
|
+
const envelope = data;
|
|
360
|
+
const payload = codec.decode(envelope.payload);
|
|
361
|
+
switch (envelope.type) {
|
|
362
|
+
case "provision": {
|
|
363
|
+
// Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt
|
|
364
|
+
// (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.
|
|
365
|
+
const provision = payload as ProvisionPayload;
|
|
366
|
+
const dataDir = provision.dataDir ?? provision.storeId ?? options.dataDir ?? "idb://pgxsinkit-overlay-v1";
|
|
367
|
+
if (bootPromise != null || provisioned != null) {
|
|
368
|
+
postBridgeMessage(port, codec, "provision-ack", {
|
|
369
|
+
ok: true,
|
|
370
|
+
...(provision.storeId ? { storeId: provision.storeId } : {}),
|
|
371
|
+
});
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
const pglite = createPglite(dataDir);
|
|
375
|
+
provisioned = { dataDir, pglite };
|
|
376
|
+
// Guard an unobserved rejection when no attach ever adopts it (the page navigated away).
|
|
377
|
+
void pglite.catch(() => undefined);
|
|
378
|
+
syncDebug("worker store provisioned", { dataDir });
|
|
379
|
+
void pglite.then(
|
|
380
|
+
() =>
|
|
381
|
+
postBridgeMessage(port, codec, "provision-ack", {
|
|
382
|
+
ok: true,
|
|
383
|
+
...(provision.storeId ? { storeId: provision.storeId } : {}),
|
|
384
|
+
}),
|
|
385
|
+
(error: unknown) =>
|
|
386
|
+
postBridgeMessage(port, codec, "provision-ack", {
|
|
387
|
+
ok: false,
|
|
388
|
+
error: serializeError(error),
|
|
389
|
+
...(provision.storeId ? { storeId: provision.storeId } : {}),
|
|
390
|
+
}),
|
|
391
|
+
);
|
|
392
|
+
break;
|
|
393
|
+
}
|
|
394
|
+
case "set-online": {
|
|
395
|
+
// The tab's Offline toggle over the bridge (ADR-0032 S3). Suppress/resume the worker's outbound
|
|
396
|
+
// convergence; resuming fires one immediate pass so queued writes flush at once.
|
|
397
|
+
const { online } = payload as SetOnlinePayload;
|
|
398
|
+
convergenceSuppressed = !online;
|
|
399
|
+
syncDebug("worker convergence gate", { online });
|
|
400
|
+
if (online) fireConvergence?.();
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
case "attach": {
|
|
404
|
+
const attach = payload as AttachPayload;
|
|
405
|
+
const alreadyBooted = bootPromise !== null;
|
|
406
|
+
if (alreadyBooted) {
|
|
407
|
+
// A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the
|
|
408
|
+
// first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.
|
|
409
|
+
tokenCache.pushIfFresher(attach.token);
|
|
410
|
+
// Role is a property of the (user, store) the engine already booted for: the worker is
|
|
411
|
+
// one-engine-per-(user,store) by ADR-0032 decision 2 and is NOT keyed by role. A mismatch is an
|
|
412
|
+
// app-layer bug to surface, not a supported topology — warn, keep the booted registry.
|
|
413
|
+
const requested = attach.config?.role;
|
|
414
|
+
if (requested !== bootedRole) {
|
|
415
|
+
syncDebug("worker attach role mismatch — engine keeps its booted registry", {
|
|
416
|
+
booted: bootedRole,
|
|
417
|
+
requested,
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
void boot(attach).then(
|
|
422
|
+
(booted) => {
|
|
423
|
+
client = booted;
|
|
424
|
+
resolveBooted(booted);
|
|
425
|
+
// Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the
|
|
426
|
+
// initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).
|
|
427
|
+
if (!engineReadyFired) {
|
|
428
|
+
void booted.ready.then(() => {
|
|
429
|
+
engineReadyFired = true;
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
// Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to
|
|
433
|
+
// hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).
|
|
434
|
+
postBridgeMessage(port, codec, "attach-ack", {
|
|
435
|
+
alreadyBooted,
|
|
436
|
+
...(engineReadyFired ? { engineReady: true } : {}),
|
|
437
|
+
});
|
|
438
|
+
postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
|
|
439
|
+
},
|
|
440
|
+
(error: unknown) => {
|
|
441
|
+
// The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of
|
|
442
|
+
// hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
|
|
443
|
+
// boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on
|
|
444
|
+
// that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
|
|
445
|
+
bootPromise = null;
|
|
446
|
+
postBridgeMessage(port, codec, "attach-ack", {
|
|
447
|
+
alreadyBooted,
|
|
448
|
+
error: serializeError(error),
|
|
449
|
+
});
|
|
450
|
+
},
|
|
451
|
+
);
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
case "token-push": {
|
|
455
|
+
// The tab pushed a fresh token (auth state change) — update the cache and satisfy any in-flight pull.
|
|
456
|
+
tokenCache.push(payload as AttachPayload["token"]);
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
case "token-response": {
|
|
460
|
+
const response = payload as TokenResponsePayload;
|
|
461
|
+
// First response for the current pull wins; a stale/duplicate requestId is ignored.
|
|
462
|
+
tokenCache.respond(response.requestId, response.token);
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
case "rpc": {
|
|
466
|
+
const { op, args } = payload as RpcPayload;
|
|
467
|
+
const id = envelope.id;
|
|
468
|
+
void (async () => {
|
|
469
|
+
try {
|
|
470
|
+
const active = client ?? (await bootPromise);
|
|
471
|
+
if (!active) throw new Error("rpc before attach");
|
|
472
|
+
const value = await dispatchRpc(active, op, args);
|
|
473
|
+
postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
|
|
476
|
+
}
|
|
477
|
+
})();
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
case "subscribe": {
|
|
481
|
+
const id = envelope.id;
|
|
482
|
+
void handleSubscribe(port, id, payload as SubscribePayload).catch((error) => {
|
|
483
|
+
postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
|
|
484
|
+
});
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
case "unsubscribe": {
|
|
488
|
+
const { queryId } = payload as { queryId: string };
|
|
489
|
+
const sub = liveSubs.get(queryId);
|
|
490
|
+
if (sub) {
|
|
491
|
+
sub.unsubscribe();
|
|
492
|
+
liveSubs.delete(queryId);
|
|
493
|
+
}
|
|
494
|
+
break;
|
|
495
|
+
}
|
|
496
|
+
case "wake": {
|
|
497
|
+
// A tab forwarded online/visibilitychange (or a manual nudge): treat it as a convergence pass request
|
|
498
|
+
// so a write flushes promptly without waiting for the worker's interval tick (decision 5 seam).
|
|
499
|
+
// Suppressed while the Offline toggle is off — a wake must not flush a simulated-offline board.
|
|
500
|
+
if (!convergenceSuppressed) void bootPromise?.then((active) => void active.flush());
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
default:
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
|
|
508
|
+
const detachPort = (port: BridgePort) => {
|
|
509
|
+
ports.delete(port);
|
|
510
|
+
for (const [queryId, sub] of liveSubs) {
|
|
511
|
+
if (sub.port === port) {
|
|
512
|
+
sub.unsubscribe();
|
|
513
|
+
liveSubs.delete(queryId);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
const connect = (port: BridgePort) => {
|
|
519
|
+
ports.add(port);
|
|
520
|
+
const listener = (event: { data: unknown }) => {
|
|
521
|
+
if (isBridgeEnvelope(event.data) && event.data.type === "detach") {
|
|
522
|
+
detachPort(port);
|
|
523
|
+
port.removeEventListener("message", listener);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
onPortMessage(port, event.data);
|
|
527
|
+
};
|
|
528
|
+
port.addEventListener("message", listener);
|
|
529
|
+
port.start?.();
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
// ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────
|
|
533
|
+
if (options.installGlobal !== false) bindGlobalScope(connect);
|
|
534
|
+
|
|
535
|
+
return {
|
|
536
|
+
connect,
|
|
537
|
+
whenBooted,
|
|
538
|
+
close: async () => {
|
|
539
|
+
for (const sub of liveSubs.values()) sub.unsubscribe();
|
|
540
|
+
liveSubs.clear();
|
|
541
|
+
ports.clear();
|
|
542
|
+
setSyncDebugSink(undefined);
|
|
543
|
+
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
544
|
+
await active?.stop();
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */
|
|
550
|
+
function serializeError(error: unknown): { message: string; detail?: unknown } {
|
|
551
|
+
if (error instanceof Error) {
|
|
552
|
+
const detail = (error as Error & { detail?: unknown }).detail;
|
|
553
|
+
return { message: error.message, ...(detail !== undefined ? { detail } : {}) };
|
|
554
|
+
}
|
|
555
|
+
return { message: String(error) };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
interface SharedWorkerConnectEvent {
|
|
559
|
+
ports: BridgePort[];
|
|
560
|
+
}
|
|
561
|
+
interface WorkerGlobalScopeLike {
|
|
562
|
+
onconnect?: (event: SharedWorkerConnectEvent) => void;
|
|
563
|
+
postMessage?: (message: unknown) => void;
|
|
564
|
+
addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
565
|
+
removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per
|
|
570
|
+
* tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the
|
|
571
|
+
* single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,
|
|
572
|
+
* where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.
|
|
573
|
+
*/
|
|
574
|
+
function bindGlobalScope(connect: (port: BridgePort) => void): void {
|
|
575
|
+
const scope = globalThis as unknown as WorkerGlobalScopeLike;
|
|
576
|
+
const hasSharedWorkerScope =
|
|
577
|
+
typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
|
|
578
|
+
const hasDedicatedWorkerScope =
|
|
579
|
+
typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
|
|
580
|
+
|
|
581
|
+
if (hasSharedWorkerScope) {
|
|
582
|
+
scope.onconnect = (event: SharedWorkerConnectEvent) => {
|
|
583
|
+
const port = event.ports[0];
|
|
584
|
+
if (port) connect(port);
|
|
585
|
+
};
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {
|
|
589
|
+
// The dedicated worker's own global scope IS the single port.
|
|
590
|
+
connect({
|
|
591
|
+
postMessage: (message: unknown) => scope.postMessage!(message),
|
|
592
|
+
addEventListener: (type, listener) => scope.addEventListener!(type, listener),
|
|
593
|
+
removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
}
|