@pgxsinkit/client 0.2.5 → 0.2.7
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/event-lane.d.ts +266 -0
- package/dist/event-lane.d.ts.map +1 -0
- package/dist/index.d.ts +94 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2797 -1995
- package/dist/index.js.map +16 -15
- package/dist/local-tables.d.ts +170 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +37 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +12 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +7 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +7 -7
- package/skills/core/SKILL.md +47 -9
- package/skills/operating/SKILL.md +359 -352
- package/src/event-lane.ts +1194 -0
- package/src/index.ts +244 -8
- package/src/local-tables.ts +48 -1
- package/src/mutation.ts +13 -1
- package/src/schema.ts +81 -1
- package/src/worker/attach-sync-client.ts +81 -2
- package/src/worker/define-sync-worker.ts +48 -0
- package/src/worker/protocol.ts +14 -0
|
@@ -0,0 +1,1194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The **Event lane**'s client half (ADR-0053 decisions 2, 3, 4 and 8): the Outbox runtime, its flush loop,
|
|
3
|
+
* and the two observation surfaces.
|
|
4
|
+
*
|
|
5
|
+
* The lane sits beside the sync rail and is deliberately NOT the mutation path. An event is a
|
|
6
|
+
* fire-and-forget fact: nothing echoes back, nothing is overlaid, nothing converges, and there is no
|
|
7
|
+
* conflict. What the client owns is exactly three things — validate + durably stage an append, drain the
|
|
8
|
+
* Outbox in batches to the ingestion endpoint, and apply the server's per-event verdicts. Everything past
|
|
9
|
+
* the endpoint (queue, consumer runner, dead-letter) is the server's half.
|
|
10
|
+
*
|
|
11
|
+
* Two invariants carry the design:
|
|
12
|
+
*
|
|
13
|
+
* 1. **Everything in the Outbox is well-formed.** `appendEvent` validates against the Event stream's
|
|
14
|
+
* registered zod schema and the contracts-level payload-size cap AT THE CALL SITE and throws — a
|
|
15
|
+
* malformed payload is a call-site bug, not a runtime condition. The flush loop and any app-authored
|
|
16
|
+
* best-guess view lean on that.
|
|
17
|
+
* 2. **The client never discards an event without a server verdict.** There is NO attempt cap and NO
|
|
18
|
+
* client-side quarantine (ADR-0053 decision 4): terminal deletion happens only on `acked`/`refused`/
|
|
19
|
+
* `rejected`. A batch that keeps failing backs off at a ceiling, observably, while the Outbox keeps
|
|
20
|
+
* absorbing appends — it is designed to hold offline weeks.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { and, asc, eq, inArray, isNull, lte, notInArray, or, sql } from "drizzle-orm";
|
|
24
|
+
import { drizzle } from "drizzle-orm/pglite";
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
batchEventAckSchema,
|
|
28
|
+
batchEventErrorSchema,
|
|
29
|
+
batchEventPaths,
|
|
30
|
+
getSyncRegistryStreams,
|
|
31
|
+
isZodSchema,
|
|
32
|
+
MAX_EVENT_PAYLOAD_BYTES,
|
|
33
|
+
MAX_EVENT_REQUEST_BYTES,
|
|
34
|
+
MAX_EVENTS_PER_BATCH,
|
|
35
|
+
type EventAck,
|
|
36
|
+
type EventAckStatus,
|
|
37
|
+
type EventEnvelope,
|
|
38
|
+
type EventStreamEntry,
|
|
39
|
+
type SyncTableRegistry,
|
|
40
|
+
} from "@pgxsinkit/contracts";
|
|
41
|
+
|
|
42
|
+
import { syncDebug } from "./debug";
|
|
43
|
+
import { getOutboxTable } from "./local-tables";
|
|
44
|
+
|
|
45
|
+
/** The raw local-store seam the Event lane executes through (structurally PGlite; mirrors `MutationDb`). */
|
|
46
|
+
export interface EventLaneDb {
|
|
47
|
+
query: <TRow extends Record<string, unknown> = Record<string, unknown>>(
|
|
48
|
+
sql: string,
|
|
49
|
+
params?: unknown[],
|
|
50
|
+
) => Promise<{ rows: TRow[] }>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Max events assembled into one flush batch when the consumer sets nothing. Clamped to {@link MAX_EVENTS_PER_BATCH}. */
|
|
54
|
+
export const DEFAULT_EVENT_BATCH_SIZE = 200;
|
|
55
|
+
/**
|
|
56
|
+
* The event-lane flush driver's fallback interval. Deliberately slower than the convergence driver's: an
|
|
57
|
+
* append NUDGES a pass (and reconnect/boot run one), so the interval only has to catch retries and recovery.
|
|
58
|
+
*/
|
|
59
|
+
export const DEFAULT_EVENT_FLUSH_INTERVAL_MS = 5_000;
|
|
60
|
+
/** First retry delay of the jittered exponential backoff (per-row deferred AND batch-level). */
|
|
61
|
+
export const DEFAULT_EVENT_BACKOFF_BASE_MS = 1_000;
|
|
62
|
+
/**
|
|
63
|
+
* The backoff ceiling (ADR-0053 decision 4: "backs off at the ceiling, observably"). Five minutes: long
|
|
64
|
+
* enough that a hard outage costs almost nothing, short enough that a recovered server drains promptly even
|
|
65
|
+
* if no append or online signal nudges the lane.
|
|
66
|
+
*/
|
|
67
|
+
export const DEFAULT_EVENT_BACKOFF_CEILING_MS = 300_000;
|
|
68
|
+
|
|
69
|
+
/** Jittered exponential backoff tuning, shared by the per-row deferred backoff and the batch-level one. */
|
|
70
|
+
export interface EventBackoffOptions {
|
|
71
|
+
/** The first delay, doubled per attempt. Defaults to {@link DEFAULT_EVENT_BACKOFF_BASE_MS}. */
|
|
72
|
+
baseMs?: number;
|
|
73
|
+
/** The delay ceiling. Defaults to {@link DEFAULT_EVENT_BACKOFF_CEILING_MS}. */
|
|
74
|
+
ceilingMs?: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Per-Event-stream flush overrides (ADR-0053 consequences: cadence is client config, never registry). */
|
|
78
|
+
export interface EventStreamFlushOptions {
|
|
79
|
+
/**
|
|
80
|
+
* Cap on how many events of THIS Event stream ride one batch. The lane assembles one mixed batch ordered
|
|
81
|
+
* by `seq` across every stream, so this is the knob that stops one chatty stream from filling every batch
|
|
82
|
+
* ahead of a quieter one. Absent → only the batch-wide {@link EventLaneOptions.batchSize} applies.
|
|
83
|
+
*
|
|
84
|
+
* The cap is applied IN the selection query (each stream's eligible rows are ranked by `seq` and the
|
|
85
|
+
* over-cap ones dropped BEFORE the global order/limit), so it genuinely yields the batch slots it frees to
|
|
86
|
+
* other streams rather than just shrinking the request. Must be an integer >= 1 — a `0`/negative/`NaN` cap
|
|
87
|
+
* would hold every row of the stream back forever, so it is refused at construction.
|
|
88
|
+
*/
|
|
89
|
+
batchSize?: number;
|
|
90
|
+
/** Backoff tuning for THIS stream's `deferred` rows (e.g. a stream mid-rollout wanting a shorter retry). */
|
|
91
|
+
backoff?: EventBackoffOptions;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The Event lane's client-level flush policy (ADR-0053 consequences). It lives on
|
|
96
|
+
* `createSyncClient`/`defineSyncWorker`, NEVER on the registry: the registry is the contract, cadence is
|
|
97
|
+
* deployment tuning, and a batch-size tweak must not surface as a registry diff. Client batching is
|
|
98
|
+
* additionally clamped by the contracts-level request-shape limits, which the server enforces independently.
|
|
99
|
+
*/
|
|
100
|
+
export interface EventLaneOptions {
|
|
101
|
+
/** Events per flush batch. Defaults to {@link DEFAULT_EVENT_BATCH_SIZE}; clamped to {@link MAX_EVENTS_PER_BATCH}. */
|
|
102
|
+
batchSize?: number;
|
|
103
|
+
/** The flush driver's fallback interval. Defaults to {@link DEFAULT_EVENT_FLUSH_INTERVAL_MS}. */
|
|
104
|
+
intervalMs?: number;
|
|
105
|
+
/** Backoff tuning for deferred rows and for batch-level faults. */
|
|
106
|
+
backoff?: EventBackoffOptions;
|
|
107
|
+
/** Per-Event-stream overrides, keyed by Event-stream name. */
|
|
108
|
+
streams?: Record<string, EventStreamFlushOptions>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** What `appendEvent` resolves with once the event is durably staged: the library's stamps + the local ordinal. */
|
|
112
|
+
export interface EventAppendResult {
|
|
113
|
+
/** The library-stamped uuid — the wire identity, and the key every {@link EventLaneVerdict} reports under. */
|
|
114
|
+
eventId: string;
|
|
115
|
+
/** The library-stamped append time in microseconds (decimal string). */
|
|
116
|
+
occurredAtUs: string;
|
|
117
|
+
/** The local append ordinal (decimal string). Local machinery: never transmitted. */
|
|
118
|
+
seq: string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The **drain signal** (ADR-0053 decision 2): whether the Outbox is empty. Deliberately no count — a count
|
|
123
|
+
* that updates only on transitions is stale by construction, and a count updated per append is a worse live
|
|
124
|
+
* query. Richer detail is a query against the Outbox table.
|
|
125
|
+
*/
|
|
126
|
+
export interface OutboxStatus {
|
|
127
|
+
empty: boolean;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** One server-issued per-event verdict, as surfaced on the report. */
|
|
131
|
+
export interface EventLaneVerdict {
|
|
132
|
+
eventId: string;
|
|
133
|
+
/** The Event-stream name the event was appended under. */
|
|
134
|
+
stream: string;
|
|
135
|
+
status: EventAckStatus;
|
|
136
|
+
reason?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A batch-level backoff transition (ADR-0053 decision 4) — the lane entering or leaving its retry backoff. */
|
|
140
|
+
export interface EventLaneBackoffTransition {
|
|
141
|
+
state: "entered" | "cleared";
|
|
142
|
+
/** How long the lane will hold off, in ms. Present when `entered`. */
|
|
143
|
+
retryInMs?: number;
|
|
144
|
+
/** Consecutive failed batch attempts behind the current backoff. Present when `entered`. */
|
|
145
|
+
attempt?: number;
|
|
146
|
+
/** The HTTP status that caused it, when there was one (absent for a transport failure). */
|
|
147
|
+
httpStatus?: number;
|
|
148
|
+
/** The failure message. Present when `entered`. */
|
|
149
|
+
reason?: string;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* One flush pass's report (ADR-0053 decision 2) — the ephemeral surface `onEventLaneReport` delivers.
|
|
154
|
+
*
|
|
155
|
+
* It carries what the Outbox can no longer answer: `acked` is NOT reported (a successful append-only lane
|
|
156
|
+
* would drown the app in its own volume), but `refused` and `rejected` are — those rows are deleted, so once
|
|
157
|
+
* they are gone the Outbox cannot say what happened to them. `deferred` rows stay, but are reported so a
|
|
158
|
+
* rollout skew is visible rather than mysterious. The batch-level backoff transitions ride here too.
|
|
159
|
+
*/
|
|
160
|
+
export interface EventLaneReport {
|
|
161
|
+
/** Terminal, non-`acked` verdicts: the row was DELETED on the server's say-so. */
|
|
162
|
+
terminal: EventLaneVerdict[];
|
|
163
|
+
/** `deferred` verdicts: the row STAYS in the Outbox and retries with backoff. */
|
|
164
|
+
deferred: EventLaneVerdict[];
|
|
165
|
+
/** Present only on the pass that changed the lane's batch-level backoff state. */
|
|
166
|
+
backoff?: EventLaneBackoffTransition;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface CreateEventLaneRuntimeOptions<TRegistry extends SyncTableRegistry> {
|
|
170
|
+
db: EventLaneDb;
|
|
171
|
+
registry: TRegistry;
|
|
172
|
+
/** The ingestion endpoint — `/api/events`, or an absolute deployment URL ending in it. */
|
|
173
|
+
batchEventUrl: string;
|
|
174
|
+
getAuthToken?: () => Promise<string | undefined>;
|
|
175
|
+
/** Static headers added to every flush request (the toolkit's own Content-Type/Authorization still win). */
|
|
176
|
+
requestHeaders?: Record<string, string>;
|
|
177
|
+
/** Client-level flush policy. See {@link EventLaneOptions}. */
|
|
178
|
+
events?: EventLaneOptions;
|
|
179
|
+
/** @internal Injectable wall clock (ms) — the deterministic seam the backoff/deferred tests drive. */
|
|
180
|
+
now?: () => number;
|
|
181
|
+
/** @internal Injectable jitter source, for deterministic backoff assertions. */
|
|
182
|
+
random?: () => number;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface EventLaneRuntime {
|
|
186
|
+
/** Whether the registry registered any Event stream. False → `appendEvent` throws and no driver is stood up. */
|
|
187
|
+
readonly hasStreams: boolean;
|
|
188
|
+
appendEvent: (stream: string, payload: unknown) => Promise<EventAppendResult>;
|
|
189
|
+
/** Drain the Outbox: assemble, POST and settle batches until nothing more is eligible this pass. */
|
|
190
|
+
flush: () => Promise<void>;
|
|
191
|
+
/** The current drain signal, read from the store. */
|
|
192
|
+
outboxStatus: () => Promise<OutboxStatus>;
|
|
193
|
+
/** Subscribe to the drain signal; the CURRENT state is delivered on subscribe. Returns an unsubscribe. */
|
|
194
|
+
onOutboxStatus: (listener: (status: OutboxStatus) => void) => () => void;
|
|
195
|
+
/** Subscribe to per-flush reports. Ephemeral (nothing is retained); returns an unsubscribe. */
|
|
196
|
+
onEventLaneReport: (listener: (report: EventLaneReport) => void) => () => void;
|
|
197
|
+
/** Abort any in-flight flush request (the teardown seam, mirroring the mutation runtime's). */
|
|
198
|
+
abortInFlight: () => void;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ─── Typed append refusals ───────────────────────────────────────────────────────────────────────────
|
|
202
|
+
|
|
203
|
+
/** The registry registered no Event stream at all, so there is nothing an append could target. */
|
|
204
|
+
export class EventStreamsNotRegisteredError extends Error {
|
|
205
|
+
constructor() {
|
|
206
|
+
super(
|
|
207
|
+
"pgxsinkit: no Event streams registered — `appendEvent` needs a `streams` entry on the sync registry " +
|
|
208
|
+
"(defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })).",
|
|
209
|
+
);
|
|
210
|
+
this.name = "EventStreamsNotRegisteredError";
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** `appendEvent` named an Event stream this registry does not register — a call-site bug, never a rollout. */
|
|
215
|
+
export class UnknownEventStreamError extends Error {
|
|
216
|
+
readonly stream: string;
|
|
217
|
+
constructor(stream: string, known: readonly string[]) {
|
|
218
|
+
super(
|
|
219
|
+
`pgxsinkit: unknown Event stream "${stream}" — this registry registers [${known.join(", ")}]. ` +
|
|
220
|
+
"Register it with `defineEventStream` or fix the name.",
|
|
221
|
+
);
|
|
222
|
+
this.name = "UnknownEventStreamError";
|
|
223
|
+
this.stream = stream;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The payload failed the Event stream's registered zod schema. Validated at append so the Outbox stays well-formed. */
|
|
228
|
+
export class EventPayloadInvalidError extends Error {
|
|
229
|
+
readonly stream: string;
|
|
230
|
+
constructor(stream: string, detail: string) {
|
|
231
|
+
super(`pgxsinkit: event payload for Event stream "${stream}" failed its registered schema — ${detail}`);
|
|
232
|
+
this.name = "EventPayloadInvalidError";
|
|
233
|
+
this.stream = stream;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The serialized payload exceeded {@link MAX_EVENT_PAYLOAD_BYTES}; the server would reject it per-event anyway. */
|
|
238
|
+
export class EventPayloadTooLargeError extends Error {
|
|
239
|
+
readonly stream: string;
|
|
240
|
+
readonly byteLength: number;
|
|
241
|
+
constructor(stream: string, byteLength: number) {
|
|
242
|
+
super(
|
|
243
|
+
`pgxsinkit: event payload for Event stream "${stream}" is ${byteLength} bytes, over the ` +
|
|
244
|
+
`${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit. Events are facts, not documents — carry a reference, not the document.`,
|
|
245
|
+
);
|
|
246
|
+
this.name = "EventPayloadTooLargeError";
|
|
247
|
+
this.stream = stream;
|
|
248
|
+
this.byteLength = byteLength;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** A non-2xx flush response. Batch-level by construction: a well-formed envelope always gets a per-event verdict. */
|
|
253
|
+
class EventRequestError extends Error {
|
|
254
|
+
readonly status: number;
|
|
255
|
+
readonly retryAfterMs: number | null;
|
|
256
|
+
|
|
257
|
+
constructor(message: string, status: number, retryAfterMs: number | null) {
|
|
258
|
+
super(message);
|
|
259
|
+
this.name = "EventRequestError";
|
|
260
|
+
this.status = status;
|
|
261
|
+
this.retryAfterMs = retryAfterMs;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ─── URL + header resolution (the mutation client's idioms) ──────────────────────────────────────────
|
|
266
|
+
|
|
267
|
+
const CANONICAL_EVENT_PATH = batchEventPaths[0];
|
|
268
|
+
|
|
269
|
+
function invalidBatchEventUrl(): Error {
|
|
270
|
+
return new Error(
|
|
271
|
+
`[pgxsinkit] batchEventUrl must be "${CANONICAL_EVENT_PATH}" or an absolute deployment URL ending in "${CANONICAL_EVENT_PATH}"`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Resolve the ingestion endpoint under the same HARD-REQUIRED-PATH rule the mutation client applies to
|
|
277
|
+
* `batchWriteUrl`: a relative URL must BE the canonical path, an absolute one must end in it, and neither
|
|
278
|
+
* may carry a query or fragment. The endpoint is toolkit-owned (`createSyncServer` mounts it), so a URL that
|
|
279
|
+
* cannot be it is a configuration error worth failing on at boot rather than at the first append.
|
|
280
|
+
*/
|
|
281
|
+
export function resolveBatchEventUrl(batchEventUrl: string): string {
|
|
282
|
+
if (batchEventUrl.trim() !== batchEventUrl || batchEventUrl.length === 0) {
|
|
283
|
+
throw invalidBatchEventUrl();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const isRelative = batchEventUrl.startsWith("/") && !batchEventUrl.startsWith("//");
|
|
287
|
+
let parsed: URL;
|
|
288
|
+
try {
|
|
289
|
+
parsed = isRelative ? new URL(batchEventUrl, "https://pgxsinkit.invalid") : new URL(batchEventUrl);
|
|
290
|
+
} catch {
|
|
291
|
+
throw invalidBatchEventUrl();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const hasCanonicalPath = isRelative
|
|
295
|
+
? parsed.pathname === CANONICAL_EVENT_PATH
|
|
296
|
+
: ["http:", "https:"].includes(parsed.protocol) && parsed.pathname.endsWith(CANONICAL_EVENT_PATH);
|
|
297
|
+
if (!hasCanonicalPath || parsed.search !== "" || parsed.hash !== "") {
|
|
298
|
+
throw invalidBatchEventUrl();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return batchEventUrl;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* The ingestion endpoint DERIVED from the mutation endpoint, for the ordinary deployment where one
|
|
306
|
+
* `createSyncServer` mounts both: `…/api/mutations` → `…/api/events`. Returns `undefined` when the write URL
|
|
307
|
+
* is not in the canonical shape, so the caller can stay silent rather than guess (the lane is then only
|
|
308
|
+
* usable with an explicit `batchEventUrl`).
|
|
309
|
+
*/
|
|
310
|
+
export function deriveBatchEventUrl(batchWriteUrl: string): string | undefined {
|
|
311
|
+
const suffix = "/api/mutations";
|
|
312
|
+
if (!batchWriteUrl.endsWith(suffix)) {
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
const candidate = `${batchWriteUrl.slice(0, -suffix.length)}${CANONICAL_EVENT_PATH}`;
|
|
316
|
+
try {
|
|
317
|
+
return resolveBatchEventUrl(candidate);
|
|
318
|
+
} catch {
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {
|
|
324
|
+
// Static headers first so the toolkit-owned Content-Type/Authorization always win (mutation.ts's rule).
|
|
325
|
+
return {
|
|
326
|
+
...(requestHeaders ?? {}),
|
|
327
|
+
"Content-Type": "application/json",
|
|
328
|
+
...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ─── Retry classification (ADR-0053 decision 4) ──────────────────────────────────────────────────────
|
|
333
|
+
|
|
334
|
+
/** Auth statuses: refresh the token once, then treat a repeat as ordinary retryable congestion. */
|
|
335
|
+
const AUTH_STATUSES: ReadonlySet<number> = new Set([401, 403]);
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The lane has EXACTLY TWO retry classes, and this is the whole rule. Unlike the mutation path there is no
|
|
339
|
+
* third, terminal class: a structural 4xx (400/404/413) is unreachable through the library (appends are
|
|
340
|
+
* validated, envelopes are library-built), and quarantining events on one would discard data the server
|
|
341
|
+
* never rejected — which at-least-once forbids. So everything that is not auth is retryable.
|
|
342
|
+
*/
|
|
343
|
+
export function classifyEventBatchFailure(httpStatus: number | null | undefined): "auth" | "retryable" {
|
|
344
|
+
return httpStatus != null && AUTH_STATUSES.has(httpStatus) ? "auth" : "retryable";
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Parse a `Retry-After` header (delta-seconds or HTTP-date) into ms, or null when absent/unreadable. */
|
|
348
|
+
export function parseRetryAfterMs(headerValue: string | null | undefined, nowMs: number): number | null {
|
|
349
|
+
if (headerValue == null) {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
const trimmed = headerValue.trim();
|
|
353
|
+
if (trimmed === "") {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
if (/^\d+$/.test(trimmed)) {
|
|
357
|
+
return Number(trimmed) * 1000;
|
|
358
|
+
}
|
|
359
|
+
const parsedDate = Date.parse(trimmed);
|
|
360
|
+
if (Number.isNaN(parsedDate)) {
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
return Math.max(0, parsedDate - nowMs);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Jittered exponential backoff with a ceiling — equal jitter around the doubling ceiling, exactly the
|
|
368
|
+
* mutation path's congestion policy (half the ceiling plus a random share of the other half), so a fleet
|
|
369
|
+
* recovering from an outage never stampedes in lockstep.
|
|
370
|
+
*/
|
|
371
|
+
export function computeEventBackoffMs(attempt: number, options: EventBackoffOptions, random: () => number): number {
|
|
372
|
+
const baseMs = options.baseMs ?? DEFAULT_EVENT_BACKOFF_BASE_MS;
|
|
373
|
+
const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_BACKOFF_CEILING_MS;
|
|
374
|
+
const exponent = Math.max(attempt - 1, 0);
|
|
375
|
+
const ceiling = Math.min(baseMs * 2 ** exponent, ceilingMs);
|
|
376
|
+
return Math.round(ceiling / 2 + random() * (ceiling / 2));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// ─── Runtime ─────────────────────────────────────────────────────────────────────────────────────────
|
|
380
|
+
|
|
381
|
+
interface OutboxRow extends Record<string, unknown> {
|
|
382
|
+
seq: string;
|
|
383
|
+
eventId: string;
|
|
384
|
+
stream: string;
|
|
385
|
+
occurredAtUs: string;
|
|
386
|
+
payload: unknown;
|
|
387
|
+
attemptCount: number;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** One assembled batch: the wire envelopes plus the local rows they map back to. */
|
|
391
|
+
interface AssembledBatch {
|
|
392
|
+
envelopes: EventEnvelope[];
|
|
393
|
+
rowsByEventId: Map<string, OutboxRow>;
|
|
394
|
+
/** True when assembly stopped on the request-byte cap rather than running out of eligible rows. */
|
|
395
|
+
clampedByBytes: boolean;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const encoder = new TextEncoder();
|
|
399
|
+
|
|
400
|
+
function byteLengthOf(value: string): number {
|
|
401
|
+
return encoder.encode(value).length;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Fail-closed validation of the client's Event-lane tuning, at CONSTRUCTION (the consumer runner's posture,
|
|
406
|
+
* mirrored on the client half — and it names EVERY offender in one error rather than one per boot).
|
|
407
|
+
*
|
|
408
|
+
* This exists because the failure mode of a typo here is silence, not an exception. A per-stream `batchSize`
|
|
409
|
+
* of `0`/`-1`/`NaN` makes batch assembly hold every row of that stream back, so the pass exits with no
|
|
410
|
+
* request and no report and the stream wedges INDEFINITELY while appends keep piling into the Outbox. A
|
|
411
|
+
* broken interval or backoff bound reaches the timer/backoff machinery just as quietly. A configuration typo
|
|
412
|
+
* must be a boundary error, never a runtime behaviour.
|
|
413
|
+
*
|
|
414
|
+
* The bounds mirror `defineEventConsumer`'s: counts are integers >= 1, a backoff FLOOR may legitimately be
|
|
415
|
+
* `0` (retry on the very next pass — the per-pass "one attempt per row" guard is what stops a spin), and a
|
|
416
|
+
* ceiling may not sit below its floor.
|
|
417
|
+
*
|
|
418
|
+
* Backoff bounds are judged on the RESOLVED pair — defaults (and, per stream, the global tuning) filled in
|
|
419
|
+
* FIRST — never on what happens to be written down. `{ baseMs: 600_000 }` alone looks coherent and is not:
|
|
420
|
+
* the omitted ceiling takes the 300,000 ms default, so even a maximum-jitter first delay is capped to half
|
|
421
|
+
* the ten-minute base that was asked for, silently. The pair the machinery will actually run under is the
|
|
422
|
+
* only pair worth checking.
|
|
423
|
+
*/
|
|
424
|
+
export function validateEventLaneOptions(options: EventLaneOptions): void {
|
|
425
|
+
const problems: string[] = [];
|
|
426
|
+
|
|
427
|
+
const requireCount = (label: string, value: number | undefined): void => {
|
|
428
|
+
if (value !== undefined && (!Number.isInteger(value) || value < 1)) {
|
|
429
|
+
problems.push(`\`${label}\` must be an integer >= 1 (got ${String(value)})`);
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
const requireMs = (label: string, value: number | undefined, minimum: number): void => {
|
|
433
|
+
if (value !== undefined && (!Number.isFinite(value) || value < minimum)) {
|
|
434
|
+
problems.push(`\`${label}\` must be a finite number >= ${minimum} (got ${String(value)})`);
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
/** One resolved bound, carrying WHERE its value came from so an incoherence names the real culprit. */
|
|
439
|
+
interface ResolvedBound {
|
|
440
|
+
value: number;
|
|
441
|
+
/** `null` when the value is still the library default; otherwise the label that supplied it. */
|
|
442
|
+
setBy: string | null;
|
|
443
|
+
}
|
|
444
|
+
type ResolvedBackoff = { baseMs: ResolvedBound; ceilingMs: ResolvedBound };
|
|
445
|
+
|
|
446
|
+
const defaults: ResolvedBackoff = {
|
|
447
|
+
baseMs: { value: DEFAULT_EVENT_BACKOFF_BASE_MS, setBy: null },
|
|
448
|
+
ceilingMs: { value: DEFAULT_EVENT_BACKOFF_CEILING_MS, setBy: null },
|
|
449
|
+
};
|
|
450
|
+
const originOf = (bound: ResolvedBound, label: string): string =>
|
|
451
|
+
bound.setBy === null ? "the default" : bound.setBy === label ? "configured" : `inherited from \`${bound.setBy}\``;
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Validate one backoff and return the bounds it will RUN under. `inherited` is what an omitted bound falls
|
|
455
|
+
* back to — the defaults for the global tuning, the resolved global tuning for a per-stream override —
|
|
456
|
+
* exactly the composition `backoffFor` performs at runtime.
|
|
457
|
+
*/
|
|
458
|
+
const requireBackoff = (
|
|
459
|
+
label: string,
|
|
460
|
+
backoff: EventBackoffOptions | undefined,
|
|
461
|
+
inherited: ResolvedBackoff,
|
|
462
|
+
): ResolvedBackoff => {
|
|
463
|
+
requireMs(`${label}.baseMs`, backoff?.baseMs, 0);
|
|
464
|
+
requireMs(`${label}.ceilingMs`, backoff?.ceilingMs, 0);
|
|
465
|
+
|
|
466
|
+
const resolve = (configured: number | undefined, fallback: ResolvedBound): ResolvedBound =>
|
|
467
|
+
configured === undefined ? fallback : { value: configured, setBy: label };
|
|
468
|
+
const resolved: ResolvedBackoff = {
|
|
469
|
+
baseMs: resolve(backoff?.baseMs, inherited.baseMs),
|
|
470
|
+
ceilingMs: resolve(backoff?.ceilingMs, inherited.ceilingMs),
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
// Only judge a pair both of whose numbers are usable — an unusable one is already its own problem.
|
|
474
|
+
if (
|
|
475
|
+
Number.isFinite(resolved.baseMs.value) &&
|
|
476
|
+
Number.isFinite(resolved.ceilingMs.value) &&
|
|
477
|
+
resolved.ceilingMs.value < resolved.baseMs.value
|
|
478
|
+
) {
|
|
479
|
+
problems.push(
|
|
480
|
+
`\`${label}\` resolves to a ceiling BELOW its base — ceilingMs ${resolved.ceilingMs.value} ` +
|
|
481
|
+
`(${originOf(resolved.ceilingMs, label)}) < baseMs ${resolved.baseMs.value} ` +
|
|
482
|
+
`(${originOf(resolved.baseMs, label)}); the base would never be waited, because every delay is ` +
|
|
483
|
+
"clamped to the ceiling",
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
return resolved;
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
requireCount("events.batchSize", options.batchSize);
|
|
490
|
+
requireMs("events.intervalMs", options.intervalMs, 1);
|
|
491
|
+
const globalBackoff = requireBackoff("events.backoff", options.backoff, defaults);
|
|
492
|
+
|
|
493
|
+
for (const [stream, streamOptions] of Object.entries(options.streams ?? {})) {
|
|
494
|
+
if (streamOptions == null || typeof streamOptions !== "object") {
|
|
495
|
+
problems.push(`\`events.streams.${stream}\` must be an object of per-stream flush overrides`);
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
requireCount(`events.streams.${stream}.batchSize`, streamOptions.batchSize);
|
|
499
|
+
// A per-stream override inherits the GLOBAL bound it does not set, so that is the ceiling it will
|
|
500
|
+
// actually run under — a per-stream base has to cohere with it, not merely with the default.
|
|
501
|
+
requireBackoff(`events.streams.${stream}.backoff`, streamOptions.backoff, globalBackoff);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (problems.length > 0) {
|
|
505
|
+
throw new Error(
|
|
506
|
+
`pgxsinkit: invalid Event-lane tuning on the sync client (the \`events\` option) — ${problems.join("; ")}.`,
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
512
|
+
options: CreateEventLaneRuntimeOptions<TRegistry>,
|
|
513
|
+
): EventLaneRuntime {
|
|
514
|
+
// Before anything else, including any store access: nonsense tuning must fail at construction.
|
|
515
|
+
validateEventLaneOptions(options.events ?? {});
|
|
516
|
+
// Statements are AUTHORED as Drizzle builders over the Outbox table object (rename-safe, typed, schema
|
|
517
|
+
// qualification handled by the object) and rendered to text+params here, because they EXECUTE through the
|
|
518
|
+
// caller's raw `EventLaneDb` seam — the same arrangement the mutation runtime uses. The connection-less
|
|
519
|
+
// builder is created on FIRST STATEMENT, not at import and not at construction: a client whose registry
|
|
520
|
+
// registers no Event stream never authors one, and the lane should cost it nothing.
|
|
521
|
+
let queryBuilderCache: ReturnType<typeof drizzle.mock> | null = null;
|
|
522
|
+
const queryBuilder = (): ReturnType<typeof drizzle.mock> => (queryBuilderCache ??= drizzle.mock());
|
|
523
|
+
const streams = getSyncRegistryStreams(options.registry);
|
|
524
|
+
const streamNames = streams ? Object.keys(streams) : [];
|
|
525
|
+
const hasStreams = streamNames.length > 0;
|
|
526
|
+
const outbox = getOutboxTable(options.registry);
|
|
527
|
+
const eventUrl = resolveBatchEventUrl(options.batchEventUrl);
|
|
528
|
+
const clockMs = options.now ?? (() => Date.now());
|
|
529
|
+
const random = options.random ?? Math.random;
|
|
530
|
+
const laneOptions = options.events ?? {};
|
|
531
|
+
// Clamp to the contracts-level cap: the server enforces it independently of any client tuning, so a
|
|
532
|
+
// client configured above it would only ever produce 413s.
|
|
533
|
+
const batchSize = Math.max(1, Math.min(laneOptions.batchSize ?? DEFAULT_EVENT_BATCH_SIZE, MAX_EVENTS_PER_BATCH));
|
|
534
|
+
|
|
535
|
+
const nowUs = (): string => (BigInt(clockMs()) * 1000n).toString();
|
|
536
|
+
const backoffFor = (stream?: string): EventBackoffOptions => ({
|
|
537
|
+
...(laneOptions.backoff ?? {}),
|
|
538
|
+
...((stream != null ? laneOptions.streams?.[stream]?.backoff : undefined) ?? {}),
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
const disposeController = new AbortController();
|
|
542
|
+
|
|
543
|
+
// ─── Observation surfaces ──────────────────────────────────────────────────────────────────────────
|
|
544
|
+
const statusListeners = new Set<(status: OutboxStatus) => void>();
|
|
545
|
+
const reportListeners = new Set<(report: EventLaneReport) => void>();
|
|
546
|
+
/** The last drain state we published. `null` until the first read — subscribe then defers to the probe. */
|
|
547
|
+
let currentEmpty: boolean | null = null;
|
|
548
|
+
|
|
549
|
+
const publishEmpty = (empty: boolean): void => {
|
|
550
|
+
if (currentEmpty === empty) {
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
currentEmpty = empty;
|
|
554
|
+
for (const listener of statusListeners) {
|
|
555
|
+
listener({ empty });
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* The drain signal's read. Deliberately `LIMIT 1`, never `count(*)`: the signal is a BOOLEAN, and an
|
|
561
|
+
* Outbox designed to hold offline weeks would make a counting scan the expensive part of every flush pass
|
|
562
|
+
* and every lifecycle check. (An app that genuinely wants a count queries the table itself.)
|
|
563
|
+
*/
|
|
564
|
+
const isOutboxEmpty = async (): Promise<boolean> => {
|
|
565
|
+
const query = queryBuilder()
|
|
566
|
+
.select({ one: sql<number>`1`.as("one") })
|
|
567
|
+
.from(outbox)
|
|
568
|
+
.limit(1)
|
|
569
|
+
.toSQL();
|
|
570
|
+
const result = await options.db.query<{ one: number }>(query.sql, query.params as unknown[]);
|
|
571
|
+
return result.rows.length === 0;
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
const refreshDrainSignal = async (): Promise<boolean> => {
|
|
575
|
+
const empty = await isOutboxEmpty();
|
|
576
|
+
publishEmpty(empty);
|
|
577
|
+
return empty;
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
// The first read of the drain signal, kicked off eagerly so a subscriber that arrives before any append
|
|
581
|
+
// or flush still gets the CURRENT state delivered (never a silent subscription). Failures are swallowed:
|
|
582
|
+
// an unreadable Outbox at boot is a store problem the boot path itself reports.
|
|
583
|
+
const initialProbe = refreshDrainSignal().catch((error: unknown) => {
|
|
584
|
+
syncDebug("event lane: initial drain-signal probe failed", { error });
|
|
585
|
+
return false;
|
|
586
|
+
});
|
|
587
|
+
|
|
588
|
+
const emitReport = (report: EventLaneReport): void => {
|
|
589
|
+
if (report.terminal.length === 0 && report.deferred.length === 0 && report.backoff == null) {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
if (reportListeners.size === 0) {
|
|
593
|
+
// The `onDeadLetter` idiom: a surface nobody subscribed to still must not be silent. Everything on
|
|
594
|
+
// this report is something the Outbox can no longer answer for (a deleted row's terminal verdict) or
|
|
595
|
+
// something an operator needs to see (a rollout skew, a lane in backoff).
|
|
596
|
+
console.warn("pgxsinkit: event-lane report (no `onEventLaneReport` subscriber)", report);
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
for (const listener of reportListeners) {
|
|
600
|
+
listener(report);
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
// ─── Append (ADR-0053 decision 2) ──────────────────────────────────────────────────────────────────
|
|
605
|
+
const resolveStreamEntry = (stream: string): EventStreamEntry => {
|
|
606
|
+
if (!hasStreams) {
|
|
607
|
+
throw new EventStreamsNotRegisteredError();
|
|
608
|
+
}
|
|
609
|
+
const entry = streams?.[stream];
|
|
610
|
+
if (!entry) {
|
|
611
|
+
throw new UnknownEventStreamError(stream, streamNames);
|
|
612
|
+
}
|
|
613
|
+
return entry;
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* Stage one event (ADR-0053 decision 2).
|
|
618
|
+
*
|
|
619
|
+
* **Validation here, the authoritative parse at ingest.** The registered payload schema is the contract,
|
|
620
|
+
* checked HERE so a malformed payload is a synchronous call-site failure rather than a server verdict on a
|
|
621
|
+
* row already in the Outbox — but this run is a VALIDATION, and its OUTPUT IS DISCARDED. What lands in the
|
|
622
|
+
* Outbox (and therefore on the wire) is EXACTLY the value the caller supplied, never `parsed.data`: the
|
|
623
|
+
* ingestion endpoint's parse is the ONE authoritative one, and the JSON-NORMALIZED form of its output is
|
|
624
|
+
* what the consumer receives (a `Date` becomes its ISO string; a nested `undefined` property is dropped).
|
|
625
|
+
* Taking this run's output instead would hand the server an already-transformed value to re-parse — a
|
|
626
|
+
* terminal `rejected` for a perfectly valid append. The per-event size cap is measured on that same
|
|
627
|
+
* original serialization, for the same reason: it is what the request will carry.
|
|
628
|
+
*
|
|
629
|
+
* So the schema EXECUTES at both boundaries even though only one execution's result is ever taken: a
|
|
630
|
+
* transform callback runs once here and once at ingest. **Transforms must therefore be pure and
|
|
631
|
+
* deterministic** — an effectful or environment-dependent transform is unsupported, because the server's
|
|
632
|
+
* run is the one that counts and nothing reconciles it against this one. Parse output that JSON cannot
|
|
633
|
+
* carry (a `BigInt`, `undefined`) is a terminal per-event `rejected` at ingest.
|
|
634
|
+
*/
|
|
635
|
+
const appendEvent = async (stream: string, payload: unknown): Promise<EventAppendResult> => {
|
|
636
|
+
const entry = resolveStreamEntry(stream);
|
|
637
|
+
|
|
638
|
+
if (!isZodSchema(entry.payload)) {
|
|
639
|
+
throw new EventPayloadInvalidError(stream, "its registration does not carry a usable zod schema");
|
|
640
|
+
}
|
|
641
|
+
const parsed = entry.payload.safeParse(payload);
|
|
642
|
+
if (!parsed.success) {
|
|
643
|
+
throw new EventPayloadInvalidError(stream, parsed.error.message);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const payloadJson = JSON.stringify(payload);
|
|
647
|
+
if (payloadJson === undefined) {
|
|
648
|
+
throw new EventPayloadInvalidError(stream, "the payload is not JSON-serializable");
|
|
649
|
+
}
|
|
650
|
+
const byteLength = byteLengthOf(payloadJson);
|
|
651
|
+
if (byteLength > MAX_EVENT_PAYLOAD_BYTES) {
|
|
652
|
+
throw new EventPayloadTooLargeError(stream, byteLength);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const eventId = globalThis.crypto.randomUUID();
|
|
656
|
+
const occurredAtUs = nowUs();
|
|
657
|
+
const insert = queryBuilder()
|
|
658
|
+
.insert(outbox)
|
|
659
|
+
.values({
|
|
660
|
+
eventId,
|
|
661
|
+
stream,
|
|
662
|
+
occurredAtUs,
|
|
663
|
+
// Bound as a jsonb param, never baked into the statement text.
|
|
664
|
+
payload: sql`${payloadJson}::jsonb`,
|
|
665
|
+
enqueuedAtUs: occurredAtUs,
|
|
666
|
+
})
|
|
667
|
+
.returning({ seq: sql<string>`${outbox.seq}::text`.as("seq") })
|
|
668
|
+
.toSQL();
|
|
669
|
+
const inserted = await options.db.query<{ seq: string }>(insert.sql, insert.params as unknown[]);
|
|
670
|
+
const seq = String(inserted.rows[0]?.seq ?? "");
|
|
671
|
+
|
|
672
|
+
// The append resolves on DURABLE local enqueue under the store's declared durability — no special
|
|
673
|
+
// casing: the INSERT above went through the same store as every other local write.
|
|
674
|
+
publishEmpty(false);
|
|
675
|
+
return { eventId, occurredAtUs, seq };
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
// ─── Batch assembly (ADR-0053 decisions 3 + 4) ─────────────────────────────────────────────────────
|
|
679
|
+
|
|
680
|
+
/** The configured per-stream caps, as `[stream, cap]` pairs. Empty → no fairness filter is needed at all. */
|
|
681
|
+
const streamCaps: [string, number][] = Object.entries(laneOptions.streams ?? {}).flatMap(([stream, streamOptions]) =>
|
|
682
|
+
streamOptions?.batchSize != null ? [[stream, streamOptions.batchSize] as const] : [],
|
|
683
|
+
);
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* A row deferred by the server waits out its own backoff; every other row is eligible.
|
|
687
|
+
*/
|
|
688
|
+
const eligibleNow = () => or(isNull(outbox.nextRetryAtUs), lte(outbox.nextRetryAtUs, nowUs()));
|
|
689
|
+
|
|
690
|
+
const readEligibleRows = async (limit: number): Promise<OutboxRow[]> => {
|
|
691
|
+
// Rows come back through the RAW seam (no drizzle result mapping), so every column is aliased to its
|
|
692
|
+
// PROPERTY key — the mutation runtime's `buildPendingRowsProjection` idiom. `_us` bigints cast to
|
|
693
|
+
// `text` so they arrive as exact decimal strings rather than lossy JS numbers.
|
|
694
|
+
const project = <TSource extends typeof outbox | ReturnType<typeof rankedEligible>>(source: TSource) => ({
|
|
695
|
+
seq: sql<string>`${source.seq}::text`.as("seq"),
|
|
696
|
+
eventId: sql<string>`${source.eventId}`.as("eventId"),
|
|
697
|
+
stream: sql<string>`${source.stream}`.as("stream"),
|
|
698
|
+
occurredAtUs: sql<string>`${source.occurredAtUs}::text`.as("occurredAtUs"),
|
|
699
|
+
payload: sql<unknown>`${source.payload}`.as("payload"),
|
|
700
|
+
attemptCount: sql<number>`${source.attemptCount}`.as("attemptCount"),
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
// `seq` is the ONE ordering key — across ALL Event streams, so one batch is a mixed, append-ordered
|
|
704
|
+
// slice — and with no per-stream cap configured that is the whole query.
|
|
705
|
+
const query =
|
|
706
|
+
streamCaps.length === 0
|
|
707
|
+
? queryBuilder().select(project(outbox)).from(outbox).where(eligibleNow()).orderBy(asc(outbox.seq)).limit(limit)
|
|
708
|
+
: (() => {
|
|
709
|
+
// Fairness has to happen IN SQL, before the global `ORDER BY seq LIMIT`. Ranking each stream's
|
|
710
|
+
// eligible rows by `seq` and dropping the over-cap ones FIRST is what makes the cap mean what it
|
|
711
|
+
// says: a chatty stream's surplus never occupies the selection window, so a quieter stream rides
|
|
712
|
+
// the same batch. (Capping after a global `LIMIT` — the shape this replaces — only shrank the
|
|
713
|
+
// request: if the earliest `batchSize` rows were all stream A, stream B stayed invisible until
|
|
714
|
+
// A's whole backlog had drained, one small A-only request at a time.)
|
|
715
|
+
const ranked = rankedEligible();
|
|
716
|
+
return queryBuilder()
|
|
717
|
+
.select(project(ranked))
|
|
718
|
+
.from(ranked)
|
|
719
|
+
.where(
|
|
720
|
+
or(
|
|
721
|
+
// An uncapped stream is unconstrained; a capped one rides only its first `cap` rows.
|
|
722
|
+
notInArray(
|
|
723
|
+
ranked.stream,
|
|
724
|
+
streamCaps.map(([stream]) => stream),
|
|
725
|
+
),
|
|
726
|
+
...streamCaps.map(([stream, cap]) => and(eq(ranked.stream, stream), lte(ranked.streamRank, cap))),
|
|
727
|
+
),
|
|
728
|
+
)
|
|
729
|
+
.orderBy(asc(ranked.seq))
|
|
730
|
+
.limit(limit);
|
|
731
|
+
})();
|
|
732
|
+
|
|
733
|
+
const compiled = query.toSQL();
|
|
734
|
+
const result = await options.db.query<OutboxRow>(compiled.sql, compiled.params as unknown[]);
|
|
735
|
+
return result.rows;
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
/** The eligible rows, each carrying its 1-based rank WITHIN its own Event stream in `seq` order. */
|
|
739
|
+
function rankedEligible() {
|
|
740
|
+
return queryBuilder()
|
|
741
|
+
.select({
|
|
742
|
+
seq: outbox.seq,
|
|
743
|
+
eventId: outbox.eventId,
|
|
744
|
+
stream: outbox.stream,
|
|
745
|
+
occurredAtUs: outbox.occurredAtUs,
|
|
746
|
+
payload: outbox.payload,
|
|
747
|
+
attemptCount: outbox.attemptCount,
|
|
748
|
+
streamRank: sql<number>`row_number() OVER (PARTITION BY ${outbox.stream} ORDER BY ${outbox.seq})`.as(
|
|
749
|
+
"stream_rank",
|
|
750
|
+
),
|
|
751
|
+
})
|
|
752
|
+
.from(outbox)
|
|
753
|
+
.where(eligibleNow())
|
|
754
|
+
.as("eligible");
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Assemble one batch from the eligible rows: append order by `seq`, clamped by the batch size, any
|
|
759
|
+
* per-stream caps, AND the contracts-level request-byte cap. At least one event always rides (a single
|
|
760
|
+
* payload cannot exceed the body cap — the per-event cap is 64 KiB against a 4 MiB body).
|
|
761
|
+
*/
|
|
762
|
+
const assembleBatch = (rows: readonly OutboxRow[]): AssembledBatch => {
|
|
763
|
+
const envelopes: EventEnvelope[] = [];
|
|
764
|
+
const rowsByEventId = new Map<string, OutboxRow>();
|
|
765
|
+
const perStreamCount = new Map<string, number>();
|
|
766
|
+
// `{"events":[]}` framing; each additional envelope also costs a comma.
|
|
767
|
+
let requestBytes = byteLengthOf('{"events":[]}');
|
|
768
|
+
let clampedByBytes = false;
|
|
769
|
+
|
|
770
|
+
for (const row of rows) {
|
|
771
|
+
if (envelopes.length >= batchSize) {
|
|
772
|
+
break;
|
|
773
|
+
}
|
|
774
|
+
const streamCap = laneOptions.streams?.[row.stream]?.batchSize;
|
|
775
|
+
const taken = perStreamCount.get(row.stream) ?? 0;
|
|
776
|
+
if (streamCap != null && taken >= streamCap) {
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const envelope: EventEnvelope = {
|
|
781
|
+
stream: row.stream,
|
|
782
|
+
eventId: row.eventId,
|
|
783
|
+
occurredAtUs: String(row.occurredAtUs),
|
|
784
|
+
payload: row.payload,
|
|
785
|
+
};
|
|
786
|
+
const envelopeBytes = byteLengthOf(JSON.stringify(envelope)) + (envelopes.length > 0 ? 1 : 0);
|
|
787
|
+
if (envelopes.length > 0 && requestBytes + envelopeBytes > MAX_EVENT_REQUEST_BYTES) {
|
|
788
|
+
clampedByBytes = true;
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
requestBytes += envelopeBytes;
|
|
793
|
+
perStreamCount.set(row.stream, taken + 1);
|
|
794
|
+
envelopes.push(envelope);
|
|
795
|
+
rowsByEventId.set(row.eventId, row);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
return { envelopes, rowsByEventId, clampedByBytes };
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
// ─── Verdict settlement ────────────────────────────────────────────────────────────────────────────
|
|
802
|
+
const deleteEvents = async (eventIds: readonly string[]): Promise<void> => {
|
|
803
|
+
if (eventIds.length === 0) {
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const query = queryBuilder()
|
|
807
|
+
.delete(outbox)
|
|
808
|
+
.where(inArray(outbox.eventId, [...eventIds]))
|
|
809
|
+
.toSQL();
|
|
810
|
+
await options.db.query(query.sql, query.params as unknown[]);
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
/** Park one deferred row: bump its attempt count and push its next retry out by the jittered backoff. */
|
|
814
|
+
const deferEvent = async (row: OutboxRow, reason: string | undefined): Promise<void> => {
|
|
815
|
+
const attempt = row.attemptCount + 1;
|
|
816
|
+
const delayMs = computeEventBackoffMs(attempt, backoffFor(row.stream), random);
|
|
817
|
+
const nextRetryAtUs = (BigInt(nowUs()) + BigInt(delayMs) * 1000n).toString();
|
|
818
|
+
const query = queryBuilder()
|
|
819
|
+
.update(outbox)
|
|
820
|
+
.set({
|
|
821
|
+
attemptCount: attempt,
|
|
822
|
+
nextRetryAtUs,
|
|
823
|
+
lastReason: reason ?? null,
|
|
824
|
+
})
|
|
825
|
+
.where(eq(outbox.eventId, row.eventId))
|
|
826
|
+
.toSQL();
|
|
827
|
+
await options.db.query(query.sql, query.params as unknown[]);
|
|
828
|
+
};
|
|
829
|
+
|
|
830
|
+
// ─── Batch-level backoff state (in memory: it is congestion, not durable intent) ───────────────────
|
|
831
|
+
let batchAttempt = 0;
|
|
832
|
+
let batchRetryAtMs = 0;
|
|
833
|
+
|
|
834
|
+
const enterBatchBackoff = (
|
|
835
|
+
message: string,
|
|
836
|
+
httpStatus: number | null,
|
|
837
|
+
retryAfterMs: number | null,
|
|
838
|
+
): EventLaneBackoffTransition => {
|
|
839
|
+
batchAttempt += 1;
|
|
840
|
+
// `Retry-After` is the server's own instruction (ADR-0053 decision 4: the endpoint returns it with a
|
|
841
|
+
// 503 when the queue is unavailable) — honour it over our own backoff when it asks for longer.
|
|
842
|
+
const backoffMs = computeEventBackoffMs(batchAttempt, backoffFor(), random);
|
|
843
|
+
const delayMs = Math.max(backoffMs, retryAfterMs ?? 0);
|
|
844
|
+
batchRetryAtMs = clockMs() + delayMs;
|
|
845
|
+
return {
|
|
846
|
+
state: "entered",
|
|
847
|
+
retryInMs: delayMs,
|
|
848
|
+
attempt: batchAttempt,
|
|
849
|
+
...(httpStatus != null ? { httpStatus } : {}),
|
|
850
|
+
reason: message,
|
|
851
|
+
};
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
const clearBatchBackoff = (): EventLaneBackoffTransition | undefined => {
|
|
855
|
+
if (batchAttempt === 0) {
|
|
856
|
+
return undefined;
|
|
857
|
+
}
|
|
858
|
+
batchAttempt = 0;
|
|
859
|
+
batchRetryAtMs = 0;
|
|
860
|
+
return { state: "cleared" };
|
|
861
|
+
};
|
|
862
|
+
|
|
863
|
+
// ─── One POST ──────────────────────────────────────────────────────────────────────────────────────
|
|
864
|
+
const postBatch = async (envelopes: readonly EventEnvelope[]): Promise<EventAck[]> => {
|
|
865
|
+
const body = JSON.stringify({ events: envelopes });
|
|
866
|
+
const signal = disposeController.signal;
|
|
867
|
+
const send = async (token: string | undefined): Promise<Response> =>
|
|
868
|
+
fetch(eventUrl, {
|
|
869
|
+
method: "POST",
|
|
870
|
+
headers: buildRequestHeaders(token, options.requestHeaders),
|
|
871
|
+
body,
|
|
872
|
+
signal,
|
|
873
|
+
});
|
|
874
|
+
|
|
875
|
+
let response = await send(await options.getAuthToken?.());
|
|
876
|
+
if (classifyEventBatchFailure(response.status) === "auth" && !response.ok && options.getAuthToken) {
|
|
877
|
+
// Refresh ONCE (the mutation client's rule): a second auth failure is ordinary retryable congestion,
|
|
878
|
+
// never a terminal verdict — only the server may retire an event.
|
|
879
|
+
response = await send(await options.getAuthToken());
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
if (!response.ok) {
|
|
883
|
+
const text = await response.text();
|
|
884
|
+
throw new EventRequestError(
|
|
885
|
+
parseBatchEventErrorMessage(text) ??
|
|
886
|
+
(text.length > 0 ? text : `Event ingestion responded with ${response.status}`),
|
|
887
|
+
response.status,
|
|
888
|
+
parseRetryAfterMs(response.headers.get("Retry-After"), clockMs()),
|
|
889
|
+
);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
const parsed = batchEventAckSchema.safeParse(await response.json());
|
|
893
|
+
if (!parsed.success) {
|
|
894
|
+
// A 2xx we cannot read is a transport-shaped fault, not a verdict: retry, never discard.
|
|
895
|
+
throw new EventRequestError(
|
|
896
|
+
`Event ingestion returned an unreadable ack body: ${parsed.error.message}`,
|
|
897
|
+
response.status,
|
|
898
|
+
null,
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
return parsed.data.acks;
|
|
902
|
+
};
|
|
903
|
+
|
|
904
|
+
// ─── The flush pass ────────────────────────────────────────────────────────────────────────────────
|
|
905
|
+
/** Settle one assembled batch's verdicts; returns the report fragments it produced. */
|
|
906
|
+
const settleAcks = async (
|
|
907
|
+
batch: AssembledBatch,
|
|
908
|
+
acks: readonly EventAck[],
|
|
909
|
+
): Promise<{ terminal: EventLaneVerdict[]; deferred: EventLaneVerdict[]; settledCount: number }> => {
|
|
910
|
+
const terminal: EventLaneVerdict[] = [];
|
|
911
|
+
const deferred: EventLaneVerdict[] = [];
|
|
912
|
+
const deletable: string[] = [];
|
|
913
|
+
|
|
914
|
+
for (const ack of acks) {
|
|
915
|
+
const row = batch.rowsByEventId.get(ack.eventId);
|
|
916
|
+
if (!row) {
|
|
917
|
+
// A verdict for an event we did not send. Nothing to settle; worth seeing on the rail.
|
|
918
|
+
syncDebug("event lane: ack for an event that was not in this batch", { eventId: ack.eventId });
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
const verdict: EventLaneVerdict = {
|
|
922
|
+
eventId: ack.eventId,
|
|
923
|
+
stream: row.stream,
|
|
924
|
+
status: ack.status,
|
|
925
|
+
...(ack.reason != null ? { reason: ack.reason } : {}),
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
if (ack.status === "deferred") {
|
|
929
|
+
// NOT terminal (ADR-0053 decision 3): an Event stream the server does not yet know is ordinary
|
|
930
|
+
// rollout skew, and deleting those events would be data loss on a normal path.
|
|
931
|
+
await deferEvent(row, ack.reason);
|
|
932
|
+
deferred.push(verdict);
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
deletable.push(ack.eventId);
|
|
937
|
+
if (ack.status !== "acked") {
|
|
938
|
+
// `refused` (gating) and `rejected` (schema-invalid/oversized for a KNOWN stream) are terminal and
|
|
939
|
+
// reported: once the row is deleted the Outbox can no longer answer what happened to it.
|
|
940
|
+
terminal.push(verdict);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// An envelope the server answered for at all is settled; one it did not answer for stays put and rides
|
|
945
|
+
// the next batch (the server owes a verdict per well-formed envelope, so this is a server bug, not a
|
|
946
|
+
// reason to discard).
|
|
947
|
+
await deleteEvents(deletable);
|
|
948
|
+
return { terminal, deferred, settledCount: deletable.length + deferred.length };
|
|
949
|
+
};
|
|
950
|
+
|
|
951
|
+
let flushChain: Promise<void> = Promise.resolve();
|
|
952
|
+
|
|
953
|
+
const runFlush = async (): Promise<void> => {
|
|
954
|
+
if (!hasStreams) {
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
if (batchAttempt > 0 && clockMs() < batchRetryAtMs) {
|
|
958
|
+
syncDebug("event lane: flush skipped (batch-level backoff)", {
|
|
959
|
+
retryInMs: batchRetryAtMs - clockMs(),
|
|
960
|
+
attempt: batchAttempt,
|
|
961
|
+
});
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
const terminal: EventLaneVerdict[] = [];
|
|
966
|
+
const deferred: EventLaneVerdict[] = [];
|
|
967
|
+
let backoff: EventLaneBackoffTransition | undefined;
|
|
968
|
+
// Rows this pass already deferred. Their backoff normally lifts them out of the eligible window, but a
|
|
969
|
+
// zero-ish configured backoff (or a frozen clock) would leave them selectable — and re-posting a row the
|
|
970
|
+
// server just deferred is a spin, not a retry. One pass, one attempt per row.
|
|
971
|
+
const deferredThisPass = new Set<string>();
|
|
972
|
+
|
|
973
|
+
// Drain in slices until nothing more is eligible. Progress is guaranteed: every settled row leaves the
|
|
974
|
+
// eligible set — deleted on a terminal verdict, or parked by its deferred backoff (and, belt and braces,
|
|
975
|
+
// by `deferredThisPass`) — so a slice that settles nothing ends the pass.
|
|
976
|
+
for (;;) {
|
|
977
|
+
const rows = (await readEligibleRows(batchSize)).filter((row) => !deferredThisPass.has(row.eventId));
|
|
978
|
+
if (rows.length === 0) {
|
|
979
|
+
break;
|
|
980
|
+
}
|
|
981
|
+
const batch = assembleBatch(rows);
|
|
982
|
+
if (batch.envelopes.length === 0) {
|
|
983
|
+
// Every eligible row was held out by a per-stream cap this pass; the next pass reorders nothing but
|
|
984
|
+
// the caps reset, so stop rather than spin.
|
|
985
|
+
break;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
let acks: EventAck[];
|
|
989
|
+
try {
|
|
990
|
+
acks = await postBatch(batch.envelopes);
|
|
991
|
+
} catch (error) {
|
|
992
|
+
const status = error instanceof EventRequestError ? error.status : null;
|
|
993
|
+
const retryAfterMs = error instanceof EventRequestError ? error.retryAfterMs : null;
|
|
994
|
+
const message = error instanceof Error ? error.message : "Unknown event flush failure";
|
|
995
|
+
// Two classes only: auth (already refreshed once inside `postBatch`) and retryable. Neither
|
|
996
|
+
// deletes a row and neither counts toward any cap — the Outbox is the buffer.
|
|
997
|
+
backoff = enterBatchBackoff(message, status, retryAfterMs);
|
|
998
|
+
syncDebug("event lane: batch failed, entering backoff", {
|
|
999
|
+
status,
|
|
1000
|
+
klass: classifyEventBatchFailure(status),
|
|
1001
|
+
retryInMs: backoff.retryInMs,
|
|
1002
|
+
});
|
|
1003
|
+
break;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
const settled = await settleAcks(batch, acks);
|
|
1007
|
+
terminal.push(...settled.terminal);
|
|
1008
|
+
deferred.push(...settled.deferred);
|
|
1009
|
+
for (const verdict of settled.deferred) deferredThisPass.add(verdict.eventId);
|
|
1010
|
+
backoff = clearBatchBackoff() ?? backoff;
|
|
1011
|
+
|
|
1012
|
+
if (settled.settledCount === 0) {
|
|
1013
|
+
break;
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
await refreshDrainSignal().catch((error: unknown) => {
|
|
1018
|
+
syncDebug("event lane: drain-signal refresh failed", { error });
|
|
1019
|
+
return false;
|
|
1020
|
+
});
|
|
1021
|
+
emitReport({ terminal, deferred, ...(backoff ? { backoff } : {}) });
|
|
1022
|
+
};
|
|
1023
|
+
|
|
1024
|
+
return {
|
|
1025
|
+
hasStreams,
|
|
1026
|
+
appendEvent,
|
|
1027
|
+
flush: async () => {
|
|
1028
|
+
// Serialise passes on one chain, exactly as the mutation runtime serialises flushes: two concurrent
|
|
1029
|
+
// passes would assemble overlapping batches and double-post events.
|
|
1030
|
+
const next = flushChain.then(() => runFlush());
|
|
1031
|
+
flushChain = next.catch(() => undefined);
|
|
1032
|
+
await next;
|
|
1033
|
+
},
|
|
1034
|
+
outboxStatus: async () => ({ empty: await isOutboxEmpty() }),
|
|
1035
|
+
onOutboxStatus: (listener) => {
|
|
1036
|
+
// Current state on subscribe (never a silent subscription), delivered EXACTLY once however the race
|
|
1037
|
+
// with the runtime's first read falls: if the state is already known, deliver now; if the initial
|
|
1038
|
+
// probe is still in flight, its own transition publish reaches this listener — and the `delivered`
|
|
1039
|
+
// guard is what stops the two paths from double-firing when the probe lands mid-subscribe.
|
|
1040
|
+
let delivered = false;
|
|
1041
|
+
const deliver = (status: OutboxStatus): void => {
|
|
1042
|
+
delivered = true;
|
|
1043
|
+
listener(status);
|
|
1044
|
+
};
|
|
1045
|
+
statusListeners.add(deliver);
|
|
1046
|
+
if (currentEmpty != null) {
|
|
1047
|
+
deliver({ empty: currentEmpty });
|
|
1048
|
+
} else {
|
|
1049
|
+
void initialProbe.then(() => {
|
|
1050
|
+
if (!delivered && statusListeners.has(deliver) && currentEmpty != null) {
|
|
1051
|
+
deliver({ empty: currentEmpty });
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
return () => {
|
|
1056
|
+
statusListeners.delete(deliver);
|
|
1057
|
+
};
|
|
1058
|
+
},
|
|
1059
|
+
onEventLaneReport: (listener) => {
|
|
1060
|
+
reportListeners.add(listener);
|
|
1061
|
+
return () => {
|
|
1062
|
+
reportListeners.delete(listener);
|
|
1063
|
+
};
|
|
1064
|
+
},
|
|
1065
|
+
// Terminal, exactly like the mutation runtime's: every caller (`haltActivity`, `stop`, `destroy`) is
|
|
1066
|
+
// tearing the client down, and a later flush must NOT sneak a request out against a closing store.
|
|
1067
|
+
abortInFlight: () => disposeController.abort(),
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/** Extract the server's `message` from a non-2xx ingestion body, or undefined when it is not the toolkit's shape. */
|
|
1072
|
+
function parseBatchEventErrorMessage(body: string): string | undefined {
|
|
1073
|
+
if (body.length === 0) {
|
|
1074
|
+
return undefined;
|
|
1075
|
+
}
|
|
1076
|
+
let parsed: unknown;
|
|
1077
|
+
try {
|
|
1078
|
+
parsed = JSON.parse(body);
|
|
1079
|
+
} catch {
|
|
1080
|
+
return undefined;
|
|
1081
|
+
}
|
|
1082
|
+
const result = batchEventErrorSchema.safeParse(parsed);
|
|
1083
|
+
return result.success ? result.data.message : undefined;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// ─── The flush driver (ADR-0053 decision 3, modelled on the convergence driver) ───────────────────────
|
|
1087
|
+
|
|
1088
|
+
/** The scheduling gate the event-lane driver shares with the convergence driver (`autoSync`'s trigger). */
|
|
1089
|
+
export interface EventFlushGate {
|
|
1090
|
+
subscribe: (onSignal: () => void) => () => void;
|
|
1091
|
+
/** Whether a flush should run right now — the offline pause (ADR-0053 decision 4). */
|
|
1092
|
+
shouldFlush: () => boolean;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
export interface EventFlushDriverOptions {
|
|
1096
|
+
flush: () => Promise<void>;
|
|
1097
|
+
/** The app's online/foreground gate, when one is installed. Absent → always flush. */
|
|
1098
|
+
gate?: EventFlushGate;
|
|
1099
|
+
/** The fallback interval. Defaults to {@link DEFAULT_EVENT_FLUSH_INTERVAL_MS}. */
|
|
1100
|
+
intervalMs?: number;
|
|
1101
|
+
/** Invoked after each pass with the error it raised, or `null`. */
|
|
1102
|
+
onPass?: (error: unknown) => void;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
export interface EventFlushDriver {
|
|
1106
|
+
start: () => void;
|
|
1107
|
+
/** Stop scheduling and await any in-flight pass, so a caller can safely close the store afterwards. */
|
|
1108
|
+
stop: () => Promise<void>;
|
|
1109
|
+
/** Request a pass now — the nudge an append fires, coalesced exactly like an interval tick. */
|
|
1110
|
+
requestPass: () => void;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* Drive the Outbox flush: at most one pass in flight, a signal arriving mid-pass coalescing into a single
|
|
1115
|
+
* follow-up, an interval as the FALLBACK trigger (retries + recovery), and `requestPass` as the event-driven
|
|
1116
|
+
* path an append takes. `start()` runs a pass immediately, which is what drains events written offline after
|
|
1117
|
+
* a reconnect or a boot — no new append required.
|
|
1118
|
+
*/
|
|
1119
|
+
export function createEventFlushDriver(options: EventFlushDriverOptions): EventFlushDriver {
|
|
1120
|
+
const intervalMs = options.intervalMs ?? DEFAULT_EVENT_FLUSH_INTERVAL_MS;
|
|
1121
|
+
let unsubscribe: (() => void) | null = null;
|
|
1122
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
1123
|
+
let running = false;
|
|
1124
|
+
let queued = false;
|
|
1125
|
+
let disposed = false;
|
|
1126
|
+
let currentPass: Promise<void> | null = null;
|
|
1127
|
+
|
|
1128
|
+
const runPass = async (): Promise<void> => {
|
|
1129
|
+
if (disposed || running) {
|
|
1130
|
+
if (!disposed) {
|
|
1131
|
+
queued = true;
|
|
1132
|
+
}
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if (options.gate && !options.gate.shouldFlush()) {
|
|
1136
|
+
// Offline/backgrounded: the Outbox keeps absorbing appends and the next online signal (or interval
|
|
1137
|
+
// tick) drains it. Nothing is lost by not trying.
|
|
1138
|
+
syncDebug("event lane: flush pass skipped (offline/backgrounded)");
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
running = true;
|
|
1143
|
+
let error: unknown = null;
|
|
1144
|
+
const pass = (async () => {
|
|
1145
|
+
try {
|
|
1146
|
+
await options.flush();
|
|
1147
|
+
} catch (passError) {
|
|
1148
|
+
error = passError;
|
|
1149
|
+
}
|
|
1150
|
+
})();
|
|
1151
|
+
currentPass = pass;
|
|
1152
|
+
await pass;
|
|
1153
|
+
running = false;
|
|
1154
|
+
currentPass = null;
|
|
1155
|
+
options.onPass?.(error);
|
|
1156
|
+
|
|
1157
|
+
if (queued && !disposed) {
|
|
1158
|
+
queued = false;
|
|
1159
|
+
void runPass();
|
|
1160
|
+
}
|
|
1161
|
+
};
|
|
1162
|
+
|
|
1163
|
+
return {
|
|
1164
|
+
start: () => {
|
|
1165
|
+
if (timer !== null || disposed) {
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
unsubscribe =
|
|
1169
|
+
options.gate?.subscribe(() => {
|
|
1170
|
+
void runPass();
|
|
1171
|
+
}) ?? null;
|
|
1172
|
+
timer = setInterval(() => {
|
|
1173
|
+
void runPass();
|
|
1174
|
+
}, intervalMs);
|
|
1175
|
+
// Boot/reconnect drain (ADR-0053): a pass runs immediately, so events written offline leave the
|
|
1176
|
+
// Outbox without waiting for a new append.
|
|
1177
|
+
void runPass();
|
|
1178
|
+
},
|
|
1179
|
+
stop: async () => {
|
|
1180
|
+
disposed = true;
|
|
1181
|
+
queued = false;
|
|
1182
|
+
unsubscribe?.();
|
|
1183
|
+
unsubscribe = null;
|
|
1184
|
+
if (timer !== null) {
|
|
1185
|
+
clearInterval(timer);
|
|
1186
|
+
timer = null;
|
|
1187
|
+
}
|
|
1188
|
+
await currentPass;
|
|
1189
|
+
},
|
|
1190
|
+
requestPass: () => {
|
|
1191
|
+
void runPass();
|
|
1192
|
+
},
|
|
1193
|
+
};
|
|
1194
|
+
}
|