@pgxsinkit/client 0.1.32 → 0.1.40

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