@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/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  // @bun
2
+ // packages/server/src/index.ts
3
+ import { batchEventPaths, getSyncRegistryStreams as getSyncRegistryStreams4 } from "@pgxsinkit/contracts";
4
+
2
5
  // packages/server/src/electric-proxy.ts
3
6
  import {
4
7
  buildRowFilterShape,
@@ -242,8 +245,434 @@ function omitColumnsFromRow(row, omittedColumns) {
242
245
  return changed ? nextRow : row;
243
246
  }
244
247
 
248
+ // packages/server/src/events/pgmq-queue.ts
249
+ import { sql } from "drizzle-orm";
250
+ import { eventQueueMessageSchema } from "@pgxsinkit/contracts";
251
+
252
+ // packages/server/src/events/queue.ts
253
+ import {
254
+ EVENT_STREAM_NAME_MAX_LENGTH,
255
+ EVENT_STREAM_NAME_PATTERN,
256
+ EVENT_STREAM_QUEUE_PREFIX
257
+ } from "@pgxsinkit/contracts";
258
+
259
+ class MalformedEventQueueMessageError extends Error {
260
+ stream;
261
+ receipt;
262
+ constructor(stream, receipt, detail) {
263
+ super(`pgxsinkit: queue message ${receipt} on Event stream "${stream}" is not a valid queue message \u2014 ${detail}`);
264
+ this.name = "MalformedEventQueueMessageError";
265
+ this.stream = stream;
266
+ this.receipt = receipt;
267
+ }
268
+ }
269
+ function eventStreamQueueName(stream) {
270
+ if (!EVENT_STREAM_NAME_PATTERN.test(stream) || stream.length > EVENT_STREAM_NAME_MAX_LENGTH) {
271
+ throw new Error(`pgxsinkit: "${stream}" is not a usable Event-stream name \u2014 it must match ` + `${EVENT_STREAM_NAME_PATTERN.source} and be at most ${EVENT_STREAM_NAME_MAX_LENGTH} characters.`);
272
+ }
273
+ return `${EVENT_STREAM_QUEUE_PREFIX}${stream}`;
274
+ }
275
+ function assertEventQueueReceipts(receipts) {
276
+ for (const receipt of receipts) {
277
+ if (!/^\d+$/.test(receipt)) {
278
+ throw new Error(`pgxsinkit: "${receipt}" is not a valid event-queue receipt (expected a decimal id).`);
279
+ }
280
+ }
281
+ }
282
+
283
+ // packages/server/src/events/pgmq-queue.ts
284
+ var PGMQ_DEAD_LETTER_KEY = "__pgxsinkitDeadLetter";
285
+ function toRows(result) {
286
+ return Array.from(result, (row) => row);
287
+ }
288
+ function parseQueueMessage(stream, receipt, body) {
289
+ let raw;
290
+ try {
291
+ raw = JSON.parse(body);
292
+ } catch (error) {
293
+ throw new MalformedEventQueueMessageError(stream, receipt, error instanceof Error ? error.message : "invalid JSON");
294
+ }
295
+ const parsed = eventQueueMessageSchema.safeParse(raw);
296
+ if (!parsed.success) {
297
+ throw new MalformedEventQueueMessageError(stream, receipt, parsed.error.message);
298
+ }
299
+ return parsed.data;
300
+ }
301
+ function createPgmqEventQueue(options) {
302
+ const run = (executor, query) => (executor ?? options.db).execute(query);
303
+ return {
304
+ enqueueBatch: async (messages, executor) => {
305
+ if (messages.length === 0) {
306
+ return;
307
+ }
308
+ const byStream = new Map;
309
+ for (const message of messages) {
310
+ const bucket = byStream.get(message.stream);
311
+ if (bucket) {
312
+ bucket.push(message);
313
+ } else {
314
+ byStream.set(message.stream, [message]);
315
+ }
316
+ }
317
+ for (const [stream, streamMessages] of byStream) {
318
+ const queueName = eventStreamQueueName(stream);
319
+ await run(executor, sql`SELECT pgmq.send_batch(${queueName}, ARRAY(SELECT jsonb_array_elements(${JSON.stringify(streamMessages)}::text::jsonb)))`);
320
+ }
321
+ },
322
+ readBatch: async (stream, readOptions) => {
323
+ const queueName = eventStreamQueueName(stream);
324
+ const result = await run(undefined, 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})`);
325
+ return toRows(result).map((row) => ({
326
+ receipt: row.receipt,
327
+ stream,
328
+ message: parseQueueMessage(stream, row.receipt, row.message),
329
+ deliveryCount: Number(row.deliveryCount),
330
+ enqueuedAtUs: row.enqueuedAtUs
331
+ }));
332
+ },
333
+ extendVisibility: async (stream, receipts, visibilityTimeoutSeconds, executor) => {
334
+ if (receipts.length === 0) {
335
+ return 0;
336
+ }
337
+ assertEventQueueReceipts(receipts);
338
+ const queueName = eventStreamQueueName(stream);
339
+ const result = await run(executor, 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"`);
340
+ return Number(toRows(result)[0]?.affected ?? 0);
341
+ },
342
+ ack: async (stream, receipts) => {
343
+ if (receipts.length === 0) {
344
+ return 0;
345
+ }
346
+ assertEventQueueReceipts(receipts);
347
+ const queueName = eventStreamQueueName(stream);
348
+ const result = await run(undefined, sql`SELECT count(*)::int AS "affected" FROM pgmq.delete(${queueName}, string_to_array(${receipts.join(",")}, ',')::bigint[])`);
349
+ return Number(toRows(result)[0]?.affected ?? 0);
350
+ },
351
+ deadLetter: async (stream, receipts, reason) => {
352
+ if (receipts.length === 0) {
353
+ return 0;
354
+ }
355
+ assertEventQueueReceipts(receipts);
356
+ const queueName = eventStreamQueueName(stream);
357
+ const ids = receipts.join(",");
358
+ const archived = await run(undefined, sql`SELECT count(*)::int AS "affected" FROM pgmq.archive(${queueName}, string_to_array(${ids}, ',')::bigint[])`);
359
+ await run(undefined, 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[])`);
360
+ return Number(toRows(archived)[0]?.affected ?? 0);
361
+ },
362
+ listDeadLetters: async (stream, limit) => {
363
+ const queueName = eventStreamQueueName(stream);
364
+ const result = await run(undefined, 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}`);
365
+ return toRows(result).map((row) => {
366
+ const message = parseQueueMessage(stream, row.id, row.message);
367
+ return {
368
+ id: row.id,
369
+ stream,
370
+ message,
371
+ ...row.reason != null ? { reason: row.reason } : {},
372
+ deliveryCount: Number(row.deliveryCount),
373
+ deadLetteredAtUs: row.deadLetteredAtUs
374
+ };
375
+ });
376
+ },
377
+ requeueDeadLetter: async (stream, id) => {
378
+ assertEventQueueReceipts([id]);
379
+ const queueName = eventStreamQueueName(stream);
380
+ const result = await run(undefined, 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`);
381
+ return toRows(result)[0]?.receipt ?? null;
382
+ }
383
+ };
384
+ }
385
+
386
+ // packages/server/src/events/route.ts
387
+ import {
388
+ batchEventRequestSchema,
389
+ getSyncRegistryStreams,
390
+ isZodSchema,
391
+ MAX_EVENT_PAYLOAD_BYTES,
392
+ MAX_EVENT_REQUEST_BYTES,
393
+ MAX_EVENTS_PER_BATCH
394
+ } from "@pgxsinkit/contracts";
395
+
396
+ // packages/server/src/events/identity.ts
397
+ function readClaimAtPath(claims, claimPath) {
398
+ let current = claims;
399
+ for (const segment of claimPath) {
400
+ if (typeof current !== "object" || current === null || Array.isArray(current)) {
401
+ return;
402
+ }
403
+ current = current[segment];
404
+ }
405
+ return current;
406
+ }
407
+ function toStampedValue(value) {
408
+ if (typeof value === "string") {
409
+ return value.trim().length > 0 ? value : null;
410
+ }
411
+ if (typeof value === "number" && Number.isFinite(value)) {
412
+ return String(value);
413
+ }
414
+ if (typeof value === "boolean") {
415
+ return String(value);
416
+ }
417
+ return null;
418
+ }
419
+ function resolveEventIdentity(claims, identityFields) {
420
+ const identity = {};
421
+ for (const [field, spec] of Object.entries(identityFields)) {
422
+ const claimPath = spec.claimPath;
423
+ const raw = readClaimAtPath(claims, claimPath);
424
+ const stamped = toStampedValue(raw);
425
+ if (stamped === null) {
426
+ return {
427
+ ok: false,
428
+ field,
429
+ claimPath,
430
+ detail: raw === undefined ? "the claim is absent" : `the claim is not a stampable scalar (${typeof raw})`
431
+ };
432
+ }
433
+ identity[field] = stamped;
434
+ }
435
+ return { ok: true, identity };
436
+ }
437
+
438
+ // packages/server/src/events/route.ts
439
+ var EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS = 5;
440
+ var encoder = new TextEncoder;
441
+ function byteLengthOf(value) {
442
+ return encoder.encode(value).length;
443
+ }
444
+ function isPlainObject(value) {
445
+ return typeof value === "object" && value !== null && !Array.isArray(value);
446
+ }
447
+ async function readBodyWithinLimit(request, limit) {
448
+ const body = request.body;
449
+ if (body == null) {
450
+ return { ok: false, status: 400 };
451
+ }
452
+ const reader = body.getReader();
453
+ const chunks = [];
454
+ let total = 0;
455
+ try {
456
+ for (;; ) {
457
+ const { done, value } = await reader.read();
458
+ if (done) {
459
+ break;
460
+ }
461
+ if (value == null) {
462
+ continue;
463
+ }
464
+ total += value.byteLength;
465
+ if (total > limit) {
466
+ await reader.cancel().catch(() => {
467
+ return;
468
+ });
469
+ return { ok: false, status: 413 };
470
+ }
471
+ chunks.push(value);
472
+ }
473
+ } catch {
474
+ return { ok: false, status: 400 };
475
+ }
476
+ const buffer = new Uint8Array(total);
477
+ let offset = 0;
478
+ for (const chunk of chunks) {
479
+ buffer.set(chunk, offset);
480
+ offset += chunk.byteLength;
481
+ }
482
+ return { ok: true, text: new TextDecoder().decode(buffer) };
483
+ }
484
+ function errorResponse(message, status, headers) {
485
+ return Response.json({ message }, { status, ...headers ? { headers } : {} });
486
+ }
487
+ function eventIngestRequiresClaims(streams) {
488
+ return Object.values(streams).some((entry) => Object.keys(entry.identity ?? {}).length > 0);
489
+ }
490
+ function createEventIngestHandler(db, registry, queue, options = {}) {
491
+ const streams = getSyncRegistryStreams(registry) ?? {};
492
+ const requiresClaims = eventIngestRequiresClaims(streams);
493
+ const perfNow2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
494
+ const handle = async (request) => {
495
+ const started = options.logTimings ? perfNow2() : 0;
496
+ let authMs = 0;
497
+ let enqueueMs = 0;
498
+ const finish = (response, eventCount) => {
499
+ if (options.logTimings) {
500
+ console.log("[pgxsinkit-timing]", JSON.stringify({
501
+ route: "events",
502
+ authMs: Math.round(authMs),
503
+ enqueueMs: Math.round(enqueueMs),
504
+ totalMs: Math.round(perfNow2() - started),
505
+ events: eventCount,
506
+ status: response.status
507
+ }));
508
+ }
509
+ return response;
510
+ };
511
+ const declaredLength = Number(request.headers.get("content-length"));
512
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_EVENT_REQUEST_BYTES) {
513
+ return finish(errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413), 0);
514
+ }
515
+ const bodyRead = await readBodyWithinLimit(request, MAX_EVENT_REQUEST_BYTES);
516
+ if (!bodyRead.ok) {
517
+ return finish(bodyRead.status === 413 ? errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413) : errorResponse("Invalid batch event request: the body could not be read", 400), 0);
518
+ }
519
+ const rawText = bodyRead.text;
520
+ let rawBody;
521
+ try {
522
+ rawBody = JSON.parse(rawText);
523
+ } catch {
524
+ return finish(errorResponse("Invalid batch event request: the body is not valid JSON", 400), 0);
525
+ }
526
+ if (isPlainObject(rawBody) && Array.isArray(rawBody["events"]) && rawBody["events"].length > MAX_EVENTS_PER_BATCH) {
527
+ return finish(errorResponse(`Event batch carries more than the ${MAX_EVENTS_PER_BATCH}-event per-request limit`, 413), 0);
528
+ }
529
+ const framing = batchEventRequestSchema.safeParse(rawBody);
530
+ if (!framing.success) {
531
+ return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);
532
+ }
533
+ const events = framing.data.events;
534
+ const authStart = options.logTimings ? perfNow2() : 0;
535
+ const resolvedClaims = await options.resolveAuthClaims?.(request);
536
+ if (options.logTimings)
537
+ authMs = perfNow2() - authStart;
538
+ if (requiresClaims && !isPlainObject(resolvedClaims)) {
539
+ return finish(errorResponse("Event streams with claim-stamped identity require validated JWT claims", 401), events.length);
540
+ }
541
+ const claims = isPlainObject(resolvedClaims) ? resolvedClaims : {};
542
+ const acks = [];
543
+ const byStream = new Map;
544
+ for (const event of events) {
545
+ const entry = streams[event.stream];
546
+ if (!entry) {
547
+ acks.push({
548
+ eventId: event.eventId,
549
+ status: "deferred",
550
+ reason: `Unknown Event stream "${event.stream}" \u2014 this server registers none by that name`
551
+ });
552
+ continue;
553
+ }
554
+ if (!isZodSchema(entry.payload)) {
555
+ acks.push({
556
+ eventId: event.eventId,
557
+ status: "rejected",
558
+ reason: `Event stream "${event.stream}" is registered without a usable payload schema`
559
+ });
560
+ continue;
561
+ }
562
+ const parsedPayload = entry.payload.safeParse(event.payload);
563
+ if (!parsedPayload.success) {
564
+ acks.push({
565
+ eventId: event.eventId,
566
+ status: "rejected",
567
+ reason: `Payload failed the schema registered for Event stream "${event.stream}": ${parsedPayload.error.message}`
568
+ });
569
+ continue;
570
+ }
571
+ let payloadJson;
572
+ let serializationFailure;
573
+ try {
574
+ payloadJson = JSON.stringify(parsedPayload.data);
575
+ } catch (error) {
576
+ serializationFailure = error;
577
+ }
578
+ if (payloadJson === undefined) {
579
+ const detail = serializationFailure instanceof Error ? serializationFailure.message : undefined;
580
+ acks.push({
581
+ eventId: event.eventId,
582
+ status: "rejected",
583
+ reason: `The payload schema's parse for Event stream "${event.stream}" produced a value that cannot be ` + `serialized as JSON${detail != null ? `: ${detail}` : ""}`
584
+ });
585
+ continue;
586
+ }
587
+ if (byteLengthOf(payloadJson) > MAX_EVENT_PAYLOAD_BYTES) {
588
+ acks.push({
589
+ eventId: event.eventId,
590
+ status: "rejected",
591
+ reason: `Payload exceeds the ${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit`
592
+ });
593
+ continue;
594
+ }
595
+ const resolvedIdentity = resolveEventIdentity(claims, entry.identity ?? {});
596
+ if (!resolvedIdentity.ok) {
597
+ acks.push({
598
+ eventId: event.eventId,
599
+ status: "rejected",
600
+ reason: `Identity field "${resolvedIdentity.field}" of Event stream "${event.stream}" could not be ` + `stamped from claim path ${JSON.stringify(resolvedIdentity.claimPath)}: ${resolvedIdentity.detail}`
601
+ });
602
+ continue;
603
+ }
604
+ if (options.eventGate) {
605
+ let decision;
606
+ try {
607
+ decision = await options.eventGate({
608
+ stream: event.stream,
609
+ event,
610
+ claims,
611
+ identity: resolvedIdentity.identity
612
+ });
613
+ } catch (error) {
614
+ console.error("[pgxsinkit] event gate threw; refusing the whole batch", error);
615
+ return finish(errorResponse("The event gate failed; nothing was enqueued", 500), events.length);
616
+ }
617
+ const allowed = typeof decision === "boolean" ? decision : decision.allow;
618
+ if (!allowed) {
619
+ const reason = typeof decision === "boolean" ? undefined : decision.reason;
620
+ acks.push({
621
+ eventId: event.eventId,
622
+ status: "refused",
623
+ ...reason ? { reason } : { reason: `Refused by the event gate for Event stream "${event.stream}"` }
624
+ });
625
+ continue;
626
+ }
627
+ }
628
+ const normalizedPayload = JSON.parse(payloadJson);
629
+ const stamped = {
630
+ eventId: event.eventId,
631
+ occurredAtUs: event.occurredAtUs,
632
+ identity: resolvedIdentity.identity,
633
+ payload: normalizedPayload
634
+ };
635
+ const bucket = byStream.get(event.stream);
636
+ if (bucket) {
637
+ bucket.push(stamped);
638
+ } else {
639
+ byStream.set(event.stream, [stamped]);
640
+ }
641
+ acks.push({ eventId: event.eventId, status: "acked" });
642
+ }
643
+ const messages = Array.from(byStream, ([stream, streamEvents]) => ({
644
+ stream,
645
+ events: streamEvents
646
+ }));
647
+ if (messages.length > 0) {
648
+ const enqueueStart = options.logTimings ? perfNow2() : 0;
649
+ try {
650
+ await db.transaction(async (tx) => {
651
+ await queue.enqueueBatch(messages, tx);
652
+ });
653
+ } catch (error) {
654
+ console.error("[pgxsinkit] event enqueue failed; nothing was enqueued", error);
655
+ return finish(errorResponse("The event queue is unavailable; nothing was enqueued", 503, {
656
+ "Retry-After": String(EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS)
657
+ }), events.length);
658
+ }
659
+ if (options.logTimings)
660
+ enqueueMs = perfNow2() - enqueueStart;
661
+ if (options.onEventsEnqueued) {
662
+ try {
663
+ options.onEventsEnqueued({ streams: [...byStream.keys()] });
664
+ } catch (error) {
665
+ console.warn("[pgxsinkit] the `onEventsEnqueued` hook threw; the events are enqueued regardless", error);
666
+ }
667
+ }
668
+ }
669
+ return finish(Response.json({ acks }), events.length);
670
+ };
671
+ return handle;
672
+ }
673
+
245
674
  // packages/server/src/mutations/route.ts
