@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,79 @@
|
|
|
1
|
+
import { getSyncRegistryStreams, hashString, quoteSqlLiteral, type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
import { eventStreamQueueName } from "./queue";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The Event lane's **deploy-time** DDL (ADR-0053 decision 5): the pgmq extension plus one queue per registered
|
|
7
|
+
* Event stream, derived from the registry.
|
|
8
|
+
*
|
|
9
|
+
* Provisioning is deploy-time and never runtime create-if-missing — the ingestion endpoint may enqueue long
|
|
10
|
+
* before any consumer runner first starts, and a create-if-missing probe would put a query back in front of
|
|
11
|
+
* the server's zero-startup-query posture.
|
|
12
|
+
*
|
|
13
|
+
* **pgmq assumptions** (read off pgmq's own extension SQL, and pinned by the integration lane):
|
|
14
|
+
* - `CREATE EXTENSION IF NOT EXISTS pgmq` needs **no `CASCADE`**: pgmq's control file declares no `requires`.
|
|
15
|
+
* (pg_partman is needed only for PARTITIONED queues, which this DDL never creates.) `CASCADE` would be
|
|
16
|
+
* harmless but would also silently install whatever a future control file starts requiring.
|
|
17
|
+
* - **No schema qualification is configurable**: the control file is `relocatable = false` with
|
|
18
|
+
* `schema = 'pgmq'`, so the extension always lives in `pgmq` and every call is `pgmq.`-qualified.
|
|
19
|
+
* - `pgmq.create()` is **idempotent**: it delegates to `create_non_partitioned`, whose tables and indexes are
|
|
20
|
+
* `IF NOT EXISTS` and whose `pgmq.meta` insert is `ON CONFLICT DO NOTHING`. So the emitted statements need
|
|
21
|
+
* no guard block and re-applying the migration is a no-op.
|
|
22
|
+
*
|
|
23
|
+
* The artifact is a MIGRATION body (raw SQL text) — `CREATE EXTENSION` and a SQL function call are outside
|
|
24
|
+
* anything Drizzle's builders can express, which is the sanctioned raw-SQL case. Every interpolated queue
|
|
25
|
+
* name is a registry-validated `[a-z][a-z0-9_]*` name, emitted through `quoteSqlLiteral`.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** Stamped into the emitted DDL so `--check` can detect drift between the registry and a committed migration. */
|
|
29
|
+
export const EVENT_LANE_FINGERPRINT_PREFIX = "pgxsinkit:events:fp1:";
|
|
30
|
+
|
|
31
|
+
/** The registered Event-stream names, SORTED — so the artifact and its fingerprint are registry-order-independent. */
|
|
32
|
+
export function eventLaneStreamNames(registry: SyncTableRegistry): string[] {
|
|
33
|
+
return Object.keys(getSyncRegistryStreams(registry) ?? {}).sort();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function buildEventLaneDdlBody(streamNames: readonly string[]): string {
|
|
37
|
+
const header =
|
|
38
|
+
"-- The pgxsinkit event lane's queues (ADR-0053 decision 5): one pgmq queue per registered Event stream.\n" +
|
|
39
|
+
"-- Provisioning is DEPLOY-TIME: the ingestion endpoint may enqueue long before any consumer runner starts.\n" +
|
|
40
|
+
"-- No CASCADE: pgmq's control file declares no `requires`. pgmq is non-relocatable (schema = 'pgmq').\n" +
|
|
41
|
+
"-- pgmq.create() is idempotent (IF NOT EXISTS tables/indexes + ON CONFLICT DO NOTHING meta), so\n" +
|
|
42
|
+
"-- re-applying this migration is a no-op and adding a stream only appends a line.";
|
|
43
|
+
|
|
44
|
+
const statements = streamNames.map(
|
|
45
|
+
(stream) => `SELECT pgmq.create(${quoteSqlLiteral(eventStreamQueueName(stream))});`,
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
return `${header}\nCREATE EXTENSION IF NOT EXISTS pgmq;\n${statements.join("\n")}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function assertHasStreams(registry: SyncTableRegistry): string[] {
|
|
52
|
+
const streamNames = eventLaneStreamNames(registry);
|
|
53
|
+
if (streamNames.length === 0) {
|
|
54
|
+
throw new Error(
|
|
55
|
+
"pgxsinkit: this registry registers no Event streams, so there is no event-lane DDL to emit. Register one " +
|
|
56
|
+
"with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.",
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return streamNames;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The fingerprint the event-lane artifact carries for this registry. Derived from the emitted DDL body, so it
|
|
64
|
+
* moves when a stream is added or removed (and when this generator's output changes) — and does NOT move for a
|
|
65
|
+
* payload-schema change, which provisions nothing.
|
|
66
|
+
*/
|
|
67
|
+
export function eventLaneDdlFingerprint(registry: SyncTableRegistry): string {
|
|
68
|
+
return EVENT_LANE_FINGERPRINT_PREFIX + hashString(buildEventLaneDdlBody(assertHasStreams(registry)));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The full migration body: the DDL plus its fingerprint as a SQL comment. The comment is what
|
|
73
|
+
* `pgxsinkit-generate --events --check` scans committed migrations for — the same pre-deploy drift detection
|
|
74
|
+
* the apply-function artifact gets, minus the in-database stamp (there is no function here to comment on).
|
|
75
|
+
*/
|
|
76
|
+
export function renderEventLaneMigration(registry: SyncTableRegistry): string {
|
|
77
|
+
const body = buildEventLaneDdlBody(assertHasStreams(registry));
|
|
78
|
+
return `-- ${EVENT_LANE_FINGERPRINT_PREFIX + hashString(body)}\n${body}`;
|
|
79
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { EventStreamIdentityField, JwtClaims } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Identity stamping (ADR-0053 decisions 1 and 5): resolve an Event stream's declared identity fields against
|
|
5
|
+
* the **verified** claims of the ingesting request.
|
|
6
|
+
*
|
|
7
|
+
* This is the security-sensitive step of the lane — the point where a client-supplied event becomes an
|
|
8
|
+
* attributed fact. The client's envelope carries no identity at all, so everything the consumer callback sees
|
|
9
|
+
* under `identity` comes from here, and only from claims the server itself verified.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A resolved stamp, or the first field that could not be resolved (which makes the event `rejected`). */
|
|
13
|
+
export type IdentityResolution =
|
|
14
|
+
| { ok: true; identity: Record<string, string> }
|
|
15
|
+
| { ok: false; field: string; claimPath: readonly string[]; detail: string };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Walk a claim path the way the managed-field `authClaim` strategy does (`ManagedFieldSpec.claimPath`), so
|
|
19
|
+
* the toolkit's two claim-stamping surfaces address claims identically: each segment is a plain key into a
|
|
20
|
+
* plain object, `["sub"]` for the auth subject, `["app_metadata", "person_id"]` for an app-minted identity.
|
|
21
|
+
*
|
|
22
|
+
* Arrays are NOT indexed (the SQL twin's `#>> '{a,b}'` would, but an identity addressed by array position is
|
|
23
|
+
* not a shape the registry validates or the toolkit wants to encourage), and the walk stops at the first
|
|
24
|
+
* segment that is not a plain object.
|
|
25
|
+
*/
|
|
26
|
+
function readClaimAtPath(claims: JwtClaims, claimPath: readonly string[]): unknown {
|
|
27
|
+
let current: unknown = claims;
|
|
28
|
+
for (const segment of claimPath) {
|
|
29
|
+
if (typeof current !== "object" || current === null || Array.isArray(current)) {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
current = (current as Record<string, unknown>)[segment];
|
|
33
|
+
}
|
|
34
|
+
return current;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Coerce a resolved claim to the stamped string value, or `null` when it is not stampable.
|
|
39
|
+
*
|
|
40
|
+
* A JSON scalar (number/boolean) is coerced to its text form deliberately: that is exactly what the SQL twin
|
|
41
|
+
* (`current_setting('request.jwt.claims')::jsonb #>> '{…}'`) does for a managed `authClaim` field, so an
|
|
42
|
+
* issuer that mints `person_id` as a JSON number stamps the same value on both surfaces. Anything else —
|
|
43
|
+
* absent, null, an object, an array, or an empty/whitespace string — is NOT stampable: an empty identity must
|
|
44
|
+
* never be stamped silently.
|
|
45
|
+
*/
|
|
46
|
+
function toStampedValue(value: unknown): string | null {
|
|
47
|
+
if (typeof value === "string") {
|
|
48
|
+
return value.trim().length > 0 ? value : null;
|
|
49
|
+
}
|
|
50
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
51
|
+
return String(value);
|
|
52
|
+
}
|
|
53
|
+
if (typeof value === "boolean") {
|
|
54
|
+
return String(value);
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolve every declared identity field, or report the FIRST unresolvable one. Fail-closed by construction:
|
|
61
|
+
* there is no partial stamp and no empty-string fallback — an event whose identity cannot be resolved gets a
|
|
62
|
+
* `rejected` verdict naming the field and its claim path.
|
|
63
|
+
*/
|
|
64
|
+
export function resolveEventIdentity(
|
|
65
|
+
claims: JwtClaims,
|
|
66
|
+
identityFields: Record<string, EventStreamIdentityField>,
|
|
67
|
+
): IdentityResolution {
|
|
68
|
+
const identity: Record<string, string> = {};
|
|
69
|
+
|
|
70
|
+
for (const [field, spec] of Object.entries(identityFields)) {
|
|
71
|
+
const claimPath = spec.claimPath;
|
|
72
|
+
const raw = readClaimAtPath(claims, claimPath);
|
|
73
|
+
const stamped = toStampedValue(raw);
|
|
74
|
+
if (stamped === null) {
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
field,
|
|
78
|
+
claimPath,
|
|
79
|
+
detail: raw === undefined ? "the claim is absent" : `the claim is not a stampable scalar (${typeof raw})`,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
identity[field] = stamped;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return { ok: true, identity };
|
|
86
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
|
|
3
|
+
import { eventQueueMessageSchema, type EventQueueMessage } from "@pgxsinkit/contracts";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
assertEventQueueReceipts,
|
|
7
|
+
eventStreamQueueName,
|
|
8
|
+
MalformedEventQueueMessageError,
|
|
9
|
+
type DeadLetteredEventMessage,
|
|
10
|
+
type DeliveredEventMessage,
|
|
11
|
+
type EventQueue,
|
|
12
|
+
type EventQueueExecutor,
|
|
13
|
+
type EventQueueReadOptions,
|
|
14
|
+
type EventQueueReceipt,
|
|
15
|
+
} from "./queue";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The shipped {@link EventQueue} backend: **pgmq** (ADR-0053 decision 5). Postgres-native, so the Event lane
|
|
19
|
+
* adds no new infrastructure to the supabase-ecosystem stacks consumers already run, and an enqueue joins the
|
|
20
|
+
* endpoint's own transaction rather than crossing a second system.
|
|
21
|
+
*
|
|
22
|
+
* One queue per Event stream (`pgxsinkit_events_<stream>`), so a poison event or a slow consumer in one stream
|
|
23
|
+
* can never head-of-line-block another. Queues are provisioned at DEPLOY time (`pgxsinkit-generate --events`),
|
|
24
|
+
* never created at runtime: the endpoint may enqueue long before any runner first starts, and a
|
|
25
|
+
* create-if-missing probe would put a query back in front of the zero-startup-query posture.
|
|
26
|
+
*
|
|
27
|
+
* **pgmq assumptions**, all read off pgmq's own extension SQL and pinned by the integration lane:
|
|
28
|
+
* - The extension is NOT relocatable and its control file declares `schema = 'pgmq'`, so every call is
|
|
29
|
+
* `pgmq.`-qualified and the schema is never configurable here.
|
|
30
|
+
* - Its control file declares no `requires`, so the DDL needs no `CASCADE` (pg_partman is needed only for
|
|
31
|
+
* PARTITIONED queues, which the toolkit never creates).
|
|
32
|
+
* - Per-queue tables are `pgmq.q_<queue>` and `pgmq.a_<queue>` (`pgmq.format_table_name`); the archive is the
|
|
33
|
+
* dead-letter storage.
|
|
34
|
+
*
|
|
35
|
+
* SQL tier discipline: pgmq's surface IS a set of SQL functions and two dynamically-named tables, so Drizzle's
|
|
36
|
+
* tier-1 builders cannot express any of it. Everything below is tier 2 — a tagged `sql` template with the
|
|
37
|
+
* queue name and every value as BOUND PARAMETERS and each table name as a typed `sql.identifier`; no
|
|
38
|
+
* identifier or value is ever baked into the template text.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The reserved key the dead-letter reason is stamped under, INSIDE the archived message body.
|
|
43
|
+
*
|
|
44
|
+
* Least surface, deliberately: pgmq's archive is the dead-letter storage (no library-owned DLQ table), the
|
|
45
|
+
* archive row has no free column to carry a reason, and its `headers` column only exists on newer pgmq
|
|
46
|
+
* versions. So the reason rides one reserved key on the ARCHIVED body — the live queue row is never mutated,
|
|
47
|
+
* a normally-consumed message is byte-identical to what was enqueued, and the key is stripped again by
|
|
48
|
+
* {@link EventQueue.listDeadLetters} / {@link EventQueue.requeueDeadLetter} so a requeued message is exactly
|
|
49
|
+
* the message that was enqueued.
|
|
50
|
+
*/
|
|
51
|
+
export const PGMQ_DEAD_LETTER_KEY = "__pgxsinkitDeadLetter";
|
|
52
|
+
|
|
53
|
+
export interface CreatePgmqEventQueueOptions {
|
|
54
|
+
/** The default executor — the server's drizzle handle. Per-call executors (a transaction) take precedence. */
|
|
55
|
+
db: EventQueueExecutor;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface DeliveredRow {
|
|
59
|
+
receipt: string;
|
|
60
|
+
deliveryCount: number;
|
|
61
|
+
enqueuedAtUs: string;
|
|
62
|
+
message: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface DeadLetterRow {
|
|
66
|
+
id: string;
|
|
67
|
+
deliveryCount: number;
|
|
68
|
+
deadLetteredAtUs: string;
|
|
69
|
+
message: string;
|
|
70
|
+
reason: string | null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface CountRow {
|
|
74
|
+
affected: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface ReceiptRow {
|
|
78
|
+
receipt: string | null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function toRows<TRow>(result: unknown): TRow[] {
|
|
82
|
+
return Array.from(result as Iterable<unknown>, (row) => row as TRow);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Parse a queue body back into the contract shape, naming the offending receipt if it is not one. */
|
|
86
|
+
function parseQueueMessage(stream: string, receipt: EventQueueReceipt, body: string): EventQueueMessage {
|
|
87
|
+
let raw: unknown;
|
|
88
|
+
try {
|
|
89
|
+
raw = JSON.parse(body);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
throw new MalformedEventQueueMessageError(stream, receipt, error instanceof Error ? error.message : "invalid JSON");
|
|
92
|
+
}
|
|
93
|
+
const parsed = eventQueueMessageSchema.safeParse(raw);
|
|
94
|
+
if (!parsed.success) {
|
|
95
|
+
throw new MalformedEventQueueMessageError(stream, receipt, parsed.error.message);
|
|
96
|
+
}
|
|
97
|
+
return parsed.data;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function createPgmqEventQueue(options: CreatePgmqEventQueueOptions): EventQueue {
|
|
101
|
+
const run = (executor: EventQueueExecutor | undefined, query: Parameters<EventQueueExecutor["execute"]>[0]) =>
|
|
102
|
+
(executor ?? options.db).execute(query);
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
enqueueBatch: async (messages, executor) => {
|
|
106
|
+
if (messages.length === 0) {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Group by Event stream, preserving the order the endpoint assembled: one `send_batch` per stream, all
|
|
111
|
+
// inside the CALLER's transaction, so a mixed flush batch is enqueued atomically or not at all.
|
|
112
|
+
const byStream = new Map<string, EventQueueMessage[]>();
|
|
113
|
+
for (const message of messages) {
|
|
114
|
+
const bucket = byStream.get(message.stream);
|
|
115
|
+
if (bucket) {
|
|
116
|
+
bucket.push(message);
|
|
117
|
+
} else {
|
|
118
|
+
byStream.set(message.stream, [message]);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
for (const [stream, streamMessages] of byStream) {
|
|
123
|
+
const queueName = eventStreamQueueName(stream);
|
|
124
|
+
// The bodies ride as ONE bound json parameter expanded to `jsonb[]` in SQL — never a driver-specific
|
|
125
|
+
// array binding, and never string-built SQL.
|
|
126
|
+
await run(
|
|
127
|
+
executor,
|
|
128
|
+
sql`SELECT pgmq.send_batch(${queueName}, ARRAY(SELECT jsonb_array_elements(${JSON.stringify(streamMessages)}::text::jsonb)))`,
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
readBatch: async (stream: string, readOptions: EventQueueReadOptions): Promise<DeliveredEventMessage[]> => {
|
|
134
|
+
const queueName = eventStreamQueueName(stream);
|
|
135
|
+
const result = await run(
|
|
136
|
+
undefined,
|
|
137
|
+
sql`SELECT "msg_id"::text AS "receipt", "read_ct" AS "deliveryCount", (EXTRACT(EPOCH FROM "enqueued_at") * 1000000)::bigint::text AS "enqueuedAtUs", "message"::text AS "message" FROM pgmq.read(${queueName}, ${readOptions.visibilityTimeoutSeconds}, ${readOptions.maxMessages})`,
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
return toRows<DeliveredRow>(result).map((row) => ({
|
|
141
|
+
receipt: row.receipt,
|
|
142
|
+
stream,
|
|
143
|
+
message: parseQueueMessage(stream, row.receipt, row.message),
|
|
144
|
+
deliveryCount: Number(row.deliveryCount),
|
|
145
|
+
enqueuedAtUs: row.enqueuedAtUs,
|
|
146
|
+
}));
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
extendVisibility: async (stream, receipts, visibilityTimeoutSeconds, executor) => {
|
|
150
|
+
if (receipts.length === 0) {
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
assertEventQueueReceipts(receipts);
|
|
154
|
+
const queueName = eventStreamQueueName(stream);
|
|
155
|
+
// pgmq gained an ARRAY-taking `set_vt` only in 1.8.0, while the single-message form has existed
|
|
156
|
+
// throughout — and the toolkit pins no pgmq version. So the portable shape is the single-message
|
|
157
|
+
// function applied over the receipts with a LATERAL: still ONE statement and one round trip, but it
|
|
158
|
+
// works on every pgmq a consumer's supabase-ecosystem stack might carry. The `::int` cast picks the
|
|
159
|
+
// seconds-offset overload over the `timestamptz` one.
|
|
160
|
+
const result = await run(
|
|
161
|
+
executor,
|
|
162
|
+
sql`SELECT count(*)::int AS "affected" FROM unnest(string_to_array(${receipts.join(",")}, ',')::bigint[]) AS "renewed"("msg_id"), LATERAL pgmq.set_vt(${queueName}, "renewed"."msg_id", ${visibilityTimeoutSeconds}::int) AS "extended"`,
|
|
163
|
+
);
|
|
164
|
+
return Number(toRows<CountRow>(result)[0]?.affected ?? 0);
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
ack: async (stream, receipts) => {
|
|
168
|
+
if (receipts.length === 0) {
|
|
169
|
+
return 0;
|
|
170
|
+
}
|
|
171
|
+
assertEventQueueReceipts(receipts);
|
|
172
|
+
const queueName = eventStreamQueueName(stream);
|
|
173
|
+
const result = await run(
|
|
174
|
+
undefined,
|
|
175
|
+
sql`SELECT count(*)::int AS "affected" FROM pgmq.delete(${queueName}, string_to_array(${receipts.join(",")}, ',')::bigint[])`,
|
|
176
|
+
);
|
|
177
|
+
return Number(toRows<CountRow>(result)[0]?.affected ?? 0);
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
deadLetter: async (stream, receipts, reason) => {
|
|
181
|
+
if (receipts.length === 0) {
|
|
182
|
+
return 0;
|
|
183
|
+
}
|
|
184
|
+
assertEventQueueReceipts(receipts);
|
|
185
|
+
const queueName = eventStreamQueueName(stream);
|
|
186
|
+
const ids = receipts.join(",");
|
|
187
|
+
|
|
188
|
+
// pgmq's own archive move first — it is the version-correct transfer (it carries every column the
|
|
189
|
+
// installed pgmq version has, including ones this code does not know about).
|
|
190
|
+
const archived = await run(
|
|
191
|
+
undefined,
|
|
192
|
+
sql`SELECT count(*)::int AS "affected" FROM pgmq.archive(${queueName}, string_to_array(${ids}, ',')::bigint[])`,
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
// Then stamp the reason onto the ARCHIVED body. Deliberately second: if it fails the message is still
|
|
196
|
+
// dead-lettered (the fail-safe direction), and the archived row is terminal so nothing races this.
|
|
197
|
+
await run(
|
|
198
|
+
undefined,
|
|
199
|
+
sql`UPDATE pgmq.${sql.identifier(`a_${queueName}`)} SET "message" = COALESCE("message", '{}'::jsonb) || jsonb_build_object(${PGMQ_DEAD_LETTER_KEY}::text, jsonb_build_object('reason', ${reason}::text, 'atUs', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000000)::bigint::text)) WHERE "msg_id" = ANY(string_to_array(${ids}, ',')::bigint[])`,
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
return Number(toRows<CountRow>(archived)[0]?.affected ?? 0);
|
|
203
|
+
},
|
|
204
|
+
|
|
205
|
+
listDeadLetters: async (stream, limit) => {
|
|
206
|
+
const queueName = eventStreamQueueName(stream);
|
|
207
|
+
const result = await run(
|
|
208
|
+
undefined,
|
|
209
|
+
sql`SELECT "msg_id"::text AS "id", "read_ct" AS "deliveryCount", (EXTRACT(EPOCH FROM "archived_at") * 1000000)::bigint::text AS "deadLetteredAtUs", ("message" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS "message", "message" -> ${PGMQ_DEAD_LETTER_KEY}::text ->> 'reason' AS "reason" FROM pgmq.${sql.identifier(`a_${queueName}`)} ORDER BY "msg_id" DESC LIMIT ${limit}`,
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
return toRows<DeadLetterRow>(result).map((row): DeadLetteredEventMessage => {
|
|
213
|
+
const message = parseQueueMessage(stream, row.id, row.message);
|
|
214
|
+
return {
|
|
215
|
+
id: row.id,
|
|
216
|
+
stream,
|
|
217
|
+
message,
|
|
218
|
+
...(row.reason != null ? { reason: row.reason } : {}),
|
|
219
|
+
deliveryCount: Number(row.deliveryCount),
|
|
220
|
+
deadLetteredAtUs: row.deadLetteredAtUs,
|
|
221
|
+
};
|
|
222
|
+
});
|
|
223
|
+
},
|
|
224
|
+
|
|
225
|
+
requeueDeadLetter: async (stream, id) => {
|
|
226
|
+
assertEventQueueReceipts([id]);
|
|
227
|
+
const queueName = eventStreamQueueName(stream);
|
|
228
|
+
// ONE statement: the archive row is removed and its (reason-stripped) body re-sent in the same command,
|
|
229
|
+
// so a requeue can never leave the message both dead-lettered and queued.
|
|
230
|
+
const result = await run(
|
|
231
|
+
undefined,
|
|
232
|
+
sql`WITH restored AS (DELETE FROM pgmq.${sql.identifier(`a_${queueName}`)} WHERE "msg_id" = ${id}::bigint RETURNING "message") SELECT pgmq.send(${queueName}, "message" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS "receipt" FROM restored`,
|
|
233
|
+
);
|
|
234
|
+
return toRows<ReceiptRow>(result)[0]?.receipt ?? null;
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { SQL } from "drizzle-orm";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
EVENT_STREAM_NAME_MAX_LENGTH,
|
|
5
|
+
EVENT_STREAM_NAME_PATTERN,
|
|
6
|
+
EVENT_STREAM_QUEUE_PREFIX,
|
|
7
|
+
type EventQueueMessage,
|
|
8
|
+
} from "@pgxsinkit/contracts";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The **Event lane**'s queue seam (ADR-0053 decision 5): a narrow, backend-agnostic interface over
|
|
12
|
+
* "enqueue a batch / consume with a visibility timeout / ack / dead-letter (+ enumerate and requeue)".
|
|
13
|
+
*
|
|
14
|
+
* It is deliberately MECHANICS ONLY — there is no loop, no polling cadence, no wake policy and no
|
|
15
|
+
* retry/backoff here. Those are the consumer runner's internals (ADR-0053 decision 7) and stay out of the
|
|
16
|
+
* seam so a backend swap can never change pacing, and so the ingestion endpoint depends on nothing but
|
|
17
|
+
* `enqueueBatch`.
|
|
18
|
+
*
|
|
19
|
+
* The interface, not the storage, is the contract: dead-letter STORAGE is backend-defined (the shipped pgmq
|
|
20
|
+
* backend uses pgmq's own per-queue archive rather than a library-owned DLQ table), and v1 ships one backend.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The minimal SQL seam a backend executes through — satisfied by a drizzle `PgAsyncDatabase` AND by the
|
|
25
|
+
* transaction handle its `transaction()` callback receives. The ingestion endpoint enqueues INSIDE its own
|
|
26
|
+
* transaction (a batch is enqueued atomically or the request fails retryably), so every mutating method
|
|
27
|
+
* takes an optional executor rather than owning a connection.
|
|
28
|
+
*/
|
|
29
|
+
export interface EventQueueExecutor {
|
|
30
|
+
execute: (query: SQL) => Promise<unknown>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* An opaque handle for one delivered message, used to ack or dead-letter it. Backend-defined (pgmq: the
|
|
35
|
+
* `msg_id` as a decimal string) — never parsed or ordered by callers.
|
|
36
|
+
*/
|
|
37
|
+
export type EventQueueReceipt = string;
|
|
38
|
+
|
|
39
|
+
export interface EventQueueReadOptions {
|
|
40
|
+
/**
|
|
41
|
+
* How long a delivered message stays invisible to other consumers, in seconds. The runner renews or lets
|
|
42
|
+
* it lapse; the queue seam only applies what it is given.
|
|
43
|
+
*/
|
|
44
|
+
visibilityTimeoutSeconds: number;
|
|
45
|
+
/** At most this many messages (each message is one single-stream sub-batch). */
|
|
46
|
+
maxMessages: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One message delivered by {@link EventQueue.readBatch}: a single-stream sub-batch plus its delivery metadata. */
|
|
50
|
+
export interface DeliveredEventMessage {
|
|
51
|
+
receipt: EventQueueReceipt;
|
|
52
|
+
/** The Event-stream name this message was read from (also carried inside `message`). */
|
|
53
|
+
stream: string;
|
|
54
|
+
message: EventQueueMessage;
|
|
55
|
+
/**
|
|
56
|
+
* How many times this message has been DELIVERED (pgmq's `read_ct`), including the current delivery — the
|
|
57
|
+
* attempt counter a runner's dead-letter-after-N policy reads. Never a client-supplied value.
|
|
58
|
+
*/
|
|
59
|
+
deliveryCount: number;
|
|
60
|
+
/** When the message was enqueued, in unix microseconds (decimal string). */
|
|
61
|
+
enqueuedAtUs: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** One dead-lettered message, as enumerated from the backend's dead-letter storage. */
|
|
65
|
+
export interface DeadLetteredEventMessage {
|
|
66
|
+
/** The dead-letter identity, and the handle {@link EventQueue.requeueDeadLetter} takes. */
|
|
67
|
+
id: EventQueueReceipt;
|
|
68
|
+
stream: string;
|
|
69
|
+
message: EventQueueMessage;
|
|
70
|
+
/** The reason recorded when it was dead-lettered, when one was recorded. */
|
|
71
|
+
reason?: string;
|
|
72
|
+
deliveryCount: number;
|
|
73
|
+
/** When it was dead-lettered, in unix microseconds (decimal string). */
|
|
74
|
+
deadLetteredAtUs: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface EventQueue {
|
|
78
|
+
/**
|
|
79
|
+
* Enqueue whole messages. Called by the ingestion endpoint inside its own transaction, so passing
|
|
80
|
+
* `executor` is what makes a multi-stream flush batch atomic: every message lands or none does
|
|
81
|
+
* (ADR-0053 decision 4 — the endpoint never partially enqueues). Without an executor the backend uses its
|
|
82
|
+
* own handle, and a multi-message call is then only as atomic as that handle.
|
|
83
|
+
*/
|
|
84
|
+
enqueueBatch: (messages: readonly EventQueueMessage[], executor?: EventQueueExecutor) => Promise<void>;
|
|
85
|
+
/** Deliver up to `maxMessages` messages of one Event stream, made invisible for the visibility timeout. */
|
|
86
|
+
readBatch: (stream: string, options: EventQueueReadOptions) => Promise<DeliveredEventMessage[]>;
|
|
87
|
+
/**
|
|
88
|
+
* Push delivered messages' invisibility out to `visibilityTimeoutSeconds` FROM NOW — the lease RENEWAL a
|
|
89
|
+
* consumer runner performs while it is still working through a read (one read makes a whole batch
|
|
90
|
+
* invisible at once, so without renewal the later messages of a slow batch would become visible to another
|
|
91
|
+
* runner while the first is still working toward them).
|
|
92
|
+
*
|
|
93
|
+
* Returns how many were actually extended. A receipt that is no longer queued (already acked or
|
|
94
|
+
* dead-lettered) is simply not counted — a renewal racing a settle is ordinary, never an error.
|
|
95
|
+
*/
|
|
96
|
+
extendVisibility: (
|
|
97
|
+
stream: string,
|
|
98
|
+
receipts: readonly EventQueueReceipt[],
|
|
99
|
+
visibilityTimeoutSeconds: number,
|
|
100
|
+
executor?: EventQueueExecutor,
|
|
101
|
+
) => Promise<number>;
|
|
102
|
+
/** Acknowledge (permanently remove) delivered messages. Returns how many were actually removed. */
|
|
103
|
+
ack: (stream: string, receipts: readonly EventQueueReceipt[]) => Promise<number>;
|
|
104
|
+
/** Move delivered messages to dead-letter storage with a recorded reason. Returns how many moved. */
|
|
105
|
+
deadLetter: (stream: string, receipts: readonly EventQueueReceipt[], reason: string) => Promise<number>;
|
|
106
|
+
/** Enumerate an Event stream's dead-lettered messages, most recent first. */
|
|
107
|
+
listDeadLetters: (stream: string, limit: number) => Promise<DeadLetteredEventMessage[]>;
|
|
108
|
+
/**
|
|
109
|
+
* Put one dead-lettered message back on its queue — a DELIBERATE act (ADR-0053 decision 7), never
|
|
110
|
+
* automatic. Resolves with the requeued message's new receipt, or `null` when the id is not dead-lettered.
|
|
111
|
+
*/
|
|
112
|
+
requeueDeadLetter: (stream: string, id: EventQueueReceipt) => Promise<EventQueueReceipt | null>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A queue message whose body is not a well-formed {@link EventQueueMessage}. The endpoint is the only writer
|
|
117
|
+
* of these queues and it writes contract-shaped bodies, so this means a hand-inserted or corrupted message.
|
|
118
|
+
* It carries the receipt precisely so a consumer runner can dead-letter exactly that message rather than
|
|
119
|
+
* failing the whole read.
|
|
120
|
+
*/
|
|
121
|
+
export class MalformedEventQueueMessageError extends Error {
|
|
122
|
+
readonly stream: string;
|
|
123
|
+
readonly receipt: EventQueueReceipt;
|
|
124
|
+
|
|
125
|
+
constructor(stream: string, receipt: EventQueueReceipt, detail: string) {
|
|
126
|
+
super(`pgxsinkit: queue message ${receipt} on Event stream "${stream}" is not a valid queue message — ${detail}`);
|
|
127
|
+
this.name = "MalformedEventQueueMessageError";
|
|
128
|
+
this.stream = stream;
|
|
129
|
+
this.receipt = receipt;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The queue name an Event stream is provisioned under: `pgxsinkit_events_<stream>` (ADR-0053 decision 5), the
|
|
135
|
+
* SAME derivation the deploy-time DDL emits — one definition, so a runtime call can never address a queue the
|
|
136
|
+
* migration did not create.
|
|
137
|
+
*
|
|
138
|
+
* The name is re-validated here even though `defineSyncRegistry` already validated it at module eval:
|
|
139
|
+
* the queue name is interpolated into backend SQL, and a value arriving from a non-registry caller must not
|
|
140
|
+
* be able to smuggle anything past that.
|
|
141
|
+
*/
|
|
142
|
+
export function eventStreamQueueName(stream: string): string {
|
|
143
|
+
if (!EVENT_STREAM_NAME_PATTERN.test(stream) || stream.length > EVENT_STREAM_NAME_MAX_LENGTH) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`pgxsinkit: "${stream}" is not a usable Event-stream name — it must match ` +
|
|
146
|
+
`${EVENT_STREAM_NAME_PATTERN.source} and be at most ${EVENT_STREAM_NAME_MAX_LENGTH} characters.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
return `${EVENT_STREAM_QUEUE_PREFIX}${stream}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Receipts are backend-issued decimal ids; anything else never reaches the backend's SQL. */
|
|
153
|
+
export function assertEventQueueReceipts(receipts: readonly EventQueueReceipt[]): void {
|
|
154
|
+
for (const receipt of receipts) {
|
|
155
|
+
if (!/^\d+$/.test(receipt)) {
|
|
156
|
+
throw new Error(`pgxsinkit: "${receipt}" is not a valid event-queue receipt (expected a decimal id).`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|