@pgxsinkit/client 0.3.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +10 -3
- package/dist/boot-report.d.ts +8 -8
- package/dist/circuits/envelope-to-change.d.ts +9 -5
- package/dist/circuits/envelope-to-change.d.ts.map +1 -1
- package/dist/circuits/group-sync.d.ts +2 -2
- package/dist/circuits/group-sync.d.ts.map +1 -1
- package/dist/circuits/stream-source.d.ts +6 -0
- package/dist/circuits/stream-source.d.ts.map +1 -1
- package/dist/circuits/sync-engine.d.ts +2 -2
- package/dist/circuits/sync-engine.d.ts.map +1 -1
- package/dist/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +10 -10
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +196 -100
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1044 -487
- package/dist/index.js.map +39 -36
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +58 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +43 -31
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +5 -5
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +82 -6
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +5 -5
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -1
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +24 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +35 -18
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/live-query-params-guard.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -8
- package/skills/core/SKILL.md +80 -15
- package/skills/operating/SKILL.md +129 -129
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +12 -12
- package/src/circuits/envelope-to-change.ts +121 -12
- package/src/circuits/group-sync.ts +2 -2
- package/src/circuits/stream-source.ts +35 -9
- package/src/circuits/sync-engine.ts +6 -4
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +31 -36
- package/src/export-store.ts +20 -20
- package/src/index.ts +576 -340
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +70 -6
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +4 -4
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +124 -18
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +59 -43
- package/src/sync/apply.ts +32 -46
- package/src/sync/copy.ts +108 -13
- package/src/sync/drizzle-executor.ts +18 -19
- package/src/sync/metadata-tables.ts +1 -1
- package/src/sync/subscription-state.ts +7 -7
- package/src/testing.ts +3 -3
- package/src/worker/attach-sync-client.ts +146 -60
- package/src/worker/define-sync-worker.ts +212 -83
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +16 -15
- package/src/worker/protocol.ts +38 -7
|
@@ -7,8 +7,6 @@
|
|
|
7
7
|
// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`
|
|
8
8
|
// port, so no real Worker is needed to exercise the whole protocol.
|
|
9
9
|
|
|
10
|
-
import { type ParserOptions, type QueryOptions, types } from "@electric-sql/pglite";
|
|
11
|
-
|
|
12
10
|
import type {
|
|
13
11
|
ResolvedStorageDeclaration,
|
|
14
12
|
SyncRuntimeStatus,
|
|
@@ -21,24 +19,29 @@ import {
|
|
|
21
19
|
assertStorageDeclarationCompatible,
|
|
22
20
|
getSyncRegistryStorage,
|
|
23
21
|
isStorageBackend,
|
|
22
|
+
isStorageBuild,
|
|
24
23
|
isStorageDurability,
|
|
24
|
+
isStorageEngineDeclaration,
|
|
25
25
|
resolveStorageDeclaration,
|
|
26
26
|
StorageDeclarationRefusedError,
|
|
27
27
|
} from "@pgxsinkit/contracts";
|
|
28
|
+
import type { PostgresBuild, QueryOptions } from "@pgxsinkit/pgwasm";
|
|
29
|
+
import { drizzleParsers } from "@pgxsinkit/pgwasm/drizzle";
|
|
28
30
|
|
|
29
31
|
import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
|
|
30
32
|
import { setSyncDebugSink, syncDebug } from "../debug";
|
|
31
33
|
import { describeErrorChain } from "../error-chain";
|
|
32
34
|
import type { EventLaneOptions } from "../event-lane";
|
|
33
35
|
import {
|
|
34
|
-
type
|
|
35
|
-
|
|
36
|
+
type PgwasmClient,
|
|
37
|
+
createPgwasmClient,
|
|
36
38
|
type CreateSyncClientOptions,
|
|
37
39
|
createSyncClient,
|
|
38
40
|
type DataExportOptions,
|
|
39
41
|
type DiagnosticExportOptions,
|
|
40
42
|
type MutationBatchItem,
|
|
41
43
|
type RawQueryOptions,
|
|
44
|
+
type RawStatement,
|
|
42
45
|
type StoreExportOptions,
|
|
43
46
|
type SyncClient,
|
|
44
47
|
} from "../index";
|
|
@@ -46,6 +49,8 @@ import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
|
|
|
46
49
|
import type { LocalStoreVersionEvent } from "../local-store";
|
|
47
50
|
import { createOpfsEffects } from "../opfs-effects";
|
|
48
51
|
import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
|
|
52
|
+
import { assertStoreBuild } from "../store-build";
|
|
53
|
+
import { createStoreEngineResolver, type StoreEngineFactory, type StoreEngineModuleLoader } from "../store-engine";
|
|
49
54
|
import { idbStoreExists, META_STORE_UNAVAILABLE, readStoreMetaRecord, writeStoreMetaRecord } from "../store-meta";
|
|
50
55
|
import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
|
|
51
56
|
import {
|
|
@@ -76,6 +81,7 @@ import {
|
|
|
76
81
|
type BridgeEvent,
|
|
77
82
|
type BridgeErrorWire,
|
|
78
83
|
type BridgePort,
|
|
84
|
+
type BridgeTransferable,
|
|
79
85
|
type ExportArtefactWire,
|
|
80
86
|
type GuardedQueryWireArgs,
|
|
81
87
|
identityCodec,
|
|
@@ -84,6 +90,7 @@ import {
|
|
|
84
90
|
type ProvisionPayload,
|
|
85
91
|
type RpcOp,
|
|
86
92
|
type RpcPayload,
|
|
93
|
+
type RpcResultPayload,
|
|
87
94
|
type SetOnlinePayload,
|
|
88
95
|
type SubscribePayload,
|
|
89
96
|
type TokenResponsePayload,
|
|
@@ -91,28 +98,11 @@ import {
|
|
|
91
98
|
import { decideSwPlacement, type SwPlacementResult } from "./sw-placement";
|
|
92
99
|
import { createWorkerTokenCache } from "./token-cache";
|
|
93
100
|
|
|
94
|
-
// The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4)
|
|
95
|
-
//
|
|
96
|
-
//
|
|
97
|
-
//
|
|
98
|
-
//
|
|
99
|
-
// and the array OIDs 1115 = `timestamp[]`, 1185 = `timestamptz[]`, 1187 = `interval[]`, 1182 = `date[]`, and
|
|
100
|
-
// 1231 = `numeric[]` (NOT temporal — drizzle's list is mirrored verbatim, whatever its members). Over the
|
|
101
|
-
// bridge the map is FUNCTIONS (non-serializable), so the attach side strips the options down to `rowMode`
|
|
102
|
-
// and this worker re-applies the identical map. We do NOT import drizzle's private constant — this is a
|
|
103
|
-
// deliberate, version-pinned mirror.
|
|
104
|
-
const identityParser = (value: string): string => value;
|
|
105
|
-
const DRIZZLE_PGLITE_IDENTITY_PARSERS: ParserOptions = {
|
|
106
|
-
[types.TIMESTAMP]: identityParser,
|
|
107
|
-
[types.TIMESTAMPTZ]: identityParser,
|
|
108
|
-
[types.INTERVAL]: identityParser,
|
|
109
|
-
[types.DATE]: identityParser,
|
|
110
|
-
1231: identityParser,
|
|
111
|
-
1115: identityParser,
|
|
112
|
-
1185: identityParser,
|
|
113
|
-
1187: identityParser,
|
|
114
|
-
1182: identityParser,
|
|
115
|
-
};
|
|
101
|
+
// The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4) is
|
|
102
|
+
// `drizzleParsers` from `@pgxsinkit/pgwasm/drizzle`: the SAME map the in-process drizzle session passes into
|
|
103
|
+
// `pg.query`, so the listed OIDs (the temporal scalars and arrays, and `numeric[]`) come back as raw STRINGS
|
|
104
|
+
// exactly as they do in process. Over the bridge the map is FUNCTIONS (non-serializable), so the attach side
|
|
105
|
+
// strips the options down to `rowMode` and this worker re-applies the identical map.
|
|
116
106
|
|
|
117
107
|
/**
|
|
118
108
|
* Cadence (ms) of the "worker store provision still pending" heartbeat rail line, emitted from the moment a
|
|
@@ -137,12 +127,26 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
137
127
|
*/
|
|
138
128
|
resolveRegistry?: (role: string | undefined) => TRegistry | undefined;
|
|
139
129
|
/**
|
|
140
|
-
* How the worker creates its raw
|
|
141
|
-
* {@link
|
|
130
|
+
* How the worker creates its raw pgwasm store (provision + fresh-attach paths). Defaults to
|
|
131
|
+
* {@link createPgwasmClient}, which loads pgwasm's own boot assets — in a browser worker those hit the
|
|
142
132
|
* same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.
|
|
143
133
|
* Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
|
|
144
134
|
*/
|
|
145
|
-
|
|
135
|
+
createStore?: (storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>;
|
|
136
|
+
/**
|
|
137
|
+
* The Postgres build this worker's stores run on: the boot's own mint, the provision mint and every spare
|
|
138
|
+
* mint (never on the wire — code cannot cross it). Defaults to `cBuild`. Pass `createCBuild({ assets })` to
|
|
139
|
+
* boot over assets warmed in the worker. It must be the registry's declared `storage.build` (default
|
|
140
|
+
* `"c"`, ADR-0063): a mismatch throws `StorageBuildMismatchError` before any store is touched. A store a
|
|
141
|
+
* {@link createStore} factory returns is checked against its own `pg.build` the same way.
|
|
142
|
+
*/
|
|
143
|
+
build?: PostgresBuild;
|
|
144
|
+
/**
|
|
145
|
+
* How this scope imports a DECLARED store-engine module (ADR-0050 addendum 2026-09-08). Defaults to the
|
|
146
|
+
* scope's own dynamic `import()`; injected by a unit test that has no module to load. It is consulted
|
|
147
|
+
* only when the store's bound declaration carries `storage.engine`, and never for the built-in store.
|
|
148
|
+
*/
|
|
149
|
+
loadStoreEngineModule?: StoreEngineModuleLoader;
|
|
146
150
|
/** The pgxsinkit control plane — subscribe, token re-mint, convergence barrier (ADR-0055). */
|
|
147
151
|
controlPlaneUrl: string;
|
|
148
152
|
/** The edge that serves durable-streams reads. */
|
|
@@ -162,9 +166,10 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
162
166
|
*/
|
|
163
167
|
batchEventUrl?: string;
|
|
164
168
|
/**
|
|
165
|
-
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff,
|
|
166
|
-
* per-Event-stream overrides. A worker-ENTRY option, never an
|
|
167
|
-
* engine-wide policy, and the Outbox it drains is shared by every
|
|
169
|
+
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff, the
|
|
170
|
+
* acked ledger's retention (ADR-0060), and per-Event-stream overrides. A worker-ENTRY option, never an
|
|
171
|
+
* attach option — flush cadence is one engine-wide policy, and the Outbox it drains is shared by every
|
|
172
|
+
* attached tab.
|
|
168
173
|
*/
|
|
169
174
|
events?: EventLaneOptions;
|
|
170
175
|
/**
|
|
@@ -206,14 +211,14 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
206
211
|
/** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
|
|
207
212
|
codec?: BridgeCodec;
|
|
208
213
|
/**
|
|
209
|
-
* A raw
|
|
210
|
-
* {@link CreateSyncClientOptions.
|
|
214
|
+
* A raw pgwasm the worker uses instead of creating its own (forwarded to `createSyncClient`'s
|
|
215
|
+
* {@link CreateSyncClientOptions.precreatedPgwasm}) — the client still applies schema/reconcile. In a
|
|
211
216
|
* browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in
|
|
212
217
|
* tests, and the future spare-worker claim (ADR-0032 decision 5).
|
|
213
218
|
*/
|
|
214
|
-
|
|
215
|
-
/** A fully-provisioned
|
|
216
|
-
|
|
219
|
+
precreatedPgwasm?: CreateSyncClientOptions<TRegistry>["precreatedPgwasm"];
|
|
220
|
+
/** A fully-provisioned pgwasm (forwarded to {@link CreateSyncClientOptions.pgwasmInstance}; caller owns schema). */
|
|
221
|
+
pgwasmInstance?: CreateSyncClientOptions<TRegistry>["pgwasmInstance"];
|
|
217
222
|
/**
|
|
218
223
|
* App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
|
|
219
224
|
* schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
|
|
@@ -223,8 +228,8 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
223
228
|
* a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
|
|
224
229
|
* this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
|
|
225
230
|
*
|
|
226
|
-
* Runs on the storePath, {@link
|
|
227
|
-
* {@link
|
|
231
|
+
* Runs on the storePath, {@link precreatedPgwasm}, and restore boots; SKIPPED entirely on the
|
|
232
|
+
* {@link pgwasmInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
|
|
228
233
|
* runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
|
|
229
234
|
* invariant does not hold there.
|
|
230
235
|
*/
|
|
@@ -236,17 +241,17 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
236
241
|
* tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
|
|
237
242
|
* that depend on the registry's local tables, which DO exist by the time this runs.
|
|
238
243
|
*
|
|
239
|
-
* Runs on the storePath, {@link
|
|
240
|
-
* {@link
|
|
244
|
+
* Runs on the storePath, {@link precreatedPgwasm}, and restore boots; SKIPPED entirely on the
|
|
245
|
+
* {@link pgwasmInstance} path (the caller owns schema/prepare/reconcile there).
|
|
241
246
|
*/
|
|
242
247
|
prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
|
|
243
248
|
/**
|
|
244
249
|
* Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
|
|
245
|
-
* subscriber leaves, a nonzero effective keep-alive retains its
|
|
250
|
+
* subscriber leaves, a nonzero effective keep-alive retains its pgwasm registration + diff state for a grace
|
|
246
251
|
* period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
|
|
247
252
|
* re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
|
|
248
253
|
* down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
|
|
249
|
-
* full SQL rerun + diff on every dependent write —
|
|
254
|
+
* full SQL rerun + diff on every dependent write — pgwasm live queries cannot be paused — so retention
|
|
250
255
|
* only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
|
|
251
256
|
* no surprise standing SQL reruns.
|
|
252
257
|
*/
|
|
@@ -301,7 +306,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
301
306
|
);
|
|
302
307
|
}
|
|
303
308
|
// ADR-0049 D1: the placement probe's OPFS grant for THIS SharedWorker lifetime. Set true only by a GRANTED
|
|
304
|
-
// `shared-worker` (SW-direct) probe, so both the provision-mint (default `
|
|
309
|
+
// `shared-worker` (SW-direct) probe, so both the provision-mint (default `createStore` factory) and the boot
|
|
305
310
|
// create (below) resolve the OPFS-repacked backend. False is the honest capability-absence invariant — the
|
|
306
311
|
// engine home in this scope opens IDBFS: the registry-declared `backend: "idbfs"` mode (no probe ran), or a
|
|
307
312
|
// capability-absence fallback (every home's probe denied / the OPFS API absent). Read at CALL time — every mint
|
|
@@ -346,31 +351,67 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
346
351
|
// provision payload bound the declaration (a construction-time constant could never see a wire declaration).
|
|
347
352
|
const currentDurability = () =>
|
|
348
353
|
engineStorage?.durability ?? getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
|
|
349
|
-
|
|
350
|
-
|
|
354
|
+
// The declared build (ADR-0063), read at mint time for the same reason as durability.
|
|
355
|
+
const currentBuild = () => engineStorage?.build ?? getSyncRegistryStorage(options.registry)?.build ?? "c";
|
|
356
|
+
const builtInCreateStore: StoreEngineFactory =
|
|
357
|
+
options.createStore ??
|
|
351
358
|
((storePath: string, backendOverride?: "memory") =>
|
|
352
|
-
|
|
359
|
+
createPgwasmClient(storePath, {
|
|
353
360
|
...(backendOverride ? { backendOverride } : {}),
|
|
361
|
+
// The worker's build, checked against the declaration before the mint touches a store.
|
|
362
|
+
...(options.build ? { build: options.build } : {}),
|
|
363
|
+
declaredBuild: currentBuild(),
|
|
364
|
+
buildCheckSite: "defineSyncWorker",
|
|
354
365
|
durability: currentDurability(),
|
|
355
366
|
// SW-direct placement grant (ADR-0049 D1): a spare minted in-scope opens OPFS-repacked, matching the boot.
|
|
356
367
|
...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
357
368
|
}));
|
|
369
|
+
// The DECLARED store engine (ADR-0050 addendum 2026-09-08). A store whose bound declaration carries
|
|
370
|
+
// `storage.engine` is minted by THAT module, not by the built-in factory — generically: the toolkit
|
|
371
|
+
// imports a module URL and calls its `createStore`, and knows nothing else about the engine behind it.
|
|
372
|
+
// Resolved per module URL and memoized (rejections included) for this scope's lifetime.
|
|
373
|
+
const resolveStoreEngine = createStoreEngineResolver(options.loadStoreEngineModule);
|
|
374
|
+
// Read at MINT time, never at construction: the declaration arrives on the first provision/attach payload,
|
|
375
|
+
// long after this closure is built, and it is immutable once bound — so every mint of this store resolves
|
|
376
|
+
// the same engine. A declared module that will not load or exports no factory throws LOUDLY here; it never
|
|
377
|
+
// degrades to the built-in store, which would report a healthy engine for one that never ran.
|
|
378
|
+
// Every store this factory returns is checked against the declared build (ADR-0063) on its own `pg.build`:
|
|
379
|
+
// a caller's `createStore` or a declared engine module may run any build, whatever `options.build` says.
|
|
380
|
+
const createStore: StoreEngineFactory = async (storePath, backendOverride) => {
|
|
381
|
+
const declaredEngine = engineStorage?.engine?.module;
|
|
382
|
+
let store: PgwasmClient;
|
|
383
|
+
if (declaredEngine === undefined) {
|
|
384
|
+
store = await builtInCreateStore(storePath, backendOverride);
|
|
385
|
+
} else {
|
|
386
|
+
const factory = await resolveStoreEngine(declaredEngine);
|
|
387
|
+
syncDebug("worker store engine declared", { storePath, module: declaredEngine });
|
|
388
|
+
store = await factory(storePath, backendOverride);
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
assertStoreBuild(currentBuild(), store.build, "createStore");
|
|
392
|
+
} catch (error) {
|
|
393
|
+
// Refused before any use: release the store's handles (an OPFS store holds exclusive ones) and propagate.
|
|
394
|
+
await store.close().catch(() => undefined);
|
|
395
|
+
throw error;
|
|
396
|
+
}
|
|
397
|
+
return store;
|
|
398
|
+
};
|
|
358
399
|
// A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
|
|
359
|
-
// non-persistent BYO store (`
|
|
400
|
+
// non-persistent BYO store (`precreatedPgwasm` / `pgwasmInstance` / a memory-returning `createStore`),
|
|
360
401
|
// which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
|
|
361
402
|
// sets it; a memory selection carried on the attach wire wins over it.
|
|
362
403
|
const workerTestMarker = readTestStoreMarker(options);
|
|
363
404
|
|
|
364
405
|
const ports = new Set<BridgePort>();
|
|
365
406
|
const liveSubs = new Map<string, LiveSub>();
|
|
366
|
-
// The live-query lifecycle (
|
|
407
|
+
// The live-query lifecycle (pgwasm registration, diff listener, and the ADR-0040 decision-1 awaited-teardown
|
|
367
408
|
// set) lives in a single manager owned per engine. Created lazily on first subscribe because it needs the
|
|
368
|
-
// booted client's `live` namespace (`active.
|
|
409
|
+
// booted client's `live` namespace (`active.pgwasm.live`); the worker never restarts its engine in place
|
|
369
410
|
// (ADR-0040 decision 7), so one manager serves the host's whole lifetime. `close()` disposes it.
|
|
370
411
|
let liveManager: LiveQueryManager | null = null;
|
|
371
412
|
const ensureLiveManager = (active: SyncClient<TRegistry>): LiveQueryManager =>
|
|
372
413
|
(liveManager ??= createLiveQueryManager({
|
|
373
|
-
live: active.
|
|
414
|
+
live: active.pgwasm.live,
|
|
374
415
|
...(options.liveQueries ? { policy: options.liveQueries } : {}),
|
|
375
416
|
}));
|
|
376
417
|
// Subscribes that have entered `handleSubscribe` but not yet reached `liveSubs.set` (they are mid-await on
|
|
@@ -399,14 +440,14 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
399
440
|
};
|
|
400
441
|
|
|
401
442
|
// ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────
|
|
402
|
-
// A `provision` mints the raw
|
|
403
|
-
// adopts it as `
|
|
443
|
+
// A `provision` mints the raw pgwasm (initdb only) and holds it idle here; the first real `attach`
|
|
444
|
+
// adopts it as `precreatedPgwasm` (the client still runs schema/journal recovery/reconcile). Provision
|
|
404
445
|
// is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.
|
|
405
446
|
// `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost
|
|
406
|
-
// as `BootReport.provision` (with `phases.
|
|
447
|
+
// as `BootReport.provision` (with `phases.pgwasmCreateMs = null`) instead of timing a create it never ran.
|
|
407
448
|
let provisioned: {
|
|
408
449
|
storePath: string;
|
|
409
|
-
|
|
450
|
+
pgwasm: Promise<PgwasmClient>;
|
|
410
451
|
stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
|
|
411
452
|
} | null = null;
|
|
412
453
|
// A provision request performs a bounded authority read before it may mint. An attach that arrives during
|
|
@@ -497,6 +538,38 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
497
538
|
}
|
|
498
539
|
};
|
|
499
540
|
|
|
541
|
+
// ─── The started-state snapshot (ADR-0059) ───────────────────────────────────────────────────────
|
|
542
|
+
// `client.isSynced` is a SYNCHRONOUS peek, so a tab cannot RPC for it. The worker therefore asks ITS OWN
|
|
543
|
+
// CLIENT — `isSynced(key)` for every key of the booted registry — and pushes the result; the tab answers
|
|
544
|
+
// out of that cache, so its answer is whatever the in-process client would have said. Faithful by
|
|
545
|
+
// construction: the promoted-group case (started from boot while its subscribe still retries), the
|
|
546
|
+
// sync-pending window and ADR-0021's sync-disabled clause all come along for free, and none of it is
|
|
547
|
+
// re-derived from the strictly weaker per-group catch-up readiness. Keyed by TABLE, so the tab needs no
|
|
548
|
+
// table→group mapping. `lastSyncedSnapshot` dedupes the broadcast — a recompute is cheap (the registry is
|
|
549
|
+
// small), an event for an unchanged answer is not.
|
|
550
|
+
let lastSyncedSnapshot: Record<string, boolean> | null = null;
|
|
551
|
+
const computeSyncedSnapshot = (active: SyncClient<TRegistry>): Record<string, boolean> => {
|
|
552
|
+
const snapshot: Record<string, boolean> = {};
|
|
553
|
+
for (const key of Object.keys(bootedRegistry ?? options.registry)) {
|
|
554
|
+
snapshot[key] = active.isSynced(key as SyncTableName<TRegistry>);
|
|
555
|
+
}
|
|
556
|
+
return snapshot;
|
|
557
|
+
};
|
|
558
|
+
const sameSnapshot = (a: Record<string, boolean>, b: Record<string, boolean>): boolean => {
|
|
559
|
+
const keys = Object.keys(a);
|
|
560
|
+
if (keys.length !== Object.keys(b).length) return false;
|
|
561
|
+
return keys.every((key) => a[key] === b[key]);
|
|
562
|
+
};
|
|
563
|
+
/** Recompute and broadcast the snapshot when (and only when) the answer changed. A no-op before boot. */
|
|
564
|
+
const publishSyncedIfChanged = (): void => {
|
|
565
|
+
const active = client;
|
|
566
|
+
if (active == null) return;
|
|
567
|
+
const snapshot = computeSyncedSnapshot(active);
|
|
568
|
+
if (lastSyncedSnapshot != null && sameSnapshot(lastSyncedSnapshot, snapshot)) return;
|
|
569
|
+
lastSyncedSnapshot = snapshot;
|
|
570
|
+
broadcastEvent({ kind: "synced", tables: snapshot });
|
|
571
|
+
};
|
|
572
|
+
|
|
500
573
|
const emitStatus = (status: SyncRuntimeStatus) => {
|
|
501
574
|
broadcastEvent({ kind: "status", status });
|
|
502
575
|
// Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the
|
|
@@ -507,6 +580,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
507
580
|
broadcastEvent({ kind: "groupReady", groupKey });
|
|
508
581
|
}
|
|
509
582
|
}
|
|
583
|
+
// A status transition accompanies every group-readiness edge and the sync-pending→wired crossing, so the
|
|
584
|
+
// started state can have moved (ADR-0059). Deduped, so a status change that moved nothing posts nothing.
|
|
585
|
+
publishSyncedIfChanged();
|
|
510
586
|
};
|
|
511
587
|
|
|
512
588
|
// ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────
|
|
@@ -515,6 +591,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
515
591
|
// The role the engine actually booted with (from the FIRST attach's config). Later attaches compare
|
|
516
592
|
// their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.
|
|
517
593
|
let bootedRole: string | undefined;
|
|
594
|
+
// The registry the engine actually booted with — `options.registry`, or the role variant `resolveRegistry`
|
|
595
|
+
// picked (ADR-0032 S3). The started-state snapshot (ADR-0059) enumerates THIS registry's keys, so a
|
|
596
|
+
// role-selected variant reports its own relations rather than the default's.
|
|
597
|
+
let bootedRegistry: TRegistry | null = null;
|
|
518
598
|
// The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase
|
|
519
599
|
// later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether
|
|
520
600
|
// it has fired and tell the ack (ADR-0032 FIX 3).
|
|
@@ -540,6 +620,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
540
620
|
if (milestones[stage]) return;
|
|
541
621
|
milestones[stage] = true;
|
|
542
622
|
broadcastEvent({ kind: "milestone", stage });
|
|
623
|
+
// `bootSettled` is the background tail's completion — sync START done, so a promoted lazy-persistent
|
|
624
|
+
// group is now started and every buffered activation has been replayed (ADR-0041/ADR-0021). That is a
|
|
625
|
+
// started-state edge no status transition is guaranteed to carry, so publish here too (ADR-0059).
|
|
626
|
+
// `failMilestone` needs no counterpart: a tail that failed never wired sync, so nothing started.
|
|
627
|
+
publishSyncedIfChanged();
|
|
543
628
|
};
|
|
544
629
|
const failMilestone = (stage: BootMilestone, error: unknown) => {
|
|
545
630
|
if (stageErrors[stage]) return;
|
|
@@ -614,6 +699,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
614
699
|
// Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
|
|
615
700
|
// and the claim/attach settles which one boots — the spare was provisioned before the role was known.
|
|
616
701
|
const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
|
|
702
|
+
bootedRegistry = registry;
|
|
617
703
|
// ADR-0050: placement and engine binding were resolved against `options.registry`'s static declaration —
|
|
618
704
|
// the spare was placed before any role existed, so a role-selected registry cannot re-home the store. A
|
|
619
705
|
// role registry whose static declaration EXPLICITLY conflicts with that bound resolution is refused typed
|
|
@@ -627,7 +713,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
627
713
|
}
|
|
628
714
|
// storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
|
|
629
715
|
// `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the
|
|
630
|
-
//
|
|
716
|
+
// pgwasm store lives at `storePath` — so the provisioned store's path must be what we adopt on.
|
|
631
717
|
// `storeId` is only a last-ditch fallback for a caller that passes it as the store path.
|
|
632
718
|
const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
|
|
633
719
|
// The testing memory-backend override rides as an explicit wire field (a symbol does not survive
|
|
@@ -643,15 +729,15 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
643
729
|
const restoreFrom = attach.restore
|
|
644
730
|
? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })
|
|
645
731
|
: undefined;
|
|
646
|
-
// Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `
|
|
732
|
+
// Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPgwasm`;
|
|
647
733
|
// createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.
|
|
648
734
|
// Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).
|
|
649
735
|
const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;
|
|
650
|
-
const
|
|
651
|
-
? provisioned!.
|
|
736
|
+
const precreatedPgwasm = adoptingProvisioned
|
|
737
|
+
? provisioned!.pgwasm
|
|
652
738
|
: restoreFrom
|
|
653
739
|
? undefined
|
|
654
|
-
: options.
|
|
740
|
+
: options.precreatedPgwasm;
|
|
655
741
|
// The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.
|
|
656
742
|
const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;
|
|
657
743
|
if (adoptingProvisioned) {
|
|
@@ -684,8 +770,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
684
770
|
// omitted only for a plain test/Node scope with no browser placement.
|
|
685
771
|
...(placementEngineHome ? { engineHome: placementEngineHome } : {}),
|
|
686
772
|
...(provisionStamp ? { provisionStamp } : {}),
|
|
687
|
-
...(
|
|
688
|
-
...(options.
|
|
773
|
+
...(precreatedPgwasm ? { precreatedPgwasm } : {}),
|
|
774
|
+
...(options.pgwasmInstance && restoreFrom == null ? { pgwasmInstance: options.pgwasmInstance } : {}),
|
|
775
|
+
// The worker's build (ADR-0063) for the boot's own mint; `createSyncClient` checks it against the bound
|
|
776
|
+
// declaration before any store is touched.
|
|
777
|
+
...(options.build ? { build: options.build } : {}),
|
|
689
778
|
// App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
|
|
690
779
|
// the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
|
|
691
780
|
...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
|
|
@@ -698,7 +787,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
698
787
|
// SW-direct placement grant (ADR-0049 D1): thread a GRANTED probe's grant into the boot create so the engine
|
|
699
788
|
// home in this SharedWorker scope opens the OPFS-repacked backend. Absent (false) is the honest IDBFS home —
|
|
700
789
|
// the declared `backend: "idbfs"` mode or a capability-absence fallback. `createSyncClient` forwards it to
|
|
701
|
-
// its `
|
|
790
|
+
// its `createPgwasmClient` boot create.
|
|
702
791
|
...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
703
792
|
// ADR-0049 D1/D12: on a capability-absence fallback (OPFS was capable but no home could hold handles) the
|
|
704
793
|
// engine boots IDBFS and stamps this verbatim reason into the BootReport's `storageFallbackReason`. Absent
|
|
@@ -756,7 +845,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
756
845
|
booted.onOutboxStatus((status) => broadcastEvent({ kind: "outbox-status", status }));
|
|
757
846
|
booted.onEventLaneReport((report) => broadcastEvent({ kind: "event-lane-report", report }));
|
|
758
847
|
} catch (error) {
|
|
759
|
-
// A client with no Event lane (a non-canonical write URL, or a caller-owned
|
|
848
|
+
// A client with no Event lane (a non-canonical write URL, or a caller-owned pgwasm) refuses these
|
|
760
849
|
// subscriptions. Nothing to bridge then — the RPCs refuse identically, so the tab still gets the
|
|
761
850
|
// honest error at its own call site.
|
|
762
851
|
syncDebug("worker: no Event lane to bridge", { error });
|
|
@@ -767,9 +856,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
767
856
|
const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
|
|
768
857
|
// Guarded-read parser re-application (ADR-0032 decision 4). A guarded read compiled by the tab's
|
|
769
858
|
// Drizzle-over-bridge arrives as the {@link GuardedQueryWireArgs} tuple `[sql, params?, { rowMode? }, use?]`:
|
|
770
|
-
// the `parsers` map drizzle
|
|
859
|
+
// the `parsers` map the pgwasm drizzle session normally passes could not cross the bridge (it is FUNCTIONS,
|
|
771
860
|
// not clonable), so the tab stripped it and we re-apply the identical map here before executing. Without it
|
|
772
|
-
//
|
|
861
|
+
// pgwasm's default parsers would turn the identity-parsed OIDs (temporal OIDs + `numeric[]`) into `Date`s
|
|
773
862
|
// and numbers, whereas the in-process drizzle session sees them as raw STRINGS — so a guarded read would
|
|
774
863
|
// diverge from its in-process twin exactly on those columns. Typed against `GuardedQueryWireArgs` so the
|
|
775
864
|
// decode here shares the wire contract with the tab-side encoders (attach-sync-client).
|
|
@@ -777,7 +866,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
777
866
|
const [sql, params, options, use] = args as unknown as GuardedQueryWireArgs;
|
|
778
867
|
const queryOptions: QueryOptions = {
|
|
779
868
|
...(options?.rowMode ? { rowMode: options.rowMode } : {}),
|
|
780
|
-
parsers:
|
|
869
|
+
parsers: drizzleParsers,
|
|
781
870
|
};
|
|
782
871
|
return active.guardedRawQuery(sql, params, queryOptions, use as readonly SyncTableName<TRegistry>[] | undefined);
|
|
783
872
|
};
|
|
@@ -848,13 +937,25 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
848
937
|
case "diagnostics":
|
|
849
938
|
return active.diagnostics(args[0] as TableKey | undefined);
|
|
850
939
|
case "rawQuery":
|
|
851
|
-
// Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.
|
|
940
|
+
// Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pgwasm`
|
|
852
941
|
// exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across
|
|
853
942
|
// the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.
|
|
854
|
-
// The options arg is the clonable RawQueryOptions subset (rowMode
|
|
943
|
+
// The options arg is the clonable RawQueryOptions subset (rowMode, plus the ADR-0061 COPY `blob`).
|
|
855
944
|
return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
|
|
856
945
|
case "rawExec":
|
|
857
946
|
return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
|
|
947
|
+
case "rawTransaction":
|
|
948
|
+
// The atomic raw seam: the whole statement list crossed in ONE dispatch, so the transaction begins
|
|
949
|
+
// and ends inside this call on the worker's own store — the tab can never hold one open. Statements
|
|
950
|
+
// are `{ sql, params, blob? }` plain objects (structured-clone safe), and the `Results[]` returns
|
|
951
|
+
// the same way `rawExec`'s does.
|
|
952
|
+
//
|
|
953
|
+
// NOTHING is rebuilt here for a COPY statement's `blob` (ADR-0061). The tab listed each body's
|
|
954
|
+
// `ArrayBuffer` on the dispatch's transfer list, and a `Uint8Array` survives structured clone AS a
|
|
955
|
+
// `Uint8Array` view over the transferred (zero-copy) buffer — so `args[0]` is already exactly the
|
|
956
|
+
// `RawStatement[]` the in-process client takes, and the single `Uint8Array → Blob` wrap lives where
|
|
957
|
+
// it does in-process: inside that client, at the pgwasm call. The tab's buffers are now detached.
|
|
958
|
+
return active.rawTransaction(args[0] as readonly RawStatement[], args[1] as RawQueryOptions);
|
|
858
959
|
case "guardedQuery":
|
|
859
960
|
// Guarded one-shot Drizzle read (ADR-0032 decision 4): the ADR-0041 read gate + the ADR-0021
|
|
860
961
|
// lazy-group guard run worker-side inside the engine's `guardedRawQuery`, so a read referencing a
|
|
@@ -956,6 +1057,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
956
1057
|
// state / sync disabled) → no `hydrated` gating at all; otherwise it drives both the `live-initial`
|
|
957
1058
|
// `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.
|
|
958
1059
|
const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });
|
|
1060
|
+
// The guard above starts any lazy relation this subscription reads, exactly as a one-shot read's does —
|
|
1061
|
+
// so publish the new started state (ADR-0059) BEFORE the initial snapshot is posted below, keeping the
|
|
1062
|
+
// same ordering the RPC path has: when the tab's `subscribeLiveRows` resolves, `isSynced` already agrees.
|
|
1063
|
+
publishSyncedIfChanged();
|
|
959
1064
|
|
|
960
1065
|
// Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
|
|
961
1066
|
// creation (`column "title" specified more than once`) unless every output column has a unique alias.
|
|
@@ -1058,7 +1163,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1058
1163
|
const provision = payload as ProvisionPayload;
|
|
1059
1164
|
const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
|
|
1060
1165
|
// The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
|
|
1061
|
-
// survive structured clone, so the store's backend selection travels here and is passed to
|
|
1166
|
+
// survive structured clone, so the store's backend selection travels here and is passed to createStore.
|
|
1062
1167
|
const backendOverride = provision.testStoreBackend;
|
|
1063
1168
|
// ADR-0050: bind (or confirm) the store's storage declaration BEFORE the mint — the mint's durability
|
|
1064
1169
|
// comes from it. An explicit disagreement with the bound declaration refuses THIS provision typed.
|
|
@@ -1178,17 +1283,17 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1178
1283
|
}
|
|
1179
1284
|
|
|
1180
1285
|
const provisionStartedAt = nowStamp();
|
|
1181
|
-
const
|
|
1182
|
-
const stamp =
|
|
1286
|
+
const pgwasm = Promise.resolve().then(() => createStore(storePath, backendOverride));
|
|
1287
|
+
const stamp = pgwasm.then(() => {
|
|
1183
1288
|
const readyAt = nowStamp();
|
|
1184
1289
|
return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
|
|
1185
1290
|
});
|
|
1186
|
-
provisioned = { storePath,
|
|
1291
|
+
provisioned = { storePath, pgwasm, stamp };
|
|
1187
1292
|
// Guard unobserved rejections when no attach ever adopts the spare (the page navigated away).
|
|
1188
|
-
void
|
|
1293
|
+
void pgwasm.catch(() => undefined);
|
|
1189
1294
|
void stamp.catch(() => undefined);
|
|
1190
1295
|
syncDebug("worker store provisioned", { storePath });
|
|
1191
|
-
await
|
|
1296
|
+
await pgwasm;
|
|
1192
1297
|
});
|
|
1193
1298
|
provisionAttempt = attempt;
|
|
1194
1299
|
const attemptStartedAt = nowStamp();
|
|
@@ -1196,7 +1301,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1196
1301
|
provisionAttemptStorePath = storePath;
|
|
1197
1302
|
provisionAttemptPending = true;
|
|
1198
1303
|
// Heartbeat the pending attempt onto the rail so a stalled create is VISIBLE (the failure that
|
|
1199
|
-
// motivated the budget showed `boot
|
|
1304
|
+
// motivated the budget showed `boot pgwasm.create start` and then nothing at all). Cleared on
|
|
1200
1305
|
// settlement below, so it never outlives the attempt it reports on.
|
|
1201
1306
|
const heartbeat = setInterval(() => {
|
|
1202
1307
|
syncDebug("worker store provision still pending", {
|
|
@@ -1329,13 +1434,17 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1329
1434
|
alreadyBooted,
|
|
1330
1435
|
...(engineReadyFired ? { engineReady: true } : {}),
|
|
1331
1436
|
...milestoneAckFields(),
|
|
1437
|
+
// The started-state snapshot (ADR-0059). `attachSyncClient` resolves at THIS ack, and the
|
|
1438
|
+
// `status` event below is posted after it — so without this field the first synchronous
|
|
1439
|
+
// `isSynced` after attach (a microtask later) would answer from an empty cache.
|
|
1440
|
+
synced: computeSyncedSnapshot(booted),
|
|
1332
1441
|
});
|
|
1333
1442
|
postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
|
|
1334
1443
|
},
|
|
1335
1444
|
(error: unknown) => {
|
|
1336
1445
|
// The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of
|
|
1337
1446
|
// hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
|
|
1338
|
-
// boot. Do NOT clear `provisioned`: a resolved provisioned
|
|
1447
|
+
// boot. Do NOT clear `provisioned`: a resolved provisioned pgwasm holds the only open handle on
|
|
1339
1448
|
// that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
|
|
1340
1449
|
if (!alreadyBooted) bootPromise = null;
|
|
1341
1450
|
postBridgeMessage(port, codec, "attach-ack", {
|
|
@@ -1361,21 +1470,32 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1361
1470
|
const { op, args } = payload as RpcPayload;
|
|
1362
1471
|
const id = envelope.id;
|
|
1363
1472
|
void (async () => {
|
|
1473
|
+
let result: RpcResultPayload;
|
|
1474
|
+
// An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its
|
|
1475
|
+
// `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value
|
|
1476
|
+
// structured-clones in place with no transfer list.
|
|
1477
|
+
let transfer: BridgeTransferable[] | undefined;
|
|
1364
1478
|
try {
|
|
1365
1479
|
const active = client ?? (await bootPromise);
|
|
1366
1480
|
if (!active) throw new Error("rpc before attach");
|
|
1367
1481
|
const value = await dispatchRpc(active, op, args);
|
|
1368
|
-
|
|
1369
|
-
// `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value
|
|
1370
|
-
// structured-clones in place with no transfer list.
|
|
1371
|
-
const transfer =
|
|
1482
|
+
transfer =
|
|
1372
1483
|
op === "exportStore" || op === "exportDiagnostics" || op === "exportData"
|
|
1373
1484
|
? [(value as ExportArtefactWire).buffer]
|
|
1374
1485
|
: undefined;
|
|
1375
|
-
|
|
1486
|
+
result = { ok: true, value };
|
|
1376
1487
|
} catch (error) {
|
|
1377
|
-
|
|
1488
|
+
result = { ok: false, error: serializeError(error) };
|
|
1378
1489
|
}
|
|
1490
|
+
// ADR-0059's ordering guarantee, for EVERY op rather than a curated list: several ops move the
|
|
1491
|
+
// started state (`ensureSynced`/`desync`/`discardEphemeral` explicitly, a `guardedQuery` or an
|
|
1492
|
+
// ordinary write implicitly, through the guard) and a rejected one may have moved it before it
|
|
1493
|
+
// failed — so publish here, after the dispatch settled either way and BEFORE the result is posted.
|
|
1494
|
+
// Events and results share one port and `MessagePort` delivery is FIFO, so on the tab
|
|
1495
|
+
// `await client.ensureSynced(["x"]); client.isSynced("x")` is already true. Deduped: an op that
|
|
1496
|
+
// changed nothing posts no event.
|
|
1497
|
+
publishSyncedIfChanged();
|
|
1498
|
+
postBridgeMessage(port, codec, "rpc-result", result, id, transfer);
|
|
1379
1499
|
})();
|
|
1380
1500
|
break;
|
|
1381
1501
|
}
|
|
@@ -1930,6 +2050,15 @@ function invalidDeclarationField(declaration: SyncStorageDeclaration): string |
|
|
|
1930
2050
|
if (declaration.durability !== undefined && !isStorageDurability(declaration.durability)) {
|
|
1931
2051
|
return `durability "${String(declaration.durability)}"`;
|
|
1932
2052
|
}
|
|
2053
|
+
if (declaration.build !== undefined && !isStorageBuild(declaration.build)) {
|
|
2054
|
+
return `build "${String(declaration.build)}"`;
|
|
2055
|
+
}
|
|
2056
|
+
// ADR-0050 addendum 2026-09-08: a declared engine must be `{ module }` naming an absolute or
|
|
2057
|
+
// origin-relative module URL. A malformed one is refused here rather than at the first mint, so a
|
|
2058
|
+
// typo surfaces at the handshake instead of halfway through a boot.
|
|
2059
|
+
if (declaration.engine !== undefined && !isStorageEngineDeclaration(declaration.engine)) {
|
|
2060
|
+
return `engine ${JSON.stringify(declaration.engine)}`;
|
|
2061
|
+
}
|
|
1933
2062
|
return undefined;
|
|
1934
2063
|
}
|
|
1935
2064
|
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// On the DEFAULT configuration the retirement signals are the ones that carry actual EVIDENCE of death:
|
|
12
12
|
// the engine control port's `close` event (MessagePort `close` is Baseline, so this covers every current
|
|
13
13
|
// browser), the reported paths owned above this module (worker `error`, spawn failure, tab death), and
|
|
14
|
-
// the teardown handshake. SILENCE IS NEVER A VERDICT HERE (ADR-0049 D5):
|
|
14
|
+
// the teardown handshake. SILENCE IS NEVER A VERDICT HERE (ADR-0049 D5): pgwasm's synchronous WASM work
|
|
15
15
|
// blocks the engine's event loop, so a legitimate long import stalls the control channel exactly as a
|
|
16
16
|
// corpse does. Timing therefore lives entirely behind the OPT-IN execution limit — with it enabled, an
|
|
17
17
|
// unacked `connect-port` and a tab-reported overdue dispatch both hand the question to the probe loop,
|