@pgxsinkit/client 0.2.7 → 0.5.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/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +11 -3
- package/dist/boot-report.d.ts +11 -8
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +39 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +96 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.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 +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +237 -113
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7037 -6665
- package/dist/index.js.map +46 -43
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +59 -1
- 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.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 +40 -28
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +17 -25
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +84 -8
- 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/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +26 -7
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +4 -3
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +27 -14
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +52 -19
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.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/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -9
- package/skills/core/SKILL.md +145 -63
- package/skills/operating/SKILL.md +221 -221
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +13 -12
- package/src/circuits/envelope-to-change.ts +211 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +191 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +643 -0
- package/src/debug.ts +1 -85
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +24 -28
- package/src/export-store.ts +17 -17
- package/src/index.ts +797 -544
- package/src/lazy-guard.ts +1 -1
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +76 -5
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +126 -29
- 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 +56 -40
- package/src/sync/apply.ts +104 -156
- package/src/sync/copy.ts +116 -21
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +43 -2
- package/src/sync/subscription-state.ts +28 -10
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +4 -4
- package/src/worker/attach-sync-client.ts +150 -57
- package/src/worker/define-sync-worker.ts +325 -87
- package/src/worker/engine-control.ts +89 -0
- 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 +10 -10
- package/src/worker/protocol.ts +38 -7
- package/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
|
@@ -8,12 +8,10 @@
|
|
|
8
8
|
// `drizzle`/`views` here are a real Drizzle database over a bridge executor whose `query` routes each read to
|
|
9
9
|
// the worker's `guardedQuery` RPC, so awaiting a builder runs the ADR-0041 read gate + the ADR-0021
|
|
10
10
|
// lazy-group guard worker-side and Drizzle's own result mapping (relational/nested included) runs on the tab.
|
|
11
|
-
// `ensureSynced` (async lazy-activation) is a plain RPC to the shared engine
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
|
|
16
|
-
import type { Results } from "@electric-sql/pglite";
|
|
11
|
+
// `ensureSynced` (async lazy-activation) is a plain RPC to the shared engine, and `isSynced` — a SYNCHRONOUS
|
|
12
|
+
// peek, so never an RPC — is answered from the started-state snapshot the worker computes on its own client
|
|
13
|
+
// and pushes (ADR-0059). The only members that stay unsupported are the genuinely tab-local ones — `pglite`
|
|
14
|
+
// (no local store) and `dropReadCache` (an engine-wide cache rebuild) — each throwing a clear error saying why.
|
|
17
15
|
|
|
18
16
|
import type {
|
|
19
17
|
MutationDiagnostics,
|
|
@@ -24,6 +22,7 @@ import type {
|
|
|
24
22
|
WriteMode,
|
|
25
23
|
} from "@pgxsinkit/contracts";
|
|
26
24
|
import { StorageDeclarationRefusedError } from "@pgxsinkit/contracts";
|
|
25
|
+
import type { Results } from "@pgxsinkit/pgwasm";
|
|
27
26
|
|
|
28
27
|
import type { BootReport } from "../boot-report";
|
|
29
28
|
import { syncDebug } from "../debug";
|
|
@@ -33,7 +32,7 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
|
|
|
33
32
|
import type { StoreExportOptions, StoreExportResult } from "../export-store";
|
|
34
33
|
import {
|
|
35
34
|
buildRegistryReadHandles,
|
|
36
|
-
type
|
|
35
|
+
type PgwasmClient,
|
|
37
36
|
ClientDisposedError,
|
|
38
37
|
createMutationsApi,
|
|
39
38
|
type LiveQueryDiagnostics,
|
|
@@ -46,10 +45,15 @@ import {
|
|
|
46
45
|
type SyncTransactionResult,
|
|
47
46
|
} from "../index";
|
|
48
47
|
import type { LocalStoreVersionEvent } from "../local-store";
|
|
49
|
-
import { createOpfsEffects, type OpfsEffectsDeps } from "../opfs-effects";
|
|
48
|
+
import { createOpfsEffects, isOpfsRootUnavailableError, type OpfsEffectsDeps } from "../opfs-effects";
|
|
50
49
|
import { committedStoreUnreachableFromWire } from "../store-boot";
|
|
51
50
|
import { type DestructionEffects, runDestruction } from "../store-lifecycle";
|
|
52
|
-
import {
|
|
51
|
+
import {
|
|
52
|
+
deleteStoreMetaRecord,
|
|
53
|
+
type StoreMetaDeps,
|
|
54
|
+
writeOpfsDeletionPending,
|
|
55
|
+
writeStoreMetaRecord,
|
|
56
|
+
} from "../store-meta";
|
|
53
57
|
import { storeIndexedDbDatabaseName } from "../store-path";
|
|
54
58
|
import { readTestStoreMarker } from "../store-path";
|
|
55
59
|
import {
|
|
@@ -78,6 +82,7 @@ import {
|
|
|
78
82
|
executionLimitMismatchFromWire,
|
|
79
83
|
type ExecutionLimitConfig,
|
|
80
84
|
isStaleIdentity,
|
|
85
|
+
provisionStalledFromWire,
|
|
81
86
|
readControlEnvelope,
|
|
82
87
|
wrapControlEnvelope,
|
|
83
88
|
} from "./engine-control";
|
|
@@ -149,10 +154,10 @@ export interface ElectedEngineWorker {
|
|
|
149
154
|
/**
|
|
150
155
|
* The default {@link AttachSyncClientOptions.awaitOwnershipRelease} — a documented NO-OP (ADR-0049 step 11b
|
|
151
156
|
* follow-up 1). The OPFS-repacked VFS enforces single-owner access with EXCLUSIVE OPFS sync-access handles
|
|
152
|
-
* (`StoreOwnedError`)
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
157
|
+
* (`StoreOwnedError`). The wait for the dead worker's agent to release the handles lives in the SUCCESSOR'S OPEN
|
|
158
|
+
* PATH: the respawned engine first takes the store's ownership Web Lock (`store-ownership-lock.ts`), which the
|
|
159
|
+
* predecessor holds until its handles are closed or its context is gone, then its `createOpfsPgwasm` open retries
|
|
160
|
+
* on any residual owned-store contention (the `openWithBoundedRetries` wrapper) — the fault-matrix row.
|
|
156
161
|
* So the coordinator can respawn immediately after a deliberate terminate; its VFS open is the real gate.
|
|
157
162
|
*/
|
|
158
163
|
export function resolvedOwnershipRelease(): Promise<void> {
|
|
@@ -228,7 +233,9 @@ export class ElectedEngineUnconstructibleError extends Error {
|
|
|
228
233
|
*
|
|
229
234
|
* - **SW-direct.** The attempt lives in the SharedWorker and is left running (an in-flight store open cannot be
|
|
230
235
|
* safely abandoned — a second open against the same store is an ownership conflict). A later
|
|
231
|
-
* {@link attachSyncClient} ADOPTS it if it completed and
|
|
236
|
+
* {@link attachSyncClient} ADOPTS it if it completed, and waits on a genuinely stuck one only within the
|
|
237
|
+
* engine's spare-store adoption budget (`provisionAdoptionBudgetMs`, default 20000 from the attempt's start),
|
|
238
|
+
* past which that attach is refused with {@link ProvisionStalledError} instead of hanging; a retried
|
|
232
239
|
* provision re-acks against the SAME attempt, so a second open never starts. A stuck storage open blocks that
|
|
233
240
|
* store whether or not it was ever provisioned, and expiring this promise neither causes nor cures that.
|
|
234
241
|
* - **Elected.** This deadline is ALSO the provision claim's expiry, so the claim releases here too. When it is
|
|
@@ -277,7 +284,7 @@ function resolveIdbDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undef
|
|
|
277
284
|
return (globalThis as { indexedDB?: IdbDeleteSurface }).indexedDB;
|
|
278
285
|
}
|
|
279
286
|
|
|
280
|
-
/** Delete-if-present the store's
|
|
287
|
+
/** Delete-if-present the store's pgwasm idb database; only `onsuccess` proves completion. */
|
|
281
288
|
function deleteStoreIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
|
|
282
289
|
const idb = resolveIdbDeleteSurface(meta);
|
|
283
290
|
if (idb?.deleteDatabase == null) return Promise.resolve();
|
|
@@ -313,10 +320,19 @@ function deleteStoreIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promis
|
|
|
313
320
|
|
|
314
321
|
/**
|
|
315
322
|
* Build the REAL {@link DestructionEffects} for a store — the OPFS commitment sentinel + store directory
|
|
316
|
-
* (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the
|
|
323
|
+
* (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the pgwasm idb database. The destruction machine is
|
|
317
324
|
* backend-agnostic (`store-lifecycle.ts`): `deleteBackendStore` delete-if-presents BOTH the OPFS directory and
|
|
318
325
|
* the idb database, so it works whichever backend the store used. Injectable IO (`opfs`/`meta`) so the wiring is
|
|
319
326
|
* unit-testable with fakes.
|
|
327
|
+
*
|
|
328
|
+
* **A context that cannot open OPFS at all** (ADR-0036 amendment, 2026-09-28): when an OPFS delete meets a root
|
|
329
|
+
* that rejects ({@link isOpfsRootUnavailableError} — WebKit's throwaway contexts, probably Safari private windows)
|
|
330
|
+
* the store there runs on IndexedDB, and destroy removes what it CAN reach: it durably records "OPFS deletion
|
|
331
|
+
* pending" for the store identity (in IndexedDB, {@link writeOpfsDeletionPending}) and carries on with the idb
|
|
332
|
+
* database and the meta record. The marker is written from the sentinel step, i.e. while the `deleting` record
|
|
333
|
+
* still stands, so the obligation to delete the OPFS side is never unrecorded; the next boot that can reach OPFS
|
|
334
|
+
* finishes it before opening anything (`store-boot.ts`). With no IndexedDB to record it in, the original failure
|
|
335
|
+
* propagates. A context that can open OPFS takes exactly the old path (ownership lock included).
|
|
320
336
|
*/
|
|
321
337
|
export function createStoreDestructionEffects(
|
|
322
338
|
storePath: string,
|
|
@@ -324,11 +340,19 @@ export function createStoreDestructionEffects(
|
|
|
324
340
|
): DestructionEffects {
|
|
325
341
|
const opfs = createOpfsEffects(storePath, deps?.opfs);
|
|
326
342
|
const meta = deps?.meta;
|
|
343
|
+
const deleteOpfsOrRecordPending = async (deleteOpfs: () => Promise<void>): Promise<void> => {
|
|
344
|
+
try {
|
|
345
|
+
await deleteOpfs();
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (!isOpfsRootUnavailableError(error)) throw error;
|
|
348
|
+
if (!(await writeOpfsDeletionPending(storePath, meta))) throw error;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
327
351
|
return {
|
|
328
352
|
setPhase: (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, meta),
|
|
329
|
-
deleteSentinel: () => opfs.deleteSentinel(),
|
|
353
|
+
deleteSentinel: () => deleteOpfsOrRecordPending(() => opfs.deleteSentinel()),
|
|
330
354
|
deleteBackendStore: async () => {
|
|
331
|
-
await opfs.deleteStoreDirectory();
|
|
355
|
+
await deleteOpfsOrRecordPending(() => opfs.deleteStoreDirectory());
|
|
332
356
|
await deleteStoreIdbDatabase(storePath, meta);
|
|
333
357
|
},
|
|
334
358
|
deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta),
|
|
@@ -343,8 +367,10 @@ export function createStoreDestructionEffects(
|
|
|
343
367
|
* **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
|
|
344
368
|
* supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
|
|
345
369
|
* `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
|
|
346
|
-
* behind, a wipe of known store paths.
|
|
347
|
-
*
|
|
370
|
+
* behind, a wipe of known store paths. The OPFS delete first takes the store's ownership lock
|
|
371
|
+
* (`store-ownership-lock.ts`), so an owner that is still going away (a reloaded page's dying engine worker) is
|
|
372
|
+
* waited for, never raced. Called on a path a live engine still holds, it fails with `StoreOwnershipWaitError`
|
|
373
|
+
* after the bounded wait — loud, and safely RE-RUNNABLE: the destruction sequence is
|
|
348
374
|
* idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
|
|
349
375
|
* completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
|
|
350
376
|
* already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
|
|
@@ -585,8 +611,32 @@ const MUTATION_RPC_OPS: ReadonlySet<RpcOp> = new Set<RpcOp>([
|
|
|
585
611
|
// `rawExec` is WRITE-CAPABLE (its docstring: any write it issues stays local and will NOT converge), so a
|
|
586
612
|
// dispatched rawExec with a lost response is `"unknown"` — retrying could double-apply a local write.
|
|
587
613
|
"rawExec",
|
|
614
|
+
// `rawTransaction` for the same reason, and more sharply: its statement list exists to WRITE atomically.
|
|
615
|
+
// Atomicity says nothing about whether the transaction committed before the response was lost — it says the
|
|
616
|
+
// store is in exactly one of the two states, and a lost response cannot tell the tab which. So `"unknown"`,
|
|
617
|
+
// never `"not-dispatched"`: a blind repeat of a committed delete-then-insert would re-apply it.
|
|
618
|
+
"rawTransaction",
|
|
588
619
|
]);
|
|
589
620
|
|
|
621
|
+
/**
|
|
622
|
+
* The DISTINCT `ArrayBuffer`s a raw-seam dispatch must transfer (ADR-0061): the COPY body of every
|
|
623
|
+
* statement (and of the call-level options) that carries one. Zero-copy is the whole point — a 1000-row
|
|
624
|
+
* chunk crosses the bridge without a structured-clone copy of its bytes — and the buffers are detached on
|
|
625
|
+
* the tab afterwards, which {@link RawStatement.blob} documents as the caller's contract.
|
|
626
|
+
*
|
|
627
|
+
* De-duplicated: `postMessage` throws on the same transferable listed twice, which two statements
|
|
628
|
+
* serialized into views over ONE buffer would otherwise produce.
|
|
629
|
+
*/
|
|
630
|
+
function copyBlobTransfers(
|
|
631
|
+
blobs: ReadonlyArray<Uint8Array<ArrayBuffer> | undefined>,
|
|
632
|
+
): BridgeTransferable[] | undefined {
|
|
633
|
+
const buffers = new Set<ArrayBuffer>();
|
|
634
|
+
for (const blob of blobs) {
|
|
635
|
+
if (blob !== undefined) buffers.add(blob.buffer);
|
|
636
|
+
}
|
|
637
|
+
return buffers.size > 0 ? [...buffers] : undefined;
|
|
638
|
+
}
|
|
639
|
+
|
|
590
640
|
export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
591
641
|
registry: TRegistry;
|
|
592
642
|
/**
|
|
@@ -723,8 +773,8 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
723
773
|
* OPFS-repacked VFS enforces ownership with EXCLUSIVE OPFS sync-access handles (`StoreOwnedError` /
|
|
724
774
|
* `STORE_OWNED`), NOT a Web Lock, so there is no lock name to `navigator.locks.request(..., { ifAvailable })`
|
|
725
775
|
* against here. The bounded wait therefore lives in the SUCCESSOR'S OPEN PATH: the respawned elected engine
|
|
726
|
-
* worker's own `
|
|
727
|
-
* (the `openWithBoundedRetries` wrapper in `
|
|
776
|
+
* worker's own `createOpfsPgwasm` open throws the owned-store contention error and is retried with backoff
|
|
777
|
+
* (the `openWithBoundedRetries` wrapper in `createPgwasmClient`) until the dead worker's agent releases the
|
|
728
778
|
* handle — exactly the fault-matrix row "VFS ownership-lock release lag → successor open retries on contention
|
|
729
779
|
* until clear, bounded, then boot failure". Supply a custom async wait only to inject a real probe (tests do).
|
|
730
780
|
*/
|
|
@@ -751,9 +801,9 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
751
801
|
/**
|
|
752
802
|
* The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
|
|
753
803
|
* token after an app auth-state change, ADR-0032 decision 3). One-shot Drizzle reads
|
|
754
|
-
* (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker
|
|
755
|
-
*
|
|
756
|
-
* `drizzle.transaction()`.
|
|
804
|
+
* (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker, and `isSynced`
|
|
805
|
+
* is answered from the worker-pushed started-state snapshot (ADR-0059); the members that throw are the
|
|
806
|
+
* structurally unproxiable ones — `pglite`, `dropReadCache`, and `drizzle.transaction()`.
|
|
757
807
|
*/
|
|
758
808
|
export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
|
|
759
809
|
notifyAuthChanged: () => void;
|
|
@@ -1129,6 +1179,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1129
1179
|
let readyResolved = false;
|
|
1130
1180
|
const readyGroups = new Set<string>();
|
|
1131
1181
|
const groupWaiters = new Map<string, Array<() => void>>();
|
|
1182
|
+
// The started-state snapshot `isSynced` answers from (ADR-0059) — per registry key, computed by the WORKER
|
|
1183
|
+
// by asking its own in-process client, folded off the `attach-ack` and refreshed by every `synced` event.
|
|
1184
|
+
// Nothing is derived here: `readyGroups` beside it is per-group CATCH-UP readiness, the strictly weaker
|
|
1185
|
+
// question, which reads a promoted-but-still-catching-up group as not started.
|
|
1186
|
+
let syncedTables: Record<string, boolean> = {};
|
|
1132
1187
|
|
|
1133
1188
|
// ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────
|
|
1134
1189
|
const pushToken = async () => {
|
|
@@ -1176,6 +1231,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1176
1231
|
markGroupReady(event.groupKey);
|
|
1177
1232
|
break;
|
|
1178
1233
|
}
|
|
1234
|
+
case "synced": {
|
|
1235
|
+
// The worker recomputed its own `isSynced` for every registry key and the answer changed. Replace
|
|
1236
|
+
// the cache wholesale — it is a full snapshot, never a delta (ADR-0059).
|
|
1237
|
+
syncedTables = event.tables;
|
|
1238
|
+
break;
|
|
1239
|
+
}
|
|
1179
1240
|
case "milestone": {
|
|
1180
1241
|
// Staged boot readiness (ADR-0041 stage 2): the engine crossed a background stage while this tab was
|
|
1181
1242
|
// attached. Idempotent with the ack's late-attach fold — whichever observes it first wins.
|
|
@@ -1281,6 +1342,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1281
1342
|
if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
|
|
1282
1343
|
if (ack.bootSettled) settleBootSettled();
|
|
1283
1344
|
if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));
|
|
1345
|
+
// The started-state snapshot (ADR-0059) — folded BEFORE the handshake resolves, so the first
|
|
1346
|
+
// synchronous `isSynced` a caller runs after `await attachSyncClient(…)` is already faithful
|
|
1347
|
+
// (the worker's `status` event is posted after this ack and has not been delivered yet).
|
|
1348
|
+
if (ack.synced) syncedTables = ack.synced;
|
|
1284
1349
|
const settle = pendingAttachAck;
|
|
1285
1350
|
pendingAttachAck = null;
|
|
1286
1351
|
settle?.resolve(ack);
|
|
@@ -1760,16 +1825,24 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1760
1825
|
};
|
|
1761
1826
|
|
|
1762
1827
|
// ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
|
|
1763
|
-
|
|
1828
|
+
// `transfer` (ADR-0061) declares payload-specific transferables for THIS dispatch — the `ArrayBuffer`s
|
|
1829
|
+
// behind a raw statement's COPY body — exactly as the restore handshake declares the backup's buffer.
|
|
1830
|
+
// They are TRANSFERRED, not cloned: zero-copy on the way in, and detached on the tab afterwards.
|
|
1831
|
+
const rpc = <T>(op: RpcOp, args: unknown[], transfer?: BridgeTransferable[]): Promise<T> => {
|
|
1764
1832
|
// A detached client has no live port listener, so a worker reply could never resolve this — reject at
|
|
1765
1833
|
// once rather than register a forever-pending waiter (ADR-0040 P2).
|
|
1766
1834
|
if (detached) return Promise.reject(detachError());
|
|
1767
|
-
|
|
1835
|
+
// A dispatch that TRANSFERRED bytes is a mutation regardless of op: its buffers are detached on the
|
|
1836
|
+
// tab, so "not-dispatched" (the read verdict, meaning "safe to repeat") would be a lie — the caller
|
|
1837
|
+
// has nothing left to repeat with. Only a DISPATCHED op is stamped this way; a queued op that never
|
|
1838
|
+
// left the tab still fails "not-dispatched" through the handoff queue, and its buffers are intact.
|
|
1839
|
+
const kind: "read" | "mutation" =
|
|
1840
|
+
MUTATION_RPC_OPS.has(op) || (transfer !== undefined && transfer.length > 0) ? "mutation" : "read";
|
|
1768
1841
|
return new Promise<T>((resolve, reject) => {
|
|
1769
1842
|
const dispatch = () => {
|
|
1770
1843
|
const id = newId("rpc");
|
|
1771
1844
|
rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject, kind });
|
|
1772
|
-
postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id);
|
|
1845
|
+
postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id, transfer);
|
|
1773
1846
|
armSilence();
|
|
1774
1847
|
armOverdue(id);
|
|
1775
1848
|
};
|
|
@@ -2153,8 +2226,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2153
2226
|
// ─── Assembled client ────────────────────────────────────────────────────────────────────────────
|
|
2154
2227
|
const notSupported = (name: string) => (): never => {
|
|
2155
2228
|
throw new Error(
|
|
2156
|
-
`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local
|
|
2157
|
-
`Direct store access (client.
|
|
2229
|
+
`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local pgwasm. ` +
|
|
2230
|
+
`Direct store access (client.pgwasm) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` +
|
|
2158
2231
|
`implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` +
|
|
2159
2232
|
`(ensureSynced), and the write API ARE proxied to the worker.`,
|
|
2160
2233
|
);
|
|
@@ -2181,7 +2254,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2181
2254
|
const options = rowMode ? { rowMode } : {};
|
|
2182
2255
|
return use ? [sql, params, options, use] : [sql, params, options];
|
|
2183
2256
|
};
|
|
2184
|
-
// A `
|
|
2257
|
+
// A `PgwasmClient`-shaped bridge executor Drizzle runs reads against (ADR-0032 decision 4). Drizzle's pglite
|
|
2185
2258
|
// driver calls only `client.query` for reads and `client.transaction` for `.transaction()`. `query` routes
|
|
2186
2259
|
// to the worker's `guardedQuery` RPC (stripping drizzle's non-serializable `parsers` to just `rowMode`; the
|
|
2187
2260
|
// worker re-applies drizzle's identity parsers) and returns the full `Results` so Drizzle's mapping runs on
|
|
@@ -2190,12 +2263,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2190
2263
|
// the builder in a microtask AFTER `queryRaw` returns, so a plain `query` issued synchronously in between
|
|
2191
2264
|
// would drain its executor first and consume the wrong call's `use`. A per-read scoped executor cannot
|
|
2192
2265
|
// cross-contaminate.
|
|
2193
|
-
const makeBridgeExecutor = (use?: readonly string[]):
|
|
2266
|
+
const makeBridgeExecutor = (use?: readonly string[]): PgwasmClient =>
|
|
2194
2267
|
({
|
|
2195
2268
|
query: (sql: string, params?: unknown[], options?: { rowMode?: "array" | "object" }): Promise<Results> =>
|
|
2196
2269
|
rpc<Results>("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
|
|
2197
2270
|
transaction: noBridgeTransaction,
|
|
2198
|
-
}) as unknown as
|
|
2271
|
+
}) as unknown as PgwasmClient;
|
|
2199
2272
|
// The base (no-`use`) bridge database `client.drizzle` exposes, plus the cached factory that mints a fresh
|
|
2200
2273
|
// database over a per-read `use`-carrying executor (the schema/relations are computed ONCE, ADR-0032
|
|
2201
2274
|
// decision 4). `views` are unchanged.
|
|
@@ -2213,9 +2286,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2213
2286
|
const client: AttachedSyncClient<TRegistry> = {
|
|
2214
2287
|
drizzle,
|
|
2215
2288
|
views,
|
|
2216
|
-
// The tab has no local
|
|
2289
|
+
// The tab has no local pgwasm; reads go through the live-rows bridge. Touching `.pgwasm` is a misuse
|
|
2217
2290
|
// — the real trap is installed as a NON-ENUMERABLE throwing getter after this literal (see below).
|
|
2218
|
-
|
|
2291
|
+
pgwasm: undefined as never,
|
|
2219
2292
|
tables: Object.fromEntries(
|
|
2220
2293
|
Object.keys(options.registry).map((tableKey) => [
|
|
2221
2294
|
tableKey,
|
|
@@ -2276,7 +2349,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2276
2349
|
// ADR-0053 decision 8, the Event lane's half of the same refusal. It rides the diagnostics round
|
|
2277
2350
|
// trip already taken above rather than a second one: the tab has no local Outbox (exactly as it has
|
|
2278
2351
|
// no local journal), and a destroy must not add a network-shaped hop it can avoid. Absent `outbox`
|
|
2279
|
-
// means the engine has no Event lane, which is not a reason to block a destroy
|
|
2352
|
+
// means the engine has no Event lane, which is not a reason to block a destroy — and neither is an
|
|
2353
|
+
// acked row the ledger is retaining (ADR-0060): it has had its verdict, so it reads as empty.
|
|
2280
2354
|
if (outbox?.empty === false) {
|
|
2281
2355
|
throw new Error(
|
|
2282
2356
|
"destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
|
|
@@ -2339,8 +2413,24 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2339
2413
|
readMutationDetails: (table) => rpc<MutationDetail[]>("readMutationDetails", [table]),
|
|
2340
2414
|
// Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`
|
|
2341
2415
|
// itself stays blocked (below); these route the raw statement over the RPC round-trip instead.
|
|
2342
|
-
|
|
2416
|
+
// `options.blob` (ADR-0061) makes this the single-statement COPY bulk load too: the bytes ride the SAME
|
|
2417
|
+
// RPC and are TRANSFERRED (detached tab-side), never cloned.
|
|
2418
|
+
rawQuery: (sql, params, options) =>
|
|
2419
|
+
rpc<Results>("rawQuery", [sql, params, options], copyBlobTransfers([options?.blob])),
|
|
2343
2420
|
rawExec: (sql, options) => rpc<Results[]>("rawExec", [sql, options]),
|
|
2421
|
+
// The ATOMIC raw seam: the whole list crosses in ONE round trip, so the transaction lives entirely inside
|
|
2422
|
+
// the worker — a tab can never hold one open across the bridge (and a relocation mid-list is impossible).
|
|
2423
|
+
// An empty list is NOT short-circuited here: the engine's own `rawTransaction` already opens no
|
|
2424
|
+
// transaction for it, and dispatching anyway keeps every lifecycle rule (detach refusal, relocation
|
|
2425
|
+
// settlement) uniform across the surface. A lost response settles `"unknown"` — see MUTATION_RPC_OPS.
|
|
2426
|
+
// Each statement's COPY body (ADR-0061) is listed on the SAME postMessage's transfer list, so a chunked
|
|
2427
|
+
// bulk load crosses zero-copy; the caller's buffers are detached when this dispatches.
|
|
2428
|
+
rawTransaction: (statements, options) =>
|
|
2429
|
+
rpc<Results[]>(
|
|
2430
|
+
"rawTransaction",
|
|
2431
|
+
[statements, options],
|
|
2432
|
+
copyBlobTransfers([...statements.map((statement) => statement.blob), options?.blob]),
|
|
2433
|
+
),
|
|
2344
2434
|
// The GUARDED raw-SQL read (ADR-0032 decision 4) — the seam the worker host dispatches `guardedQuery` to.
|
|
2345
2435
|
// Unlike `rawQuery` (raw inspection, no guard), this routes to the worker's `guardedRawQuery`, so the read
|
|
2346
2436
|
// gate + lazy-group guard run worker-side. Only `rowMode` crosses in the options (see the bridge executor).
|
|
@@ -2385,20 +2475,15 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2385
2475
|
// it never reverts or truncates, so there is no cross-tab footgun. Resolves once the group's stream is
|
|
2386
2476
|
// started (catch-up may still be in flight — await `groupReady` for that), exactly as in-process.
|
|
2387
2477
|
ensureSynced: (keys) => rpc<void>("ensureSynced", [keys]),
|
|
2388
|
-
//
|
|
2389
|
-
//
|
|
2390
|
-
//
|
|
2391
|
-
//
|
|
2392
|
-
//
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
"readiness (status.groups / groupReady) — an activated-but-not-caught-up group reads as not-ready — " +
|
|
2398
|
-
"so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " +
|
|
2399
|
-
"client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.",
|
|
2400
|
-
);
|
|
2401
|
-
},
|
|
2478
|
+
// The SYNCHRONOUS activation-STARTED peek (ADR-0059), answered from the worker-pushed snapshot: the
|
|
2479
|
+
// worker asks ITS OWN client `isSynced(key)` for every registry key and pushes the result (folded off
|
|
2480
|
+
// the `attach-ack`, refreshed by the `synced` broadcast), so this returns exactly what the in-process
|
|
2481
|
+
// client would — promoted groups, the sync-pending window and the sync-disabled clause included. An
|
|
2482
|
+
// unknown key, or any key before the first snapshot, reads `false`, matching the in-process sync-pending
|
|
2483
|
+
// answer. A DETACHED client keeps its last snapshot rather than throwing: this is a peek, not an
|
|
2484
|
+
// operation (detach rejects those), it is read from render paths that cannot handle a throw, and the
|
|
2485
|
+
// in-process client leaves the same started state readable after `stop()`.
|
|
2486
|
+
isSynced: (key) => syncedTables[key as string] === true,
|
|
2402
2487
|
// In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for
|
|
2403
2488
|
// EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower
|
|
2404
2489
|
// `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).
|
|
@@ -2509,14 +2594,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2509
2594
|
},
|
|
2510
2595
|
};
|
|
2511
2596
|
|
|
2512
|
-
// The `
|
|
2597
|
+
// The `pgwasm` misuse trap MUST be a NON-ENUMERABLE throwing getter, never an enumerable property
|
|
2513
2598
|
// holding a throw-on-get Proxy: host tooling reflects over the client wherever the app hands it around
|
|
2514
2599
|
// (React 19.2's dev-build render logging serializes prop diffs property-by-property — observed crashing
|
|
2515
2600
|
// a <SyncClientProvider client={...}> re-render — and console inspection / object spreads do the same),
|
|
2516
2601
|
// and an enumerable trap turns that passive reflection into a crash. Non-enumerable keeps the trap out
|
|
2517
|
-
// of every enumeration path while a direct `client.
|
|
2518
|
-
Object.defineProperty(client, "
|
|
2519
|
-
get: notSupported("client.
|
|
2602
|
+
// of every enumeration path while a direct `client.pgwasm` touch still throws the misuse error.
|
|
2603
|
+
Object.defineProperty(client, "pgwasm", {
|
|
2604
|
+
get: notSupported("client.pgwasm"),
|
|
2520
2605
|
enumerable: false,
|
|
2521
2606
|
configurable: true,
|
|
2522
2607
|
});
|
|
@@ -2560,7 +2645,7 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2560
2645
|
|
|
2561
2646
|
/**
|
|
2562
2647
|
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
|
|
2563
|
-
* freshly-named spare `SharedWorker`: the worker runs
|
|
2648
|
+
* freshly-named spare `SharedWorker`: the worker runs pgwasm `create`/initdb only and holds the raw store idle
|
|
2564
2649
|
* until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
|
|
2565
2650
|
* settled); rejects if the worker reports the create failed, if it refuses the storage declaration, if the elected
|
|
2566
2651
|
* engine is unconstructible, or — bounding the whole thing — with {@link ProvisionExpiredError} once
|
|
@@ -2660,7 +2745,11 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2660
2745
|
const ackListener = (message: { data: unknown }): void => {
|
|
2661
2746
|
if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack") return;
|
|
2662
2747
|
const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
|
|
2663
|
-
|
|
2748
|
+
// A refusal keeps its type across the bridge (a `StorageBuildMismatchError`, pgwasm's build refusals, a
|
|
2749
|
+
// committed store unreachable from this home): rebuilt by name and detail like every other bridge error.
|
|
2750
|
+
settle(() =>
|
|
2751
|
+
ack.ok ? resolve() : reject(ack.error ? rebuildError(ack.error) : new Error("worker provision failed")),
|
|
2752
|
+
);
|
|
2664
2753
|
};
|
|
2665
2754
|
ackPort.addEventListener("message", ackListener);
|
|
2666
2755
|
ackPort.start?.();
|
|
@@ -2842,6 +2931,10 @@ function rebuildError(error: RpcResultPayload["error"]): Error {
|
|
|
2842
2931
|
if (error && "detail" in error) {
|
|
2843
2932
|
const mismatch = executionLimitMismatchFromWire(error.detail);
|
|
2844
2933
|
if (mismatch !== undefined) return mismatch;
|
|
2934
|
+
// An attach refused because the engine's in-flight spare provision outran the adoption budget: the host
|
|
2935
|
+
// branches on the TYPE to rebind to a fresh store, so it must cross the bridge as the class.
|
|
2936
|
+
const stalled = provisionStalledFromWire(error.detail);
|
|
2937
|
+
if (stalled !== undefined) return stalled;
|
|
2845
2938
|
// A no-grant engine home refusing an `opfs-committed` store: the consumer branches on the TYPE to offer
|
|
2846
2939
|
// the destroy-then-rebuild exit, so it must cross the bridge as the class, not a name-tagged plain Error.
|
|
2847
2940
|
const unreachable = committedStoreUnreachableFromWire(error.detail);
|