@pgxsinkit/client 0.5.2 → 0.6.0-rc.2
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/dist/circuits/long-poll.d.ts +76 -0
- package/dist/circuits/long-poll.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +3 -3
- package/dist/circuits/stream-source.d.ts +76 -43
- package/dist/circuits/stream-source.d.ts.map +1 -1
- package/dist/circuits/subscription-client.d.ts +7 -7
- package/dist/circuits/sync-engine.d.ts +1 -1
- package/dist/event-lane.d.ts +2 -2
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +228 -54
- package/dist/index.js.map +15 -13
- package/dist/local-tables.d.ts +511 -482
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/retry-after.d.ts +9 -0
- package/dist/retry-after.d.ts.map +1 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-build.d.ts.map +1 -1
- package/dist/sync/metadata-tables.d.ts +2 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/worker/live-diff.d.ts.map +1 -1
- package/package.json +7 -8
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +6 -6
- package/src/circuits/long-poll.ts +174 -0
- package/src/circuits/shape-group.ts +3 -3
- package/src/circuits/stream-source.ts +226 -99
- package/src/circuits/subscription-client.ts +15 -15
- package/src/circuits/sync-engine.ts +1 -1
- package/src/event-lane.ts +3 -19
- package/src/index.ts +11 -3
- package/src/local-tables.ts +8 -5
- package/src/retry-after.ts +24 -0
- package/src/schema.ts +9 -4
- package/src/store-build.ts +4 -3
- package/src/sync/types.ts +2 -1
- package/src/worker/live-diff.ts +8 -5
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import { stream, type StreamErrorHandler } from "@durable-streams/client";
|
|
2
|
-
|
|
3
1
|
import type { StreamEnvelope } from "@pgxsinkit/contracts";
|
|
4
2
|
|
|
3
|
+
import { parseRetryAfterMs } from "../retry-after";
|
|
4
|
+
import {
|
|
5
|
+
classifyStatus,
|
|
6
|
+
failedRead,
|
|
7
|
+
readRequestUrl,
|
|
8
|
+
readResponse,
|
|
9
|
+
retryDelayMs,
|
|
10
|
+
sleep,
|
|
11
|
+
StreamReadError,
|
|
12
|
+
type ReadPosition,
|
|
13
|
+
type ReadResponse,
|
|
14
|
+
} from "./long-poll";
|
|
15
|
+
|
|
5
16
|
/** The resume position of a fresh subscription — the start of the stream. */
|
|
6
17
|
export const STREAM_START = "-1";
|
|
7
18
|
|
|
@@ -9,13 +20,13 @@ export const STREAM_START = "-1";
|
|
|
9
20
|
export interface StreamBatch {
|
|
10
21
|
envelopes: readonly StreamEnvelope[];
|
|
11
22
|
/**
|
|
12
|
-
* The offset to resume from. Persist it **with** the applied rows in one
|
|
13
|
-
* ahead, a crash loses the envelopes between; persisted behind, they are
|
|
14
|
-
* path is idempotent so the second is survivable and the first is not, which
|
|
15
|
-
* the batch rather than being read off the
|
|
23
|
+
* The offset to resume from after THIS batch. Persist it **with** the applied rows in one
|
|
24
|
+
* transaction: persisted ahead, a crash loses the envelopes between; persisted behind, they are
|
|
25
|
+
* re-applied. The apply path is idempotent so the second is survivable and the first is not, which
|
|
26
|
+
* is why this rides the batch rather than being read off the stream afterwards.
|
|
16
27
|
*/
|
|
17
28
|
offset: string;
|
|
18
|
-
/** Whether the
|
|
29
|
+
/** Whether THIS batch reached the tail of the stream as it stood when the server answered. */
|
|
19
30
|
upToDate: boolean;
|
|
20
31
|
}
|
|
21
32
|
|
|
@@ -29,9 +40,8 @@ export interface StreamSourceOptions {
|
|
|
29
40
|
*
|
|
30
41
|
* A live subscription outlives its token by design — the ADR-0055 default lifetime is five
|
|
31
42
|
* minutes and a subscription runs for hours — so a token frozen at open would 403 the whole
|
|
32
|
-
* stream at the first TTL boundary. This is the ADR-0013 read-path refresh seam
|
|
33
|
-
*
|
|
34
|
-
* afresh per request.
|
|
43
|
+
* stream at the first TTL boundary. This is the ADR-0013 read-path refresh seam. A token that
|
|
44
|
+
* cannot be produced (the thunk throws) ends the read with that error.
|
|
35
45
|
*/
|
|
36
46
|
token: () => string | Promise<string>;
|
|
37
47
|
/**
|
|
@@ -49,18 +59,24 @@ export interface StreamSourceOptions {
|
|
|
49
59
|
}
|
|
50
60
|
|
|
51
61
|
/**
|
|
52
|
-
* The
|
|
62
|
+
* The token-recovery policy as a function of a read error: resolves with the `authorization` header
|
|
63
|
+
* to retry with, or `undefined` when the error must stand.
|
|
64
|
+
*/
|
|
65
|
+
export type StreamErrorHandler = (error: Error) => Promise<{ headers: { authorization: string } } | undefined>;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The token-recovery policy the reader applies to every request: **one re-mint per rejection**.
|
|
53
69
|
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
70
|
+
* On a 401/403 the handler asks `onTokenRejected` for a fresh token and answers with it; if the
|
|
71
|
+
* fresh token is refused too, it answers `undefined` and the error stands. The second consecutive
|
|
72
|
+
* rejection is the answer — the token was refreshed and still refused, so this is a revocation, not
|
|
73
|
+
* an expiry — and retrying past it would turn a revoked entitlement into a hot loop of refused
|
|
74
|
+
* requests. A revocation must instead surface as an error the caller can act on: truncate the scope
|
|
75
|
+
* and unsubscribe (ADR-0055 decision 6).
|
|
59
76
|
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* decision 6) — not as a stream that spins.
|
|
77
|
+
* Stateful and single-shot: one handler re-mints once. The reader makes a new one for each request, so
|
|
78
|
+
* a read that lives for hours can re-mint many times, but no request is retried on a second rejection.
|
|
79
|
+
* Errors that are not 401/403 are not the handler's to recover and answer `undefined`.
|
|
64
80
|
*/
|
|
65
81
|
export function createTokenRecovery(
|
|
66
82
|
onTokenRejected: NonNullable<StreamSourceOptions["onTokenRejected"]>,
|
|
@@ -69,8 +85,6 @@ export function createTokenRecovery(
|
|
|
69
85
|
return async (error: Error & { status?: number }) => {
|
|
70
86
|
const status = error.status;
|
|
71
87
|
if (status !== 401 && status !== 403) return undefined;
|
|
72
|
-
// The second consecutive rejection is the answer: the token was refreshed and still refused, so
|
|
73
|
-
// this is a revocation, not an expiry.
|
|
74
88
|
if (recovering) return undefined;
|
|
75
89
|
|
|
76
90
|
recovering = true;
|
|
@@ -80,112 +94,225 @@ export function createTokenRecovery(
|
|
|
80
94
|
};
|
|
81
95
|
}
|
|
82
96
|
|
|
83
|
-
/** A running subscription.
|
|
97
|
+
/** A running subscription. */
|
|
84
98
|
export interface ShapeStreamSubscription {
|
|
85
|
-
/** Stop reading and release the connection. */
|
|
99
|
+
/** Stop reading: abort the request in flight and release the connection. Reports nothing. */
|
|
86
100
|
close(): void;
|
|
87
101
|
}
|
|
88
102
|
|
|
103
|
+
/** The reader's time and chance, injectable so a test can assert a retry schedule without waiting. */
|
|
104
|
+
export interface ReadInternals {
|
|
105
|
+
/** Wait out a backoff. Must resolve early when `signal` aborts. */
|
|
106
|
+
wait: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
107
|
+
/** The jitter source, uniform on [0, 1). */
|
|
108
|
+
random: () => number;
|
|
109
|
+
}
|
|
110
|
+
|
|
89
111
|
/**
|
|
90
112
|
* Read one Circuits shape stream, yielding envelopes in stream order.
|
|
91
113
|
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
114
|
+
* pgxsinkit's own long-poll reader of the Durable Streams protocol (ADR-0065 decision 6; the wire is
|
|
115
|
+
* `long-poll.ts`). It catches up with plain reads from `offset` (so a catch-up response stays
|
|
116
|
+
* cacheable), and once a response says it is up to date, a live read long-polls the tail, echoing the
|
|
117
|
+
* server's cursor. `live: false` stops at the first up-to-date response instead.
|
|
118
|
+
*
|
|
119
|
+
* Resolves once the first response has arrived, so an immediate failure — a refused token, a stream
|
|
120
|
+
* that does not exist — rejects this call rather than dying on a loop nobody is watching. The first
|
|
121
|
+
* batch is delivered after that, never during the call: a caller that closes its subscription from
|
|
122
|
+
* inside `onBatch` already holds it.
|
|
95
123
|
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
* a lost connection) and RESOLVES on a normal end (`live: false` reaching up-to-date,
|
|
104
|
-
* `Stream-Closed`, or our own {@link ShapeStreamSubscription.close}). So `onEnd(null)` means "this
|
|
105
|
-
* read is over and nothing failed"; `onEnd(error)` is the mid-session reset (ADR-0056 decision 7)
|
|
106
|
-
* that a caller must answer with a re-subscribe.
|
|
124
|
+
* Every successful response is one batch, an empty one included (a long poll that timed out delivers
|
|
125
|
+
* the empty up-to-date batch at the same offset). **Backpressure, one response ahead:** the request
|
|
126
|
+
* for the next response is sent when a batch is handed to `onBatch`, and the request after that not
|
|
127
|
+
* until `onBatch` has settled. So the network wait and the apply overlap instead of adding up, which
|
|
128
|
+
* is worth up to half the time of a catch-up that spans many responses, and a slow apply still
|
|
129
|
+
* throttles the read: at most one response is ever held beyond the one being applied. One request is
|
|
130
|
+
* in flight at a time, which is one connection per stream while it long-polls.
|
|
107
131
|
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
132
|
+
* **Failures, per request:**
|
|
133
|
+
* - 401/403: one immediate retry with a token from `onTokenRejected` ({@link createTokenRecovery}); a
|
|
134
|
+
* second rejection of the same request, or no fresh token, is terminal. Every request of the session
|
|
135
|
+
* gets this, not only the opening one, so a read that lives for hours can re-mint many times, but a
|
|
136
|
+
* refused token never loops.
|
|
137
|
+
* - 429 and every 5xx, and network failures (the request, or its body, cut off): retried with backoff
|
|
138
|
+
* until they succeed or the caller stops the read. A `Retry-After` is a floor under the backoff.
|
|
139
|
+
* - Every other status is terminal, 404 and 410 (the stream was never created, or was retired)
|
|
140
|
+
* included, as is a response that breaks the protocol ({@link readResponse}).
|
|
113
141
|
*
|
|
114
|
-
* The
|
|
115
|
-
*
|
|
116
|
-
*
|
|
142
|
+
* **The end of a read.** `onEnd` is not optional decoration: without it a read that dies mid-session
|
|
143
|
+
* is silent — the rows stay, and nobody re-subscribes. It fires at most once:
|
|
144
|
+
* - `onEnd(null)` after `onBatch` has been handed the batch that ends the read — the up-to-date batch
|
|
145
|
+
* of a `live: false` read, the `Stream-Closed` batch of any read — and has settled on it. A caller
|
|
146
|
+
* may close on `onEnd` without losing that batch.
|
|
147
|
+
* - `onEnd(error)` for a terminal failure after the first response, and for an `onBatch` that throws.
|
|
148
|
+
* This is the mid-session reset (ADR-0056 decision 7) a caller answers with a re-subscribe.
|
|
149
|
+
* - `onEnd(null)` when the caller's `signal` aborts.
|
|
150
|
+
* - Nothing when the caller called {@link ShapeStreamSubscription.close}: a group tearing its streams
|
|
151
|
+
* down would otherwise hear K "the stream ended" reports and try to recover from a stop it ordered.
|
|
152
|
+
* - Nothing for a failure before the first response: that rejects this call instead.
|
|
153
|
+
*
|
|
154
|
+
* The transport only. Everything above it — the fold, apply modes, the boot gate — is the engine's,
|
|
155
|
+
* which is ADR-0009's precedent applied to a new substrate.
|
|
117
156
|
*/
|
|
118
|
-
export
|
|
157
|
+
export function readShapeStream(
|
|
119
158
|
options: StreamSourceOptions,
|
|
120
159
|
onBatch: (batch: StreamBatch) => void | Promise<void>,
|
|
121
160
|
onEnd?: (error: Error | null) => void,
|
|
122
161
|
): Promise<ShapeStreamSubscription> {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
offset: options.offset ?? STREAM_START,
|
|
126
|
-
live: options.live ?? true,
|
|
127
|
-
headers: { authorization: async () => `Bearer ${await options.token()}` },
|
|
128
|
-
...(options.onTokenRejected ? { onError: createTokenRecovery(options.onTokenRejected) } : {}),
|
|
129
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
130
|
-
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
131
|
-
});
|
|
162
|
+
return readShapeStreamWith({}, options, onBatch, onEnd);
|
|
163
|
+
}
|
|
132
164
|
|
|
165
|
+
/** {@link readShapeStream} with its time and chance injected. Not public API. */
|
|
166
|
+
export function readShapeStreamWith(
|
|
167
|
+
internals: Partial<ReadInternals>,
|
|
168
|
+
options: StreamSourceOptions,
|
|
169
|
+
onBatch: (batch: StreamBatch) => void | Promise<void>,
|
|
170
|
+
onEnd?: (error: Error | null) => void,
|
|
171
|
+
): Promise<ShapeStreamSubscription> {
|
|
172
|
+
const wait = internals.wait ?? sleep;
|
|
173
|
+
const random = internals.random ?? Math.random;
|
|
174
|
+
const send: (input: string, init: RequestInit) => Promise<Response> =
|
|
175
|
+
options.fetch ?? ((input, init) => fetch(input, init));
|
|
133
176
|
const live = options.live ?? true;
|
|
134
177
|
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
|
|
138
|
-
|
|
178
|
+
// One controller stops everything in flight — the request, its body, a backoff — whichever of the
|
|
179
|
+
// caller's close() or the caller's signal comes first.
|
|
180
|
+
const stop = new AbortController();
|
|
181
|
+
const signal = stop.signal;
|
|
182
|
+
const forwardAbort = (): void => stop.abort();
|
|
183
|
+
options.signal?.addEventListener("abort", forwardAbort, { once: true });
|
|
184
|
+
if (options.signal?.aborted) stop.abort();
|
|
185
|
+
|
|
139
186
|
let closedByCaller = false;
|
|
140
187
|
let endReported = false;
|
|
141
188
|
const reportEnd = (error: Error | null): void => {
|
|
189
|
+
options.signal?.removeEventListener("abort", forwardAbort);
|
|
142
190
|
if (endReported || closedByCaller) return;
|
|
143
191
|
endReported = true;
|
|
144
192
|
onEnd?.(error);
|
|
145
193
|
};
|
|
146
194
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
void response.closed.then(
|
|
176
|
-
() => {
|
|
177
|
-
// A normal transport close is answered by the terminal batch above, which is already queued
|
|
178
|
-
// for the subscriber. The one normal close with NOTHING queued is the caller's own abort
|
|
179
|
-
// signal, and that one would otherwise wait forever.
|
|
180
|
-
if (options.signal?.aborted) reportEnd(null);
|
|
181
|
-
},
|
|
182
|
-
(error: unknown) => reportEnd(error instanceof Error ? error : new Error(String(error))),
|
|
183
|
-
);
|
|
195
|
+
/**
|
|
196
|
+
* One request, retried until it has an answer the session can use. `null` when the read was stopped
|
|
197
|
+
* while it was in flight; throws when it failed for good.
|
|
198
|
+
*/
|
|
199
|
+
async function request(position: ReadPosition): Promise<ReadResponse | null> {
|
|
200
|
+
const url = readRequestUrl(options.url, position);
|
|
201
|
+
const recover = options.onTokenRejected ? createTokenRecovery(options.onTokenRejected) : null;
|
|
202
|
+
// The header a re-mint answered with. It carries exactly one retry; every other attempt asks the
|
|
203
|
+
// token thunk again, so the session never freezes a token, even one it was just handed.
|
|
204
|
+
let reminted: string | null = null;
|
|
205
|
+
let attempt = 0;
|
|
206
|
+
|
|
207
|
+
for (;;) {
|
|
208
|
+
if (signal.aborted) return null;
|
|
209
|
+
const authorization = reminted ?? `Bearer ${await options.token()}`;
|
|
210
|
+
reminted = null;
|
|
211
|
+
|
|
212
|
+
let response: Response;
|
|
213
|
+
try {
|
|
214
|
+
response = await send(url, { method: "GET", headers: { authorization }, signal });
|
|
215
|
+
if (response.ok) return await readResponse(response, url, position.offset);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (signal.aborted) return null;
|
|
218
|
+
if (error instanceof StreamReadError) throw error;
|
|
219
|
+
// The request or its body never arrived whole: the same read is safe to ask again.
|
|
220
|
+
await wait(retryDelayMs(++attempt, null, random), signal);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
184
223
|
|
|
185
|
-
|
|
224
|
+
const verdict = classifyStatus(response.status);
|
|
225
|
+
if (verdict === "retry") {
|
|
226
|
+
await response.body?.cancel().catch(() => {});
|
|
227
|
+
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), Date.now());
|
|
228
|
+
await wait(retryDelayMs(++attempt, retryAfterMs, random), signal);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const failure = await failedRead(response, url);
|
|
233
|
+
if (verdict === "token-rejected") {
|
|
234
|
+
const retry = await recover?.(failure);
|
|
235
|
+
if (retry) {
|
|
236
|
+
reminted = retry.headers.authorization;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
throw failure;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
let position: ReadPosition = { offset: options.offset ?? STREAM_START, cursor: null, longPoll: false };
|
|
245
|
+
let first: ReadResponse | null = null;
|
|
246
|
+
|
|
247
|
+
const subscription: ShapeStreamSubscription = {
|
|
186
248
|
close: () => {
|
|
187
249
|
closedByCaller = true;
|
|
188
|
-
|
|
250
|
+
options.signal?.removeEventListener("abort", forwardAbort);
|
|
251
|
+
stop.abort();
|
|
189
252
|
},
|
|
190
253
|
};
|
|
254
|
+
|
|
255
|
+
const opened = (async () => {
|
|
256
|
+
try {
|
|
257
|
+
first = await request(position);
|
|
258
|
+
if (first === null) {
|
|
259
|
+
throw new StreamReadError(`[pgxsinkit] stream read of ${options.url} was aborted before its first response`);
|
|
260
|
+
}
|
|
261
|
+
return subscription;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
options.signal?.removeEventListener("abort", forwardAbort);
|
|
264
|
+
throw error;
|
|
265
|
+
}
|
|
266
|
+
})();
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Deliver each batch while the next response is fetched, until the read ends. Resolves with what
|
|
270
|
+
* `onEnd` reports.
|
|
271
|
+
*/
|
|
272
|
+
async function deliver(): Promise<Error | null> {
|
|
273
|
+
let response = first!;
|
|
274
|
+
try {
|
|
275
|
+
for (;;) {
|
|
276
|
+
if (signal.aborted) return null;
|
|
277
|
+
const last = response.closed || (!live && response.upToDate);
|
|
278
|
+
|
|
279
|
+
// One response ahead: asked for now, awaited once this batch is applied. Its failure belongs
|
|
280
|
+
// after this batch in the order of events, so it is held until then rather than thrown here.
|
|
281
|
+
let ahead: Promise<ReadResponse | null> | null = null;
|
|
282
|
+
if (!last) {
|
|
283
|
+
position = {
|
|
284
|
+
offset: response.offset,
|
|
285
|
+
cursor: response.cursor ?? position.cursor,
|
|
286
|
+
longPoll: live && response.upToDate,
|
|
287
|
+
};
|
|
288
|
+
ahead = request(position);
|
|
289
|
+
ahead.catch(() => {});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
await onBatch({ envelopes: response.envelopes, offset: response.offset, upToDate: response.upToDate });
|
|
293
|
+
if (ahead === null) return null;
|
|
294
|
+
|
|
295
|
+
const next = await ahead;
|
|
296
|
+
if (next === null) return null;
|
|
297
|
+
response = next;
|
|
298
|
+
}
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (signal.aborted) return null;
|
|
301
|
+
// A failed apply leaves the request that was sent ahead of it in flight; end it.
|
|
302
|
+
stop.abort();
|
|
303
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Delivery starts one reaction BEHIND the caller's own `await` of the returned promise: reactions
|
|
308
|
+
// run in the order they were registered, the caller's is registered when this function returns,
|
|
309
|
+
// and the extra `then` puts ours after it. So the caller holds its subscription before the first
|
|
310
|
+
// `onBatch`, and `opened` must be returned as it is, not wrapped by an `async` function.
|
|
311
|
+
void opened
|
|
312
|
+
.then(() => undefined)
|
|
313
|
+
.then(
|
|
314
|
+
async () => reportEnd(await deliver()),
|
|
315
|
+
() => undefined,
|
|
316
|
+
);
|
|
317
|
+
return opened;
|
|
191
318
|
}
|
|
@@ -108,13 +108,13 @@ export interface SubscriptionSession {
|
|
|
108
108
|
*
|
|
109
109
|
* A re-mint that FAILS (the control plane is down, unreachable, or answering 5xx) resolves with the
|
|
110
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:
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
* `
|
|
117
|
-
* visible.
|
|
111
|
+
* the subject's problem" rule applied at the one place it is easy to get wrong: the stream reader
|
|
112
|
+
* awaits this promise (through `token` and `onTokenRejected`) before its requests, and a rejection
|
|
113
|
+
* there ends the read — every stream of the group then re-subscribes over a blip the held token
|
|
114
|
+
* would have ridden out. The held token is still good for up to `refreshSkewSeconds`, and when it
|
|
115
|
+
* truly lapses the edge answers 403, the stream ends, and the group re-subscribes
|
|
116
|
+
* (`startCircuitsSync`'s `scheduleRestart`) — which is where a 401 surfaces as `onAuthError` and a
|
|
117
|
+
* 503 as a retried subscribe, both of them recoverable and both of them visible.
|
|
118
118
|
*/
|
|
119
119
|
refresh: () => Promise<string | null>;
|
|
120
120
|
/**
|
|
@@ -209,12 +209,12 @@ export async function openSubscriptionSession(
|
|
|
209
209
|
* fire K refreshes for the same window — the exact fan-out ADR-0055 batches the token to avoid.
|
|
210
210
|
*
|
|
211
211
|
* A FAILED re-mint keeps the current token and its expiry, and resolves with it. Not leniency:
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
* restarting, a 503 while the entitlement set catches up (which that
|
|
215
|
-
* client does NOT clear anything), a laptop between networks. The held
|
|
216
|
-
* the refresh skew; past that the edge refuses it, the read ends, and
|
|
217
|
-
* re-subscribes — the loud, recoverable version of the same failure.
|
|
212
|
+
* the stream reader awaits it before its requests, so rejecting would end the read and send the
|
|
213
|
+
* whole group through a re-subscribe, and it would do so for a condition that is routinely
|
|
214
|
+
* transient — a control plane restarting, a 503 while the entitlement set catches up (which that
|
|
215
|
+
* route answers precisely so a client does NOT clear anything), a laptop between networks. The held
|
|
216
|
+
* token stays valid for up to the refresh skew; past that the edge refuses it, the read ends, and
|
|
217
|
+
* the group's restart path re-subscribes — the loud, recoverable version of the same failure.
|
|
218
218
|
*
|
|
219
219
|
* The expiry is not moved either, so the next {@link token} call asks again: a failing control
|
|
220
220
|
* plane is re-tried once per poll cycle, and the first answer that lands restores the lifecycle
|
|
@@ -252,8 +252,8 @@ export async function openSubscriptionSession(
|
|
|
252
252
|
const refreshed = await refresh();
|
|
253
253
|
if (refreshed !== null) return refreshed;
|
|
254
254
|
}
|
|
255
|
-
// A refresh that revoked every grant leaves `currentToken` null: the stream
|
|
256
|
-
//
|
|
255
|
+
// A refresh that revoked every grant leaves `currentToken` null: the stream reader needs a usable
|
|
256
|
+
// bearer, and `Bearer null` is not a state — fail here rather than on the wire.
|
|
257
257
|
if (currentToken === null) throw new Error("[pgxsinkit] no stream token — every grant was revoked on refresh");
|
|
258
258
|
return currentToken;
|
|
259
259
|
}
|
|
@@ -38,7 +38,7 @@ import type { StreamSourceOptions } from "./stream-source";
|
|
|
38
38
|
*
|
|
39
39
|
* `flipFailures` is the term the others cannot express. A flip batch abandoned after its retries
|
|
40
40
|
* carried membership effects that are **gone**, not late: the engine keeps that batch's
|
|
41
|
-
* `pendingFlips` count held forever and latches itself degraded — 503 on `/
|
|
41
|
+
* `pendingFlips` count held forever and latches itself degraded — 503 on `/ready` and on every
|
|
42
42
|
* membership-bearing route, subquery streams reaped, recovery only by operator restart. The waiting
|
|
43
43
|
* terms are therefore honest but permanently unsatisfied, which is indistinguishable from a slow
|
|
44
44
|
* engine; this term is how a client tells the two apart.
|
package/src/event-lane.ts
CHANGED
|
@@ -47,6 +47,9 @@ import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
|
|
|
47
47
|
|
|
48
48
|
import { syncDebug } from "./debug";
|
|
49
49
|
import { getOutboxTable } from "./local-tables";
|
|
50
|
+
import { parseRetryAfterMs } from "./retry-after";
|
|
51
|
+
|
|
52
|
+
export { parseRetryAfterMs };
|
|
50
53
|
|
|
51
54
|
/** The raw local-store seam the Event lane executes through (structurally pgwasm; mirrors `MutationDb`). */
|
|
52
55
|
export interface EventLaneDb {
|
|
@@ -375,25 +378,6 @@ export function classifyEventBatchFailure(httpStatus: number | null | undefined)
|
|
|
375
378
|
return httpStatus != null && AUTH_STATUSES.has(httpStatus) ? "auth" : "retryable";
|
|
376
379
|
}
|
|
377
380
|
|
|
378
|
-
/** Parse a `Retry-After` header (delta-seconds or HTTP-date) into ms, or null when absent/unreadable. */
|
|
379
|
-
export function parseRetryAfterMs(headerValue: string | null | undefined, nowMs: number): number | null {
|
|
380
|
-
if (headerValue == null) {
|
|
381
|
-
return null;
|
|
382
|
-
}
|
|
383
|
-
const trimmed = headerValue.trim();
|
|
384
|
-
if (trimmed === "") {
|
|
385
|
-
return null;
|
|
386
|
-
}
|
|
387
|
-
if (/^\d+$/.test(trimmed)) {
|
|
388
|
-
return Number(trimmed) * 1000;
|
|
389
|
-
}
|
|
390
|
-
const parsedDate = Date.parse(trimmed);
|
|
391
|
-
if (Number.isNaN(parsedDate)) {
|
|
392
|
-
return null;
|
|
393
|
-
}
|
|
394
|
-
return Math.max(0, parsedDate - nowMs);
|
|
395
|
-
}
|
|
396
|
-
|
|
397
381
|
/**
|
|
398
382
|
* Jittered exponential backoff with a ceiling — equal jitter around the doubling ceiling, exactly the
|
|
399
383
|
* mutation path's congestion policy (half the ceiling plus a random share of the other half), so a fleet
|
package/src/index.ts
CHANGED
|
@@ -340,10 +340,15 @@ export {
|
|
|
340
340
|
serializeCopyValue,
|
|
341
341
|
} from "./sync/copy";
|
|
342
342
|
|
|
343
|
-
// The Circuits-native read transport (ADR-0055 decision 10)
|
|
344
|
-
// through the edge
|
|
343
|
+
// The Circuits-native read transport (ADR-0055 decision 10): pgxsinkit's own long-poll reader of
|
|
344
|
+
// durable-streams, through the edge (ADR-0065 decision 6). Everything above the transport stays ours.
|
|
345
345
|
export { createTokenRecovery, readShapeStream, STREAM_START } from "./circuits/stream-source";
|
|
346
|
-
export type {
|
|
346
|
+
export type {
|
|
347
|
+
ShapeStreamSubscription,
|
|
348
|
+
StreamBatch,
|
|
349
|
+
StreamErrorHandler,
|
|
350
|
+
StreamSourceOptions,
|
|
351
|
+
} from "./circuits/stream-source";
|
|
347
352
|
export { createShapeGroup } from "./circuits/shape-group";
|
|
348
353
|
export type { GroupShapeSpec, ShapeGroup, ShapeGroupBatch, ShapeGroupOptions } from "./circuits/shape-group";
|
|
349
354
|
export { envelopeToChange, primaryKeyFromStreamKey } from "./circuits/envelope-to-change";
|
|
@@ -2645,6 +2650,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2645
2650
|
hadStored: storedFingerprint != null,
|
|
2646
2651
|
});
|
|
2647
2652
|
await pgwasm.exec(generateDurableLocalSchemaSql(options.registry));
|
|
2653
|
+
// pgwasm discovers array OIDs before the registry DDL creates its enum types. Refresh after
|
|
2654
|
+
// replay so enum-array reads are JS arrays on this boot, rather than Postgres array text.
|
|
2655
|
+
await pgwasm.refreshArrayTypes();
|
|
2648
2656
|
await writeStoredLocalSchemaFingerprint(pgwasm, options.registry, currentFingerprint);
|
|
2649
2657
|
bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
|
|
2650
2658
|
}
|
package/src/local-tables.ts
CHANGED
|
@@ -200,6 +200,7 @@ export type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{
|
|
|
200
200
|
schema: string | undefined;
|
|
201
201
|
columns: EntryColumns<TEntry> & OverlayFixedColumns;
|
|
202
202
|
dialect: "pg";
|
|
203
|
+
isAlias: false;
|
|
203
204
|
}>;
|
|
204
205
|
|
|
205
206
|
/**
|
|
@@ -207,11 +208,13 @@ export type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{
|
|
|
207
208
|
* property keys plus the two fixed overlay columns (`overlay_kind`, `local_updated_at_us`). Read
|
|
208
209
|
* through a live query, so `local_updated_at_us` is an int8 `mode: "bigint"` column.
|
|
209
210
|
*/
|
|
210
|
-
export type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<
|
|
211
|
-
string
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
211
|
+
export type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<{
|
|
212
|
+
name: string;
|
|
213
|
+
schema: string | undefined;
|
|
214
|
+
existing: true;
|
|
215
|
+
isAlias: false;
|
|
216
|
+
selectedFields: EntryColumns<TEntry> & ReadModelFixedColumns;
|
|
217
|
+
}>;
|
|
215
218
|
|
|
216
219
|
/**
|
|
217
220
|
* The projected SYNCED read-cache table — the entry's projected local table (or `AnyPgTable` fallback).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse a `Retry-After` header (delta-seconds or HTTP-date, RFC 9110 §10.2.3) into ms, or null when
|
|
3
|
+
* absent/unreadable.
|
|
4
|
+
*
|
|
5
|
+
* Shared by the two clients that honour it: the Event lane's flush loop and the stream reader. Both treat
|
|
6
|
+
* it as a floor under their own backoff, never as a replacement for it.
|
|
7
|
+
*/
|
|
8
|
+
export function parseRetryAfterMs(headerValue: string | null | undefined, nowMs: number): number | null {
|
|
9
|
+
if (headerValue == null) {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
const trimmed = headerValue.trim();
|
|
13
|
+
if (trimmed === "") {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
if (/^\d+$/.test(trimmed)) {
|
|
17
|
+
return Number(trimmed) * 1000;
|
|
18
|
+
}
|
|
19
|
+
const parsedDate = Date.parse(trimmed);
|
|
20
|
+
if (Number.isNaN(parsedDate)) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return Math.max(0, parsedDate - nowMs);
|
|
24
|
+
}
|
package/src/schema.ts
CHANGED
|
@@ -676,8 +676,8 @@ function buildLocalIndexStatements(
|
|
|
676
676
|
* `ANALYZE` does not fix it either, it is what CAUSES it (a never-analysed overlay gets the 10-page floor
|
|
677
677
|
* and plans as a hash anti join).
|
|
678
678
|
*
|
|
679
|
-
* `NOT IN`
|
|
680
|
-
* hashed SubPlan and each synced row is a hash probe — measured ~95-215 ms in that same pathological state
|
|
679
|
+
* `(key NOT IN (...)) IS TRUE` keeps this choice local: the subquery is uncorrelated, so Postgres evaluates
|
|
680
|
+
* it ONCE into a hashed SubPlan and each synced row is a hash probe — measured ~95-215 ms in that same pathological state
|
|
681
681
|
* (roughly half the nested loop, machine-load dependent), 106 ms with no statistics at all, and 60 ms (vs
|
|
682
682
|
* 196 ms) for a composite key. The one cost is the tail:
|
|
683
683
|
* above roughly `hash_mem / (pk width + 24)` rows — order 150k pending overlay rows at the default 4 MB —
|
|
@@ -686,6 +686,11 @@ function buildLocalIndexStatements(
|
|
|
686
686
|
* is already an app in trouble, while "empty and analysed" is the steady state of every read-mostly table.
|
|
687
687
|
* (`EXPLAIN` tells the two apart: `hashed SubPlan` vs a bare `SubPlan`.)
|
|
688
688
|
*
|
|
689
|
+
* PG19 can turn a bare `NOT IN` back into the same anti join when it proves both keys non-null.
|
|
690
|
+
* `IS TRUE` leaves the WHERE result unchanged but puts the SubLink below a BooleanTest, outside
|
|
691
|
+
* `pull_up_sublinks`' top-level NOT/AND traversal. The later SubPlan still hashes the uncorrelated
|
|
692
|
+
* membership set. An OFFSET inside the subquery does not stop that ANY-to-anti conversion.
|
|
693
|
+
*
|
|
689
694
|
* The NULL trap that normally disqualifies `NOT IN` cannot fire here: both sides are PRIMARY KEY columns
|
|
690
695
|
* of tables this generator emits (the overlay carries the same key as the synced table), so neither side
|
|
691
696
|
* can be NULL and `NOT IN` is exactly equivalent to the `NOT EXISTS` it replaces.
|
|
@@ -696,10 +701,10 @@ function buildOverlayNonMembershipTest(primaryKeyColumns: string[], overlayTable
|
|
|
696
701
|
? `t.${primaryKeyColumns[0]}`
|
|
697
702
|
: `(${primaryKeyColumns.map((column) => `t.${column}`).join(", ")})`;
|
|
698
703
|
return [
|
|
699
|
-
`WHERE ${key} NOT IN (`,
|
|
704
|
+
`WHERE (${key} NOT IN (`,
|
|
700
705
|
` SELECT ${primaryKeyColumns.map((column) => `o.${column}`).join(", ")}`,
|
|
701
706
|
` FROM ${overlayTable} AS o`,
|
|
702
|
-
")",
|
|
707
|
+
")) IS TRUE",
|
|
703
708
|
];
|
|
704
709
|
}
|
|
705
710
|
|