@pgxsinkit/server 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/cli/generate.d.ts +20 -0
- package/dist/cli/generate.d.ts.map +1 -1
- package/dist/events/consumer.d.ts +282 -0
- package/dist/events/consumer.d.ts.map +1 -0
- package/dist/events/ddl.d.ts +40 -0
- package/dist/events/ddl.d.ts.map +1 -0
- package/dist/events/identity.d.ts +26 -0
- package/dist/events/identity.d.ts.map +1 -0
- package/dist/events/pgmq-queue.d.ts +41 -0
- package/dist/events/pgmq-queue.d.ts.map +1 -0
- package/dist/events/queue.d.ts +119 -0
- package/dist/events/queue.d.ts.map +1 -0
- package/dist/events/route.d.ts +99 -0
- package/dist/events/route.d.ts.map +1 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1022 -54
- package/dist/index.js.map +13 -7
- package/dist/migrations/utilities.d.ts.map +1 -1
- package/dist/mutations/plpgsql-apply.d.ts +30 -9
- package/dist/mutations/plpgsql-apply.d.ts.map +1 -1
- package/dist/mutations/route.d.ts +27 -1
- package/dist/mutations/route.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +195 -7
- package/src/cli/generate.ts +195 -45
- package/src/events/consumer.ts +831 -0
- package/src/events/ddl.ts +79 -0
- package/src/events/identity.ts +86 -0
- package/src/events/pgmq-queue.ts +237 -0
- package/src/events/queue.ts +159 -0
- package/src/events/route.ts +488 -0
- package/src/index.ts +124 -0
- package/src/migrations/utilities.ts +22 -2
- package/src/mutations/plpgsql-apply.ts +357 -38
- package/src/mutations/route.ts +93 -16
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getSyncRegistryStreams,
|
|
3
|
+
type EventQueueMessage,
|
|
4
|
+
type StampedEvent,
|
|
5
|
+
type SyncTableRegistry,
|
|
6
|
+
} from "@pgxsinkit/contracts";
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
MalformedEventQueueMessageError,
|
|
10
|
+
type DeliveredEventMessage,
|
|
11
|
+
type EventQueue,
|
|
12
|
+
type EventQueueReceipt,
|
|
13
|
+
} from "./queue";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The **Event lane**'s consumer runner (ADR-0053 decisions 6 and 7): the library defines it, the app hosts it.
|
|
17
|
+
*
|
|
18
|
+
* `defineEventConsumer` returns a `start()`/`stop()` handle the app runs in its OWN long-lived Bun process —
|
|
19
|
+
* the toolkit's first long-lived server artifact, deliberately separate from `createSyncServer`'s
|
|
20
|
+
* zero-startup-query serverless posture. There is no supervisor, no CLI entrypoint, no daemon and no signal
|
|
21
|
+
* handling here: the app owns its process lifecycle and calls `stop()` from wherever it already handles
|
|
22
|
+
* shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside
|
|
23
|
+
* `start()`.
|
|
24
|
+
*
|
|
25
|
+
* One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in
|
|
26
|
+
* one stream must never head-of-line-block another), so small deployments run one process and large ones split
|
|
27
|
+
* `streams` across processes.
|
|
28
|
+
*
|
|
29
|
+
* **Pacing is adaptive interval polling, and it is INTERNAL** (ADR-0053 decision 7 — out of consumer-app design
|
|
30
|
+
* space by ratified requirement; only the floor/ceiling/factor are exposed as tuning, never as contract):
|
|
31
|
+
*
|
|
32
|
+
* - a NON-EMPTY read is followed by an immediate re-read, so a backlog drains back-to-back;
|
|
33
|
+
* - consecutive EMPTY reads grow the wait from a floor ({@link DEFAULT_EVENT_POLL_FLOOR_MS}) toward an idle
|
|
34
|
+
* ceiling ({@link DEFAULT_EVENT_POLL_CEILING_MS}) by {@link DEFAULT_EVENT_POLL_FACTOR};
|
|
35
|
+
* - one non-empty read resets the wait to the floor.
|
|
36
|
+
*
|
|
37
|
+
* LISTEN/NOTIFY and `pgmq.read_with_poll` long-polling are REJECTED as wake mechanisms (ADR-0053, maintainer
|
|
38
|
+
* decision): Bun's native `SQL` — the sanctioned Postgres driver — has no LISTEN/NOTIFY, and both mechanisms
|
|
39
|
+
* hold a connection per stream through the transaction poolers the consumers' stacks run behind. Because
|
|
40
|
+
* pacing is internal, the mechanism can change later without any contract change.
|
|
41
|
+
*
|
|
42
|
+
* **Leases are RENEWED while a read is being worked through; a thrown sub-batch's lease is deliberately left
|
|
43
|
+
* to lapse** (ADR-0053 decision 7: visibility renewal is internal). One read makes up to `batchSize` messages
|
|
44
|
+
* invisible at once, so the timeout cannot be "the processing budget": ten ordinary ten-second callbacks
|
|
45
|
+
* would outlive a 60-second window for the later messages, and in a documented multi-runner deployment
|
|
46
|
+
* another process would pick them up while the first is still working toward them. So for as long as a read
|
|
47
|
+
* is in flight the runner extends EVERY not-yet-settled receipt of that read — the one running plus the ones
|
|
48
|
+
* still queued behind it — every `visibilityTimeoutSeconds / 2`. Renewal is best-effort: a failure is
|
|
49
|
+
* warn-logged and the loop carries on, because redelivery is the safety net it would fall back on anyway.
|
|
50
|
+
*
|
|
51
|
+
* `visibilityTimeoutSeconds` therefore means two retry-shaped things, never a budget:
|
|
52
|
+
*
|
|
53
|
+
* - **the redelivery delay of a FAILED sub-batch.** A callback that throws is not acked AND is dropped from
|
|
54
|
+
* renewal immediately, so its lease lapses and the queue redelivers it with an incremented `deliveryCount`.
|
|
55
|
+
* That lapse IS the retry pacing — the runner never sleeps "on behalf of" a failed message, and if a
|
|
56
|
+
* backend ever wants exponential redelivery backoff it belongs INSIDE that backend, behind the
|
|
57
|
+
* {@link EventQueue} seam, so the runner stays backend-agnostic;
|
|
58
|
+
* - **the crash-recovery bound.** A runner that dies takes its renewals with it, so everything it held comes
|
|
59
|
+
* back one timeout later.
|
|
60
|
+
*
|
|
61
|
+
* **A graceful stop does not cancel renewal — it narrows it.** `stop()` starts no further read and no further
|
|
62
|
+
* callback, but the callbacks already in flight are AWAITED and then acked, so their receipts must stay
|
|
63
|
+
* invisible until they settle: cancelling renewal at `stop()` would hand a second runner the very message
|
|
64
|
+
* this one is deliberately finishing, on every ordinary SIGTERM/rollout. What IS released at `stop()` is the
|
|
65
|
+
* rest of that read — the messages no callback has started — which drop out of the renewal set so their
|
|
66
|
+
* leases lapse and the queue redelivers them promptly. `stop()` therefore resolves only once every in-flight
|
|
67
|
+
* callback has settled AND its renewal task has shut down.
|
|
68
|
+
*
|
|
69
|
+
* **The SECOND pacing mode: `drainOnce()`, for hosts that cannot hold a process** (ADR-0053 amendment,
|
|
70
|
+
* 2026-08-02). Everything above describes the primary mode. A serverless-only deployment — managed
|
|
71
|
+
* Supabase, whose edge functions are the only compute — has nowhere to put a `start()`; its queue would
|
|
72
|
+
* simply never drain. So the SAME handle also answers `drainOnce({ budgetMs })`: one bounded pass that
|
|
73
|
+
* reads/delivers/acks through the identical internals until every stream reads empty or the wall-clock
|
|
74
|
+
* budget runs out. Nothing about the delivery contract moves — at-least-once, batch-internal order only,
|
|
75
|
+
* dead-lettering to the backend's archive are all the same code — because pacing was internal from the
|
|
76
|
+
* start (decision 7), which is exactly what makes this a HOSTING addition rather than a contract change.
|
|
77
|
+
* The long-lived runner remains the primary mode; `drainOnce` is what a scheduled invocation calls.
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/** Max messages (each ONE single-stream sub-batch) a single read delivers, when the app sets nothing. */
|
|
81
|
+
export const DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;
|
|
82
|
+
/**
|
|
83
|
+
* How long a delivered sub-batch stays invisible, when the app sets nothing — and how long the runner extends
|
|
84
|
+
* it by on each renewal (it renews at half this). Healthy long processing is covered by renewal, so this is
|
|
85
|
+
* the REDELIVERY DELAY of a sub-batch whose callback threw and the crash-recovery bound, not a budget: it
|
|
86
|
+
* wants to sit above a single callback's worst case (too short redelivers a callback that is merely slower
|
|
87
|
+
* than one renewal interval), never above the whole batch's.
|
|
88
|
+
*/
|
|
89
|
+
export const DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;
|
|
90
|
+
/** Deliveries a sub-batch gets before a further callback failure dead-letters it, when the app sets nothing. */
|
|
91
|
+
export const DEFAULT_EVENT_MAX_ATTEMPTS = 5;
|
|
92
|
+
/** The adaptive poll's floor — the wait after the FIRST empty read (ADR-0053 decision 7: ~250 ms). */
|
|
93
|
+
export const DEFAULT_EVENT_POLL_FLOOR_MS = 250;
|
|
94
|
+
/** The adaptive poll's idle ceiling — the longest an idle stream ever waits between reads. */
|
|
95
|
+
export const DEFAULT_EVENT_POLL_CEILING_MS = 5_000;
|
|
96
|
+
/** How fast consecutive empty reads grow the wait from the floor toward the ceiling. */
|
|
97
|
+
export const DEFAULT_EVENT_POLL_FACTOR = 2;
|
|
98
|
+
/**
|
|
99
|
+
* The wall-clock budget one {@link EventConsumer.drainOnce} pass gets, when the caller sets nothing.
|
|
100
|
+
*
|
|
101
|
+
* **Set it under your platform's invocation wall-clock cap**, with head-room for one callback: the budget is
|
|
102
|
+
* only ever checked BETWEEN sub-batches, so a pass can overrun it by however long the callback that was
|
|
103
|
+
* already running takes. 25 s suits the common serverless caps (Supabase Edge, Vercel, Cloud Run jobs); a
|
|
104
|
+
* platform with a tighter cap wants a tighter budget, and a generous one (a cron container) can raise it.
|
|
105
|
+
*/
|
|
106
|
+
export const DEFAULT_EVENT_DRAIN_BUDGET_MS = 25_000;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Adaptive-poll tuning. Defaults are the ADR's; they are TUNING, not contract — the pacing mechanism itself is
|
|
110
|
+
* internal and may change.
|
|
111
|
+
*/
|
|
112
|
+
export interface EventConsumerPollOptions {
|
|
113
|
+
/** The wait after the first empty read. Defaults to {@link DEFAULT_EVENT_POLL_FLOOR_MS}. */
|
|
114
|
+
floorMs?: number;
|
|
115
|
+
/** The longest wait an idle stream reaches. Defaults to {@link DEFAULT_EVENT_POLL_CEILING_MS}. */
|
|
116
|
+
ceilingMs?: number;
|
|
117
|
+
/** The growth factor per consecutive empty read. Defaults to {@link DEFAULT_EVENT_POLL_FACTOR}. */
|
|
118
|
+
factor?: number;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** One callback invocation: exactly ONE delivered queue message, i.e. one single-stream sub-batch. */
|
|
122
|
+
export interface EventConsumerBatch {
|
|
123
|
+
/** The Event stream these events were appended under. */
|
|
124
|
+
stream: string;
|
|
125
|
+
/**
|
|
126
|
+
* The stamped envelopes, EXACTLY as the ingestion endpoint enqueued them (ADR-0053 decision 5) — in append
|
|
127
|
+
* order within this sub-batch. Across sub-batches there is no ordering promise (decision 6).
|
|
128
|
+
*/
|
|
129
|
+
events: readonly StampedEvent[];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The consumer callback. Returning (resolving) ACKS the sub-batch; THROWING retries it — the message stays
|
|
134
|
+
* invisible until its visibility timeout lapses and the queue redelivers it.
|
|
135
|
+
*
|
|
136
|
+
* It MUST be idempotent (ADR-0053 decision 6, at-least-once): the blessed pattern is deduping on `eventId`
|
|
137
|
+
* against the app's own durable store, which composes to effectively-exactly-once.
|
|
138
|
+
*/
|
|
139
|
+
export type EventConsumerCallback = (batch: EventConsumerBatch) => void | Promise<void>;
|
|
140
|
+
|
|
141
|
+
/** What {@link DefineEventConsumerOptions.onDeadLetter} is told about a sub-batch the runner gave up on. */
|
|
142
|
+
export interface EventDeadLetterReport {
|
|
143
|
+
stream: string;
|
|
144
|
+
/** Why it was dead-lettered — the same reason recorded in the backend's dead-letter storage. */
|
|
145
|
+
reason: string;
|
|
146
|
+
/** Deliveries this message had received. `0` when the body was unreadable (nothing was ever delivered from it). */
|
|
147
|
+
attempts: number;
|
|
148
|
+
/** The receipt it was dead-lettered under — always present, including for an unparseable body. */
|
|
149
|
+
receipt: EventQueueReceipt;
|
|
150
|
+
/** The message, when it was readable. Absent for a malformed body (that is exactly what could not be parsed). */
|
|
151
|
+
message?: EventQueueMessage;
|
|
152
|
+
/** The error behind it: the callback's throw, or the {@link MalformedEventQueueMessageError}. */
|
|
153
|
+
cause?: unknown;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never
|
|
158
|
+
* lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.
|
|
159
|
+
*/
|
|
160
|
+
export type EventConsumerSleep = (ms: number, signal: AbortSignal) => Promise<void>;
|
|
161
|
+
|
|
162
|
+
/** What {@link EventConsumer.drainOnce} is tuned with. */
|
|
163
|
+
export interface EventDrainOptions {
|
|
164
|
+
/**
|
|
165
|
+
* The pass's wall-clock budget. Defaults to {@link DEFAULT_EVENT_DRAIN_BUDGET_MS}. Checked between
|
|
166
|
+
* sub-batches only, never inside a callback — so size it under the invocation's cap with head-room for
|
|
167
|
+
* one callback's worst case.
|
|
168
|
+
*/
|
|
169
|
+
budgetMs?: number;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** What one {@link EventConsumer.drainOnce} pass reports back. Counts are SUB-BATCHES (one queue message,
|
|
173
|
+
* one callback invocation), the unit the queue and the dead-letter archive both work in. */
|
|
174
|
+
export interface EventDrainSummary {
|
|
175
|
+
/**
|
|
176
|
+
* Sub-batches whose callback completed during this pass. An ack that then failed still counts — the work
|
|
177
|
+
* was delivered, and at-least-once means it may be delivered again later (the callback is idempotent).
|
|
178
|
+
*/
|
|
179
|
+
delivered: number;
|
|
180
|
+
/** Sub-batches this pass moved to the backend's dead-letter storage. */
|
|
181
|
+
deadLettered: number;
|
|
182
|
+
/**
|
|
183
|
+
* `true` when every configured Event stream read empty before the budget ran out — the queue is drained
|
|
184
|
+
* as far as this pass can see.
|
|
185
|
+
*
|
|
186
|
+
* `false` means the pass ended with work possibly still queued: the budget cut it short, or a stream's
|
|
187
|
+
* read faulted. It is the caller's signal that another tick has something to do — a scheduler that
|
|
188
|
+
* chains passes should invoke again promptly rather than waiting out its full period.
|
|
189
|
+
*/
|
|
190
|
+
empty: boolean;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry> {
|
|
194
|
+
/** The sync registry whose `streams` this runner consumes. */
|
|
195
|
+
registry: TRegistry;
|
|
196
|
+
/**
|
|
197
|
+
* The queue to consume from — REQUIRED, and the reason the runner is backend-agnostic by construction. The
|
|
198
|
+
* ordinary wiring is `createPgmqEventQueue({ db })` with the app's own drizzle handle; constructing it here
|
|
199
|
+
* from a `db` option would bake the shipped backend into the runner for one line of ergonomics.
|
|
200
|
+
*/
|
|
201
|
+
queue: EventQueue;
|
|
202
|
+
callback: EventConsumerCallback;
|
|
203
|
+
/**
|
|
204
|
+
* Narrow to a subset of the registered Event streams — the knob that splits streams across processes.
|
|
205
|
+
* Defaults to ALL registered streams. An unknown name is a definition-time throw (fail-closed): a runner
|
|
206
|
+
* that silently consumed nothing is the failure mode this forbids.
|
|
207
|
+
*/
|
|
208
|
+
streams?: readonly string[];
|
|
209
|
+
/** Max messages per read. Defaults to {@link DEFAULT_EVENT_CONSUMER_BATCH_SIZE}. */
|
|
210
|
+
batchSize?: number;
|
|
211
|
+
/**
|
|
212
|
+
* The delivered-message invisibility window, renewed at half of it while the runner is still working
|
|
213
|
+
* through a read. Defaults to {@link DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS}. Size it above ONE
|
|
214
|
+
* callback's worst case (renewal covers the rest of the batch), not above the whole batch's.
|
|
215
|
+
*/
|
|
216
|
+
visibilityTimeoutSeconds?: number;
|
|
217
|
+
/**
|
|
218
|
+
* Max CONCURRENT callback invocations per Event stream. Defaults to `1` (strictly sequential). Values above 1
|
|
219
|
+
* are safe for the idempotent callback the lane already requires: ADR-0053 decision 6 disclaims any ordering
|
|
220
|
+
* across sub-batches precisely so concurrency is available. Reads stay serial — only the callbacks of one
|
|
221
|
+
* delivered read run in parallel.
|
|
222
|
+
*/
|
|
223
|
+
concurrency?: number;
|
|
224
|
+
/**
|
|
225
|
+
* Deliveries a sub-batch gets before a further callback failure dead-letters it. Defaults to
|
|
226
|
+
* {@link DEFAULT_EVENT_MAX_ATTEMPTS}. A malformed body never gets attempts — it dead-letters on sight.
|
|
227
|
+
*/
|
|
228
|
+
maxAttempts?: number;
|
|
229
|
+
/** Adaptive-poll tuning. See {@link EventConsumerPollOptions}. */
|
|
230
|
+
poll?: EventConsumerPollOptions;
|
|
231
|
+
/**
|
|
232
|
+
* Notified for every dead-lettered sub-batch. The runner ALSO warn-logs each one unconditionally: loudness is
|
|
233
|
+
* the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.
|
|
234
|
+
*/
|
|
235
|
+
onDeadLetter?: (report: EventDeadLetterReport) => void;
|
|
236
|
+
/** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */
|
|
237
|
+
sleep?: EventConsumerSleep;
|
|
238
|
+
/** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */
|
|
239
|
+
now?: () => number;
|
|
240
|
+
/**
|
|
241
|
+
* @internal The injectable RENEWAL wait, deliberately a second seam rather than `sleep`: the two cadences
|
|
242
|
+
* are independent (one paces reads, one paces lease renewal) and sharing one would make every pacing
|
|
243
|
+
* assertion depend on renewal timing. Defaults to `setTimeout`.
|
|
244
|
+
*/
|
|
245
|
+
renewalSleep?: EventConsumerSleep;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export interface EventConsumer {
|
|
249
|
+
/**
|
|
250
|
+
* Begin every stream's loop. Idempotent; a no-op after {@link EventConsumer.stop}. Throws while a
|
|
251
|
+
* {@link EventConsumer.drainOnce} pass is in flight — one handle drives one pacing mode at a time.
|
|
252
|
+
*/
|
|
253
|
+
start: () => void;
|
|
254
|
+
/**
|
|
255
|
+
* Graceful stop: no new reads, no new callbacks, in-flight callbacks are awaited (and their leases KEPT
|
|
256
|
+
* renewed until they ack or dead-letter), and the promise resolves when every loop — and every renewal
|
|
257
|
+
* task it still owned — is quiet. Safe to call twice (the second call awaits the first). Messages of an
|
|
258
|
+
* in-progress read whose callback had not started are released at once: they stop being renewed and are
|
|
259
|
+
* left unacked, so at-least-once redelivers them as soon as their lease lapses.
|
|
260
|
+
*
|
|
261
|
+
* A `drainOnce` pass in flight is treated the same way: it starts no further read, finishes the callback
|
|
262
|
+
* it is on, and `stop()` resolves once it has.
|
|
263
|
+
*/
|
|
264
|
+
stop: () => Promise<void>;
|
|
265
|
+
/**
|
|
266
|
+
* One bounded drain pass — the pacing mode for a host that cannot hold a process (ADR-0053 amendment,
|
|
267
|
+
* 2026-08-02).
|
|
268
|
+
*
|
|
269
|
+
* It walks every configured Event stream, read → deliver → ack, and keeps going until EITHER every stream
|
|
270
|
+
* has returned an empty read OR the wall-clock budget is spent. Same internals as the loop mode
|
|
271
|
+
* throughout: the same read/deliver/ack path, the same lease renewal while a callback runs, the same
|
|
272
|
+
* per-sub-batch retry-by-lapsing-lease, the same dead-lettering after `maxAttempts` with the same
|
|
273
|
+
* `onDeadLetter` hook and unconditional warn log. It never sleeps: a stream that reads empty is finished
|
|
274
|
+
* for this pass, and there is no adaptive interval to wait out.
|
|
275
|
+
*
|
|
276
|
+
* **The budget is checked BETWEEN sub-batches, never inside one.** A callback already running is awaited
|
|
277
|
+
* and acked exactly as the runner would (its lease stays renewed throughout), and no new read starts once
|
|
278
|
+
* the budget is gone — so a pass can overrun its budget by one callback, and `budgetMs` must leave
|
|
279
|
+
* head-room for that under the platform's invocation cap. A sub-batch whose callback THROWS near the
|
|
280
|
+
* budget edge is not special-cased: it is left unacked and dropped from renewal, its lease lapses, and the
|
|
281
|
+
* queue redelivers it on a later pass with an incremented delivery count. That is at-least-once working as
|
|
282
|
+
* designed, not a lost event — and it is why the callback must be idempotent.
|
|
283
|
+
*
|
|
284
|
+
* **Hosting it.** Wire a SCHEDULED invocation (a platform cron, e.g. every 10 s) that calls `drainOnce`
|
|
285
|
+
* and, optionally, an ingest-side nudge (`createSyncServer({ onEventsEnqueued })` firing a
|
|
286
|
+
* fetch-and-forget at the same endpoint) so an interactive append is drained in milliseconds instead of
|
|
287
|
+
* waiting for the next tick. The **schedule is the delivery guarantee; the nudge is only latency** — a
|
|
288
|
+
* lost nudge costs nothing but time. Overlapping invocations are SAFE: two processes reading the same
|
|
289
|
+
* queue are arbitrated by the visibility timeout, exactly as two long-lived runners would be. (Two passes
|
|
290
|
+
* on ONE handle are not — that is a bug, and throws; see below.)
|
|
291
|
+
*
|
|
292
|
+
* **One handle, one pacing mode.** Throws if `start()` is live, if another `drainOnce` is already in
|
|
293
|
+
* flight on this handle, or if the handle has been stopped — the lifecycle is one-way, so the next drain
|
|
294
|
+
* builds a fresh `defineEventConsumer` (construction is query-free, so that costs nothing).
|
|
295
|
+
*/
|
|
296
|
+
drainOnce: (options?: EventDrainOptions) => Promise<EventDrainSummary>;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The adaptive wait for `idleCount` CONSECUTIVE unproductive reads (an empty read or a queue fault), clamped to
|
|
301
|
+
* the ceiling. `idleCount` is 1 for the first one; a productive read resets it to 0 and re-reads immediately.
|
|
302
|
+
*/
|
|
303
|
+
export function computeEventPollWaitMs(idleCount: number, options: EventConsumerPollOptions = {}): number {
|
|
304
|
+
const floorMs = options.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS;
|
|
305
|
+
const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS;
|
|
306
|
+
const factor = options.factor ?? DEFAULT_EVENT_POLL_FACTOR;
|
|
307
|
+
const exponent = Math.max(idleCount - 1, 0);
|
|
308
|
+
return Math.min(Math.round(floorMs * factor ** exponent), ceilingMs);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** The production wait: a `setTimeout` that is CLEARED on abort, so `stop()` never leaves a timer holding the process open. */
|
|
312
|
+
const abortableSleep: EventConsumerSleep = (ms, signal) =>
|
|
313
|
+
new Promise<void>((resolve) => {
|
|
314
|
+
if (signal.aborted) {
|
|
315
|
+
resolve();
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
let handle: ReturnType<typeof setTimeout> | undefined;
|
|
319
|
+
const finish = (): void => {
|
|
320
|
+
if (handle !== undefined) {
|
|
321
|
+
clearTimeout(handle);
|
|
322
|
+
}
|
|
323
|
+
signal.removeEventListener("abort", finish);
|
|
324
|
+
resolve();
|
|
325
|
+
};
|
|
326
|
+
handle = setTimeout(finish, ms);
|
|
327
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
function assertPositive(label: string, value: number, minimum: number): number {
|
|
331
|
+
if (!Number.isFinite(value) || value < minimum) {
|
|
332
|
+
throw new Error(
|
|
333
|
+
`pgxsinkit: defineEventConsumer's \`${label}\` must be a finite number >= ${minimum} (got ${value}).`,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
return value;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
|
|
340
|
+
options: DefineEventConsumerOptions<TRegistry>,
|
|
341
|
+
): EventConsumer {
|
|
342
|
+
// ─── Definition-time resolution (fail-closed, and query-free) ────────────────────────────────────────
|
|
343
|
+
const registered = getSyncRegistryStreams(options.registry) ?? {};
|
|
344
|
+
const registeredNames = Object.keys(registered);
|
|
345
|
+
if (registeredNames.length === 0) {
|
|
346
|
+
throw new Error(
|
|
347
|
+
"pgxsinkit: this registry registers no Event streams, so there is nothing for a consumer runner to " +
|
|
348
|
+
"consume. Register one with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.",
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
let streams: string[];
|
|
353
|
+
if (options.streams) {
|
|
354
|
+
const unknown = options.streams.filter((stream) => !Object.hasOwn(registered, stream));
|
|
355
|
+
if (unknown.length > 0) {
|
|
356
|
+
// Every offender is named: a typo'd stream on a runner would otherwise present as "the events never
|
|
357
|
+
// arrive", which is the most expensive shape of silence in the lane.
|
|
358
|
+
throw new Error(
|
|
359
|
+
`pgxsinkit: defineEventConsumer was asked for Event stream(s) [${unknown.join(", ")}] this registry ` +
|
|
360
|
+
`does not register — it registers [${registeredNames.join(", ")}].`,
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
streams = [...new Set(options.streams)];
|
|
364
|
+
if (streams.length === 0) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
"pgxsinkit: defineEventConsumer was given an empty `streams` list. Omit it to consume every registered " +
|
|
367
|
+
"Event stream, or name at least one.",
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
} else {
|
|
371
|
+
streams = registeredNames;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const batchSize = assertPositive("batchSize", options.batchSize ?? DEFAULT_EVENT_CONSUMER_BATCH_SIZE, 1);
|
|
375
|
+
const visibilityTimeoutSeconds = assertPositive(
|
|
376
|
+
"visibilityTimeoutSeconds",
|
|
377
|
+
options.visibilityTimeoutSeconds ?? DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
|
|
378
|
+
1,
|
|
379
|
+
);
|
|
380
|
+
const concurrency = assertPositive("concurrency", options.concurrency ?? 1, 1);
|
|
381
|
+
const maxAttempts = assertPositive("maxAttempts", options.maxAttempts ?? DEFAULT_EVENT_MAX_ATTEMPTS, 1);
|
|
382
|
+
const poll = options.poll ?? {};
|
|
383
|
+
const floorMs = assertPositive("poll.floorMs", poll.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS, 0);
|
|
384
|
+
const ceilingMs = assertPositive("poll.ceilingMs", poll.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS, floorMs);
|
|
385
|
+
const factor = assertPositive("poll.factor", poll.factor ?? DEFAULT_EVENT_POLL_FACTOR, 1);
|
|
386
|
+
const pollOptions: EventConsumerPollOptions = { floorMs, ceilingMs, factor };
|
|
387
|
+
|
|
388
|
+
const queue = options.queue;
|
|
389
|
+
const sleep = options.sleep ?? abortableSleep;
|
|
390
|
+
const renewalSleep = options.renewalSleep ?? abortableSleep;
|
|
391
|
+
const now = options.now ?? Date.now;
|
|
392
|
+
/** Renew at HALF the window: one missed renewal still leaves a full half-window of head-room. */
|
|
393
|
+
const renewalIntervalMs = Math.max(1, Math.floor((visibilityTimeoutSeconds * 1000) / 2));
|
|
394
|
+
|
|
395
|
+
// ─── Lifecycle state ─────────────────────────────────────────────────────────────────────────────────
|
|
396
|
+
const stopController = new AbortController();
|
|
397
|
+
let started = false;
|
|
398
|
+
let stopping = false;
|
|
399
|
+
let loops: Promise<void>[] = [];
|
|
400
|
+
let stopPromise: Promise<void> | null = null;
|
|
401
|
+
/** The in-flight bounded drain, if any — the second pacing mode's whole lifecycle state. */
|
|
402
|
+
let activeDrain: Promise<EventDrainSummary> | null = null;
|
|
403
|
+
/**
|
|
404
|
+
* The counters of the drain pass in flight, or `null` in loop mode. The settle points below feed it
|
|
405
|
+
* rather than returning counts, so `drainOnce` reports on the SAME delivery path the runner uses instead
|
|
406
|
+
* of a parallel one. Exactly one pass can be in flight (the mode is mutually exclusive), so one slot is
|
|
407
|
+
* all this needs.
|
|
408
|
+
*/
|
|
409
|
+
let drainStats: { delivered: number; deadLettered: number } | null = null;
|
|
410
|
+
|
|
411
|
+
// ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────
|
|
412
|
+
const reportDeadLetter = (report: EventDeadLetterReport): void => {
|
|
413
|
+
// Unconditional, and deliberately not the client report surface's "warn only when nobody subscribed"
|
|
414
|
+
// rule: a dead letter is rare and terminal, so it is worth a line in the operator's log even when the
|
|
415
|
+
// app also handles it.
|
|
416
|
+
console.warn(
|
|
417
|
+
`pgxsinkit: dead-lettered an event sub-batch on Event stream "${report.stream}" (receipt ${report.receipt}, ` +
|
|
418
|
+
`${report.attempts} delivery attempt(s)) — ${report.reason}. It is in the queue's dead-letter storage; ` +
|
|
419
|
+
"requeue it deliberately with `requeueDeadLetter` once the cause is fixed.",
|
|
420
|
+
report.cause,
|
|
421
|
+
);
|
|
422
|
+
if (!options.onDeadLetter) {
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
try {
|
|
426
|
+
options.onDeadLetter(report);
|
|
427
|
+
} catch (error) {
|
|
428
|
+
console.error("pgxsinkit: the `onDeadLetter` hook threw; the message is dead-lettered regardless", error);
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
/** Move one message to dead-letter storage and report it. Resolves `false` when the QUEUE refused the move. */
|
|
433
|
+
const deadLetter = async (
|
|
434
|
+
stream: string,
|
|
435
|
+
receipt: EventQueueReceipt,
|
|
436
|
+
attempts: number,
|
|
437
|
+
reason: string,
|
|
438
|
+
cause: unknown,
|
|
439
|
+
message?: EventQueueMessage,
|
|
440
|
+
): Promise<boolean> => {
|
|
441
|
+
try {
|
|
442
|
+
await queue.deadLetter(stream, [receipt], reason);
|
|
443
|
+
} catch (error) {
|
|
444
|
+
// The message is still queued and still invisible; it redelivers and dead-letters on a later pass.
|
|
445
|
+
console.warn(
|
|
446
|
+
`pgxsinkit: could not dead-letter message ${receipt} on Event stream "${stream}"; it stays queued and ` +
|
|
447
|
+
"will be retried",
|
|
448
|
+
error,
|
|
449
|
+
);
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
if (drainStats) {
|
|
453
|
+
drainStats.deadLettered += 1;
|
|
454
|
+
}
|
|
455
|
+
reportDeadLetter({ stream, reason, attempts, receipt, ...(message ? { message } : {}), cause });
|
|
456
|
+
return true;
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
// ─── Lease renewal (ADR-0053 decision 7: internal, and not optional) ─────────────────────────────────
|
|
460
|
+
/**
|
|
461
|
+
* Keep every UNSETTLED receipt of one read invisible for as long as that read is being worked through.
|
|
462
|
+
* Returns the stopper, which the caller awaits so no renewal outlives its read (a stray timer would hold
|
|
463
|
+
* the app's process open, and a stray extension would delay a redelivery the runner no longer wants).
|
|
464
|
+
*
|
|
465
|
+
* Its lifetime is the READ's, deliberately NOT the runner's: this task is wired to its OWN controller and
|
|
466
|
+
* never to `stopController`. A graceful stop still awaits the callbacks already in flight, so aborting
|
|
467
|
+
* renewal there would let their leases lapse mid-callback and let another runner take the work this one is
|
|
468
|
+
* finishing. `stop()` instead shrinks `unsettled` (see `processDelivered`), and the loop below exits on its
|
|
469
|
+
* own the moment that set drains.
|
|
470
|
+
*/
|
|
471
|
+
const startRenewal = (stream: string, unsettled: Set<EventQueueReceipt>): (() => Promise<void>) => {
|
|
472
|
+
const controller = new AbortController();
|
|
473
|
+
|
|
474
|
+
const task = (async () => {
|
|
475
|
+
while (!controller.signal.aborted && unsettled.size > 0) {
|
|
476
|
+
await renewalSleep(renewalIntervalMs, controller.signal);
|
|
477
|
+
if (controller.signal.aborted || unsettled.size === 0) {
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
try {
|
|
481
|
+
await queue.extendVisibility(stream, [...unsettled], visibilityTimeoutSeconds);
|
|
482
|
+
} catch (error) {
|
|
483
|
+
// Best-effort by design: the worst case of a failed renewal is the behaviour there would be with
|
|
484
|
+
// no renewal at all — the lease lapses and the sub-batch is redelivered to an idempotent callback.
|
|
485
|
+
console.warn(
|
|
486
|
+
`pgxsinkit: could not renew the visibility lease on Event stream "${stream}" (receipts ` +
|
|
487
|
+
`${[...unsettled].join(", ")}); the sub-batch may be redelivered while it is still being processed`,
|
|
488
|
+
error,
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
})();
|
|
493
|
+
|
|
494
|
+
return async () => {
|
|
495
|
+
controller.abort();
|
|
496
|
+
await task;
|
|
497
|
+
};
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
// ─── One delivered message ───────────────────────────────────────────────────────────────────────────
|
|
501
|
+
const processMessage = async (
|
|
502
|
+
stream: string,
|
|
503
|
+
delivered: DeliveredEventMessage,
|
|
504
|
+
/** Drop this message from the read's renewal set — it is settled, one way or the other. */
|
|
505
|
+
settle: () => void,
|
|
506
|
+
): Promise<void> => {
|
|
507
|
+
try {
|
|
508
|
+
await options.callback({ stream, events: delivered.message.events });
|
|
509
|
+
} catch (error) {
|
|
510
|
+
// Settled the moment it throws, and settled FIRST: a failed sub-batch's lease is deliberately allowed
|
|
511
|
+
// to lapse, because that lapse IS the retry pacing. Renewing it would postpone its own redelivery.
|
|
512
|
+
settle();
|
|
513
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
514
|
+
if (delivered.deliveryCount >= maxAttempts) {
|
|
515
|
+
await deadLetter(
|
|
516
|
+
stream,
|
|
517
|
+
delivered.receipt,
|
|
518
|
+
delivered.deliveryCount,
|
|
519
|
+
`the consumer callback failed on delivery ${delivered.deliveryCount} of ${maxAttempts}: ${detail}`,
|
|
520
|
+
error,
|
|
521
|
+
delivered.message,
|
|
522
|
+
);
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
// NOT acked, and no longer renewed: the lapsing lease IS the retry pacing (see the module note).
|
|
526
|
+
console.warn(
|
|
527
|
+
`pgxsinkit: the event consumer callback failed for Event stream "${stream}" (receipt ${delivered.receipt}, ` +
|
|
528
|
+
`delivery ${delivered.deliveryCount} of ${maxAttempts}); the sub-batch will be redelivered after its ` +
|
|
529
|
+
`${visibilityTimeoutSeconds}s visibility timeout`,
|
|
530
|
+
error,
|
|
531
|
+
);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
if (drainStats) {
|
|
536
|
+
// Counted on the callback's success, before the ack: the work was delivered either way, and an ack
|
|
537
|
+
// that fails only means at-least-once will deliver it again to an idempotent callback.
|
|
538
|
+
drainStats.delivered += 1;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
try {
|
|
542
|
+
await queue.ack(stream, [delivered.receipt]);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
// At-least-once's honest failure mode: the work succeeded but the ack did not, so the sub-batch will be
|
|
545
|
+
// redelivered. The idempotent callback the lane requires is exactly what makes that harmless.
|
|
546
|
+
console.warn(
|
|
547
|
+
`pgxsinkit: could not ack message ${delivered.receipt} on Event stream "${stream}"; it will be ` +
|
|
548
|
+
"redelivered (the callback must be idempotent)",
|
|
549
|
+
error,
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
// Settled either way: an acked message is gone, and one whose ack failed is meant to be redelivered.
|
|
553
|
+
settle();
|
|
554
|
+
};
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Process one read's messages, at most `concurrency` callbacks at a time. Never throws.
|
|
558
|
+
*
|
|
559
|
+
* The renewal task spans the WHOLE read, not one callback: the messages queued behind the one in flight are
|
|
560
|
+
* just as invisible, and they are precisely the ones a long first callback would otherwise let lapse.
|
|
561
|
+
*
|
|
562
|
+
* `halted` is the "enter no further callback" predicate — a graceful stop in loop mode, and additionally
|
|
563
|
+
* the spent wall-clock budget under {@link EventConsumer.drainOnce}. It is consulted BETWEEN sub-batches
|
|
564
|
+
* only, so whatever is already running is always awaited and settled first; the messages of this read no
|
|
565
|
+
* callback ever entered are then released from renewal so their leases lapse and they redeliver at once,
|
|
566
|
+
* rather than staying invisible behind work this pass will not do.
|
|
567
|
+
*/
|
|
568
|
+
const processDelivered = async (
|
|
569
|
+
stream: string,
|
|
570
|
+
messages: readonly DeliveredEventMessage[],
|
|
571
|
+
halted: () => boolean,
|
|
572
|
+
): Promise<void> => {
|
|
573
|
+
const unsettled = new Set(messages.map((delivered) => delivered.receipt));
|
|
574
|
+
const settleOf = (delivered: DeliveredEventMessage) => () => unsettled.delete(delivered.receipt);
|
|
575
|
+
/** Receipts a callback has actually been entered for — the ones a graceful stop must keep renewing. */
|
|
576
|
+
const startedReceipts = new Set<EventQueueReceipt>();
|
|
577
|
+
/**
|
|
578
|
+
* A graceful stop enters no further callback, so every message of this read the workers never reached is
|
|
579
|
+
* released HERE: dropping it from the renewal set lets its lease lapse and the queue redeliver it at once,
|
|
580
|
+
* instead of holding it invisible for as long as the in-flight callbacks still take. The started ones stay
|
|
581
|
+
* in the set and keep being renewed until `processMessage` settles them.
|
|
582
|
+
*/
|
|
583
|
+
const releaseUnstarted = (): void => {
|
|
584
|
+
for (const delivered of messages) {
|
|
585
|
+
if (!startedReceipts.has(delivered.receipt)) {
|
|
586
|
+
unsettled.delete(delivered.receipt);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
if (stopController.signal.aborted) {
|
|
591
|
+
releaseUnstarted();
|
|
592
|
+
} else {
|
|
593
|
+
stopController.signal.addEventListener("abort", releaseUnstarted, { once: true });
|
|
594
|
+
}
|
|
595
|
+
const stopRenewal = startRenewal(stream, unsettled);
|
|
596
|
+
|
|
597
|
+
// The `halted` check and this call are one synchronous step, so a stop (or an expiring budget) can never
|
|
598
|
+
// land between "we decided to run it" and "it counts as started".
|
|
599
|
+
const runOne = async (delivered: DeliveredEventMessage): Promise<void> => {
|
|
600
|
+
startedReceipts.add(delivered.receipt);
|
|
601
|
+
await processMessage(stream, delivered, settleOf(delivered));
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
try {
|
|
605
|
+
if (concurrency <= 1) {
|
|
606
|
+
for (const delivered of messages) {
|
|
607
|
+
if (halted()) {
|
|
608
|
+
releaseUnstarted();
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
await runOne(delivered);
|
|
612
|
+
}
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
let cursor = 0;
|
|
617
|
+
const worker = async (): Promise<void> => {
|
|
618
|
+
for (;;) {
|
|
619
|
+
if (halted()) {
|
|
620
|
+
releaseUnstarted();
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const delivered = messages[cursor++];
|
|
624
|
+
if (!delivered) {
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
await runOne(delivered);
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, worker));
|
|
631
|
+
} finally {
|
|
632
|
+
// Every callback of this read has settled by now (the workers await theirs), so the renewal task has
|
|
633
|
+
// nothing left to protect — and `stop()`, which awaits this loop, therefore awaits the shutdown too.
|
|
634
|
+
stopController.signal.removeEventListener("abort", releaseUnstarted);
|
|
635
|
+
await stopRenewal();
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
// ─── One stream's loop ───────────────────────────────────────────────────────────────────────────────
|
|
640
|
+
const runStream = async (stream: string): Promise<void> => {
|
|
641
|
+
let idleCount = 0;
|
|
642
|
+
|
|
643
|
+
while (!stopping) {
|
|
644
|
+
let productive = false;
|
|
645
|
+
try {
|
|
646
|
+
const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
|
|
647
|
+
if (messages.length > 0) {
|
|
648
|
+
productive = true;
|
|
649
|
+
await processDelivered(stream, messages, () => stopping);
|
|
650
|
+
}
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (error instanceof MalformedEventQueueMessageError) {
|
|
653
|
+
// The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a
|
|
654
|
+
// hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges
|
|
655
|
+
// the stream: dead-letter exactly the named receipt, then re-read for the rest of the batch.
|
|
656
|
+
productive = await deadLetter(
|
|
657
|
+
stream,
|
|
658
|
+
error.receipt,
|
|
659
|
+
0,
|
|
660
|
+
`the queue message body is not a valid event queue message: ${error.message}`,
|
|
661
|
+
error,
|
|
662
|
+
);
|
|
663
|
+
} else {
|
|
664
|
+
// A queue/database fault. A runner NEVER exits on a transient one — it backs off exactly like an
|
|
665
|
+
// idle stream and keeps trying.
|
|
666
|
+
console.warn(
|
|
667
|
+
`pgxsinkit: the event consumer could not read Event stream "${stream}"; backing off and retrying`,
|
|
668
|
+
error,
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
if (productive) {
|
|
674
|
+
// A backlog drains back-to-back: read again immediately, at the floor again once it runs dry.
|
|
675
|
+
idleCount = 0;
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
idleCount += 1;
|
|
680
|
+
if (stopping) {
|
|
681
|
+
break;
|
|
682
|
+
}
|
|
683
|
+
await sleep(computeEventPollWaitMs(idleCount, pollOptions), stopController.signal);
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
// ─── One bounded drain pass (the serverless pacing mode) ─────────────────────────────────────────────
|
|
688
|
+
/**
|
|
689
|
+
* Read → deliver → ack across every stream until they all read empty or the budget is spent. Deliberately
|
|
690
|
+
* built out of `processDelivered` and `deadLetter` — the loop mode's own path — so retry, renewal and
|
|
691
|
+
* dead-lettering cannot drift between the two modes.
|
|
692
|
+
*/
|
|
693
|
+
const runDrain = async (budgetMs: number): Promise<EventDrainSummary> => {
|
|
694
|
+
const stats = { delivered: 0, deadLettered: 0 };
|
|
695
|
+
drainStats = stats;
|
|
696
|
+
const deadline = now() + budgetMs;
|
|
697
|
+
/** Streams not yet known to be empty. A stream leaves the set on an empty read, or on a read fault. */
|
|
698
|
+
const pending = new Set(streams);
|
|
699
|
+
/** Anything that ended the pass with work possibly still queued — the `empty: false` reasons. */
|
|
700
|
+
let unfinished = false;
|
|
701
|
+
// Budget AND stop: a `stop()` during a pass must wind it down just as it winds down a loop.
|
|
702
|
+
const halted = (): boolean => stopping || now() >= deadline;
|
|
703
|
+
|
|
704
|
+
try {
|
|
705
|
+
while (pending.size > 0) {
|
|
706
|
+
if (halted()) {
|
|
707
|
+
unfinished = true;
|
|
708
|
+
break;
|
|
709
|
+
}
|
|
710
|
+
for (const stream of [...pending]) {
|
|
711
|
+
if (halted()) {
|
|
712
|
+
unfinished = true;
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
let messages: readonly DeliveredEventMessage[];
|
|
717
|
+
try {
|
|
718
|
+
messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
|
|
719
|
+
} catch (error) {
|
|
720
|
+
if (error instanceof MalformedEventQueueMessageError) {
|
|
721
|
+
// Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays
|
|
722
|
+
// pending for the re-read that fetches the rest of the batch.
|
|
723
|
+
await deadLetter(
|
|
724
|
+
stream,
|
|
725
|
+
error.receipt,
|
|
726
|
+
0,
|
|
727
|
+
`the queue message body is not a valid event queue message: ${error.message}`,
|
|
728
|
+
error,
|
|
729
|
+
);
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
// A queue/database fault. The loop mode backs off and retries; a bounded pass has nothing to
|
|
733
|
+
// back off INTO (it must not busy-spin against a broken queue for the whole budget), so the
|
|
734
|
+
// stream is left for the next invocation and the pass reports itself unfinished.
|
|
735
|
+
console.warn(
|
|
736
|
+
`pgxsinkit: the event consumer could not read Event stream "${stream}" during a bounded drain; ` +
|
|
737
|
+
"leaving it for the next pass",
|
|
738
|
+
error,
|
|
739
|
+
);
|
|
740
|
+
pending.delete(stream);
|
|
741
|
+
unfinished = true;
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (messages.length === 0) {
|
|
746
|
+
pending.delete(stream);
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
await processDelivered(stream, messages, halted);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
} finally {
|
|
753
|
+
drainStats = null;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
return { delivered: stats.delivered, deadLettered: stats.deadLettered, empty: !unfinished };
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
return {
|
|
760
|
+
start: () => {
|
|
761
|
+
if (activeDrain) {
|
|
762
|
+
throw new Error(
|
|
763
|
+
"pgxsinkit: this event consumer is running a bounded `drainOnce()` pass, so `start()` cannot also " +
|
|
764
|
+
"run its polling loops — one handle drives one pacing mode at a time. Await the pass first.",
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
if (started || stopping) {
|
|
768
|
+
// Idempotent, and a no-op after `stop()` — the handle's lifecycle is one-way, matching the client's
|
|
769
|
+
// flush driver. A restart is a new `defineEventConsumer`.
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
started = true;
|
|
773
|
+
loops = streams.map((stream) =>
|
|
774
|
+
// The catch is attached HERE, at creation: a loop is only awaited by `stop()`, so an unexpected
|
|
775
|
+
// rejection must never be able to surface as an unhandled promise in the app's process.
|
|
776
|
+
runStream(stream).catch((error: unknown) => {
|
|
777
|
+
console.error(`pgxsinkit: the event consumer loop for Event stream "${stream}" ended unexpectedly`, error);
|
|
778
|
+
}),
|
|
779
|
+
);
|
|
780
|
+
},
|
|
781
|
+
|
|
782
|
+
stop: () => {
|
|
783
|
+
stopping = true;
|
|
784
|
+
stopController.abort();
|
|
785
|
+
stopPromise ??= (async () => {
|
|
786
|
+
await Promise.all(loops);
|
|
787
|
+
loops = [];
|
|
788
|
+
// A bounded pass is stopped like a loop: `halted()` already saw `stopping`, so it enters no further
|
|
789
|
+
// callback — this just makes `stop()` resolve only once the one it was on has settled.
|
|
790
|
+
await activeDrain?.catch(() => undefined);
|
|
791
|
+
})();
|
|
792
|
+
return stopPromise;
|
|
793
|
+
},
|
|
794
|
+
|
|
795
|
+
// Deliberately `async`, so every refusal below is a REJECTION rather than a synchronous throw from a
|
|
796
|
+
// promise-returning function — a caller that only wired `.catch()` must not lose one.
|
|
797
|
+
drainOnce: async (drainOptions = {}) => {
|
|
798
|
+
if (started) {
|
|
799
|
+
throw new Error(
|
|
800
|
+
"pgxsinkit: `drainOnce()` cannot run while this consumer's polling loops are live — one handle " +
|
|
801
|
+
"drives one pacing mode at a time. Use the long-lived runner OR bounded drains, not both on one " +
|
|
802
|
+
"handle. (Two separate PROCESSES draining the same queues concurrently is safe: the visibility " +
|
|
803
|
+
"timeout arbitrates them.)",
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
if (stopping) {
|
|
807
|
+
throw new Error(
|
|
808
|
+
"pgxsinkit: this event consumer handle is stopped — its lifecycle is one-way. Build a fresh " +
|
|
809
|
+
"`defineEventConsumer` for the next drain pass; construction is query-free, so that costs nothing.",
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
if (activeDrain) {
|
|
813
|
+
throw new Error(
|
|
814
|
+
"pgxsinkit: a `drainOnce()` pass is already in flight on this handle. Two SEPARATE PROCESSES " +
|
|
815
|
+
"draining concurrently is safe (the queue's visibility timeouts arbitrate); two passes on one " +
|
|
816
|
+
"handle would share its internal state, so it is refused. Await the first pass.",
|
|
817
|
+
);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
const budgetMs = drainOptions.budgetMs ?? DEFAULT_EVENT_DRAIN_BUDGET_MS;
|
|
821
|
+
if (!Number.isFinite(budgetMs) || budgetMs < 0) {
|
|
822
|
+
throw new Error(`pgxsinkit: drainOnce's \`budgetMs\` must be a finite number >= 0 (got ${budgetMs}).`);
|
|
823
|
+
}
|
|
824
|
+
const pass = runDrain(budgetMs).finally(() => {
|
|
825
|
+
activeDrain = null;
|
|
826
|
+
});
|
|
827
|
+
activeDrain = pass;
|
|
828
|
+
return pass;
|
|
829
|
+
},
|
|
830
|
+
};
|
|
831
|
+
}
|