@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
|
@@ -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
|
+
}
|