246
- import { and, eq, sql as sql2 } from "drizzle-orm";
675
+ import { and, eq, sql as sql3 } from "drizzle-orm";
247
676
  import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
248
677
  import { getColumns as getColumns2 } from "drizzle-orm/utils";
249
678
  import { createSchemaFactory } from "drizzle-orm/zod";
@@ -252,6 +681,7 @@ import {
252
681
  batchMutationRequestSchema,
253
682
  getOmittedProjectedColumns as getOmittedProjectionColumns,
254
683
  getProjectedColumns as getProjectedColumns2,
684
+ isManagedFieldGuarded as isManagedFieldGuarded2,
255
685
  resolveServerVersionColumnName as resolveServerVersionColumnName2
256
686
  } from "@pgxsinkit/contracts";
257
687
 
@@ -349,14 +779,16 @@ function asSqlState(value) {
349
779
  }
350
780
 
351
781
  // packages/server/src/mutations/plpgsql-apply.ts
352
- import { getTableName, sql } from "drizzle-orm";
782
+ import { getTableName, sql as sql2 } from "drizzle-orm";
353
783
  import { getTableConfig } from "drizzle-orm/pg-core";
354
784
  import { getColumns } from "drizzle-orm/utils";
355
785
  import {
786
+ buildRoleGuardedStatement,
356
787
  CLOCK_US_CALL_SQL_TEXT,
357
788
  escapeSqlLiteral as toSqlLiteral,
358
789
  getProjectedColumns,
359
790
  hashString,
791
+ isManagedFieldGuarded,
360
792
  quoteIdentifier as quoteIdent,
361
793
  resolveServerVersionColumnName
362
794
  } from "@pgxsinkit/contracts";
