@pgxsinkit/server 0.2.5 → 0.2.6
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,488 @@
|
|
|
1
|
+
import {
|
|
2
|
+
batchEventRequestSchema,
|
|
3
|
+
getSyncRegistryStreams,
|
|
4
|
+
isZodSchema,
|
|
5
|
+
MAX_EVENT_PAYLOAD_BYTES,
|
|
6
|
+
MAX_EVENT_REQUEST_BYTES,
|
|
7
|
+
MAX_EVENTS_PER_BATCH,
|
|
8
|
+
type EventAck,
|
|
9
|
+
type EventEnvelope,
|
|
10
|
+
type EventQueueMessage,
|
|
11
|
+
type EventStreamRegistry,
|
|
12
|
+
type JwtClaims,
|
|
13
|
+
type StampedEvent,
|
|
14
|
+
type SyncTableRegistry,
|
|
15
|
+
} from "@pgxsinkit/contracts";
|
|
16
|
+
|
|
17
|
+
import type { FetchHandler } from "../router";
|
|
18
|
+
import { resolveEventIdentity } from "./identity";
|
|
19
|
+
import type { EventQueue, EventQueueExecutor } from "./queue";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The **Event lane**'s ingestion endpoint (ADR-0053 decisions 3, 4 and 5): the mutation endpoint's sibling,
|
|
23
|
+
* minus what events don't need. `createSyncServer` mounts it automatically at `batchEventPaths` when — and
|
|
24
|
+
* only when — the registry registers at least one Event stream.
|
|
25
|
+
*
|
|
26
|
+
* Two shapes of verdict, and the split is the whole design:
|
|
27
|
+
*
|
|
28
|
+
* - **Framing is batch-level.** A body over the request cap OR an events array over the per-batch count cap
|
|
29
|
+
* (413), unparseable JSON or a body that fails the strict envelope parse (400), missing claims (401), or an
|
|
30
|
+
* unavailable queue (503) is a WHOLE-batch fault: a malformed item without a parseable `eventId` cannot
|
|
31
|
+
* receive a per-event verdict, and a queue that cannot take the batch must not half-take it.
|
|
32
|
+
* - **Every well-formed envelope gets a per-event verdict.** `acked` (enqueued), `refused` (the gating hook
|
|
33
|
+
* said no), `rejected` (schema-invalid payload for a KNOWN stream, oversized payload, or an unresolvable
|
|
34
|
+
* identity claim) and `deferred` (an Event stream this server does not know — ordinary rollout skew, and
|
|
35
|
+
* the ONLY non-terminal verdict). A batch-level 400 on one bad event would wedge the whole Outbox behind
|
|
36
|
+
* that row, which is exactly what the layering avoids.
|
|
37
|
+
*
|
|
38
|
+
* It keeps the write path's **zero-startup-query** posture (ADR-0030): nothing is probed, verified or created
|
|
39
|
+
* at construction — queue provisioning is deploy-time DDL — so the first statement this route sends is the
|
|
40
|
+
* enqueue transaction itself.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/** What the gating hook is told about one event. `identity` is already resolved from the verified claims. */
|
|
44
|
+
export interface EventGateInput {
|
|
45
|
+
/** The Event-stream name — the key the hook dispatches on. */
|
|
46
|
+
stream: string;
|
|
47
|
+
/** The client's envelope, with its payload already validated against the stream's registered schema. */
|
|
48
|
+
event: EventEnvelope;
|
|
49
|
+
/** The verified claims of the ingesting request (`{}` when the registry needs none). */
|
|
50
|
+
claims: JwtClaims;
|
|
51
|
+
/** The server-stamped identity this event would carry onto the queue. */
|
|
52
|
+
identity: Record<string, string>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `true` allows; `false` or `{ allow: false, reason }` refuses (a TERMINAL `refused` verdict). */
|
|
56
|
+
export type EventGateDecision = boolean | { allow: boolean; reason?: string };
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The consent/entitlement gate (ADR-0053 decision 1): the one FUNCTION of the Event lane's contract, and so a
|
|
60
|
+
* `createSyncServer` option rather than a registry field (the registry stays declarative data only).
|
|
61
|
+
*
|
|
62
|
+
* Called **once per event**, after the payload validated and the identity resolved, and before anything is
|
|
63
|
+
* enqueued. Per-event (rather than per stream × batch) is the simplest correct shape: a consent or entitlement
|
|
64
|
+
* decision may legitimately depend on the payload, and a per-batch hook could only express the subset that
|
|
65
|
+
* does not. The claims are constant across a batch, so a hook that consults a store should memoize on them —
|
|
66
|
+
* a batch can carry up to `MAX_EVENTS_PER_BATCH` events.
|
|
67
|
+
*
|
|
68
|
+
* A hook that THROWS fails the whole batch retryably (500, nothing enqueued): a gate that cannot decide must
|
|
69
|
+
* never be read as "allow".
|
|
70
|
+
*/
|
|
71
|
+
export type EventGate = (input: EventGateInput) => EventGateDecision | Promise<EventGateDecision>;
|
|
72
|
+
|
|
73
|
+
/** What {@link EventsEnqueuedHook} is told about a request that enqueued something. */
|
|
74
|
+
export interface EventsEnqueuedInfo {
|
|
75
|
+
/** The Event streams this request put a sub-batch onto, deduplicated, in first-appearance order. */
|
|
76
|
+
streams: string[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Fired after a request has ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02) — the
|
|
81
|
+
* deployment-agnostic seam a serverless deployment uses to NUDGE its drain function.
|
|
82
|
+
*
|
|
83
|
+
* The library stays out of the transport: this hook hands over "something landed on these streams" and the
|
|
84
|
+
* deployment decides what that means. A long-lived runner deployment wires nothing (its poller is already
|
|
85
|
+
* about to read). A serverless one fires a fetch-and-forget at whatever endpoint calls the consumer's
|
|
86
|
+
* `drainOnce()`, so an interactive append is drained in milliseconds rather than at the next scheduled tick.
|
|
87
|
+
*
|
|
88
|
+
* **It is latency, never delivery.** The scheduled sweep is the guarantee; a nudge that is lost, refused or
|
|
89
|
+
* never sent costs nothing but time. So it is fire-and-forget by construction: it is called AFTER the
|
|
90
|
+
* enqueue transaction committed, its return value is ignored (it is `void` — do not await anything through
|
|
91
|
+
* it), and a throw is caught and warn-logged rather than affecting the response the client already earned.
|
|
92
|
+
*/
|
|
93
|
+
export type EventsEnqueuedHook = (info: EventsEnqueuedInfo) => void;
|
|
94
|
+
|
|
95
|
+
/** The minimal transaction seam the endpoint needs — satisfied by a drizzle `PgAsyncDatabase`. */
|
|
96
|
+
export interface EventIngestDb {
|
|
97
|
+
transaction: <TResult>(callback: (tx: EventQueueExecutor) => Promise<TResult>) => Promise<TResult>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface CreateEventIngestHandlerOptions {
|
|
101
|
+
resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
|
|
102
|
+
eventGate?: EventGate;
|
|
103
|
+
/** See {@link EventsEnqueuedHook}. Fired only when something was actually enqueued. */
|
|
104
|
+
onEventsEnqueued?: EventsEnqueuedHook;
|
|
105
|
+
logTimings?: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* What a 503 asks the client to wait, in seconds. The client honours `Retry-After` over its own jittered
|
|
110
|
+
* backoff when it asks for longer, so this is a floor on the retry of a batch the queue could not take.
|
|
111
|
+
*/
|
|
112
|
+
export const EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS = 5;
|
|
113
|
+
|
|
114
|
+
const encoder = new TextEncoder();
|
|
115
|
+
|
|
116
|
+
function byteLengthOf(value: string): number {
|
|
117
|
+
return encoder.encode(value).length;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
121
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** What {@link readBodyWithinLimit} answers with: the decoded body, or the batch-level status to return. */
|
|
125
|
+
type BodyRead = { ok: true; text: string } | { ok: false; status: 400 | 413 };
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Read the request body WHILE enforcing the byte cap, aborting the moment the accumulated bytes exceed it.
|
|
129
|
+
*
|
|
130
|
+
* `request.text()` would buffer the whole body first and measure afterwards, which protects the JSON parse
|
|
131
|
+
* and the queue but NOT memory: `Content-Length` is a claim, and a chunked (or simply lying) caller can omit
|
|
132
|
+
* or understate it. This endpoint is public, so the cap has to bound what is ever held — hence a reader loop
|
|
133
|
+
* that counts as it goes and cancels the stream on the first chunk that crosses the line, buffering at most
|
|
134
|
+
* one chunk past the cap and never the rest of the upload.
|
|
135
|
+
*
|
|
136
|
+
* A body that cannot be read at all (including a request with no body) is a 400: it is a framing fault, and
|
|
137
|
+
* a batch-level one, exactly like unparseable JSON.
|
|
138
|
+
*/
|
|
139
|
+
async function readBodyWithinLimit(request: Request, limit: number): Promise<BodyRead> {
|
|
140
|
+
const body = request.body;
|
|
141
|
+
if (body == null) {
|
|
142
|
+
return { ok: false, status: 400 };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const reader = body.getReader();
|
|
146
|
+
const chunks: Uint8Array[] = [];
|
|
147
|
+
let total = 0;
|
|
148
|
+
try {
|
|
149
|
+
for (;;) {
|
|
150
|
+
const { done, value } = await reader.read();
|
|
151
|
+
if (done) {
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
if (value == null) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
total += value.byteLength;
|
|
158
|
+
if (total > limit) {
|
|
159
|
+
// Stop the peer rather than draining the rest of an oversized upload into a buffer we will discard.
|
|
160
|
+
await reader.cancel().catch(() => undefined);
|
|
161
|
+
return { ok: false, status: 413 };
|
|
162
|
+
}
|
|
163
|
+
chunks.push(value);
|
|
164
|
+
}
|
|
165
|
+
} catch {
|
|
166
|
+
return { ok: false, status: 400 };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const buffer = new Uint8Array(total);
|
|
170
|
+
let offset = 0;
|
|
171
|
+
for (const chunk of chunks) {
|
|
172
|
+
buffer.set(chunk, offset);
|
|
173
|
+
offset += chunk.byteLength;
|
|
174
|
+
}
|
|
175
|
+
return { ok: true, text: new TextDecoder().decode(buffer) };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function errorResponse(message: string, status: number, headers?: Record<string, string>): Response {
|
|
179
|
+
// `batchEventErrorSchema`: a non-2xx is always a whole-batch fault, so the body carries a message and
|
|
180
|
+
// nothing to attribute.
|
|
181
|
+
return Response.json({ message }, { status, ...(headers ? { headers } : {}) });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Whether ANY registered Event stream declares an identity field — i.e. whether ingest NEEDS verified claims.
|
|
186
|
+
* The mutation path's posture, mirrored: it demands claims when the registry actually requires them (an RLS
|
|
187
|
+
* policy or an `authClaim` managed field) rather than unconditionally. A registry whose streams declare no
|
|
188
|
+
* identity at all stamps nothing from claims, so it does not force an auth adapter into existence.
|
|
189
|
+
*/
|
|
190
|
+
export function eventIngestRequiresClaims(streams: EventStreamRegistry): boolean {
|
|
191
|
+
return Object.values(streams).some((entry) => Object.keys(entry.identity ?? {}).length > 0);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function createEventIngestHandler<TRegistry extends SyncTableRegistry>(
|
|
195
|
+
db: EventIngestDb,
|
|
196
|
+
registry: TRegistry,
|
|
197
|
+
queue: EventQueue,
|
|
198
|
+
options: CreateEventIngestHandlerOptions = {},
|
|
199
|
+
): FetchHandler {
|
|
200
|
+
const streams = getSyncRegistryStreams(registry) ?? {};
|
|
201
|
+
const requiresClaims = eventIngestRequiresClaims(streams);
|
|
202
|
+
const perfNow = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
203
|
+
|
|
204
|
+
const handle = async (request: Request): Promise<Response> => {
|
|
205
|
+
const started = options.logTimings ? perfNow() : 0;
|
|
206
|
+
let authMs = 0;
|
|
207
|
+
let enqueueMs = 0;
|
|
208
|
+
|
|
209
|
+
const finish = (response: Response, eventCount: number): Response => {
|
|
210
|
+
if (options.logTimings) {
|
|
211
|
+
console.log(
|
|
212
|
+
"[pgxsinkit-timing]",
|
|
213
|
+
JSON.stringify({
|
|
214
|
+
route: "events",
|
|
215
|
+
authMs: Math.round(authMs),
|
|
216
|
+
enqueueMs: Math.round(enqueueMs),
|
|
217
|
+
totalMs: Math.round(perfNow() - started),
|
|
218
|
+
events: eventCount,
|
|
219
|
+
status: response.status,
|
|
220
|
+
}),
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
return response;
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
// 1. Request-shape limits, BEFORE any parse — and the cap BOUNDS MEMORY, it does not merely report on it
|
|
227
|
+
// afterwards. A truthful `Content-Length` is the cheap fast path (refused without reading a byte);
|
|
228
|
+
// otherwise the body is read through a counting reader that aborts the moment it crosses the cap, so a
|
|
229
|
+
// chunked or lying caller cannot make this public endpoint buffer an arbitrary upload.
|
|
230
|
+
const declaredLength = Number(request.headers.get("content-length"));
|
|
231
|
+
if (Number.isFinite(declaredLength) && declaredLength > MAX_EVENT_REQUEST_BYTES) {
|
|
232
|
+
return finish(
|
|
233
|
+
errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413),
|
|
234
|
+
0,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const bodyRead = await readBodyWithinLimit(request, MAX_EVENT_REQUEST_BYTES);
|
|
239
|
+
if (!bodyRead.ok) {
|
|
240
|
+
return finish(
|
|
241
|
+
bodyRead.status === 413
|
|
242
|
+
? errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413)
|
|
243
|
+
: errorResponse("Invalid batch event request: the body could not be read", 400),
|
|
244
|
+
0,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
const rawText = bodyRead.text;
|
|
248
|
+
|
|
249
|
+
// 2. Strict framing. Unreachable through the library (appends are validated, envelopes are library-built)
|
|
250
|
+
// — this layer exists for library bugs and non-library callers.
|
|
251
|
+
let rawBody: unknown;
|
|
252
|
+
try {
|
|
253
|
+
rawBody = JSON.parse(rawText);
|
|
254
|
+
} catch {
|
|
255
|
+
return finish(errorResponse("Invalid batch event request: the body is not valid JSON", 400), 0);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Request-shape limits are 413, NOT 400 (ADR-0053 decision 3): an over-count is a LIMIT violation, and
|
|
259
|
+
// the client must distinguish it from malformed framing. `batchEventRequestSchema` caps the array too, so
|
|
260
|
+
// the count is checked here — after the JSON parse, before the strict parse — or the schema would answer
|
|
261
|
+
// first with a 400. Only the count is read; every other malformation still falls through to the 400 below.
|
|
262
|
+
if (isPlainObject(rawBody) && Array.isArray(rawBody["events"]) && rawBody["events"].length > MAX_EVENTS_PER_BATCH) {
|
|
263
|
+
return finish(
|
|
264
|
+
errorResponse(`Event batch carries more than the ${MAX_EVENTS_PER_BATCH}-event per-request limit`, 413),
|
|
265
|
+
0,
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const framing = batchEventRequestSchema.safeParse(rawBody);
|
|
270
|
+
if (!framing.success) {
|
|
271
|
+
return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);
|
|
272
|
+
}
|
|
273
|
+
const events = framing.data.events;
|
|
274
|
+
|
|
275
|
+
// 3. Claims, resolved through the ONE adapter the read and write paths share, so an event's attribution
|
|
276
|
+
// can never be authorized differently from a write.
|
|
277
|
+
const authStart = options.logTimings ? perfNow() : 0;
|
|
278
|
+
const resolvedClaims = await options.resolveAuthClaims?.(request);
|
|
279
|
+
if (options.logTimings) authMs = perfNow() - authStart;
|
|
280
|
+
|
|
281
|
+
if (requiresClaims && !isPlainObject(resolvedClaims)) {
|
|
282
|
+
return finish(
|
|
283
|
+
errorResponse("Event streams with claim-stamped identity require validated JWT claims", 401),
|
|
284
|
+
events.length,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
const claims: JwtClaims = isPlainObject(resolvedClaims) ? resolvedClaims : {};
|
|
288
|
+
|
|
289
|
+
// 4. Per-event verdicts, in request order. Survivors are split by Event stream — insertion order gives
|
|
290
|
+
// each stream's sub-batch the events in the order the client appended them (ADR-0053 decision 5).
|
|
291
|
+
const acks: EventAck[] = [];
|
|
292
|
+
const byStream = new Map<string, StampedEvent[]>();
|
|
293
|
+
|
|
294
|
+
for (const event of events) {
|
|
295
|
+
const entry = streams[event.stream];
|
|
296
|
+
if (!entry) {
|
|
297
|
+
// NOT terminal: a client rolled out ahead of its server is ordinary deployment skew, and deleting
|
|
298
|
+
// its events would be data loss on a normal path.
|
|
299
|
+
acks.push({
|
|
300
|
+
eventId: event.eventId,
|
|
301
|
+
status: "deferred",
|
|
302
|
+
reason: `Unknown Event stream "${event.stream}" — this server registers none by that name`,
|
|
303
|
+
});
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (!isZodSchema(entry.payload)) {
|
|
308
|
+
acks.push({
|
|
309
|
+
eventId: event.eventId,
|
|
310
|
+
status: "rejected",
|
|
311
|
+
reason: `Event stream "${event.stream}" is registered without a usable payload schema`,
|
|
312
|
+
});
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// THE authoritative parse: the one whose OUTPUT is taken. The JSON-NORMALIZED form of `parsed.data`
|
|
317
|
+
// (never the raw envelope payload) is what gets stamped onto the queue and what the consumer callback
|
|
318
|
+
// receives — the normalization is the JSON round-trip below, and it is part of the contract, not an
|
|
319
|
+
// artefact: a transform producing a `Date` delivers that date's ISO STRING, and nested `undefined`
|
|
320
|
+
// properties are dropped.
|
|
321
|
+
//
|
|
322
|
+
// The schema itself EXECUTES at both boundaries, and that is worth being exact about: `appendEvent`
|
|
323
|
+
// already ran it on the client as pure validation — discarding the result and storing the caller's
|
|
324
|
+
// original value — so what arrives here is the value that was appended, never a once-transformed one.
|
|
325
|
+
// A transform CALLBACK therefore runs twice while its result is only ever taken once, which is exactly
|
|
326
|
+
// why the lane requires transforms to be pure and deterministic: an effectful or environment-dependent
|
|
327
|
+
// one is unsupported, because this server's run is the one that counts and nothing reconciles it
|
|
328
|
+
// against the client's.
|
|
329
|
+
const parsedPayload = entry.payload.safeParse(event.payload);
|
|
330
|
+
if (!parsedPayload.success) {
|
|
331
|
+
acks.push({
|
|
332
|
+
eventId: event.eventId,
|
|
333
|
+
status: "rejected",
|
|
334
|
+
reason: `Payload failed the schema registered for Event stream "${event.stream}": ${parsedPayload.error.message}`,
|
|
335
|
+
});
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// The authoritative parse's OUTPUT still has to reach the queue as JSON, and a schema is free to
|
|
340
|
+
// produce something JSON cannot carry: `z.string().transform(BigInt)` makes `JSON.stringify` THROW,
|
|
341
|
+
// and a transform returning `undefined` makes it RETURN `undefined`. Untrapped, the throw would fail
|
|
342
|
+
// the WHOLE batch with a 500 — and the Outbox, having had no verdict, would resend that same event
|
|
343
|
+
// forever, wedging every sibling behind it. So it is a TERMINAL per-event `rejected`, and deliberately
|
|
344
|
+
// its own reason: labelling it "exceeds the byte limit" would send an author hunting a size problem
|
|
345
|
+
// that does not exist. (The size check below stays exactly what it says.)
|
|
346
|
+
//
|
|
347
|
+
// This serialization is NOT merely a check — it IS the normalization the consumer contract names. A
|
|
348
|
+
// successful `JSON.stringify` does not mean the value belongs to the JSON domain: a `Date` stringifies
|
|
349
|
+
// to an ISO string, a nested `undefined` property vanishes, an `undefined` array member becomes `null`.
|
|
350
|
+
// Enqueueing `parsedPayload.data` itself would hand an in-memory/fake queue the un-normalized value
|
|
351
|
+
// while real pgmq (which serializes into `jsonb`) delivered the normalized one — the same event
|
|
352
|
+
// observed as two different values depending on the backend. So these exact bytes are what is parsed
|
|
353
|
+
// back and stamped below, and every backend, the fake and pgmq alike, sees the identical payload.
|
|
354
|
+
let payloadJson: string | undefined;
|
|
355
|
+
let serializationFailure: unknown;
|
|
356
|
+
try {
|
|
357
|
+
payloadJson = JSON.stringify(parsedPayload.data);
|
|
358
|
+
} catch (error) {
|
|
359
|
+
serializationFailure = error;
|
|
360
|
+
}
|
|
361
|
+
if (payloadJson === undefined) {
|
|
362
|
+
const detail = serializationFailure instanceof Error ? serializationFailure.message : undefined;
|
|
363
|
+
acks.push({
|
|
364
|
+
eventId: event.eventId,
|
|
365
|
+
status: "rejected",
|
|
366
|
+
reason:
|
|
367
|
+
`The payload schema's parse for Event stream "${event.stream}" produced a value that cannot be ` +
|
|
368
|
+
`serialized as JSON${detail != null ? `: ${detail}` : ""}`,
|
|
369
|
+
});
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (byteLengthOf(payloadJson) > MAX_EVENT_PAYLOAD_BYTES) {
|
|
374
|
+
acks.push({
|
|
375
|
+
eventId: event.eventId,
|
|
376
|
+
status: "rejected",
|
|
377
|
+
reason: `Payload exceeds the ${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit`,
|
|
378
|
+
});
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Identity is resolved BEFORE the gate so the hook can consult the attribution it is gating; an
|
|
383
|
+
// unresolvable identity is a rejection in its own right and never reaches the hook.
|
|
384
|
+
const resolvedIdentity = resolveEventIdentity(claims, entry.identity ?? {});
|
|
385
|
+
if (!resolvedIdentity.ok) {
|
|
386
|
+
acks.push({
|
|
387
|
+
eventId: event.eventId,
|
|
388
|
+
status: "rejected",
|
|
389
|
+
reason:
|
|
390
|
+
`Identity field "${resolvedIdentity.field}" of Event stream "${event.stream}" could not be ` +
|
|
391
|
+
`stamped from claim path ${JSON.stringify(resolvedIdentity.claimPath)}: ${resolvedIdentity.detail}`,
|
|
392
|
+
});
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (options.eventGate) {
|
|
397
|
+
let decision: EventGateDecision;
|
|
398
|
+
try {
|
|
399
|
+
decision = await options.eventGate({
|
|
400
|
+
stream: event.stream,
|
|
401
|
+
event,
|
|
402
|
+
claims,
|
|
403
|
+
identity: resolvedIdentity.identity,
|
|
404
|
+
});
|
|
405
|
+
} catch (error) {
|
|
406
|
+
// A gate that cannot decide must never be read as "allow". Fail the batch retryably: nothing is
|
|
407
|
+
// enqueued, the Outbox keeps every row, and the client retries.
|
|
408
|
+
console.error("[pgxsinkit] event gate threw; refusing the whole batch", error);
|
|
409
|
+
return finish(errorResponse("The event gate failed; nothing was enqueued", 500), events.length);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const allowed = typeof decision === "boolean" ? decision : decision.allow;
|
|
413
|
+
if (!allowed) {
|
|
414
|
+
const reason = typeof decision === "boolean" ? undefined : decision.reason;
|
|
415
|
+
acks.push({
|
|
416
|
+
eventId: event.eventId,
|
|
417
|
+
status: "refused",
|
|
418
|
+
...(reason ? { reason } : { reason: `Refused by the event gate for Event stream "${event.stream}"` }),
|
|
419
|
+
});
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// `payloadJson` is exactly the bytes the queue will carry, so parsing it back yields exactly the value
|
|
425
|
+
// the consumer will observe — whatever backend is behind the seam. (`JSON.parse` of a string that
|
|
426
|
+
// `JSON.stringify` just produced cannot throw.)
|
|
427
|
+
const normalizedPayload: unknown = JSON.parse(payloadJson);
|
|
428
|
+
|
|
429
|
+
const stamped: StampedEvent = {
|
|
430
|
+
eventId: event.eventId,
|
|
431
|
+
occurredAtUs: event.occurredAtUs,
|
|
432
|
+
identity: resolvedIdentity.identity,
|
|
433
|
+
payload: normalizedPayload,
|
|
434
|
+
};
|
|
435
|
+
const bucket = byStream.get(event.stream);
|
|
436
|
+
if (bucket) {
|
|
437
|
+
bucket.push(stamped);
|
|
438
|
+
} else {
|
|
439
|
+
byStream.set(event.stream, [stamped]);
|
|
440
|
+
}
|
|
441
|
+
acks.push({ eventId: event.eventId, status: "acked" });
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// 5. One message per Event stream, all enqueued in ONE transaction. Atomic or nothing (ADR-0053
|
|
445
|
+
// decision 4): the endpoint never partially enqueues and never buffers on the queue's behalf — the
|
|
446
|
+
// Outbox is the buffer.
|
|
447
|
+
const messages: EventQueueMessage[] = Array.from(byStream, ([stream, streamEvents]) => ({
|
|
448
|
+
stream,
|
|
449
|
+
events: streamEvents,
|
|
450
|
+
}));
|
|
451
|
+
|
|
452
|
+
if (messages.length > 0) {
|
|
453
|
+
const enqueueStart = options.logTimings ? perfNow() : 0;
|
|
454
|
+
try {
|
|
455
|
+
await db.transaction(async (tx) => {
|
|
456
|
+
await queue.enqueueBatch(messages, tx);
|
|
457
|
+
});
|
|
458
|
+
} catch (error) {
|
|
459
|
+
// Deliberately generic to the client (the detail can name schema/queue internals); the operator gets
|
|
460
|
+
// the full error on the server's own log.
|
|
461
|
+
console.error("[pgxsinkit] event enqueue failed; nothing was enqueued", error);
|
|
462
|
+
return finish(
|
|
463
|
+
errorResponse("The event queue is unavailable; nothing was enqueued", 503, {
|
|
464
|
+
"Retry-After": String(EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS),
|
|
465
|
+
}),
|
|
466
|
+
events.length,
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
if (options.logTimings) enqueueMs = perfNow() - enqueueStart;
|
|
470
|
+
|
|
471
|
+
// The nudge (ADR-0053 amendment): AFTER the commit, never awaited, never able to change the verdict
|
|
472
|
+
// the client already earned. `byStream`'s keys are unique by construction, so the hook gets the
|
|
473
|
+
// deduplicated stream names of this request in first-appearance order.
|
|
474
|
+
if (options.onEventsEnqueued) {
|
|
475
|
+
try {
|
|
476
|
+
options.onEventsEnqueued({ streams: [...byStream.keys()] });
|
|
477
|
+
} catch (error) {
|
|
478
|
+
// A failed nudge costs latency, never delivery: the scheduled sweep is the guarantee.
|
|
479
|
+
console.warn("[pgxsinkit] the `onEventsEnqueued` hook threw; the events are enqueued regardless", error);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
return finish(Response.json({ acks }), events.length);
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
return handle;
|
|
488
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -8,8 +8,12 @@ import type {
|
|
|
8
8
|
SyncServerAddress,
|
|
9
9
|
SyncTableRegistry,
|
|
10
10
|
} from "@pgxsinkit/contracts";
|
|
11
|
+
import { batchEventPaths, getSyncRegistryStreams } from "@pgxsinkit/contracts";
|
|
11
12
|
|
|
12
13
|
import { proxyElectricShapeRequest } from "./electric-proxy";
|
|
14
|
+
import { createPgmqEventQueue } from "./events/pgmq-queue";
|
|
15
|
+
import type { EventQueue } from "./events/queue";
|
|
16
|
+
import { createEventIngestHandler, type EventGate, type EventsEnqueuedHook } from "./events/route";
|
|
13
17
|
import {
|
|
14
18
|
authoritativeMutationPaths,
|
|
15
19
|
batchMutationPaths,
|
|
@@ -99,6 +103,28 @@ export interface CreateSyncServerOptions<
|
|
|
99
103
|
* are the safe degradation posture (ADR-0030). See {@link DeploymentProfile}.
|
|
100
104
|
*/
|
|
101
105
|
deployment?: DeploymentProfile;
|
|
106
|
+
/**
|
|
107
|
+
* The **Event lane**'s consent/entitlement gate (ADR-0053 decision 1): the lane's one function, and so an
|
|
108
|
+
* option here rather than a registry field (the registry stays declarative data only). Called once per
|
|
109
|
+
* event, after its payload validated and its identity resolved, and before anything is enqueued; a refusal
|
|
110
|
+
* is a per-event `refused` verdict. Absent → every well-formed event is allowed. See {@link EventGate}.
|
|
111
|
+
*/
|
|
112
|
+
eventGate?: EventGate;
|
|
113
|
+
/**
|
|
114
|
+
* Fired after an ingest request ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02): the
|
|
115
|
+
* deployment-agnostic seam a SERVERLESS deployment uses to nudge whatever endpoint runs the consumer's
|
|
116
|
+
* `drainOnce()`, so an interactive append drains in milliseconds instead of waiting for the next
|
|
117
|
+
* scheduled tick. Fire-and-forget — it is called after the commit, its throw is caught and warn-logged,
|
|
118
|
+
* and the scheduled sweep (not the nudge) is the delivery guarantee. Absent → nothing is nudged, which is
|
|
119
|
+
* right for a deployment hosting the long-lived runner. See {@link EventsEnqueuedHook}.
|
|
120
|
+
*/
|
|
121
|
+
onEventsEnqueued?: EventsEnqueuedHook;
|
|
122
|
+
/**
|
|
123
|
+
* The Event lane's queue backend. Defaults to the shipped pgmq backend over this server's own `db`
|
|
124
|
+
* (`createPgmqEventQueue`), which is what makes an enqueue join the endpoint's transaction. Override it to
|
|
125
|
+
* run the lane on another backend, or to substitute a fake in tests.
|
|
126
|
+
*/
|
|
127
|
+
eventQueue?: EventQueue;
|
|
102
128
|
/**
|
|
103
129
|
* Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits
|
|
104
130
|
* one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for
|
|
@@ -106,6 +132,28 @@ export interface CreateSyncServerOptions<
|
|
|
106
132
|
* diagnostic surface that adds no standing query or latency when unset.
|
|
107
133
|
*/
|
|
108
134
|
logTimings?: boolean;
|
|
135
|
+
/**
|
|
136
|
+
* The roles the INSTALLED apply function was generated with (`pgxsinkit-generate
|
|
137
|
+
* --grant-execute-to <role>`, ADR-0054). Default `[]` — owner-only, the default the CLI generates.
|
|
138
|
+
*
|
|
139
|
+
* It is not a grant this server performs; it is how the server reproduces the artifact's ADR-0018
|
|
140
|
+
* fingerprint, which hashes the ACL along with the rest of the body. Generate with a grant and leave
|
|
141
|
+
* this unset and every write fails `PXS01` (stale artifact) — so the two lists must stay identical.
|
|
142
|
+
*/
|
|
143
|
+
applyFunctionGrantExecuteTo?: readonly string[];
|
|
144
|
+
/**
|
|
145
|
+
* The schema the INSTALLED apply function lives in (`pgxsinkit-generate --function-schema <schema>`).
|
|
146
|
+
* Default: unset — the artifact is generated unqualified and resolved through the connection's
|
|
147
|
+
* `search_path`.
|
|
148
|
+
*
|
|
149
|
+
* It does two things at once, which is why one option drives both: the schema is part of the
|
|
150
|
+
* fingerprinted body (the function names itself in its own self-check), AND it is how this server
|
|
151
|
+
* QUALIFIES the call. Generate with `--function-schema` and leave this unset and the call goes out
|
|
152
|
+
* unqualified — which either finds nothing (`42883`) or, worse, finds a same-named function elsewhere
|
|
153
|
+
* on the `search_path` that then fails `PXS01` against a fingerprint it does not carry. The two must
|
|
154
|
+
* name the same schema.
|
|
155
|
+
*/
|
|
156
|
+
applyFunctionSchema?: string;
|
|
109
157
|
}
|
|
110
158
|
|
|
111
159
|
export interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {
|
|
@@ -215,6 +263,8 @@ export function createSyncServer<
|
|
|
215
263
|
options.resolveAuthClaims,
|
|
216
264
|
options.deployment?.startupVerification ?? "in-process",
|
|
217
265
|
options.logTimings ?? false,
|
|
266
|
+
options.applyFunctionGrantExecuteTo ?? [],
|
|
267
|
+
options.applyFunctionSchema,
|
|
218
268
|
);
|
|
219
269
|
for (const path of batchMutationPaths) {
|
|
220
270
|
router.post(path, mutationHandlers.batch);
|
|
@@ -223,6 +273,24 @@ export function createSyncServer<
|
|
|
223
273
|
router.post(path, mutationHandlers.authoritative);
|
|
224
274
|
}
|
|
225
275
|
|
|
276
|
+
// The Event lane's ingestion endpoint (ADR-0053 decision 3), mounted ONLY when the registry registers at
|
|
277
|
+
// least one Event stream — a registry without streams has no event lane, and the path stays a 404. Nothing
|
|
278
|
+
// is probed or provisioned here: the queues are deploy-time DDL (`pgxsinkit-generate --events`), so the
|
|
279
|
+
// route preserves the zero-startup-query posture.
|
|
280
|
+
const eventStreams = getSyncRegistryStreams(options.registry);
|
|
281
|
+
if (eventStreams && Object.keys(eventStreams).length > 0) {
|
|
282
|
+
const eventQueue = options.eventQueue ?? createPgmqEventQueue({ db });
|
|
283
|
+
const eventHandler = createEventIngestHandler(db, options.registry, eventQueue, {
|
|
284
|
+
...(options.resolveAuthClaims ? { resolveAuthClaims: options.resolveAuthClaims } : {}),
|
|
285
|
+
...(options.eventGate ? { eventGate: options.eventGate } : {}),
|
|
286
|
+
...(options.onEventsEnqueued ? { onEventsEnqueued: options.onEventsEnqueued } : {}),
|
|
287
|
+
logTimings: options.logTimings ?? false,
|
|
288
|
+
});
|
|
289
|
+
for (const path of batchEventPaths) {
|
|
290
|
+
router.post(path, eventHandler);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
226
294
|
// The read-path shape proxy shares the same resolveAuthClaims adapter, so read and
|
|
227
295
|
// write authorization can never diverge (ADR-0003).
|
|
228
296
|
if (options.electricUrl) {
|
|
@@ -338,9 +406,65 @@ export type { StartupVerificationMode } from "./mutations/route";
|
|
|
338
406
|
export type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from "./router";
|
|
339
407
|
export { FetchRouter } from "./router";
|
|
340
408
|
export { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from "./mutations/plpgsql-apply";
|
|
409
|
+
export type { ApplyFunctionRenderOptions } from "./mutations/plpgsql-apply";
|
|
341
410
|
export { renderPgxsinkitUtilitiesMigration } from "./migrations/utilities";
|
|
342
411
|
export { ensureOperationsLogSchema, operationsLogRegclassTarget } from "./operations-log/ddl";
|
|
343
412
|
export { operationsLogTable } from "./operations-log/schema";
|
|
344
413
|
export { proxyElectricShapeRequest } from "./electric-proxy";
|
|
345
414
|
export type { ElectricProxyOptions } from "./electric-proxy";
|
|
346
415
|
export { readSqlState } from "./sql-state";
|
|
416
|
+
export {
|
|
417
|
+
createEventIngestHandler,
|
|
418
|
+
eventIngestRequiresClaims,
|
|
419
|
+
EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,
|
|
420
|
+
} from "./events/route";
|
|
421
|
+
export type {
|
|
422
|
+
CreateEventIngestHandlerOptions,
|
|
423
|
+
EventGate,
|
|
424
|
+
EventGateDecision,
|
|
425
|
+
EventGateInput,
|
|
426
|
+
EventIngestDb,
|
|
427
|
+
EventsEnqueuedHook,
|
|
428
|
+
EventsEnqueuedInfo,
|
|
429
|
+
} from "./events/route";
|
|
430
|
+
export { assertEventQueueReceipts, eventStreamQueueName, MalformedEventQueueMessageError } from "./events/queue";
|
|
431
|
+
export type {
|
|
432
|
+
DeadLetteredEventMessage,
|
|
433
|
+
DeliveredEventMessage,
|
|
434
|
+
EventQueue,
|
|
435
|
+
EventQueueExecutor,
|
|
436
|
+
EventQueueReadOptions,
|
|
437
|
+
EventQueueReceipt,
|
|
438
|
+
} from "./events/queue";
|
|
439
|
+
export { createPgmqEventQueue, PGMQ_DEAD_LETTER_KEY } from "./events/pgmq-queue";
|
|
440
|
+
export type { CreatePgmqEventQueueOptions } from "./events/pgmq-queue";
|
|
441
|
+
export {
|
|
442
|
+
computeEventPollWaitMs,
|
|
443
|
+
defineEventConsumer,
|
|
444
|
+
DEFAULT_EVENT_CONSUMER_BATCH_SIZE,
|
|
445
|
+
DEFAULT_EVENT_DRAIN_BUDGET_MS,
|
|
446
|
+
DEFAULT_EVENT_MAX_ATTEMPTS,
|
|
447
|
+
DEFAULT_EVENT_POLL_CEILING_MS,
|
|
448
|
+
DEFAULT_EVENT_POLL_FACTOR,
|
|
449
|
+
DEFAULT_EVENT_POLL_FLOOR_MS,
|
|
450
|
+
DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
|
|
451
|
+
} from "./events/consumer";
|
|
452
|
+
export type {
|
|
453
|
+
DefineEventConsumerOptions,
|
|
454
|
+
EventConsumer,
|
|
455
|
+
EventConsumerBatch,
|
|
456
|
+
EventConsumerCallback,
|
|
457
|
+
EventConsumerPollOptions,
|
|
458
|
+
EventConsumerSleep,
|
|
459
|
+
EventDeadLetterReport,
|
|
460
|
+
EventDrainOptions,
|
|
461
|
+
EventDrainSummary,
|
|
462
|
+
} from "./events/consumer";
|
|
463
|
+
export {
|
|
464
|
+
EVENT_LANE_FINGERPRINT_PREFIX,
|
|
465
|
+
eventLaneDdlFingerprint,
|
|
466
|
+
eventLaneStreamNames,
|
|
467
|
+
renderEventLaneMigration,
|
|
468
|
+
} from "./events/ddl";
|
|
469
|
+
export { resolveEventIdentity } from "./events/identity";
|
|
470
|
+
export type { IdentityResolution } from "./events/identity";
|