@pgxsinkit/client 0.2.7 → 0.3.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/README.md +2 -1
- package/dist/boot-report.d.ts +5 -2
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +35 -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 +90 -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/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +47 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6258 -6443
- package/dist/index.js.map +26 -26
- package/dist/local-tables.d.ts +1 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +13 -21
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +8 -8
- 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 +21 -2
- 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.js +3 -3
- package/dist/testing.js.map +2 -2
- package/dist/worker/attach-sync-client.d.ts +3 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -1
- 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/package.json +4 -5
- package/skills/core/SKILL.md +72 -55
- package/skills/operating/SKILL.md +120 -120
- package/src/boot-report.ts +4 -3
- package/src/circuits/envelope-to-change.ts +102 -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 +165 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +641 -0
- package/src/debug.ts +1 -85
- package/src/export-dump.ts +3 -2
- package/src/index.ts +290 -273
- package/src/lazy-guard.ts +1 -1
- package/src/local-tables.ts +9 -2
- package/src/schema.ts +2 -11
- package/src/sync/apply.ts +72 -110
- package/src/sync/copy.ts +15 -15
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +42 -1
- package/src/sync/subscription-state.ts +21 -3
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +8 -1
- package/src/worker/define-sync-worker.ts +122 -13
- package/src/worker/engine-control.ts +89 -0
- 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,641 @@
|
|
|
1
|
+
import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
|
|
2
|
+
import { sql } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
classifyTableApplyStrategy,
|
|
6
|
+
type ApplyStrategy,
|
|
7
|
+
type PredicateValue,
|
|
8
|
+
type SyncTableRegistry,
|
|
9
|
+
} from "@pgxsinkit/contracts";
|
|
10
|
+
|
|
11
|
+
import { nowMs, type GroupBootStamp } from "../boot-report";
|
|
12
|
+
import { resolveApplyTarget, type ApplyTarget } from "../local-tables";
|
|
13
|
+
import {
|
|
14
|
+
applyBulkDeletesToTable,
|
|
15
|
+
applyInsertsToTable,
|
|
16
|
+
applyMessagesToTableWithCopy,
|
|
17
|
+
applyMessagesToTableWithJson,
|
|
18
|
+
applyUpsertsToTable,
|
|
19
|
+
applyUpsertsToTableWithJson,
|
|
20
|
+
} from "../sync/apply";
|
|
21
|
+
import { drizzleOverPg } from "../sync/drizzle-executor";
|
|
22
|
+
import { foldChangeBatch } from "../sync/fold";
|
|
23
|
+
import { getSubscriptionState, updateSubscriptionState } from "../sync/subscription-state";
|
|
24
|
+
import type { InitialInsertMethod } from "../sync/types";
|
|
25
|
+
import { envelopeToChange, type ChangeLike } from "./envelope-to-change";
|
|
26
|
+
import { createShapeGroup, type ShapeGroup } from "./shape-group";
|
|
27
|
+
import { StreamInbox } from "./stream-inbox";
|
|
28
|
+
import type { StreamSourceOptions } from "./stream-source";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The engine's convergence barrier, read through the control plane (ADR-0056 decision 4).
|
|
32
|
+
*
|
|
33
|
+
* Never a bare position: `pendingFlips` counts computed-but-undelivered subquery flips — membership
|
|
34
|
+
* move-out and move-in — so a barrier without it reports convergence while a revocation is still in
|
|
35
|
+
* the engine. That is silent staleness on exactly the security-relevant path.
|
|
36
|
+
*
|
|
37
|
+
* `flipFailures` is the term the others cannot express. A flip batch abandoned after its retries
|
|
38
|
+
* carried membership effects that are **gone**, not late: the engine keeps that batch's
|
|
39
|
+
* `pendingFlips` count held forever and latches itself degraded — 503 on `/v1/health` and on every
|
|
40
|
+
* membership-bearing route, subquery streams reaped, recovery only by operator restart. The waiting
|
|
41
|
+
* terms are therefore honest but permanently unsatisfied, which is indistinguishable from a slow
|
|
42
|
+
* engine; this term is how a client tells the two apart.
|
|
43
|
+
*
|
|
44
|
+
* These are the fields of `GET /replication/lsn` this client aligns on. Nothing here is derived, and
|
|
45
|
+
* nothing here is optional — a term the engine does not report is a term this client must not claim
|
|
46
|
+
* to check. The engine's `sync` field is deliberately absent: it is the `__el_sync` sentinel
|
|
47
|
+
* watermark, not a convergence term (see `replicationState` in the server's engine client).
|
|
48
|
+
*/
|
|
49
|
+
export interface ConvergenceBarrier {
|
|
50
|
+
/** Deferred subquery flip batches not yet propagated. Read engine-global — conservative. */
|
|
51
|
+
pendingFlips: number;
|
|
52
|
+
/**
|
|
53
|
+
* Flip batches the engine abandoned. Non-zero means membership effects were **lost**, not delayed
|
|
54
|
+
* — unrecoverable in-process, and terminal for any group that reads it.
|
|
55
|
+
*/
|
|
56
|
+
flipFailures: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface CircuitsShapeSpec {
|
|
60
|
+
/** Absolute URL of this shape's stream through the edge. */
|
|
61
|
+
streamUrl: string;
|
|
62
|
+
/** The registry table key this shape applies into. Several shapes may share one (ADR-0055 d4). */
|
|
63
|
+
tableKey: string;
|
|
64
|
+
/**
|
|
65
|
+
* What this reader IS, as the registry and the control plane name it — persisted alongside the
|
|
66
|
+
* offset so a later subscribe can resolve a stored entry back to its spec.
|
|
67
|
+
*
|
|
68
|
+
* Required, not derived, and the map key is why it cannot be either. That key is a name the caller
|
|
69
|
+
* mints to keep two readers apart; the engine treats it as opaque and has no way to take it apart
|
|
70
|
+
* again. Without this, a persisted entry the next subscribe does NOT find in its grants is
|
|
71
|
+
* unattributable — which is exactly the entry that has to be cleared (ADR-0055 decision 6).
|
|
72
|
+
*/
|
|
73
|
+
identity: {
|
|
74
|
+
/** The registry shape key this stream carries. */
|
|
75
|
+
shapeKey: string;
|
|
76
|
+
/** Shared tier only: the scope values the grant named, in the shape's declared column order. */
|
|
77
|
+
scope?: readonly PredicateValue[];
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Scoped cache clear for a must-refetch, replacing the default `TRUNCATE`.
|
|
81
|
+
*
|
|
82
|
+
* **Required when several shapes share a `tableKey`**, and the engine refuses the group otherwise:
|
|
83
|
+
* the default truncate would wipe a co-tenant scope's rows. A shared-tier shape derives it from
|
|
84
|
+
* its scope key, so supplying one is mechanical rather than a burden.
|
|
85
|
+
*/
|
|
86
|
+
onMustRefetch?: (db: ReturnType<typeof drizzleOverPg>) => Promise<void>;
|
|
87
|
+
/** Per-shape backfill strategy override; otherwise the registry's classification. */
|
|
88
|
+
initialInsertMethod?: InitialInsertMethod;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface CircuitsSyncOptions {
|
|
92
|
+
pg: PGliteInterface;
|
|
93
|
+
registry: SyncTableRegistry;
|
|
94
|
+
/** Subscription key for persisted resume state; `null` disables persistence. */
|
|
95
|
+
key: string | null;
|
|
96
|
+
metadataSchema: string;
|
|
97
|
+
shapes: Record<string, CircuitsShapeSpec>;
|
|
98
|
+
token: StreamSourceOptions["token"];
|
|
99
|
+
onTokenRejected?: StreamSourceOptions["onTokenRejected"];
|
|
100
|
+
/** Reads the engine barrier through the control plane. Consulted once per alignment generation. */
|
|
101
|
+
readBarrier: () => Promise<ConvergenceBarrier>;
|
|
102
|
+
sessionScoped?: boolean;
|
|
103
|
+
/**
|
|
104
|
+
* Boot observability (ADR-0034). Present only for a BOOT group — an on-demand lazy activation gets
|
|
105
|
+
* none, so post-boot traffic never enters a finalized report.
|
|
106
|
+
*/
|
|
107
|
+
bootStamp?: GroupBootStamp;
|
|
108
|
+
onInitialSync?: () => void;
|
|
109
|
+
onSyncError?: (error: Error) => void;
|
|
110
|
+
onSyncActivity?: () => void;
|
|
111
|
+
/**
|
|
112
|
+
* One shape's read ended — `null` for a normal end, an error for a stream that died mid-session.
|
|
113
|
+
*
|
|
114
|
+
* Passed through from the shape group and deliberately NOT acted on here. Recovery is a
|
|
115
|
+
* re-subscribe, and this engine has no subscription: it is handed URLs and a token by the layer
|
|
116
|
+
* above (ADR-0055 decision 10), which is the only layer that can ask the control plane for a fresh
|
|
117
|
+
* grant. Ignored once `unsubscribe()` has been called — a teardown's own stream closes are not
|
|
118
|
+
* conditions.
|
|
119
|
+
*/
|
|
120
|
+
onStreamEnd?: (shapeName: string, error: Error | null) => void;
|
|
121
|
+
/**
|
|
122
|
+
* Long-poll the tail after catching up (default). `false` reads each stream to its tail and stops
|
|
123
|
+
* — a one-shot hydration rather than a live subscription.
|
|
124
|
+
*/
|
|
125
|
+
live?: boolean;
|
|
126
|
+
maxCommitRetries?: number;
|
|
127
|
+
commitRetryDelayMs?: (attempt: number) => number;
|
|
128
|
+
debug?: boolean;
|
|
129
|
+
fetch?: typeof fetch;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface CircuitsSyncHandle {
|
|
133
|
+
unsubscribe(): void;
|
|
134
|
+
readonly isUpToDate: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Map the statically-resolved apply strategy (ADR-0009 decision 3) onto the backfill path. No
|
|
139
|
+
* strategy defaults to `copy`: the COPY TEXT serializer round-trips every built-in type, so it is
|
|
140
|
+
* the safe bootstrap rather than the fast one.
|
|
141
|
+
*/
|
|
142
|
+
function applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {
|
|
143
|
+
switch (strategy) {
|
|
144
|
+
case "json":
|
|
145
|
+
return "json";
|
|
146
|
+
case "insert":
|
|
147
|
+
return "insert";
|
|
148
|
+
default:
|
|
149
|
+
return "copy";
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const DEFAULT_MAX_COMMIT_RETRIES = 5;
|
|
154
|
+
const defaultRetryDelayMs = (attempt: number) => Math.min(1000 * 2 ** (attempt - 1), 8000);
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Sync K Circuits shape streams into one consistency group (ADR-0055 + ADR-0056).
|
|
158
|
+
*
|
|
159
|
+
* The commit gate is the whole of ADR-0056's steady state: **commit when every shape's most recent
|
|
160
|
+
* response asserted up-to-date**. That is a happens-before, not a position comparison. Offsets are
|
|
161
|
+
* per-stream and the protocol only sanctions comparing them within a stream, so no `min` over
|
|
162
|
+
* positions exists to take, and none is taken.
|
|
163
|
+
*
|
|
164
|
+
* The happens-before is airtight at ALIGNMENT — every stream has drained what the server held, and
|
|
165
|
+
* everything held commits together — and weaker in the live steady state, where every stream's report
|
|
166
|
+
* is latched true between parked long polls and each delivery commits on arrival. Two streams
|
|
167
|
+
* carrying halves of one server transaction are answered separately, so the window in which one half
|
|
168
|
+
* is applied and the other is not is their response inter-arrival, normally milliseconds. Closing it
|
|
169
|
+
* needs a fence the engine does not emit — see `docs/backlog/0014-cross-stream-commit-fence.md`.
|
|
170
|
+
*
|
|
171
|
+
* The barrier is consulted **once per alignment generation**, at boot and after any must-refetch.
|
|
172
|
+
* Its job there is narrow and specific: every stream can report drained while the engine still holds
|
|
173
|
+
* a computed revocation, and a boot that claimed consistency in that window would present a store
|
|
174
|
+
* missing an eviction. Mid-session the same condition is just a change arriving late.
|
|
175
|
+
*/
|
|
176
|
+
export async function syncCircuitsShapes(options: CircuitsSyncOptions): Promise<CircuitsSyncHandle> {
|
|
177
|
+
const {
|
|
178
|
+
pg,
|
|
179
|
+
registry,
|
|
180
|
+
key,
|
|
181
|
+
metadataSchema,
|
|
182
|
+
shapes,
|
|
183
|
+
sessionScoped = false,
|
|
184
|
+
debug = false,
|
|
185
|
+
maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,
|
|
186
|
+
commitRetryDelayMs = defaultRetryDelayMs,
|
|
187
|
+
bootStamp,
|
|
188
|
+
} = options;
|
|
189
|
+
|
|
190
|
+
const shapeNames = Object.keys(shapes);
|
|
191
|
+
const { soleOccupants } = resolveTableSharing(shapes);
|
|
192
|
+
|
|
193
|
+
const targets = new Map<string, ApplyTarget>(
|
|
194
|
+
shapeNames.map((shapeName) => [shapeName, resolveApplyTarget(registry, shapes[shapeName]!.tableKey)]),
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
const subState =
|
|
198
|
+
key === null ? null : await getSubscriptionState({ pg, metadataSchema, subscriptionKey: key, sessionScoped });
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Which shapes may resume, and which must re-snapshot (ADR-0056 decision 6).
|
|
202
|
+
*
|
|
203
|
+
* The native must-refetch trigger is **the handle**, and it is discovered here rather than
|
|
204
|
+
* received. The persisted handle is the stream this shape was reading; the granted one is the
|
|
205
|
+
* stream the control plane has just named for it. When they differ the stored offset addresses a
|
|
206
|
+
* *different stream*, and ds offsets carry no meaning across streams (PROTOCOL.md §10.2) — so
|
|
207
|
+
* resuming from it is not stale, it is undefined.
|
|
208
|
+
*
|
|
209
|
+
* Every native reset funnels through this one check. A shape the engine evicted, a stream deleted
|
|
210
|
+
* (404) or soft-deleted (410) underneath a live read, a stream that closed — each one ends with
|
|
211
|
+
* the client re-subscribing, and re-subscribing is what produces a new path. That is the whole
|
|
212
|
+
* mechanism: Electric needed an out-of-band `must-refetch` control message because its handles
|
|
213
|
+
* were opaque server state the client could not compare, and here the client simply notices.
|
|
214
|
+
*/
|
|
215
|
+
const resumable = new Set(
|
|
216
|
+
shapeNames.filter((shapeName) => {
|
|
217
|
+
const persisted = subState?.shape_metadata[shapeName];
|
|
218
|
+
return persisted?.offset != null && persisted.handle === shapes[shapeName]!.streamUrl;
|
|
219
|
+
}),
|
|
220
|
+
);
|
|
221
|
+
const rehydrating = shapeNames.filter((shapeName) => !resumable.has(shapeName) && subState !== null);
|
|
222
|
+
|
|
223
|
+
// Per shape, the backfill strategy: an explicit override, else the registry's build-time
|
|
224
|
+
// classification. Resolved per shape rather than per group so one shape's column profile never
|
|
225
|
+
// forces its siblings onto a slower path.
|
|
226
|
+
const insertMethod = new Map<string, InitialInsertMethod>(
|
|
227
|
+
shapeNames.map((shapeName) => [
|
|
228
|
+
shapeName,
|
|
229
|
+
shapes[shapeName]!.initialInsertMethod ??
|
|
230
|
+
applyStrategyToInsertMethod(classifyTableApplyStrategy(registry[shapes[shapeName]!.tableKey]!)),
|
|
231
|
+
]),
|
|
232
|
+
);
|
|
233
|
+
// A resume starts in plain-insert mode: the bulk backfill path is only ever correct onto an empty
|
|
234
|
+
// table, which is a fresh subscription or a post-must-refetch re-snapshot. A shape whose handle
|
|
235
|
+
// changed is the second of those — its rows are about to be cleared — so it takes the bulk path
|
|
236
|
+
// too, rather than being penalised for a reset it did not cause.
|
|
237
|
+
const useBulkBackfill = new Map<string, boolean>(
|
|
238
|
+
shapeNames.map((shapeName) => [shapeName, !resumable.has(shapeName) && insertMethod.get(shapeName) !== "insert"]),
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
const inbox = new StreamInbox(shapeNames);
|
|
242
|
+
// Seeded, not merely declared: a shape re-hydrating onto a store that still holds the previous
|
|
243
|
+
// stream's rows must clear them in the same transaction the new snapshot lands in, or the two
|
|
244
|
+
// memberships merge and every row the shape lost stays visible forever.
|
|
245
|
+
const truncateNeeded = new Set<string>(rehydrating);
|
|
246
|
+
let unsubscribed = false;
|
|
247
|
+
let degraded = false;
|
|
248
|
+
let commitInFlight: Promise<void> | null = null;
|
|
249
|
+
let commitRerun = false;
|
|
250
|
+
let initialSyncSignalled = false;
|
|
251
|
+
|
|
252
|
+
const bulkAppliers = {
|
|
253
|
+
json: applyMessagesToTableWithJson,
|
|
254
|
+
copy: applyMessagesToTableWithCopy,
|
|
255
|
+
insert: applyInsertsToTable,
|
|
256
|
+
} as const;
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Apply everything currently held, in one transaction, and persist each shape's offset with it.
|
|
260
|
+
*
|
|
261
|
+
* Peek rather than drain: the batch stays in the inbox until the transaction actually succeeds, so
|
|
262
|
+
* a commit that exhausts its retries HOLDS its work instead of losing it, and the persisted offset
|
|
263
|
+
* does not advance — a later resume re-streams exactly that batch.
|
|
264
|
+
*/
|
|
265
|
+
const commitHeld = async (): Promise<boolean> => {
|
|
266
|
+
const appliedAt = nowMs();
|
|
267
|
+
const held = inbox.peekAll();
|
|
268
|
+
const epochsAtPeek = inbox.snapshotEpochs();
|
|
269
|
+
const offsets = inbox.pendingOffsets();
|
|
270
|
+
const shapesToTruncate = new Set(truncateNeeded);
|
|
271
|
+
|
|
272
|
+
const runCommit = () =>
|
|
273
|
+
pg.transaction(async (tx) => {
|
|
274
|
+
// Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin flag the apply trigger
|
|
275
|
+
// reads to tell streamed server truth from local writes. GUCs have no tier-①/② builder form.
|
|
276
|
+
await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);
|
|
277
|
+
|
|
278
|
+
for (const shapeName of shapeNames) {
|
|
279
|
+
const target = targets.get(shapeName)!;
|
|
280
|
+
const spec = shapes[shapeName]!;
|
|
281
|
+
let changes = held.get(shapeName) ?? [];
|
|
282
|
+
|
|
283
|
+
if (shapesToTruncate.has(shapeName)) {
|
|
284
|
+
if (spec.onMustRefetch) {
|
|
285
|
+
await spec.onMustRefetch(drizzleOverPg(tx));
|
|
286
|
+
await assertClearLeftNoResidue({ pg: tx, target, shapeName, soleOccupant: soleOccupants.has(shapeName) });
|
|
287
|
+
} else {
|
|
288
|
+
// A must-refetch wipe is engine cache maintenance, not server truth (ADR-0029 D4), so it
|
|
289
|
+
// TRUNCATEs rather than reacting per row. Tier ②: TRUNCATE has no Drizzle builder, so the
|
|
290
|
+
// table object is interpolated rather than its name spliced.
|
|
291
|
+
await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// The bulk backfill fast path: the leading run of upserts, bulk-loaded onto an empty table
|
|
296
|
+
// (a fresh subscription or a post-truncate re-snapshot) through a tier that cannot express
|
|
297
|
+
// ON CONFLICT. What that tier requires is DISTINCT primary keys — and on the two-verb wire
|
|
298
|
+
// (ADR-0058) the run does not supply them: `upsert` asserts a row's value and says nothing
|
|
299
|
+
// about whether it existed, so a stream read from `-1` carries one envelope per revision
|
|
300
|
+
// and any key ever updated repeats. That is the ordinary shape of a fresh replay, not an
|
|
301
|
+
// anomaly. So the run is folded to its net rows first — ADR-0014's fold, the same one the
|
|
302
|
+
// remainder takes; for an all-upsert run it yields no deletes and exactly one row per key,
|
|
303
|
+
// last wins in stream order. A plain INSERT of DISTINCT keys onto an empty table is what
|
|
304
|
+
// the fast path buys.
|
|
305
|
+
if (useBulkBackfill.get(shapeName) && changes.length > 0) {
|
|
306
|
+
const leadingUpserts: ChangeLike[] = [];
|
|
307
|
+
const remainder: ChangeLike[] = [];
|
|
308
|
+
let sawDelete = false;
|
|
309
|
+
for (const change of changes) {
|
|
310
|
+
if (!sawDelete && change.headers.operation === "upsert") leadingUpserts.push(change);
|
|
311
|
+
else {
|
|
312
|
+
sawDelete = true;
|
|
313
|
+
remainder.push(change);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const backfill = foldChangeBatch(leadingUpserts as never).upserts;
|
|
317
|
+
const method = insertMethod.get(shapeName)!;
|
|
318
|
+
// COPY has no ON CONFLICT clause and cannot be mixed with a following per-row apply of the
|
|
319
|
+
// same key, so the last net row is handed back to the fold rather than bulk-loaded.
|
|
320
|
+
if (backfill.length > 0 && method === "copy") remainder.unshift(backfill.pop()!);
|
|
321
|
+
changes = remainder;
|
|
322
|
+
|
|
323
|
+
if (backfill.length > 0) {
|
|
324
|
+
// ADR-0045: a table that legitimately receives locally-derived provisional rows must not
|
|
325
|
+
// collide with them here — a trigger firing during another table's apply in the same
|
|
326
|
+
// catch-up can create rows before this snapshot lands.
|
|
327
|
+
const applyBackfill =
|
|
328
|
+
target.applyMode === "upsert"
|
|
329
|
+
? method === "insert"
|
|
330
|
+
? applyUpsertsToTable
|
|
331
|
+
: applyUpsertsToTableWithJson
|
|
332
|
+
: bulkAppliers[method];
|
|
333
|
+
await applyBackfill({ pg: tx, target, messages: backfill, debug });
|
|
334
|
+
useBulkBackfill.set(shapeName, false);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
if (changes.length === 0) continue;
|
|
339
|
+
|
|
340
|
+
// ADR-0014: fold to one net op per primary key, then DELETE → UPSERT. A re-created key's
|
|
341
|
+
// delete must precede its upsert; every other key lands in exactly one statement.
|
|
342
|
+
//
|
|
343
|
+
// Always the upsert applier, never a plain INSERT: the engine emits `upsert`, which asserts
|
|
344
|
+
// the row's value and says nothing about whether it existed. ADR-0014's plain-INSERT rule
|
|
345
|
+
// rested on `insert` meaning "this row is new", and that verb is gone from the wire — see
|
|
346
|
+
// {@link StreamOperation}. `applyMode` no longer selects between insert and upsert here; it
|
|
347
|
+
// survives only to keep the BULK BACKFILL path conflict-tolerant (below).
|
|
348
|
+
const folded = foldChangeBatch(changes as never);
|
|
349
|
+
if (folded.deletes.length > 0) {
|
|
350
|
+
await applyBulkDeletesToTable({ pg: tx, target, messages: folded.deletes, debug });
|
|
351
|
+
}
|
|
352
|
+
if (folded.upserts.length > 0) {
|
|
353
|
+
await applyUpsertsToTable({ pg: tx, target, messages: folded.upserts, debug });
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (key !== null) {
|
|
358
|
+
// The offsets ride the SAME transaction as the rows they acknowledge. `last_lsn` has no
|
|
359
|
+
// native meaning — ADR-0056 makes the per-shape offset the only frontier — so it is written
|
|
360
|
+
// as a constant until the vestigial column itself is dropped.
|
|
361
|
+
await updateSubscriptionState({
|
|
362
|
+
pg: tx,
|
|
363
|
+
metadataSchema,
|
|
364
|
+
subscriptionKey: key,
|
|
365
|
+
sessionScoped,
|
|
366
|
+
shapeMetadata: Object.fromEntries(
|
|
367
|
+
shapeNames.map((shapeName) => {
|
|
368
|
+
const spec = shapes[shapeName]!;
|
|
369
|
+
return [
|
|
370
|
+
shapeName,
|
|
371
|
+
{
|
|
372
|
+
handle: spec.streamUrl,
|
|
373
|
+
offset: (offsets.get(shapeName) ?? "-1") as never,
|
|
374
|
+
// The identity rides with the cursor rather than being reconstructed later: the
|
|
375
|
+
// next subscribe reads this row BEFORE it has any shape map to look anything up
|
|
376
|
+
// in, and a scope it is no longer granted has nothing else left naming it.
|
|
377
|
+
shapeKey: spec.identity.shapeKey,
|
|
378
|
+
...(spec.identity.scope ? { scope: spec.identity.scope } : {}),
|
|
379
|
+
},
|
|
380
|
+
];
|
|
381
|
+
}),
|
|
382
|
+
),
|
|
383
|
+
lastLsn: BigInt(0),
|
|
384
|
+
debug,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Discard rather than persist work during teardown: PGlite skips the COMMIT once the tx is
|
|
389
|
+
// rolled back, so both the rows and the offset advance are undone and a resume re-streams.
|
|
390
|
+
if (unsubscribed) await tx.rollback();
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
for (let attempt = 1; ; attempt++) {
|
|
394
|
+
if (unsubscribed) return false;
|
|
395
|
+
try {
|
|
396
|
+
await runCommit();
|
|
397
|
+
if (unsubscribed) return false;
|
|
398
|
+
// ADR-0034: the apply wall for this group, recorded BEFORE `signalInitialSyncIfReady` — the
|
|
399
|
+
// ready edge freezes the accumulator, and the commit that caused it must still be counted.
|
|
400
|
+
bootStamp?.onApply(nowMs() - appliedAt);
|
|
401
|
+
inbox.ackAll(epochsAtPeek);
|
|
402
|
+
for (const shapeName of shapesToTruncate) truncateNeeded.delete(shapeName);
|
|
403
|
+
signalInitialSyncIfReady();
|
|
404
|
+
return true;
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (unsubscribed) return false;
|
|
407
|
+
if (attempt >= maxCommitRetries) {
|
|
408
|
+
degraded = true;
|
|
409
|
+
options.onSyncError?.(error instanceof Error ? error : new Error(String(error)));
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
function signalInitialSyncIfReady(): void {
|
|
418
|
+
if (initialSyncSignalled || !inbox.isGroupUpToDate()) return;
|
|
419
|
+
initialSyncSignalled = true;
|
|
420
|
+
options.onInitialSync?.();
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Single-flight commit queue: at most one commit runs at a time, and anything buffered while one
|
|
425
|
+
* is in flight coalesces into the next run rather than queueing a second transaction.
|
|
426
|
+
*
|
|
427
|
+
* Refuses to run while degraded — a later batch must never apply over a held, unapplied one.
|
|
428
|
+
*/
|
|
429
|
+
const enqueueCommit = (): Promise<void> => {
|
|
430
|
+
if (degraded || unsubscribed) return Promise.resolve();
|
|
431
|
+
if (commitInFlight) {
|
|
432
|
+
commitRerun = true;
|
|
433
|
+
return commitInFlight;
|
|
434
|
+
}
|
|
435
|
+
commitInFlight = (async () => {
|
|
436
|
+
try {
|
|
437
|
+
do {
|
|
438
|
+
commitRerun = false;
|
|
439
|
+
if (!(await gateOpen())) break;
|
|
440
|
+
await commitHeld();
|
|
441
|
+
} while (commitRerun && !degraded && !unsubscribed);
|
|
442
|
+
} finally {
|
|
443
|
+
commitInFlight = null;
|
|
444
|
+
}
|
|
445
|
+
})();
|
|
446
|
+
return commitInFlight;
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Whether the group may commit right now.
|
|
451
|
+
*
|
|
452
|
+
* Every shape drained, plus — for the first commit of each alignment generation — the engine
|
|
453
|
+
* barrier. An unsatisfied barrier does not fail: the group simply does not align yet and retries
|
|
454
|
+
* on the next delivery, which is correct if slower.
|
|
455
|
+
*
|
|
456
|
+
* A **degraded** engine is the one reading that is not a delay, and is handled the opposite way.
|
|
457
|
+
*/
|
|
458
|
+
const gateOpen = async (): Promise<boolean> => {
|
|
459
|
+
if (!inbox.isGroupUpToDate()) return false;
|
|
460
|
+
if (!inbox.needsAlignment()) return true;
|
|
461
|
+
if (!inbox.everyShapeReported()) return false;
|
|
462
|
+
|
|
463
|
+
try {
|
|
464
|
+
const barrier = await options.readBarrier();
|
|
465
|
+
// Lost membership effects are terminal, and waiting them out is the one wrong response: the
|
|
466
|
+
// engine holds the abandoned batch's `pendingFlips` count forever, so a group that merely held
|
|
467
|
+
// would be indistinguishable from a slow engine while quietly never aligning. The engine has
|
|
468
|
+
// latched itself degraded and refuses its membership-bearing routes until it is restarted; the
|
|
469
|
+
// client says so and stops.
|
|
470
|
+
if (barrier.flipFailures > 0) {
|
|
471
|
+
degraded = true;
|
|
472
|
+
options.onSyncError?.(
|
|
473
|
+
new Error(
|
|
474
|
+
`[pgxsinkit] the sync engine abandoned ${barrier.flipFailures} membership flip batch(es) after exhausting ` +
|
|
475
|
+
`its retries and is degraded: those effects are lost, so this store cannot be proven consistent. The ` +
|
|
476
|
+
`engine must be restarted and the client re-subscribed.`,
|
|
477
|
+
),
|
|
478
|
+
);
|
|
479
|
+
return false;
|
|
480
|
+
}
|
|
481
|
+
// The alignment term is `pendingFlips` (ADR-0056 d3) — no computed revocation still undelivered.
|
|
482
|
+
// Per-table offsets at tail are what each stream's own up-to-date report already asserts.
|
|
483
|
+
if (barrier.pendingFlips > 0) {
|
|
484
|
+
if (debug) console.log("alignment barrier unsatisfied", barrier);
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
inbox.markAligned();
|
|
488
|
+
if (debug) console.log("aligned on barrier", barrier);
|
|
489
|
+
return true;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
// A barrier the client cannot read is a DELAY, not a failure (ADR-0056): the group stays on the
|
|
492
|
+
// pre-alignment gate and tries again on the next delivery.
|
|
493
|
+
if (debug) console.log("alignment barrier unreachable", error);
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
const group: ShapeGroup = createShapeGroup({
|
|
499
|
+
shapes: Object.fromEntries(
|
|
500
|
+
shapeNames.map((shapeName) => [
|
|
501
|
+
shapeName,
|
|
502
|
+
{
|
|
503
|
+
url: shapes[shapeName]!.streamUrl,
|
|
504
|
+
...(resumable.has(shapeName) ? { offset: String(subState!.shape_metadata[shapeName]!.offset) } : {}),
|
|
505
|
+
},
|
|
506
|
+
]),
|
|
507
|
+
),
|
|
508
|
+
token: options.token,
|
|
509
|
+
live: options.live ?? true,
|
|
510
|
+
...(options.onTokenRejected ? { onTokenRejected: options.onTokenRejected } : {}),
|
|
511
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
512
|
+
...(options.onStreamEnd
|
|
513
|
+
? {
|
|
514
|
+
onStreamEnd: (shapeName: string, error: Error | null) => {
|
|
515
|
+
if (unsubscribed) return;
|
|
516
|
+
options.onStreamEnd?.(shapeName, error);
|
|
517
|
+
},
|
|
518
|
+
}
|
|
519
|
+
: {}),
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
group.subscribe(async (batch) => {
|
|
523
|
+
if (unsubscribed) return;
|
|
524
|
+
// A delivered batch means a fetch just succeeded — the read path is alive, so a runtime can clear
|
|
525
|
+
// an auth-needed status once a fresh token starts working again (ADR-0013).
|
|
526
|
+
options.onSyncActivity?.();
|
|
527
|
+
|
|
528
|
+
// ADR-0034: one delivered response, carrying its change rows — the fetch/rows half of the group's
|
|
529
|
+
// boot stamp. Recorded before the apply so a report attributes network wait and apply wall apart.
|
|
530
|
+
bootStamp?.onBatchDelivered(batch.envelopes.length);
|
|
531
|
+
|
|
532
|
+
const target = targets.get(batch.shape)!;
|
|
533
|
+
inbox.ingestBatch(
|
|
534
|
+
batch.shape,
|
|
535
|
+
batch.envelopes.map((envelope) => envelopeToChange(target, envelope)),
|
|
536
|
+
batch.offset,
|
|
537
|
+
batch.upToDate,
|
|
538
|
+
);
|
|
539
|
+
await enqueueCommit();
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
await group.start();
|
|
543
|
+
|
|
544
|
+
return {
|
|
545
|
+
unsubscribe(): void {
|
|
546
|
+
unsubscribed = true;
|
|
547
|
+
group.unsubscribeAll();
|
|
548
|
+
},
|
|
549
|
+
get isUpToDate(): boolean {
|
|
550
|
+
// Never claim up-to-date on an unapplied commit or after going degraded: the read cache must
|
|
551
|
+
// not assert it matches the server while work is held (ADR-0009 decision 5).
|
|
552
|
+
return !degraded && commitInFlight === null && !inbox.hasBufferedBatches() && inbox.isGroupUpToDate();
|
|
553
|
+
},
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* K shapes may share one table (ADR-0055 decision 4), but only when each brings a scoped clear.
|
|
559
|
+
*
|
|
560
|
+
* The default must-refetch is a TRUNCATE of the whole table, which would wipe a co-tenant scope's
|
|
561
|
+
* rows — so this is the same condition the removed ingest engine's one-shape-per-table guard enforced
|
|
562
|
+
* (ADR-0055 decision 4), stated as the requirement it always was rather than as a prohibition on
|
|
563
|
+
* sharing.
|
|
564
|
+
*
|
|
565
|
+
* Returns the shapes that are the **sole occupant** of their table, which is the set
|
|
566
|
+
* {@link assertClearLeftNoResidue} can check: for those, and only those, "this shape's rows are
|
|
567
|
+
* gone" and "the table is empty" are the same statement.
|
|
568
|
+
*/
|
|
569
|
+
function resolveTableSharing(shapes: Record<string, CircuitsShapeSpec>): { soleOccupants: Set<string> } {
|
|
570
|
+
const byTable = new Map<string, string[]>();
|
|
571
|
+
for (const [shapeName, spec] of Object.entries(shapes)) {
|
|
572
|
+
const sharing = byTable.get(spec.tableKey) ?? [];
|
|
573
|
+
sharing.push(shapeName);
|
|
574
|
+
byTable.set(spec.tableKey, sharing);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
const soleOccupants = new Set<string>();
|
|
578
|
+
for (const [tableKey, sharing] of byTable) {
|
|
579
|
+
if (sharing.length < 2) {
|
|
580
|
+
soleOccupants.add(sharing[0]!);
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
const bare = sharing.filter((shapeName) => !shapes[shapeName]!.onMustRefetch);
|
|
584
|
+
if (bare.length > 0) {
|
|
585
|
+
throw new Error(
|
|
586
|
+
`[pgxsinkit] shapes ${bare.join(", ")} share table "${tableKey}" without an onMustRefetch — the ` +
|
|
587
|
+
`default must-refetch truncates the whole table and would wipe the other shapes' rows. A ` +
|
|
588
|
+
`shared-tier shape derives a scoped clear from its scope key.`,
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return { soleOccupants };
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* After a custom {@link CircuitsShapeSpec.onMustRefetch}, assert the clear actually cleared.
|
|
597
|
+
*
|
|
598
|
+
* This is one of the two checks that replace ADR-0014's primary-key collision tripwire. That
|
|
599
|
+
* tripwire was never an application-data guard — Postgres enforces PK uniqueness upstream, so the
|
|
600
|
+
* server cannot send two distinct rows sharing a key. It was an invariant alarm on the replication
|
|
601
|
+
* machinery, and the state it could actually catch was *stale rows the client should no longer
|
|
602
|
+
* hold*. It fired only indirectly, when the server later re-sent one of those keys as an `insert`.
|
|
603
|
+
* With `upsert` on the wire the alarm is unreachable, so the invariant is asserted where it lives
|
|
604
|
+
* instead: at the clear, on the shape whose own callback is responsible for it.
|
|
605
|
+
*
|
|
606
|
+
* **Only sound for a sole occupant.** When K shapes share a table, each brings a scoped clear that
|
|
607
|
+
* deliberately leaves its co-tenants' rows in place, and the client holds no scope predicate to
|
|
608
|
+
* subtract them with (`CircuitsShapeSpec` carries an opaque callback, not a scope key). Demanding
|
|
609
|
+
* emptiness there would fail every correct shared-table clear. What carries the shared case is the
|
|
610
|
+
* contract in {@link resolveTableSharing}, not a check here — stated plainly rather than papered
|
|
611
|
+
* over with a check that only looks like one.
|
|
612
|
+
*
|
|
613
|
+
* The default TRUNCATE path is not routed here: it cannot leave residue, so the query would be pure
|
|
614
|
+
* cost. Must-refetch is rare, so the surviving cost is a single existence probe per reset.
|
|
615
|
+
*/
|
|
616
|
+
async function assertClearLeftNoResidue({
|
|
617
|
+
pg,
|
|
618
|
+
target,
|
|
619
|
+
shapeName,
|
|
620
|
+
soleOccupant,
|
|
621
|
+
}: {
|
|
622
|
+
pg: PGliteInterface | Transaction;
|
|
623
|
+
target: ApplyTarget;
|
|
624
|
+
shapeName: string;
|
|
625
|
+
soleOccupant: boolean;
|
|
626
|
+
}): Promise<void> {
|
|
627
|
+
if (!soleOccupant) return;
|
|
628
|
+
|
|
629
|
+
const residue = await drizzleOverPg(pg)
|
|
630
|
+
.select({ one: sql<number>`1` })
|
|
631
|
+
.from(target.table)
|
|
632
|
+
.limit(1);
|
|
633
|
+
if (residue.length === 0) return;
|
|
634
|
+
|
|
635
|
+
throw new Error(
|
|
636
|
+
`[pgxsinkit] shape "${shapeName}" ran its onMustRefetch but rows remain in its table, and it is ` +
|
|
637
|
+
`the only shape on that table — so the clear was incomplete. The re-snapshot that follows would ` +
|
|
638
|
+
`merge onto rows the shape no longer holds, leaving them visible forever. Fix the onMustRefetch ` +
|
|
639
|
+
`to clear everything this shape syncs, or drop it and take the default TRUNCATE.`,
|
|
640
|
+
);
|
|
641
|
+
}
|