@@ -369,6 +801,29 @@ function qualifyIdent(schemaName, name) {
369
801
  function toSqlTextOrNull(value) {
370
802
  return value.length > 0 ? `'${toSqlLiteral(value)}'` : "NULL";
371
803
  }
804
+ function columnDimensions(column) {
805
+ return column.dimensions ?? 0;
806
+ }
807
+ function buildPayloadValueExpression(tableName, column) {
808
+ const columnLiteral = `'${toSqlLiteral(column.name)}'`;
809
+ const dimensions = columnDimensions(column);
810
+ const sqlType = column.getSQLType();
811
+ if (dimensions === 0) {
812
+ return `(x.p->>${columnLiteral})::${sqlType}`;
813
+ }
814
+ if (dimensions > 1) {
815
+ throw new Error(`plpgsql apply generator: column ${tableName}.${column.name} is a ${dimensions}-dimensional array; ` + `multi-dimensional arrays are not supported by the apply function (use a single-dimension array, ` + `or a jsonb column)`);
816
+ }
817
+ const elementExpansion = isJsonElementType(sqlType) ? "jsonb_array_elements" : "jsonb_array_elements_text";
818
+ return `CASE WHEN jsonb_typeof(x.p->${columnLiteral}) = 'array' THEN ` + `ARRAY(SELECT e FROM ${elementExpansion}(x.p->${columnLiteral}) WITH ORDINALITY AS a(e, ord) ORDER BY ord)` + `::${sqlType}[] END`;
819
+ }
820
+ function isJsonElementType(sqlType) {
821
+ const normalized = sqlType.trim().toLowerCase();
822
+ return normalized === "json" || normalized === "jsonb";
823
+ }
824
+ function toColumnCandidateRow(tableName, column) {
825
+ return `('${toSqlLiteral(column.name)}', '${toSqlLiteral(buildPayloadValueExpression(tableName, column))}')`;
826
+ }
372
827
  function buildManagedFieldExpression(field) {
373
828
  if (field.strategy === "authClaim") {
374
829
  const path = (field.claimPath ?? []).join(",");
@@ -377,22 +832,24 @@ function buildManagedFieldExpression(field) {
377
832
  }
378
833
  return CLOCK_US_CALL_SQL_TEXT;
379
834
  }
380
- function getManagedFieldsForOperation(entry, operation) {
835
+ function resolveManagedFields(entry) {
836
+ const tableName = getTableName(entry.table);
381
837
  const columns = getColumns(entry.table);
382
838
  const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
383
839
  return (entry.governance?.managedFields ?? []).flatMap((field) => {
384
- if (!field.applyOn.includes(operation)) {
385
- return [];
386
- }
387
840
  const columnName = columnNameMap.get(field.column);
388
841
  if (!columnName) {
389
842
  return [];
390
843
  }
391
844
  const column = columns[field.column] ?? Object.values(columns).find((candidate) => candidate.name === field.column);
845
+ if (column && columnDimensions(column) > 0) {
846
+ throw new Error(`plpgsql apply generator: managed field ${tableName}.${columnName} is an array column; ` + `managed fields stamp a single scalar value and are not supported on array columns`);
847
+ }
392
848
  return [
393
849
  {
394
850
  propertyKey: field.column,
395
851
  columnName,
852
+ applyOn: field.applyOn,
396
853
  strategy: field.strategy,
397
854
  ...field.claimPath ? { claimPath: field.claimPath } : {},
398
855
  ...field.cast ? { cast: field.cast } : {},
@@ -412,16 +869,20 @@ function buildTableBranch(entry) {
412
869
  if (!columnObject) {
413
870
  throw new Error(`plpgsql apply generator: primary key column ${columnName} not found on table ${tableName}; ` + `the entry's primaryKey spec has drifted from its Drizzle table`);
414
871
  }
872
+ if (columnDimensions(columnObject) > 0) {
873
+ throw new Error(`plpgsql apply generator: primary key column ${tableName}.${columnName} is an array column; ` + `array columns are not supported as primary keys by the apply function`);
874
+ }
415
875
  return { name: columnName, type: columnObject.getSQLType() };
416
876
  });
417
877
  const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));
418
- const createManagedFields = getManagedFieldsForOperation(entry, "create");
419
- const updateManagedFields = getManagedFieldsForOperation(entry, "update");
420
- const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));
421
- const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));
422
- const allColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => !createManagedFieldNames.has(column.name)).map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`).join(`,
878
+ const managedFields = resolveManagedFields(entry);
879
+ const createManagedFields = managedFields.filter((field) => field.applyOn.includes("create"));
880
+ const updateManagedFields = managedFields.filter((field) => field.applyOn.includes("update"));
881
+ const createGuardedColumnNames = new Set(managedFields.filter((field) => isManagedFieldGuarded(field, "create")).map((field) => field.columnName));
882
+ const updateGuardedColumnNames = new Set(managedFields.filter((field) => isManagedFieldGuarded(field, "update")).map((field) => field.columnName));
883
+ const allColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => !createGuardedColumnNames.has(column.name)).map((column) => toColumnCandidateRow(tableName, column)).join(`,
423
884
  `);
424
- const nonPrimaryKeyColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => !primaryKeyColumnNames.has(column.name) && !updateManagedFieldNames.has(column.name)).map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`).join(`,
885
+ const nonPrimaryKeyColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => !primaryKeyColumnNames.has(column.name) && !updateGuardedColumnNames.has(column.name)).map((column) => toColumnCandidateRow(tableName, column)).join(`,
425
886
  `);
426
887
  const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(", ");
427
888
  const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field)).join(", ");
