@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
package/dist/cli/generate.d.ts
CHANGED
|
@@ -15,6 +15,20 @@
|
|
|
15
15
|
* The result is a standard drizzle-kit migration tracked via snapshot.json.
|
|
16
16
|
*/
|
|
17
17
|
import type { SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
18
|
+
/** Exported for direct unit coverage of the flag surface (repeatable/comma-separated `--grant-execute-to`). */
|
|
19
|
+
export declare function parseArgs(argv: string[]): {
|
|
20
|
+
check: boolean;
|
|
21
|
+
utilities: boolean;
|
|
22
|
+
events: boolean;
|
|
23
|
+
functionSchema: string | undefined;
|
|
24
|
+
grantExecuteTo: string[];
|
|
25
|
+
registryPath: string;
|
|
26
|
+
projectDir: string;
|
|
27
|
+
migrationName: string;
|
|
28
|
+
drizzleConfig: string;
|
|
29
|
+
outDir: string | undefined;
|
|
30
|
+
exportName: string | undefined;
|
|
31
|
+
};
|
|
18
32
|
/** Registry source paths are relative to the invocation directory, not the migration output directory. */
|
|
19
33
|
export declare function resolveRegistryModulePath(registryPath: string, cwd?: string): string;
|
|
20
34
|
/** Select a registry from an imported module, with `--export` available for arbitrary names. */
|
|
@@ -27,4 +41,10 @@ export declare function selectRegistryExport(moduleExports: Record<string, unkno
|
|
|
27
41
|
* 3. a probe of the conventional `drizzle` / `infra/drizzle` locations.
|
|
28
42
|
*/
|
|
29
43
|
export declare function resolveDrizzleOutDir(projectDir: string, drizzleConfig?: string, outFlag?: string): Promise<string | null>;
|
|
44
|
+
/**
|
|
45
|
+
* The one committed-migration scan every `--check` mode shares: the folder whose `migration.sql` carries
|
|
46
|
+
* `marker`, or `null`. Unreadable folders are skipped — a `--check` reports drift, never filesystem noise.
|
|
47
|
+
* Exported for direct unit coverage.
|
|
48
|
+
*/
|
|
49
|
+
export declare function findMigrationCarrying(drizzleDir: string, marker: string): string | null;
|
|
30
50
|
//# sourceMappingURL=generate.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/cli/generate.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;GAcG;AAQH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/cli/generate.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;GAcG;AAQH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAU9D,+GAA+G;AAC/G,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE;;;;;;;;;;;;EA+EvC;AAED,0GAA0G;AAC1G,wBAAgB,yBAAyB,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,SAAgB,GAAG,MAAM,CAE3F;AAMD,gGAAgG;AAChG,wBAAgB,oBAAoB,CAAC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,iBAAiB,CAwBnH;AAiCD;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,MAAM,EAClB,aAAa,CAAC,EAAE,MAAM,EACtB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAuBxB;AA6ED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAYvF"}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { type EventQueueMessage, type StampedEvent, type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
2
|
+
import { type EventQueue, type EventQueueReceipt } from "./queue";
|
|
3
|
+
/**
|
|
4
|
+
* The **Event lane**'s consumer runner (ADR-0053 decisions 6 and 7): the library defines it, the app hosts it.
|
|
5
|
+
*
|
|
6
|
+
* `defineEventConsumer` returns a `start()`/`stop()` handle the app runs in its OWN long-lived Bun process —
|
|
7
|
+
* the toolkit's first long-lived server artifact, deliberately separate from `createSyncServer`'s
|
|
8
|
+
* zero-startup-query serverless posture. There is no supervisor, no CLI entrypoint, no daemon and no signal
|
|
9
|
+
* handling here: the app owns its process lifecycle and calls `stop()` from wherever it already handles
|
|
10
|
+
* shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside
|
|
11
|
+
* `start()`.
|
|
12
|
+
*
|
|
13
|
+
* One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in
|
|
14
|
+
* one stream must never head-of-line-block another), so small deployments run one process and large ones split
|
|
15
|
+
* `streams` across processes.
|
|
16
|
+
*
|
|
17
|
+
* **Pacing is adaptive interval polling, and it is INTERNAL** (ADR-0053 decision 7 — out of consumer-app design
|
|
18
|
+
* space by ratified requirement; only the floor/ceiling/factor are exposed as tuning, never as contract):
|
|
19
|
+
*
|
|
20
|
+
* - a NON-EMPTY read is followed by an immediate re-read, so a backlog drains back-to-back;
|
|
21
|
+
* - consecutive EMPTY reads grow the wait from a floor ({@link DEFAULT_EVENT_POLL_FLOOR_MS}) toward an idle
|
|
22
|
+
* ceiling ({@link DEFAULT_EVENT_POLL_CEILING_MS}) by {@link DEFAULT_EVENT_POLL_FACTOR};
|
|
23
|
+
* - one non-empty read resets the wait to the floor.
|
|
24
|
+
*
|
|
25
|
+
* LISTEN/NOTIFY and `pgmq.read_with_poll` long-polling are REJECTED as wake mechanisms (ADR-0053, maintainer
|
|
26
|
+
* decision): Bun's native `SQL` — the sanctioned Postgres driver — has no LISTEN/NOTIFY, and both mechanisms
|
|
27
|
+
* hold a connection per stream through the transaction poolers the consumers' stacks run behind. Because
|
|
28
|
+
* pacing is internal, the mechanism can change later without any contract change.
|
|
29
|
+
*
|
|
30
|
+
* **Leases are RENEWED while a read is being worked through; a thrown sub-batch's lease is deliberately left
|
|
31
|
+
* to lapse** (ADR-0053 decision 7: visibility renewal is internal). One read makes up to `batchSize` messages
|
|
32
|
+
* invisible at once, so the timeout cannot be "the processing budget": ten ordinary ten-second callbacks
|
|
33
|
+
* would outlive a 60-second window for the later messages, and in a documented multi-runner deployment
|
|
34
|
+
* another process would pick them up while the first is still working toward them. So for as long as a read
|
|
35
|
+
* is in flight the runner extends EVERY not-yet-settled receipt of that read — the one running plus the ones
|
|
36
|
+
* still queued behind it — every `visibilityTimeoutSeconds / 2`. Renewal is best-effort: a failure is
|
|
37
|
+
* warn-logged and the loop carries on, because redelivery is the safety net it would fall back on anyway.
|
|
38
|
+
*
|
|
39
|
+
* `visibilityTimeoutSeconds` therefore means two retry-shaped things, never a budget:
|
|
40
|
+
*
|
|
41
|
+
* - **the redelivery delay of a FAILED sub-batch.** A callback that throws is not acked AND is dropped from
|
|
42
|
+
* renewal immediately, so its lease lapses and the queue redelivers it with an incremented `deliveryCount`.
|
|
43
|
+
* That lapse IS the retry pacing — the runner never sleeps "on behalf of" a failed message, and if a
|
|
44
|
+
* backend ever wants exponential redelivery backoff it belongs INSIDE that backend, behind the
|
|
45
|
+
* {@link EventQueue} seam, so the runner stays backend-agnostic;
|
|
46
|
+
* - **the crash-recovery bound.** A runner that dies takes its renewals with it, so everything it held comes
|
|
47
|
+
* back one timeout later.
|
|
48
|
+
*
|
|
49
|
+
* **A graceful stop does not cancel renewal — it narrows it.** `stop()` starts no further read and no further
|
|
50
|
+
* callback, but the callbacks already in flight are AWAITED and then acked, so their receipts must stay
|
|
51
|
+
* invisible until they settle: cancelling renewal at `stop()` would hand a second runner the very message
|
|
52
|
+
* this one is deliberately finishing, on every ordinary SIGTERM/rollout. What IS released at `stop()` is the
|
|
53
|
+
* rest of that read — the messages no callback has started — which drop out of the renewal set so their
|
|
54
|
+
* leases lapse and the queue redelivers them promptly. `stop()` therefore resolves only once every in-flight
|
|
55
|
+
* callback has settled AND its renewal task has shut down.
|
|
56
|
+
*
|
|
57
|
+
* **The SECOND pacing mode: `drainOnce()`, for hosts that cannot hold a process** (ADR-0053 amendment,
|
|
58
|
+
* 2026-08-02). Everything above describes the primary mode. A serverless-only deployment — managed
|
|
59
|
+
* Supabase, whose edge functions are the only compute — has nowhere to put a `start()`; its queue would
|
|
60
|
+
* simply never drain. So the SAME handle also answers `drainOnce({ budgetMs })`: one bounded pass that
|
|
61
|
+
* reads/delivers/acks through the identical internals until every stream reads empty or the wall-clock
|
|
62
|
+
* budget runs out. Nothing about the delivery contract moves — at-least-once, batch-internal order only,
|
|
63
|
+
* dead-lettering to the backend's archive are all the same code — because pacing was internal from the
|
|
64
|
+
* start (decision 7), which is exactly what makes this a HOSTING addition rather than a contract change.
|
|
65
|
+
* The long-lived runner remains the primary mode; `drainOnce` is what a scheduled invocation calls.
|
|
66
|
+
*/
|
|
67
|
+
/** Max messages (each ONE single-stream sub-batch) a single read delivers, when the app sets nothing. */
|
|
68
|
+
export declare const DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;
|
|
69
|
+
/**
|
|
70
|
+
* How long a delivered sub-batch stays invisible, when the app sets nothing — and how long the runner extends
|
|
71
|
+
* it by on each renewal (it renews at half this). Healthy long processing is covered by renewal, so this is
|
|
72
|
+
* the REDELIVERY DELAY of a sub-batch whose callback threw and the crash-recovery bound, not a budget: it
|
|
73
|
+
* wants to sit above a single callback's worst case (too short redelivers a callback that is merely slower
|
|
74
|
+
* than one renewal interval), never above the whole batch's.
|
|
75
|
+
*/
|
|
76
|
+
export declare const DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;
|
|
77
|
+
/** Deliveries a sub-batch gets before a further callback failure dead-letters it, when the app sets nothing. */
|
|
78
|
+
export declare const DEFAULT_EVENT_MAX_ATTEMPTS = 5;
|
|
79
|
+
/** The adaptive poll's floor — the wait after the FIRST empty read (ADR-0053 decision 7: ~250 ms). */
|
|
80
|
+
export declare const DEFAULT_EVENT_POLL_FLOOR_MS = 250;
|
|
81
|
+
/** The adaptive poll's idle ceiling — the longest an idle stream ever waits between reads. */
|
|
82
|
+
export declare const DEFAULT_EVENT_POLL_CEILING_MS = 5000;
|
|
83
|
+
/** How fast consecutive empty reads grow the wait from the floor toward the ceiling. */
|
|
84
|
+
export declare const DEFAULT_EVENT_POLL_FACTOR = 2;
|
|
85
|
+
/**
|
|
86
|
+
* The wall-clock budget one {@link EventConsumer.drainOnce} pass gets, when the caller sets nothing.
|
|
87
|
+
*
|
|
88
|
+
* **Set it under your platform's invocation wall-clock cap**, with head-room for one callback: the budget is
|
|
89
|
+
* only ever checked BETWEEN sub-batches, so a pass can overrun it by however long the callback that was
|
|
90
|
+
* already running takes. 25 s suits the common serverless caps (Supabase Edge, Vercel, Cloud Run jobs); a
|
|
91
|
+
* platform with a tighter cap wants a tighter budget, and a generous one (a cron container) can raise it.
|
|
92
|
+
*/
|
|
93
|
+
export declare const DEFAULT_EVENT_DRAIN_BUDGET_MS = 25000;
|
|
94
|
+
/**
|
|
95
|
+
* Adaptive-poll tuning. Defaults are the ADR's; they are TUNING, not contract — the pacing mechanism itself is
|
|
96
|
+
* internal and may change.
|
|
97
|
+
*/
|
|
98
|
+
export interface EventConsumerPollOptions {
|
|
99
|
+
/** The wait after the first empty read. Defaults to {@link DEFAULT_EVENT_POLL_FLOOR_MS}. */
|
|
100
|
+
floorMs?: number;
|
|
101
|
+
/** The longest wait an idle stream reaches. Defaults to {@link DEFAULT_EVENT_POLL_CEILING_MS}. */
|
|
102
|
+
ceilingMs?: number;
|
|
103
|
+
/** The growth factor per consecutive empty read. Defaults to {@link DEFAULT_EVENT_POLL_FACTOR}. */
|
|
104
|
+
factor?: number;
|
|
105
|
+
}
|
|
106
|
+
/** One callback invocation: exactly ONE delivered queue message, i.e. one single-stream sub-batch. */
|
|
107
|
+
export interface EventConsumerBatch {
|
|
108
|
+
/** The Event stream these events were appended under. */
|
|
109
|
+
stream: string;
|
|
110
|
+
/**
|
|
111
|
+
* The stamped envelopes, EXACTLY as the ingestion endpoint enqueued them (ADR-0053 decision 5) — in append
|
|
112
|
+
* order within this sub-batch. Across sub-batches there is no ordering promise (decision 6).
|
|
113
|
+
*/
|
|
114
|
+
events: readonly StampedEvent[];
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The consumer callback. Returning (resolving) ACKS the sub-batch; THROWING retries it — the message stays
|
|
118
|
+
* invisible until its visibility timeout lapses and the queue redelivers it.
|
|
119
|
+
*
|
|
120
|
+
* It MUST be idempotent (ADR-0053 decision 6, at-least-once): the blessed pattern is deduping on `eventId`
|
|
121
|
+
* against the app's own durable store, which composes to effectively-exactly-once.
|
|
122
|
+
*/
|
|
123
|
+
export type EventConsumerCallback = (batch: EventConsumerBatch) => void | Promise<void>;
|
|
124
|
+
/** What {@link DefineEventConsumerOptions.onDeadLetter} is told about a sub-batch the runner gave up on. */
|
|
125
|
+
export interface EventDeadLetterReport {
|
|
126
|
+
stream: string;
|
|
127
|
+
/** Why it was dead-lettered — the same reason recorded in the backend's dead-letter storage. */
|
|
128
|
+
reason: string;
|
|
129
|
+
/** Deliveries this message had received. `0` when the body was unreadable (nothing was ever delivered from it). */
|
|
130
|
+
attempts: number;
|
|
131
|
+
/** The receipt it was dead-lettered under — always present, including for an unparseable body. */
|
|
132
|
+
receipt: EventQueueReceipt;
|
|
133
|
+
/** The message, when it was readable. Absent for a malformed body (that is exactly what could not be parsed). */
|
|
134
|
+
message?: EventQueueMessage;
|
|
135
|
+
/** The error behind it: the callback's throw, or the {@link MalformedEventQueueMessageError}. */
|
|
136
|
+
cause?: unknown;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never
|
|
140
|
+
* lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.
|
|
141
|
+
*/
|
|
142
|
+
export type EventConsumerSleep = (ms: number, signal: AbortSignal) => Promise<void>;
|
|
143
|
+
/** What {@link EventConsumer.drainOnce} is tuned with. */
|
|
144
|
+
export interface EventDrainOptions {
|
|
145
|
+
/**
|
|
146
|
+
* The pass's wall-clock budget. Defaults to {@link DEFAULT_EVENT_DRAIN_BUDGET_MS}. Checked between
|
|
147
|
+
* sub-batches only, never inside a callback — so size it under the invocation's cap with head-room for
|
|
148
|
+
* one callback's worst case.
|
|
149
|
+
*/
|
|
150
|
+
budgetMs?: number;
|
|
151
|
+
}
|
|
152
|
+
/** What one {@link EventConsumer.drainOnce} pass reports back. Counts are SUB-BATCHES (one queue message,
|
|
153
|
+
* one callback invocation), the unit the queue and the dead-letter archive both work in. */
|
|
154
|
+
export interface EventDrainSummary {
|
|
155
|
+
/**
|
|
156
|
+
* Sub-batches whose callback completed during this pass. An ack that then failed still counts — the work
|
|
157
|
+
* was delivered, and at-least-once means it may be delivered again later (the callback is idempotent).
|
|
158
|
+
*/
|
|
159
|
+
delivered: number;
|
|
160
|
+
/** Sub-batches this pass moved to the backend's dead-letter storage. */
|
|
161
|
+
deadLettered: number;
|
|
162
|
+
/**
|
|
163
|
+
* `true` when every configured Event stream read empty before the budget ran out — the queue is drained
|
|
164
|
+
* as far as this pass can see.
|
|
165
|
+
*
|
|
166
|
+
* `false` means the pass ended with work possibly still queued: the budget cut it short, or a stream's
|
|
167
|
+
* read faulted. It is the caller's signal that another tick has something to do — a scheduler that
|
|
168
|
+
* chains passes should invoke again promptly rather than waiting out its full period.
|
|
169
|
+
*/
|
|
170
|
+
empty: boolean;
|
|
171
|
+
}
|
|
172
|
+
export interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry> {
|
|
173
|
+
/** The sync registry whose `streams` this runner consumes. */
|
|
174
|
+
registry: TRegistry;
|
|
175
|
+
/**
|
|
176
|
+
* The queue to consume from — REQUIRED, and the reason the runner is backend-agnostic by construction. The
|
|
177
|
+
* ordinary wiring is `createPgmqEventQueue({ db })` with the app's own drizzle handle; constructing it here
|
|
178
|
+
* from a `db` option would bake the shipped backend into the runner for one line of ergonomics.
|
|
179
|
+
*/
|
|
180
|
+
queue: EventQueue;
|
|
181
|
+
callback: EventConsumerCallback;
|
|
182
|
+
/**
|
|
183
|
+
* Narrow to a subset of the registered Event streams — the knob that splits streams across processes.
|
|
184
|
+
* Defaults to ALL registered streams. An unknown name is a definition-time throw (fail-closed): a runner
|
|
185
|
+
* that silently consumed nothing is the failure mode this forbids.
|
|
186
|
+
*/
|
|
187
|
+
streams?: readonly string[];
|
|
188
|
+
/** Max messages per read. Defaults to {@link DEFAULT_EVENT_CONSUMER_BATCH_SIZE}. */
|
|
189
|
+
batchSize?: number;
|
|
190
|
+
/**
|
|
191
|
+
* The delivered-message invisibility window, renewed at half of it while the runner is still working
|
|
192
|
+
* through a read. Defaults to {@link DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS}. Size it above ONE
|
|
193
|
+
* callback's worst case (renewal covers the rest of the batch), not above the whole batch's.
|
|
194
|
+
*/
|
|
195
|
+
visibilityTimeoutSeconds?: number;
|
|
196
|
+
/**
|
|
197
|
+
* Max CONCURRENT callback invocations per Event stream. Defaults to `1` (strictly sequential). Values above 1
|
|
198
|
+
* are safe for the idempotent callback the lane already requires: ADR-0053 decision 6 disclaims any ordering
|
|
199
|
+
* across sub-batches precisely so concurrency is available. Reads stay serial — only the callbacks of one
|
|
200
|
+
* delivered read run in parallel.
|
|
201
|
+
*/
|
|
202
|
+
concurrency?: number;
|
|
203
|
+
/**
|
|
204
|
+
* Deliveries a sub-batch gets before a further callback failure dead-letters it. Defaults to
|
|
205
|
+
* {@link DEFAULT_EVENT_MAX_ATTEMPTS}. A malformed body never gets attempts — it dead-letters on sight.
|
|
206
|
+
*/
|
|
207
|
+
maxAttempts?: number;
|
|
208
|
+
/** Adaptive-poll tuning. See {@link EventConsumerPollOptions}. */
|
|
209
|
+
poll?: EventConsumerPollOptions;
|
|
210
|
+
/**
|
|
211
|
+
* Notified for every dead-lettered sub-batch. The runner ALSO warn-logs each one unconditionally: loudness is
|
|
212
|
+
* the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.
|
|
213
|
+
*/
|
|
214
|
+
onDeadLetter?: (report: EventDeadLetterReport) => void;
|
|
215
|
+
/** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */
|
|
216
|
+
sleep?: EventConsumerSleep;
|
|
217
|
+
/** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */
|
|
218
|
+
now?: () => number;
|
|
219
|
+
/**
|
|
220
|
+
* @internal The injectable RENEWAL wait, deliberately a second seam rather than `sleep`: the two cadences
|
|
221
|
+
* are independent (one paces reads, one paces lease renewal) and sharing one would make every pacing
|
|
222
|
+
* assertion depend on renewal timing. Defaults to `setTimeout`.
|
|
223
|
+
*/
|
|
224
|
+
renewalSleep?: EventConsumerSleep;
|
|
225
|
+
}
|
|
226
|
+
export interface EventConsumer {
|
|
227
|
+
/**
|
|
228
|
+
* Begin every stream's loop. Idempotent; a no-op after {@link EventConsumer.stop}. Throws while a
|
|
229
|
+
* {@link EventConsumer.drainOnce} pass is in flight — one handle drives one pacing mode at a time.
|
|
230
|
+
*/
|
|
231
|
+
start: () => void;
|
|
232
|
+
/**
|
|
233
|
+
* Graceful stop: no new reads, no new callbacks, in-flight callbacks are awaited (and their leases KEPT
|
|
234
|
+
* renewed until they ack or dead-letter), and the promise resolves when every loop — and every renewal
|
|
235
|
+
* task it still owned — is quiet. Safe to call twice (the second call awaits the first). Messages of an
|
|
236
|
+
* in-progress read whose callback had not started are released at once: they stop being renewed and are
|
|
237
|
+
* left unacked, so at-least-once redelivers them as soon as their lease lapses.
|
|
238
|
+
*
|
|
239
|
+
* A `drainOnce` pass in flight is treated the same way: it starts no further read, finishes the callback
|
|
240
|
+
* it is on, and `stop()` resolves once it has.
|
|
241
|
+
*/
|
|
242
|
+
stop: () => Promise<void>;
|
|
243
|
+
/**
|
|
244
|
+
* One bounded drain pass — the pacing mode for a host that cannot hold a process (ADR-0053 amendment,
|
|
245
|
+
* 2026-08-02).
|
|
246
|
+
*
|
|
247
|
+
* It walks every configured Event stream, read → deliver → ack, and keeps going until EITHER every stream
|
|
248
|
+
* has returned an empty read OR the wall-clock budget is spent. Same internals as the loop mode
|
|
249
|
+
* throughout: the same read/deliver/ack path, the same lease renewal while a callback runs, the same
|
|
250
|
+
* per-sub-batch retry-by-lapsing-lease, the same dead-lettering after `maxAttempts` with the same
|
|
251
|
+
* `onDeadLetter` hook and unconditional warn log. It never sleeps: a stream that reads empty is finished
|
|
252
|
+
* for this pass, and there is no adaptive interval to wait out.
|
|
253
|
+
*
|
|
254
|
+
* **The budget is checked BETWEEN sub-batches, never inside one.** A callback already running is awaited
|
|
255
|
+
* and acked exactly as the runner would (its lease stays renewed throughout), and no new read starts once
|
|
256
|
+
* the budget is gone — so a pass can overrun its budget by one callback, and `budgetMs` must leave
|
|
257
|
+
* head-room for that under the platform's invocation cap. A sub-batch whose callback THROWS near the
|
|
258
|
+
* budget edge is not special-cased: it is left unacked and dropped from renewal, its lease lapses, and the
|
|
259
|
+
* queue redelivers it on a later pass with an incremented delivery count. That is at-least-once working as
|
|
260
|
+
* designed, not a lost event — and it is why the callback must be idempotent.
|
|
261
|
+
*
|
|
262
|
+
* **Hosting it.** Wire a SCHEDULED invocation (a platform cron, e.g. every 10 s) that calls `drainOnce`
|
|
263
|
+
* and, optionally, an ingest-side nudge (`createSyncServer({ onEventsEnqueued })` firing a
|
|
264
|
+
* fetch-and-forget at the same endpoint) so an interactive append is drained in milliseconds instead of
|
|
265
|
+
* waiting for the next tick. The **schedule is the delivery guarantee; the nudge is only latency** — a
|
|
266
|
+
* lost nudge costs nothing but time. Overlapping invocations are SAFE: two processes reading the same
|
|
267
|
+
* queue are arbitrated by the visibility timeout, exactly as two long-lived runners would be. (Two passes
|
|
268
|
+
* on ONE handle are not — that is a bug, and throws; see below.)
|
|
269
|
+
*
|
|
270
|
+
* **One handle, one pacing mode.** Throws if `start()` is live, if another `drainOnce` is already in
|
|
271
|
+
* flight on this handle, or if the handle has been stopped — the lifecycle is one-way, so the next drain
|
|
272
|
+
* builds a fresh `defineEventConsumer` (construction is query-free, so that costs nothing).
|
|
273
|
+
*/
|
|
274
|
+
drainOnce: (options?: EventDrainOptions) => Promise<EventDrainSummary>;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* The adaptive wait for `idleCount` CONSECUTIVE unproductive reads (an empty read or a queue fault), clamped to
|
|
278
|
+
* the ceiling. `idleCount` is 1 for the first one; a productive read resets it to 0 and re-reads immediately.
|
|
279
|
+
*/
|
|
280
|
+
export declare function computeEventPollWaitMs(idleCount: number, options?: EventConsumerPollOptions): number;
|
|
281
|
+
export declare function defineEventConsumer<TRegistry extends SyncTableRegistry>(options: DefineEventConsumerOptions<TRegistry>): EventConsumer;
|
|
282
|
+
//# sourceMappingURL=consumer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consumer.d.ts","sourceRoot":"","sources":["../../src/events/consumer.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
2
|
+
/**
|
|
3
|
+
* The Event lane's **deploy-time** DDL (ADR-0053 decision 5): the pgmq extension plus one queue per registered
|
|
4
|
+
* Event stream, derived from the registry.
|
|
5
|
+
*
|
|
6
|
+
* Provisioning is deploy-time and never runtime create-if-missing — the ingestion endpoint may enqueue long
|
|
7
|
+
* before any consumer runner first starts, and a create-if-missing probe would put a query back in front of
|
|
8
|
+
* the server's zero-startup-query posture.
|
|
9
|
+
*
|
|
10
|
+
* **pgmq assumptions** (read off pgmq's own extension SQL, and pinned by the integration lane):
|
|
11
|
+
* - `CREATE EXTENSION IF NOT EXISTS pgmq` needs **no `CASCADE`**: pgmq's control file declares no `requires`.
|
|
12
|
+
* (pg_partman is needed only for PARTITIONED queues, which this DDL never creates.) `CASCADE` would be
|
|
13
|
+
* harmless but would also silently install whatever a future control file starts requiring.
|
|
14
|
+
* - **No schema qualification is configurable**: the control file is `relocatable = false` with
|
|
15
|
+
* `schema = 'pgmq'`, so the extension always lives in `pgmq` and every call is `pgmq.`-qualified.
|
|
16
|
+
* - `pgmq.create()` is **idempotent**: it delegates to `create_non_partitioned`, whose tables and indexes are
|
|
17
|
+
* `IF NOT EXISTS` and whose `pgmq.meta` insert is `ON CONFLICT DO NOTHING`. So the emitted statements need
|
|
18
|
+
* no guard block and re-applying the migration is a no-op.
|
|
19
|
+
*
|
|
20
|
+
* The artifact is a MIGRATION body (raw SQL text) — `CREATE EXTENSION` and a SQL function call are outside
|
|
21
|
+
* anything Drizzle's builders can express, which is the sanctioned raw-SQL case. Every interpolated queue
|
|
22
|
+
* name is a registry-validated `[a-z][a-z0-9_]*` name, emitted through `quoteSqlLiteral`.
|
|
23
|
+
*/
|
|
24
|
+
/** Stamped into the emitted DDL so `--check` can detect drift between the registry and a committed migration. */
|
|
25
|
+
export declare const EVENT_LANE_FINGERPRINT_PREFIX = "pgxsinkit:events:fp1:";
|
|
26
|
+
/** The registered Event-stream names, SORTED — so the artifact and its fingerprint are registry-order-independent. */
|
|
27
|
+
export declare function eventLaneStreamNames(registry: SyncTableRegistry): string[];
|
|
28
|
+
/**
|
|
29
|
+
* The fingerprint the event-lane artifact carries for this registry. Derived from the emitted DDL body, so it
|
|
30
|
+
* moves when a stream is added or removed (and when this generator's output changes) — and does NOT move for a
|
|
31
|
+
* payload-schema change, which provisions nothing.
|
|
32
|
+
*/
|
|
33
|
+
export declare function eventLaneDdlFingerprint(registry: SyncTableRegistry): string;
|
|
34
|
+
/**
|
|
35
|
+
* The full migration body: the DDL plus its fingerprint as a SQL comment. The comment is what
|
|
36
|
+
* `pgxsinkit-generate --events --check` scans committed migrations for — the same pre-deploy drift detection
|
|
37
|
+
* the apply-function artifact gets, minus the in-database stamp (there is no function here to comment on).
|
|
38
|
+
*/
|
|
39
|
+
export declare function renderEventLaneMigration(registry: SyncTableRegistry): string;
|
|
40
|
+
//# sourceMappingURL=ddl.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ddl.d.ts","sourceRoot":"","sources":["../../src/events/ddl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuD,KAAK,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAInH;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,iHAAiH;AACjH,eAAO,MAAM,6BAA6B,0BAA0B,CAAC;AAErE,sHAAsH;AACtH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,MAAM,EAAE,CAE1E;AA4BD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,MAAM,CAE3E;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,MAAM,CAG5E"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { EventStreamIdentityField, JwtClaims } from "@pgxsinkit/contracts";
|
|
2
|
+
/**
|
|
3
|
+
* Identity stamping (ADR-0053 decisions 1 and 5): resolve an Event stream's declared identity fields against
|
|
4
|
+
* the **verified** claims of the ingesting request.
|
|
5
|
+
*
|
|
6
|
+
* This is the security-sensitive step of the lane — the point where a client-supplied event becomes an
|
|
7
|
+
* attributed fact. The client's envelope carries no identity at all, so everything the consumer callback sees
|
|
8
|
+
* under `identity` comes from here, and only from claims the server itself verified.
|
|
9
|
+
*/
|
|
10
|
+
/** A resolved stamp, or the first field that could not be resolved (which makes the event `rejected`). */
|
|
11
|
+
export type IdentityResolution = {
|
|
12
|
+
ok: true;
|
|
13
|
+
identity: Record<string, string>;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
field: string;
|
|
17
|
+
claimPath: readonly string[];
|
|
18
|
+
detail: string;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Resolve every declared identity field, or report the FIRST unresolvable one. Fail-closed by construction:
|
|
22
|
+
* there is no partial stamp and no empty-string fallback — an event whose identity cannot be resolved gets a
|
|
23
|
+
* `rejected` verdict naming the field and its claim path.
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveEventIdentity(claims: JwtClaims, identityFields: Record<string, EventStreamIdentityField>): IdentityResolution;
|
|
26
|
+
//# sourceMappingURL=identity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../src/events/identity.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEhF;;;;;;;GAOG;AAEH,0GAA0G;AAC1G,MAAM,MAAM,kBAAkB,GAC1B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,GAC9C;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AA4C/E;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,SAAS,EACjB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,wBAAwB,CAAC,GACvD,kBAAkB,CAmBpB"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type EventQueue, type EventQueueExecutor } from "./queue";
|
|
2
|
+
/**
|
|
3
|
+
* The shipped {@link EventQueue} backend: **pgmq** (ADR-0053 decision 5). Postgres-native, so the Event lane
|
|
4
|
+
* adds no new infrastructure to the supabase-ecosystem stacks consumers already run, and an enqueue joins the
|
|
5
|
+
* endpoint's own transaction rather than crossing a second system.
|
|
6
|
+
*
|
|
7
|
+
* One queue per Event stream (`pgxsinkit_events_<stream>`), so a poison event or a slow consumer in one stream
|
|
8
|
+
* can never head-of-line-block another. Queues are provisioned at DEPLOY time (`pgxsinkit-generate --events`),
|
|
9
|
+
* never created at runtime: the endpoint may enqueue long before any runner first starts, and a
|
|
10
|
+
* create-if-missing probe would put a query back in front of the zero-startup-query posture.
|
|
11
|
+
*
|
|
12
|
+
* **pgmq assumptions**, all read off pgmq's own extension SQL and pinned by the integration lane:
|
|
13
|
+
* - The extension is NOT relocatable and its control file declares `schema = 'pgmq'`, so every call is
|
|
14
|
+
* `pgmq.`-qualified and the schema is never configurable here.
|
|
15
|
+
* - Its control file declares no `requires`, so the DDL needs no `CASCADE` (pg_partman is needed only for
|
|
16
|
+
* PARTITIONED queues, which the toolkit never creates).
|
|
17
|
+
* - Per-queue tables are `pgmq.q_<queue>` and `pgmq.a_<queue>` (`pgmq.format_table_name`); the archive is the
|
|
18
|
+
* dead-letter storage.
|
|
19
|
+
*
|
|
20
|
+
* SQL tier discipline: pgmq's surface IS a set of SQL functions and two dynamically-named tables, so Drizzle's
|
|
21
|
+
* tier-1 builders cannot express any of it. Everything below is tier 2 — a tagged `sql` template with the
|
|
22
|
+
* queue name and every value as BOUND PARAMETERS and each table name as a typed `sql.identifier`; no
|
|
23
|
+
* identifier or value is ever baked into the template text.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* The reserved key the dead-letter reason is stamped under, INSIDE the archived message body.
|
|
27
|
+
*
|
|
28
|
+
* Least surface, deliberately: pgmq's archive is the dead-letter storage (no library-owned DLQ table), the
|
|
29
|
+
* archive row has no free column to carry a reason, and its `headers` column only exists on newer pgmq
|
|
30
|
+
* versions. So the reason rides one reserved key on the ARCHIVED body — the live queue row is never mutated,
|
|
31
|
+
* a normally-consumed message is byte-identical to what was enqueued, and the key is stripped again by
|
|
32
|
+
* {@link EventQueue.listDeadLetters} / {@link EventQueue.requeueDeadLetter} so a requeued message is exactly
|
|
33
|
+
* the message that was enqueued.
|
|
34
|
+
*/
|
|
35
|
+
export declare const PGMQ_DEAD_LETTER_KEY = "__pgxsinkitDeadLetter";
|
|
36
|
+
export interface CreatePgmqEventQueueOptions {
|
|
37
|
+
/** The default executor — the server's drizzle handle. Per-call executors (a transaction) take precedence. */
|
|
38
|
+
db: EventQueueExecutor;
|
|
39
|
+
}
|
|
40
|
+
export declare function createPgmqEventQueue(options: CreatePgmqEventQueueOptions): EventQueue;
|
|
41
|
+
//# sourceMappingURL=pgmq-queue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pgmq-queue.d.ts","sourceRoot":"","sources":["../../src/events/pgmq-queue.ts"],"names":[],"mappings":"AAIA,OAAO,EAML,KAAK,UAAU,EACf,KAAK,kBAAkB,EAGxB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;;;;;;GASG;AACH,eAAO,MAAM,oBAAoB,0BAA0B,CAAC;AAE5D,MAAM,WAAW,2BAA2B;IAC1C,8GAA8G;IAC9G,EAAE,EAAE,kBAAkB,CAAC;CACxB;AA4CD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,UAAU,CAyIrF"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { SQL } from "drizzle-orm";
|
|
2
|
+
import { type EventQueueMessage } from "@pgxsinkit/contracts";
|
|
3
|
+
/**
|
|
4
|
+
* The **Event lane**'s queue seam (ADR-0053 decision 5): a narrow, backend-agnostic interface over
|
|
5
|
+
* "enqueue a batch / consume with a visibility timeout / ack / dead-letter (+ enumerate and requeue)".
|
|
6
|
+
*
|
|
7
|
+
* It is deliberately MECHANICS ONLY — there is no loop, no polling cadence, no wake policy and no
|
|
8
|
+
* retry/backoff here. Those are the consumer runner's internals (ADR-0053 decision 7) and stay out of the
|
|
9
|
+
* seam so a backend swap can never change pacing, and so the ingestion endpoint depends on nothing but
|
|
10
|
+
* `enqueueBatch`.
|
|
11
|
+
*
|
|
12
|
+
* The interface, not the storage, is the contract: dead-letter STORAGE is backend-defined (the shipped pgmq
|
|
13
|
+
* backend uses pgmq's own per-queue archive rather than a library-owned DLQ table), and v1 ships one backend.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* The minimal SQL seam a backend executes through — satisfied by a drizzle `PgAsyncDatabase` AND by the
|
|
17
|
+
* transaction handle its `transaction()` callback receives. The ingestion endpoint enqueues INSIDE its own
|
|
18
|
+
* transaction (a batch is enqueued atomically or the request fails retryably), so every mutating method
|
|
19
|
+
* takes an optional executor rather than owning a connection.
|
|
20
|
+
*/
|
|
21
|
+
export interface EventQueueExecutor {
|
|
22
|
+
execute: (query: SQL) => Promise<unknown>;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* An opaque handle for one delivered message, used to ack or dead-letter it. Backend-defined (pgmq: the
|
|
26
|
+
* `msg_id` as a decimal string) — never parsed or ordered by callers.
|
|
27
|
+
*/
|
|
28
|
+
export type EventQueueReceipt = string;
|
|
29
|
+
export interface EventQueueReadOptions {
|
|
30
|
+
/**
|
|
31
|
+
* How long a delivered message stays invisible to other consumers, in seconds. The runner renews or lets
|
|
32
|
+
* it lapse; the queue seam only applies what it is given.
|
|
33
|
+
*/
|
|
34
|
+
visibilityTimeoutSeconds: number;
|
|
35
|
+
/** At most this many messages (each message is one single-stream sub-batch). */
|
|
36
|
+
maxMessages: number;
|
|
37
|
+
}
|
|
38
|
+
/** One message delivered by {@link EventQueue.readBatch}: a single-stream sub-batch plus its delivery metadata. */
|
|
39
|
+
export interface DeliveredEventMessage {
|
|
40
|
+
receipt: EventQueueReceipt;
|
|
41
|
+
/** The Event-stream name this message was read from (also carried inside `message`). */
|
|
42
|
+
stream: string;
|
|
43
|
+
message: EventQueueMessage;
|
|
44
|
+
/**
|
|
45
|
+
* How many times this message has been DELIVERED (pgmq's `read_ct`), including the current delivery — the
|
|
46
|
+
* attempt counter a runner's dead-letter-after-N policy reads. Never a client-supplied value.
|
|
47
|
+
*/
|
|
48
|
+
deliveryCount: number;
|
|
49
|
+
/** When the message was enqueued, in unix microseconds (decimal string). */
|
|
50
|
+
enqueuedAtUs: string;
|
|
51
|
+
}
|
|
52
|
+
/** One dead-lettered message, as enumerated from the backend's dead-letter storage. */
|
|
53
|
+
export interface DeadLetteredEventMessage {
|
|
54
|
+
/** The dead-letter identity, and the handle {@link EventQueue.requeueDeadLetter} takes. */
|
|
55
|
+
id: EventQueueReceipt;
|
|
56
|
+
stream: string;
|
|
57
|
+
message: EventQueueMessage;
|
|
58
|
+
/** The reason recorded when it was dead-lettered, when one was recorded. */
|
|
59
|
+
reason?: string;
|
|
60
|
+
deliveryCount: number;
|
|
61
|
+
/** When it was dead-lettered, in unix microseconds (decimal string). */
|
|
62
|
+
deadLetteredAtUs: string;
|
|
63
|
+
}
|
|
64
|
+
export interface EventQueue {
|
|
65
|
+
/**
|
|
66
|
+
* Enqueue whole messages. Called by the ingestion endpoint inside its own transaction, so passing
|
|
67
|
+
* `executor` is what makes a multi-stream flush batch atomic: every message lands or none does
|
|
68
|
+
* (ADR-0053 decision 4 — the endpoint never partially enqueues). Without an executor the backend uses its
|
|
69
|
+
* own handle, and a multi-message call is then only as atomic as that handle.
|
|
70
|
+
*/
|
|
71
|
+
enqueueBatch: (messages: readonly EventQueueMessage[], executor?: EventQueueExecutor) => Promise<void>;
|
|
72
|
+
/** Deliver up to `maxMessages` messages of one Event stream, made invisible for the visibility timeout. */
|
|
73
|
+
readBatch: (stream: string, options: EventQueueReadOptions) => Promise<DeliveredEventMessage[]>;
|
|
74
|
+
/**
|
|
75
|
+
* Push delivered messages' invisibility out to `visibilityTimeoutSeconds` FROM NOW — the lease RENEWAL a
|
|
76
|
+
* consumer runner performs while it is still working through a read (one read makes a whole batch
|
|
77
|
+
* invisible at once, so without renewal the later messages of a slow batch would become visible to another
|
|
78
|
+
* runner while the first is still working toward them).
|
|
79
|
+
*
|
|
80
|
+
* Returns how many were actually extended. A receipt that is no longer queued (already acked or
|
|
81
|
+
* dead-lettered) is simply not counted — a renewal racing a settle is ordinary, never an error.
|
|
82
|
+
*/
|
|
83
|
+
extendVisibility: (stream: string, receipts: readonly EventQueueReceipt[], visibilityTimeoutSeconds: number, executor?: EventQueueExecutor) => Promise<number>;
|
|
84
|
+
/** Acknowledge (permanently remove) delivered messages. Returns how many were actually removed. */
|
|
85
|
+
ack: (stream: string, receipts: readonly EventQueueReceipt[]) => Promise<number>;
|
|
86
|
+
/** Move delivered messages to dead-letter storage with a recorded reason. Returns how many moved. */
|
|
87
|
+
deadLetter: (stream: string, receipts: readonly EventQueueReceipt[], reason: string) => Promise<number>;
|
|
88
|
+
/** Enumerate an Event stream's dead-lettered messages, most recent first. */
|
|
89
|
+
listDeadLetters: (stream: string, limit: number) => Promise<DeadLetteredEventMessage[]>;
|
|
90
|
+
/**
|
|
91
|
+
* Put one dead-lettered message back on its queue — a DELIBERATE act (ADR-0053 decision 7), never
|
|
92
|
+
* automatic. Resolves with the requeued message's new receipt, or `null` when the id is not dead-lettered.
|
|
93
|
+
*/
|
|
94
|
+
requeueDeadLetter: (stream: string, id: EventQueueReceipt) => Promise<EventQueueReceipt | null>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A queue message whose body is not a well-formed {@link EventQueueMessage}. The endpoint is the only writer
|
|
98
|
+
* of these queues and it writes contract-shaped bodies, so this means a hand-inserted or corrupted message.
|
|
99
|
+
* It carries the receipt precisely so a consumer runner can dead-letter exactly that message rather than
|
|
100
|
+
* failing the whole read.
|
|
101
|
+
*/
|
|
102
|
+
export declare class MalformedEventQueueMessageError extends Error {
|
|
103
|
+
readonly stream: string;
|
|
104
|
+
readonly receipt: EventQueueReceipt;
|
|
105
|
+
constructor(stream: string, receipt: EventQueueReceipt, detail: string);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The queue name an Event stream is provisioned under: `pgxsinkit_events_<stream>` (ADR-0053 decision 5), the
|
|
109
|
+
* SAME derivation the deploy-time DDL emits — one definition, so a runtime call can never address a queue the
|
|
110
|
+
* migration did not create.
|
|
111
|
+
*
|
|
112
|
+
* The name is re-validated here even though `defineSyncRegistry` already validated it at module eval:
|
|
113
|
+
* the queue name is interpolated into backend SQL, and a value arriving from a non-registry caller must not
|
|
114
|
+
* be able to smuggle anything past that.
|
|
115
|
+
*/
|
|
116
|
+
export declare function eventStreamQueueName(stream: string): string;
|
|
117
|
+
/** Receipts are backend-issued decimal ids; anything else never reaches the backend's SQL. */
|
|
118
|
+
export declare function assertEventQueueReceipts(receipts: readonly EventQueueReceipt[]): void;
|
|
119
|
+
//# sourceMappingURL=queue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../../src/events/queue.ts"],"names":[],"mappings":"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"}
|