@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.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
@@ -0,0 +1,353 @@
1
+ import type { PredicateValue } from "@pgxsinkit/contracts";
2
+
3
+ import type { ConvergenceBarrier } from "./sync-engine";
4
+
5
+ /**
6
+ * One shape the client wants to follow — by declared identity, and nothing else.
7
+ *
8
+ * No scope, deliberately (ADR-0055 decision 6). A shared-tier shape comes back as one grant per
9
+ * scope the subject holds, expanded by the control plane, which is the only side that knows the
10
+ * answer. So K requests can return more than K streams, and a client that tracks them by shapeKey
11
+ * alone will lose all but one.
12
+ */
13
+ export interface ShapeSubscriptionRequest {
14
+ shapeKey: string;
15
+ }
16
+
17
+ /** A subscription the control plane granted. */
18
+ export interface GrantedStream {
19
+ shapeKey: string;
20
+ scope?: readonly PredicateValue[];
21
+ shapeId: string;
22
+ /** The durable-streams path, relative to the edge's stream route. */
23
+ streamPath: string;
24
+ /** The absolute URL to read it from, through the edge. */
25
+ streamUrl: string;
26
+ }
27
+
28
+ /** A subscription refused, or later revoked, with why. */
29
+ export interface RefusedStream {
30
+ shapeKey: string;
31
+ scope?: readonly PredicateValue[];
32
+ reason: string;
33
+ }
34
+
35
+ /**
36
+ * A control-plane call that did not return 2xx, carrying the status so a caller can tell an AUTH
37
+ * failure from an outage.
38
+ *
39
+ * That distinction is the whole reason this is a class rather than a bare `Error`. A 401 means the
40
+ * subject's own credential is stale and an app can fix it by prompting for re-login (ADR-0013); a
41
+ * 503 means the engine is unreachable and only time fixes it. Both retry, but only one of them is
42
+ * worth telling the user about.
43
+ */
44
+ export class ControlPlaneError extends Error {
45
+ readonly status: number;
46
+ readonly path: string;
47
+ readonly body: string;
48
+
49
+ constructor(status: number, path: string, body: string) {
50
+ super(`[pgxsinkit] control plane ${path} → ${status}: ${body}`);
51
+ this.name = "ControlPlaneError";
52
+ this.status = status;
53
+ this.path = path;
54
+ this.body = body;
55
+ }
56
+
57
+ /** Whether this is the subject's credential failing, rather than the deployment. */
58
+ get isAuthFailure(): boolean {
59
+ return this.status === 401 || this.status === 403;
60
+ }
61
+ }
62
+
63
+ export interface SubscriptionClientOptions {
64
+ /** Base URL of the control plane — the pgxsinkit server. */
65
+ controlPlaneUrl: string;
66
+ /** Base URL the edge serves streams from. `streamPath` is appended to it. */
67
+ streamBaseUrl: string;
68
+ /**
69
+ * The caller's own auth headers, resolved per request.
70
+ *
71
+ * The SAME adapter the write path uses (ADR-0003): read and write authorization must not diverge,
72
+ * and a JWT that refreshed for one has refreshed for both.
73
+ */
74
+ authHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
75
+ /**
76
+ * Re-mint this many seconds before the token expires. Default 60 — comfortably inside ADR-0055's
77
+ * 5-minute default lifetime, and large enough that a slow round trip does not race the expiry.
78
+ */
79
+ refreshSkewSeconds?: number;
80
+ /** Called when a scope is revoked. The subscriber truncates that scope and unsubscribes. */
81
+ onRevoked?: (revoked: RefusedStream[]) => void;
82
+ /**
83
+ * Aborts in-flight control-plane requests on teardown.
84
+ *
85
+ * Load-bearing rather than tidy: a client stopped while its control plane is unreachable has a
86
+ * subscribe sitting on a TCP connect that can take minutes to fail, and `stop()` waits for the boot
87
+ * tail. Without this, teardown is held hostage by a network that is already gone.
88
+ */
89
+ signal?: AbortSignal;
90
+ fetch?: typeof fetch;
91
+ }
92
+
93
+ export interface SubscriptionSession {
94
+ granted: GrantedStream[];
95
+ refused: RefusedStream[];
96
+ /**
97
+ * The current stream token, re-minted on demand.
98
+ *
99
+ * Hand this straight to the sync engine: it is called per request, so a token that expires mid-poll
100
+ * is replaced without the subscription noticing.
101
+ *
102
+ * It rejects for exactly one reason — every grant was revoked, so there is no bearer left to send.
103
+ * A control plane that could not be reached is NOT that reason: see {@link SubscriptionSession.refresh}.
104
+ */
105
+ token: () => Promise<string>;
106
+ /**
107
+ * Force a re-mint now — what a 403 from the edge should trigger. Null when nothing survived.
108
+ *
109
+ * A re-mint that FAILS (the control plane is down, unreachable, or answering 5xx) resolves with the
110
+ * token already held rather than rejecting. This is the ADR-0013 "the deployment being down is not
111
+ * the subject's problem" rule applied at the one place it is easy to get wrong: this promise is
112
+ * awaited inside `@durable-streams/client`'s header thunk, and a rejection there kills the read
113
+ * with no path back — the very silence backlog 0010 is about. The held token is still good for up
114
+ * to `refreshSkewSeconds`, and when it truly lapses the edge answers 403, the stream ends, and the
115
+ * group re-subscribes (`startCircuitsSync`'s `scheduleRestart`) — which is where a 401 surfaces as
116
+ * `onAuthError` and a 503 as a retried subscribe, both of them recoverable and both of them
117
+ * visible.
118
+ */
119
+ refresh: () => Promise<string | null>;
120
+ /**
121
+ * Close the session and hand its engine shape claims back — **promptly, best-effort**.
122
+ *
123
+ * Synchronous and fire-and-forget by design. Every grant this session was given is a named claim on
124
+ * an engine shape (a `POST /shapes` join), and a live claim blocks both dormancy and eviction, so
125
+ * releasing at close is what lets an idle shape be reclaimed now rather than at the end of its lease
126
+ * window.
127
+ *
128
+ * Not reporting whether it landed is a consequence of WHEN this runs, not of a correctness trade.
129
+ * The release is idempotent — each grant names its own claim, so a repeat is the same act once
130
+ * (fork ADR-0008) — but the most common close is a page unload, which cannot await anything or
131
+ * retry anything. So it fires once, silently, and the lease covers the rest: a release lost with the
132
+ * document leaves claims the engine reclaims within its lease window (`leaseSeconds`), because
133
+ * nothing renews them once the session is gone.
134
+ */
135
+ close: () => void;
136
+ }
137
+
138
+ const DEFAULT_REFRESH_SKEW_SECONDS = 60;
139
+
140
+ /**
141
+ * The client's half of the native subscribe path (ADR-0055 decisions 6 and 10).
142
+ *
143
+ * The native path inverts how a client finds a stream. On the Electric path it *constructed* a URL
144
+ * (`electricUrl?table=<shapeKey>`) and the proxy resolved it; here it **asks**, and the control plane
145
+ * answers with the streams the subject may actually read. That inversion is what removes shape
146
+ * selection from the wire entirely — there is no client-supplied `where` or `table` left to discard.
147
+ */
148
+ export async function openSubscriptionSession(
149
+ options: SubscriptionClientOptions,
150
+ requests: readonly ShapeSubscriptionRequest[],
151
+ ): Promise<SubscriptionSession> {
152
+ const doFetch = options.fetch ?? fetch;
153
+ const controlPlane = options.controlPlaneUrl.replace(/\/+$/, "");
154
+ const streamBase = options.streamBaseUrl.replace(/\/+$/, "");
155
+ const skew = options.refreshSkewSeconds ?? DEFAULT_REFRESH_SKEW_SECONDS;
156
+
157
+ let currentToken: string | null = null;
158
+ let expiresAt = 0;
159
+ let inFlight: Promise<string | null> | null = null;
160
+ let closed = false;
161
+ /**
162
+ * The token the SUBSCRIBE answered with, kept for the whole life of the session.
163
+ *
164
+ * Deliberately not `currentToken`. A re-mint only ever DROPS grants — it re-authorizes each one and
165
+ * omits the ones that no longer pass — so the first token is a superset of every later one, and it
166
+ * is the only record of the full set of engine claims this session acquired. Releasing with the
167
+ * live token after a revocation narrowed it would leak exactly the claims that were revoked, which
168
+ * are the ones nothing else will ever come back for. The release route verifies with `allowExpired`
169
+ * precisely so this stays usable at close, long past its TTL.
170
+ */
171
+ let initialToken: string | null = null;
172
+ let releaseSent = false;
173
+
174
+ async function post(path: string, body: unknown): Promise<Record<string, unknown>> {
175
+ const headers = new Headers(await (options.authHeaders?.() ?? {}));
176
+ headers.set("content-type", "application/json");
177
+ const response = await doFetch(`${controlPlane}${path}`, {
178
+ method: "POST",
179
+ headers,
180
+ body: JSON.stringify(body),
181
+ ...(options.signal ? { signal: options.signal } : {}),
182
+ });
183
+ if (!response.ok) {
184
+ throw new ControlPlaneError(response.status, path, await response.text());
185
+ }
186
+ return (await response.json()) as Record<string, unknown>;
187
+ }
188
+
189
+ const result = await post("/sync/v1/subscribe", { subscriptions: requests });
190
+ const grantedRaw = (result["granted"] ?? []) as Array<Record<string, unknown>>;
191
+ const refused = (result["denied"] ?? []) as RefusedStream[];
192
+
193
+ currentToken = (result["token"] as string | undefined) ?? null;
194
+ initialToken = currentToken;
195
+ expiresAt = (result["expiresAt"] as number | undefined) ?? 0;
196
+
197
+ const granted: GrantedStream[] = grantedRaw.map((entry) => ({
198
+ shapeKey: entry["shapeKey"] as string,
199
+ ...(entry["scope"] !== undefined ? { scope: entry["scope"] as readonly PredicateValue[] } : {}),
200
+ shapeId: entry["shapeId"] as string,
201
+ streamPath: entry["streamPath"] as string,
202
+ streamUrl: `${streamBase}/${String(entry["streamPath"]).replace(/^\/+/, "")}`,
203
+ }));
204
+
205
+ /**
206
+ * Re-mint, single-flight.
207
+ *
208
+ * K subscriptions share one token, so K concurrent polls hitting expiry at once would otherwise
209
+ * fire K refreshes for the same window — the exact fan-out ADR-0055 batches the token to avoid.
210
+ *
211
+ * A FAILED re-mint keeps the current token and its expiry, and resolves with it. Not leniency:
212
+ * this runs inside the read's header thunk, so rejecting would take the stream down silently and
213
+ * permanently, and it would do so for a condition that is routinely transient — a control plane
214
+ * restarting, a 503 while the entitlement set catches up (which that route answers precisely so a
215
+ * client does NOT clear anything), a laptop between networks. The held token stays valid for up to
216
+ * the refresh skew; past that the edge refuses it, the read ends, and the group's restart path
217
+ * re-subscribes — the loud, recoverable version of the same failure.
218
+ *
219
+ * The expiry is not moved either, so the next {@link token} call asks again: a failing control
220
+ * plane is re-tried once per poll cycle, and the first answer that lands restores the lifecycle
221
+ * without anything having noticed.
222
+ */
223
+ async function refresh(): Promise<string | null> {
224
+ if (closed || currentToken === null) return null;
225
+ if (inFlight) return inFlight;
226
+
227
+ inFlight = (async () => {
228
+ try {
229
+ const refreshed = await post("/sync/v1/refresh", { token: currentToken });
230
+ const revoked = (refreshed["revoked"] ?? []) as RefusedStream[];
231
+ if (revoked.length > 0) options.onRevoked?.(revoked);
232
+
233
+ currentToken = (refreshed["token"] as string | undefined) ?? null;
234
+ expiresAt = (refreshed["expiresAt"] as number | undefined) ?? 0;
235
+ return currentToken;
236
+ } catch {
237
+ // `currentToken`/`expiresAt` deliberately untouched: the answer that would have replaced them
238
+ // never arrived, and the one thing worse than a stale token here is no token at all.
239
+ return currentToken;
240
+ } finally {
241
+ inFlight = null;
242
+ }
243
+ })();
244
+ return inFlight;
245
+ }
246
+
247
+ async function token(): Promise<string> {
248
+ if (currentToken === null) throw new Error("[pgxsinkit] no stream token — nothing was granted");
249
+ // Refresh on the SKEW, not on expiry: a token that expires while a long-poll is in flight would
250
+ // otherwise 403 the poll and cost a round trip to discover what the clock already knew.
251
+ if (Date.now() / 1000 >= expiresAt - skew) {
252
+ const refreshed = await refresh();
253
+ if (refreshed !== null) return refreshed;
254
+ }
255
+ // A refresh that revoked every grant leaves `currentToken` null: the stream-source header thunk
256
+ // needs a usable bearer, and `Bearer null` is not a state — fail here rather than on the wire.
257
+ if (currentToken === null) throw new Error("[pgxsinkit] no stream token — every grant was revoked on refresh");
258
+ return currentToken;
259
+ }
260
+
261
+ /**
262
+ * The one release request, built by hand rather than through {@link post}, for two reasons that are
263
+ * both about it actually leaving the process.
264
+ *
265
+ * NO `options.signal`. Group teardown aborts that controller BEFORE it closes its sessions, so a
266
+ * release riding it would be cancelled in the same tick it was created — the teardown path is
267
+ * exactly the one that most needs the claims back.
268
+ *
269
+ * `keepalive`, so a page unload does not cancel it either: closing a tab is the single most common
270
+ * way a session ends, and a release that dies with the document is the leak this route exists to
271
+ * stop.
272
+ *
273
+ * Errors are SWALLOWED and nothing is retried — because there is nothing here that COULD retry,
274
+ * not because a retry would be unsafe. The release names each claim and is idempotent (fork
275
+ * ADR-0008), so repeating it is harmless; but `close()` is synchronous and its commonest caller is
276
+ * a page unload, which has no future in which to try again and no one left to report to. A release
277
+ * that dies with the document leaves claims the engine reclaims within one lease window, since
278
+ * nothing renews them once the session is gone.
279
+ */
280
+ function sendRelease(releaseToken: string): void {
281
+ void (async () => {
282
+ try {
283
+ const headers = new Headers(await (options.authHeaders?.() ?? {}));
284
+ headers.set("content-type", "application/json");
285
+ await doFetch(`${controlPlane}/sync/v1/release`, {
286
+ method: "POST",
287
+ headers,
288
+ body: JSON.stringify({ token: releaseToken }),
289
+ keepalive: true,
290
+ });
291
+ } catch {
292
+ // Deliberately silent: see above.
293
+ }
294
+ })();
295
+ }
296
+
297
+ return {
298
+ granted,
299
+ refused,
300
+ token,
301
+ refresh,
302
+ close: () => {
303
+ closed = true;
304
+ // A session that was granted nothing holds no claim and has nothing to give back. The
305
+ // `releaseSent` latch makes a second `close()` — a stop racing a teardown, say — a no-op: the
306
+ // server would answer the repeat 200 and change nothing (releases are by claim id and therefore
307
+ // idempotent), so the latch is about not making a request that can only be redundant.
308
+ if (initialToken === null || releaseSent) return;
309
+ releaseSent = true;
310
+ sendRelease(initialToken);
311
+ },
312
+ };
313
+ }
314
+
315
+ /**
316
+ * Read the engine's convergence barrier through the control plane — the `readBarrier` the sync
317
+ * engine takes.
318
+ *
319
+ * An unreachable barrier throws, and the engine treats that as a DELAY rather than a failure
320
+ * (ADR-0056): the group stays on the pre-alignment gate and tries again on the next delivery. So a
321
+ * control plane that is briefly down costs boot latency, not correctness.
322
+ *
323
+ * A body missing a term throws for the same reason and to the same effect. Defaulting the absent
324
+ * field to zero would let a control plane that CANNOT report lost membership effects be read as one
325
+ * reporting none — a guard that cannot trip, which is protection nobody has. Throwing leaves the
326
+ * group on the pre-alignment gate instead: it never aligns against a barrier it cannot read whole.
327
+ */
328
+ export function createBarrierReader(
329
+ options: Pick<SubscriptionClientOptions, "controlPlaneUrl" | "authHeaders" | "signal" | "fetch">,
330
+ ): () => Promise<ConvergenceBarrier> {
331
+ const doFetch = options.fetch ?? fetch;
332
+ const controlPlane = options.controlPlaneUrl.replace(/\/+$/, "");
333
+
334
+ return async () => {
335
+ const headers = new Headers(await (options.authHeaders?.() ?? {}));
336
+ const response = await doFetch(`${controlPlane}/sync/v1/barrier`, {
337
+ headers,
338
+ ...(options.signal ? { signal: options.signal } : {}),
339
+ });
340
+ if (!response.ok) {
341
+ throw new ControlPlaneError(response.status, "/sync/v1/barrier", await response.text());
342
+ }
343
+ const body = (await response.json()) as Partial<ConvergenceBarrier>;
344
+ if (typeof body.pendingFlips !== "number" || typeof body.flipFailures !== "number") {
345
+ throw new Error(
346
+ `[pgxsinkit] the barrier at /sync/v1/barrier answered without \`pendingFlips\`/\`flipFailures\` ` +
347
+ `(${JSON.stringify(body)}). This client aligns only on the whole barrier (ADR-0056 decision 3); a control ` +
348
+ `plane that cannot report lost membership effects is not one this client can align against.`,
349
+ );
350
+ }
351
+ return { pendingFlips: body.pendingFlips, flipFailures: body.flipFailures };
352
+ };
353
+ }