@@ -438,17 +899,17 @@ function buildTableBranch(entry) {
438
899
  const deleteSql = `DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}) WHERE ${pkDeleteJoin}`.replace(/'/g, "''");
439
900
  const createColumnSelect = allColumnPairs.length ? `SELECT
440
901
  string_agg(quote_ident(col_name), ', ' ORDER BY col_name),
441
- string_agg(format('(x.p->>%L)::%s', col_name, col_type), ', ' ORDER BY col_name)
902
+ string_agg(col_value, ', ' ORDER BY col_name)
442
903
  INTO v_cols, v_vals
443
904
  FROM (VALUES
444
905
  ${allColumnPairs}
445
- ) AS col_types(col_name, col_type)
906
+ ) AS col_types(col_name, col_value)
446
907
  WHERE col_name = ANY(string_to_array(v_sig, ','));` : `v_cols := NULL; v_vals := NULL;`;
447
- const updateSetSelect = nonPrimaryKeyColumnPairs.length ? `SELECT string_agg(format('%I = (x.p->>%L)::%s', col_name, col_name, col_type), ', ' ORDER BY col_name)
908
+ const updateSetSelect = nonPrimaryKeyColumnPairs.length ? `SELECT string_agg(format('%I = %s', col_name, col_value), ', ' ORDER BY col_name)
448
909
  INTO v_set
449
910
  FROM (VALUES
450
911
  ${nonPrimaryKeyColumnPairs}
451
- ) AS col_types(col_name, col_type)
912
+ ) AS col_types(col_name, col_value)
452
913
  WHERE col_name = ANY(string_to_array(v_sig, ','));` : `v_set := NULL;`;
453
914
  const createBranch = `
454
915
  ${createColumnSelect}
@@ -533,10 +994,92 @@ function buildTableBranch(entry) {
533
994
  var APPLY_FUNCTION_NAME = "pgxsinkit_apply_mutations";
534
995
  var APPLY_FUNCTION_ARG_TYPES = "jsonb, text, boolean, boolean, jsonb, text";
535
996
  var APPLY_FINGERPRINT_PREFIX = "pgxsinkit:fp1:";
997
+ var SUPABASE_DEFAULT_PRIVILEGE_ROLES = ["anon", "authenticated", "service_role"];
998
+ var GRANT_ROLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
999
+ function resolveApplyFunctionSchema(functionSchema) {
1000
+ if (functionSchema === undefined) {
1001
+ return;
1002
+ }
1003
+ if (typeof functionSchema !== "string" || functionSchema.trim().length === 0) {
1004
+ throw new Error("plpgsql apply generator: functionSchema is empty");
1005
+ }
1006
+ if (!GRANT_ROLE_NAME_PATTERN.test(functionSchema)) {
1007
+ throw new Error(`plpgsql apply generator: functionSchema '${functionSchema}' is not a plain SQL identifier ` + `(letters, digits, '_' and '$', not starting with a digit)`);
1008
+ }
1009
+ if (functionSchema.length > 63) {
1010
+ throw new Error(`plpgsql apply generator: functionSchema '${functionSchema}' exceeds PostgreSQL's 63-byte name limit`);
1011
+ }
1012
+ return functionSchema;
1013
+ }
1014
+ function resolveGrantExecuteRoles(grantExecuteTo) {
1015
+ const roles = grantExecuteTo ?? [];
1016
+ const seen = new Set;
1017
+ for (const role of roles) {
1018
+ if (typeof role !== "string" || role.trim().length === 0) {
1019
+ throw new Error("plpgsql apply generator: grantExecuteTo contains an empty role name");
1020
+ }
1021
+ if (!GRANT_ROLE_NAME_PATTERN.test(role)) {
1022
+ throw new Error(`plpgsql apply generator: grantExecuteTo role '${role}' is not a plain SQL identifier ` + `(letters, digits, '_' and '$', not starting with a digit)`);
1023
+ }
1024
+ if (role.length > 63) {
1025
+ throw new Error(`plpgsql apply generator: grantExecuteTo role '${role}' exceeds PostgreSQL's 63-byte name limit`);
1026
+ }
1027
+ if (seen.has(role)) {
1028
+ throw new Error(`plpgsql apply generator: grantExecuteTo lists role '${role}' more than once`);
1029
+ }
1030
+ seen.add(role);
1031
+ }
1032
+ return [...roles].sort();
1033
+ }
1034
+ function buildApplyFunctionAclConvergerSql(signature, grantExecuteTo) {
1035
+ const keepList = grantExecuteTo.length > 0 ? `ARRAY[${grantExecuteTo.map((role) => `'${toSqlLiteral(role)}'`).join(", ")}]::text[]` : `ARRAY[]::text[]`;
1036
+ return `DO $$
1037
+ DECLARE
1038
+ _fn oid := '${toSqlLiteral(signature)}'::regprocedure;
1039
+ _owner oid;
1040
+ _keep text[] := ${keepList};
1041
+ _grantees oid[];
1042
+ _grantee oid;
1043
+ _grantee_name text;
1044
+ BEGIN
1045
+ SELECT p.proowner INTO _owner FROM pg_proc AS p WHERE p.oid = _fn;
1046
+ SELECT array_agg(DISTINCT acl.grantee) INTO _grantees
1047
+ FROM pg_proc AS p, aclexplode(p.proacl) AS acl
1048
+ WHERE p.oid = _fn;
1049
+
1050
+ FOREACH _grantee IN ARRAY COALESCE(_grantees, ARRAY[]::oid[]) LOOP
1051
+ IF _grantee = _owner THEN
1052
+ CONTINUE;
1053
+ END IF;
1054
+ IF _grantee = 0 THEN
1055
+ EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', _fn::regprocedure::text);
1056
+ CONTINUE;
1057
+ END IF;
1058
+ _grantee_name := pg_get_userbyid(_grantee);
1059
+ IF _grantee_name = ANY (_keep) THEN
1060
+ CONTINUE;
1061
+ END IF;
1062
+ EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM %I', _fn::regprocedure::text, _grantee_name);
1063
+ END LOOP;
1064
+ END;
1065
+ $$;`;
1066
+ }
1067
+ function buildApplyFunctionAclSql(functionName, grantExecuteTo) {
1068
+ const signature = `${functionName}(${APPLY_FUNCTION_ARG_TYPES})`;
1069
+ return [
1070
+ `REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC;`,
1071
+ ...SUPABASE_DEFAULT_PRIVILEGE_ROLES.map((role) => buildRoleGuardedStatement(role, `REVOKE ALL ON FUNCTION ${signature} FROM ${quoteIdent(role)}`)),
1072
+ buildApplyFunctionAclConvergerSql(signature, grantExecuteTo),
1073
+ ...grantExecuteTo.map((role) => buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${signature} TO ${quoteIdent(role)}`))
1074
+ ].join(`
1075
+
1076
+ `);
1077
+ }
536
1078
  function buildApplyFunctionBody(registry, options = {}) {
537
1079
  const tableBranches = Object.values(registry).filter((entry) => !entry.readProjection).map((entry) => buildTableBranch(entry)).join(`
538
1080
  `);
539
- const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);
1081
+ const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);
1082
+ const aclSql = buildApplyFunctionAclSql(functionName, resolveGrantExecuteRoles(options.grantExecuteTo));
540
1083
  return `
541
1084
  -- Install idempotently by dropping the current signature first. PostgreSQL cannot change a function's
542
1085
  -- return type through CREATE OR REPLACE, while a generated artifact must install its complete definition.
@@ -724,6 +1267,13 @@ BEGIN
724
1267
  FROM jsonb_array_elements(v_conflicts) AS c;
725
1268
  END;
726
1269
  $$;
1270
+
1271
+ -- ADR-0054: deny by default. Emitted on EVERY install because the DROP above resets the ACL to
1272
+ -- Postgres's PUBLIC default (plus Supabase's default-privilege grants), so convergence cannot depend
1273
+ -- on install history. EXECUTE is owner-only unless the artifact was generated with an explicit
1274
+ -- --grant-execute-to; the grant list is the write path's ENTIRE trust boundary, because this function
1275
+ -- trusts the claims it is handed.
1276
+ ${aclSql}
727
1277
  `.trim();
728
1278
  }
729
1279
  function expectedApplyFingerprint(registry, options = {}) {
@@ -731,14 +1281,14 @@ function expectedApplyFingerprint(registry, options = {}) {
731
1281
  }
732
1282
  function buildPlpgsqlBatchFunctionDdl(registry, options = {}) {
733
1283
  const body = buildApplyFunctionBody(registry, options);
734
- const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);
1284
+ const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);
735
1285
  const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);
736
1286
  return `${body}
737
1287
 
738
1288
  COMMENT ON FUNCTION ${functionName}(${APPLY_FUNCTION_ARG_TYPES}) IS '${fingerprint}';`;
739
1289
  }
740
1290
  async function verifyRlsAuthHelpers(db) {
741
- const result = await db.execute(sql`
1291
+ const result = await db.execute(sql2`
742
1292
  SELECT
743
1293
  to_regprocedure('auth.uid()')::text AS "authUid"
744
1294
  `);
@@ -750,8 +1300,9 @@ async function verifyRlsAuthHelpers(db) {
750
1300
  }
751
1301
  async function executePlpgsqlBatch(tx, batch, requestPath, logEnabled, rlsEnabled, userClaims, expectedFingerprint, options = {}) {
752
1302
  const normalizedClaims = userClaims ?? {};
753
- const functionRef = options.functionSchema ? sql`${sql.identifier(options.functionSchema)}.${sql.identifier("pgxsinkit_apply_mutations")}` : sql`${sql.identifier("pgxsinkit_apply_mutations")}`;
754
- const result = await tx.execute(sql`SELECT "mutation_id"::text AS "mutationId", "table_name" AS "tableName", "current_server_version"::text AS "currentServerVersion" FROM ${functionRef}(${JSON.stringify(batch)}::text::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::text::jsonb, ${expectedFingerprint})`);
1303
+ const functionSchema = resolveApplyFunctionSchema(options.functionSchema);
1304
+ const functionRef = functionSchema ? sql2`${sql2.identifier(functionSchema)}.${sql2.identifier("pgxsinkit_apply_mutations")}` : sql2`${sql2.identifier("pgxsinkit_apply_mutations")}`;
1305
+ const result = await tx.execute(sql2`SELECT "mutation_id"::text AS "mutationId", "table_name" AS "tableName", "current_server_version"::text AS "currentServerVersion" FROM ${functionRef}(${JSON.stringify(batch)}::text::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::text::jsonb, ${expectedFingerprint})`);
755
1306
  const rows = Array.from(result, (row) => row);
756
1307
  return rows.flatMap((row) => row.mutationId != null ? [
757
1308
  {
@@ -768,9 +1319,15 @@ var { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({
768
1319
  });
769
1320
  var batchMutationPaths = ["/api/mutations"];
770
1321
  var authoritativeMutationPaths = ["/api/mutations/unit"];
771
- function createMutationHandler(db, registry, operationsLogConfig, operationsLogReady, resolveAuthClaims, startupVerification = "in-process", logTimings = false) {
1322
+ function createMutationHandler(db, registry, operationsLogConfig, operationsLogReady, resolveAuthClaims, startupVerification = "in-process", logTimings = false, applyFunctionGrantExecuteTo = [], applyFunctionSchema) {
772
1323
  let startupReadyPromise;
773
- const expectedFingerprint = expectedApplyFingerprint(registry);
1324
+ const applyFunctionRenderOptions = {
1325
+ ...applyFunctionGrantExecuteTo.length > 0 ? { grantExecuteTo: applyFunctionGrantExecuteTo } : {},
1326
+ ...applyFunctionSchema ? { functionSchema: applyFunctionSchema } : {}
1327
+ };
1328
+ const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);
1329
+ const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};
1330
+ const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);
774
1331
  const perfNow2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
775
1332
  const withTiming = (route, handler) => {
776
1333
  if (!logTimings) {
@@ -849,7 +1406,7 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
849
1406
  if (payloadKeys.length === 0) {
850
1407
  throw new Error("At least one field must be provided");
851
1408
  }
852
- createMutationInsertSchema(syncEntry.table).partial().parse(normalizedPayload);
1409
+ buildUpdateValidationSchema(syncEntry).parse(normalizedPayload);
853
1410
  } else if (mutation.kind === "create") {
854
1411
  buildCreateValidationSchema(syncEntry).parse(normalizedPayload);
855
1412
  }
@@ -949,7 +1506,7 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
949
1506
  const resolvedClaims = await resolveAuthClaims?.(request);
950
1507
  if (timing)
951
1508
  timing.authMs = perfNow2() - authStart;
952
- if (!isPlainObject(resolvedClaims)) {
1509
+ if (!isPlainObject2(resolvedClaims)) {
953
1510
  await logOperationSafely(db, operationsLogConfig, {
954
1511
  tableName: null,
955
1512
  operationKind: null,
@@ -966,13 +1523,13 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
966
1523
  actorUserId = getUuidClaim(userClaims, "sub");
967
1524
  }
968
1525
  const batchRequest = sanitizeRestrictedFields(body, registry);
969
- await tx.execute(sql2`SET CONSTRAINTS ALL DEFERRED`);
1526
+ await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
970
1527
  const applyStart = timing ? perfNow2() : 0;
971
- const conflicts = await executePlpgsqlBatch(tx, batchRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint);
1528
+ const conflicts = await executePlpgsqlBatch(tx, batchRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint, applyInvocationOptions);
972
1529
  if (timing)
973
1530
  timing.applyMs = perfNow2() - applyStart;
974
1531
  if (shouldApplyRlsContext) {
975
- await tx.execute(sql2`RESET ROLE`);
1532
+ await tx.execute(sql3`RESET ROLE`);
976
1533
  }
977
1534
  const conflictByMutationId = new Map(conflicts.map((conflict) => [conflict.mutationId, conflict]));
978
1535
  for (const mutation of batchRequest.mutations) {
@@ -1113,7 +1670,7 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1113
1670
  const resolvedClaims = await resolveAuthClaims?.(request);
1114
1671
  if (timing)
1115
1672
  timing.authMs = perfNow2() - authStart;
1116
- if (!isPlainObject(resolvedClaims)) {
1673
+ if (!isPlainObject2(resolvedClaims)) {
1117
1674
  await logOperationSafely(db, operationsLogConfig, {
1118
1675
  tableName: null,
1119
1676
  operationKind: null,
@@ -1130,13 +1687,13 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1130
1687
  actorUserId = getUuidClaim(userClaims, "sub");
1131
1688
  }
1132
1689
  const unitRequest = sanitizeRestrictedFields(body, registry);
1133
- await tx.execute(sql2`SET CONSTRAINTS ALL DEFERRED`);
1690
+ await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
1134
1691
  const applyStart = timing ? perfNow2() : 0;
1135
- const conflicts = await executePlpgsqlBatch(tx, unitRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint);
1692
+ const conflicts = await executePlpgsqlBatch(tx, unitRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint, applyInvocationOptions);
1136
1693
  if (timing)
1137
1694
  timing.applyMs = perfNow2() - applyStart;
1138
1695
  if (shouldApplyRlsContext) {
1139
- await tx.execute(sql2`RESET ROLE`);
1696
+ await tx.execute(sql3`RESET ROLE`);
1140
1697
  }
1141
1698
  if (conflicts.length > 0) {
1142
1699
  unitConflicts = conflicts;
@@ -1253,7 +1810,7 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1253
1810
  function isValidationError(error) {
1254
1811
  return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
1255
1812
  }
1256
- function isPlainObject(value) {
1813
+ function isPlainObject2(value) {
1257
1814
  return typeof value === "object" && value !== null && !Array.isArray(value);
1258
1815
  }
1259
1816
  function formatBatchExecutionError(error) {
@@ -1339,10 +1896,10 @@ function getUuidClaim(claims, key) {
1339
1896
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;
1340
1897
  }
1341
1898
  function findManagedFieldViolations(entry, mutationKind, payload) {
1342
- if (mutationKind === "delete" || !isPlainObject(payload)) {
1899
+ if (mutationKind === "delete" || !isPlainObject2(payload)) {
1343
1900
  return [];
1344
1901
  }
1345
- const managedFields = getManagedFieldsForOperation2(entry, mutationKind);
1902
+ const managedFields = getGuardedManagedFields(entry, mutationKind);
1346
1903
  if (managedFields.length === 0) {
1347
1904
  return [];
1348
1905
  }
@@ -1353,7 +1910,7 @@ var warnedDroppedPayloadKeys = new Set;
1353
1910
  var MAX_WARNED_DROPPED_KEYS = 1e4;
1354
1911
  var droppedKeyWarningSuppressed = false;
1355
1912
  function warnOnSilentlyDroppedPayloadKeys(entry, tableName, mutationKind, payload) {
1356
- if (mutationKind === "delete" || !isPlainObject(payload)) {
1913
+ if (mutationKind === "delete" || !isPlainObject2(payload)) {
1357
1914
  return;
1358
1915
  }
1359
1916
  const writable = new Set;
@@ -1361,7 +1918,7 @@ function warnOnSilentlyDroppedPayloadKeys(entry, tableName, mutationKind, payloa
1361
1918
  writable.add(propertyKey);
1362
1919
  writable.add(columnName);
1363
1920
  }
1364
- for (const { propertyKey, columnName } of getManagedFieldsForOperation2(entry, mutationKind)) {
1921
+ for (const { propertyKey, columnName } of getManagedFieldsForOperation(entry, mutationKind)) {
1365
1922
  writable.add(propertyKey);
1366
1923
  writable.add(columnName);
1367
1924
  }
@@ -1390,7 +1947,7 @@ function warnOnSilentlyDroppedPayloadKeys(entry, tableName, mutationKind, payloa
1390
1947
  }
1391
1948
  }
1392
1949
  function findProjectedFieldViolations(entry, mutationKind, payload) {
1393
- if (mutationKind === "delete" || !isPlainObject(payload)) {
1950
+ if (mutationKind === "delete" || !isPlainObject2(payload)) {
1394
1951
  return [];
1395
1952
  }
1396
1953
  const projectedFields = getProjectedAwayFields(entry);
@@ -1412,12 +1969,12 @@ function sanitizeRestrictedFields(batch, registry) {
1412
1969
  if (!entry) {
1413
1970
  return mutation;
1414
1971
  }
1415
- const managedFields = getManagedFieldsForOperation2(entry, mutation.kind);
1972
+ const managedFields = getGuardedManagedFields(entry, mutation.kind);
1416
1973
  const projectedFields = getProjectedAwayFields(entry);
1417
1974
  if (managedFields.length === 0 && projectedFields.length === 0) {
1418
1975
  return mutation;
1419
1976
  }
1420
- const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};
1977
+ const payload = isPlainObject2(mutation.payload) ? { ...mutation.payload } : {};
1421
1978
  for (const field of managedFields) {
1422
1979
  delete payload[field.propertyKey];
1423
1980
  delete payload[field.columnName];
@@ -1435,25 +1992,40 @@ function sanitizeRestrictedFields(batch, registry) {
1435
1992
  }
1436
1993
  function buildCreateValidationSchema(entry) {
1437
1994
  const createSchema = createMutationInsertSchema(entry.table);
1438
- const managedCreateKeys = getManagedFieldsForOperation2(entry, "create").map((field) => field.propertyKey);
1995
+ const managedCreateKeys = getGuardedManagedFields(entry, "create").map((field) => field.propertyKey);
1439
1996
  if (managedCreateKeys.length === 0) {
1440
1997
  return createSchema;
1441
1998
  }
1442
1999
  const omitMask = Object.fromEntries(managedCreateKeys.map((key) => [key, true]));
1443
2000
  return createSchema.omit(omitMask);
1444
2001
  }
1445
- function getManagedFieldsForOperation2(entry, mutationKind) {
1446
- if (mutationKind === "delete") {
1447
- return [];
2002
+ function buildUpdateValidationSchema(entry) {
2003
+ const updateSchema = createMutationInsertSchema(entry.table).partial();
2004
+ const managedKeys = getGuardedManagedFields(entry, "update").map((field) => field.propertyKey);
2005
+ if (managedKeys.length === 0) {
2006
+ return updateSchema;
1448
2007
  }
2008
+ const omitMask = Object.fromEntries(managedKeys.map((key) => [key, true]));
2009
+ return updateSchema.omit(omitMask);
2010
+ }
2011
+ function getManagedFields(entry, matches) {
1449
2012
  const columns = getColumns2(entry.table);
1450
2013
  const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
1451
- return (entry.governance?.managedFields ?? []).filter((field) => field.applyOn.includes(mutationKind)).map((field) => ({
2014
+ return (entry.governance?.managedFields ?? []).filter((field) => matches(field)).map((field) => ({
1452
2015
  propertyKey: field.column,
1453
2016
  columnName: columnMap.get(field.column) ?? field.column,
1454
2017
  strategy: field.strategy
1455
2018
  }));
1456
2019
  }
2020
+ function getManagedFieldsForOperation(entry, mutationKind) {
2021
+ if (mutationKind === "delete") {
2022
+ return [];
2023
+ }
2024
+ return getManagedFields(entry, (field) => field.applyOn.includes(mutationKind));
2025
+ }
2026
+ function getGuardedManagedFields(entry, mutationKind) {
2027
+ return getManagedFields(entry, (field) => isManagedFieldGuarded2(field, mutationKind));
2028
+ }
1457
2029
  function getProjectedAwayFields(entry) {
1458
2030
  return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({
1459
2031
  propertyKey,
@@ -1461,7 +2033,7 @@ function getProjectedAwayFields(entry) {
1461
2033
  }));
1462
2034
  }
1463
2035
  function toSchemaPayload(entry, payload) {
1464
- if (!isPlainObject(payload)) {
2036
+ if (!isPlainObject2(payload)) {
1465
2037
  return payload;
1466
2038
  }
1467
2039
  const columns = getColumns2(entry.table);
@@ -1494,7 +2066,7 @@ async function readServerUpdatedAtUs(tx, entry, entityKey) {
1494
2066
  return eq(primaryKeyTableColumn, rawValue);
1495
2067
  });
1496
2068
  const whereClause = conditions.length === 1 ? conditions[0] : and(...conditions);
1497
- const rows = await tx.select({ updatedAtUs: sql2`${updatedAtColumn}::text` }).from(entry.table).where(whereClause).limit(1);
2069
+ const rows = await tx.select({ updatedAtUs: sql3`${updatedAtColumn}::text` }).from(entry.table).where(whereClause).limit(1);
1498
2070
  return rows[0]?.updatedAtUs ?? undefined;
1499
2071
  }
1500
2072
  async function installStartupDdl(db, registry) {
@@ -1504,7 +2076,7 @@ async function installStartupDdl(db, registry) {
1504
2076
  }
1505
2077
 
1506
2078
  // packages/server/src/operations-log/ddl.ts
1507
- import { getTableName as getTableName2, sql as sql3 } from "drizzle-orm";
2079
+ import { getTableName as getTableName2, sql as sql4 } from "drizzle-orm";
1508
2080
  function operationsLogRegclassTarget() {
1509
2081
  return `public.${getTableName2(operationsLogTable)}`;
1510
2082
  }
@@ -1513,7 +2085,7 @@ async function ensureOperationsLogSchema(db, config) {
1513
2085
  return false;
1514
2086
  }
1515
2087
  try {
1516
- const result = await db.execute(sql3`
2088
+ const result = await db.execute(sql4`
1517
2089
  SELECT to_regclass(${operationsLogRegclassTarget()})::text AS "tableName"
1518
2090
  `);
1519
2091
  const row = Array.from(result, (entry) => entry)[0];
@@ -1597,7 +2169,9 @@ class FetchRouter {
1597
2169
  }
1598
2170
  }
1599
2171
  // packages/server/src/migrations/utilities.ts
1600
- import { NOW_MICROSECONDS_SQL_TEXT } from "@pgxsinkit/contracts";
2172
+ import { buildRoleGuardedStatement as buildRoleGuardedStatement2, NOW_MICROSECONDS_SQL_TEXT, quoteIdentifier } from "@pgxsinkit/contracts";
2173
+ var CLOCK_US_SIGNATURE = "public.pgxsinkit_clock_us()";
2174
+ var CLOCK_US_GRANTEES = ["anon", "authenticated", "service_role"];
1601
2175
  function renderPgxsinkitUtilitiesMigration() {
1602
2176
  return `-- The pgxsinkit canonical microsecond clock. Deliberately clock_timestamp() (advances WITHIN a
1603
2177
  -- transaction \u2014 LWW/audit ordering of multi-row applies depends on it), never now()/transaction_timestamp()
@@ -1608,7 +2182,366 @@ CREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()
1608
2182
  VOLATILE
1609
2183
  AS $$
1610
2184
  SELECT ${NOW_MICROSECONDS_SQL_TEXT}
1611
- $$;`;
2185
+ $$;
2186
+
2187
+ -- Deny by default, then grant back deliberately (ADR-0054 decision 5). Stated on every install: a
2188
+ -- first install on a Supabase-shaped cluster otherwise picks up ALTER DEFAULT PRIVILEGES ... GRANT ALL
2189
+ -- ON FUNCTIONS TO anon, authenticated, service_role, so the posture is declared here, never inherited.
2190
+ -- The grants are real: a column DEFAULT calling this clock is evaluated as whatever role writes the row.
2191
+ REVOKE ALL ON FUNCTION ${CLOCK_US_SIGNATURE} FROM PUBLIC;
2192
+
2193
+ ${CLOCK_US_GRANTEES.map((role) => buildRoleGuardedStatement2(role, `GRANT EXECUTE ON FUNCTION ${CLOCK_US_SIGNATURE} TO ${quoteIdentifier(role)}`)).join(`
2194
+
2195
+ `)}`;
2196
+ }
2197
+ // packages/server/src/events/consumer.ts
2198
+ import {
2199
+ getSyncRegistryStreams as getSyncRegistryStreams2
2200
+ } from "@pgxsinkit/contracts";
2201
+ var DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;
2202
+ var DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;
2203
+ var DEFAULT_EVENT_MAX_ATTEMPTS = 5;
2204
+ var DEFAULT_EVENT_POLL_FLOOR_MS = 250;
2205
+ var DEFAULT_EVENT_POLL_CEILING_MS = 5000;
2206
+ var DEFAULT_EVENT_POLL_FACTOR = 2;
2207
+ var DEFAULT_EVENT_DRAIN_BUDGET_MS = 25000;
2208
+ function computeEventPollWaitMs(idleCount, options = {}) {
2209
+ const floorMs = options.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS;
2210
+ const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS;
2211
+ const factor = options.factor ?? DEFAULT_EVENT_POLL_FACTOR;
2212
+ const exponent = Math.max(idleCount - 1, 0);
2213
+ return Math.min(Math.round(floorMs * factor ** exponent), ceilingMs);
2214
+ }
2215
+ var abortableSleep = (ms, signal) => new Promise((resolve) => {
2216
+ if (signal.aborted) {
2217
+ resolve();
2218
+ return;
2219
+ }
2220
+ let handle;
2221
+ const finish = () => {
2222
+ if (handle !== undefined) {
2223
+ clearTimeout(handle);
2224
+ }
2225
+ signal.removeEventListener("abort", finish);
2226
+ resolve();
2227
+ };
2228
+ handle = setTimeout(finish, ms);
2229
+ signal.addEventListener("abort", finish, { once: true });
2230
+ });
2231
+ function assertPositive(label, value, minimum) {
2232
+ if (!Number.isFinite(value) || value < minimum) {
2233
+ throw new Error(`pgxsinkit: defineEventConsumer's \`${label}\` must be a finite number >= ${minimum} (got ${value}).`);
2234
+ }
2235
+ return value;
2236
+ }
2237
+ function defineEventConsumer(options) {
2238
+ const registered = getSyncRegistryStreams2(options.registry) ?? {};
2239
+ const registeredNames = Object.keys(registered);
2240
+ if (registeredNames.length === 0) {
2241
+ throw new Error("pgxsinkit: this registry registers no Event streams, so there is nothing for a consumer runner to " + "consume. Register one with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ \u2026 }) } })`.");
2242
+ }
2243
+ let streams;
2244
+ if (options.streams) {
2245
+ const unknown = options.streams.filter((stream) => !Object.hasOwn(registered, stream));
2246
+ if (unknown.length > 0) {
2247
+ throw new Error(`pgxsinkit: defineEventConsumer was asked for Event stream(s) [${unknown.join(", ")}] this registry ` + `does not register \u2014 it registers [${registeredNames.join(", ")}].`);
2248
+ }
2249
+ streams = [...new Set(options.streams)];
2250
+ if (streams.length === 0) {
2251
+ throw new Error("pgxsinkit: defineEventConsumer was given an empty `streams` list. Omit it to consume every registered " + "Event stream, or name at least one.");
2252
+ }
2253
+ } else {
2254
+ streams = registeredNames;
2255
+ }
2256
+ const batchSize = assertPositive("batchSize", options.batchSize ?? DEFAULT_EVENT_CONSUMER_BATCH_SIZE, 1);
2257
+ const visibilityTimeoutSeconds = assertPositive("visibilityTimeoutSeconds", options.visibilityTimeoutSeconds ?? DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS, 1);
2258
+ const concurrency = assertPositive("concurrency", options.concurrency ?? 1, 1);
2259
+ const maxAttempts = assertPositive("maxAttempts", options.maxAttempts ?? DEFAULT_EVENT_MAX_ATTEMPTS, 1);
2260
+ const poll = options.poll ?? {};
2261
+ const floorMs = assertPositive("poll.floorMs", poll.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS, 0);
2262
+ const ceilingMs = assertPositive("poll.ceilingMs", poll.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS, floorMs);
2263
+ const factor = assertPositive("poll.factor", poll.factor ?? DEFAULT_EVENT_POLL_FACTOR, 1);
2264
+ const pollOptions = { floorMs, ceilingMs, factor };
2265
+ const queue = options.queue;
2266
+ const sleep = options.sleep ?? abortableSleep;
2267
+ const renewalSleep = options.renewalSleep ?? abortableSleep;
2268
+ const now = options.now ?? Date.now;
2269
+ const renewalIntervalMs = Math.max(1, Math.floor(visibilityTimeoutSeconds * 1000 / 2));
2270
+ const stopController = new AbortController;
2271
+ let started = false;
2272
+ let stopping = false;
2273
+ let loops = [];
2274
+ let stopPromise = null;
2275
+ let activeDrain = null;
2276
+ let drainStats = null;
2277
+ const reportDeadLetter = (report) => {
2278
+ console.warn(`pgxsinkit: dead-lettered an event sub-batch on Event stream "${report.stream}" (receipt ${report.receipt}, ` + `${report.attempts} delivery attempt(s)) \u2014 ${report.reason}. It is in the queue's dead-letter storage; ` + "requeue it deliberately with `requeueDeadLetter` once the cause is fixed.", report.cause);
2279
+ if (!options.onDeadLetter) {
2280
+ return;
2281
+ }
2282
+ try {
2283
+ options.onDeadLetter(report);
2284
+ } catch (error) {
2285
+ console.error("pgxsinkit: the `onDeadLetter` hook threw; the message is dead-lettered regardless", error);
2286
+ }
2287
+ };
2288
+ const deadLetter = async (stream, receipt, attempts, reason, cause, message) => {
2289
+ try {
2290
+ await queue.deadLetter(stream, [receipt], reason);
2291
+ } catch (error) {
2292
+ console.warn(`pgxsinkit: could not dead-letter message ${receipt} on Event stream "${stream}"; it stays queued and ` + "will be retried", error);
2293
+ return false;
2294
+ }
2295
+ if (drainStats) {
2296
+ drainStats.deadLettered += 1;
2297
+ }
2298
+ reportDeadLetter({ stream, reason, attempts, receipt, ...message ? { message } : {}, cause });
2299
+ return true;
2300
+ };
2301
+ const startRenewal = (stream, unsettled) => {
2302
+ const controller = new AbortController;
2303
+ const task = (async () => {
2304
+ while (!controller.signal.aborted && unsettled.size > 0) {
2305
+ await renewalSleep(renewalIntervalMs, controller.signal);
2306
+ if (controller.signal.aborted || unsettled.size === 0) {
2307
+ return;
2308
+ }
2309
+ try {
2310
+ await queue.extendVisibility(stream, [...unsettled], visibilityTimeoutSeconds);
2311
+ } catch (error) {
2312
+ console.warn(`pgxsinkit: could not renew the visibility lease on Event stream "${stream}" (receipts ` + `${[...unsettled].join(", ")}); the sub-batch may be redelivered while it is still being processed`, error);
2313
+ }
2314
+ }
2315
+ })();
2316
+ return async () => {
2317
+ controller.abort();
2318
+ await task;
2319
+ };
2320
+ };
2321
+ const processMessage = async (stream, delivered, settle) => {
2322
+ try {
2323
+ await options.callback({ stream, events: delivered.message.events });
2324
+ } catch (error) {
2325
+ settle();
2326
+ const detail = error instanceof Error ? error.message : String(error);
2327
+ if (delivered.deliveryCount >= maxAttempts) {
2328
+ await deadLetter(stream, delivered.receipt, delivered.deliveryCount, `the consumer callback failed on delivery ${delivered.deliveryCount} of ${maxAttempts}: ${detail}`, error, delivered.message);
2329
+ return;
2330
+ }
2331
+ console.warn(`pgxsinkit: the event consumer callback failed for Event stream "${stream}" (receipt ${delivered.receipt}, ` + `delivery ${delivered.deliveryCount} of ${maxAttempts}); the sub-batch will be redelivered after its ` + `${visibilityTimeoutSeconds}s visibility timeout`, error);
2332
+ return;
2333
+ }
2334
+ if (drainStats) {
2335
+ drainStats.delivered += 1;
2336
+ }
2337
+ try {
2338
+ await queue.ack(stream, [delivered.receipt]);
2339
+ } catch (error) {
2340
+ console.warn(`pgxsinkit: could not ack message ${delivered.receipt} on Event stream "${stream}"; it will be ` + "redelivered (the callback must be idempotent)", error);
2341
+ }
2342
+ settle();
2343
+ };
2344
+ const processDelivered = async (stream, messages, halted) => {
2345
+ const unsettled = new Set(messages.map((delivered) => delivered.receipt));
2346
+ const settleOf = (delivered) => () => unsettled.delete(delivered.receipt);
2347
+ const startedReceipts = new Set;
2348
+ const releaseUnstarted = () => {
2349
+ for (const delivered of messages) {
2350
+ if (!startedReceipts.has(delivered.receipt)) {
2351
+ unsettled.delete(delivered.receipt);
2352
+ }
2353
+ }
2354
+ };
2355
+ if (stopController.signal.aborted) {
2356
+ releaseUnstarted();
2357
+ } else {
2358
+ stopController.signal.addEventListener("abort", releaseUnstarted, { once: true });
2359
+ }
2360
+ const stopRenewal = startRenewal(stream, unsettled);
2361
+ const runOne = async (delivered) => {
2362
+ startedReceipts.add(delivered.receipt);
2363
+ await processMessage(stream, delivered, settleOf(delivered));
2364
+ };
2365
+ try {
2366
+ if (concurrency <= 1) {
2367
+ for (const delivered of messages) {
2368
+ if (halted()) {
2369
+ releaseUnstarted();
2370
+ return;
2371
+ }
2372
+ await runOne(delivered);
2373
+ }
2374
+ return;
2375
+ }
2376
+ let cursor = 0;
2377
+ const worker = async () => {
2378
+ for (;; ) {
2379
+ if (halted()) {
2380
+ releaseUnstarted();
2381
+ return;
2382
+ }
2383
+ const delivered = messages[cursor++];
2384
+ if (!delivered) {
2385
+ return;
2386
+ }
2387
+ await runOne(delivered);
2388
+ }
2389
+ };
2390
+ await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, worker));
2391
+ } finally {
2392
+ stopController.signal.removeEventListener("abort", releaseUnstarted);
2393
+ await stopRenewal();
2394
+ }
2395
+ };
2396
+ const runStream = async (stream) => {
2397
+ let idleCount = 0;
2398
+ while (!stopping) {
2399
+ let productive = false;
2400
+ try {
2401
+ const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
2402
+ if (messages.length > 0) {
2403
+ productive = true;
2404
+ await processDelivered(stream, messages, () => stopping);
2405
+ }
2406
+ } catch (error) {
2407
+ if (error instanceof MalformedEventQueueMessageError) {
2408
+ productive = await deadLetter(stream, error.receipt, 0, `the queue message body is not a valid event queue message: ${error.message}`, error);
2409
+ } else {
2410
+ console.warn(`pgxsinkit: the event consumer could not read Event stream "${stream}"; backing off and retrying`, error);
2411
+ }
2412
+ }
2413
+ if (productive) {
2414
+ idleCount = 0;
2415
+ continue;
2416
+ }
2417
+ idleCount += 1;
2418
+ if (stopping) {
2419
+ break;
2420
+ }
2421
+ await sleep(computeEventPollWaitMs(idleCount, pollOptions), stopController.signal);
2422
+ }
2423
+ };
2424
+ const runDrain = async (budgetMs) => {
2425
+ const stats = { delivered: 0, deadLettered: 0 };
2426
+ drainStats = stats;
2427
+ const deadline = now() + budgetMs;
2428
+ const pending = new Set(streams);
2429
+ let unfinished = false;
2430
+ const halted = () => stopping || now() >= deadline;
2431
+ try {
2432
+ while (pending.size > 0) {
2433
+ if (halted()) {
2434
+ unfinished = true;
2435
+ break;
2436
+ }
2437
+ for (const stream of [...pending]) {
2438
+ if (halted()) {
2439
+ unfinished = true;
2440
+ break;
2441
+ }
2442
+ let messages;
2443
+ try {
2444
+ messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
2445
+ } catch (error) {
2446
+ if (error instanceof MalformedEventQueueMessageError) {
2447
+ await deadLetter(stream, error.receipt, 0, `the queue message body is not a valid event queue message: ${error.message}`, error);
2448
+ continue;
2449
+ }
2450
+ console.warn(`pgxsinkit: the event consumer could not read Event stream "${stream}" during a bounded drain; ` + "leaving it for the next pass", error);
2451
+ pending.delete(stream);
2452
+ unfinished = true;
2453
+ continue;
2454
+ }
2455
+ if (messages.length === 0) {
2456
+ pending.delete(stream);
2457
+ continue;
2458
+ }
2459
+ await processDelivered(stream, messages, halted);
2460
+ }
2461
+ }
2462
+ } finally {
2463
+ drainStats = null;
2464
+ }
2465
+ return { delivered: stats.delivered, deadLettered: stats.deadLettered, empty: !unfinished };
2466
+ };
2467
+ return {
2468
+ start: () => {
2469
+ if (activeDrain) {
2470
+ throw new Error("pgxsinkit: this event consumer is running a bounded `drainOnce()` pass, so `start()` cannot also " + "run its polling loops \u2014 one handle drives one pacing mode at a time. Await the pass first.");
2471
+ }
2472
+ if (started || stopping) {
2473
+ return;
2474
+ }
2475
+ started = true;
2476
+ loops = streams.map((stream) => runStream(stream).catch((error) => {
2477
+ console.error(`pgxsinkit: the event consumer loop for Event stream "${stream}" ended unexpectedly`, error);
2478
+ }));
2479
+ },
2480
+ stop: () => {
2481
+ stopping = true;
2482
+ stopController.abort();
2483
+ stopPromise ??= (async () => {
2484
+ await Promise.all(loops);
2485
+ loops = [];
2486
+ await activeDrain?.catch(() => {
2487
+ return;
2488
+ });
2489
+ })();
2490
+ return stopPromise;
2491
+ },
2492
+ drainOnce: async (drainOptions = {}) => {
2493
+ if (started) {
2494
+ throw new Error("pgxsinkit: `drainOnce()` cannot run while this consumer's polling loops are live \u2014 one handle " + "drives one pacing mode at a time. Use the long-lived runner OR bounded drains, not both on one " + "handle. (Two separate PROCESSES draining the same queues concurrently is safe: the visibility " + "timeout arbitrates them.)");
2495
+ }
2496
+ if (stopping) {
2497
+ throw new Error("pgxsinkit: this event consumer handle is stopped \u2014 its lifecycle is one-way. Build a fresh " + "`defineEventConsumer` for the next drain pass; construction is query-free, so that costs nothing.");
2498
+ }
2499
+ if (activeDrain) {
2500
+ throw new Error("pgxsinkit: a `drainOnce()` pass is already in flight on this handle. Two SEPARATE PROCESSES " + "draining concurrently is safe (the queue's visibility timeouts arbitrate); two passes on one " + "handle would share its internal state, so it is refused. Await the first pass.");
2501
+ }
2502
+ const budgetMs = drainOptions.budgetMs ?? DEFAULT_EVENT_DRAIN_BUDGET_MS;
2503
+ if (!Number.isFinite(budgetMs) || budgetMs < 0) {
2504
+ throw new Error(`pgxsinkit: drainOnce's \`budgetMs\` must be a finite number >= 0 (got ${budgetMs}).`);
2505
+ }
2506
+ const pass = runDrain(budgetMs).finally(() => {
2507
+ activeDrain = null;
2508
+ });
2509
+ activeDrain = pass;
2510
+ return pass;
2511
+ }
2512
+ };
2513
+ }
2514
+ // packages/server/src/events/ddl.ts
2515
+ import { getSyncRegistryStreams as getSyncRegistryStreams3, hashString as hashString2, quoteSqlLiteral } from "@pgxsinkit/contracts";
2516
+ var EVENT_LANE_FINGERPRINT_PREFIX = "pgxsinkit:events:fp1:";
2517
+ function eventLaneStreamNames(registry) {
2518
+ return Object.keys(getSyncRegistryStreams3(registry) ?? {}).sort();
2519
+ }
2520
+ function buildEventLaneDdlBody(streamNames) {
2521
+ const header = `-- The pgxsinkit event lane's queues (ADR-0053 decision 5): one pgmq queue per registered Event stream.
2522
+ ` + `-- Provisioning is DEPLOY-TIME: the ingestion endpoint may enqueue long before any consumer runner starts.
2523
+ ` + "-- No CASCADE: pgmq's control file declares no `requires`. pgmq is non-relocatable (schema = 'pgmq').\n" + `-- pgmq.create() is idempotent (IF NOT EXISTS tables/indexes + ON CONFLICT DO NOTHING meta), so
2524
+ ` + "-- re-applying this migration is a no-op and adding a stream only appends a line.";
2525
+ const statements = streamNames.map((stream) => `SELECT pgmq.create(${quoteSqlLiteral(eventStreamQueueName(stream))});`);
2526
+ return `${header}
2527
+ CREATE EXTENSION IF NOT EXISTS pgmq;
2528
+ ${statements.join(`
2529
+ `)}`;
2530
+ }
2531
+ function assertHasStreams(registry) {
2532
+ const streamNames = eventLaneStreamNames(registry);
2533
+ if (streamNames.length === 0) {
2534
+ throw new Error("pgxsinkit: this registry registers no Event streams, so there is no event-lane DDL to emit. Register one " + "with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ \u2026 }) } })`.");
2535
+ }
2536
+ return streamNames;
2537
+ }
2538
+ function eventLaneDdlFingerprint(registry) {
2539
+ return EVENT_LANE_FINGERPRINT_PREFIX + hashString2(buildEventLaneDdlBody(assertHasStreams(registry)));
2540
+ }
2541
+ function renderEventLaneMigration(registry) {
2542
+ const body = buildEventLaneDdlBody(assertHasStreams(registry));
2543
+ return `-- ${EVENT_LANE_FINGERPRINT_PREFIX + hashString2(body)}
2544
+ ${body}`;
1612
2545
  }
1613
2546
 
1614
2547
  // packages/server/src/index.ts
@@ -1658,13 +2591,26 @@ function createSyncServer(options) {
1658
2591
  if (healthCheckPath) {
1659
2592
  router.get(healthCheckPath, () => Response.json({ ok: true }));
1660
2593
  }
1661
- const mutationHandlers = createMutationHandler(db, options.registry, operationsLogConfig, operationsLogReady, options.resolveAuthClaims, options.deployment?.startupVerification ?? "in-process", options.logTimings ?? false);
2594
+ const mutationHandlers = createMutationHandler(db, options.registry, operationsLogConfig, operationsLogReady, options.resolveAuthClaims, options.deployment?.startupVerification ?? "in-process", options.logTimings ?? false, options.applyFunctionGrantExecuteTo ?? [], options.applyFunctionSchema);
1662
2595
  for (const path of batchMutationPaths) {
1663
2596
  router.post(path, mutationHandlers.batch);
1664
2597
  }
1665
2598
  for (const path of authoritativeMutationPaths) {
1666
2599
  router.post(path, mutationHandlers.authoritative);
1667
2600
  }
2601
+ const eventStreams = getSyncRegistryStreams4(options.registry);
2602
+ if (eventStreams && Object.keys(eventStreams).length > 0) {
2603
+ const eventQueue = options.eventQueue ?? createPgmqEventQueue({ db });
2604
+ const eventHandler = createEventIngestHandler(db, options.registry, eventQueue, {
2605
+ ...options.resolveAuthClaims ? { resolveAuthClaims: options.resolveAuthClaims } : {},
2606
+ ...options.eventGate ? { eventGate: options.eventGate } : {},
2607
+ ...options.onEventsEnqueued ? { onEventsEnqueued: options.onEventsEnqueued } : {},
2608
+ logTimings: options.logTimings ?? false
2609
+ });
2610
+ for (const path of batchEventPaths) {
2611
+ router.post(path, eventHandler);
2612
+ }
2613
+ }
1668
2614
  if (options.electricUrl) {
1669
2615
  const electricUrl = options.electricUrl;
1670
2616
  const resolveAuthClaims = options.resolveAuthClaims;
@@ -1755,20 +2701,42 @@ function resolveOperationsLogConfig(options) {
1755
2701
  };
1756
2702
  }
1757
2703
  export {
2704
+ resolveEventIdentity,
1758
2705
  renderPgxsinkitUtilitiesMigration,
2706
+ renderEventLaneMigration,
1759
2707
  readSqlState,
1760
2708
  proxyElectricShapeRequest,
1761
2709
  operationsLogTable,
1762
2710
  operationsLogRegclassTarget,
1763
2711
  expectedApplyFingerprint,
2712
+ eventStreamQueueName,
2713
+ eventLaneStreamNames,
2714
+ eventLaneDdlFingerprint,
2715
+ eventIngestRequiresClaims,
1764
2716
  ensureOperationsLogSchema,
2717
+ defineEventConsumer,
1765
2718
  createSyncServer,
2719
+ createPgmqEventQueue,
1766
2720
  createMutationHandler,
2721
+ createEventIngestHandler,
2722
+ computeEventPollWaitMs,
1767
2723
  buildRegistrySchema,
1768
2724
  buildPlpgsqlBatchFunctionDdl,
1769
2725
  batchMutationPaths,
1770
2726
  authoritativeMutationPaths,
1771
- FetchRouter
2727
+ assertEventQueueReceipts,
2728
+ PGMQ_DEAD_LETTER_KEY,
2729
+ MalformedEventQueueMessageError,
2730
+ FetchRouter,
2731
+ EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,
2732
+ EVENT_LANE_FINGERPRINT_PREFIX,
2733
+ DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
2734
+ DEFAULT_EVENT_POLL_FLOOR_MS,
2735
+ DEFAULT_EVENT_POLL_FACTOR,
2736
+ DEFAULT_EVENT_POLL_CEILING_MS,
2737
+ DEFAULT_EVENT_MAX_ATTEMPTS,
2738
+ DEFAULT_EVENT_DRAIN_BUDGET_MS,
2739
+ DEFAULT_EVENT_CONSUMER_BATCH_SIZE
1772
2740
  };
1773
2741
 
1774
- //# debugId=A20A9FDEDE6EC14E64756E2164756E21
2742
+ //# debugId=5CEE23A5C2F9E5C264756E2164756E21