@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
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Supplying the Postgres build, and the build refusals
|
|
2
|
+
|
|
3
|
+
A store runs on a **Postgres build** — `cBuild` from `@pgxsinkit/pgwasm-c` by default — and belongs to the
|
|
4
|
+
build that created it. Full page: <https://pgxsinkit.github.io/concepts/postgres-builds/>.
|
|
5
|
+
|
|
6
|
+
## Where the build is supplied
|
|
7
|
+
|
|
8
|
+
- `createSyncClient({ build })` — the in-process client and the tab of a worker-mode app.
|
|
9
|
+
- `defineSyncWorker({ build })` — a worker-entry option, never on the wire; e.g. `createCBuild({ assets })`
|
|
10
|
+
over assets warmed inside the worker.
|
|
11
|
+
- `createPgwasmClient(storePath, { build })` — the eager spare-store create. It runs the exact same create the
|
|
12
|
+
client does internally (the `live` extension, the build's warm, the `boot pgwasm.create` stamp). A rejected
|
|
13
|
+
`precreatedPgwasm` falls back to the `storePath` create path on the same `build`.
|
|
14
|
+
|
|
15
|
+
`createCBuild({ assets })` takes a `Promise<CBuildAssets>` (`{ postgresWasmModule, initdbWasmModule, fsBundle }`,
|
|
16
|
+
whose URLs `cBuildArtefacts` holds). A rejected `assets` falls back to the build's own lazy load; the warm never
|
|
17
|
+
fails the boot. The client awaits the build's `prepare()` (an unfinished warm) before it starts the
|
|
18
|
+
`boot pgwasm.create` stamp, so `phases.pgwasmCreateMs` measures the create alone. The board demo's
|
|
19
|
+
`apps/board/src/board/pgwasm-warm.ts` (`warmCBuildAssets()`) reads the URLs from `cBuildArtefacts`, compiles
|
|
20
|
+
them from the login route, and stamps `boot pgwasm build warm`.
|
|
21
|
+
|
|
22
|
+
## Worker mode: don't hand the engine the tab's compiled modules
|
|
23
|
+
|
|
24
|
+
The engine loads the build's own assets deliberately. The tab's warm still serves it by priming the
|
|
25
|
+
same-origin HTTP cache the worker fetches from. Handing the engine a pre-compiled `WebAssembly.Module` benched
|
|
26
|
+
NET-NEGATIVE: it forces compile-to-completion before instantiate (forfeiting the build's streaming-load
|
|
27
|
+
pipelining), and the engine realm's only overlap window is the placement/handshake gap, so the compile just
|
|
28
|
+
competes for CPU at spawn.
|
|
29
|
+
|
|
30
|
+
## The declaration and the check
|
|
31
|
+
|
|
32
|
+
The registry declares the build as `storage.build` (`"c"`, the default, or `"pgrust"`; see the contracts
|
|
33
|
+
`registry-authoring` skill). The declaration only names it; the app supplies the build as code. Before any
|
|
34
|
+
store is touched, the client checks the supplied build — and an adopted `pgwasmInstance` / `precreatedPgwasm`
|
|
35
|
+
through its own `pg.build` — against the declaration.
|
|
36
|
+
|
|
37
|
+
## The typed refusals (permanent: fix the input, never retry)
|
|
38
|
+
|
|
39
|
+
- `StorageBuildMismatchError` (`@pgxsinkit/contracts`): the supplied or adopted build is not the declared one.
|
|
40
|
+
Fix the build at the named site, or correct `storage.build` together with a fresh store path.
|
|
41
|
+
- `BuildMismatchError` (`@pgxsinkit/pgwasm`): the data directory or backup was made by another build.
|
|
42
|
+
- `DataFormatMismatchError` (`@pgxsinkit/pgwasm`): the directory or backup is another data format.
|
|
43
|
+
- `BuildMarkerUnreadableError` (`@pgxsinkit/pgwasm`): the directory's build marker can't be read.
|
|
44
|
+
- `StorageDeclarationRefusedError`: two declarations explicitly disagree (e.g. a dynamic declaration on the
|
|
45
|
+
wire vs the registry's).
|
|
46
|
+
|
|
47
|
+
These are not transient, so the client's bounded OPFS open retry propagates them at once. A store backup
|
|
48
|
+
(`exportStore()`) restores only into the build that made it.
|
package/src/boot-report.ts
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
import { syncDebug } from "./debug";
|
|
12
12
|
|
|
13
13
|
/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */
|
|
14
|
-
|
|
14
|
+
/** The monotonic clock every boot offset and duration in this module is measured on. */
|
|
15
|
+
export const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:
|
|
@@ -79,23 +80,23 @@ export interface BootReport {
|
|
|
79
80
|
writeReadyMs: number | null;
|
|
80
81
|
/**
|
|
81
82
|
* Present only when the store was pre-provisioned (a spare's initdb ran off-thread before this boot
|
|
82
|
-
* adopted it); `null` otherwise. When present, `phases.
|
|
83
|
+
* adopted it); `null` otherwise. When present, `phases.pgwasmCreateMs` is `null` — the create cost is
|
|
83
84
|
* reported here instead.
|
|
84
85
|
*/
|
|
85
86
|
provision: {
|
|
86
|
-
/** The spare's
|
|
87
|
+
/** The spare's pgwasm create (initdb) cost, paid at provision time. */
|
|
87
88
|
initdbMs: number;
|
|
88
89
|
/** How long the provisioned store sat ready before this boot adopted it. */
|
|
89
90
|
provisionedMsBeforeBoot: number;
|
|
90
91
|
} | null;
|
|
91
92
|
phases: {
|
|
92
|
-
/**
|
|
93
|
-
|
|
93
|
+
/** pgwasm create cost, or `null` when the store was adopted from a spare (see {@link BootReport.provision}). */
|
|
94
|
+
pgwasmCreateMs: number | null;
|
|
94
95
|
schemaExecMs: number;
|
|
95
96
|
journalRecoveryMs: number;
|
|
96
97
|
storeVersionReconcileMs: number;
|
|
97
98
|
/**
|
|
98
|
-
* `
|
|
99
|
+
* `startCircuitsSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
|
|
99
100
|
* {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema, journal
|
|
100
101
|
* recovery, and registry reconciliation, so this includes that shared wall. Structurally 0 when the boot
|
|
101
102
|
* is ready inside the
|
|
@@ -155,7 +156,7 @@ export interface BootReport {
|
|
|
155
156
|
*/
|
|
156
157
|
fetchMs: number;
|
|
157
158
|
/**
|
|
158
|
-
* Wall around this group's batch commits into
|
|
159
|
+
* Wall around this group's batch commits into pgwasm. Includes waiting behind another group's
|
|
159
160
|
* transaction on the shared connection (single writer), so concurrent groups' `applyMs` can overlap.
|
|
160
161
|
*/
|
|
161
162
|
applyMs: number;
|
|
@@ -173,13 +174,13 @@ type PhaseKey = "schemaExec" | "journalRecovery" | "storeVersionReconcile" | "sy
|
|
|
173
174
|
export interface GroupBootStamp {
|
|
174
175
|
/** A batch was delivered to the group's subscribe callback (one response). `changeCount` = its change rows. */
|
|
175
176
|
onBatchDelivered: (changeCount: number) => void;
|
|
176
|
-
/** A commit transaction applied `ms` of work into
|
|
177
|
+
/** A commit transaction applied `ms` of work into pgwasm for this group. */
|
|
177
178
|
onApply: (ms: number) => void;
|
|
178
179
|
/** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */
|
|
179
180
|
markReady: () => void;
|
|
180
181
|
}
|
|
181
182
|
|
|
182
|
-
/** The seam `
|
|
183
|
+
/** The seam `startCircuitsSync` uses to open a boot group's accumulator (implemented by the builder). */
|
|
183
184
|
export interface BootStampCollector {
|
|
184
185
|
beginGroup: (groupKey: string, tables: number) => GroupBootStamp;
|
|
185
186
|
}
|
|
@@ -328,7 +329,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
|
|
|
328
329
|
const bootStartPerf = nowMs();
|
|
329
330
|
const durations = new Map<PhaseKey, number>();
|
|
330
331
|
let prepareMs: number | null = null;
|
|
331
|
-
let
|
|
332
|
+
let pgwasmCreateMs: number | null = null;
|
|
332
333
|
let provision: BootReport["provision"] = null;
|
|
333
334
|
// Conservative defaults used until the boot path reports its actual schema and recovery outcomes through
|
|
334
335
|
// the setters below.
|
|
@@ -368,7 +369,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
|
|
|
368
369
|
}
|
|
369
370
|
},
|
|
370
371
|
setPgliteCreateMs: (ms) => {
|
|
371
|
-
|
|
372
|
+
pgwasmCreateMs = ms;
|
|
372
373
|
},
|
|
373
374
|
setProvision: (value) => {
|
|
374
375
|
provision = value;
|
|
@@ -431,7 +432,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
|
|
|
431
432
|
provision,
|
|
432
433
|
warmBoot,
|
|
433
434
|
phases: {
|
|
434
|
-
|
|
435
|
+
pgwasmCreateMs,
|
|
435
436
|
schemaExecMs: duration("schemaExec"),
|
|
436
437
|
journalRecoveryMs: duration("journalRecovery"),
|
|
437
438
|
storeVersionReconcileMs: duration("storeVersionReconcile"),
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import type { StreamEnvelope, StreamValue, SyncOperation } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
import type { ApplyTarget } from "../local-tables";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Separator the engine joins composite primary-key values with (`schema.rs`, `PK_SEP`).
|
|
7
|
+
*
|
|
8
|
+
* ASCII Unit Separator, chosen upstream so it cannot collide with real id text. Restated here rather
|
|
9
|
+
* than derived: getting it wrong does not fail loudly, it produces deletes that match no row.
|
|
10
|
+
*/
|
|
11
|
+
const PK_SEPARATOR = "\u001f";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Decode one component of a COMPOSITE stream key — the exact inverse of the engine's
|
|
15
|
+
* `escape_key_component` (`schema.rs`): `\\` was a literal backslash, `\x1f` (four characters) was a
|
|
16
|
+
* literal U+001F. The escaping is what makes the joined key an injective encoding of the tuple, so an
|
|
17
|
+
* escaped component contains no bare separator and the split-then-unescape here recovers exactly the
|
|
18
|
+
* original values. Single-column keys are NOT escaped upstream and never reach this function. Any
|
|
19
|
+
* other backslash sequence cannot be engine output — throw rather than guess at an identity.
|
|
20
|
+
*/
|
|
21
|
+
function unescapeKeyComponent(part: string): string {
|
|
22
|
+
if (!part.includes("\\")) return part;
|
|
23
|
+
let out = "";
|
|
24
|
+
for (let i = 0; i < part.length; i += 1) {
|
|
25
|
+
const ch = part[i]!;
|
|
26
|
+
if (ch !== "\\") {
|
|
27
|
+
out += ch;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (part[i + 1] === "\\") {
|
|
31
|
+
out += "\\";
|
|
32
|
+
i += 1;
|
|
33
|
+
} else if (part.startsWith("x1f", i + 1)) {
|
|
34
|
+
out += PK_SEPARATOR;
|
|
35
|
+
i += 3;
|
|
36
|
+
} else {
|
|
37
|
+
throw new Error(`[pgxsinkit] stream key component ${JSON.stringify(part)} carries an unknown escape sequence`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The applier's message shape, once an envelope has been resolved against its table. */
|
|
44
|
+
export interface ChangeLike {
|
|
45
|
+
key: string;
|
|
46
|
+
value: Record<string, unknown>;
|
|
47
|
+
headers: { operation: SyncOperation };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Coerce one primary-key value out of its key-string rendering.
|
|
52
|
+
*
|
|
53
|
+
* The engine writes keys through `Value::to_key_string`, which erases type: `Int(42)` becomes
|
|
54
|
+
* `"42"`, `Bool(true)` becomes `"true"`. A delete carries **only** that key, so the pk has to be
|
|
55
|
+
* re-typed here or the `WHERE` binds text against a non-text column.
|
|
56
|
+
*
|
|
57
|
+
* `bigint` and `numeric` stay strings deliberately — routing them through `Number` would lose
|
|
58
|
+
* precision above 2^53, and a silently-wrong id is worse than a driver-level coercion.
|
|
59
|
+
*/
|
|
60
|
+
function coercePrimaryKeyValue(sqlType: string, raw: string): StreamValue {
|
|
61
|
+
switch (sqlType) {
|
|
62
|
+
case "integer":
|
|
63
|
+
case "smallint":
|
|
64
|
+
case "serial":
|
|
65
|
+
case "smallserial":
|
|
66
|
+
return Number(raw);
|
|
67
|
+
case "boolean":
|
|
68
|
+
return raw === "true";
|
|
69
|
+
default:
|
|
70
|
+
return raw;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Rebuild the LOCAL primary-key columns of a row from the stream key.
|
|
76
|
+
*
|
|
77
|
+
* The key is the SERVER identity: composite keys are joined in server primary-key declaration order
|
|
78
|
+
* (escaped per component — see {@link unescapeKeyComponent}), single keys are the raw value. Under a
|
|
79
|
+
* `clientProjection.localPrimaryKey` narrowing the local key is a subset of the server key, so the
|
|
80
|
+
* split runs over `serverPrimaryKey` and only the local components are kept — the dropped ones are
|
|
81
|
+
* predicate-pinned (subscribe-time compile refuses the narrowing otherwise), so within this shape
|
|
82
|
+
* the narrowed key is still unique. A count mismatch is thrown rather than tolerated: a silently
|
|
83
|
+
* short split would produce a `WHERE` over only part of the key, and a delete matching more rows
|
|
84
|
+
* than it should is data loss, not a stale row.
|
|
85
|
+
*/
|
|
86
|
+
export function primaryKeyFromStreamKey(target: ApplyTarget, key: string): Record<string, unknown> {
|
|
87
|
+
const serverKey = target.serverPrimaryKey;
|
|
88
|
+
const parts = serverKey.length === 1 ? [key] : key.split(PK_SEPARATOR).map(unescapeKeyComponent);
|
|
89
|
+
if (parts.length !== serverKey.length) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
`[pgxsinkit] stream key "${key}" splits into ${parts.length} part(s) but the server identity is a ` +
|
|
92
|
+
`${serverKey.length}-column primary key (${serverKey.join(", ")})`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const localKey = new Set(target.primaryKey);
|
|
97
|
+
const row: Record<string, unknown> = {};
|
|
98
|
+
serverKey.forEach((column, index) => {
|
|
99
|
+
if (!localKey.has(column)) return;
|
|
100
|
+
const sqlType = target.columnTypes.find((type) => type.name === column)?.sqlType ?? "text";
|
|
101
|
+
row[column] = coercePrimaryKeyValue(sqlType, parts[index]!);
|
|
102
|
+
});
|
|
103
|
+
for (const column of target.primaryKey) {
|
|
104
|
+
if (!(column in row)) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
`[pgxsinkit] local primary-key column "${column}" is not part of the server key ` +
|
|
107
|
+
`(${serverKey.join(", ")}) — the stream key cannot address the local row`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return row;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Decode the cells of the SCALAR `json`/`jsonb` columns in a streamed row — **the one place the wire's
|
|
116
|
+
* text becomes a JS value**, and the invariant every apply tier below depends on.
|
|
117
|
+
*
|
|
118
|
+
* THE WIRE CARRIES A JSON COLUMN AS TEXT. The engine's cell model is five scalars (`value.rs`:
|
|
119
|
+
* `Null | Int | Text | Bool | Float`), and its Postgres type map (`pg.rs` `map_pg_type`) sends everything
|
|
120
|
+
* that is not int/float/bool through `Text` — so a `jsonb` column is emitted as a JSON **string** holding
|
|
121
|
+
* Postgres's own output text (`t.col::text` on the backfill path, `test_decoding`'s text on the live path;
|
|
122
|
+
* that is deliberate upstream, so a backfilled row and its first replicated update compare equal). Hence
|
|
123
|
+
* `{"lang.v1": {"levelOrdinal": 1}}` — `jsonb_out` spacing, which `JSON.stringify` never emits.
|
|
124
|
+
*
|
|
125
|
+
* Left as text, every apply tier then encodes that text a SECOND time and the local column ends up holding
|
|
126
|
+
* a JSON *string scalar* (`jsonb_typeof` = `'string'`) instead of the document: `json_to_recordset` escapes
|
|
127
|
+
* a JSON string into a JSON literal when the target column is json/jsonb (`populate_scalar`), the COPY
|
|
128
|
+
* serializer runs `JSON.stringify` over it (`copy.ts` `jsonToText`), and drizzle's `jsonb` codec does the
|
|
129
|
+
* same on the param-bound tiers. All three were measured doing exactly that. Decoding here — once, at the
|
|
130
|
+
* boundary — fixes all of them at their shared root, and matches what the appliers have always documented
|
|
131
|
+
* they receive ("json/jsonb as parsed objects/arrays").
|
|
132
|
+
*
|
|
133
|
+
* ARRAY columns (json arrays included) are deliberately NOT decoded: they arrive as Postgres `array_out`
|
|
134
|
+
* text, which every tier hands back to `array_in` — the recordset cast, COPY's field text, and drizzle's
|
|
135
|
+
* array codec all accept the literal verbatim (measured), so parsing it here would only mean re-rendering
|
|
136
|
+
* it below.
|
|
137
|
+
*
|
|
138
|
+
* A cell that is not a string (a wire that already sent a parsed value) is passed through untouched, so
|
|
139
|
+
* the decode is idempotent. A string that is not valid JSON cannot come from Postgres — the server column
|
|
140
|
+
* validated it — so it throws rather than being stored as text.
|
|
141
|
+
*/
|
|
142
|
+
function decodeJsonColumns(target: ApplyTarget, value: Record<string, unknown>): Record<string, unknown> {
|
|
143
|
+
let decoded: Record<string, unknown> | undefined;
|
|
144
|
+
for (const column of target.jsonColumns) {
|
|
145
|
+
const cell = value[column];
|
|
146
|
+
if (typeof cell !== "string") continue;
|
|
147
|
+
let parsed: unknown;
|
|
148
|
+
try {
|
|
149
|
+
parsed = JSON.parse(cell);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
`[pgxsinkit] json column "${column}" carried a value that is not JSON text: ${JSON.stringify(
|
|
153
|
+
cell.slice(0, 120),
|
|
154
|
+
)}`,
|
|
155
|
+
{ cause: error },
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
decoded ??= { ...value };
|
|
159
|
+
decoded[column] = parsed;
|
|
160
|
+
}
|
|
161
|
+
return decoded ?? value;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Translate a Circuits envelope into the message the applier consumes.
|
|
166
|
+
*
|
|
167
|
+
* There is no operation mapping to do — {@link SyncOperation} is the wire's own vocabulary. What
|
|
168
|
+
* this function carries is the one structural difference: **a delete has no row body**, only its
|
|
169
|
+
* key, so the pk columns are reconstructed here. That is a privacy improvement (an eviction
|
|
170
|
+
* discloses the key and nothing else) and an implementation hazard in the same change, which is why
|
|
171
|
+
* the reconstruction is a named, tested function rather than an inline split.
|
|
172
|
+
*
|
|
173
|
+
* An `upsert` carries the **complete projected row** every time — the engine's `row_to_json_cols`
|
|
174
|
+
* emits every column of the shape's `out_cols`, never a changed-column subset — which is what lets
|
|
175
|
+
* the apply path refresh every non-pk column from `excluded` without knowing whether the row already
|
|
176
|
+
* existed locally.
|
|
177
|
+
*/
|
|
178
|
+
export function envelopeToChange(target: ApplyTarget, envelope: StreamEnvelope): ChangeLike {
|
|
179
|
+
const operation = envelope.headers.operation;
|
|
180
|
+
|
|
181
|
+
if (operation === "delete") {
|
|
182
|
+
return {
|
|
183
|
+
key: envelope.key,
|
|
184
|
+
value: primaryKeyFromStreamKey(target, envelope.key),
|
|
185
|
+
headers: { operation: "delete" },
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (envelope.value === undefined) {
|
|
190
|
+
throw new Error(
|
|
191
|
+
`[pgxsinkit] ${operation} envelope for key "${envelope.key}" carries no row body — only a ` +
|
|
192
|
+
`delete may omit one`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// The engine force-includes every server pk component in the emitted row (its `resolve_columns`
|
|
197
|
+
// keeps them "so the client can identify rows"), so under a localPrimaryKey narrowing the pinned,
|
|
198
|
+
// projected-away components arrive anyway. Project exactly those off; any other column the local
|
|
199
|
+
// table lacks still fails loudly in the applier's re-keying.
|
|
200
|
+
let value: Record<string, unknown> = envelope.value;
|
|
201
|
+
if (target.droppedKeyColumns.length > 0) {
|
|
202
|
+
value = { ...value };
|
|
203
|
+
for (const column of target.droppedKeyColumns) {
|
|
204
|
+
delete value[column];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// The wire→JS decode: a json column's text becomes its value here and stays a value all the way to the
|
|
209
|
+
// store (see {@link decodeJsonColumns}).
|
|
210
|
+
return { key: envelope.key, value: decodeJsonColumns(target, value), headers: { operation: "upsert" } };
|
|
211
|
+
}
|