@pgxsinkit/client 0.1.50 → 0.1.53
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/dist/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +66 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +284 -82
- package/dist/index.js.map +21 -19
- package/dist/local-tables.d.ts +6 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/schema.d.ts +18 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +6 -0
- package/dist/shape-sync.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/metadata-tables.d.ts +16 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +10 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/tags.d.ts +16 -4
- package/dist/sync/tags.d.ts.map +1 -1
- package/dist/sync/types.d.ts +12 -0
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +4 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +41 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +17 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +6 -2
- package/skills/operating/SKILL.md +28 -5
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/index.ts +175 -41
- package/src/local-tables.ts +7 -0
- package/src/schema.ts +22 -4
- package/src/shape-sync.ts +11 -0
- package/src/sync/apply.ts +164 -26
- package/src/sync/index.ts +45 -8
- package/src/sync/metadata-tables.ts +41 -0
- package/src/sync/subscription-state.ts +29 -4
- package/src/sync/tags.ts +34 -9
- package/src/sync/types.ts +12 -0
- package/src/worker/attach-sync-client.ts +119 -20
- package/src/worker/define-sync-worker.ts +112 -2
- package/src/worker/live-query-manager.ts +6 -0
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +28 -0
package/src/sync/tags.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { quoteIdentifier, quoteSqlLiteral } from "@pgxsinkit/contracts";
|
|
|
8
8
|
import type { ApplyTarget } from "../local-tables";
|
|
9
9
|
import { applyBulkDeletesToTable } from "./apply";
|
|
10
10
|
import { drizzleOverPg } from "./drizzle-executor";
|
|
11
|
-
import { getMetadataTables } from "./metadata-tables";
|
|
11
|
+
import { getMetadataTables, getSessionMetadataTables, pickMetadataTables } from "./metadata-tables";
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
|
|
@@ -74,6 +74,16 @@ export function shapeRowTagsTableName(metadataSchema: string): string {
|
|
|
74
74
|
return `${quoteIdentifier(config.schema ?? "public")}.${quoteIdentifier(config.name)}`;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
+
/**
|
|
78
|
+
* The SESSION (`pg_temp`) tag store's qualified identifier (ADR-0042), derived from the session
|
|
79
|
+
* `shape_row_tags` pgTable config — the same relation name, in `pg_temp`. Used by the scope-blind
|
|
80
|
+
* {@link buildClearShapeTagsSql} so a desync/discard clears an ephemeral shape's tags wherever they live.
|
|
81
|
+
*/
|
|
82
|
+
export function shapeRowTagsSessionTableName(): string {
|
|
83
|
+
const config = getTableConfig(getSessionMetadataTables().shapeRowTags);
|
|
84
|
+
return `${quoteIdentifier(config.schema ?? "public")}.${quoteIdentifier(config.name)}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
77
87
|
/** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
|
|
78
88
|
export function shapeTableId(schema: string | undefined, table: string): string {
|
|
79
89
|
return `${schema ?? "public"}.${table}`;
|
|
@@ -87,11 +97,16 @@ export function shapeTableId(schema: string | undefined, table: string): string
|
|
|
87
97
|
* guarded.
|
|
88
98
|
*/
|
|
89
99
|
export function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
100
|
+
// ADR-0042: SCOPE-BLIND — clear the shape's tags from BOTH the durable and the session (`pg_temp`) tag
|
|
101
|
+
// store, each guarded independently by `to_regclass` (a desync/discard may run on a persistent table whose
|
|
102
|
+
// session store never existed, or standalone before any engine boot). `to_regclass('pg_temp.shape_row_tags')`
|
|
103
|
+
// resolves the session table via the per-session `pg_temp` alias (probed on real PGlite).
|
|
104
|
+
const clearOne = (table: string) => ` IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
|
|
93
105
|
DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};
|
|
94
|
-
END IF
|
|
106
|
+
END IF;`;
|
|
107
|
+
return `DO $$ BEGIN
|
|
108
|
+
${clearOne(shapeRowTagsTableName(metadataSchema))}
|
|
109
|
+
${clearOne(shapeRowTagsSessionTableName())}
|
|
95
110
|
END $$;`;
|
|
96
111
|
}
|
|
97
112
|
|
|
@@ -158,6 +173,8 @@ interface TagSyncOptions {
|
|
|
158
173
|
shapeTable: string;
|
|
159
174
|
messages: ChangeMessage<Row<unknown>>[];
|
|
160
175
|
primaryKey: string[];
|
|
176
|
+
/** ADR-0042: route the tag DML to the SESSION (`pg_temp`) store for an ephemeral group. */
|
|
177
|
+
sessionScoped?: boolean;
|
|
161
178
|
}
|
|
162
179
|
|
|
163
180
|
/**
|
|
@@ -173,8 +190,9 @@ export async function applyShapeTagSync({
|
|
|
173
190
|
shapeTable,
|
|
174
191
|
messages,
|
|
175
192
|
primaryKey,
|
|
193
|
+
sessionScoped = false,
|
|
176
194
|
}: TagSyncOptions): Promise<void> {
|
|
177
|
-
const { shapeRowTags } =
|
|
195
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
178
196
|
const db = drizzleOverPg(pg);
|
|
179
197
|
|
|
180
198
|
for (const message of messages) {
|
|
@@ -233,8 +251,9 @@ export async function addShapeRowTags({
|
|
|
233
251
|
shapeTable,
|
|
234
252
|
messages,
|
|
235
253
|
primaryKey,
|
|
254
|
+
sessionScoped = false,
|
|
236
255
|
}: TagSyncOptions): Promise<void> {
|
|
237
|
-
const { shapeRowTags } =
|
|
256
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
238
257
|
const db = drizzleOverPg(pg);
|
|
239
258
|
|
|
240
259
|
for (const message of messages) {
|
|
@@ -259,6 +278,8 @@ interface MoveOutOptions {
|
|
|
259
278
|
/** One entry per buffered `move-out` event, each its own pattern set. */
|
|
260
279
|
patternSets: MovePattern[][];
|
|
261
280
|
debug: boolean;
|
|
281
|
+
/** ADR-0042: route the tag reads/evictions to the SESSION (`pg_temp`) store for an ephemeral group. */
|
|
282
|
+
sessionScoped?: boolean;
|
|
262
283
|
}
|
|
263
284
|
|
|
264
285
|
/**
|
|
@@ -274,8 +295,9 @@ export async function applyShapeMoveOut({
|
|
|
274
295
|
target,
|
|
275
296
|
patternSets,
|
|
276
297
|
debug,
|
|
298
|
+
sessionScoped = false,
|
|
277
299
|
}: MoveOutOptions): Promise<number> {
|
|
278
|
-
const { shapeRowTags } =
|
|
300
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
279
301
|
const db = drizzleOverPg(pg);
|
|
280
302
|
const evictedPkJsons = new Set<string>();
|
|
281
303
|
|
|
@@ -355,11 +377,14 @@ export async function clearShapeTags({
|
|
|
355
377
|
pg,
|
|
356
378
|
metadataSchema,
|
|
357
379
|
shapeTable,
|
|
380
|
+
sessionScoped = false,
|
|
358
381
|
}: {
|
|
359
382
|
pg: PGliteInterface | Transaction;
|
|
360
383
|
metadataSchema: string;
|
|
361
384
|
shapeTable: string;
|
|
385
|
+
/** ADR-0042: clear the SESSION (`pg_temp`) tag store for an ephemeral group's must-refetch rebuild. */
|
|
386
|
+
sessionScoped?: boolean;
|
|
362
387
|
}): Promise<void> {
|
|
363
|
-
const { shapeRowTags } =
|
|
388
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
364
389
|
await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));
|
|
365
390
|
}
|
package/src/sync/types.ts
CHANGED
|
@@ -51,6 +51,16 @@ export interface SyncShapesToTablesOptions {
|
|
|
51
51
|
/** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */
|
|
52
52
|
registry: SyncTableRegistry;
|
|
53
53
|
shapes: Record<string, ShapeToTableOptions>;
|
|
54
|
+
/**
|
|
55
|
+
* ADR-0042: this group's sync bookkeeping (subscription cursor + tagged-subquery reason sets) is
|
|
56
|
+
* SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the
|
|
57
|
+
* durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor
|
|
58
|
+
* and tags then die with the rows they index, so a returning engine re-streams the shape from scratch
|
|
59
|
+
* instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — every
|
|
60
|
+
* persistent group's storage is byte-identical to before. One storage-scope bit; the engine never learns
|
|
61
|
+
* the retention model.
|
|
62
|
+
*/
|
|
63
|
+
sessionScoped?: boolean | undefined;
|
|
54
64
|
initialInsertMethod?: InitialInsertMethod | undefined;
|
|
55
65
|
onInitialSync?: (() => void) | undefined;
|
|
56
66
|
/**
|
|
@@ -113,6 +123,8 @@ export interface SyncShapeToTableOptions {
|
|
|
113
123
|
registry: SyncTableRegistry;
|
|
114
124
|
tableKey: string;
|
|
115
125
|
shapeKey: string | null;
|
|
126
|
+
/** ADR-0042: SESSION-scope this shape's cursor + tags (ephemeral retention); see {@link SyncShapesToTablesOptions.sessionScoped}. */
|
|
127
|
+
sessionScoped?: boolean | undefined;
|
|
116
128
|
initialInsertMethod?: InitialInsertMethod | undefined;
|
|
117
129
|
onInitialSync?: (() => void) | undefined;
|
|
118
130
|
onError?: ((error: FetchError | Error) => void) | undefined;
|
|
@@ -4,10 +4,14 @@
|
|
|
4
4
|
// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the
|
|
5
5
|
// worker's expiry pull-requests via `getToken`.
|
|
6
6
|
//
|
|
7
|
-
// One-shot Drizzle reads (`query`/`queryRaw
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
7
|
+
// One-shot Drizzle reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) ARE proxied (ADR-0032 decision 4):
|
|
8
|
+
// `drizzle`/`views` here are a real Drizzle database over a bridge executor whose `query` routes each read to
|
|
9
|
+
// the worker's `guardedQuery` RPC, so awaiting a builder runs the ADR-0041 read gate + the ADR-0021
|
|
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. The only members that stay
|
|
12
|
+
// unsupported are the genuinely tab-local ones — `pglite` (no local store), `destroy`/`dropReadCache` (store
|
|
13
|
+
// lifecycle the worker owns), and `isSynced` (a SYNCHRONOUS activation-STARTED peek the tab's cached per-group
|
|
14
|
+
// catch-up readiness cannot answer, and a sync method cannot be an RPC) — each throwing a clear error saying why.
|
|
11
15
|
|
|
12
16
|
import type { Results } from "@electric-sql/pglite";
|
|
13
17
|
|
|
@@ -25,6 +29,7 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
|
|
|
25
29
|
import type { StoreExportOptions, StoreExportResult } from "../export-store";
|
|
26
30
|
import {
|
|
27
31
|
buildRegistryReadHandles,
|
|
32
|
+
type ClientPGlite,
|
|
28
33
|
ClientDisposedError,
|
|
29
34
|
createMutationsApi,
|
|
30
35
|
type LiveQueryDiagnostics,
|
|
@@ -48,6 +53,7 @@ import {
|
|
|
48
53
|
type BridgePort,
|
|
49
54
|
type BridgeTransferable,
|
|
50
55
|
type ExportArtefactWire,
|
|
56
|
+
type GuardedQueryWireArgs,
|
|
51
57
|
identityCodec,
|
|
52
58
|
isBridgeEnvelope,
|
|
53
59
|
type LiveDiffPayload,
|
|
@@ -128,7 +134,10 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
128
134
|
|
|
129
135
|
/**
|
|
130
136
|
* The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
|
|
131
|
-
* token after an app auth-state change, ADR-0032 decision 3).
|
|
137
|
+
* token after an app auth-state change, ADR-0032 decision 3). One-shot Drizzle reads
|
|
138
|
+
* (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker; the members
|
|
139
|
+
* that throw are the structurally unproxiable ones — `pglite`, `destroy`, `dropReadCache`, `isSynced`, and
|
|
140
|
+
* `drizzle.transaction()`.
|
|
132
141
|
*/
|
|
133
142
|
export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
|
|
134
143
|
notifyAuthChanged: () => void;
|
|
@@ -614,13 +623,60 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
614
623
|
};
|
|
615
624
|
|
|
616
625
|
// ─── Assembled client ────────────────────────────────────────────────────────────────────────────
|
|
617
|
-
const { drizzle, views } = buildRegistryReadHandles(options.registry);
|
|
618
626
|
const notSupported = (name: string) => (): never => {
|
|
619
627
|
throw new Error(
|
|
620
|
-
`[pgxsinkit] ${name} is not available on a worker-attached client
|
|
628
|
+
`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local PGlite. ` +
|
|
629
|
+
`Direct store access (client.pglite) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` +
|
|
630
|
+
`implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` +
|
|
631
|
+
`(ensureSynced), and the write API ARE proxied to the worker.`,
|
|
621
632
|
);
|
|
622
633
|
};
|
|
623
634
|
|
|
635
|
+
// A tab has no local store to run a read transaction against — every bridge executor's `transaction` throws.
|
|
636
|
+
const noBridgeTransaction = (): never => {
|
|
637
|
+
throw new Error(
|
|
638
|
+
"[pgxsinkit] client.drizzle.transaction() is not available on a worker-attached client: a read " +
|
|
639
|
+
"transaction needs a local PGlite the tab does not have. Use one-shot reads (client.query) instead.",
|
|
640
|
+
);
|
|
641
|
+
};
|
|
642
|
+
// The ONE encoder of the `guardedQuery` positional wire tuple ({@link GuardedQueryWireArgs}): both tab-side
|
|
643
|
+
// senders (the bridge executor below and `guardedRawQuery`) route through this so the shape is written once
|
|
644
|
+
// and shares its contract with the worker-side decoder (`defineSyncWorker` types the decode against the same
|
|
645
|
+
// type). The optional trailing `use` is appended only when present — never a spread of `undefined`.
|
|
646
|
+
const guardedQueryArgs = (
|
|
647
|
+
sql: string,
|
|
648
|
+
params: unknown[] | undefined,
|
|
649
|
+
rowMode: "array" | "object" | undefined,
|
|
650
|
+
use?: readonly string[],
|
|
651
|
+
): GuardedQueryWireArgs => {
|
|
652
|
+
// `rowMode` is only included when set (exactOptionalPropertyTypes: no `{ rowMode: undefined }`).
|
|
653
|
+
const options = rowMode ? { rowMode } : {};
|
|
654
|
+
return use ? [sql, params, options, use] : [sql, params, options];
|
|
655
|
+
};
|
|
656
|
+
// A `ClientPGlite`-shaped bridge executor Drizzle runs reads against (ADR-0032 decision 4). Drizzle's pglite
|
|
657
|
+
// driver calls only `client.query` for reads and `client.transaction` for `.transaction()`. `query` routes
|
|
658
|
+
// to the worker's `guardedQuery` RPC (stripping drizzle's non-serializable `parsers` to just `rowMode`; the
|
|
659
|
+
// worker re-applies drizzle's identity parsers) and returns the full `Results` so Drizzle's mapping runs on
|
|
660
|
+
// the tab. `use` (a raw-fragment's undetectable lazy relations, ADR-0021) is baked into the closure per read —
|
|
661
|
+
// see `bridgeReadDrizzle` — NOT stashed on a shared field: a shared stash races, because Drizzle executes
|
|
662
|
+
// the builder in a microtask AFTER `queryRaw` returns, so a plain `query` issued synchronously in between
|
|
663
|
+
// would drain its executor first and consume the wrong call's `use`. A per-read scoped executor cannot
|
|
664
|
+
// cross-contaminate.
|
|
665
|
+
const makeBridgeExecutor = (use?: readonly string[]): ClientPGlite =>
|
|
666
|
+
({
|
|
667
|
+
query: (sql: string, params?: unknown[], options?: { rowMode?: "array" | "object" }): Promise<Results> =>
|
|
668
|
+
rpc<Results>("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
|
|
669
|
+
transaction: noBridgeTransaction,
|
|
670
|
+
}) as unknown as ClientPGlite;
|
|
671
|
+
// The base (no-`use`) bridge database `client.drizzle` exposes, plus the cached factory that mints a fresh
|
|
672
|
+
// database over a per-read `use`-carrying executor (the schema/relations are computed ONCE, ADR-0032
|
|
673
|
+
// decision 4). `views` are unchanged.
|
|
674
|
+
const { drizzle, views, drizzleFor } = buildRegistryReadHandles(options.registry, makeBridgeExecutor());
|
|
675
|
+
// Build a `use`-scoped Drizzle for one `queryRaw`/`queryRawRow` call and run its builder against a shallow
|
|
676
|
+
// clone of the client whose `drizzle` is that scoped db. The clone is safe: every client method is an arrow
|
|
677
|
+
// closing over this scope (no `this`), so spreading preserves behaviour and only `drizzle` is swapped.
|
|
678
|
+
const bridgeReadDrizzle = (use?: readonly string[]) => drizzleFor(makeBridgeExecutor(use));
|
|
679
|
+
|
|
624
680
|
const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {
|
|
625
681
|
const entry = options.registry[table];
|
|
626
682
|
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
@@ -629,13 +685,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
629
685
|
const client: AttachedSyncClient<TRegistry> = {
|
|
630
686
|
drizzle,
|
|
631
687
|
views,
|
|
632
|
-
// The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
{
|
|
636
|
-
get: notSupported("client.pglite"),
|
|
637
|
-
},
|
|
638
|
-
) as never,
|
|
688
|
+
// The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse
|
|
689
|
+
// — the real trap is installed as a NON-ENUMERABLE throwing getter after this literal (see below).
|
|
690
|
+
pglite: undefined as never,
|
|
639
691
|
tables: Object.fromEntries(
|
|
640
692
|
Object.keys(options.registry).map((tableKey) => [
|
|
641
693
|
tableKey,
|
|
@@ -671,6 +723,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
671
723
|
// itself stays blocked (below); these route the raw statement over the RPC round-trip instead.
|
|
672
724
|
rawQuery: (sql, params, options) => rpc<Results>("rawQuery", [sql, params, options]),
|
|
673
725
|
rawExec: (sql, options) => rpc<Results[]>("rawExec", [sql, options]),
|
|
726
|
+
// The GUARDED raw-SQL read (ADR-0032 decision 4) — the seam the worker host dispatches `guardedQuery` to.
|
|
727
|
+
// Unlike `rawQuery` (raw inspection, no guard), this routes to the worker's `guardedRawQuery`, so the read
|
|
728
|
+
// gate + lazy-group guard run worker-side. Only `rowMode` crosses in the options (see the bridge executor).
|
|
729
|
+
guardedRawQuery: (sql, params, options, use) =>
|
|
730
|
+
rpc<Results>("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
|
|
674
731
|
mutate: {
|
|
675
732
|
create: (table, input) => rpc<void>("create", [table, input]),
|
|
676
733
|
update: (table, entityKey, patch) => rpc<void>("update", [table, entityKey, patch]),
|
|
@@ -688,12 +745,42 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
688
745
|
subscribeLiveRows,
|
|
689
746
|
query: (sql, params) => rpc<Results>("rawQuery", [sql, params]),
|
|
690
747
|
}),
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
748
|
+
// One-shot Drizzle reads (ADR-0032 decision 4) — proxied, mirroring the in-process shapes exactly. `build`
|
|
749
|
+
// runs against a client whose `drizzle` is a bridge database, so awaiting the builder executes the read via
|
|
750
|
+
// the `guardedQuery` RPC: the read gate + lazy-group guard run worker-side (no tab-side `prepareQuery`) and
|
|
751
|
+
// Drizzle's own mapping runs on the tab. The pure `query`/`queryRow` need no `use` (the worker's SQL scan
|
|
752
|
+
// finds every relation) and run against the base `client`. `queryRaw`/`queryRawRow` may embed a raw
|
|
753
|
+
// fragment naming a lazy relation the scan cannot see, so each runs against a `{ ...client, drizzle }`
|
|
754
|
+
// clone whose drizzle carries THAT call's `use` in its own executor — no shared state, no cross-read race.
|
|
755
|
+
query: (build) => Promise.resolve(build(client)),
|
|
756
|
+
queryRow: async (build) => {
|
|
757
|
+
const rows = await build(client);
|
|
758
|
+
return rows[0] ?? null;
|
|
759
|
+
},
|
|
760
|
+
queryRaw: ({ build, use }) => Promise.resolve(build({ ...client, drizzle: bridgeReadDrizzle(use) })),
|
|
761
|
+
queryRawRow: async ({ build, use }) => {
|
|
762
|
+
const rows = await build({ ...client, drizzle: bridgeReadDrizzle(use) });
|
|
763
|
+
return rows[0] ?? null;
|
|
764
|
+
},
|
|
765
|
+
// Lazy activation (ADR-0021) over the shared engine — a plain RPC. Activation is engine-WIDE, but unlike
|
|
766
|
+
// `desync` it is additive and idempotent: starting a group another tab already activated is a no-op, and
|
|
767
|
+
// it never reverts or truncates, so there is no cross-tab footgun. Resolves once the group's stream is
|
|
768
|
+
// started (catch-up may still be in flight — await `groupReady` for that), exactly as in-process.
|
|
769
|
+
ensureSynced: (keys) => rpc<void>("ensureSynced", [keys]),
|
|
770
|
+
// `isSynced` is the SYNCHRONOUS peek in-process (`isTableStarted` — is the group's stream STARTED). It
|
|
771
|
+
// cannot be an RPC (its signature returns a boolean, not a promise), and the tab's cached state cannot
|
|
772
|
+
// answer it: the bridge delivers per-group CATCH-UP readiness (`status.groups` / `groupReady`), which is
|
|
773
|
+
// strictly weaker than activation-started — an activated-but-not-yet-caught-up lazy group reads as
|
|
774
|
+
// not-ready, the very case `isSynced` exists to distinguish. So no faithful synchronous answer is derivable.
|
|
775
|
+
isSynced: () => {
|
|
776
|
+
throw new Error(
|
|
777
|
+
"[pgxsinkit] client.isSynced is not available on a worker-attached client: it is a SYNCHRONOUS " +
|
|
778
|
+
"activation-STARTED peek (in-process: isTableStarted), but the tab caches only per-group CATCH-UP " +
|
|
779
|
+
"readiness (status.groups / groupReady) — an activated-but-not-caught-up group reads as not-ready — " +
|
|
780
|
+
"so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " +
|
|
781
|
+
"client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.",
|
|
782
|
+
);
|
|
783
|
+
},
|
|
697
784
|
// In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for
|
|
698
785
|
// EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower
|
|
699
786
|
// `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).
|
|
@@ -804,6 +891,18 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
804
891
|
},
|
|
805
892
|
};
|
|
806
893
|
|
|
894
|
+
// The `pglite` misuse trap MUST be a NON-ENUMERABLE throwing getter, never an enumerable property
|
|
895
|
+
// holding a throw-on-get Proxy: host tooling reflects over the client wherever the app hands it around
|
|
896
|
+
// (React 19.2's dev-build render logging serializes prop diffs property-by-property — observed crashing
|
|
897
|
+
// a <SyncClientProvider client={...}> re-render — and console inspection / object spreads do the same),
|
|
898
|
+
// and an enumerable trap turns that passive reflection into a crash. Non-enumerable keeps the trap out
|
|
899
|
+
// of every enumeration path while a direct `client.pglite` touch still throws the misuse error.
|
|
900
|
+
Object.defineProperty(client, "pglite", {
|
|
901
|
+
get: notSupported("client.pglite"),
|
|
902
|
+
enumerable: false,
|
|
903
|
+
configurable: true,
|
|
904
|
+
});
|
|
905
|
+
|
|
807
906
|
return client;
|
|
808
907
|
}
|
|
809
908
|
|
|
@@ -7,10 +7,13 @@
|
|
|
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
|
+
|
|
10
12
|
import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
|
|
11
13
|
|
|
12
14
|
import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
|
|
13
15
|
import { setSyncDebugSink, syncDebug } from "../debug";
|
|
16
|
+
import { describeErrorChain } from "../error-chain";
|
|
14
17
|
import {
|
|
15
18
|
type ClientPGlite,
|
|
16
19
|
createClientPGlite,
|
|
@@ -40,6 +43,7 @@ import {
|
|
|
40
43
|
type BridgeEvent,
|
|
41
44
|
type BridgePort,
|
|
42
45
|
type ExportArtefactWire,
|
|
46
|
+
type GuardedQueryWireArgs,
|
|
43
47
|
identityCodec,
|
|
44
48
|
isBridgeEnvelope,
|
|
45
49
|
postBridgeMessage,
|
|
@@ -52,6 +56,29 @@ import {
|
|
|
52
56
|
} from "./protocol";
|
|
53
57
|
import { createWorkerTokenCache } from "./token-cache";
|
|
54
58
|
|
|
59
|
+
// The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4). It
|
|
60
|
+
// MIRRORS the fixed `parsers` constant in `drizzle-orm/pglite`'s session VERBATIM (pinned to
|
|
61
|
+
// drizzle-orm@1.0.0-rc.4, `drizzle-orm/pglite/session.js`): identity parsers so the listed OIDs come back as
|
|
62
|
+
// raw STRINGS — exactly what the in-process drizzle session receives, because it passes this same map into
|
|
63
|
+
// `pglite.query`. The members are: the scalar OIDs `types.TIMESTAMP` / `TIMESTAMPTZ` / `INTERVAL` / `DATE`,
|
|
64
|
+
// and the array OIDs 1115 = `timestamp[]`, 1185 = `timestamptz[]`, 1187 = `interval[]`, 1182 = `date[]`, and
|
|
65
|
+
// 1231 = `numeric[]` (NOT temporal — drizzle's list is mirrored verbatim, whatever its members). Over the
|
|
66
|
+
// bridge the map is FUNCTIONS (non-serializable), so the attach side strips the options down to `rowMode`
|
|
67
|
+
// and this worker re-applies the identical map. We do NOT import drizzle's private constant — this is a
|
|
68
|
+
// deliberate, version-pinned mirror.
|
|
69
|
+
const identityParser = (value: string): string => value;
|
|
70
|
+
const DRIZZLE_PGLITE_IDENTITY_PARSERS: ParserOptions = {
|
|
71
|
+
[types.TIMESTAMP]: identityParser,
|
|
72
|
+
[types.TIMESTAMPTZ]: identityParser,
|
|
73
|
+
[types.INTERVAL]: identityParser,
|
|
74
|
+
[types.DATE]: identityParser,
|
|
75
|
+
1231: identityParser,
|
|
76
|
+
1115: identityParser,
|
|
77
|
+
1185: identityParser,
|
|
78
|
+
1187: identityParser,
|
|
79
|
+
1182: identityParser,
|
|
80
|
+
};
|
|
81
|
+
|
|
55
82
|
export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
56
83
|
/**
|
|
57
84
|
* The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
|
|
@@ -74,6 +101,21 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
74
101
|
* Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
|
|
75
102
|
*/
|
|
76
103
|
createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
|
|
104
|
+
/**
|
|
105
|
+
* Relax PGlite's per-query durability for every store this worker mints (default `true`; ADR-0047). A
|
|
106
|
+
* worker-ENTRY option (baked into the worker file as code, like {@link convergenceIntervalMs}), NOT an
|
|
107
|
+
* attach option — a tab cannot set it. Forwarded to the worker's default {@link createPglite} factory (the
|
|
108
|
+
* provision/spare mint) AND to the {@link createSyncClient} boot, so it governs whichever path mints the
|
|
109
|
+
* store. Ignored when a custom {@link createPglite} is injected (that factory owns its own create).
|
|
110
|
+
*
|
|
111
|
+
* On PGlite's idb backend the per-query synchronous flush to IndexedDB dominates local write latency, so
|
|
112
|
+
* the toolkit defaults to relaxed: the query returns before the flush and the flush is scheduled
|
|
113
|
+
* asynchronously. Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a
|
|
114
|
+
* crash before BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the
|
|
115
|
+
* scheduled idb flush lands — synced tables are recoverable from the server by construction, so this
|
|
116
|
+
* relaxes flush TIMING, not persistence (ADR-0036). Opt out with `relaxedDurability: false`.
|
|
117
|
+
*/
|
|
118
|
+
relaxedDurability?: boolean;
|
|
77
119
|
electricUrl: string;
|
|
78
120
|
writeUrl: string;
|
|
79
121
|
/** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
|
|
@@ -109,6 +151,32 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
109
151
|
precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
|
|
110
152
|
/** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
|
|
111
153
|
pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
|
|
154
|
+
/**
|
|
155
|
+
* App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
|
|
156
|
+
* schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
|
|
157
|
+
* timing as the in-process client. This is a worker-ENTRY option (baked into the worker file as code),
|
|
158
|
+
* NOT an attach option: the hook is a function and functions cannot cross the bridge, so a tab can never
|
|
159
|
+
* supply it — the worker owns it. Use it for DDL that must precede the registry's local tables (extensions,
|
|
160
|
+
* a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
|
|
161
|
+
* this runs (that ordering is what distinguishes it from {@link prepareLocalDb}).
|
|
162
|
+
*
|
|
163
|
+
* Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
|
|
164
|
+
* {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
|
|
165
|
+
* runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
|
|
166
|
+
* invariant does not hold there.
|
|
167
|
+
*/
|
|
168
|
+
prepareLocalDbBeforeSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbBeforeSchema"];
|
|
169
|
+
/**
|
|
170
|
+
* App-level schema prep run IN THE WORKER, against the engine's own local store, AFTER the registry schema
|
|
171
|
+
* exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDb}, same timing as the in-process
|
|
172
|
+
* client. Like {@link prepareLocalDbBeforeSchema} this is a worker-ENTRY option, never an attach option (the
|
|
173
|
+
* tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
|
|
174
|
+
* that depend on the registry's local tables, which DO exist by the time this runs.
|
|
175
|
+
*
|
|
176
|
+
* Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
|
|
177
|
+
* {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
|
|
178
|
+
*/
|
|
179
|
+
prepareLocalDb?: CreateSyncClientOptions<TRegistry>["prepareLocalDb"];
|
|
112
180
|
/**
|
|
113
181
|
* Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
|
|
114
182
|
* subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
|
|
@@ -160,7 +228,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
160
228
|
const createPglite =
|
|
161
229
|
options.createPglite ??
|
|
162
230
|
((storePath: string, backendOverride?: "memory") =>
|
|
163
|
-
|
|
231
|
+
// Relaxed durability (ADR-0047): the default factory forwards the worker-entry choice into
|
|
232
|
+
// `createClientPGlite`, which resolves the `?? true` default. A store minted for a spare/provision
|
|
233
|
+
// (`provision` handler) is thus created under the same durability mode the boot create uses.
|
|
234
|
+
createClientPGlite(storePath, {
|
|
235
|
+
...(backendOverride ? { backendOverride } : {}),
|
|
236
|
+
...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
|
|
237
|
+
}));
|
|
164
238
|
// A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
|
|
165
239
|
// non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
|
|
166
240
|
// which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
|
|
@@ -409,6 +483,14 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
409
483
|
...(provisionStamp ? { provisionStamp } : {}),
|
|
410
484
|
...(precreatedPglite ? { precreatedPglite } : {}),
|
|
411
485
|
...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
|
|
486
|
+
// App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
|
|
487
|
+
// the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
|
|
488
|
+
...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
|
|
489
|
+
...(options.prepareLocalDb ? { prepareLocalDb: options.prepareLocalDb } : {}),
|
|
490
|
+
// Relaxed durability (ADR-0047): forward the worker-entry choice to the client-owned boot create too
|
|
491
|
+
// (the storePath / precreated-fallback path inside createSyncClient), so a worker that never adopts a
|
|
492
|
+
// provisioned spare still mints its store under the chosen durability mode.
|
|
493
|
+
...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
|
|
412
494
|
// Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
|
|
413
495
|
// spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
|
|
414
496
|
// journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
|
|
@@ -428,7 +510,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
428
510
|
onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
|
|
429
511
|
onReject: (details) => broadcastEvent({ kind: "reject", details }),
|
|
430
512
|
onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: "schema-change", event }),
|
|
431
|
-
|
|
513
|
+
// The cause chain, not just the wrapper message: the bridge carries a string, and dropping
|
|
514
|
+
// `.cause` here hid the actual database error from every tab (SQLSTATE, detail).
|
|
515
|
+
onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: describeErrorChain(error) }),
|
|
432
516
|
// Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
|
|
433
517
|
// push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
|
|
434
518
|
onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
|
|
@@ -445,6 +529,22 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
445
529
|
|
|
446
530
|
// ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
|
|
447
531
|
const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
|
|
532
|
+
// Guarded-read parser re-application (ADR-0032 decision 4). A guarded read compiled by the tab's
|
|
533
|
+
// Drizzle-over-bridge arrives as the {@link GuardedQueryWireArgs} tuple `[sql, params?, { rowMode? }, use?]`:
|
|
534
|
+
// the `parsers` map drizzle's pglite session normally passes could not cross the bridge (it is FUNCTIONS,
|
|
535
|
+
// not clonable), so the tab stripped it and we re-apply the identical map here before executing. Without it
|
|
536
|
+
// PGlite's default parsers would turn the identity-parsed OIDs (temporal OIDs + `numeric[]`) into `Date`s
|
|
537
|
+
// and numbers, whereas the in-process drizzle session sees them as raw STRINGS — so a guarded read would
|
|
538
|
+
// diverge from its in-process twin exactly on those columns. Typed against `GuardedQueryWireArgs` so the
|
|
539
|
+
// decode here shares the wire contract with the tab-side encoders (attach-sync-client).
|
|
540
|
+
const runGuardedQueryRpc = (): Promise<unknown> => {
|
|
541
|
+
const [sql, params, options, use] = args as unknown as GuardedQueryWireArgs;
|
|
542
|
+
const queryOptions: QueryOptions = {
|
|
543
|
+
...(options?.rowMode ? { rowMode: options.rowMode } : {}),
|
|
544
|
+
parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS,
|
|
545
|
+
};
|
|
546
|
+
return active.guardedRawQuery(sql, params, queryOptions, use as readonly SyncTableName<TRegistry>[] | undefined);
|
|
547
|
+
};
|
|
448
548
|
type TableKey = SyncTableName<TRegistry>;
|
|
449
549
|
switch (op) {
|
|
450
550
|
case "create":
|
|
@@ -491,6 +591,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
491
591
|
return active.desync(args[0] as TableKey);
|
|
492
592
|
case "discardEphemeral":
|
|
493
593
|
return active.discardEphemeral(args[0] as TableKey);
|
|
594
|
+
case "ensureSynced":
|
|
595
|
+
// Lazy activation (ADR-0021) on the worker's real client. Engine-wide but additive/idempotent — a tab
|
|
596
|
+
// activating a group another tab already started is a no-op, so no cross-tab revert hazard (cf. desync).
|
|
597
|
+
return active.ensureSynced(args[0] as readonly TableKey[]);
|
|
494
598
|
case "readMutationDetails":
|
|
495
599
|
return active.readMutationDetails(args[0] as TableKey | undefined);
|
|
496
600
|
case "diagnostics":
|
|
@@ -503,6 +607,12 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
503
607
|
return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
|
|
504
608
|
case "rawExec":
|
|
505
609
|
return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
|
|
610
|
+
case "guardedQuery":
|
|
611
|
+
// Guarded one-shot Drizzle read (ADR-0032 decision 4): the ADR-0041 read gate + the ADR-0021
|
|
612
|
+
// lazy-group guard run worker-side inside the engine's `guardedRawQuery`, so a read referencing a
|
|
613
|
+
// lazy relation activates its group exactly as in-process. The full `Results` structured-clones back
|
|
614
|
+
// and drizzle's own mapping (relational/nested included) runs on the tab.
|
|
615
|
+
return runGuardedQueryRpc();
|
|
506
616
|
case "bootReport":
|
|
507
617
|
// Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
|
|
508
618
|
// reads a boot predating it; the report structured-clones across the bridge as a plain object.
|
|
@@ -19,6 +19,7 @@ import type { LiveNamespace, LiveQuery, LiveQueryResults } from "@electric-sql/p
|
|
|
19
19
|
import { syncDebug } from "../debug";
|
|
20
20
|
import { computeLiveDiff, type LiveDiffState, seedLiveDiffState } from "./live-diff";
|
|
21
21
|
import { fingerprintLiveQuery } from "./live-query-fingerprint";
|
|
22
|
+
import { assertLiveQueryParamsSafe } from "./live-query-params-guard";
|
|
22
23
|
import type { LiveDiffPayload } from "./protocol";
|
|
23
24
|
|
|
24
25
|
type Row = Record<string, unknown>;
|
|
@@ -452,6 +453,11 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
452
453
|
`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`,
|
|
453
454
|
);
|
|
454
455
|
}
|
|
456
|
+
// Reject a param shape that would trip PGlite bug #1055's broken live-query param inlining BEFORE any
|
|
457
|
+
// fingerprinting or registration (see live-query-params-guard.ts). Synchronous, so every subscriber —
|
|
458
|
+
// in-process and worker alike — fails loudly rather than binding wrong rows or hitting a cryptic
|
|
459
|
+
// `format()` error deep inside PGlite.
|
|
460
|
+
assertLiveQueryParamsSafe(spec.materialSql, spec.params);
|
|
455
461
|
const keepAliveMs = hint ?? 0;
|
|
456
462
|
const scope = opts?.scope;
|
|
457
463
|
// Track this whole call so `dispose()` can drain the post-await join before it settles the teardown set —
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// A defensive guard against PGlite upstream bug https://github.com/electric-sql/pglite/issues/1055 on the
|
|
2
|
+
// live-query path. WHY this exists:
|
|
3
|
+
//
|
|
4
|
+
// PGlite 0.5.4's `live.query` / `live.incrementalQuery` inline bound params into a `CREATE TEMP VIEW`
|
|
5
|
+
// (via `formatQuery`) WHENEVER `params.length > 0`. That inlining rewrites every `$N` placeholder with
|
|
6
|
+
// `sql.replace(/\$([0-9]+)/g, (_, n) => "%" + n + "L")` — emitting `%NL`, which is Postgres `format()`'s
|
|
7
|
+
// "pad to width N, consume the NEXT argument sequentially" directive, NOT the positional `%N$L` it means to
|
|
8
|
+
// emit. Empirically confirmed consequences:
|
|
9
|
+
// - out-of-order placeholders (`… $2 … $1 …`) silently bind params in TEXTUAL order → wrong rows;
|
|
10
|
+
// - a repeated placeholder (`$1 … $1`) throws `too few arguments for format()`;
|
|
11
|
+
// - a skipped placeholder silently mis-binds.
|
|
12
|
+
// The ONLY input shape under which PGlite's broken inlining is still correct: the placeholders, read in
|
|
13
|
+
// textual order, are exactly `$1, $2, …, $n` (n = params.length) — each appearing exactly once, strictly
|
|
14
|
+
// ascending. Drizzle-compiled SQL always satisfies this (its serializer numbers params in the same
|
|
15
|
+
// left-to-right pass that emits them); hand-written raw SQL may not.
|
|
16
|
+
//
|
|
17
|
+
// So this guard fails LOUDLY at the client boundary for any other shape, turning a silent wrong-rows /
|
|
18
|
+
// cryptic-`format()` failure into an actionable error naming the upstream bug. It can be DELETED once
|
|
19
|
+
// transcrobes/pgxsinkit pin a PGlite release whose `formatQuery` emits the positional `%N$L`.
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Throw if `sql` + `params` would hit PGlite bug #1055's broken param inlining (see the module header).
|
|
23
|
+
*
|
|
24
|
+
* `params.length === 0` returns immediately: PGlite skips `formatQuery` entirely in that case, so any `$N`
|
|
25
|
+
* tokens are Postgres's own concern, not this guard's. Otherwise the SQL is scanned with the SAME regex
|
|
26
|
+
* PGlite's rewrite uses (`/\$(\d+)/g`) — deliberately, so the guard sees EXACTLY the tokens PGlite would
|
|
27
|
+
* touch. That includes a `$1` sitting inside a string literal: PGlite would corrupt that too, so a loud
|
|
28
|
+
* false positive here is a feature, not a bug — it flags SQL PGlite cannot inline safely regardless.
|
|
29
|
+
*
|
|
30
|
+
* Safe iff the collected numbers (in textual order) are exactly `[1, 2, …, params.length]`. Anything else —
|
|
31
|
+
* out-of-order, repeated, skipped, or a count mismatch in either direction — throws.
|
|
32
|
+
*/
|
|
33
|
+
export function assertLiveQueryParamsSafe(sql: string, params: readonly unknown[]): void {
|
|
34
|
+
// No params → PGlite never calls formatQuery, so its broken inlining never runs. Placeholders without
|
|
35
|
+
// params are Postgres's problem to report, not this guard's.
|
|
36
|
+
if (params.length === 0) return;
|
|
37
|
+
|
|
38
|
+
// The SAME regex PGlite's `formatQuery` applies — so we see exactly the tokens its rewrite would touch,
|
|
39
|
+
// including any `$N` inside a string literal (which PGlite would corrupt too; flagging it is intentional).
|
|
40
|
+
const numbers: number[] = [];
|
|
41
|
+
for (const match of sql.matchAll(/\$(\d+)/g)) numbers.push(Number(match[1]));
|
|
42
|
+
|
|
43
|
+
const expected = params.length;
|
|
44
|
+
const safe = numbers.length === expected && numbers.every((n, i) => n === i + 1);
|
|
45
|
+
if (safe) return;
|
|
46
|
+
|
|
47
|
+
const found = numbers.length === 0 ? "(none)" : numbers.map((n) => `$${n}`).join(", ");
|
|
48
|
+
throw new Error(
|
|
49
|
+
`[pgxsinkit] live query hits PGlite bug #1055 ` +
|
|
50
|
+
`(https://github.com/electric-sql/pglite/issues/1055): its live-query param inlining binds $N ` +
|
|
51
|
+
`placeholders SEQUENTIALLY (in textual order), not positionally, so anything but a strictly ` +
|
|
52
|
+
`ascending $1..$n each used once silently mis-binds or throws. Found placeholders [${found}] for ` +
|
|
53
|
+
`${expected} param${expected === 1 ? "" : "s"}, expected exactly [$1..$${expected}]. Renumber the ` +
|
|
54
|
+
`placeholders to a strictly sequential $1..$${expected}, each used once — or pass the query as a ` +
|
|
55
|
+
`Drizzle builder, which always compiles to that shape.`,
|
|
56
|
+
);
|
|
57
|
+
}
|