@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
package/src/sync/index.ts
DELETED
|
@@ -1,1124 +0,0 @@
|
|
|
1
|
-
// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
|
|
2
|
-
// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
|
|
3
|
-
import type { EventMessage, MovePattern, Row } from "@electric-sql/client";
|
|
4
|
-
import { isChangeMessage, isControlMessage } from "@electric-sql/client";
|
|
5
|
-
import type { ChangeMessage, ShapeStreamOptions } from "@electric-sql/client";
|
|
6
|
-
import { MultiShapeStream } from "@electric-sql/experimental";
|
|
7
|
-
import type { PGliteInterface } from "@electric-sql/pglite";
|
|
8
|
-
import { sql } from "drizzle-orm";
|
|
9
|
-
import { getTableConfig } from "drizzle-orm/pg-core";
|
|
10
|
-
|
|
11
|
-
import { type ApplyStrategy, classifyTableApplyStrategy } from "@pgxsinkit/contracts";
|
|
12
|
-
|
|
13
|
-
import { instrumentShapeFetch, syncDebug } from "../debug";
|
|
14
|
-
import { type ApplyTarget, resolveApplyTarget } from "../local-tables";
|
|
15
|
-
import { computeRetryDelayMs } from "../mutation";
|
|
16
|
-
import {
|
|
17
|
-
applyBulkDeletesToTable,
|
|
18
|
-
applyBulkUpdatesToTable,
|
|
19
|
-
applyInsertsToTable,
|
|
20
|
-
applyMessagesToTableWithCopy,
|
|
21
|
-
applyMessagesToTableWithJson,
|
|
22
|
-
applyUpsertsToTable,
|
|
23
|
-
applyUpsertsToTableWithJson,
|
|
24
|
-
} from "./apply";
|
|
25
|
-
import { drizzleOverPg } from "./drizzle-executor";
|
|
26
|
-
import {
|
|
27
|
-
NUDGE_HOLD_GRACE_MS,
|
|
28
|
-
NUDGE_MAX_ROUNDS,
|
|
29
|
-
NUDGE_ROUND_GRACE_MS,
|
|
30
|
-
NUDGE_ROUND_WAIT_MS,
|
|
31
|
-
withNudgeBuster,
|
|
32
|
-
} from "./nudge";
|
|
33
|
-
import { foldChangeBatch, ShapeInbox } from "./shape-inbox";
|
|
34
|
-
import {
|
|
35
|
-
deleteSubscriptionState,
|
|
36
|
-
getSubscriptionState,
|
|
37
|
-
migrateSubscriptionMetadataTables,
|
|
38
|
-
type SubscriptionState,
|
|
39
|
-
updateSubscriptionState,
|
|
40
|
-
} from "./subscription-state";
|
|
41
|
-
import {
|
|
42
|
-
addShapeRowTags,
|
|
43
|
-
applyShapeMoveOut,
|
|
44
|
-
applyShapeTagSync,
|
|
45
|
-
assertValidMetadataSchema,
|
|
46
|
-
clearShapeTags,
|
|
47
|
-
DEFAULT_METADATA_SCHEMA,
|
|
48
|
-
shapeTableId,
|
|
49
|
-
} from "./tags";
|
|
50
|
-
import {
|
|
51
|
-
DEFAULT_MAX_COMMIT_RETRIES,
|
|
52
|
-
type ElectricSyncOptions,
|
|
53
|
-
type InitialInsertMethod,
|
|
54
|
-
type InsertChangeMessage,
|
|
55
|
-
type Lsn,
|
|
56
|
-
type SyncShapesToTablesOptions,
|
|
57
|
-
type SyncShapesToTablesResult,
|
|
58
|
-
type SyncShapeToTableOptions,
|
|
59
|
-
type SyncShapeToTableResult,
|
|
60
|
-
} from "./types";
|
|
61
|
-
|
|
62
|
-
export * from "./types";
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Replication-stream headers Electric attaches to change messages but does not
|
|
66
|
-
* declare on its `Header` type: `lsn` orders changes within the stream and
|
|
67
|
-
* `last` marks the final change of an LSN. Single choke point for these
|
|
68
|
-
* protocol assumptions.
|
|
69
|
-
*/
|
|
70
|
-
/**
|
|
71
|
-
* Maps the statically-resolved {@link ApplyStrategy} (ADR-0009 decision 3) onto the engine's
|
|
72
|
-
* initial-backfill apply path. Undefined (no registry-supplied strategy) defaults to `copy`:
|
|
73
|
-
* the COPY TEXT serializer round-trips every built-in type, so it is the safe no-brainer bootstrap.
|
|
74
|
-
*/
|
|
75
|
-
function applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {
|
|
76
|
-
switch (strategy) {
|
|
77
|
-
case "json":
|
|
78
|
-
return "json";
|
|
79
|
-
case "insert":
|
|
80
|
-
return "insert";
|
|
81
|
-
default:
|
|
82
|
-
return "copy";
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function readReplicationHeaders(headers: ChangeMessage["headers"]): { lsn: bigint; isLastOfLsn: boolean } {
|
|
87
|
-
const rawLsn: unknown = headers["lsn"];
|
|
88
|
-
|
|
89
|
-
return {
|
|
90
|
-
lsn: typeof rawLsn === "string" ? BigInt(rawLsn) : BigInt(0),
|
|
91
|
-
isLastOfLsn: headers["last"] === true,
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Electric's tagged-subquery `EventMessage` (ADR-0023) — `headers.event` is `move-out` | `move-in`,
|
|
97
|
-
* carrying `patterns`. It is neither a change nor a control message, so `@electric-sql/client` exposes
|
|
98
|
-
* no guard; we detect it by the `event` header. `MultiShapeStream` adds `.shape` like every message.
|
|
99
|
-
*/
|
|
100
|
-
type ShapeEventMessage = EventMessage & { shape: string };
|
|
101
|
-
|
|
102
|
-
function isEventMessage(message: unknown): message is ShapeEventMessage {
|
|
103
|
-
return (
|
|
104
|
-
typeof message === "object" &&
|
|
105
|
-
message !== null &&
|
|
106
|
-
typeof (message as { headers?: { event?: unknown } }).headers?.event === "string"
|
|
107
|
-
);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine
|
|
112
|
-
* is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it
|
|
113
|
-
* actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`
|
|
114
|
-
* / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the
|
|
115
|
-
* local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit
|
|
116
|
-
* `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked
|
|
117
|
-
* explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).
|
|
118
|
-
*/
|
|
119
|
-
export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions) {
|
|
120
|
-
const debug = options?.debug ?? false;
|
|
121
|
-
// pgxsinkit-owned metadata namespace (ADR-0009 decision 6): this is our local bookkeeping (the
|
|
122
|
-
// subscription-state table) and the sync-origin GUC (`<schema>.syncing`), not Electric's — so it
|
|
123
|
-
// lives under our own schema, renamed from the upstream `electric` default.
|
|
124
|
-
const metadataSchema = options?.metadataSchema ?? DEFAULT_METADATA_SCHEMA;
|
|
125
|
-
// The schema name reaches raw GUC + DDL identifier positions below (no quoted-identifier form exists
|
|
126
|
-
// there), so validate it at construction rather than trust caller input in those raw spots.
|
|
127
|
-
assertValidMetadataSchema(metadataSchema);
|
|
128
|
-
const streams: Array<{
|
|
129
|
-
stream: MultiShapeStream<Record<string, Row<unknown>>>;
|
|
130
|
-
aborter: AbortController;
|
|
131
|
-
}> = [];
|
|
132
|
-
|
|
133
|
-
const getShapeOptions = (shapes: SyncShapesToTablesOptions["shapes"], shapeName: string) => {
|
|
134
|
-
const shape = shapes[shapeName];
|
|
135
|
-
if (!shape) {
|
|
136
|
-
throw new Error(`Missing shape options for ${shapeName}`);
|
|
137
|
-
}
|
|
138
|
-
return shape;
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
const shapePerTableLock = new Map<string, void>();
|
|
142
|
-
|
|
143
|
-
// Memoize the metadata DDL as a PROMISE, not a boolean: concurrent eager groups (`shape-sync.ts`
|
|
144
|
-
// starts them with `Promise.all`) both call `initMetadataTables`, and a boolean set BEFORE the async
|
|
145
|
-
// migration completed let the second caller return early and query the metadata tables before the DDL
|
|
146
|
-
// had run. Storing the in-flight promise makes every concurrent caller await the same single migration.
|
|
147
|
-
// Cleared on rejection so a transient DDL failure can be retried by a later start rather than caching a
|
|
148
|
-
// rejected promise forever.
|
|
149
|
-
let initMetadataTablesPromise: Promise<void> | undefined;
|
|
150
|
-
const initMetadataTables = (): Promise<void> => {
|
|
151
|
-
if (!initMetadataTablesPromise) {
|
|
152
|
-
initMetadataTablesPromise = migrateSubscriptionMetadataTables({
|
|
153
|
-
pg,
|
|
154
|
-
metadataSchema,
|
|
155
|
-
}).catch((error: unknown) => {
|
|
156
|
-
initMetadataTablesPromise = undefined;
|
|
157
|
-
throw error;
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
return initMetadataTablesPromise;
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
const syncShapesToTables = async ({
|
|
164
|
-
key,
|
|
165
|
-
registry,
|
|
166
|
-
shapes,
|
|
167
|
-
sessionScoped = false,
|
|
168
|
-
initialInsertMethod,
|
|
169
|
-
onInitialSync,
|
|
170
|
-
onError,
|
|
171
|
-
onSyncError,
|
|
172
|
-
onSyncActivity,
|
|
173
|
-
dbReady,
|
|
174
|
-
bootStamp,
|
|
175
|
-
maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,
|
|
176
|
-
commitRetryDelayMs = computeRetryDelayMs,
|
|
177
|
-
}: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {
|
|
178
|
-
let unsubscribed = false;
|
|
179
|
-
// Fresh-store prefetch overlap (ADR-0032 S4): the caller proved the store fresh and handed a `dbReady`
|
|
180
|
-
// gate, so start the streams and buffer their catch-up into the memory inbox NOW — before the local
|
|
181
|
-
// store's schema/journal/reconcile finish — and defer every DB touch (metadata DDL, the first commit)
|
|
182
|
-
// until the gate lifts. Without it, the exact sequential path: init the metadata tables up front.
|
|
183
|
-
const overlap = dbReady != null;
|
|
184
|
-
if (!overlap) {
|
|
185
|
-
await initMetadataTables();
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Resolve each shape's apply target ONCE at subscribe time (ADR-0029 D1/D2): the real projected
|
|
189
|
-
// synced table, its columns, PKs, and model-derived types — the engine's per-message work is then a
|
|
190
|
-
// pure builder over these resolved objects, never a per-message re-derivation or catalog probe.
|
|
191
|
-
const targets = new Map<string, ApplyTarget>(
|
|
192
|
-
Object.entries(shapes).map(([shapeName, shapeOptions]) => [
|
|
193
|
-
shapeName,
|
|
194
|
-
resolveApplyTarget(registry, shapeOptions.tableKey),
|
|
195
|
-
]),
|
|
196
|
-
);
|
|
197
|
-
const getTarget = (shapeName: string): ApplyTarget => {
|
|
198
|
-
const target = targets.get(shapeName);
|
|
199
|
-
if (!target) {
|
|
200
|
-
throw new Error(`Missing apply target for ${shapeName}`);
|
|
201
|
-
}
|
|
202
|
-
return target;
|
|
203
|
-
};
|
|
204
|
-
// The synced table's physical identity — the per-table lock key and the tag-store `shape_table` key.
|
|
205
|
-
const tableIdentity = (target: ApplyTarget) => {
|
|
206
|
-
const { name, schema } = getTableConfig(target.table);
|
|
207
|
-
return shapeTableId(schema, name);
|
|
208
|
-
};
|
|
209
|
-
|
|
210
|
-
Object.entries(shapes)
|
|
211
|
-
.filter(([, shape]) => !shape.onMustRefetch)
|
|
212
|
-
.forEach(([, shape]) => {
|
|
213
|
-
if (shapePerTableLock.has(shape.tableKey)) {
|
|
214
|
-
throw new Error("Already syncing shape for table " + shape.tableKey);
|
|
215
|
-
}
|
|
216
|
-
shapePerTableLock.set(shape.tableKey);
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
let subState: SubscriptionState | null = null;
|
|
220
|
-
|
|
221
|
-
// On the overlap path the store is provably fresh (the `freshStore` gate), so it carries no persisted
|
|
222
|
-
// subscription state — AND its metadata tables do not exist yet (their DDL is deferred to the gate).
|
|
223
|
-
// Skip the read entirely: `subState` stays null, so the group is (correctly) a new subscription.
|
|
224
|
-
if (key !== null && !overlap) {
|
|
225
|
-
subState = await getSubscriptionState({
|
|
226
|
-
pg,
|
|
227
|
-
metadataSchema,
|
|
228
|
-
subscriptionKey: key,
|
|
229
|
-
sessionScoped,
|
|
230
|
-
});
|
|
231
|
-
if (debug && subState) {
|
|
232
|
-
console.log("resuming from subscription state", subState);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
const isNewSubscription = subState === null;
|
|
237
|
-
|
|
238
|
-
// Each shape resolves its own apply method (ADR-0009 decisions 2 + 3 / ADR-0029 D1): an explicit
|
|
239
|
-
// per-shape `initialInsertMethod` override wins, else the group-level default, else the registry's
|
|
240
|
-
// build-time classification of the entry. So a consistency group with mixed column profiles applies
|
|
241
|
-
// each table on its correct path.
|
|
242
|
-
const shapeInsertMethod = new Map<string, InitialInsertMethod>(
|
|
243
|
-
Object.entries(shapes).map(([shapeName, shapeOptions]) => {
|
|
244
|
-
// Strategy precedence (ADR-0009 decisions 2+3 / ADR-0029 D1): an explicit per-shape override,
|
|
245
|
-
// then the group-level default, then the registry's build-time classification of the entry.
|
|
246
|
-
const entry = registry[shapeOptions.tableKey]!;
|
|
247
|
-
const method =
|
|
248
|
-
shapeOptions.initialInsertMethod ??
|
|
249
|
-
initialInsertMethod ??
|
|
250
|
-
applyStrategyToInsertMethod(classifyTableApplyStrategy(entry));
|
|
251
|
-
return [shapeName, method];
|
|
252
|
-
}),
|
|
253
|
-
);
|
|
254
|
-
|
|
255
|
-
// `useInsert` is per-shape, not shared: in a multi-shape group, one shape finishing its bulk
|
|
256
|
-
// backfill must not flip every other shape onto plain `INSERT`. A shape uses its bulk path only
|
|
257
|
-
// on a fresh subscription with a non-`insert` method; a resume starts already in insert mode.
|
|
258
|
-
const useInsert = new Map<string, boolean>(
|
|
259
|
-
Object.keys(shapes).map((shapeName) => [
|
|
260
|
-
shapeName,
|
|
261
|
-
!isNewSubscription || shapeInsertMethod.get(shapeName) === "insert",
|
|
262
|
-
]),
|
|
263
|
-
);
|
|
264
|
-
let onInitialSyncCalled = false;
|
|
265
|
-
|
|
266
|
-
const maybeSignalInitialSync = () => {
|
|
267
|
-
if (onInitialSync && !onInitialSyncCalled && multiShapeStream.isUpToDate) {
|
|
268
|
-
onInitialSync();
|
|
269
|
-
onInitialSyncCalled = true;
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
|
|
273
|
-
// The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory buffer + complete-LSN frontier for
|
|
274
|
-
// this group's shapes. The engine keeps the commit queue, the apply, and the truncate set.
|
|
275
|
-
const inbox = new ShapeInbox(Object.keys(shapes));
|
|
276
|
-
|
|
277
|
-
// Live-tail sibling nudge (ADR-0031): a per-shape one-shot cache-buster token. The watchdog (below)
|
|
278
|
-
// sets a token just before nudging a lagging sibling; `withNudgeBuster` (wrapping each shape's
|
|
279
|
-
// fetchClient) consumes it on the sibling's next non-live catch-up so a CDN HIT cannot return the same
|
|
280
|
-
// stale watermark and defeat the nudge. Empty on the steady path → the wrapper is a straight passthrough.
|
|
281
|
-
const nudgeBusters = new Map<string, string>();
|
|
282
|
-
|
|
283
|
-
const truncateNeeded = new Set<string>();
|
|
284
|
-
// The committed frontier is a *running* variable, advanced after each successful commit — not
|
|
285
|
-
// the boot-time `const` the upstream engine never advanced (which forced redundant empty
|
|
286
|
-
// re-commits). `degraded` latches once commits exhaust their retries (ADR-0009 decision 5).
|
|
287
|
-
let committedLsn: Lsn = subState?.last_lsn ?? BigInt(-1);
|
|
288
|
-
let degraded = false;
|
|
289
|
-
// Single-flight commit queue: at most one commit runs at a time; messages buffered while one
|
|
290
|
-
// is in flight coalesce into the next run (re-armed via `commitRerun`).
|
|
291
|
-
let commitInFlight: Promise<void> | null = null;
|
|
292
|
-
let commitRerun = false;
|
|
293
|
-
|
|
294
|
-
const aborter = new AbortController();
|
|
295
|
-
Object.values(shapes)
|
|
296
|
-
.filter((shapeOptions) => !!shapeOptions.shape.signal)
|
|
297
|
-
.forEach((shapeOptions) => {
|
|
298
|
-
shapeOptions.shape.signal!.addEventListener("abort", () => aborter.abort(), {
|
|
299
|
-
once: true,
|
|
300
|
-
});
|
|
301
|
-
});
|
|
302
|
-
|
|
303
|
-
const multiShapeOptions: Record<string, ShapeStreamOptions<Row<unknown>>> = {};
|
|
304
|
-
for (const [shapeName, shapeOptions] of Object.entries(shapes)) {
|
|
305
|
-
const shapeMetadata = subState?.shape_metadata[shapeName];
|
|
306
|
-
const streamOptions: ShapeStreamOptions<Row<unknown>> = {
|
|
307
|
-
...shapeOptions.shape,
|
|
308
|
-
signal: aborter.signal,
|
|
309
|
-
// Instrument every ShapeStream HTTP request (the read-path long-poll/catch-up) when debug is on;
|
|
310
|
-
// a passthrough otherwise (see instrumentShapeFetch). Wraps any existing fetchClient rather than
|
|
311
|
-
// replacing it, so auth/header injection on the shape's own fetchClient still runs. `withNudgeBuster`
|
|
312
|
-
// is the OUTER wrapper (ADR-0031 live-tail nudge): it stamps the cache-buster onto the URL BEFORE
|
|
313
|
-
// instrumentation runs, so the debug rail logs the busted URL (`BUSTED`) that actually hits the wire.
|
|
314
|
-
fetchClient: withNudgeBuster(instrumentShapeFetch(shapeOptions.shape.fetchClient), nudgeBusters, shapeName),
|
|
315
|
-
};
|
|
316
|
-
|
|
317
|
-
if (shapeMetadata) {
|
|
318
|
-
streamOptions.offset = shapeMetadata.offset;
|
|
319
|
-
streamOptions.handle = shapeMetadata.handle;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
multiShapeOptions[shapeName] = streamOptions;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
const multiShapeStream = new MultiShapeStream<Record<string, Row<unknown>>>({
|
|
326
|
-
shapes: multiShapeOptions,
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
// The commit gate (ADR-0032 S4). Open immediately on the sequential path; held closed on the overlap
|
|
330
|
-
// path until `dbReady` resolves, so NOTHING writes to PGlite before the local schema exists. The inbox
|
|
331
|
-
// is pure memory, so buffering catch-up behind this closed gate is safe — the only DB-bound work
|
|
332
|
-
// (metadata DDL, then commits) waits for the gate.
|
|
333
|
-
let dbGateOpen = !overlap;
|
|
334
|
-
if (overlap) {
|
|
335
|
-
// The streams' network side is starting now (subscribe below triggers the first fetch), overlapping
|
|
336
|
-
// the caller's local boot phases. Name the shapes so the overlap is measurable on the boot rail.
|
|
337
|
-
syncDebug("boot shape prefetch start", { shapes: Object.keys(shapes) });
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
const getShapeStream = (shapeName: string) => {
|
|
341
|
-
const stream = multiShapeStream.shapes[shapeName];
|
|
342
|
-
if (!stream) {
|
|
343
|
-
throw new Error(`Missing stream for ${shapeName}`);
|
|
344
|
-
}
|
|
345
|
-
return stream;
|
|
346
|
-
};
|
|
347
|
-
|
|
348
|
-
const insertMethods = {
|
|
349
|
-
json: applyMessagesToTableWithJson,
|
|
350
|
-
copy: applyMessagesToTableWithCopy,
|
|
351
|
-
insert: applyInsertsToTable,
|
|
352
|
-
} as const;
|
|
353
|
-
|
|
354
|
-
// Apply everything buffered up to `targetLsn` in a single transaction, retrying with jittered
|
|
355
|
-
// backoff on failure. Returns `true` once applied (and advances the running committed frontier);
|
|
356
|
-
// returns `false` without advancing if the engine unsubscribed mid-flight or the commit
|
|
357
|
-
// exhausted its retries (→ `degraded` + `onSyncError`, ADR-0009 decision 5). The drained
|
|
358
|
-
// messages and the truncate snapshot are held across retries so a transient failure loses
|
|
359
|
-
// nothing; the read cache never advances past an unapplied commit.
|
|
360
|
-
const commitUpToLsn = async (targetLsn: Lsn): Promise<boolean> => {
|
|
361
|
-
// PEEK (not drain) the buffered batch: it stays in the inbox until the transaction below actually
|
|
362
|
-
// succeeds, and is only then ACKed (removed). A commit that exhausts its retries (→ `degraded`)
|
|
363
|
-
// therefore HOLDS the drained batch in the buffer instead of losing it (ADR-0009 decision 5) — and
|
|
364
|
-
// `enqueueCommit` refuses to run any newer commit while degraded, so a later LSN can never apply
|
|
365
|
-
// over this held, unapplied batch. Recovery is a restart/refetch: the persisted offset was not
|
|
366
|
-
// advanced, so the held batch re-streams from the same frontier.
|
|
367
|
-
const messagesToCommit = inbox.peekUpTo(targetLsn);
|
|
368
|
-
|
|
369
|
-
// Record every shape's reset epoch AT PEEK TIME (synchronously with the peeks, before the async
|
|
370
|
-
// transaction). If a must-refetch + re-snapshot bumps a shape's epoch mid-commit, the acks below
|
|
371
|
-
// skip that shape so its post-reset rebuild survives rather than being deleted/spliced away — see
|
|
372
|
-
// ShapeInbox.ackUpTo / ackMoveOuts / ackMoveIns.
|
|
373
|
-
const epochsAtPeek = inbox.snapshotEpochs();
|
|
374
|
-
|
|
375
|
-
// Capture, per shape, whether it is still accepting snapshot (LSN-0) rows AT PEEK TIME. A shape in
|
|
376
|
-
// snapshot acceptance (post-reset re-snapshot, or a brand-new shape before its first real lsn) can
|
|
377
|
-
// have the SAME snapshot rows double-delivered by the racing recovery fetch loops — possibly across
|
|
378
|
-
// separate commits — so its inserts are applied idempotently (upsert) rather than as plain
|
|
379
|
-
// collision-surfacing inserts. Once a real lsn re-arms the dedup, this is false and the live-tail
|
|
380
|
-
// plain-INSERT invariant (a genuine PK collision must surface, ADR-0014) is back in force.
|
|
381
|
-
const snapshotModeAtPeek = new Map<string, boolean>(
|
|
382
|
-
Object.keys(shapes).map((shapeName) => [shapeName, inbox.acceptsSnapshotRowsFor(shapeName)]),
|
|
383
|
-
);
|
|
384
|
-
|
|
385
|
-
// Snapshot the truncate set so a retried transaction still truncates; the per-shape flag is
|
|
386
|
-
// cleared only once the commit has succeeded.
|
|
387
|
-
const shapesToTruncate = new Set(truncateNeeded);
|
|
388
|
-
|
|
389
|
-
// Peek the buffered tagged-subquery move-outs (ADR-0023) the same way: held in the buffer so a
|
|
390
|
-
// retried/degraded commit still has them, ACKed only on success (by the exact peeked count, so a
|
|
391
|
-
// move-out that arrived during a coalescing commit is not dropped).
|
|
392
|
-
const moveOutsToCommit = new Map<string, MovePattern[][]>();
|
|
393
|
-
// Peek the buffered tagged-subquery move-ins (ADR-0024) identically: a move-in snapshot row carries
|
|
394
|
-
// no LSN; it is applied idempotently in the commit transaction and ACKed only on success.
|
|
395
|
-
const moveInsToCommit = new Map<string, ChangeMessage<Row<unknown>>[]>();
|
|
396
|
-
for (const shapeName of Object.keys(shapes)) {
|
|
397
|
-
const pendingOut = inbox.peekMoveOuts(shapeName);
|
|
398
|
-
if (pendingOut.length > 0) {
|
|
399
|
-
moveOutsToCommit.set(shapeName, pendingOut);
|
|
400
|
-
}
|
|
401
|
-
const pendingIn = inbox.peekMoveIns(shapeName);
|
|
402
|
-
if (pendingIn.length > 0) {
|
|
403
|
-
moveInsToCommit.set(shapeName, pendingIn);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
const runCommit = () =>
|
|
408
|
-
pg.transaction(async (tx) => {
|
|
409
|
-
if (debug) {
|
|
410
|
-
console.time("commit");
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin `<schema>.syncing` flag
|
|
414
|
-
// the apply trigger reads to distinguish streamed server truth from local writes. GUCs have
|
|
415
|
-
// no tier-①/② builder form; the schema identifier is fixed at engine construction.
|
|
416
|
-
await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);
|
|
417
|
-
|
|
418
|
-
for (const [shapeName, initialMessages] of messagesToCommit.entries()) {
|
|
419
|
-
const shape = getShapeOptions(shapes, shapeName);
|
|
420
|
-
const target = getTarget(shapeName);
|
|
421
|
-
const shapeMethod = shapeInsertMethod.get(shapeName)!;
|
|
422
|
-
let messages = initialMessages;
|
|
423
|
-
|
|
424
|
-
// ADR-0023: the shape's tag store key (synced table, schema-qualified).
|
|
425
|
-
const shapeTable = tableIdentity(target);
|
|
426
|
-
|
|
427
|
-
if (shapesToTruncate.has(shapeName)) {
|
|
428
|
-
if (debug) {
|
|
429
|
-
console.log("truncating table", shapeTable);
|
|
430
|
-
}
|
|
431
|
-
if (shape.onMustRefetch) {
|
|
432
|
-
await shape.onMustRefetch(drizzleOverPg(tx));
|
|
433
|
-
} else {
|
|
434
|
-
// ADR-0029 D4: a must-refetch wipe is engine cache maintenance, not server truth — so it
|
|
435
|
-
// TRUNCATEs (tier ②; `TRUNCATE` has no Drizzle builder, the table object is interpolated)
|
|
436
|
-
// rather than reacting via the per-row reconcile trigger. Correctness rides the reconcile
|
|
437
|
-
// loop; TRUNCATE is O(1) and the re-snapshot inserts still fire the trigger.
|
|
438
|
-
await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);
|
|
439
|
-
}
|
|
440
|
-
// The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too
|
|
441
|
-
// (ADR-0023 Slice 2: a must-refetch/rebuild must not leave orphan tags).
|
|
442
|
-
await clearShapeTags({ pg: tx, metadataSchema, shapeTable, sessionScoped });
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
// ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their
|
|
446
|
-
// tags are UNIONED first (a move-in adds a reason, it must not clear an independent grant's
|
|
447
|
-
// tag) — and a regular change for the same row in this batch then authoritatively replaces
|
|
448
|
-
// below, so union-then-replace converges either way.
|
|
449
|
-
const moveInMessages = moveInsToCommit.get(shapeName) ?? [];
|
|
450
|
-
if (moveInMessages.length > 0) {
|
|
451
|
-
await addShapeRowTags({
|
|
452
|
-
pg: tx,
|
|
453
|
-
metadataSchema,
|
|
454
|
-
shapeTable,
|
|
455
|
-
messages: moveInMessages,
|
|
456
|
-
primaryKey: target.primaryKey,
|
|
457
|
-
sessionScoped,
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
// Maintain the tag-set from the RAW drained batch (ADR-0023) — before the data apply and
|
|
462
|
-
// the move-out eviction, so an add-then-remove within one commit resolves correctly. Uses
|
|
463
|
-
// `initialMessages` (the full batch) since the insert/fold split below reduces `messages`.
|
|
464
|
-
await applyShapeTagSync({
|
|
465
|
-
pg: tx,
|
|
466
|
-
metadataSchema,
|
|
467
|
-
shapeTable,
|
|
468
|
-
messages: initialMessages,
|
|
469
|
-
primaryKey: target.primaryKey,
|
|
470
|
-
sessionScoped,
|
|
471
|
-
});
|
|
472
|
-
|
|
473
|
-
// ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit
|
|
474
|
-
// update to a just-moved-in row lands on a present row. Upsert (not plain INSERT) because the
|
|
475
|
-
// row may already be present via another grant or be re-delivered on a resume.
|
|
476
|
-
if (moveInMessages.length > 0) {
|
|
477
|
-
await applyUpsertsToTable({
|
|
478
|
-
pg: tx,
|
|
479
|
-
target,
|
|
480
|
-
messages: moveInMessages,
|
|
481
|
-
debug,
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
if (!useInsert.get(shapeName)) {
|
|
486
|
-
const initialInserts: InsertChangeMessage[] = [];
|
|
487
|
-
const remainingMessages: ChangeMessage<Row<unknown>>[] = [];
|
|
488
|
-
let foundNonInsert = false;
|
|
489
|
-
for (const message of messages) {
|
|
490
|
-
if (!foundNonInsert && message.headers.operation === "insert") {
|
|
491
|
-
initialInserts.push(message as InsertChangeMessage);
|
|
492
|
-
} else {
|
|
493
|
-
foundNonInsert = true;
|
|
494
|
-
remainingMessages.push(message);
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
if (initialInserts.length > 0 && shapeMethod === "copy") {
|
|
498
|
-
remainingMessages.unshift(initialInserts.pop()!);
|
|
499
|
-
}
|
|
500
|
-
messages = remainingMessages;
|
|
501
|
-
|
|
502
|
-
if (initialInserts.length > 0) {
|
|
503
|
-
if (target.applyMode === "upsert") {
|
|
504
|
-
// ADR-0045: the initial bulk-insert fast path's appliers (json/copy/insert) are all
|
|
505
|
-
// plain-INSERT appliers with no conflict clause. A local trigger can already have created
|
|
506
|
-
// rows before this snapshot applies — even on a fresh store, because another table's
|
|
507
|
-
// apply in the same catch-up can fire the trigger — so route through an idempotent
|
|
508
|
-
// upsert applier instead, keeping the `useInsert` bookkeeping identical. A json- or
|
|
509
|
-
// COPY-classified table takes the set-based `json_to_recordset` upsert (COPY itself has
|
|
510
|
-
// no ON CONFLICT clause, so json is the bulk ceiling — and it keeps the performance a
|
|
511
|
-
// param-bound `applyUpsertsToTable` would lose on a large snapshot). A table classified
|
|
512
|
-
// `insert` is so BECAUSE a column is not json-safe — it must take the batched-VALUES
|
|
513
|
-
// upsert, never the json cast.
|
|
514
|
-
const applyInitialUpserts =
|
|
515
|
-
shapeMethod === "insert" ? applyUpsertsToTable : applyUpsertsToTableWithJson;
|
|
516
|
-
await applyInitialUpserts({
|
|
517
|
-
pg: tx,
|
|
518
|
-
target,
|
|
519
|
-
messages: initialInserts,
|
|
520
|
-
debug,
|
|
521
|
-
});
|
|
522
|
-
} else {
|
|
523
|
-
await insertMethods[shapeMethod]({
|
|
524
|
-
pg: tx,
|
|
525
|
-
target,
|
|
526
|
-
messages: initialInserts,
|
|
527
|
-
debug,
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
useInsert.set(shapeName, true);
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// ADR-0014 Phase 3: fold this shape's drained batch to one net op per PK, then apply
|
|
536
|
-
// three bulk statements in the order DELETE → INSERT → UPDATE. A re-created PK's delete
|
|
537
|
-
// must precede its insert; every other PK lands in exactly one statement, so the rest of
|
|
538
|
-
// the order is irrelevant within the (atomic) commit. The fold collapses same-PK runs, so
|
|
539
|
-
// no bulk statement ever holds two rows for one PK — closing the `UPDATE … FROM` /
|
|
540
|
-
// `json_to_recordset` join hazard (which would use one arbitrary matching row) by
|
|
541
|
-
// construction. This replaces the previous one-SQL-statement-per-row steady-state loop.
|
|
542
|
-
if (messages.length > 0) {
|
|
543
|
-
const folded = foldChangeBatch(messages);
|
|
544
|
-
|
|
545
|
-
if (folded.deletes.length > 0) {
|
|
546
|
-
await applyBulkDeletesToTable({
|
|
547
|
-
pg: tx,
|
|
548
|
-
target,
|
|
549
|
-
messages: folded.deletes,
|
|
550
|
-
debug,
|
|
551
|
-
});
|
|
552
|
-
}
|
|
553
|
-
if (folded.inserts.length > 0) {
|
|
554
|
-
if (snapshotModeAtPeek.get(shapeName) || target.applyMode === "upsert") {
|
|
555
|
-
// Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery
|
|
556
|
-
// loops can re-deliver these exact snapshot rows, possibly in a later commit after this
|
|
557
|
-
// shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same
|
|
558
|
-
// posture as a move-in, rather than failing the commit on a PK collision.
|
|
559
|
-
// ADR-0045: a table declaring `applyMode: "upsert"` also folds its CDC inserts through the
|
|
560
|
-
// idempotent applier, because a local trigger may already have created the provisional row.
|
|
561
|
-
await applyUpsertsToTable({
|
|
562
|
-
pg: tx,
|
|
563
|
-
target,
|
|
564
|
-
messages: folded.inserts,
|
|
565
|
-
debug,
|
|
566
|
-
});
|
|
567
|
-
} else {
|
|
568
|
-
await applyInsertsToTable({
|
|
569
|
-
pg: tx,
|
|
570
|
-
target,
|
|
571
|
-
messages: folded.inserts,
|
|
572
|
-
debug,
|
|
573
|
-
});
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
if (folded.updates.length > 0) {
|
|
577
|
-
await applyBulkUpdatesToTable({
|
|
578
|
-
pg: tx,
|
|
579
|
-
target,
|
|
580
|
-
messages: folded.updates,
|
|
581
|
-
debug,
|
|
582
|
-
});
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
// ADR-0023: after the data + tag state is current, apply this shape's buffered move-outs —
|
|
587
|
-
// withdraw the revoked tag and evict any row left with no tag (via the bulk-delete path, so
|
|
588
|
-
// the reconcile trigger fires and the read model converges).
|
|
589
|
-
const patternSets = moveOutsToCommit.get(shapeName);
|
|
590
|
-
if (patternSets) {
|
|
591
|
-
await applyShapeMoveOut({
|
|
592
|
-
pg: tx,
|
|
593
|
-
metadataSchema,
|
|
594
|
-
shapeTable,
|
|
595
|
-
target,
|
|
596
|
-
patternSets,
|
|
597
|
-
debug,
|
|
598
|
-
sessionScoped,
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
if (key) {
|
|
604
|
-
await updateSubscriptionState({
|
|
605
|
-
pg: tx,
|
|
606
|
-
metadataSchema,
|
|
607
|
-
subscriptionKey: key,
|
|
608
|
-
sessionScoped,
|
|
609
|
-
shapeMetadata: Object.fromEntries(
|
|
610
|
-
Object.keys(shapes).map((shapeName) => {
|
|
611
|
-
const stream = getShapeStream(shapeName);
|
|
612
|
-
return [
|
|
613
|
-
shapeName,
|
|
614
|
-
{
|
|
615
|
-
handle: stream.shapeHandle!,
|
|
616
|
-
offset: stream.lastOffset,
|
|
617
|
-
},
|
|
618
|
-
];
|
|
619
|
-
}),
|
|
620
|
-
),
|
|
621
|
-
lastLsn: targetLsn,
|
|
622
|
-
debug,
|
|
623
|
-
});
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// If we unsubscribed while this commit was in flight, discard it rather than persist
|
|
627
|
-
// work during teardown. PGlite's `transaction()` skips its COMMIT once `tx.rollback()`
|
|
628
|
-
// has closed the tx, so this rolls back both the applied rows and the subscription-state
|
|
629
|
-
// advance; the (un-advanced) persisted offset means a later resume re-streams this batch.
|
|
630
|
-
if (unsubscribed) {
|
|
631
|
-
await tx.rollback();
|
|
632
|
-
}
|
|
633
|
-
});
|
|
634
|
-
|
|
635
|
-
for (let attempt = 1; ; attempt++) {
|
|
636
|
-
if (unsubscribed) {
|
|
637
|
-
return false;
|
|
638
|
-
}
|
|
639
|
-
try {
|
|
640
|
-
await runCommit();
|
|
641
|
-
if (unsubscribed) {
|
|
642
|
-
// The commit rolled itself back on unsubscribe (see runCommit); do not advance the
|
|
643
|
-
// committed frontier, ACK the peeked buffer, or clear truncate flags for discarded work.
|
|
644
|
-
return false;
|
|
645
|
-
}
|
|
646
|
-
committedLsn = targetLsn;
|
|
647
|
-
// The transaction committed — now (and only now) remove the peeked batch from the inbox, passing
|
|
648
|
-
// the peek-time epochs so a shape reset mid-commit is skipped (its rebuild survives). Move-outs/
|
|
649
|
-
// move-ins are ACKed by the exact peeked count so anything that arrived during a coalescing
|
|
650
|
-
// commit survives for the next run.
|
|
651
|
-
inbox.ackUpTo(targetLsn, epochsAtPeek);
|
|
652
|
-
for (const [shapeName, patternSets] of moveOutsToCommit) {
|
|
653
|
-
inbox.ackMoveOuts(shapeName, patternSets.length, epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName));
|
|
654
|
-
}
|
|
655
|
-
for (const [shapeName, moveInMessages] of moveInsToCommit) {
|
|
656
|
-
inbox.ackMoveIns(
|
|
657
|
-
shapeName,
|
|
658
|
-
moveInMessages.length,
|
|
659
|
-
epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName),
|
|
660
|
-
);
|
|
661
|
-
}
|
|
662
|
-
for (const shapeName of shapesToTruncate) {
|
|
663
|
-
truncateNeeded.delete(shapeName);
|
|
664
|
-
}
|
|
665
|
-
if (debug) console.timeEnd("commit");
|
|
666
|
-
maybeSignalInitialSync();
|
|
667
|
-
return true;
|
|
668
|
-
} catch (error) {
|
|
669
|
-
if (unsubscribed) {
|
|
670
|
-
return false;
|
|
671
|
-
}
|
|
672
|
-
if (attempt >= maxCommitRetries) {
|
|
673
|
-
degraded = true;
|
|
674
|
-
onSyncError?.(error instanceof Error ? error : new Error(String(error)));
|
|
675
|
-
return false;
|
|
676
|
-
}
|
|
677
|
-
await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
};
|
|
681
|
-
|
|
682
|
-
const lowestCompleteLsn = (): Lsn => inbox.lowestCompleteLsn();
|
|
683
|
-
|
|
684
|
-
// ─── Live-tail sibling nudge (ADR-0031 live-tail completion) ──────────────────────────────────────
|
|
685
|
-
// The catch-up alignment (ADR-0031 in shape-inbox.ts) fixed this class of stall at BOOT: quiet shapes'
|
|
686
|
-
// stale cached watermarks no longer hold a busy shape's backfill. On the LIVE tail the same shape holds
|
|
687
|
-
// recur — a change batch lands on a busy shape at LSN L, but the group commits only at the min effective
|
|
688
|
-
// frontier, so the batch stays buffered until every quiet sibling's PARKED long-poll returns a fresh
|
|
689
|
-
// `global_last_seen_lsn` (~41s on Electric Cloud). This watchdog closes that live-tail gap: when a batch
|
|
690
|
-
// is gated (its `batchMaxLsn > committedLsn`), it nudges each lagging sibling — aborting its parked poll
|
|
691
|
-
// and forcing an immediate NON-live catch-up (`forceDisconnectAndRefresh`), which returns a fresh
|
|
692
|
-
// watermark in ~sub-second. The group frontier then reaches L and the normal commit path (driven by the
|
|
693
|
-
// up-to-date arrivals, NOT by this watchdog) fires. Atomicity is untouched: commits still happen only at
|
|
694
|
-
// the group min frontier. The one-shot cache-buster (`nudgeBusters` + `withNudgeBuster`) defends each
|
|
695
|
-
// nudged catch-up against a CDN HIT that would echo the stale watermark. Bounded to NUDGE_MAX_ROUNDS so a
|
|
696
|
-
// genuinely-dead or still-legitimately-polling sibling degrades to the old wait-out-the-poll behavior
|
|
697
|
-
// rather than a refresh storm.
|
|
698
|
-
const nudgeInFlight = new Map<string, Promise<void>>();
|
|
699
|
-
let nudgeTargetLsn: Lsn = BigInt(-1);
|
|
700
|
-
let nudgeWatchdogRunning = false;
|
|
701
|
-
|
|
702
|
-
// Void-called from the subscribe callback (never awaited — it must not backpressure the stream). Raises
|
|
703
|
-
// the shared target and, if not already running, runs bounded rounds until the frontier reaches it, the
|
|
704
|
-
// group tears down / degrades / re-closes its gate, or the rounds exhaust. Single-flight: a concurrent
|
|
705
|
-
// gated batch just raises `nudgeTargetLsn` and returns. Wrapped so it can never throw unhandled.
|
|
706
|
-
const runNudgeWatchdog = async (targetLsn: Lsn): Promise<void> => {
|
|
707
|
-
if (targetLsn > nudgeTargetLsn) {
|
|
708
|
-
nudgeTargetLsn = targetLsn;
|
|
709
|
-
}
|
|
710
|
-
if (nudgeWatchdogRunning) {
|
|
711
|
-
return;
|
|
712
|
-
}
|
|
713
|
-
nudgeWatchdogRunning = true;
|
|
714
|
-
try {
|
|
715
|
-
// Pre-alignment (boot catch-up, before ADR-0031 lays the commit floors) the nudge is pure noise:
|
|
716
|
-
// the alignment itself will commit the gated backfill the moment every shape reports, and firing
|
|
717
|
-
// busted catch-ups mid-boot only contends with the boot requests. The floors survive later resets,
|
|
718
|
-
// so this gate closes exactly once — the live tail is always past it.
|
|
719
|
-
if (inbox.alignedFloor() < BigInt(0)) {
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
// Resolved / torn-down / gated-shut → nothing to nudge; the up-to-date arrival itself runs the
|
|
723
|
-
// commit, so the watchdog never commits.
|
|
724
|
-
const resolvedOrStopped = (): boolean =>
|
|
725
|
-
unsubscribed || degraded || !dbGateOpen || lowestCompleteLsn() >= nudgeTargetLsn;
|
|
726
|
-
|
|
727
|
-
// Hold-persistence grace: a cross-shape transaction's sibling halves arrive milliseconds apart,
|
|
728
|
-
// so EVERY grouped commit passes through a transient held instant — nudging on it would abort
|
|
729
|
-
// the sibling poll that is about to deliver the other half (the sync-e2e regression). Only a
|
|
730
|
-
// hold that survives this grace is a real quiet-sibling park worth nudging.
|
|
731
|
-
for (let waited = 0; waited < NUDGE_HOLD_GRACE_MS; waited += NUDGE_ROUND_GRACE_MS) {
|
|
732
|
-
await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));
|
|
733
|
-
if (resolvedOrStopped()) {
|
|
734
|
-
return;
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
for (let round = 1; round <= NUDGE_MAX_ROUNDS; round++) {
|
|
739
|
-
if (resolvedOrStopped()) {
|
|
740
|
-
return;
|
|
741
|
-
}
|
|
742
|
-
for (const shapeName of Object.keys(shapes)) {
|
|
743
|
-
// A shape still catching up advances on its own — only nudge one already in its live tail.
|
|
744
|
-
if (!inbox.hasReportedUpToDate(shapeName)) continue;
|
|
745
|
-
if (inbox.effectiveLsnFor(shapeName) >= nudgeTargetLsn) continue;
|
|
746
|
-
if (nudgeInFlight.has(shapeName)) continue;
|
|
747
|
-
// `forceDisconnectAndRefresh` is declared on the real ShapeStream, but a mocked/typed surface may
|
|
748
|
-
// omit it — reach it structurally and skip (with a rail line) when absent.
|
|
749
|
-
const stream = getShapeStream(shapeName) as { forceDisconnectAndRefresh?: () => Promise<void> };
|
|
750
|
-
if (typeof stream.forceDisconnectAndRefresh !== "function") {
|
|
751
|
-
syncDebug("live-tail sibling nudge unavailable", { shape: shapeName });
|
|
752
|
-
continue;
|
|
753
|
-
}
|
|
754
|
-
// Arm the one-shot cache-buster BEFORE the refresh so the forced catch-up carries it.
|
|
755
|
-
nudgeBusters.set(shapeName, crypto.randomUUID());
|
|
756
|
-
syncDebug("live-tail sibling nudge", { shape: shapeName, target: String(nudgeTargetLsn), round });
|
|
757
|
-
const refresh = stream
|
|
758
|
-
.forceDisconnectAndRefresh()
|
|
759
|
-
.catch((err: unknown) =>
|
|
760
|
-
syncDebug("live-tail sibling nudge failed", { shape: shapeName, error: String(err) }),
|
|
761
|
-
)
|
|
762
|
-
.finally(() => {
|
|
763
|
-
nudgeInFlight.delete(shapeName);
|
|
764
|
-
});
|
|
765
|
-
nudgeInFlight.set(shapeName, refresh);
|
|
766
|
-
}
|
|
767
|
-
// Nothing to nudge and nothing in flight → exit QUIETLY (no exhaustion line). This is the routine
|
|
768
|
-
// pre-alignment case: a gated batch during catch-up has siblings that have not yet reported
|
|
769
|
-
// up-to-date, and those advance on their own — spinning the remaining rounds would only delay-loop
|
|
770
|
-
// and print a misleading "exhausted" line on every boot rail. The "held by group frontier" line
|
|
771
|
-
// already told the story.
|
|
772
|
-
if (nudgeInFlight.size === 0) {
|
|
773
|
-
return;
|
|
774
|
-
}
|
|
775
|
-
// Wait for this round's forced catch-ups to actually land and advance the frontier. The refresh
|
|
776
|
-
// promises settle before the refreshed response does (measured), so awaiting them alone would
|
|
777
|
-
// re-nudge into still-in-flight requests — poll the frontier instead, bounded per round, and
|
|
778
|
-
// break out the moment the target is reached.
|
|
779
|
-
await Promise.all([...nudgeInFlight.values()]);
|
|
780
|
-
for (let waited = 0; waited < NUDGE_ROUND_WAIT_MS; waited += NUDGE_ROUND_GRACE_MS) {
|
|
781
|
-
await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));
|
|
782
|
-
if (resolvedOrStopped()) {
|
|
783
|
-
return;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
// Rounds exhausted and the frontier is still short: a sibling is dead or genuinely mid-poll. Degrade
|
|
788
|
-
// to the old behavior (wait out its live long-poll) rather than nudge forever.
|
|
789
|
-
syncDebug("live-tail nudge exhausted; waiting on sibling live polls", {
|
|
790
|
-
target: String(nudgeTargetLsn),
|
|
791
|
-
frontier: String(lowestCompleteLsn()),
|
|
792
|
-
});
|
|
793
|
-
} catch (err) {
|
|
794
|
-
syncDebug("live-tail nudge watchdog error", { error: String(err) });
|
|
795
|
-
} finally {
|
|
796
|
-
nudgeWatchdogRunning = false;
|
|
797
|
-
}
|
|
798
|
-
};
|
|
799
|
-
|
|
800
|
-
// Drain buffered changes up to the current complete frontier, one commit at a time, looping
|
|
801
|
-
// while fresh messages keep arriving (so commits coalesce). Returns early on `degraded` — a held
|
|
802
|
-
// commit is not retried here; recovery is a later message/refetch or a restart.
|
|
803
|
-
const runCommitLoop = async (): Promise<void> => {
|
|
804
|
-
do {
|
|
805
|
-
commitRerun = false;
|
|
806
|
-
const target = lowestCompleteLsn();
|
|
807
|
-
const isCommitNeeded = target > committedLsn;
|
|
808
|
-
const isMustRefetchAndCatchingUp = target >= committedLsn && truncateNeeded.size > 0;
|
|
809
|
-
// A buffered move-out (ADR-0023) or move-in (ADR-0024) must be committed even if no change
|
|
810
|
-
// advanced the frontier — the revocation/grant has to land. Their `up-to-date` normally advances
|
|
811
|
-
// `target`, but don't rely on that (move/event messages carry no LSN).
|
|
812
|
-
const hasPendingMoves = target >= committedLsn && (inbox.hasPendingMoveOuts() || inbox.hasPendingMoveIns());
|
|
813
|
-
// ADR-0031: a LATE-arriving change at or below an already-committed target must still commit. The
|
|
814
|
-
// aligned commit floor lets `ingestChange` accept a change below the floor (its dedup frontier is
|
|
815
|
-
// the raw `completeLsns`, unmoved by the floor), so such a change can land AFTER the group frontier
|
|
816
|
-
// has already reached — or passed — its LSN, where no frontier advance would trigger a commit for
|
|
817
|
-
// it. Committing at `target === committedLsn` is safe: it mirrors the moves path, which already
|
|
818
|
-
// calls `commitUpToLsn(target)` with no frontier advance. (At `target > committedLsn` this overlaps
|
|
819
|
-
// `isCommitNeeded` — harmless; the expression stays simple.)
|
|
820
|
-
const hasLateArrivals = target >= committedLsn && inbox.hasBufferedChangesAtOrBelow(target);
|
|
821
|
-
if (isCommitNeeded || isMustRefetchAndCatchingUp || hasPendingMoves || hasLateArrivals) {
|
|
822
|
-
const applied = await commitUpToLsn(target);
|
|
823
|
-
if (!applied) {
|
|
824
|
-
return;
|
|
825
|
-
}
|
|
826
|
-
} else {
|
|
827
|
-
maybeSignalInitialSync();
|
|
828
|
-
}
|
|
829
|
-
} while (commitRerun);
|
|
830
|
-
};
|
|
831
|
-
|
|
832
|
-
// Single-flight: at most one commit loop runs. A message arriving while one is running buffers
|
|
833
|
-
// synchronously (above) and re-arms the loop via `commitRerun`; `commitInFlight` is cleared
|
|
834
|
-
// inside the same async body — before its promise resolves — so an enqueue can never observe a
|
|
835
|
-
// stale in-flight handle and resolve without committing its messages.
|
|
836
|
-
const enqueueCommit = (): Promise<void> => {
|
|
837
|
-
// ADR-0009 decision 5: once a commit exhausts its retries the engine latches `degraded` and
|
|
838
|
-
// REFUSES to run any further commit. `commitUpToLsn` peeks (never drains) the buffer, so the
|
|
839
|
-
// unapplied batch is still held; refusing later commits guarantees a newer LSN can never apply
|
|
840
|
-
// over that held batch (the divergence the destructive drain allowed). The buffer keeps
|
|
841
|
-
// accumulating incoming messages harmlessly; recovery is a restart/refetch, which re-streams the
|
|
842
|
-
// held frontier because the persisted offset was never advanced. Note the commit-await backpressure
|
|
843
|
-
// is intentionally absent while degraded — the inbox grows at the stream's rate until recovery,
|
|
844
|
-
// which is the accepted cost of ADR-0009's documented "hold the buffer" posture.
|
|
845
|
-
if (degraded) {
|
|
846
|
-
return commitInFlight ?? Promise.resolve();
|
|
847
|
-
}
|
|
848
|
-
if (commitInFlight) {
|
|
849
|
-
commitRerun = true;
|
|
850
|
-
return commitInFlight;
|
|
851
|
-
}
|
|
852
|
-
commitInFlight = (async () => {
|
|
853
|
-
try {
|
|
854
|
-
await runCommitLoop();
|
|
855
|
-
} finally {
|
|
856
|
-
commitInFlight = null;
|
|
857
|
-
}
|
|
858
|
-
})();
|
|
859
|
-
return commitInFlight;
|
|
860
|
-
};
|
|
861
|
-
|
|
862
|
-
multiShapeStream.subscribe(async (messages) => {
|
|
863
|
-
if (unsubscribed) {
|
|
864
|
-
return;
|
|
865
|
-
}
|
|
866
|
-
// A delivered batch means a fetch just succeeded — the read path is alive (ADR-0013 Phase 3),
|
|
867
|
-
// so the runtime can clear an auth-needed status once a fresh token starts working again.
|
|
868
|
-
onSyncActivity?.();
|
|
869
|
-
if (debug) {
|
|
870
|
-
console.log("received messages", messages.length);
|
|
871
|
-
}
|
|
872
|
-
// Receive-path latency probe: a batch carrying real change rows is the moment Electric delivered
|
|
873
|
-
// a write to this subscriber (the writer's own echo, or another browser's edit fanning in). The
|
|
874
|
-
// gap from here to the commit finishing is the local apply cost.
|
|
875
|
-
const changeCount = messages.reduce((n, message) => (isChangeMessage(message) ? n + 1 : n), 0);
|
|
876
|
-
if (changeCount > 0) {
|
|
877
|
-
syncDebug("sync received change batch from Electric", { changes: changeCount });
|
|
878
|
-
}
|
|
879
|
-
// Boot observability (ADR-0034): one delivery = one shape-stream response. Records the fetch (network)
|
|
880
|
-
// gap since the last settle plus this batch's request + change-row counts. No-op post-ready (frozen).
|
|
881
|
-
bootStamp?.onBatchDelivered(changeCount);
|
|
882
|
-
const commitStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
883
|
-
|
|
884
|
-
// The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;
|
|
885
|
-
// move-in rows carry no lsn and are excluded). It is what the batch needs the group frontier to reach
|
|
886
|
-
// to actually commit — the truth test for the "applied" vs "held" rail line below. -1 if none.
|
|
887
|
-
let batchMaxLsn: Lsn = BigInt(-1);
|
|
888
|
-
|
|
889
|
-
messages.forEach((message) => {
|
|
890
|
-
if (isChangeMessage(message)) {
|
|
891
|
-
// A tagged-subquery MOVE-IN row (ADR-0024): an existing row ENTERING the shape because a grant
|
|
892
|
-
// was added. Electric delivers it as a snapshot insert flagged `is_move_in` with NO `lsn`/`last`
|
|
893
|
-
// (it is not a replication-stream change), so the `ingestChange` dedup — which floors a missing
|
|
894
|
-
// lsn to 0 — would treat it as already-seen and drop it once the frontier passed 0. Route it to
|
|
895
|
-
// its own buffer, applied idempotently at the next commit (the trailing `up-to-date`).
|
|
896
|
-
if (message.headers["is_move_in"] === true) {
|
|
897
|
-
inbox.ingestMoveIn(message.shape, message);
|
|
898
|
-
} else {
|
|
899
|
-
const { lsn, isLastOfLsn } = readReplicationHeaders(message.headers);
|
|
900
|
-
inbox.ingestChange(message.shape, message, lsn, isLastOfLsn);
|
|
901
|
-
if (isLastOfLsn && lsn > batchMaxLsn) {
|
|
902
|
-
batchMaxLsn = lsn;
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
} else if (isControlMessage(message)) {
|
|
906
|
-
switch (message.headers.control) {
|
|
907
|
-
case "up-to-date": {
|
|
908
|
-
if (debug) {
|
|
909
|
-
console.log("received up-to-date", message);
|
|
910
|
-
}
|
|
911
|
-
if (typeof message.headers.global_last_seen_lsn !== "string") {
|
|
912
|
-
throw new Error("global_last_seen_lsn is not a string");
|
|
913
|
-
}
|
|
914
|
-
// ADR-0031: `ingestUpToDate` returns true ONLY on the transition where this control message
|
|
915
|
-
// completed the group (every shape has now reported up-to-date) and the inbox aligned the
|
|
916
|
-
// commit floors. Surface that single moment on the debug rail so a "stale board at load that
|
|
917
|
-
// rearranges itself" symptom is diagnosable — the floor it aligned to is the group head.
|
|
918
|
-
if (inbox.ingestUpToDate(message.shape, BigInt(message.headers.global_last_seen_lsn))) {
|
|
919
|
-
syncDebug("catch-up watermark aligned", { floor: String(inbox.alignedFloor()) });
|
|
920
|
-
}
|
|
921
|
-
break;
|
|
922
|
-
}
|
|
923
|
-
case "must-refetch": {
|
|
924
|
-
if (debug) {
|
|
925
|
-
console.log("received must-refetch", message);
|
|
926
|
-
}
|
|
927
|
-
// Surface the expired-handle / rewind event on the syncDebug rail too (the `debug` option only
|
|
928
|
-
// console.logs it): must-refetch is the trigger for the truncate + re-snapshot
|
|
929
|
-
// recovery, so it must be visible when diagnosing a convergence loss in a live app.
|
|
930
|
-
syncDebug("must-refetch received", { shape: message.shape });
|
|
931
|
-
inbox.resetShape(message.shape);
|
|
932
|
-
truncateNeeded.add(message.shape);
|
|
933
|
-
break;
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
} else if (isEventMessage(message)) {
|
|
937
|
-
// ADR-0023: a tagged-subquery move-out — a grant was revoked, so the rows it kept in the shape
|
|
938
|
-
// must be evicted. Buffer the patterns; the eviction runs in the next commit (decision 3).
|
|
939
|
-
// `MultiShapeStream`'s callback type does not declare `EventMessage` (the prior guards narrow
|
|
940
|
-
// `message` to `never` here), so reach the runtime-present event through an explicit cast.
|
|
941
|
-
const eventMessage = message as unknown as ShapeEventMessage;
|
|
942
|
-
if (eventMessage.headers.event === "move-out") {
|
|
943
|
-
if (debug) {
|
|
944
|
-
console.log("received move-out", eventMessage);
|
|
945
|
-
}
|
|
946
|
-
inbox.ingestMoveOut(eventMessage.shape, eventMessage.headers.patterns);
|
|
947
|
-
}
|
|
948
|
-
// A `move-in` EventMessage (ADR-0024) needs no action here: its newly-matched rows arrive in the
|
|
949
|
-
// same batch as snapshot inserts flagged `is_move_in`, which the change branch routes to the
|
|
950
|
-
// move-in buffer. The event's `patterns` are redundant with those inserts' `tags`.
|
|
951
|
-
}
|
|
952
|
-
});
|
|
953
|
-
|
|
954
|
-
// Buffering above is synchronous. On the overlap path, while the commit gate is still closed the
|
|
955
|
-
// batch stays in the memory inbox (its LSN frontier + catch-up watermarks still advance from the
|
|
956
|
-
// ingest above) and the callback returns WITHOUT awaiting a commit — so the stream keeps fetching
|
|
957
|
-
// catch-up and does not stall behind the local boot phases. Once the gate lifts, the deferred commit
|
|
958
|
-
// train (below) drains everything buffered. On the sequential path the gate is already open, so this
|
|
959
|
-
// is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that
|
|
960
|
-
// bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).
|
|
961
|
-
if (dbGateOpen) {
|
|
962
|
-
const applyStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
963
|
-
await enqueueCommit();
|
|
964
|
-
// Boot observability (ADR-0034): the apply (commit-into-PGlite) wall for this delivery.
|
|
965
|
-
bootStamp?.onApply((typeof performance !== "undefined" ? performance.now() : Date.now()) - applyStartedAt);
|
|
966
|
-
if (changeCount > 0) {
|
|
967
|
-
// Truthful rail (ADR-0031): the "applied" line only fires when this batch's completed changes
|
|
968
|
-
// actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the
|
|
969
|
-
// group frontier had not reached them — the batch is BUFFERED behind a quiet sibling's watermark —
|
|
970
|
-
// so say so, and kick the live-tail sibling nudge to shorten that hold (void: never backpressure
|
|
971
|
-
// the stream).
|
|
972
|
-
if (batchMaxLsn <= committedLsn) {
|
|
973
|
-
const elapsed = (typeof performance !== "undefined" ? performance.now() : Date.now()) - commitStartedAt;
|
|
974
|
-
syncDebug("sync applied change batch to local store", { changes: changeCount, ms: Math.round(elapsed) });
|
|
975
|
-
} else {
|
|
976
|
-
syncDebug("sync change batch held by group frontier", {
|
|
977
|
-
changes: changeCount,
|
|
978
|
-
heldLsn: String(batchMaxLsn),
|
|
979
|
-
frontier: String(lowestCompleteLsn()),
|
|
980
|
-
});
|
|
981
|
-
void runNudgeWatchdog(batchMaxLsn);
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
}, onError);
|
|
986
|
-
|
|
987
|
-
// Fresh-store prefetch overlap (ADR-0032 S4): the moment the caller signals the local store is ready
|
|
988
|
-
// (schema exec + journal recovery + store-version reconcile done), run the deferred metadata DDL, open
|
|
989
|
-
// the commit gate, and drain everything the streams buffered during the window in one commit train. The
|
|
990
|
-
// ADR-0031 catch-up watermarks were aligned by the ingests above as the up-to-dates arrived, so this
|
|
991
|
-
// drain commits to the aligned floor and `onInitialSync` fires exactly as on the sequential path.
|
|
992
|
-
if (overlap) {
|
|
993
|
-
void dbReady!.then(async () => {
|
|
994
|
-
if (unsubscribed) {
|
|
995
|
-
return;
|
|
996
|
-
}
|
|
997
|
-
// The metadata tables' DDL was deferred past the gate (the store had no schema when the streams
|
|
998
|
-
// started); create them now, before the first commit needs the subscription-state table.
|
|
999
|
-
await initMetadataTables();
|
|
1000
|
-
dbGateOpen = true;
|
|
1001
|
-
syncDebug("boot commits opened");
|
|
1002
|
-
// Boot observability (ADR-0034): on the overlap path the buffered catch-up drains here (not in a
|
|
1003
|
-
// subscribe callback), so stamp the drain's apply wall into the group's accumulator.
|
|
1004
|
-
const drainStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
1005
|
-
await enqueueCommit();
|
|
1006
|
-
bootStamp?.onApply((typeof performance !== "undefined" ? performance.now() : Date.now()) - drainStartedAt);
|
|
1007
|
-
});
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
streams.push({
|
|
1011
|
-
stream: multiShapeStream,
|
|
1012
|
-
aborter,
|
|
1013
|
-
});
|
|
1014
|
-
|
|
1015
|
-
const unsubscribe = () => {
|
|
1016
|
-
if (debug) {
|
|
1017
|
-
console.log("unsubscribing");
|
|
1018
|
-
}
|
|
1019
|
-
unsubscribed = true;
|
|
1020
|
-
multiShapeStream.unsubscribeAll();
|
|
1021
|
-
aborter.abort();
|
|
1022
|
-
for (const shape of Object.values(shapes)) {
|
|
1023
|
-
shapePerTableLock.delete(shape.tableKey);
|
|
1024
|
-
}
|
|
1025
|
-
};
|
|
1026
|
-
|
|
1027
|
-
return {
|
|
1028
|
-
unsubscribe,
|
|
1029
|
-
get isUpToDate() {
|
|
1030
|
-
// Never report up-to-date while a commit is pending or after going degraded (ADR-0009
|
|
1031
|
-
// decision 5): the read cache must not claim to match the server on an unapplied commit. Nor while
|
|
1032
|
-
// the overlap commit gate is still closed (ADR-0032 S4): the stream may already be `isUpToDate` on
|
|
1033
|
-
// the network side while its catch-up is still buffered, unapplied, in the memory inbox.
|
|
1034
|
-
return dbGateOpen && !degraded && commitInFlight === null && multiShapeStream.isUpToDate;
|
|
1035
|
-
},
|
|
1036
|
-
streams: Object.fromEntries(
|
|
1037
|
-
Object.keys(shapes).map((shapeName) => [shapeName, getShapeStream(shapeName)]),
|
|
1038
|
-
) as SyncShapesToTablesResult["streams"],
|
|
1039
|
-
};
|
|
1040
|
-
};
|
|
1041
|
-
|
|
1042
|
-
const syncShapeToTable = async (options: SyncShapeToTableOptions): Promise<SyncShapeToTableResult> => {
|
|
1043
|
-
// ADR-0029 D6: thin sugar over the group form, forwarding the same entry-based options. The
|
|
1044
|
-
// per-shape `initialInsertMethod` (if any) rides through; the group form resolves the backfill
|
|
1045
|
-
// strategy from the registry entry when it is absent.
|
|
1046
|
-
const multiShapeSub = await syncShapesToTables({
|
|
1047
|
-
registry: options.registry,
|
|
1048
|
-
shapes: {
|
|
1049
|
-
shape: {
|
|
1050
|
-
shape: options.shape,
|
|
1051
|
-
tableKey: options.tableKey,
|
|
1052
|
-
onMustRefetch: options.onMustRefetch,
|
|
1053
|
-
...(options.initialInsertMethod ? { initialInsertMethod: options.initialInsertMethod } : {}),
|
|
1054
|
-
},
|
|
1055
|
-
},
|
|
1056
|
-
key: options.shapeKey,
|
|
1057
|
-
...(options.sessionScoped ? { sessionScoped: options.sessionScoped } : {}),
|
|
1058
|
-
onInitialSync: options.onInitialSync,
|
|
1059
|
-
onError: options.onError,
|
|
1060
|
-
onSyncError: options.onSyncError,
|
|
1061
|
-
maxCommitRetries: options.maxCommitRetries,
|
|
1062
|
-
commitRetryDelayMs: options.commitRetryDelayMs,
|
|
1063
|
-
});
|
|
1064
|
-
|
|
1065
|
-
return {
|
|
1066
|
-
unsubscribe: multiShapeSub.unsubscribe,
|
|
1067
|
-
get isUpToDate() {
|
|
1068
|
-
return multiShapeSub.isUpToDate;
|
|
1069
|
-
},
|
|
1070
|
-
stream: (() => {
|
|
1071
|
-
const stream = multiShapeSub.streams["shape"];
|
|
1072
|
-
if (!stream) {
|
|
1073
|
-
throw new Error("Missing stream for shape");
|
|
1074
|
-
}
|
|
1075
|
-
return stream;
|
|
1076
|
-
})() as SyncShapeToTableResult["stream"],
|
|
1077
|
-
};
|
|
1078
|
-
};
|
|
1079
|
-
|
|
1080
|
-
const deleteSubscription = async (key: string) => {
|
|
1081
|
-
// ADR-0042: the scope-blind delete now also touches `pg_temp.subscriptions_metadata`, which does NOT
|
|
1082
|
-
// exist until the (per-engine, memoized) metadata migration has run — so a warm-store reset that fires
|
|
1083
|
-
// before any group started (nothing else triggered `initMetadataTables` yet) would hit 42P01. Ensure the
|
|
1084
|
-
// provisioning first; the promise is memoized/idempotent, so on the normal path (a group already
|
|
1085
|
-
// started) this is a no-op await on the resolved init promise.
|
|
1086
|
-
await initMetadataTables();
|
|
1087
|
-
await deleteSubscriptionState({
|
|
1088
|
-
pg,
|
|
1089
|
-
metadataSchema,
|
|
1090
|
-
subscriptionKey: key,
|
|
1091
|
-
});
|
|
1092
|
-
};
|
|
1093
|
-
|
|
1094
|
-
const namespaceObj = {
|
|
1095
|
-
initMetadataTables,
|
|
1096
|
-
syncShapesToTables,
|
|
1097
|
-
syncShapeToTable,
|
|
1098
|
-
deleteSubscription,
|
|
1099
|
-
};
|
|
1100
|
-
|
|
1101
|
-
const close = async () => {
|
|
1102
|
-
for (const { stream, aborter } of streams) {
|
|
1103
|
-
stream.unsubscribeAll();
|
|
1104
|
-
aborter.abort();
|
|
1105
|
-
}
|
|
1106
|
-
};
|
|
1107
|
-
|
|
1108
|
-
return {
|
|
1109
|
-
namespace: namespaceObj,
|
|
1110
|
-
close,
|
|
1111
|
-
};
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
/**
|
|
1115
|
-
* The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,
|
|
1116
|
-
* plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type
|
|
1117
|
-
* follows the object.
|
|
1118
|
-
*/
|
|
1119
|
-
export type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;
|
|
1120
|
-
export type SyncNamespaceObj = SyncEngine["namespace"];
|
|
1121
|
-
|
|
1122
|
-
export type PGliteWithSync = PGliteInterface & {
|
|
1123
|
-
sync: SyncNamespaceObj;
|
|
1124
|
-
};
|