@pgxsinkit/client 0.3.0 → 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 +10 -3
- package/dist/boot-report.d.ts +6 -6
- 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 +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +191 -95
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +989 -432
- 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.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 +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/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 +9 -9
- 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 +21 -26
- package/src/export-store.ts +17 -17
- package/src/index.ts +520 -284
- 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 +2 -2
- 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 +56 -40
- package/src/sync/apply.ts +32 -46
- package/src/sync/copy.ts +108 -13
- package/src/sync/drizzle-executor.ts +13 -14
- 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 +142 -56
- package/src/worker/define-sync-worker.ts +204 -75
- 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/src/testing.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).
|
|
2
2
|
//
|
|
3
3
|
// pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a
|
|
4
|
-
// memory store: `createSyncClient`/`
|
|
4
|
+
// memory store: `createSyncClient`/`createPgwasmClient` take a plain `storePath` whose backend is derived
|
|
5
5
|
// (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory
|
|
6
6
|
// stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export
|
|
7
7
|
// machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
|
|
13
13
|
//
|
|
14
14
|
// createSyncClient({ ...memoryStoreForTests("my-test"), registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })
|
|
15
|
-
// createSyncClient({ ...testStoreAcknowledgment(),
|
|
15
|
+
// createSyncClient({ ...testStoreAcknowledgment(), pgwasmInstance, registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })
|
|
16
16
|
|
|
17
17
|
import { TEST_STORE_BACKEND } from "./store-path";
|
|
18
18
|
|
|
@@ -42,7 +42,7 @@ export function memoryStoreForTests(storePath: string): MemoryStoreForTests {
|
|
|
42
42
|
/**
|
|
43
43
|
* Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal
|
|
44
44
|
* (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent
|
|
45
|
-
*
|
|
45
|
+
* pgwasm via `pgwasmInstance` / `precreatedPgwasm`. Spread it alongside that option.
|
|
46
46
|
*
|
|
47
47
|
* Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent
|
|
48
48
|
* store voids the retention + journal durability guarantees.
|
|
@@ -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 {
|
|
@@ -150,10 +154,10 @@ export interface ElectedEngineWorker {
|
|
|
150
154
|
/**
|
|
151
155
|
* The default {@link AttachSyncClientOptions.awaitOwnershipRelease} — a documented NO-OP (ADR-0049 step 11b
|
|
152
156
|
* follow-up 1). The OPFS-repacked VFS enforces single-owner access with EXCLUSIVE OPFS sync-access handles
|
|
153
|
-
* (`StoreOwnedError`)
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
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.
|
|
157
161
|
* So the coordinator can respawn immediately after a deliberate terminate; its VFS open is the real gate.
|
|
158
162
|
*/
|
|
159
163
|
export function resolvedOwnershipRelease(): Promise<void> {
|
|
@@ -280,7 +284,7 @@ function resolveIdbDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undef
|
|
|
280
284
|
return (globalThis as { indexedDB?: IdbDeleteSurface }).indexedDB;
|
|
281
285
|
}
|
|
282
286
|
|
|
283
|
-
/** Delete-if-present the store's
|
|
287
|
+
/** Delete-if-present the store's pgwasm idb database; only `onsuccess` proves completion. */
|
|
284
288
|
function deleteStoreIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
|
|
285
289
|
const idb = resolveIdbDeleteSurface(meta);
|
|
286
290
|
if (idb?.deleteDatabase == null) return Promise.resolve();
|
|
@@ -316,10 +320,19 @@ function deleteStoreIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promis
|
|
|
316
320
|
|
|
317
321
|
/**
|
|
318
322
|
* Build the REAL {@link DestructionEffects} for a store — the OPFS commitment sentinel + store directory
|
|
319
|
-
* (`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
|
|
320
324
|
* backend-agnostic (`store-lifecycle.ts`): `deleteBackendStore` delete-if-presents BOTH the OPFS directory and
|
|
321
325
|
* the idb database, so it works whichever backend the store used. Injectable IO (`opfs`/`meta`) so the wiring is
|
|
322
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).
|
|
323
336
|
*/
|
|
324
337
|
export function createStoreDestructionEffects(
|
|
325
338
|
storePath: string,
|
|
@@ -327,11 +340,19 @@ export function createStoreDestructionEffects(
|
|
|
327
340
|
): DestructionEffects {
|
|
328
341
|
const opfs = createOpfsEffects(storePath, deps?.opfs);
|
|
329
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
|
+
};
|
|
330
351
|
return {
|
|
331
352
|
setPhase: (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, meta),
|
|
332
|
-
deleteSentinel: () => opfs.deleteSentinel(),
|
|
353
|
+
deleteSentinel: () => deleteOpfsOrRecordPending(() => opfs.deleteSentinel()),
|
|
333
354
|
deleteBackendStore: async () => {
|
|
334
|
-
await opfs.deleteStoreDirectory();
|
|
355
|
+
await deleteOpfsOrRecordPending(() => opfs.deleteStoreDirectory());
|
|
335
356
|
await deleteStoreIdbDatabase(storePath, meta);
|
|
336
357
|
},
|
|
337
358
|
deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta),
|
|
@@ -346,8 +367,10 @@ export function createStoreDestructionEffects(
|
|
|
346
367
|
* **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
|
|
347
368
|
* supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
|
|
348
369
|
* `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
|
|
349
|
-
* behind, a wipe of known store paths.
|
|
350
|
-
*
|
|
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
|
|
351
374
|
* idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
|
|
352
375
|
* completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
|
|
353
376
|
* already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
|
|
@@ -588,8 +611,32 @@ const MUTATION_RPC_OPS: ReadonlySet<RpcOp> = new Set<RpcOp>([
|
|
|
588
611
|
// `rawExec` is WRITE-CAPABLE (its docstring: any write it issues stays local and will NOT converge), so a
|
|
589
612
|
// dispatched rawExec with a lost response is `"unknown"` — retrying could double-apply a local write.
|
|
590
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",
|
|
591
619
|
]);
|
|
592
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
|
+
|
|
593
640
|
export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
594
641
|
registry: TRegistry;
|
|
595
642
|
/**
|
|
@@ -726,8 +773,8 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
726
773
|
* OPFS-repacked VFS enforces ownership with EXCLUSIVE OPFS sync-access handles (`StoreOwnedError` /
|
|
727
774
|
* `STORE_OWNED`), NOT a Web Lock, so there is no lock name to `navigator.locks.request(..., { ifAvailable })`
|
|
728
775
|
* against here. The bounded wait therefore lives in the SUCCESSOR'S OPEN PATH: the respawned elected engine
|
|
729
|
-
* worker's own `
|
|
730
|
-
* (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
|
|
731
778
|
* handle — exactly the fault-matrix row "VFS ownership-lock release lag → successor open retries on contention
|
|
732
779
|
* until clear, bounded, then boot failure". Supply a custom async wait only to inject a real probe (tests do).
|
|
733
780
|
*/
|
|
@@ -754,9 +801,9 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
754
801
|
/**
|
|
755
802
|
* The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
|
|
756
803
|
* token after an app auth-state change, ADR-0032 decision 3). One-shot Drizzle reads
|
|
757
|
-
* (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker
|
|
758
|
-
*
|
|
759
|
-
* `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()`.
|
|
760
807
|
*/
|
|
761
808
|
export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
|
|
762
809
|
notifyAuthChanged: () => void;
|
|
@@ -1132,6 +1179,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1132
1179
|
let readyResolved = false;
|
|
1133
1180
|
const readyGroups = new Set<string>();
|
|
1134
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> = {};
|
|
1135
1187
|
|
|
1136
1188
|
// ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────
|
|
1137
1189
|
const pushToken = async () => {
|
|
@@ -1179,6 +1231,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1179
1231
|
markGroupReady(event.groupKey);
|
|
1180
1232
|
break;
|
|
1181
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
|
+
}
|
|
1182
1240
|
case "milestone": {
|
|
1183
1241
|
// Staged boot readiness (ADR-0041 stage 2): the engine crossed a background stage while this tab was
|
|
1184
1242
|
// attached. Idempotent with the ack's late-attach fold — whichever observes it first wins.
|
|
@@ -1284,6 +1342,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1284
1342
|
if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
|
|
1285
1343
|
if (ack.bootSettled) settleBootSettled();
|
|
1286
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;
|
|
1287
1349
|
const settle = pendingAttachAck;
|
|
1288
1350
|
pendingAttachAck = null;
|
|
1289
1351
|
settle?.resolve(ack);
|
|
@@ -1763,16 +1825,24 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1763
1825
|
};
|
|
1764
1826
|
|
|
1765
1827
|
// ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
|
|
1766
|
-
|
|
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> => {
|
|
1767
1832
|
// A detached client has no live port listener, so a worker reply could never resolve this — reject at
|
|
1768
1833
|
// once rather than register a forever-pending waiter (ADR-0040 P2).
|
|
1769
1834
|
if (detached) return Promise.reject(detachError());
|
|
1770
|
-
|
|
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";
|
|
1771
1841
|
return new Promise<T>((resolve, reject) => {
|
|
1772
1842
|
const dispatch = () => {
|
|
1773
1843
|
const id = newId("rpc");
|
|
1774
1844
|
rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject, kind });
|
|
1775
|
-
postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id);
|
|
1845
|
+
postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id, transfer);
|
|
1776
1846
|
armSilence();
|
|
1777
1847
|
armOverdue(id);
|
|
1778
1848
|
};
|
|
@@ -2156,8 +2226,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2156
2226
|
// ─── Assembled client ────────────────────────────────────────────────────────────────────────────
|
|
2157
2227
|
const notSupported = (name: string) => (): never => {
|
|
2158
2228
|
throw new Error(
|
|
2159
|
-
`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local
|
|
2160
|
-
`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 ` +
|
|
2161
2231
|
`implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` +
|
|
2162
2232
|
`(ensureSynced), and the write API ARE proxied to the worker.`,
|
|
2163
2233
|
);
|
|
@@ -2184,7 +2254,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2184
2254
|
const options = rowMode ? { rowMode } : {};
|
|
2185
2255
|
return use ? [sql, params, options, use] : [sql, params, options];
|
|
2186
2256
|
};
|
|
2187
|
-
// A `
|
|
2257
|
+
// A `PgwasmClient`-shaped bridge executor Drizzle runs reads against (ADR-0032 decision 4). Drizzle's pglite
|
|
2188
2258
|
// driver calls only `client.query` for reads and `client.transaction` for `.transaction()`. `query` routes
|
|
2189
2259
|
// to the worker's `guardedQuery` RPC (stripping drizzle's non-serializable `parsers` to just `rowMode`; the
|
|
2190
2260
|
// worker re-applies drizzle's identity parsers) and returns the full `Results` so Drizzle's mapping runs on
|
|
@@ -2193,12 +2263,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2193
2263
|
// the builder in a microtask AFTER `queryRaw` returns, so a plain `query` issued synchronously in between
|
|
2194
2264
|
// would drain its executor first and consume the wrong call's `use`. A per-read scoped executor cannot
|
|
2195
2265
|
// cross-contaminate.
|
|
2196
|
-
const makeBridgeExecutor = (use?: readonly string[]):
|
|
2266
|
+
const makeBridgeExecutor = (use?: readonly string[]): PgwasmClient =>
|
|
2197
2267
|
({
|
|
2198
2268
|
query: (sql: string, params?: unknown[], options?: { rowMode?: "array" | "object" }): Promise<Results> =>
|
|
2199
2269
|
rpc<Results>("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
|
|
2200
2270
|
transaction: noBridgeTransaction,
|
|
2201
|
-
}) as unknown as
|
|
2271
|
+
}) as unknown as PgwasmClient;
|
|
2202
2272
|
// The base (no-`use`) bridge database `client.drizzle` exposes, plus the cached factory that mints a fresh
|
|
2203
2273
|
// database over a per-read `use`-carrying executor (the schema/relations are computed ONCE, ADR-0032
|
|
2204
2274
|
// decision 4). `views` are unchanged.
|
|
@@ -2216,9 +2286,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2216
2286
|
const client: AttachedSyncClient<TRegistry> = {
|
|
2217
2287
|
drizzle,
|
|
2218
2288
|
views,
|
|
2219
|
-
// The tab has no local
|
|
2289
|
+
// The tab has no local pgwasm; reads go through the live-rows bridge. Touching `.pgwasm` is a misuse
|
|
2220
2290
|
// — the real trap is installed as a NON-ENUMERABLE throwing getter after this literal (see below).
|
|
2221
|
-
|
|
2291
|
+
pgwasm: undefined as never,
|
|
2222
2292
|
tables: Object.fromEntries(
|
|
2223
2293
|
Object.keys(options.registry).map((tableKey) => [
|
|
2224
2294
|
tableKey,
|
|
@@ -2279,7 +2349,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2279
2349
|
// ADR-0053 decision 8, the Event lane's half of the same refusal. It rides the diagnostics round
|
|
2280
2350
|
// trip already taken above rather than a second one: the tab has no local Outbox (exactly as it has
|
|
2281
2351
|
// no local journal), and a destroy must not add a network-shaped hop it can avoid. Absent `outbox`
|
|
2282
|
-
// 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.
|
|
2283
2354
|
if (outbox?.empty === false) {
|
|
2284
2355
|
throw new Error(
|
|
2285
2356
|
"destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
|
|
@@ -2342,8 +2413,24 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2342
2413
|
readMutationDetails: (table) => rpc<MutationDetail[]>("readMutationDetails", [table]),
|
|
2343
2414
|
// Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`
|
|
2344
2415
|
// itself stays blocked (below); these route the raw statement over the RPC round-trip instead.
|
|
2345
|
-
|
|
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])),
|
|
2346
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
|
+
),
|
|
2347
2434
|
// The GUARDED raw-SQL read (ADR-0032 decision 4) — the seam the worker host dispatches `guardedQuery` to.
|
|
2348
2435
|
// Unlike `rawQuery` (raw inspection, no guard), this routes to the worker's `guardedRawQuery`, so the read
|
|
2349
2436
|
// gate + lazy-group guard run worker-side. Only `rowMode` crosses in the options (see the bridge executor).
|
|
@@ -2388,20 +2475,15 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2388
2475
|
// it never reverts or truncates, so there is no cross-tab footgun. Resolves once the group's stream is
|
|
2389
2476
|
// started (catch-up may still be in flight — await `groupReady` for that), exactly as in-process.
|
|
2390
2477
|
ensureSynced: (keys) => rpc<void>("ensureSynced", [keys]),
|
|
2391
|
-
//
|
|
2392
|
-
//
|
|
2393
|
-
//
|
|
2394
|
-
//
|
|
2395
|
-
//
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
"readiness (status.groups / groupReady) — an activated-but-not-caught-up group reads as not-ready — " +
|
|
2401
|
-
"so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " +
|
|
2402
|
-
"client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.",
|
|
2403
|
-
);
|
|
2404
|
-
},
|
|
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,
|
|
2405
2487
|
// In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for
|
|
2406
2488
|
// EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower
|
|
2407
2489
|
// `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).
|
|
@@ -2512,14 +2594,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2512
2594
|
},
|
|
2513
2595
|
};
|
|
2514
2596
|
|
|
2515
|
-
// The `
|
|
2597
|
+
// The `pgwasm` misuse trap MUST be a NON-ENUMERABLE throwing getter, never an enumerable property
|
|
2516
2598
|
// holding a throw-on-get Proxy: host tooling reflects over the client wherever the app hands it around
|
|
2517
2599
|
// (React 19.2's dev-build render logging serializes prop diffs property-by-property — observed crashing
|
|
2518
2600
|
// a <SyncClientProvider client={...}> re-render — and console inspection / object spreads do the same),
|
|
2519
2601
|
// and an enumerable trap turns that passive reflection into a crash. Non-enumerable keeps the trap out
|
|
2520
|
-
// of every enumeration path while a direct `client.
|
|
2521
|
-
Object.defineProperty(client, "
|
|
2522
|
-
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"),
|
|
2523
2605
|
enumerable: false,
|
|
2524
2606
|
configurable: true,
|
|
2525
2607
|
});
|
|
@@ -2563,7 +2645,7 @@ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pi
|
|
|
2563
2645
|
|
|
2564
2646
|
/**
|
|
2565
2647
|
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
|
|
2566
|
-
* 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
|
|
2567
2649
|
* until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
|
|
2568
2650
|
* settled); rejects if the worker reports the create failed, if it refuses the storage declaration, if the elected
|
|
2569
2651
|
* engine is unconstructible, or — bounding the whole thing — with {@link ProvisionExpiredError} once
|
|
@@ -2663,7 +2745,11 @@ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
2663
2745
|
const ackListener = (message: { data: unknown }): void => {
|
|
2664
2746
|
if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack") return;
|
|
2665
2747
|
const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
|
|
2666
|
-
|
|
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
|
+
);
|
|
2667
2753
|
};
|
|
2668
2754
|
ackPort.addEventListener("message", ackListener);
|
|
2669
2755
|
ackPort.start?.();
|