@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
|
@@ -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
|
@@ -80,18 +80,18 @@ export interface BootReport {
|
|
|
80
80
|
writeReadyMs: number | null;
|
|
81
81
|
/**
|
|
82
82
|
* Present only when the store was pre-provisioned (a spare's initdb ran off-thread before this boot
|
|
83
|
-
* adopted it); `null` otherwise. When present, `phases.
|
|
83
|
+
* adopted it); `null` otherwise. When present, `phases.pgwasmCreateMs` is `null` — the create cost is
|
|
84
84
|
* reported here instead.
|
|
85
85
|
*/
|
|
86
86
|
provision: {
|
|
87
|
-
/** The spare's
|
|
87
|
+
/** The spare's pgwasm create (initdb) cost, paid at provision time. */
|
|
88
88
|
initdbMs: number;
|
|
89
89
|
/** How long the provisioned store sat ready before this boot adopted it. */
|
|
90
90
|
provisionedMsBeforeBoot: number;
|
|
91
91
|
} | null;
|
|
92
92
|
phases: {
|
|
93
|
-
/**
|
|
94
|
-
|
|
93
|
+
/** pgwasm create cost, or `null` when the store was adopted from a spare (see {@link BootReport.provision}). */
|
|
94
|
+
pgwasmCreateMs: number | null;
|
|
95
95
|
schemaExecMs: number;
|
|
96
96
|
journalRecoveryMs: number;
|
|
97
97
|
storeVersionReconcileMs: number;
|
|
@@ -156,7 +156,7 @@ export interface BootReport {
|
|
|
156
156
|
*/
|
|
157
157
|
fetchMs: number;
|
|
158
158
|
/**
|
|
159
|
-
* Wall around this group's batch commits into
|
|
159
|
+
* Wall around this group's batch commits into pgwasm. Includes waiting behind another group's
|
|
160
160
|
* transaction on the shared connection (single writer), so concurrent groups' `applyMs` can overlap.
|
|
161
161
|
*/
|
|
162
162
|
applyMs: number;
|
|
@@ -174,7 +174,7 @@ type PhaseKey = "schemaExec" | "journalRecovery" | "storeVersionReconcile" | "sy
|
|
|
174
174
|
export interface GroupBootStamp {
|
|
175
175
|
/** A batch was delivered to the group's subscribe callback (one response). `changeCount` = its change rows. */
|
|
176
176
|
onBatchDelivered: (changeCount: number) => void;
|
|
177
|
-
/** A commit transaction applied `ms` of work into
|
|
177
|
+
/** A commit transaction applied `ms` of work into pgwasm for this group. */
|
|
178
178
|
onApply: (ms: number) => void;
|
|
179
179
|
/** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */
|
|
180
180
|
markReady: () => void;
|
|
@@ -329,7 +329,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
|
|
|
329
329
|
const bootStartPerf = nowMs();
|
|
330
330
|
const durations = new Map<PhaseKey, number>();
|
|
331
331
|
let prepareMs: number | null = null;
|
|
332
|
-
let
|
|
332
|
+
let pgwasmCreateMs: number | null = null;
|
|
333
333
|
let provision: BootReport["provision"] = null;
|
|
334
334
|
// Conservative defaults used until the boot path reports its actual schema and recovery outcomes through
|
|
335
335
|
// the setters below.
|
|
@@ -369,7 +369,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
|
|
|
369
369
|
}
|
|
370
370
|
},
|
|
371
371
|
setPgliteCreateMs: (ms) => {
|
|
372
|
-
|
|
372
|
+
pgwasmCreateMs = ms;
|
|
373
373
|
},
|
|
374
374
|
setProvision: (value) => {
|
|
375
375
|
provision = value;
|
|
@@ -432,7 +432,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
|
|
|
432
432
|
provision,
|
|
433
433
|
warmBoot,
|
|
434
434
|
phases: {
|
|
435
|
-
|
|
435
|
+
pgwasmCreateMs,
|
|
436
436
|
schemaExecMs: duration("schemaExec"),
|
|
437
437
|
journalRecoveryMs: duration("journalRecovery"),
|
|
438
438
|
storeVersionReconcileMs: duration("storeVersionReconcile"),
|
|
@@ -3,13 +3,43 @@ import type { StreamEnvelope, StreamValue, SyncOperation } from "@pgxsinkit/cont
|
|
|
3
3
|
import type { ApplyTarget } from "../local-tables";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* Separator the engine joins composite primary-key values with (`schema.rs`, `
|
|
6
|
+
* Separator the engine joins composite primary-key values with (`schema.rs`, `PK_SEP`).
|
|
7
7
|
*
|
|
8
8
|
* ASCII Unit Separator, chosen upstream so it cannot collide with real id text. Restated here rather
|
|
9
9
|
* than derived: getting it wrong does not fail loudly, it produces deletes that match no row.
|
|
10
10
|
*/
|
|
11
11
|
const PK_SEPARATOR = "\u001f";
|
|
12
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
|
+
|
|
13
43
|
/** The applier's message shape, once an envelope has been resolved against its table. */
|
|
14
44
|
export interface ChangeLike {
|
|
15
45
|
key: string;
|
|
@@ -42,30 +72,95 @@ function coercePrimaryKeyValue(sqlType: string, raw: string): StreamValue {
|
|
|
42
72
|
}
|
|
43
73
|
|
|
44
74
|
/**
|
|
45
|
-
* Rebuild the primary-key columns of a row from the stream key.
|
|
75
|
+
* Rebuild the LOCAL primary-key columns of a row from the stream key.
|
|
46
76
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
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.
|
|
51
85
|
*/
|
|
52
86
|
export function primaryKeyFromStreamKey(target: ApplyTarget, key: string): Record<string, unknown> {
|
|
53
|
-
const
|
|
54
|
-
|
|
87
|
+
const serverKey = target.serverPrimaryKey;
|
|
88
|
+
const parts = serverKey.length === 1 ? [key] : key.split(PK_SEPARATOR).map(unescapeKeyComponent);
|
|
89
|
+
if (parts.length !== serverKey.length) {
|
|
55
90
|
throw new Error(
|
|
56
|
-
`[pgxsinkit] stream key "${key}" splits into ${parts.length} part(s) but the
|
|
57
|
-
`${
|
|
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(", ")})`,
|
|
58
93
|
);
|
|
59
94
|
}
|
|
60
95
|
|
|
96
|
+
const localKey = new Set(target.primaryKey);
|
|
61
97
|
const row: Record<string, unknown> = {};
|
|
62
|
-
|
|
98
|
+
serverKey.forEach((column, index) => {
|
|
99
|
+
if (!localKey.has(column)) return;
|
|
63
100
|
const sqlType = target.columnTypes.find((type) => type.name === column)?.sqlType ?? "text";
|
|
64
101
|
row[column] = coercePrimaryKeyValue(sqlType, parts[index]!);
|
|
65
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
|
+
}
|
|
66
111
|
return row;
|
|
67
112
|
}
|
|
68
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
|
+
|
|
69
164
|
/**
|
|
70
165
|
* Translate a Circuits envelope into the message the applier consumes.
|
|
71
166
|
*
|
|
@@ -98,5 +193,19 @@ export function envelopeToChange(target: ApplyTarget, envelope: StreamEnvelope):
|
|
|
98
193
|
);
|
|
99
194
|
}
|
|
100
195
|
|
|
101
|
-
|
|
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" } };
|
|
102
211
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { PGliteInterface } from "@electric-sql/pglite";
|
|
2
1
|
import { and, eq, getTableName, isNull, sql, type SQL } from "drizzle-orm";
|
|
3
2
|
|
|
4
3
|
import type { PredicateValue, SyncTableEntry, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
4
|
+
import type { Pgwasm } from "@pgxsinkit/pgwasm";
|
|
5
5
|
|
|
6
6
|
import type { BootStampCollector, GroupBootStamp } from "../boot-report";
|
|
7
7
|
import { resolveApplyTarget, type ApplyTarget } from "../local-tables";
|
|
@@ -371,7 +371,7 @@ const SUBSCRIBE_RETRY_BASE_MS = 250;
|
|
|
371
371
|
const SUBSCRIBE_RETRY_MAX_MS = 10_000;
|
|
372
372
|
|
|
373
373
|
export async function startCircuitsSync(
|
|
374
|
-
pg:
|
|
374
|
+
pg: Pgwasm,
|
|
375
375
|
options: CircuitsGroupSyncOptions,
|
|
376
376
|
): Promise<CircuitsGroupSyncResult> {
|
|
377
377
|
const specs = deriveSpecs(options.registry);
|
|
@@ -105,6 +105,12 @@ export interface ShapeStreamSubscription {
|
|
|
105
105
|
* read is over and nothing failed"; `onEnd(error)` is the mid-session reset (ADR-0056 decision 7)
|
|
106
106
|
* that a caller must answer with a re-subscribe.
|
|
107
107
|
*
|
|
108
|
+
* ORDERING GUARANTEE: `onEnd(null)` is called only AFTER `onBatch` has been handed the batch that
|
|
109
|
+
* ends the read (the up-to-date batch of a `live: false` read; the `Stream-Closed` batch of any
|
|
110
|
+
* read). `closed` alone does not give that — it settles when the transport's fetch loop is done,
|
|
111
|
+
* which for a non-live read can be before the subscriber has consumed the final response — so the
|
|
112
|
+
* normal end is reported off the terminal batch, and a caller may close on `onEnd` without losing it.
|
|
113
|
+
*
|
|
108
114
|
* The transport only. Everything above it — the fold, apply modes, the boot gate — stays
|
|
109
115
|
* pgxsinkit's, which is ADR-0009's precedent applied to a new substrate: keep the transport,
|
|
110
116
|
* internalize the semantics.
|
|
@@ -124,6 +130,20 @@ export async function readShapeStream(
|
|
|
124
130
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
125
131
|
});
|
|
126
132
|
|
|
133
|
+
const live = options.live ?? true;
|
|
134
|
+
|
|
135
|
+
// Our OWN close is not an end worth reporting: the caller asked for it, and a group tearing its
|
|
136
|
+
// streams down would otherwise hear K "the stream ended" reports and try to recover from a stop it
|
|
137
|
+
// ordered. `cancel()` resolves `closed` rather than rejecting it, so this suppresses a normal end;
|
|
138
|
+
// the flag also covers the race where a close lands while a read error is already in flight.
|
|
139
|
+
let closedByCaller = false;
|
|
140
|
+
let endReported = false;
|
|
141
|
+
const reportEnd = (error: Error | null): void => {
|
|
142
|
+
if (endReported || closedByCaller) return;
|
|
143
|
+
endReported = true;
|
|
144
|
+
onEnd?.(error);
|
|
145
|
+
};
|
|
146
|
+
|
|
127
147
|
const unsubscribe = response.subscribeJson(async (batch) => {
|
|
128
148
|
await onBatch({
|
|
129
149
|
// The server flattens arrays onto the stream (PROTOCOL.md §9.1.2), so a batch's items are
|
|
@@ -140,20 +160,26 @@ export async function readShapeStream(
|
|
|
140
160
|
// inbox and no error anywhere.
|
|
141
161
|
upToDate: batch.upToDate,
|
|
142
162
|
});
|
|
163
|
+
// THE NORMAL END IS REPORTED HERE, off the batch that ends the read — never off `closed`. The
|
|
164
|
+
// transport settles `closed` when its FETCH loop is done, and for a non-live read whose first
|
|
165
|
+
// response is already up-to-date that is inside `stream()` itself: the response is enqueued and
|
|
166
|
+
// the loop closed in the same tick, BEFORE any subscriber has consumed it. An `onEnd(null)` fired
|
|
167
|
+
// off that moment says "over, nothing failed" while the final batch is still queued, and a caller
|
|
168
|
+
// that (reasonably) closes on it aborts the subscriber loop with the batch undelivered — a
|
|
169
|
+
// `live: false` read of a populated stream then yields nothing, silently. The batch that ends a
|
|
170
|
+
// read is the transport's own stopping rule: a non-live read stops at its first up-to-date
|
|
171
|
+
// response, and any read stops at `Stream-Closed`.
|
|
172
|
+
if (batch.streamClosed === true || (!live && batch.upToDate)) reportEnd(null);
|
|
143
173
|
});
|
|
144
174
|
|
|
145
|
-
// Our OWN close is not an end worth reporting: the caller asked for it, and a group tearing its
|
|
146
|
-
// streams down would otherwise hear K "the stream ended" reports and try to recover from a stop it
|
|
147
|
-
// ordered. `cancel()` resolves `closed` rather than rejecting it, so this suppresses a normal end;
|
|
148
|
-
// the flag also covers the race where a close lands while a read error is already in flight.
|
|
149
|
-
let closedByCaller = false;
|
|
150
175
|
void response.closed.then(
|
|
151
176
|
() => {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if (
|
|
177
|
+
// A normal transport close is answered by the terminal batch above, which is already queued
|
|
178
|
+
// for the subscriber. The one normal close with NOTHING queued is the caller's own abort
|
|
179
|
+
// signal, and that one would otherwise wait forever.
|
|
180
|
+
if (options.signal?.aborted) reportEnd(null);
|
|
156
181
|
},
|
|
182
|
+
(error: unknown) => reportEnd(error instanceof Error ? error : new Error(String(error))),
|
|
157
183
|
);
|
|
158
184
|
|
|
159
185
|
return {
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
|
|
2
1
|
import { sql } from "drizzle-orm";
|
|
3
2
|
|
|
4
3
|
import {
|
|
@@ -7,6 +6,9 @@ import {
|
|
|
7
6
|
type PredicateValue,
|
|
8
7
|
type SyncTableRegistry,
|
|
9
8
|
} from "@pgxsinkit/contracts";
|
|
9
|
+
// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
|
|
10
|
+
// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
|
|
11
|
+
import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
|
|
10
12
|
|
|
11
13
|
import { nowMs, type GroupBootStamp } from "../boot-report";
|
|
12
14
|
import { resolveApplyTarget, type ApplyTarget } from "../local-tables";
|
|
@@ -89,7 +91,7 @@ export interface CircuitsShapeSpec {
|
|
|
89
91
|
}
|
|
90
92
|
|
|
91
93
|
export interface CircuitsSyncOptions {
|
|
92
|
-
pg:
|
|
94
|
+
pg: Pgwasm;
|
|
93
95
|
registry: SyncTableRegistry;
|
|
94
96
|
/** Subscription key for persisted resume state; `null` disables persistence. */
|
|
95
97
|
key: string | null;
|
|
@@ -385,7 +387,7 @@ export async function syncCircuitsShapes(options: CircuitsSyncOptions): Promise<
|
|
|
385
387
|
});
|
|
386
388
|
}
|
|
387
389
|
|
|
388
|
-
// Discard rather than persist work during teardown:
|
|
390
|
+
// Discard rather than persist work during teardown: pgwasm skips the COMMIT once the tx is
|
|
389
391
|
// rolled back, so both the rows and the offset advance are undone and a resume re-streams.
|
|
390
392
|
if (unsubscribed) await tx.rollback();
|
|
391
393
|
});
|
|
@@ -619,7 +621,7 @@ async function assertClearLeftNoResidue({
|
|
|
619
621
|
shapeName,
|
|
620
622
|
soleOccupant,
|
|
621
623
|
}: {
|
|
622
|
-
pg:
|
|
624
|
+
pg: Pgwasm | Transaction;
|
|
623
625
|
target: ApplyTarget;
|
|
624
626
|
shapeName: string;
|
|
625
627
|
soleOccupant: boolean;
|