@pgxsinkit/client 0.2.6 → 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 +6 -7
- 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
package/src/shape-sync.ts
DELETED
|
@@ -1,533 +0,0 @@
|
|
|
1
|
-
import type { ExternalHeadersRecord } from "@electric-sql/client";
|
|
2
|
-
import type { PGliteInterface } from "@electric-sql/pglite";
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
type Retention,
|
|
6
|
-
type SubscriptionTiming,
|
|
7
|
-
type SyncConfigInput,
|
|
8
|
-
type SyncTableRegistry,
|
|
9
|
-
type TableSpecInput,
|
|
10
|
-
} from "@pgxsinkit/contracts";
|
|
11
|
-
|
|
12
|
-
import type { BootStampCollector, GroupBootStamp } from "./boot-report";
|
|
13
|
-
import { createReadStreamStallProbe } from "./read-stream-stall";
|
|
14
|
-
import type { SyncNamespaceObj } from "./sync";
|
|
15
|
-
import { createShapeErrorHandler } from "./sync-auth";
|
|
16
|
-
|
|
17
|
-
export interface ShapeSyncSpec {
|
|
18
|
-
electricUrl: string;
|
|
19
|
-
tableName: string;
|
|
20
|
-
schema?: string;
|
|
21
|
-
shapeKey: string;
|
|
22
|
-
primaryKey: string[];
|
|
23
|
-
electricTable?: string;
|
|
24
|
-
/**
|
|
25
|
-
* Consistency group (ADR-0009 decision 2). Specs sharing a group sync on one `MultiShapeStream`
|
|
26
|
-
* and commit atomically. Absent → the table is its own singleton group keyed by its `shapeKey`.
|
|
27
|
-
*/
|
|
28
|
-
consistencyGroup?: string;
|
|
29
|
-
/**
|
|
30
|
-
* Subscription timing (ADR-0021). Absent → `eager`. A `lazy` spec's group is held out of the eager
|
|
31
|
-
* boot set and started on demand via {@link StartConfiguredSyncResult.ensureGroupStarted}. A group's
|
|
32
|
-
* members all agree (registry-validated), so the group's timing is any member's.
|
|
33
|
-
*/
|
|
34
|
-
subscription?: SubscriptionTiming;
|
|
35
|
-
/**
|
|
36
|
-
* Retention (ADR-0021). Absent → `persistent`. Only a `persistent` `lazy` group is promoted to the
|
|
37
|
-
* eager set on activation (its activation is permanent across boots); an `ephemeral` group's activation
|
|
38
|
-
* is session-scoped by construction, so it is never promoted/persisted.
|
|
39
|
-
*/
|
|
40
|
-
retention?: Retention;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export interface ConfiguredShapeSyncSpec extends ShapeSyncSpec {
|
|
44
|
-
key: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export interface StartConfiguredSyncOptions {
|
|
48
|
-
syncConfig: SyncConfigInput;
|
|
49
|
-
/**
|
|
50
|
-
* The sync registry (ADR-0029 D1): the engine's sole per-table spec source. Each shape's `tableKey`
|
|
51
|
-
* (its `syncConfig` table key) resolves against it for the local table, PKs, apply strategy, and
|
|
52
|
-
* column types — no table-scoped fact is threaded from `syncConfig` into the engine.
|
|
53
|
-
*/
|
|
54
|
-
registry: SyncTableRegistry;
|
|
55
|
-
/**
|
|
56
|
-
* Shape request headers shared by every member shape. Values may be async functions resolved per
|
|
57
|
-
* request (ADR-0013) — the read-path `Authorization` token is one such function.
|
|
58
|
-
*/
|
|
59
|
-
shapeHeaders?: ExternalHeadersRecord;
|
|
60
|
-
onInitialSync?: () => void;
|
|
61
|
-
onTableInitialSync?: (tableKey: string) => void;
|
|
62
|
-
/**
|
|
63
|
-
* Fresh-store prefetch overlap (ADR-0032 S4). When present, every EAGER group starts its shape streams
|
|
64
|
-
* and buffers their catch-up into the memory inbox immediately, gating all commits until this promise
|
|
65
|
-
* resolves — so the network catch-up overlaps the local boot phases (schema/journal/reconcile) instead
|
|
66
|
-
* of running after them. Set ONLY by `createSyncClient` on a provably-fresh store (its `freshStore`
|
|
67
|
-
* hint); absent → the sequential path. Passed straight through to the engine's `syncShapesToTables`.
|
|
68
|
-
*/
|
|
69
|
-
dbReady?: Promise<void>;
|
|
70
|
-
/** Commit-level error surfacing (ADR-0009 decision 5): a sync commit exhausted its retries. */
|
|
71
|
-
onSyncError?: (error: Error) => void;
|
|
72
|
-
/**
|
|
73
|
-
* Notified when a shape hits an auth error (401/403) and the read path is retrying for a fresh
|
|
74
|
-
* token (ADR-0013 Phase 3). The runtime surfaces a distinct `auth-needed` status from this.
|
|
75
|
-
*/
|
|
76
|
-
onAuthError?: () => void;
|
|
77
|
-
/**
|
|
78
|
-
* Notified when a shape hits a NON-auth stream error (#4): a transient 5xx/429/network (retried) or
|
|
79
|
-
* a structural 4xx (stops the stream). The runtime surfaces a `degraded` status from this so it
|
|
80
|
-
* never silently believes the read path is live while it has actually stalled.
|
|
81
|
-
*/
|
|
82
|
-
onReadStreamError?: (error: Error) => void;
|
|
83
|
-
/**
|
|
84
|
-
* Notified when a shape's fetch ATTEMPT failed and Electric is retrying it inside its own backoff
|
|
85
|
-
* wrapper (board ADR-0010): a rejected request (the offline case — no HTTP status at all), a 5xx, or a
|
|
86
|
-
* 429. The complement of {@link onReadStreamError}, which only ever fires for an error that ESCAPED that
|
|
87
|
-
* wrapper (any other 4xx) — which a network outage never does, since Electric retries it forever. Fires
|
|
88
|
-
* per attempt for as long as the outage lasts, so the runtime owns the transition; a deliberate abort
|
|
89
|
-
* (teardown, hidden tab, nudge refresh) is not a failure and is filtered out. See `read-stream-stall.ts`.
|
|
90
|
-
*/
|
|
91
|
-
onReadStreamStalled?: () => void;
|
|
92
|
-
/**
|
|
93
|
-
* Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013
|
|
94
|
-
* Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.
|
|
95
|
-
*/
|
|
96
|
-
onSyncActivity?: () => void;
|
|
97
|
-
/**
|
|
98
|
-
* Consistency-group keys of `lazy` groups that were activated on a previous boot and persisted their
|
|
99
|
-
* activation flag (ADR-0021 §2 — `lazy + persistent` promotion). These join the eager boot set as if
|
|
100
|
-
* they were declared `eager`, so a once-activated durable lazy group resumes without re-evaluation.
|
|
101
|
-
* Computed by the caller from the local meta table (the sync engine does no DB read of its own).
|
|
102
|
-
*/
|
|
103
|
-
promotedGroups?: ReadonlySet<string>;
|
|
104
|
-
/**
|
|
105
|
-
* Invoked when a `persistent` `lazy` group is activated on demand (not promoted at boot), so the
|
|
106
|
-
* caller can persist its activation flag for the next boot (ADR-0021 §2). Never fired for an
|
|
107
|
-
* `ephemeral` group (its activation is session-scoped and leaves no durable trace).
|
|
108
|
-
*/
|
|
109
|
-
onLazyActivated?: (groupKey: string) => void;
|
|
110
|
-
/**
|
|
111
|
-
* Invoked exactly once per consistency group the moment it becomes up-to-date (ADR-0032 decision 6 —
|
|
112
|
-
* per-group readiness). Fires for eager, promoted, and on-demand `lazy` groups alike, so a client can
|
|
113
|
-
* surface progressive per-group paint (and the worker bridge can fan a `groupReady` event to tabs)
|
|
114
|
-
* without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.
|
|
115
|
-
*/
|
|
116
|
-
onGroupReady?: (groupKey: string) => void;
|
|
117
|
-
/**
|
|
118
|
-
* Boot observability (ADR-0034): opens a per-group accumulator (rows/requests/fetch/apply wall) for each
|
|
119
|
-
* EAGER + PROMOTED boot group, stamped by the engine as the group's stream chain delivers and applies. A
|
|
120
|
-
* lazy on-demand start gets none — so a lazily-activated-later group never enters (or mutates) the report.
|
|
121
|
-
* Absent → no boot instrumentation.
|
|
122
|
-
*/
|
|
123
|
-
bootCollector?: BootStampCollector;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// The engine is reached through the `electric` namespace the client attaches post-create (ADR-0032 S1) —
|
|
127
|
-
// a plain property carrying the sync entry points, no longer a create-time PGlite extension.
|
|
128
|
-
type SyncEnginePGlite = PGliteInterface & { electric: SyncNamespaceObj };
|
|
129
|
-
|
|
130
|
-
export interface ShapeSyncResult {
|
|
131
|
-
unsubscribe: () => void;
|
|
132
|
-
readonly isUpToDate: boolean;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export interface StartConfiguredSyncResult {
|
|
136
|
-
unsubscribe: () => void;
|
|
137
|
-
tables: Record<string, ShapeSyncResult>;
|
|
138
|
-
/**
|
|
139
|
-
* Start a `lazy` consistency group (ADR-0021) held out of the eager boot set. Idempotent and
|
|
140
|
-
* single-flight: concurrent calls share one start; a started, unknown, or eager group resolves
|
|
141
|
-
* immediately. Resolves once the group's initial sync completes — the seam the live-query layer
|
|
142
|
-
* calls on first reference to a lazy table. After it resolves, the group's member `tables` entries
|
|
143
|
-
* report `isUpToDate` live.
|
|
144
|
-
*/
|
|
145
|
-
ensureGroupStarted: (groupKey: string) => Promise<void>;
|
|
146
|
-
/**
|
|
147
|
-
* Stop a group's stream and return it to dormant (ADR-0021 §2): tear down its live subscription and
|
|
148
|
-
* clear the runtime so {@link isTableStarted} reports false again and a later {@link ensureGroupStarted}
|
|
149
|
-
* re-subscribes from scratch — the inverse of an on-demand activation. Used by the client's `desync`
|
|
150
|
-
* to halt a lazy group before truncating its read cache. A no-op for an unknown or never-started group.
|
|
151
|
-
* The temp cluster of an `ephemeral` group is NOT dropped here (that is the deferred idle-eviction); the
|
|
152
|
-
* cluster simply stops being fed.
|
|
153
|
-
*/
|
|
154
|
-
stopGroup: (groupKey: string) => void;
|
|
155
|
-
/** The consistency-group key a table belongs to — maps a queried table to its {@link ensureGroupStarted}. */
|
|
156
|
-
groupKeyForTable: (tableKey: string) => string | undefined;
|
|
157
|
-
/**
|
|
158
|
-
* Whether a table's consistency group has started and completed its initial sync, so its reads are
|
|
159
|
-
* hydrated (ADR-0021). False for a `lazy` group still held out of the boot set. Drives the read-path
|
|
160
|
-
* tripwire — a lazy relation read while this is false would return empty/stale rows.
|
|
161
|
-
*/
|
|
162
|
-
isTableStarted: (tableKey: string) => boolean;
|
|
163
|
-
/**
|
|
164
|
-
* A promise that resolves the moment the given consistency group is up-to-date (ADR-0032 decision 6).
|
|
165
|
-
* Resolves immediately for an already-ready group; stays pending for a `lazy` group until it is
|
|
166
|
-
* activated (via {@link ensureGroupStarted}) and catches up. An unknown group resolves immediately
|
|
167
|
-
* (nothing to await). Per-group readiness the client re-exposes as `client.groupReady(table)`.
|
|
168
|
-
*/
|
|
169
|
-
groupReady: (groupKey: string) => Promise<void>;
|
|
170
|
-
/** Whether the given consistency group has completed its initial sync (synchronous peek at {@link groupReady}). */
|
|
171
|
-
isGroupReady: (groupKey: string) => boolean;
|
|
172
|
-
/** Every consistency-group key this config declares — the domain of {@link groupReady}/{@link isGroupReady}. */
|
|
173
|
-
groupKeys: () => string[];
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function buildShapeUrl(electricUrl: string, table: string) {
|
|
177
|
-
const url = new URL(electricUrl);
|
|
178
|
-
url.searchParams.set("table", table);
|
|
179
|
-
return url.toString();
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export function buildShapeConfig(input: ShapeSyncSpec) {
|
|
183
|
-
return {
|
|
184
|
-
shape: {
|
|
185
|
-
// The ingress `table` param carries the unique `shapeKey` — the proxy resolves the shape by it and
|
|
186
|
-
// maps it to the physical Electric table on egress (so a read projection and its owner, which share
|
|
187
|
-
// a physical table, stay distinguishable). `table` below is the LOCAL PGlite apply target.
|
|
188
|
-
url: buildShapeUrl(input.electricUrl, input.shapeKey),
|
|
189
|
-
},
|
|
190
|
-
table: input.tableName,
|
|
191
|
-
...(input.schema !== undefined ? { schema: input.schema } : {}),
|
|
192
|
-
primaryKey: [...input.primaryKey],
|
|
193
|
-
shapeKey: input.shapeKey,
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
export function buildConfiguredShapeSpecs(input: SyncConfigInput): ConfiguredShapeSyncSpec[] {
|
|
198
|
-
return Object.entries(input.tables)
|
|
199
|
-
.filter(([, table]) => table.mode !== "writeonly")
|
|
200
|
-
.map(([key, table]) => buildConfiguredShapeSpec(input.electricUrl, input.localSchema, key, table));
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* One consistency group's runtime: its specs, the subscription timing its members agree on, and its
|
|
205
|
-
* live stream once started (`null` while a `lazy` group is still held). `startPromise` makes start
|
|
206
|
-
* single-flight so concurrent on-demand triggers share one subscription.
|
|
207
|
-
*/
|
|
208
|
-
interface GroupRuntime {
|
|
209
|
-
groupKey: string;
|
|
210
|
-
specs: ConfiguredShapeSyncSpec[];
|
|
211
|
-
subscription: SubscriptionTiming;
|
|
212
|
-
retention: Retention;
|
|
213
|
-
result: ShapeSyncResult | null;
|
|
214
|
-
startPromise: Promise<void> | null;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
export async function startConfiguredSync(
|
|
218
|
-
pg: SyncEnginePGlite,
|
|
219
|
-
input: StartConfiguredSyncOptions,
|
|
220
|
-
): Promise<StartConfiguredSyncResult> {
|
|
221
|
-
const specs = buildConfiguredShapeSpecs(input.syncConfig);
|
|
222
|
-
|
|
223
|
-
// Bucket specs into consistency groups (ADR-0009 decision 2). Each group is one MultiShapeStream
|
|
224
|
-
// committed atomically; an ungrouped table is its own singleton group keyed by its shapeKey. A group
|
|
225
|
-
// carries the subscription timing its members agree on (ADR-0021; registry validation guarantees
|
|
226
|
-
// agreement, so the first member's value is the group's): `eager` groups start at boot, `lazy` groups
|
|
227
|
-
// are held until ensureGroupStarted (the on-demand / live-query interception seam).
|
|
228
|
-
const groups = new Map<string, GroupRuntime>();
|
|
229
|
-
const groupKeyByTable = new Map<string, string>();
|
|
230
|
-
for (const spec of specs) {
|
|
231
|
-
const groupKey = groupSubscriptionKey(spec);
|
|
232
|
-
groupKeyByTable.set(spec.key, groupKey);
|
|
233
|
-
const existing = groups.get(groupKey);
|
|
234
|
-
if (existing) {
|
|
235
|
-
existing.specs.push(spec);
|
|
236
|
-
} else {
|
|
237
|
-
groups.set(groupKey, {
|
|
238
|
-
groupKey,
|
|
239
|
-
specs: [spec],
|
|
240
|
-
subscription: spec.subscription ?? "eager",
|
|
241
|
-
retention: spec.retention ?? "persistent",
|
|
242
|
-
result: null,
|
|
243
|
-
startPromise: null,
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// Per-group readiness (ADR-0032 decision 6): one deferred per group, created up front so a caller can
|
|
249
|
-
// await ANY group — eager or still-dormant lazy — before it has started. Resolved once (idempotent) the
|
|
250
|
-
// moment the group reports up-to-date; a never-activated lazy group's promise simply stays pending.
|
|
251
|
-
interface GroupReadyDeferred {
|
|
252
|
-
promise: Promise<void>;
|
|
253
|
-
resolve: () => void;
|
|
254
|
-
ready: boolean;
|
|
255
|
-
}
|
|
256
|
-
const groupReadyState = new Map<string, GroupReadyDeferred>();
|
|
257
|
-
for (const groupKey of groups.keys()) {
|
|
258
|
-
let resolve!: () => void;
|
|
259
|
-
const promise = new Promise<void>((r) => {
|
|
260
|
-
resolve = r;
|
|
261
|
-
});
|
|
262
|
-
groupReadyState.set(groupKey, { promise, resolve, ready: false });
|
|
263
|
-
}
|
|
264
|
-
const markGroupReady = (groupKey: string) => {
|
|
265
|
-
const state = groupReadyState.get(groupKey);
|
|
266
|
-
if (!state || state.ready) return;
|
|
267
|
-
state.ready = true;
|
|
268
|
-
state.resolve();
|
|
269
|
-
input.onGroupReady?.(groupKey);
|
|
270
|
-
};
|
|
271
|
-
|
|
272
|
-
// A `lazy` group activated on a previous boot (ADR-0021 §2 `lazy + persistent` promotion) is treated
|
|
273
|
-
// as eager this boot: its activation is permanent, so it joins the boot set and resumes like any durable
|
|
274
|
-
// table — no per-session re-evaluation, no half-lazy.
|
|
275
|
-
const promotedGroups = input.promotedGroups ?? new Set<string>();
|
|
276
|
-
const isEagerAtBoot = (group: GroupRuntime) => group.subscription !== "lazy" || promotedGroups.has(group.groupKey);
|
|
277
|
-
|
|
278
|
-
// Boot readiness (`onInitialSync`) waits only for the boot (eager + promoted) groups to catch up; a lazy
|
|
279
|
-
// group started later via ensureGroupStarted signals its members' `onTableInitialSync` but never the gate.
|
|
280
|
-
const eagerGroups = [...groups.values()].filter(isEagerAtBoot);
|
|
281
|
-
let pendingBootGroups = eagerGroups.length;
|
|
282
|
-
let bootSignalled = false;
|
|
283
|
-
const signalBootIfReady = () => {
|
|
284
|
-
if (!bootSignalled && pendingBootGroups <= 0) {
|
|
285
|
-
bootSignalled = true;
|
|
286
|
-
input.onInitialSync?.();
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
// Start one group's stream, single-flight: a started group resolves immediately; an in-flight start
|
|
291
|
-
// is shared. `countsTowardBoot` is true only for the eager boot starts.
|
|
292
|
-
const startGroup = (group: GroupRuntime, countsTowardBoot: boolean): Promise<void> => {
|
|
293
|
-
if (group.result) {
|
|
294
|
-
return Promise.resolve();
|
|
295
|
-
}
|
|
296
|
-
if (group.startPromise) {
|
|
297
|
-
return group.startPromise;
|
|
298
|
-
}
|
|
299
|
-
// Boot observability (ADR-0034): open an accumulator for a BOOT group only (eager + promoted); an
|
|
300
|
-
// on-demand lazy start (`countsTowardBoot === false`) gets none, so it never enters the report.
|
|
301
|
-
const bootStamp: GroupBootStamp | undefined =
|
|
302
|
-
countsTowardBoot && input.bootCollector
|
|
303
|
-
? input.bootCollector.beginGroup(group.groupKey, group.specs.length)
|
|
304
|
-
: undefined;
|
|
305
|
-
group.startPromise = startGroupSync(pg, {
|
|
306
|
-
groupKey: group.groupKey,
|
|
307
|
-
specs: group.specs,
|
|
308
|
-
registry: input.registry,
|
|
309
|
-
// ADR-0042: an ephemeral group's cursor + tags are session-scoped (stored in `pg_temp`), so a warm
|
|
310
|
-
// engine restart re-streams the shape from scratch rather than resuming a stale durable cursor over
|
|
311
|
-
// the recreated-empty TEMP cluster. The engine learns only this one storage-scope bit.
|
|
312
|
-
...(group.retention === "ephemeral" ? { sessionScoped: true } : {}),
|
|
313
|
-
...(bootStamp ? { bootStamp } : {}),
|
|
314
|
-
// The prefetch overlap (ADR-0032 S4) applies ONLY to the eager BOOT starts: a fresh store's eager
|
|
315
|
-
// groups are genuinely new, so buffering their catch-up behind the commit gate is safe. An on-demand
|
|
316
|
-
// `lazy` start happens post-boot on an already-provisioned store (which may even be RESUMING persisted
|
|
317
|
-
// subscription state), so it must take the exact sequential path — never the fresh-store overlap.
|
|
318
|
-
...(countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {}),
|
|
319
|
-
...(input.shapeHeaders ? { headers: input.shapeHeaders } : {}),
|
|
320
|
-
...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),
|
|
321
|
-
...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),
|
|
322
|
-
...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),
|
|
323
|
-
...(input.onReadStreamStalled ? { onReadStreamStalled: input.onReadStreamStalled } : {}),
|
|
324
|
-
...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),
|
|
325
|
-
onGroupInitialSync: () => {
|
|
326
|
-
// The group is up-to-date as a unit; signal each member table, mark the group ready (per-group
|
|
327
|
-
// readiness, ADR-0032 decision 6), then (for an eager group only) advance the boot gate once
|
|
328
|
-
// every eager group is caught up.
|
|
329
|
-
for (const spec of group.specs) {
|
|
330
|
-
input.onTableInitialSync?.(spec.key);
|
|
331
|
-
}
|
|
332
|
-
// Boot observability (ADR-0034): stamp readyAtMs and freeze the accumulator at the group's ready edge,
|
|
333
|
-
// so later live traffic never mutates a finalized report.
|
|
334
|
-
bootStamp?.markReady();
|
|
335
|
-
markGroupReady(group.groupKey);
|
|
336
|
-
if (countsTowardBoot) {
|
|
337
|
-
pendingBootGroups -= 1;
|
|
338
|
-
signalBootIfReady();
|
|
339
|
-
}
|
|
340
|
-
},
|
|
341
|
-
}).then((result) => {
|
|
342
|
-
group.result = result;
|
|
343
|
-
// A `persistent` `lazy` group activated on demand (not a boot start) persists its activation, so the
|
|
344
|
-
// next boot promotes it to eager (ADR-0021 §2). `ephemeral` activation is session-scoped — never persisted.
|
|
345
|
-
if (!countsTowardBoot && group.subscription === "lazy" && group.retention === "persistent") {
|
|
346
|
-
input.onLazyActivated?.(group.groupKey);
|
|
347
|
-
}
|
|
348
|
-
});
|
|
349
|
-
return group.startPromise;
|
|
350
|
-
};
|
|
351
|
-
|
|
352
|
-
// Each member table exposes a per-table view backed by its group's runtime: up-to-date exactly when
|
|
353
|
-
// the group is (false until a lazy group is started), and unsubscribing it tears down the group.
|
|
354
|
-
const tables: Record<string, ShapeSyncResult> = {};
|
|
355
|
-
for (const [tableKey, groupKey] of groupKeyByTable) {
|
|
356
|
-
const group = groups.get(groupKey)!;
|
|
357
|
-
tables[tableKey] = {
|
|
358
|
-
unsubscribe: () => group.result?.unsubscribe(),
|
|
359
|
-
get isUpToDate() {
|
|
360
|
-
return group.result?.isUpToDate ?? false;
|
|
361
|
-
},
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// Start the eager groups at boot; lazy groups wait for ensureGroupStarted. `signalBootIfReady` after
|
|
366
|
-
// the await covers a config with no eager groups (boot is trivially complete).
|
|
367
|
-
await Promise.all(eagerGroups.map((group) => startGroup(group, true)));
|
|
368
|
-
signalBootIfReady();
|
|
369
|
-
|
|
370
|
-
return {
|
|
371
|
-
unsubscribe: () => {
|
|
372
|
-
// Unsubscribe per group (not per table) so a multi-table group's stream is torn down once.
|
|
373
|
-
for (const group of groups.values()) {
|
|
374
|
-
group.result?.unsubscribe();
|
|
375
|
-
}
|
|
376
|
-
},
|
|
377
|
-
tables,
|
|
378
|
-
ensureGroupStarted: (groupKey) => {
|
|
379
|
-
const group = groups.get(groupKey);
|
|
380
|
-
return group ? startGroup(group, false) : Promise.resolve();
|
|
381
|
-
},
|
|
382
|
-
stopGroup: (groupKey) => {
|
|
383
|
-
const group = groups.get(groupKey);
|
|
384
|
-
if (!group) return;
|
|
385
|
-
// Tear down the live stream and clear the runtime so the group is dormant again: `isTableStarted`
|
|
386
|
-
// reports false and `ensureGroupStarted` re-runs `startGroupSync` (its `group.result`/`startPromise`
|
|
387
|
-
// short-circuits no longer apply) on the next reference.
|
|
388
|
-
group.result?.unsubscribe();
|
|
389
|
-
group.result = null;
|
|
390
|
-
group.startPromise = null;
|
|
391
|
-
// Return the group's readiness to pending: a stopped group is dormant again, so `groupReady` for a
|
|
392
|
-
// later re-activation must re-await its fresh catch-up rather than resolve on the stale deferred.
|
|
393
|
-
if (groupReadyState.get(groupKey)?.ready) {
|
|
394
|
-
let resolve!: () => void;
|
|
395
|
-
const promise = new Promise<void>((r) => {
|
|
396
|
-
resolve = r;
|
|
397
|
-
});
|
|
398
|
-
groupReadyState.set(groupKey, { promise, resolve, ready: false });
|
|
399
|
-
}
|
|
400
|
-
},
|
|
401
|
-
groupKeyForTable: (tableKey) => groupKeyByTable.get(tableKey),
|
|
402
|
-
isTableStarted: (tableKey) => {
|
|
403
|
-
const groupKey = groupKeyByTable.get(tableKey);
|
|
404
|
-
if (groupKey == null) return false;
|
|
405
|
-
return groups.get(groupKey)?.result != null;
|
|
406
|
-
},
|
|
407
|
-
// An unknown group key has nothing to await, so its readiness resolves immediately (never blocks).
|
|
408
|
-
groupReady: (groupKey) => groupReadyState.get(groupKey)?.promise ?? Promise.resolve(),
|
|
409
|
-
isGroupReady: (groupKey) => groupReadyState.get(groupKey)?.ready ?? true,
|
|
410
|
-
groupKeys: () => [...groups.keys()],
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
interface StartGroupSyncOptions {
|
|
415
|
-
groupKey: string;
|
|
416
|
-
specs: ConfiguredShapeSyncSpec[];
|
|
417
|
-
registry: SyncTableRegistry;
|
|
418
|
-
/**
|
|
419
|
-
* ADR-0042: the group's retention is `ephemeral`, so its sync bookkeeping (cursor + tags) is session-
|
|
420
|
-
* scoped — the engine stores it in `pg_temp` relations that die with the engine. Forwarded straight to
|
|
421
|
-
* the engine's `syncShapesToTables`; absent/`false` for a persistent group (byte-identical storage).
|
|
422
|
-
*/
|
|
423
|
-
sessionScoped?: boolean;
|
|
424
|
-
headers?: ExternalHeadersRecord;
|
|
425
|
-
/** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */
|
|
426
|
-
dbReady?: Promise<void>;
|
|
427
|
-
/** Boot observability (ADR-0034): the group's accumulator, stamped by the engine on delivery/apply. */
|
|
428
|
-
bootStamp?: GroupBootStamp;
|
|
429
|
-
onGroupInitialSync?: () => void;
|
|
430
|
-
onSyncError?: (error: Error) => void;
|
|
431
|
-
onAuthError?: () => void;
|
|
432
|
-
onReadStreamError?: (error: Error) => void;
|
|
433
|
-
/** A failed fetch ATTEMPT inside Electric's backoff loop; see {@link StartConfiguredSyncOptions.onReadStreamStalled}. */
|
|
434
|
-
onReadStreamStalled?: () => void;
|
|
435
|
-
onSyncActivity?: () => void;
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* Sync one consistency group on a single `MultiShapeStream` (ADR-0009 decision 2). All member
|
|
440
|
-
* shapes share the group's subscription key and commit atomically at a shared LSN frontier; each
|
|
441
|
-
* shape keeps its own apply strategy and column types (resolved per-shape inside the engine).
|
|
442
|
-
*/
|
|
443
|
-
export async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSyncOptions) {
|
|
444
|
-
const shapeHeaders = input.headers && Object.keys(input.headers).length > 0 ? input.headers : undefined;
|
|
445
|
-
|
|
446
|
-
// The per-shape onError owns read-path auth recovery (ADR-0013 Phase 2: a 401/403 retries with a
|
|
447
|
-
// fresh token) AND read-stream error surfacing (#4: a non-auth error moves the runtime to
|
|
448
|
-
// `degraded`, retrying transient 5xx/429/network and stopping a structural 4xx).
|
|
449
|
-
const onError = createShapeErrorHandler({
|
|
450
|
-
...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),
|
|
451
|
-
...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),
|
|
452
|
-
});
|
|
453
|
-
|
|
454
|
-
// The failed-attempt probe is `onError`'s complement and the reason it exists: `onError` sees only the
|
|
455
|
-
// failures that ESCAPE Electric's retry wrapper, which a network outage never does — it is retried in
|
|
456
|
-
// there forever (board ADR-0010). The two PARTITION the failure space; neither masks the other. One probe
|
|
457
|
-
// per shape — each classifies its own in-flight request — and none at all when no consumer wants the
|
|
458
|
-
// signal, so the off-path keeps Electric's untouched fetch/backoff wiring.
|
|
459
|
-
const onReadStreamStalled = input.onReadStreamStalled;
|
|
460
|
-
|
|
461
|
-
const shapes = Object.fromEntries(
|
|
462
|
-
input.specs.map((spec) => {
|
|
463
|
-
const stallProbe = onReadStreamStalled ? createReadStreamStallProbe({ onStalled: onReadStreamStalled }) : null;
|
|
464
|
-
return [
|
|
465
|
-
spec.key,
|
|
466
|
-
{
|
|
467
|
-
shape: {
|
|
468
|
-
// Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).
|
|
469
|
-
url: buildShapeUrl(spec.electricUrl, spec.shapeKey),
|
|
470
|
-
...(shapeHeaders ? { headers: shapeHeaders } : {}),
|
|
471
|
-
onError,
|
|
472
|
-
...(stallProbe ? { backoffOptions: stallProbe.backoffOptions, fetchClient: stallProbe.fetchClient } : {}),
|
|
473
|
-
},
|
|
474
|
-
// ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply
|
|
475
|
-
// target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The
|
|
476
|
-
// `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.
|
|
477
|
-
tableKey: spec.key,
|
|
478
|
-
},
|
|
479
|
-
];
|
|
480
|
-
}),
|
|
481
|
-
);
|
|
482
|
-
|
|
483
|
-
return getElectricNamespace(pg).syncShapesToTables({
|
|
484
|
-
key: input.groupKey,
|
|
485
|
-
registry: input.registry,
|
|
486
|
-
shapes,
|
|
487
|
-
...(input.sessionScoped ? { sessionScoped: input.sessionScoped } : {}),
|
|
488
|
-
...(input.dbReady ? { dbReady: input.dbReady } : {}),
|
|
489
|
-
...(input.bootStamp ? { bootStamp: input.bootStamp } : {}),
|
|
490
|
-
...(input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {}),
|
|
491
|
-
...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),
|
|
492
|
-
...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),
|
|
493
|
-
});
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
function getElectricNamespace(pg: SyncEnginePGlite) {
|
|
497
|
-
return pg.electric;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
function buildConfiguredShapeSpec(
|
|
501
|
-
electricUrl: string,
|
|
502
|
-
localSchema: string | undefined,
|
|
503
|
-
key: string,
|
|
504
|
-
table: TableSpecInput,
|
|
505
|
-
): ConfiguredShapeSyncSpec {
|
|
506
|
-
if (table.shape === undefined) {
|
|
507
|
-
throw new Error(`shape is required for synced table ${key}`);
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
return {
|
|
511
|
-
key,
|
|
512
|
-
electricUrl,
|
|
513
|
-
tableName: table.clientProjection?.syncedTable ?? table.shape.tableName,
|
|
514
|
-
// ADR-0021 §3: an ephemeral table's cluster is `TEMP` (bare names in `pg_temp`), so the row-applier
|
|
515
|
-
// must target the unqualified name (resolved via search_path) — omit the schema for it.
|
|
516
|
-
...(localSchema && table.retention !== "ephemeral" ? { schema: localSchema } : {}),
|
|
517
|
-
shapeKey: table.shape.shapeKey,
|
|
518
|
-
primaryKey: [...(table.clientProjection?.localPrimaryKey?.columns ?? table.primaryKey.columns)],
|
|
519
|
-
electricTable: table.shape.electricTable ?? table.shape.tableName,
|
|
520
|
-
...(table.consistencyGroup ? { consistencyGroup: table.consistencyGroup } : {}),
|
|
521
|
-
...(table.subscription ? { subscription: table.subscription } : {}),
|
|
522
|
-
...(table.retention ? { retention: table.retention } : {}),
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
/**
|
|
527
|
-
* The subscription key for a spec's consistency group (ADR-0009 decision 2): the explicit
|
|
528
|
-
* `consistencyGroup` when set, else the table's own `shapeKey` (a singleton group). One persisted
|
|
529
|
-
* subscription-state row exists per group key, so subscription reset enumerates these.
|
|
530
|
-
*/
|
|
531
|
-
export function groupSubscriptionKey(spec: Pick<ConfiguredShapeSyncSpec, "consistencyGroup" | "shapeKey">): string {
|
|
532
|
-
return spec.consistencyGroup ?? spec.shapeKey;
|
|
533
|
-
}
|