@pgxsinkit/server 0.2.4 → 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 +1023 -55
- 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 +28 -1
- package/dist/mutations/route.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +199 -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 +96 -17
package/dist/index.js.map
CHANGED
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/electric-proxy.ts", "../src/cors-origin.ts", "../src/mutations/route.ts", "../src/operations-log/schema.ts", "../src/operations-log/writer.ts", "../src/sql-state.ts", "../src/mutations/plpgsql-apply.ts", "../src/operations-log/ddl.ts", "../src/router.ts", "../src/migrations/utilities.ts", "../src/
|
|
3
|
+
"sources": ["../src/index.ts", "../src/electric-proxy.ts", "../src/cors-origin.ts", "../src/events/pgmq-queue.ts", "../src/events/queue.ts", "../src/events/route.ts", "../src/events/identity.ts", "../src/mutations/route.ts", "../src/operations-log/schema.ts", "../src/operations-log/writer.ts", "../src/sql-state.ts", "../src/mutations/plpgsql-apply.ts", "../src/operations-log/ddl.ts", "../src/router.ts", "../src/migrations/utilities.ts", "../src/events/consumer.ts", "../src/events/ddl.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
+
"import type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type {\n JwtClaims,\n RegistryRelations,\n RegistryTables,\n SyncRuntimeStatus,\n SyncServerAddress,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport { batchEventPaths, getSyncRegistryStreams } from \"@pgxsinkit/contracts\";\n\nimport { proxyElectricShapeRequest } from \"./electric-proxy\";\nimport { createPgmqEventQueue } from \"./events/pgmq-queue\";\nimport type { EventQueue } from \"./events/queue\";\nimport { createEventIngestHandler, type EventGate, type EventsEnqueuedHook } from \"./events/route\";\nimport {\n authoritativeMutationPaths,\n batchMutationPaths,\n createMutationHandler,\n type StartupVerificationMode,\n} from \"./mutations/route\";\nimport { ensureOperationsLogSchema } from \"./operations-log/ddl\";\nimport type { OperationsLogConfig } from \"./operations-log/types\";\nimport { FetchRouter, type CorsScope } from \"./router\";\n\nconst defaultAllowedOrigins = [\"http://localhost:5173\", \"http://localhost:5174\"];\n\ninterface BunServerHandle {\n stop: () => void;\n}\n\ninterface BunNamespace {\n serve: (options: {\n port: number;\n hostname?: string;\n idleTimeout?: number;\n fetch: (request: Request) => Response | Promise<Response>;\n }) => BunServerHandle;\n}\n\n/**\n * How the operations-log table's presence is resolved at startup (ADR-0030 decision 3):\n * - `\"probe\"` (default): the safe degradation posture (ADR-0030) — one query ensures/confirms the table,\n * and logging is disabled at runtime (with a warning) if it is absent, so a missing table degrades\n * gracefully instead of failing writes.\n * - `\"enabled\"`: assume the table exists — NO query. If it is actually absent, writes then fail loudly.\n * - `\"disabled\"`: turn logging off with NO query.\n *\n * `\"enabled\" | \"disabled\"` are the serverless posture: paired with `startupVerification: \"deploy-time\"`,\n * a fresh worker sends zero queries before the mutation transaction itself.\n */\nexport type OperationsLogStartupMode = \"probe\" | \"enabled\" | \"disabled\";\n\n/**\n * The `deployment` profile owns the server's startup query posture (ADR-0030 decision 3). Its defaults\n * are the safe degradation posture — probe-and-verify at startup — so a long-lived host that never sets\n * it still verifies and degrades gracefully; serverless / per-request workers set\n * `{ startupVerification: \"deploy-time\", operationsLog: \"enabled\" | \"disabled\" }` for a\n * zero-startup-query first write.\n */\nexport interface DeploymentProfile {\n /** Governs ONLY the RLS auth-helper verify now (apply-fn drift is self-verifying). Default `\"in-process\"`. */\n startupVerification?: StartupVerificationMode;\n /** How the operations-log table presence is resolved. Default `\"probe\"`. */\n operationsLog?: OperationsLogStartupMode;\n}\n\nexport interface CreateSyncServerOptions<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n registry: TRegistry;\n db: TDb;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n /**\n * When set, the server serves a read-path Electric shape proxy that shares the\n * single `resolveAuthClaims` adapter with the write path (ADR-0003). Without it,\n * no shape proxy is registered.\n */\n electricUrl?: string;\n /** Path for the shape proxy route. Defaults to `/api/shape`. */\n shapeProxyPath?: string;\n /** Optional per-request extra params passed to customWhere/shared filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\n operationsLog?: {\n enabled?: boolean;\n };\n /** Health check endpoint. Enabled by default at `/health`; `false` disables it, `{ path }` relocates it. */\n healthCheck?: boolean | { path: string };\n port?: number;\n host?: string;\n idleTimeoutSeconds?: number;\n allowedOrigins?: string[];\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n /**\n * The startup query posture (ADR-0030). The apply function now verifies its own ADR-0018 fingerprint\n * in-body on every call (SQLSTATE `PXS01` on drift), so there is no startup drift check to configure;\n * this governs only the RLS auth-helper verify and the operations-log presence resolution. Defaults\n * are the safe degradation posture (ADR-0030). See {@link DeploymentProfile}.\n */\n deployment?: DeploymentProfile;\n /**\n * The **Event lane**'s consent/entitlement gate (ADR-0053 decision 1): the lane's one function, and so an\n * option here rather than a registry field (the registry stays declarative data only). Called once per\n * event, after its payload validated and its identity resolved, and before anything is enqueued; a refusal\n * is a per-event `refused` verdict. Absent → every well-formed event is allowed. See {@link EventGate}.\n */\n eventGate?: EventGate;\n /**\n * Fired after an ingest request ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02): the\n * deployment-agnostic seam a SERVERLESS deployment uses to nudge whatever endpoint runs the consumer's\n * `drainOnce()`, so an interactive append drains in milliseconds instead of waiting for the next\n * scheduled tick. Fire-and-forget — it is called after the commit, its throw is caught and warn-logged,\n * and the scheduled sweep (not the nudge) is the delivery guarantee. Absent → nothing is nudged, which is\n * right for a deployment hosting the long-lived runner. See {@link EventsEnqueuedHook}.\n */\n onEventsEnqueued?: EventsEnqueuedHook;\n /**\n * The Event lane's queue backend. Defaults to the shipped pgmq backend over this server's own `db`\n * (`createPgmqEventQueue`), which is what makes an enqueue join the endpoint's transaction. Override it to\n * run the lane on another backend, or to substitute a fake in tests.\n */\n eventQueue?: EventQueue;\n /**\n * Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits\n * one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for\n * attributing wall-clock latency against the client's `syncDebug` lines. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n /**\n * The roles the INSTALLED apply function was generated with (`pgxsinkit-generate\n * --grant-execute-to <role>`, ADR-0054). Default `[]` — owner-only, the default the CLI generates.\n *\n * It is not a grant this server performs; it is how the server reproduces the artifact's ADR-0018\n * fingerprint, which hashes the ACL along with the rest of the body. Generate with a grant and leave\n * this unset and every write fails `PXS01` (stale artifact) — so the two lists must stay identical.\n */\n applyFunctionGrantExecuteTo?: readonly string[];\n /**\n * The schema the INSTALLED apply function lives in (`pgxsinkit-generate --function-schema <schema>`).\n * Default: unset — the artifact is generated unqualified and resolved through the connection's\n * `search_path`.\n *\n * It does two things at once, which is why one option drives both: the schema is part of the\n * fingerprinted body (the function names itself in its own self-check), AND it is how this server\n * QUALIFIES the call. Generate with `--function-schema` and leave this unset and the call goes out\n * unqualified — which either finds nothing (`42883`) or, worse, finds a same-named function elsewhere\n * on the `search_path` that then fails `PXS01` against a fingerprint it does not carry. The two must\n * name the same schema.\n */\n applyFunctionSchema?: string;\n}\n\nexport interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {\n tables: Array<keyof TRegistry & string>;\n modes: Record<string, TRegistry[keyof TRegistry][\"mode\"]>;\n}\n\nexport interface SyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n drizzle: TDb;\n fetch: (request: Request) => Promise<Response>;\n request: (path: string, init?: RequestInit) => Promise<Response>;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n status: SyncRuntimeStatus;\n address: SyncServerAddress | null;\n diagnostics: () => ServerDiagnostics<TRegistry>;\n}\n\nexport function createSyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n>(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {\n const db = options.db;\n const router = new FetchRouter();\n let bunServer: BunServerHandle | undefined;\n\n const status: SyncRuntimeStatus = {\n phase: \"ready\",\n isRunning: false,\n };\n\n let address: SyncServerAddress | null = null;\n const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);\n const operationsLogStartup = options.deployment?.operationsLog ?? \"probe\";\n // ADR-0030: how operations_log presence is resolved decides whether startup issues a query at all.\n // - \"probe\" (default): thread the presence probe into the effective config. operations_log is an\n // *optional* feature (default-enabled), so if logging was requested but the table is absent, disable\n // it at runtime rather than letting every write fail on a missing table — the documented degradation\n // (ensureOperationsLogSchema warns and returns `false`). The route awaits `operationsLogReady` before\n // any logOperation, so the corrected flag is in effect by the time logging runs, and the route holds\n // this same config object. (Board dogfooding: discarding this boolean 500'd every mutation on a\n // missing optional table.)\n // - \"enabled\": assume the table exists — NO query; logging stays on (an actual absence then fails\n // writes loudly, by design). \"disabled\": logging off — NO query.\n let operationsLogReady: Promise<void>;\n if (operationsLogStartup === \"probe\") {\n operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig).then((present) => {\n operationsLogConfig.enabled = operationsLogConfig.enabled && present;\n });\n } else {\n if (operationsLogStartup === \"disabled\") {\n operationsLogConfig.enabled = false;\n }\n operationsLogReady = Promise.resolve();\n }\n\n const shapeProxyPath = options.shapeProxyPath ?? \"/api/shape\";\n\n // CORS covers the canonical /api/* routes and the shape proxy path when it is relocated outside /api/.\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }];\n if (options.electricUrl) {\n corsScopes.push({ exact: shapeProxyPath });\n }\n router.setCors(\n {\n origins: options.allowedOrigins ?? defaultAllowedOrigins,\n allowMethods: [\"GET\", \"POST\", \"OPTIONS\"],\n // `apikey`: a deployment gateway (Supabase) expects it on every request, so the browser client\n // sends it; it must be allowed in the preflight even though the server itself ignores it.\n allowHeaders: [\"Content-Type\", \"Authorization\", \"apikey\"],\n },\n corsScopes,\n );\n\n router.setErrorHandler((error) => {\n status.phase = \"degraded\";\n status.lastError = error instanceof Error ? error.message : \"Unexpected error\";\n options.onStatusChange?.(status);\n\n if (isValidationError(error)) {\n return Response.json({ message: \"Validation failed\", issues: error.issues }, { status: 400 });\n }\n\n return Response.json({ message: error instanceof Error ? error.message : \"Unexpected error\" }, { status: 500 });\n });\n\n const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);\n if (healthCheckPath) {\n router.get(healthCheckPath, () => Response.json({ ok: true }));\n }\n\n // The single mutation ingress point — all writes go through POST /api/mutations.\n const mutationHandlers = createMutationHandler(\n db,\n options.registry,\n operationsLogConfig,\n operationsLogReady,\n options.resolveAuthClaims,\n options.deployment?.startupVerification ?? \"in-process\",\n options.logTimings ?? false,\n options.applyFunctionGrantExecuteTo ?? [],\n options.applyFunctionSchema,\n );\n for (const path of batchMutationPaths) {\n router.post(path, mutationHandlers.batch);\n }\n for (const path of authoritativeMutationPaths) {\n router.post(path, mutationHandlers.authoritative);\n }\n\n // The Event lane's ingestion endpoint (ADR-0053 decision 3), mounted ONLY when the registry registers at\n // least one Event stream — a registry without streams has no event lane, and the path stays a 404. Nothing\n // is probed or provisioned here: the queues are deploy-time DDL (`pgxsinkit-generate --events`), so the\n // route preserves the zero-startup-query posture.\n const eventStreams = getSyncRegistryStreams(options.registry);\n if (eventStreams && Object.keys(eventStreams).length > 0) {\n const eventQueue = options.eventQueue ?? createPgmqEventQueue({ db });\n const eventHandler = createEventIngestHandler(db, options.registry, eventQueue, {\n ...(options.resolveAuthClaims ? { resolveAuthClaims: options.resolveAuthClaims } : {}),\n ...(options.eventGate ? { eventGate: options.eventGate } : {}),\n ...(options.onEventsEnqueued ? { onEventsEnqueued: options.onEventsEnqueued } : {}),\n logTimings: options.logTimings ?? false,\n });\n for (const path of batchEventPaths) {\n router.post(path, eventHandler);\n }\n }\n\n // The read-path shape proxy shares the same resolveAuthClaims adapter, so read and\n // write authorization can never diverge (ADR-0003).\n if (options.electricUrl) {\n const electricUrl = options.electricUrl;\n const resolveAuthClaims = options.resolveAuthClaims;\n const resolveShapeParams = options.resolveShapeParams;\n router.get(shapeProxyPath, async (request) => {\n const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;\n const extraParams = resolveShapeParams?.(request);\n return proxyElectricShapeRequest(request, claims, {\n registry: options.registry,\n electricUrl,\n ...(extraParams ? { extraParams } : {}),\n ...(options.logTimings ? { logTimings: true } : {}),\n });\n });\n }\n\n const fetch = router.fetch;\n\n return {\n drizzle: db,\n fetch,\n request: (path, init) => {\n const baseUrl = address === null ? \"http://localhost\" : `http://${address.host}:${address.port}`;\n return fetch(new Request(new URL(path, baseUrl).toString(), init));\n },\n start: async () => {\n if (bunServer) {\n return;\n }\n\n const bun = getBunNamespace();\n if (!bun) {\n throw new Error(\"createSyncServer.start() requires the Bun runtime\");\n }\n\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3001;\n const idleTimeout = options.idleTimeoutSeconds;\n\n bunServer = bun.serve({\n hostname: host,\n port,\n ...(idleTimeout !== undefined ? { idleTimeout } : {}),\n fetch,\n });\n\n status.isRunning = true;\n status.phase = \"ready\";\n delete status.lastError;\n address = { host, port };\n options.onStatusChange?.(status);\n },\n stop: async () => {\n bunServer?.stop();\n bunServer = undefined;\n status.isRunning = false;\n options.onStatusChange?.(status);\n },\n status,\n get address() {\n return address;\n },\n diagnostics: () => ({\n tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,\n modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),\n }),\n };\n}\n\nexport function buildRegistrySchema<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): RegistryTables<TRegistry> {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction resolveHealthCheckPath(config?: boolean | { path: string }, defaultEnabled = false): string | null {\n if (config === false) {\n return null;\n }\n\n if (config === undefined && !defaultEnabled) {\n return null;\n }\n\n if (typeof config === \"object\" && \"path\" in config) {\n return config.path;\n }\n\n return \"/health\";\n}\n\nfunction getBunNamespace(): BunNamespace | undefined {\n const maybeBun = (globalThis as { Bun?: BunNamespace }).Bun;\n return maybeBun;\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction resolveOperationsLogConfig(options?: { enabled?: boolean }): OperationsLogConfig {\n return {\n enabled: options?.enabled ?? true,\n };\n}\n\nexport { authoritativeMutationPaths, batchMutationPaths, createMutationHandler } from \"./mutations/route\";\nexport type { StartupVerificationMode } from \"./mutations/route\";\nexport type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from \"./router\";\nexport { FetchRouter } from \"./router\";\nexport { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from \"./mutations/plpgsql-apply\";\nexport type { ApplyFunctionRenderOptions } from \"./mutations/plpgsql-apply\";\nexport { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { proxyElectricShapeRequest } from \"./electric-proxy\";\nexport type { ElectricProxyOptions } from \"./electric-proxy\";\nexport { readSqlState } from \"./sql-state\";\nexport {\n createEventIngestHandler,\n eventIngestRequiresClaims,\n EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,\n} from \"./events/route\";\nexport type {\n CreateEventIngestHandlerOptions,\n EventGate,\n EventGateDecision,\n EventGateInput,\n EventIngestDb,\n EventsEnqueuedHook,\n EventsEnqueuedInfo,\n} from \"./events/route\";\nexport { assertEventQueueReceipts, eventStreamQueueName, MalformedEventQueueMessageError } from \"./events/queue\";\nexport type {\n DeadLetteredEventMessage,\n DeliveredEventMessage,\n EventQueue,\n EventQueueExecutor,\n EventQueueReadOptions,\n EventQueueReceipt,\n} from \"./events/queue\";\nexport { createPgmqEventQueue, PGMQ_DEAD_LETTER_KEY } from \"./events/pgmq-queue\";\nexport type { CreatePgmqEventQueueOptions } from \"./events/pgmq-queue\";\nexport {\n computeEventPollWaitMs,\n defineEventConsumer,\n DEFAULT_EVENT_CONSUMER_BATCH_SIZE,\n DEFAULT_EVENT_DRAIN_BUDGET_MS,\n DEFAULT_EVENT_MAX_ATTEMPTS,\n DEFAULT_EVENT_POLL_CEILING_MS,\n DEFAULT_EVENT_POLL_FACTOR,\n DEFAULT_EVENT_POLL_FLOOR_MS,\n DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n} from \"./events/consumer\";\nexport type {\n DefineEventConsumerOptions,\n EventConsumer,\n EventConsumerBatch,\n EventConsumerCallback,\n EventConsumerPollOptions,\n EventConsumerSleep,\n EventDeadLetterReport,\n EventDrainOptions,\n EventDrainSummary,\n} from \"./events/consumer\";\nexport {\n EVENT_LANE_FINGERPRINT_PREFIX,\n eventLaneDdlFingerprint,\n eventLaneStreamNames,\n renderEventLaneMigration,\n} from \"./events/ddl\";\nexport { resolveEventIdentity } from \"./events/identity\";\nexport type { IdentityResolution } from \"./events/identity\";\n",
|
|
5
6
|
"import {\n buildRowFilterShape,\n getOmittedProjectedColumnNames,\n type JwtClaims,\n type RowTransform,\n type RowTransformContext,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { resolveCorsOrigin } from \"./cors-origin\";\n\nexport interface ElectricProxyCors {\n /**\n * Browser origins allowed to read this shape: exact strings (e.g. a hosted SPA + localhost dev),\n * or a `\"*\"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}).\n */\n origins: string[];\n}\n\nexport interface ElectricProxyOptions {\n registry: SyncTableRegistry;\n electricUrl: string;\n /** Extra params passed to customWhere functions (e.g. fromLang, toLang). */\n extraParams?: Record<string, unknown>;\n /**\n * CORS for a browser-facing deployment with **no CORS-adding gateway in front** — e.g. a Supabase\n * Cloud edge function, which the platform routes to directly. When set, OPTIONS preflights are\n * answered here and the response carries the allowed origin plus the Electric headers the client\n * must read off each shape. Omit it where a gateway already handles CORS (the local stack's Envoy).\n */\n cors?: ElectricProxyCors;\n /**\n * Opt-in per-request timing log (default off). When on, each forwarded shape request emits one compact\n * `[pgxsinkit-timing]` line (route `\"shape\"`) with the request's table/live/offset and the upstream\n * Electric fetch duration + status, for attributing read-path latency. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n /**\n * Append a unique `cache-buster` to every `live=true` request forwarded upstream (default ON; set\n * `false` to restore upstream CDN collapse of live long-polls). Stopgap for Electric Cloud serving\n * live long-polls from a layer blind to fresh commits: consecutive full-hold (~41s) `up-to-date`\n * responses at an unmoved offset despite an advancing `cursor`, measured cross-client propagation\n * of 40–89s (backlog 0001, 2026-07-04; upstream report alongside it). Only the live tail is busted —\n * catch-up responses keep their CDN cold-fanout sharing, and per-user-filtered live polls share\n * ~nothing across clients anyway. Remove when Electric fixes the live path (backlog 0001's close).\n */\n bustLiveUpstreamCache?: boolean;\n}\n\nconst perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/** Per-request shape-proxy timing scratch: the upstream Electric fetch duration + its HTTP status. */\ninterface ShapeProxyTiming {\n upstreamMs: number;\n upstreamStatus: number;\n}\n\n// Electric response headers the browser client reads off each shape response (offset/handle drive\n// resumption, schema/cursor drive parsing, up-to-date ends the initial sync). They must be exposed via\n// CORS or the client cannot resume — the classic Electric \"MissingHeadersError\".\nconst ELECTRIC_EXPOSED_HEADERS = \"electric-offset,electric-handle,electric-schema,electric-cursor,electric-up-to-date\";\n\n/**\n * Proxies an Electric shape request, applying registry-driven row filters and stripping omitted\n * columns from JSON shape-log payloads. Optionally answers CORS preflights and adds CORS headers\n * ({@link ElectricProxyOptions.cors}) for gateway-less browser deployments.\n *\n * The caller is responsible for resolving auth claims from the request.\n * Pass `claims` as `null` for unauthenticated requests (all rows blocked).\n */\nexport async function proxyElectricShapeRequest(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n): Promise<Response> {\n if (options.cors && request.method === \"OPTIONS\") {\n return corsPreflightResponse(request, options.cors);\n }\n const timing: ShapeProxyTiming | undefined = options.logTimings ? { upstreamMs: 0, upstreamStatus: 0 } : undefined;\n const start = timing ? perfNow() : 0;\n const response = await forwardShapeRequest(request, claims, options, timing);\n const finalResponse = options.cors ? withCorsResponseHeaders(request, response, options.cors) : response;\n if (timing) {\n logShapeTiming(request, timing, perfNow() - start);\n }\n return finalResponse;\n}\n\n/** Emit the one-line shape-proxy timing log: table/live/offset from the request, upstream + total ms. */\nfunction logShapeTiming(request: Request, timing: ShapeProxyTiming, totalMs: number): void {\n const params = new URL(request.url).searchParams;\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route: \"shape\",\n table: params.get(\"table\") ?? undefined,\n live: params.get(\"live\") === \"true\",\n offset: params.get(\"offset\") ?? undefined,\n upstreamMs: Math.round(timing.upstreamMs),\n upstreamStatus: timing.upstreamStatus,\n totalMs: Math.round(totalMs),\n }),\n );\n}\n\nasync function forwardShapeRequest(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n timing?: ShapeProxyTiming,\n): Promise<Response> {\n const decision = decideProxyTarget(request, claims, options);\n\n if (decision.kind === \"reject\") {\n // Fail closed: never forward, so the upstream Electric credentials in\n // `electricUrl` are not lent to a request the registry does not govern.\n return new Response(JSON.stringify({ message: decision.message }), {\n status: decision.status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n const upstreamStart = timing ? perfNow() : 0;\n const response = await fetch(decision.targetUrl, {\n method: \"GET\",\n signal: request.signal,\n }).catch((error: unknown) => {\n // Client disconnected — no meaningful response can be sent.\n // Return a 499 (client closed request) to avoid a 500 in logs.\n // Keyed on the signal's aborted state first: Bun can reject an aborted fetch with a\n // literal `null` (no AbortError to pattern-match), and once the caller aborted there is\n // nobody to answer regardless of what the rejection value looks like.\n if (request.signal.aborted || isAbortError(error)) {\n return new Response(null, { status: 499, statusText: \"Client Closed Request\" });\n }\n throw error;\n });\n if (timing) {\n timing.upstreamMs = perfNow() - upstreamStart;\n timing.upstreamStatus = response.status;\n }\n\n const responseHeaders = new Headers(response.headers);\n // Strip encoding/length since the response body may be re-serialized\n // (column omission path) or streamed through a new Response object.\n responseHeaders.delete(\"content-encoding\");\n responseHeaders.delete(\"content-length\");\n\n // The ingress `table` param carries the shape's unique `shapeKey` (the client identifies the shape;\n // the proxy maps it to the physical Electric table on egress). Resolve the entry by it.\n const shapeKey = new URL(request.url).searchParams.get(\"table\");\n const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];\n const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;\n const contentType = responseHeaders.get(\"content-type\") ?? \"\";\n\n // Re-serialize the shape log when this table needs any row-level rewriting: column\n // omission and/or a registry-declared row transform. The transform runs first so it can\n // read a column (e.g. a control flag) that omission then strips from the client row.\n if ((omittedColumns.length > 0 || rowTransform) && contentType.includes(\"application/json\")) {\n const payload = await response\n .clone()\n .json()\n .catch(() => undefined);\n\n if (Array.isArray(payload)) {\n const context: RowTransformContext = { claims, ...(options.extraParams ? { params: options.extraParams } : {}) };\n const rewritten = rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context);\n return new Response(JSON.stringify(rewritten), {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n }\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n}\n\ntype ProxyTargetDecision = { kind: \"forward\"; targetUrl: string } | { kind: \"reject\"; status: number; message: string };\n\n/**\n * Decide whether a shape request may be forwarded. The proxy serves only\n * registry-governed shapes (ADR-0003): a request with no `table`, or one whose `table`\n * (the shape's `shapeKey`) does not match a declared shape **exactly**, is rejected and never\n * reaches Electric. A shape that is in the registry but declares no `rowFilter` still\n * forwards — the gate is registry membership, not the presence of a filter.\n */\nfunction decideProxyTarget(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n): ProxyTargetDecision {\n const requestedShapeKey = new URL(request.url).searchParams.get(\"table\");\n\n if (!requestedShapeKey) {\n return { kind: \"reject\", status: 400, message: \"Shape request must specify a table\" };\n }\n\n if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {\n return { kind: \"reject\", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };\n }\n\n return { kind: \"forward\", targetUrl: buildProxyTargetUrl(request, claims, options) };\n}\n\n/**\n * Electric protocol resume/control query params a client may legitimately set on a shape request.\n * These drive resumption and long-poll; they do **not** define the shape's data. Every\n * shape-DEFINING param (`table`, `where`, `columns`, and any shape option such as `replica`) is\n * derived from the registry below, never forwarded from the client (ADR-0003 ISS-08).\n *\n * Kept as an explicit local allowlist — mirroring the `*_QUERY_PARAM` constants in\n * `@electric-sql/client` (1.5.x) — so the proxy fails **closed** on any unknown or future param\n * rather than lending it upstream Electric authority. `@electric-sql/client` exposes no aggregate\n * \"protocol params\" export to import, and `@pgxsinkit/server` deliberately takes no client-package\n * dependency, so the set is enumerated here with each Electric param it maps to.\n */\nconst ELECTRIC_CONTROL_QUERY_PARAMS: ReadonlySet<string> = new Set([\n \"offset\", // OFFSET_QUERY_PARAM — resume position\n \"handle\", // SHAPE_HANDLE_QUERY_PARAM — shape handle\n \"live\", // LIVE_QUERY_PARAM — long-poll mode\n \"cursor\", // LIVE_CACHE_BUSTER_QUERY_PARAM — live cursor\n \"cache-buster\", // CACHE_BUSTER_QUERY_PARAM\n \"expired_handle\", // EXPIRED_HANDLE_QUERY_PARAM — resume after a handle expires\n \"experimental_live_sse\", // EXPERIMENTAL_LIVE_SSE_QUERY_PARAM\n \"live_sse\", // LIVE_SSE_QUERY_PARAM\n \"log\", // LOG_MODE_QUERY_PARAM\n]);\n\nfunction buildProxyTargetUrl(request: Request, claims: JwtClaims | null, options: ElectricProxyOptions): string {\n const requestUrl = new URL(request.url);\n const targetUrl = new URL(options.electricUrl);\n\n // The registry entry — resolved by the request's `shapeKey` — is the sole shape authority\n // (ADR-0003). Strip any shape-defining param riding on `electricUrl` and re-derive `table`,\n // `where`, and `columns` from the registry. The client-supplied `where` never reaches here\n // either: authorization must never depend on client-controlled SQL — there is no safe way to\n // merge untrusted raw SQL into the ownership predicate (`1=1) OR (1=1` escapes any wrapping and\n // precedence-reduces to all-rows), so the registry row filter is the only `where`.\n targetUrl.searchParams.delete(\"where\");\n targetUrl.searchParams.delete(\"columns\");\n\n // Resolve by the ingress shapeKey, then set the EGRESS `table` to the entry's physical Electric\n // target (a read projection's owning table differs from its shapeKey).\n const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get(\"table\") ?? \"\");\n const electricTarget = electricTargetForEntry(entry);\n\n if (!electricTarget) {\n // Defensive only: decideProxyTarget already validated the shapeKey against the registry before we\n // get here. Without a registry-resolved target there is no governed shape to serve.\n return targetUrl.toString();\n }\n\n targetUrl.searchParams.set(\"table\", electricTarget);\n\n // Forward ONLY Electric protocol resume/control params from the client. A client-supplied\n // `columns`, `replica`, or any unknown/future param is never lent upstream authority — it cannot\n // alter the shape beyond what the registry authorized.\n requestUrl.searchParams.forEach((value, key) => {\n if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {\n targetUrl.searchParams.set(key, value);\n }\n });\n\n // Live-tail cache bust ({@link ElectricProxyOptions.bustLiveUpstreamCache}): a unique\n // Electric-recognized `cache-buster` per live long-poll keeps any upstream CDN from answering the\n // poll out of a collapsed/cached entry that cannot see fresh commits (backlog 0001). Catch-up\n // requests are left untouched so cold-fanout CDN sharing keeps working. Set AFTER the forward loop\n // so a client-sent buster (the stale-cache ladder rides catch-up, not live) is never clobbered on\n // non-live requests and a live request always gets a fresh one.\n if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get(\"live\") === \"true\") {\n targetUrl.searchParams.set(\"cache-buster\", crypto.randomUUID());\n }\n\n const rowFilter = entry?.shape?.rowFilter;\n\n if (!rowFilter) {\n return targetUrl.toString();\n }\n\n // A `customWhere` that returns a Drizzle `SQL` fragment is emitted as a *parameterized* Electric\n // where — `where=… $1 …` plus `params[1]=…` — so no request-derived value is ever inlined/escaped by\n // hand (Drizzle owns identifiers + structure, Electric binds the leaves). `ownership`/`shared` and a\n // string `customWhere` stay inline; `buildRowFilterShape` composes both forms.\n const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);\n\n if (shape) {\n targetUrl.searchParams.set(\"where\", shape.where);\n shape.params.forEach((param, index) => {\n targetUrl.searchParams.set(`params[${index + 1}]`, param);\n });\n }\n\n // Registry-declared column projection (an explicit opt-in). Per-row `omitColumns` is enforced\n // separately by post-hoc JSON stripping (below), so an omitted column never reaches the client\n // even when no projection is set here.\n if (rowFilter.columns && rowFilter.columns.length > 0) {\n targetUrl.searchParams.set(\"columns\", rowFilter.columns.join(\",\"));\n }\n\n return targetUrl.toString();\n}\n\n/**\n * The physical Electric table an entry reads — `electricTable` (a read projection's owning table) if\n * set, otherwise the shape's own table name. This is the value the proxy sends UPSTREAM in the egress\n * `table` param; several shapes may share it (a projection and its owner), which is exactly why an\n * incoming request is resolved by `shapeKey` (below), not by this.\n */\nfunction electricTargetForEntry(entry: SyncTableEntry | undefined): string | null {\n const shape = entry?.shape;\n if (!shape) {\n return null;\n }\n return shape.electricTable ?? shape.tableName;\n}\n\n/**\n * Resolve the registry entry a request selects by its **`shapeKey`** — the unique per-shape identity a\n * client puts in the ingress `table` param. Resolving by shapeKey (not by physical Electric target) is\n * what lets several shapes read ONE physical table: a read projection and its owner share an Electric\n * target but carry distinct shapeKeys. Schema qualification is significant (`authors` ≠\n * `private.authors`). Returns undefined when no entry declares that shapeKey — the caller fails closed.\n */\nfunction resolveEntryByShapeKey(registry: SyncTableRegistry, requestedShapeKey: string): SyncTableEntry | undefined {\n for (const key of Object.keys(registry)) {\n const entry = registry[key as keyof typeof registry] as SyncTableEntry | undefined;\n if (entry?.shape?.shapeKey === requestedShapeKey) {\n return entry;\n }\n }\n return undefined;\n}\n\nfunction getOmittedProjectedColumnsForTable(registry: SyncTableRegistry, shapeKey: string): readonly string[] {\n const entry = resolveEntryByShapeKey(registry, shapeKey);\n return entry ? getOmittedProjectedColumnNames(entry) : [];\n}\n\nfunction getRowTransformForTable(registry: SyncTableRegistry, shapeKey: string): RowTransform | undefined {\n return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Subset of an Electric shape-log entry the proxy rewrites: `value` carries the\n * row, `old_value` the prior row on updates. Runtime guards still validate both\n * before use; the declared shape is the wire-protocol expectation.\n */\ninterface ShapeLogEntry {\n value?: Record<string, unknown>;\n old_value?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nfunction isShapeLogEntry(value: unknown): value is ShapeLogEntry {\n return isObjectRecord(value);\n}\n\n/**\n * Rewrite each shape-log row: apply the registry row transform (if any), then strip\n * omitted columns. Both passes preserve object identity when nothing changes, so an\n * untouched entry flows through unmodified.\n */\nfunction rewriteRow(\n row: Record<string, unknown>,\n omittedColumns: readonly string[],\n rowTransform: RowTransform | undefined,\n context: RowTransformContext,\n): Record<string, unknown> {\n const transformed = rowTransform ? rowTransform(row, context) : row;\n return omittedColumns.length > 0 ? omitColumnsFromRow(transformed, omittedColumns) : transformed;\n}\n\nfunction rewriteShapeLogEntries(\n payload: unknown[],\n omittedColumns: readonly string[],\n rowTransform: RowTransform | undefined,\n context: RowTransformContext,\n): unknown[] {\n return payload.map((entry) => {\n if (!isShapeLogEntry(entry)) {\n return entry;\n }\n\n let currentEntry: ShapeLogEntry = entry;\n\n if (isObjectRecord(entry.value)) {\n const nextValue = rewriteRow(entry.value, omittedColumns, rowTransform, context);\n if (nextValue !== entry.value) {\n currentEntry = { ...currentEntry, value: nextValue };\n }\n }\n\n if (isObjectRecord(currentEntry.old_value)) {\n const nextOldValue = rewriteRow(currentEntry.old_value, omittedColumns, rowTransform, context);\n if (nextOldValue !== currentEntry.old_value) {\n currentEntry = { ...currentEntry, old_value: nextOldValue };\n }\n }\n\n return currentEntry;\n });\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"AbortError\" ||\n // Bun wraps aborted fetch as DOMException with numeric code\n (typeof (error as unknown as { code?: unknown }).code === \"number\" &&\n (error as unknown as { code: number }).code === 20))\n );\n}\n\n/** The request's `Origin` if it is on the allow-list, else `null` (so a disallowed origin gets no CORS). */\nfunction allowedCorsOrigin(request: Request, cors: ElectricProxyCors): string | null {\n return resolveCorsOrigin(request, cors.origins);\n}\n\n/** Answer a browser preflight: allowed origin, GET-only, the requested headers, cached for an hour. */\nfunction corsPreflightResponse(request: Request, cors: ElectricProxyCors): Response {\n const headers = new Headers();\n const origin = allowedCorsOrigin(request, cors);\n if (origin) {\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n }\n headers.set(\"Access-Control-Allow-Methods\", \"GET,OPTIONS\");\n // Echo what the browser asks to send (authorization + apikey for a Supabase function), falling back\n // to the standard set — so any client header is permitted without enumerating every one here.\n headers.set(\n \"Access-Control-Allow-Headers\",\n request.headers.get(\"access-control-request-headers\") ?? \"authorization,apikey,content-type\",\n );\n headers.set(\"Access-Control-Max-Age\", \"3600\");\n return new Response(null, { status: 204, headers });\n}\n\n/** Add the allowed origin + the exposed Electric headers to a real shape response (no-op off-list). */\nfunction withCorsResponseHeaders(request: Request, response: Response, cors: ElectricProxyCors): Response {\n const origin = allowedCorsOrigin(request, cors);\n if (!origin) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n headers.set(\"Access-Control-Expose-Headers\", ELECTRIC_EXPOSED_HEADERS);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n}\n\nfunction omitColumnsFromRow(row: Record<string, unknown>, omittedColumns: readonly string[]): Record<string, unknown> {\n let changed = false;\n const nextRow = { ...row };\n\n for (const column of omittedColumns) {\n if (Object.prototype.hasOwnProperty.call(nextRow, column)) {\n delete nextRow[column];\n changed = true;\n }\n }\n\n return changed ? nextRow : row;\n}\n",
|
|
6
7
|
"/**\n * Resolve which origin (if any) a response's CORS headers should allow for this request.\n *\n * Entries are exact scheme+host[+port] strings (`https://app.example.com`, `http://localhost:5660`),\n * plus one special form: a literal `\"*\"` entry allows EVERY origin by reflecting the request's\n * `Origin` header back — never a literal `*` header value, which the Fetch spec rejects for\n * credentialed requests (the toolkit's requests carry `Authorization`). Reflection is sound here\n * because auth is a per-request bearer token, not ambient cookies: a hostile page cannot mint the\n * header, so the origin list is deployment hygiene rather than the security boundary. Use `\"*\"` for\n * dev/demo backends serving many local origins; enumerate exact origins for production.\n *\n * Returns `null` when the request has no `Origin` or it is not allowed — callers then omit CORS\n * headers entirely, and the browser blocks the read.\n */\nexport function resolveCorsOrigin(request: Request, origins: readonly string[]): string | null {\n const origin = request.headers.get(\"origin\");\n if (!origin) {\n return null;\n }\n return origins.includes(\"*\") || origins.includes(origin) ? origin : null;\n}\n",
|
|
7
|
-
"import { and, eq, sql, type AnyRelations } from \"drizzle-orm\";\nimport { getTableConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\nimport type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\nimport { createSchemaFactory } from \"drizzle-orm/zod\";\n\nimport type {\n AuthoritativeWriteRequest,\n BatchMutationRequest,\n JwtClaims,\n MutationAck,\n RegistryRelations,\n SyncTableEntry,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport {\n authoritativeWriteRequestSchema,\n batchMutationRequestSchema,\n getOmittedProjectedColumns as getOmittedProjectionColumns,\n getProjectedColumns,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport type { OperationsLogConfig } from \"../operations-log/types\";\nimport { logOperation, logOperationSafely } from \"../operations-log/writer\";\nimport type { FetchHandler } from \"../router\";\nimport { readSqlState } from \"../sql-state\";\nimport {\n executePlpgsqlBatch,\n expectedApplyFingerprint,\n type MutationConflict,\n verifyRlsAuthHelpers,\n} from \"./plpgsql-apply\";\nimport type { TransactionClient } from \"./types\";\n\n/**\n * How the write path handles its remaining startup query class — the RLS auth-helper verify (ADR-0030\n * decision 3). The apply-function drift guarantee moved into the call itself (self-verifying function),\n * so this now governs ONLY that helper check:\n * - `\"in-process\"` (default): keep today's boot-time `verifyRlsAuthHelpers` and its clear startup error.\n * - `\"deploy-time\"`: skip it — the migration pipeline owns that guarantee, so a fresh (serverless)\n * worker sends ZERO queries before the mutation transaction itself.\n */\nexport type StartupVerificationMode = \"in-process\" | \"deploy-time\";\n\nconst { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({\n coerce: { date: true },\n});\n\ntype RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, \"select\">;\n\nexport const batchMutationPaths = [\"/api/mutations\"] as const;\n/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */\nexport const authoritativeMutationPaths = [\"/api/mutations/unit\"] as const;\n\nexport function createMutationHandler<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n operationsLogConfig: OperationsLogConfig,\n operationsLogReady: Promise<void>,\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null,\n startupVerification: StartupVerificationMode = \"in-process\",\n logTimings = false,\n): { batch: FetchHandler; authoritative: FetchHandler } {\n let startupReadyPromise: Promise<void> | undefined;\n\n // ADR-0030: the fingerprint this server expects for its registry + applier codegen, computed ONCE per\n // server instance. Every `executePlpgsqlBatch` passes it so the installed apply function can verify\n // itself in-body (SQLSTATE 'PXS01' on drift) — this replaces the deleted startup verify.\n const expectedFingerprint = expectedApplyFingerprint(registry);\n\n // Per-request timing scratch (opt-in). authMs/applyMs are filled at the narrow phase call sites inside\n // the handler; totalMs + status are measured by `withTiming` wrapping the returned handler. A fresh\n // object per request keeps this concurrency-safe without threading state through the handler internals.\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n interface RequestTiming {\n handlerStart: number;\n preTxMs: number;\n txOpenMs: number;\n authMs: number;\n applyMs: number;\n mutations: number;\n }\n const withTiming = (route: string, handler: (request: Request, timing?: RequestTiming) => Promise<Response>) => {\n if (!logTimings) {\n return (request: Request) => handler(request);\n }\n return async (request: Request): Promise<Response> => {\n const start = perfNow();\n const timing: RequestTiming = {\n handlerStart: start,\n preTxMs: 0,\n txOpenMs: 0,\n authMs: 0,\n applyMs: 0,\n mutations: 0,\n };\n const response = await handler(request, timing);\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route,\n preTxMs: Math.round(timing.preTxMs),\n txOpenMs: Math.round(timing.txOpenMs),\n authMs: Math.round(timing.authMs),\n applyMs: Math.round(timing.applyMs),\n totalMs: Math.round(perfNow() - start),\n mutations: timing.mutations,\n status: response.status,\n }),\n );\n return response;\n };\n };\n // Stamp the two spans the phase timers cannot see: preTxMs = handler entry → transaction call\n // (parse + zod validation), txOpenMs = transaction call → callback entry (the driver's LAZY\n // connection establishment + BEGIN — on serverless this is where a fresh worker's pooler\n // TLS/DNS cost lands, invisible to authMs/applyMs).\n const stampPreTx = (timing: RequestTiming | undefined) => {\n if (timing) timing.preTxMs = perfNow() - timing.handlerStart;\n return timing ? perfNow() : 0;\n };\n const stampTxOpen = (timing: RequestTiming | undefined, txCallAt: number) => {\n if (timing) timing.txOpenMs = perfNow() - txCallAt;\n };\n\n const startupReady = () => {\n if (!startupReadyPromise) {\n // ADR-0030: \"deploy-time\" skips the boot-time RLS auth-helper verify (the migration pipeline owns\n // that guarantee), so a fresh worker sends no query here — combined with a declared operations-log\n // posture, the first statement a serverless worker sends is the mutation transaction itself.\n startupReadyPromise = startupVerification === \"in-process\" ? installStartupDdl(db, registry) : Promise.resolve();\n }\n\n return startupReadyPromise;\n };\n\n // Per-mutation payload validation shared by the batch and authoritative endpoints (security: both must\n // reject client-omitted projection fields, server-managed fields, and malformed payloads before apply).\n // Logs each offender and returns the attributable 400 Response, or null when every mutation is valid.\n const validateMutationsOrRespond = async (\n mutations: BatchMutationRequest[\"mutations\"],\n requestPath: string,\n ): Promise<Response | null> => {\n const validationErrors: string[] = [];\n const invalidMutations: Array<{\n mutation: BatchMutationRequest[\"mutations\"][number];\n message: string;\n }> = [];\n\n for (const mutation of mutations) {\n if (!(mutation.tableName in registry)) {\n const message = `Unknown table: ${mutation.tableName}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const entry = registry[mutation.tableName as keyof TRegistry]!;\n const syncEntry = entry as SyncTableEntry;\n const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);\n // Surface (once per table+key) only a payload key the apply path would SILENTLY drop — a truly\n // unknown key, never a projected-away/server-only column (those are 400-rejected just below, so\n // the helper excludes them; warning \"the write succeeds\" then rejecting was the misleading overlap).\n warnOnSilentlyDroppedPayloadKeys(syncEntry, mutation.tableName, mutation.kind, normalizedPayload);\n const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (projectedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (managedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n try {\n if (mutation.kind === \"update\") {\n const payloadKeys =\n typeof normalizedPayload === \"object\" && normalizedPayload !== null\n ? Object.keys(normalizedPayload as object)\n : [];\n if (payloadKeys.length === 0) {\n throw new Error(\"At least one field must be provided\");\n }\n createMutationInsertSchema(syncEntry.table as AnyPgTable)\n .partial()\n .parse(normalizedPayload);\n } else if (mutation.kind === \"create\") {\n buildCreateValidationSchema(syncEntry).parse(normalizedPayload);\n }\n // delete has no payload to validate\n } catch (error) {\n const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : \"\";\n const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n }\n }\n\n if (validationErrors.length > 0) {\n for (const invalidMutation of invalidMutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: invalidMutation.mutation.tableName,\n operationKind: invalidMutation.mutation.kind,\n entityKey: invalidMutation.mutation.entityKey,\n payload: invalidMutation.mutation.payload,\n status: \"validation_failed\",\n errorMessage: invalidMutation.message,\n httpStatus: 400,\n mutationId: invalidMutation.mutation.mutationId,\n mutationSeq: invalidMutation.mutation.mutationSeq,\n clientTimestampUs: invalidMutation.mutation.clientTimestampUs,\n requestPath: requestPath,\n });\n }\n\n // Attribute the rejection to the specific offending mutations. The batch is atomic\n // (nothing was applied), so the client can quarantine exactly these and keep the\n // innocent siblings retryable — one bad mutation never poisons the whole offline queue.\n return Response.json(\n {\n message: `Payload validation failed: ${validationErrors.join(\"; \")}`,\n rejections: invalidMutations.map(({ mutation, message }) => ({\n tableName: mutation.tableName,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n reason: message,\n })),\n },\n { status: 400 },\n );\n }\n\n return null;\n };\n\n const handleBatchMutation = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: [],\n },\n { status: 400 },\n );\n }\n\n let body: BatchMutationRequest;\n\n try {\n body = batchMutationRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid batch mutation request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const acks: MutationAck[] = [];\n let actorUserId: string | null = null;\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const batchRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n batchRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n // ADR-0015: a reject-if-stale stale write was NOT applied — the applier returned it here.\n // Surface a `conflicted` ack (distinct from a failure) carrying the row's current Server\n // version, so the client keeps the optimistic overlay and resolves it as a new write.\n const conflictByMutationId = new Map(conflicts.map((conflict) => [conflict.mutationId, conflict]));\n\n for (const mutation of batchRequest.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n\n if (conflict) {\n // #6: a null currentServerVersion means the target row no longer exists (an UPDATE whose\n // row was deleted by another writer), distinct from a stale write over a row that moved.\n const conflictReason =\n conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no ` +\n `longer exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`;\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n continue;\n }\n\n const serverUpdatedAtUs = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n const errorMessage = formatBatchExecutionError(error);\n\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage,\n httpStatus: 500,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n }\n\n return Response.json({ message: errorMessage }, { status: 500 });\n }\n\n return Response.json({ acks });\n };\n\n // ADR-0022 §3 (mechanism c): the authoritative (pessimistic) write endpoint. One write-**unit** per POST,\n // applied in its OWN isolated transaction, atomically — so a constraint/trigger exception becomes a clean\n // per-mutation `rejected` ack (the whole unit rolls back, overlays auto-discard) instead of the batch\n // path's whole-batch 500, and a stale member surfaces `conflicted` (overlays kept) without partial apply.\n const handleAuthoritativeWrite = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json({ message: \"Invalid authoritative write request\", issues: [] }, { status: 400 });\n }\n\n let body: AuthoritativeWriteRequest;\n\n try {\n body = authoritativeWriteRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid authoritative write request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json(\n {\n message: \"Invalid authoritative write request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n let actorUserId: string | null = null;\n // The unit's outcome, decided inside its OWN transaction: applied (Server versions per member) or\n // conflicted (a stale member → rolled back, overlays kept). An execution exception is handled in catch.\n let appliedServerVersions: Map<string, string | null> | null = null;\n let unitConflicts: MutationConflict[] | null = null;\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const unitRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n unitRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n if (conflicts.length > 0) {\n // The unit is atomic — a stale member means none of it applies. Roll back; report all members as\n // conflicted (overlays kept, re-resolve the unit) below.\n unitConflicts = conflicts;\n throw new UnitNotCommittedError();\n }\n\n // Applied cleanly. Read each member's resulting Server version INSIDE the txn, before it commits.\n const versions = new Map<string, string | null>();\n for (const mutation of unitRequest.mutations) {\n const version = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n versions.set(mutation.mutationId, version ?? null);\n }\n appliedServerVersions = versions;\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n if (!(error instanceof UnitNotCommittedError)) {\n // A DB-enforced invariant (capacity/quota/uniqueness constraint or trigger) declined the unit. The\n // whole unit rolled back; surface a per-mutation `rejected` ack so the client auto-discards the\n // unit's optimistic overlay (ADR-0022 §4). The ack carries a SANITISED reason — the raw DB error\n // (constraint names, offending values/PII, schema, hints) stays in the operations log only.\n const internalDetail = formatBatchExecutionError(error);\n const publicReason = toPublicRejectionReason(error);\n const rejectedAcks: MutationAck[] = [];\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage: internalDetail,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n rejectedAcks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"rejected\",\n rejectionReason: publicReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks: rejectedAcks });\n }\n // UnitNotCommittedError — `unitConflicts` is set; fall through to conflicted-ack building.\n }\n\n const acks: MutationAck[] = [];\n\n if (unitConflicts) {\n const conflictByMutationId = new Map(\n (unitConflicts as MutationConflict[]).map((conflict) => [conflict.mutationId, conflict]),\n );\n for (const mutation of body.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n const conflictReason = conflict\n ? conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no longer ` +\n `exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`\n : `Atomic write-unit not committed (ADR-0022): a sibling write in the same unit was rejected as ` +\n `stale, so this write rolled back too. Re-resolve the unit.`;\n\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict?.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks });\n }\n\n // Applied: ack every member, carrying the Server version each converged to.\n const serverVersions = appliedServerVersions ?? new Map<string, string | null>();\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n const serverUpdatedAtUs = serverVersions.get(mutation.mutationId) ?? undefined;\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n\n return Response.json({ acks });\n };\n\n return {\n batch: withTiming(\"mutations\", handleBatchMutation),\n authoritative: withTiming(\"mutations\", handleAuthoritativeWrite),\n };\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatBatchExecutionError(error: unknown): string {\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return \"Batch mutation failed\";\n }\n\n const details = [rootCause.message];\n const errorCode = getErrorStringProperty(rootCause, \"code\");\n const errorDetail = getErrorStringProperty(rootCause, \"detail\");\n const errorHint = getErrorStringProperty(rootCause, \"hint\");\n\n if (errorCode) {\n details.push(`code: ${errorCode}`);\n }\n\n if (errorDetail) {\n details.push(`detail: ${errorDetail}`);\n }\n\n if (errorHint) {\n details.push(`hint: ${errorHint}`);\n }\n\n return details.join(\" | \");\n}\n\n/**\n * Map a DB exception to a **client-safe** rejection reason for an authoritative `rejected` ack (ADR-0022 §4).\n * The raw error text (`formatBatchExecutionError`) leaks constraint names, schema/table, the offending\n * VALUES (potential PII), and trigger hints — and a `rejected` ack is success-path copy the app surfaces to\n * users, so it must not echo that. Two cases:\n *\n * - **App-authored `RAISE`** (PL/pgSQL `RAISE EXCEPTION 'cohort is full'`, SQLSTATE `P0001` / a custom `P0…`\n * class): the message IS the consumer's own user-facing copy — pass it through. This is the intended way\n * to give a friendly capacity/quota message.\n * - **Built-in integrity violations** (SQLSTATE class `23`) and everything else: return a stable generic\n * message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.\n */\nexport function toPublicRejectionReason(error: unknown): string {\n const fallback = \"The write was rejected by a server rule.\";\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return fallback;\n }\n\n // Resolve the SQLSTATE with the driver-agnostic helper (bun-sql — this project's runtime driver —\n // carries it on `errno`, not `code`; postgres.js / pg on `code`). Reading `error.code` directly, as\n // this did, returned bun's generic \"ERR_POSTGRES_SERVER_ERROR\" and dropped every app-authored `P0…`\n // and constraint code into the generic fallback, breaking ADR-0022's friendly rejection channel.\n // `readSqlState` walks the cause chain itself, so it runs on the ORIGINAL error; the app-authored\n // RAISE MESSAGE below still comes from the root cause.\n const code = readSqlState(error);\n\n // ADR-0030: the self-verifying apply function raises SQLSTATE 'PXS01' when its installed fingerprint\n // does not match this server's registry/codegen — the drift the deleted startup verify used to catch.\n // Surface the same actionable operator guidance the old startup error gave (it carries no PII, only the\n // regenerate-and-apply instruction), rather than the generic rejection fallback.\n if (code === \"PXS01\") {\n return (\n \"The server's apply function is out of date: its installed fingerprint does not match this \" +\n \"server's registry/codegen. Regenerate the sync-function migration (pgxsinkit-generate) and apply \" +\n \"it before serving writes.\"\n );\n }\n\n // App-authored RAISE — the message is the consumer's own copy, safe to surface.\n if (code && (code === \"P0001\" || code.startsWith(\"P0\"))) {\n return rootCause.message.trim() || fallback;\n }\n\n // Built-in integrity violations: generic, code-keyed messages only (no raw constraint names / values).\n const genericByCode: Record<string, string> = {\n \"23505\": \"This conflicts with an existing record (a uniqueness rule was violated).\",\n \"23514\": \"A validation rule rejected this write.\",\n \"23503\": \"A referenced record is missing (a relationship rule was violated).\",\n \"23502\": \"A required value was missing.\",\n \"23P01\": \"An exclusion rule rejected this write.\",\n };\n\n if (code && genericByCode[code]) {\n return genericByCode[code]!;\n }\n\n if (code && code.startsWith(\"23\")) {\n return \"A data-integrity rule rejected this write.\";\n }\n\n return fallback;\n}\n\nfunction getRootCauseError(error: unknown): Error | null {\n let current = error;\n let lastError: Error | null = null;\n const seen = new Set<unknown>();\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n lastError = current;\n current = current.cause;\n }\n\n return lastError;\n}\n\nfunction getErrorStringProperty(error: Error, key: string): string | null {\n if (!(key in error)) {\n return null;\n }\n\n const value = (error as unknown as Record<string, unknown>)[key];\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction isRlsAuthContextRequired(registry: SyncTableRegistry): boolean {\n return Object.values(registry).some(\n (entry) =>\n getTableConfig(entry.table as AnyPgTable).policies.length > 0 ||\n (entry.governance?.managedFields ?? []).some((field) => field.strategy === \"authClaim\"),\n );\n}\n\nclass UnauthorizedBatchMutationError extends Error {}\n\n/**\n * Thrown inside the authoritative write's transaction to roll the whole unit back when a member is a stale\n * write (ADR-0015) — distinct from an execution exception (a capacity/constraint rejection). The handler\n * catches it and reports every member `conflicted` (overlays kept), having committed nothing.\n */\nclass UnitNotCommittedError extends Error {}\n\nfunction getUuidClaim(claims: JwtClaims, key: string): string | null {\n const value = claims[key];\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n 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;\n}\n\nfunction findManagedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const managedFields = getManagedFieldsForOperation(entry, mutationKind);\n if (managedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);\n}\n\n// One structured warning per (table, dropped-key) per process. The apply path is hot; a memoized set\n// keeps a recurring silent-drop from spamming the log while still surfacing it once. The keys are\n// client-controlled (a malicious/buggy client can send unbounded junk keys), so the set is capped: past\n// the cap we stop memoizing AND stop warning, so the process can never accumulate unbounded entries.\nconst warnedDroppedPayloadKeys = new Set<string>();\nconst MAX_WARNED_DROPPED_KEYS = 10_000;\n// Set true after the one-time \"warnings suppressed\" notice fires, so the cap notice logs exactly once.\nlet droppedKeyWarningSuppressed = false;\n\n/**\n * Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path\n * will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,\n * nor a projected-away column that request validation already 400-rejects. The generated apply function\n * reads only the table's PROJECTED columns from the payload jsonb, so such a key never lands — were it\n * \"applied\" the write would collapse to a bare server-version (`updated_at_us`) bump. This is the clean\n * two-case split (ADR-0022 posture docs):\n *\n * - **Projected-away / server-only columns** (`clientProjection.omitColumns`) sent explicitly are\n * **400-rejected** by {@link findProjectedFieldViolations} — they are NOT silently dropped, so this\n * helper deliberately does **not** warn for them (warning \"the write still succeeds\" and then\n * rejecting was the misleading overlap the review flagged).\n * - **Unknown non-column keys** (a typo, a stale field) are what the apply path silently ignores — those\n * are exactly the keys this warns about, once, as a debugging aid. It is NOT an error and changes no\n * semantics.\n *\n * Exported for direct unit coverage.\n */\nexport function warnOnSilentlyDroppedPayloadKeys(\n entry: SyncTableEntry,\n tableName: string,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): void {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return;\n }\n\n // The keys the apply path will actually write: the projected columns (what it reads from payload) plus\n // the managed fields for this operation (server-stamped, legitimately present). Both property key and\n // DB column name are accepted, so a payload keyed either way is not falsely flagged.\n const writable = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedColumns(entry)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n for (const { propertyKey, columnName } of getManagedFieldsForOperation(entry, mutationKind)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n\n // Keys request validation will 400-REJECT (an explicitly-sent projected-away / server-only column):\n // those never reach apply, so they are NOT a silent drop — exclude them so the warning is reserved for\n // truly-unknown keys the apply path drops without validation rejecting.\n const rejectedAtValidation = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedAwayFields(entry)) {\n rejectedAtValidation.add(propertyKey);\n rejectedAtValidation.add(columnName);\n }\n\n for (const key of Object.keys(payload)) {\n if (writable.has(key) || rejectedAtValidation.has(key)) {\n continue;\n }\n const memoKey = `${tableName}::${key}`;\n if (warnedDroppedPayloadKeys.has(memoKey)) {\n continue;\n }\n // Cap the memo set against client-controlled key spray: once full, emit one final suppression notice\n // and stop both memoizing and warning — the set never grows past the cap.\n if (warnedDroppedPayloadKeys.size >= MAX_WARNED_DROPPED_KEYS) {\n if (!droppedKeyWarningSuppressed) {\n droppedKeyWarningSuppressed = true;\n console.warn(\n `[pgxsinkit] Dropped-key warnings suppressed: more than ${MAX_WARNED_DROPPED_KEYS} distinct ` +\n `(table, key) pairs have been reported this process. Further dropped payload keys will not be logged.`,\n );\n }\n return;\n }\n warnedDroppedPayloadKeys.add(memoKey);\n console.warn(\n `[pgxsinkit] Payload for table \"${tableName}\" carries key \"${key}\", which is not a column of that ` +\n `table — the apply path silently ignores it (a write that reached apply would collapse to a bare ` +\n `server-version bump). This is almost always a typo or a stale field: check the spelling against ` +\n `the table's columns, or remove \"${key}\" if the schema no longer has it. (A projected-away/` +\n `server-only column would instead be 400-rejected, not dropped, so it is not what this warns about.) ` +\n `(Logged once per table+key per process.)`,\n { table: tableName, droppedKey: key, hint: \"unknown-non-column-key\" },\n );\n }\n}\n\nfunction findProjectedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const projectedFields = getProjectedAwayFields(entry);\n if (projectedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n\n return [\n ...new Set(\n projectedFields\n .filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName))\n .map((field) => field.propertyKey),\n ),\n ];\n}\n\nfunction sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTableRegistry): BatchMutationRequest {\n return {\n mutations: batch.mutations.map((mutation) => {\n if (mutation.kind === \"delete\") {\n return mutation;\n }\n\n const entry = registry[mutation.tableName];\n\n if (!entry) {\n return mutation;\n }\n\n const managedFields = getManagedFieldsForOperation(entry as SyncTableEntry, mutation.kind);\n const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);\n\n if (managedFields.length === 0 && projectedFields.length === 0) {\n return mutation;\n }\n\n const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};\n\n for (const field of managedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n for (const field of projectedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n return {\n ...mutation,\n payload,\n };\n }),\n };\n}\n\n/**\n * The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /\n * `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —\n * and {@link findManagedFieldViolations} already rejects a payload that includes them. They are\n * omitted from the insert schema so a NOT NULL managed column without a SQL DEFAULT (e.g. an `authUid`\n * author/owner/created_by) is not falsely required. (A column carrying a DEFAULT is already optional\n * in the drizzle insert schema; this also covers a managed column that has none.)\n */\nexport function buildCreateValidationSchema(entry: SyncTableEntry) {\n const createSchema = createMutationInsertSchema(entry.table as AnyPgTable);\n const managedCreateKeys = getManagedFieldsForOperation(entry, \"create\").map((field) => field.propertyKey);\n if (managedCreateKeys.length === 0) {\n return createSchema;\n }\n // The omit-mask keys are derived from governance at runtime, so they cannot be narrowed to the\n // schema's literal-key mask type — cast through the parameter type.\n const omitMask = Object.fromEntries(managedCreateKeys.map((key) => [key, true as const])) as Parameters<\n typeof createSchema.omit\n >[0];\n return createSchema.omit(omitMask);\n}\n\nfunction getManagedFieldsForOperation(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n if (mutationKind === \"delete\") {\n return [];\n }\n\n const columns = getColumns(entry.table as AnyPgTable);\n const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? [])\n .filter((field) => field.applyOn.includes(mutationKind))\n .map((field) => ({\n propertyKey: field.column,\n columnName: columnMap.get(field.column) ?? field.column,\n strategy: field.strategy,\n }));\n}\n\nfunction getProjectedAwayFields(entry: SyncTableEntry) {\n return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({\n propertyKey,\n columnName,\n }));\n}\n\nfunction toSchemaPayload(entry: SyncTableEntry, payload: unknown): unknown {\n if (!isPlainObject(payload)) {\n return payload;\n }\n\n const columns = getColumns(entry.table as AnyPgTable);\n const keyMap = new Map<string, string>();\n\n for (const [propertyKey, column] of Object.entries(columns)) {\n keyMap.set(propertyKey, propertyKey);\n keyMap.set(column.name, propertyKey);\n }\n\n return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));\n}\n\nfunction resolveServerUpdatedAtColumnName(entry: SyncTableEntry): string {\n // The single source for the Server version column (ADR-0010 / ADR-0004): resolves the\n // managed field's property key to its column name. Falls back to the conventional name for\n // resilience, though registry validation now guarantees a writable table declares one.\n return resolveServerVersionColumnName(entry) ?? \"updated_at_us\";\n}\n\nasync function readServerUpdatedAtUs(\n tx: RouteReadQueryClient,\n entry: SyncTableEntry,\n entityKey: Record<string, string>,\n): Promise<string | undefined> {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnName = resolveServerUpdatedAtColumnName(entry);\n const updatedAtColumn = Object.values(columns).find((column) => column.name === columnName);\n\n if (!updatedAtColumn) {\n return undefined;\n }\n\n const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {\n const rawValue = entityKey[primaryKeyColumn];\n\n if (rawValue === undefined) {\n throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);\n }\n\n const primaryKeyTableColumn = Object.values(columns).find((column) => column.name === primaryKeyColumn);\n\n if (!primaryKeyTableColumn) {\n throw new Error(`Missing table column metadata for primary key column ${primaryKeyColumn}`);\n }\n\n return eq(primaryKeyTableColumn, rawValue);\n });\n\n const whereClause = conditions.length === 1 ? conditions[0]! : and(...conditions);\n const rows = await tx\n .select({ updatedAtUs: sql<string>`${updatedAtColumn}::text` })\n .from(entry.table as AnyPgTable)\n .where(whereClause)\n .limit(1);\n\n return rows[0]?.updatedAtUs ?? undefined;\n}\n\n// ADR-0030: the apply-function drift verify is gone from startup — the function verifies itself in-body\n// (SQLSTATE 'PXS01'). The only remaining boot-time check is the RLS auth-helper presence, and only when\n// the registry actually needs it. Reached only under `startupVerification: \"in-process\"`.\nasync function installStartupDdl<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n): Promise<void> {\n if (isRlsAuthContextRequired(registry)) {\n await verifyRlsAuthHelpers(db);\n }\n}\n",
|
|
8
|
+
"import { sql } from \"drizzle-orm\";\n\nimport { eventQueueMessageSchema, type EventQueueMessage } from \"@pgxsinkit/contracts\";\n\nimport {\n assertEventQueueReceipts,\n eventStreamQueueName,\n MalformedEventQueueMessageError,\n type DeadLetteredEventMessage,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueExecutor,\n type EventQueueReadOptions,\n type EventQueueReceipt,\n} from \"./queue\";\n\n/**\n * The shipped {@link EventQueue} backend: **pgmq** (ADR-0053 decision 5). Postgres-native, so the Event lane\n * adds no new infrastructure to the supabase-ecosystem stacks consumers already run, and an enqueue joins the\n * endpoint's own transaction rather than crossing a second system.\n *\n * One queue per Event stream (`pgxsinkit_events_<stream>`), so a poison event or a slow consumer in one stream\n * can never head-of-line-block another. Queues are provisioned at DEPLOY time (`pgxsinkit-generate --events`),\n * never created at runtime: the endpoint may enqueue long before any runner first starts, and a\n * create-if-missing probe would put a query back in front of the zero-startup-query posture.\n *\n * **pgmq assumptions**, all read off pgmq's own extension SQL and pinned by the integration lane:\n * - The extension is NOT relocatable and its control file declares `schema = 'pgmq'`, so every call is\n * `pgmq.`-qualified and the schema is never configurable here.\n * - Its control file declares no `requires`, so the DDL needs no `CASCADE` (pg_partman is needed only for\n * PARTITIONED queues, which the toolkit never creates).\n * - Per-queue tables are `pgmq.q_<queue>` and `pgmq.a_<queue>` (`pgmq.format_table_name`); the archive is the\n * dead-letter storage.\n *\n * SQL tier discipline: pgmq's surface IS a set of SQL functions and two dynamically-named tables, so Drizzle's\n * tier-1 builders cannot express any of it. Everything below is tier 2 — a tagged `sql` template with the\n * queue name and every value as BOUND PARAMETERS and each table name as a typed `sql.identifier`; no\n * identifier or value is ever baked into the template text.\n */\n\n/**\n * The reserved key the dead-letter reason is stamped under, INSIDE the archived message body.\n *\n * Least surface, deliberately: pgmq's archive is the dead-letter storage (no library-owned DLQ table), the\n * archive row has no free column to carry a reason, and its `headers` column only exists on newer pgmq\n * versions. So the reason rides one reserved key on the ARCHIVED body — the live queue row is never mutated,\n * a normally-consumed message is byte-identical to what was enqueued, and the key is stripped again by\n * {@link EventQueue.listDeadLetters} / {@link EventQueue.requeueDeadLetter} so a requeued message is exactly\n * the message that was enqueued.\n */\nexport const PGMQ_DEAD_LETTER_KEY = \"__pgxsinkitDeadLetter\";\n\nexport interface CreatePgmqEventQueueOptions {\n /** The default executor — the server's drizzle handle. Per-call executors (a transaction) take precedence. */\n db: EventQueueExecutor;\n}\n\ninterface DeliveredRow {\n receipt: string;\n deliveryCount: number;\n enqueuedAtUs: string;\n message: string;\n}\n\ninterface DeadLetterRow {\n id: string;\n deliveryCount: number;\n deadLetteredAtUs: string;\n message: string;\n reason: string | null;\n}\n\ninterface CountRow {\n affected: number;\n}\n\ninterface ReceiptRow {\n receipt: string | null;\n}\n\nfunction toRows<TRow>(result: unknown): TRow[] {\n return Array.from(result as Iterable<unknown>, (row) => row as TRow);\n}\n\n/** Parse a queue body back into the contract shape, naming the offending receipt if it is not one. */\nfunction parseQueueMessage(stream: string, receipt: EventQueueReceipt, body: string): EventQueueMessage {\n let raw: unknown;\n try {\n raw = JSON.parse(body);\n } catch (error) {\n throw new MalformedEventQueueMessageError(stream, receipt, error instanceof Error ? error.message : \"invalid JSON\");\n }\n const parsed = eventQueueMessageSchema.safeParse(raw);\n if (!parsed.success) {\n throw new MalformedEventQueueMessageError(stream, receipt, parsed.error.message);\n }\n return parsed.data;\n}\n\nexport function createPgmqEventQueue(options: CreatePgmqEventQueueOptions): EventQueue {\n const run = (executor: EventQueueExecutor | undefined, query: Parameters<EventQueueExecutor[\"execute\"]>[0]) =>\n (executor ?? options.db).execute(query);\n\n return {\n enqueueBatch: async (messages, executor) => {\n if (messages.length === 0) {\n return;\n }\n\n // Group by Event stream, preserving the order the endpoint assembled: one `send_batch` per stream, all\n // inside the CALLER's transaction, so a mixed flush batch is enqueued atomically or not at all.\n const byStream = new Map<string, EventQueueMessage[]>();\n for (const message of messages) {\n const bucket = byStream.get(message.stream);\n if (bucket) {\n bucket.push(message);\n } else {\n byStream.set(message.stream, [message]);\n }\n }\n\n for (const [stream, streamMessages] of byStream) {\n const queueName = eventStreamQueueName(stream);\n // The bodies ride as ONE bound json parameter expanded to `jsonb[]` in SQL — never a driver-specific\n // array binding, and never string-built SQL.\n await run(\n executor,\n sql`SELECT pgmq.send_batch(${queueName}, ARRAY(SELECT jsonb_array_elements(${JSON.stringify(streamMessages)}::text::jsonb)))`,\n );\n }\n },\n\n readBatch: async (stream: string, readOptions: EventQueueReadOptions): Promise<DeliveredEventMessage[]> => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n 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})`,\n );\n\n return toRows<DeliveredRow>(result).map((row) => ({\n receipt: row.receipt,\n stream,\n message: parseQueueMessage(stream, row.receipt, row.message),\n deliveryCount: Number(row.deliveryCount),\n enqueuedAtUs: row.enqueuedAtUs,\n }));\n },\n\n extendVisibility: async (stream, receipts, visibilityTimeoutSeconds, executor) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n // pgmq gained an ARRAY-taking `set_vt` only in 1.8.0, while the single-message form has existed\n // throughout — and the toolkit pins no pgmq version. So the portable shape is the single-message\n // function applied over the receipts with a LATERAL: still ONE statement and one round trip, but it\n // works on every pgmq a consumer's supabase-ecosystem stack might carry. The `::int` cast picks the\n // seconds-offset overload over the `timestamptz` one.\n const result = await run(\n executor,\n 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\"`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n ack: async (stream, receipts) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.delete(${queueName}, string_to_array(${receipts.join(\",\")}, ',')::bigint[])`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n deadLetter: async (stream, receipts, reason) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const ids = receipts.join(\",\");\n\n // pgmq's own archive move first — it is the version-correct transfer (it carries every column the\n // installed pgmq version has, including ones this code does not know about).\n const archived = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.archive(${queueName}, string_to_array(${ids}, ',')::bigint[])`,\n );\n\n // Then stamp the reason onto the ARCHIVED body. Deliberately second: if it fails the message is still\n // dead-lettered (the fail-safe direction), and the archived row is terminal so nothing races this.\n await run(\n undefined,\n 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[])`,\n );\n\n return Number(toRows<CountRow>(archived)[0]?.affected ?? 0);\n },\n\n listDeadLetters: async (stream, limit) => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n 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}`,\n );\n\n return toRows<DeadLetterRow>(result).map((row): DeadLetteredEventMessage => {\n const message = parseQueueMessage(stream, row.id, row.message);\n return {\n id: row.id,\n stream,\n message,\n ...(row.reason != null ? { reason: row.reason } : {}),\n deliveryCount: Number(row.deliveryCount),\n deadLetteredAtUs: row.deadLetteredAtUs,\n };\n });\n },\n\n requeueDeadLetter: async (stream, id) => {\n assertEventQueueReceipts([id]);\n const queueName = eventStreamQueueName(stream);\n // ONE statement: the archive row is removed and its (reason-stripped) body re-sent in the same command,\n // so a requeue can never leave the message both dead-lettered and queued.\n const result = await run(\n undefined,\n 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`,\n );\n return toRows<ReceiptRow>(result)[0]?.receipt ?? null;\n },\n };\n}\n",
|
|
9
|
+
"import type { SQL } from \"drizzle-orm\";\n\nimport {\n EVENT_STREAM_NAME_MAX_LENGTH,\n EVENT_STREAM_NAME_PATTERN,\n EVENT_STREAM_QUEUE_PREFIX,\n type EventQueueMessage,\n} from \"@pgxsinkit/contracts\";\n\n/**\n * The **Event lane**'s queue seam (ADR-0053 decision 5): a narrow, backend-agnostic interface over\n * \"enqueue a batch / consume with a visibility timeout / ack / dead-letter (+ enumerate and requeue)\".\n *\n * It is deliberately MECHANICS ONLY — there is no loop, no polling cadence, no wake policy and no\n * retry/backoff here. Those are the consumer runner's internals (ADR-0053 decision 7) and stay out of the\n * seam so a backend swap can never change pacing, and so the ingestion endpoint depends on nothing but\n * `enqueueBatch`.\n *\n * The interface, not the storage, is the contract: dead-letter STORAGE is backend-defined (the shipped pgmq\n * backend uses pgmq's own per-queue archive rather than a library-owned DLQ table), and v1 ships one backend.\n */\n\n/**\n * The minimal SQL seam a backend executes through — satisfied by a drizzle `PgAsyncDatabase` AND by the\n * transaction handle its `transaction()` callback receives. The ingestion endpoint enqueues INSIDE its own\n * transaction (a batch is enqueued atomically or the request fails retryably), so every mutating method\n * takes an optional executor rather than owning a connection.\n */\nexport interface EventQueueExecutor {\n execute: (query: SQL) => Promise<unknown>;\n}\n\n/**\n * An opaque handle for one delivered message, used to ack or dead-letter it. Backend-defined (pgmq: the\n * `msg_id` as a decimal string) — never parsed or ordered by callers.\n */\nexport type EventQueueReceipt = string;\n\nexport interface EventQueueReadOptions {\n /**\n * How long a delivered message stays invisible to other consumers, in seconds. The runner renews or lets\n * it lapse; the queue seam only applies what it is given.\n */\n visibilityTimeoutSeconds: number;\n /** At most this many messages (each message is one single-stream sub-batch). */\n maxMessages: number;\n}\n\n/** One message delivered by {@link EventQueue.readBatch}: a single-stream sub-batch plus its delivery metadata. */\nexport interface DeliveredEventMessage {\n receipt: EventQueueReceipt;\n /** The Event-stream name this message was read from (also carried inside `message`). */\n stream: string;\n message: EventQueueMessage;\n /**\n * How many times this message has been DELIVERED (pgmq's `read_ct`), including the current delivery — the\n * attempt counter a runner's dead-letter-after-N policy reads. Never a client-supplied value.\n */\n deliveryCount: number;\n /** When the message was enqueued, in unix microseconds (decimal string). */\n enqueuedAtUs: string;\n}\n\n/** One dead-lettered message, as enumerated from the backend's dead-letter storage. */\nexport interface DeadLetteredEventMessage {\n /** The dead-letter identity, and the handle {@link EventQueue.requeueDeadLetter} takes. */\n id: EventQueueReceipt;\n stream: string;\n message: EventQueueMessage;\n /** The reason recorded when it was dead-lettered, when one was recorded. */\n reason?: string;\n deliveryCount: number;\n /** When it was dead-lettered, in unix microseconds (decimal string). */\n deadLetteredAtUs: string;\n}\n\nexport interface EventQueue {\n /**\n * Enqueue whole messages. Called by the ingestion endpoint inside its own transaction, so passing\n * `executor` is what makes a multi-stream flush batch atomic: every message lands or none does\n * (ADR-0053 decision 4 — the endpoint never partially enqueues). Without an executor the backend uses its\n * own handle, and a multi-message call is then only as atomic as that handle.\n */\n enqueueBatch: (messages: readonly EventQueueMessage[], executor?: EventQueueExecutor) => Promise<void>;\n /** Deliver up to `maxMessages` messages of one Event stream, made invisible for the visibility timeout. */\n readBatch: (stream: string, options: EventQueueReadOptions) => Promise<DeliveredEventMessage[]>;\n /**\n * Push delivered messages' invisibility out to `visibilityTimeoutSeconds` FROM NOW — the lease RENEWAL a\n * consumer runner performs while it is still working through a read (one read makes a whole batch\n * invisible at once, so without renewal the later messages of a slow batch would become visible to another\n * runner while the first is still working toward them).\n *\n * Returns how many were actually extended. A receipt that is no longer queued (already acked or\n * dead-lettered) is simply not counted — a renewal racing a settle is ordinary, never an error.\n */\n extendVisibility: (\n stream: string,\n receipts: readonly EventQueueReceipt[],\n visibilityTimeoutSeconds: number,\n executor?: EventQueueExecutor,\n ) => Promise<number>;\n /** Acknowledge (permanently remove) delivered messages. Returns how many were actually removed. */\n ack: (stream: string, receipts: readonly EventQueueReceipt[]) => Promise<number>;\n /** Move delivered messages to dead-letter storage with a recorded reason. Returns how many moved. */\n deadLetter: (stream: string, receipts: readonly EventQueueReceipt[], reason: string) => Promise<number>;\n /** Enumerate an Event stream's dead-lettered messages, most recent first. */\n listDeadLetters: (stream: string, limit: number) => Promise<DeadLetteredEventMessage[]>;\n /**\n * Put one dead-lettered message back on its queue — a DELIBERATE act (ADR-0053 decision 7), never\n * automatic. Resolves with the requeued message's new receipt, or `null` when the id is not dead-lettered.\n */\n requeueDeadLetter: (stream: string, id: EventQueueReceipt) => Promise<EventQueueReceipt | null>;\n}\n\n/**\n * A queue message whose body is not a well-formed {@link EventQueueMessage}. The endpoint is the only writer\n * of these queues and it writes contract-shaped bodies, so this means a hand-inserted or corrupted message.\n * It carries the receipt precisely so a consumer runner can dead-letter exactly that message rather than\n * failing the whole read.\n */\nexport class MalformedEventQueueMessageError extends Error {\n readonly stream: string;\n readonly receipt: EventQueueReceipt;\n\n constructor(stream: string, receipt: EventQueueReceipt, detail: string) {\n super(`pgxsinkit: queue message ${receipt} on Event stream \"${stream}\" is not a valid queue message — ${detail}`);\n this.name = \"MalformedEventQueueMessageError\";\n this.stream = stream;\n this.receipt = receipt;\n }\n}\n\n/**\n * The queue name an Event stream is provisioned under: `pgxsinkit_events_<stream>` (ADR-0053 decision 5), the\n * SAME derivation the deploy-time DDL emits — one definition, so a runtime call can never address a queue the\n * migration did not create.\n *\n * The name is re-validated here even though `defineSyncRegistry` already validated it at module eval:\n * the queue name is interpolated into backend SQL, and a value arriving from a non-registry caller must not\n * be able to smuggle anything past that.\n */\nexport function eventStreamQueueName(stream: string): string {\n if (!EVENT_STREAM_NAME_PATTERN.test(stream) || stream.length > EVENT_STREAM_NAME_MAX_LENGTH) {\n throw new Error(\n `pgxsinkit: \"${stream}\" is not a usable Event-stream name — it must match ` +\n `${EVENT_STREAM_NAME_PATTERN.source} and be at most ${EVENT_STREAM_NAME_MAX_LENGTH} characters.`,\n );\n }\n return `${EVENT_STREAM_QUEUE_PREFIX}${stream}`;\n}\n\n/** Receipts are backend-issued decimal ids; anything else never reaches the backend's SQL. */\nexport function assertEventQueueReceipts(receipts: readonly EventQueueReceipt[]): void {\n for (const receipt of receipts) {\n if (!/^\\d+$/.test(receipt)) {\n throw new Error(`pgxsinkit: \"${receipt}\" is not a valid event-queue receipt (expected a decimal id).`);\n }\n }\n}\n",
|
|
10
|
+
"import {\n batchEventRequestSchema,\n getSyncRegistryStreams,\n isZodSchema,\n MAX_EVENT_PAYLOAD_BYTES,\n MAX_EVENT_REQUEST_BYTES,\n MAX_EVENTS_PER_BATCH,\n type EventAck,\n type EventEnvelope,\n type EventQueueMessage,\n type EventStreamRegistry,\n type JwtClaims,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { FetchHandler } from \"../router\";\nimport { resolveEventIdentity } from \"./identity\";\nimport type { EventQueue, EventQueueExecutor } from \"./queue\";\n\n/**\n * The **Event lane**'s ingestion endpoint (ADR-0053 decisions 3, 4 and 5): the mutation endpoint's sibling,\n * minus what events don't need. `createSyncServer` mounts it automatically at `batchEventPaths` when — and\n * only when — the registry registers at least one Event stream.\n *\n * Two shapes of verdict, and the split is the whole design:\n *\n * - **Framing is batch-level.** A body over the request cap OR an events array over the per-batch count cap\n * (413), unparseable JSON or a body that fails the strict envelope parse (400), missing claims (401), or an\n * unavailable queue (503) is a WHOLE-batch fault: a malformed item without a parseable `eventId` cannot\n * receive a per-event verdict, and a queue that cannot take the batch must not half-take it.\n * - **Every well-formed envelope gets a per-event verdict.** `acked` (enqueued), `refused` (the gating hook\n * said no), `rejected` (schema-invalid payload for a KNOWN stream, oversized payload, or an unresolvable\n * identity claim) and `deferred` (an Event stream this server does not know — ordinary rollout skew, and\n * the ONLY non-terminal verdict). A batch-level 400 on one bad event would wedge the whole Outbox behind\n * that row, which is exactly what the layering avoids.\n *\n * It keeps the write path's **zero-startup-query** posture (ADR-0030): nothing is probed, verified or created\n * at construction — queue provisioning is deploy-time DDL — so the first statement this route sends is the\n * enqueue transaction itself.\n */\n\n/** What the gating hook is told about one event. `identity` is already resolved from the verified claims. */\nexport interface EventGateInput {\n /** The Event-stream name — the key the hook dispatches on. */\n stream: string;\n /** The client's envelope, with its payload already validated against the stream's registered schema. */\n event: EventEnvelope;\n /** The verified claims of the ingesting request (`{}` when the registry needs none). */\n claims: JwtClaims;\n /** The server-stamped identity this event would carry onto the queue. */\n identity: Record<string, string>;\n}\n\n/** `true` allows; `false` or `{ allow: false, reason }` refuses (a TERMINAL `refused` verdict). */\nexport type EventGateDecision = boolean | { allow: boolean; reason?: string };\n\n/**\n * The consent/entitlement gate (ADR-0053 decision 1): the one FUNCTION of the Event lane's contract, and so a\n * `createSyncServer` option rather than a registry field (the registry stays declarative data only).\n *\n * Called **once per event**, after the payload validated and the identity resolved, and before anything is\n * enqueued. Per-event (rather than per stream × batch) is the simplest correct shape: a consent or entitlement\n * decision may legitimately depend on the payload, and a per-batch hook could only express the subset that\n * does not. The claims are constant across a batch, so a hook that consults a store should memoize on them —\n * a batch can carry up to `MAX_EVENTS_PER_BATCH` events.\n *\n * A hook that THROWS fails the whole batch retryably (500, nothing enqueued): a gate that cannot decide must\n * never be read as \"allow\".\n */\nexport type EventGate = (input: EventGateInput) => EventGateDecision | Promise<EventGateDecision>;\n\n/** What {@link EventsEnqueuedHook} is told about a request that enqueued something. */\nexport interface EventsEnqueuedInfo {\n /** The Event streams this request put a sub-batch onto, deduplicated, in first-appearance order. */\n streams: string[];\n}\n\n/**\n * Fired after a request has ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02) — the\n * deployment-agnostic seam a serverless deployment uses to NUDGE its drain function.\n *\n * The library stays out of the transport: this hook hands over \"something landed on these streams\" and the\n * deployment decides what that means. A long-lived runner deployment wires nothing (its poller is already\n * about to read). A serverless one fires a fetch-and-forget at whatever endpoint calls the consumer's\n * `drainOnce()`, so an interactive append is drained in milliseconds rather than at the next scheduled tick.\n *\n * **It is latency, never delivery.** The scheduled sweep is the guarantee; a nudge that is lost, refused or\n * never sent costs nothing but time. So it is fire-and-forget by construction: it is called AFTER the\n * enqueue transaction committed, its return value is ignored (it is `void` — do not await anything through\n * it), and a throw is caught and warn-logged rather than affecting the response the client already earned.\n */\nexport type EventsEnqueuedHook = (info: EventsEnqueuedInfo) => void;\n\n/** The minimal transaction seam the endpoint needs — satisfied by a drizzle `PgAsyncDatabase`. */\nexport interface EventIngestDb {\n transaction: <TResult>(callback: (tx: EventQueueExecutor) => Promise<TResult>) => Promise<TResult>;\n}\n\nexport interface CreateEventIngestHandlerOptions {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n eventGate?: EventGate;\n /** See {@link EventsEnqueuedHook}. Fired only when something was actually enqueued. */\n onEventsEnqueued?: EventsEnqueuedHook;\n logTimings?: boolean;\n}\n\n/**\n * What a 503 asks the client to wait, in seconds. The client honours `Retry-After` over its own jittered\n * backoff when it asks for longer, so this is a floor on the retry of a batch the queue could not take.\n */\nexport const EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS = 5;\n\nconst encoder = new TextEncoder();\n\nfunction byteLengthOf(value: string): number {\n return encoder.encode(value).length;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** What {@link readBodyWithinLimit} answers with: the decoded body, or the batch-level status to return. */\ntype BodyRead = { ok: true; text: string } | { ok: false; status: 400 | 413 };\n\n/**\n * Read the request body WHILE enforcing the byte cap, aborting the moment the accumulated bytes exceed it.\n *\n * `request.text()` would buffer the whole body first and measure afterwards, which protects the JSON parse\n * and the queue but NOT memory: `Content-Length` is a claim, and a chunked (or simply lying) caller can omit\n * or understate it. This endpoint is public, so the cap has to bound what is ever held — hence a reader loop\n * that counts as it goes and cancels the stream on the first chunk that crosses the line, buffering at most\n * one chunk past the cap and never the rest of the upload.\n *\n * A body that cannot be read at all (including a request with no body) is a 400: it is a framing fault, and\n * a batch-level one, exactly like unparseable JSON.\n */\nasync function readBodyWithinLimit(request: Request, limit: number): Promise<BodyRead> {\n const body = request.body;\n if (body == null) {\n return { ok: false, status: 400 };\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value == null) {\n continue;\n }\n total += value.byteLength;\n if (total > limit) {\n // Stop the peer rather than draining the rest of an oversized upload into a buffer we will discard.\n await reader.cancel().catch(() => undefined);\n return { ok: false, status: 413 };\n }\n chunks.push(value);\n }\n } catch {\n return { ok: false, status: 400 };\n }\n\n const buffer = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { ok: true, text: new TextDecoder().decode(buffer) };\n}\n\nfunction errorResponse(message: string, status: number, headers?: Record<string, string>): Response {\n // `batchEventErrorSchema`: a non-2xx is always a whole-batch fault, so the body carries a message and\n // nothing to attribute.\n return Response.json({ message }, { status, ...(headers ? { headers } : {}) });\n}\n\n/**\n * Whether ANY registered Event stream declares an identity field — i.e. whether ingest NEEDS verified claims.\n * The mutation path's posture, mirrored: it demands claims when the registry actually requires them (an RLS\n * policy or an `authClaim` managed field) rather than unconditionally. A registry whose streams declare no\n * identity at all stamps nothing from claims, so it does not force an auth adapter into existence.\n */\nexport function eventIngestRequiresClaims(streams: EventStreamRegistry): boolean {\n return Object.values(streams).some((entry) => Object.keys(entry.identity ?? {}).length > 0);\n}\n\nexport function createEventIngestHandler<TRegistry extends SyncTableRegistry>(\n db: EventIngestDb,\n registry: TRegistry,\n queue: EventQueue,\n options: CreateEventIngestHandlerOptions = {},\n): FetchHandler {\n const streams = getSyncRegistryStreams(registry) ?? {};\n const requiresClaims = eventIngestRequiresClaims(streams);\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n const handle = async (request: Request): Promise<Response> => {\n const started = options.logTimings ? perfNow() : 0;\n let authMs = 0;\n let enqueueMs = 0;\n\n const finish = (response: Response, eventCount: number): Response => {\n if (options.logTimings) {\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route: \"events\",\n authMs: Math.round(authMs),\n enqueueMs: Math.round(enqueueMs),\n totalMs: Math.round(perfNow() - started),\n events: eventCount,\n status: response.status,\n }),\n );\n }\n return response;\n };\n\n // 1. Request-shape limits, BEFORE any parse — and the cap BOUNDS MEMORY, it does not merely report on it\n // afterwards. A truthful `Content-Length` is the cheap fast path (refused without reading a byte);\n // otherwise the body is read through a counting reader that aborts the moment it crosses the cap, so a\n // chunked or lying caller cannot make this public endpoint buffer an arbitrary upload.\n const declaredLength = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > MAX_EVENT_REQUEST_BYTES) {\n return finish(\n errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413),\n 0,\n );\n }\n\n const bodyRead = await readBodyWithinLimit(request, MAX_EVENT_REQUEST_BYTES);\n if (!bodyRead.ok) {\n return finish(\n bodyRead.status === 413\n ? errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413)\n : errorResponse(\"Invalid batch event request: the body could not be read\", 400),\n 0,\n );\n }\n const rawText = bodyRead.text;\n\n // 2. Strict framing. Unreachable through the library (appends are validated, envelopes are library-built)\n // — this layer exists for library bugs and non-library callers.\n let rawBody: unknown;\n try {\n rawBody = JSON.parse(rawText);\n } catch {\n return finish(errorResponse(\"Invalid batch event request: the body is not valid JSON\", 400), 0);\n }\n\n // Request-shape limits are 413, NOT 400 (ADR-0053 decision 3): an over-count is a LIMIT violation, and\n // the client must distinguish it from malformed framing. `batchEventRequestSchema` caps the array too, so\n // the count is checked here — after the JSON parse, before the strict parse — or the schema would answer\n // first with a 400. Only the count is read; every other malformation still falls through to the 400 below.\n if (isPlainObject(rawBody) && Array.isArray(rawBody[\"events\"]) && rawBody[\"events\"].length > MAX_EVENTS_PER_BATCH) {\n return finish(\n errorResponse(`Event batch carries more than the ${MAX_EVENTS_PER_BATCH}-event per-request limit`, 413),\n 0,\n );\n }\n\n const framing = batchEventRequestSchema.safeParse(rawBody);\n if (!framing.success) {\n return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);\n }\n const events = framing.data.events;\n\n // 3. Claims, resolved through the ONE adapter the read and write paths share, so an event's attribution\n // can never be authorized differently from a write.\n const authStart = options.logTimings ? perfNow() : 0;\n const resolvedClaims = await options.resolveAuthClaims?.(request);\n if (options.logTimings) authMs = perfNow() - authStart;\n\n if (requiresClaims && !isPlainObject(resolvedClaims)) {\n return finish(\n errorResponse(\"Event streams with claim-stamped identity require validated JWT claims\", 401),\n events.length,\n );\n }\n const claims: JwtClaims = isPlainObject(resolvedClaims) ? resolvedClaims : {};\n\n // 4. Per-event verdicts, in request order. Survivors are split by Event stream — insertion order gives\n // each stream's sub-batch the events in the order the client appended them (ADR-0053 decision 5).\n const acks: EventAck[] = [];\n const byStream = new Map<string, StampedEvent[]>();\n\n for (const event of events) {\n const entry = streams[event.stream];\n if (!entry) {\n // NOT terminal: a client rolled out ahead of its server is ordinary deployment skew, and deleting\n // its events would be data loss on a normal path.\n acks.push({\n eventId: event.eventId,\n status: \"deferred\",\n reason: `Unknown Event stream \"${event.stream}\" — this server registers none by that name`,\n });\n continue;\n }\n\n if (!isZodSchema(entry.payload)) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Event stream \"${event.stream}\" is registered without a usable payload schema`,\n });\n continue;\n }\n\n // THE authoritative parse: the one whose OUTPUT is taken. The JSON-NORMALIZED form of `parsed.data`\n // (never the raw envelope payload) is what gets stamped onto the queue and what the consumer callback\n // receives — the normalization is the JSON round-trip below, and it is part of the contract, not an\n // artefact: a transform producing a `Date` delivers that date's ISO STRING, and nested `undefined`\n // properties are dropped.\n //\n // The schema itself EXECUTES at both boundaries, and that is worth being exact about: `appendEvent`\n // already ran it on the client as pure validation — discarding the result and storing the caller's\n // original value — so what arrives here is the value that was appended, never a once-transformed one.\n // A transform CALLBACK therefore runs twice while its result is only ever taken once, which is exactly\n // why the lane requires transforms to be pure and deterministic: an effectful or environment-dependent\n // one is unsupported, because this server's run is the one that counts and nothing reconciles it\n // against the client's.\n const parsedPayload = entry.payload.safeParse(event.payload);\n if (!parsedPayload.success) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Payload failed the schema registered for Event stream \"${event.stream}\": ${parsedPayload.error.message}`,\n });\n continue;\n }\n\n // The authoritative parse's OUTPUT still has to reach the queue as JSON, and a schema is free to\n // produce something JSON cannot carry: `z.string().transform(BigInt)` makes `JSON.stringify` THROW,\n // and a transform returning `undefined` makes it RETURN `undefined`. Untrapped, the throw would fail\n // the WHOLE batch with a 500 — and the Outbox, having had no verdict, would resend that same event\n // forever, wedging every sibling behind it. So it is a TERMINAL per-event `rejected`, and deliberately\n // its own reason: labelling it \"exceeds the byte limit\" would send an author hunting a size problem\n // that does not exist. (The size check below stays exactly what it says.)\n //\n // This serialization is NOT merely a check — it IS the normalization the consumer contract names. A\n // successful `JSON.stringify` does not mean the value belongs to the JSON domain: a `Date` stringifies\n // to an ISO string, a nested `undefined` property vanishes, an `undefined` array member becomes `null`.\n // Enqueueing `parsedPayload.data` itself would hand an in-memory/fake queue the un-normalized value\n // while real pgmq (which serializes into `jsonb`) delivered the normalized one — the same event\n // observed as two different values depending on the backend. So these exact bytes are what is parsed\n // back and stamped below, and every backend, the fake and pgmq alike, sees the identical payload.\n let payloadJson: string | undefined;\n let serializationFailure: unknown;\n try {\n payloadJson = JSON.stringify(parsedPayload.data);\n } catch (error) {\n serializationFailure = error;\n }\n if (payloadJson === undefined) {\n const detail = serializationFailure instanceof Error ? serializationFailure.message : undefined;\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason:\n `The payload schema's parse for Event stream \"${event.stream}\" produced a value that cannot be ` +\n `serialized as JSON${detail != null ? `: ${detail}` : \"\"}`,\n });\n continue;\n }\n\n if (byteLengthOf(payloadJson) > MAX_EVENT_PAYLOAD_BYTES) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Payload exceeds the ${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit`,\n });\n continue;\n }\n\n // Identity is resolved BEFORE the gate so the hook can consult the attribution it is gating; an\n // unresolvable identity is a rejection in its own right and never reaches the hook.\n const resolvedIdentity = resolveEventIdentity(claims, entry.identity ?? {});\n if (!resolvedIdentity.ok) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason:\n `Identity field \"${resolvedIdentity.field}\" of Event stream \"${event.stream}\" could not be ` +\n `stamped from claim path ${JSON.stringify(resolvedIdentity.claimPath)}: ${resolvedIdentity.detail}`,\n });\n continue;\n }\n\n if (options.eventGate) {\n let decision: EventGateDecision;\n try {\n decision = await options.eventGate({\n stream: event.stream,\n event,\n claims,\n identity: resolvedIdentity.identity,\n });\n } catch (error) {\n // A gate that cannot decide must never be read as \"allow\". Fail the batch retryably: nothing is\n // enqueued, the Outbox keeps every row, and the client retries.\n console.error(\"[pgxsinkit] event gate threw; refusing the whole batch\", error);\n return finish(errorResponse(\"The event gate failed; nothing was enqueued\", 500), events.length);\n }\n\n const allowed = typeof decision === \"boolean\" ? decision : decision.allow;\n if (!allowed) {\n const reason = typeof decision === \"boolean\" ? undefined : decision.reason;\n acks.push({\n eventId: event.eventId,\n status: \"refused\",\n ...(reason ? { reason } : { reason: `Refused by the event gate for Event stream \"${event.stream}\"` }),\n });\n continue;\n }\n }\n\n // `payloadJson` is exactly the bytes the queue will carry, so parsing it back yields exactly the value\n // the consumer will observe — whatever backend is behind the seam. (`JSON.parse` of a string that\n // `JSON.stringify` just produced cannot throw.)\n const normalizedPayload: unknown = JSON.parse(payloadJson);\n\n const stamped: StampedEvent = {\n eventId: event.eventId,\n occurredAtUs: event.occurredAtUs,\n identity: resolvedIdentity.identity,\n payload: normalizedPayload,\n };\n const bucket = byStream.get(event.stream);\n if (bucket) {\n bucket.push(stamped);\n } else {\n byStream.set(event.stream, [stamped]);\n }\n acks.push({ eventId: event.eventId, status: \"acked\" });\n }\n\n // 5. One message per Event stream, all enqueued in ONE transaction. Atomic or nothing (ADR-0053\n // decision 4): the endpoint never partially enqueues and never buffers on the queue's behalf — the\n // Outbox is the buffer.\n const messages: EventQueueMessage[] = Array.from(byStream, ([stream, streamEvents]) => ({\n stream,\n events: streamEvents,\n }));\n\n if (messages.length > 0) {\n const enqueueStart = options.logTimings ? perfNow() : 0;\n try {\n await db.transaction(async (tx) => {\n await queue.enqueueBatch(messages, tx);\n });\n } catch (error) {\n // Deliberately generic to the client (the detail can name schema/queue internals); the operator gets\n // the full error on the server's own log.\n console.error(\"[pgxsinkit] event enqueue failed; nothing was enqueued\", error);\n return finish(\n errorResponse(\"The event queue is unavailable; nothing was enqueued\", 503, {\n \"Retry-After\": String(EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS),\n }),\n events.length,\n );\n }\n if (options.logTimings) enqueueMs = perfNow() - enqueueStart;\n\n // The nudge (ADR-0053 amendment): AFTER the commit, never awaited, never able to change the verdict\n // the client already earned. `byStream`'s keys are unique by construction, so the hook gets the\n // deduplicated stream names of this request in first-appearance order.\n if (options.onEventsEnqueued) {\n try {\n options.onEventsEnqueued({ streams: [...byStream.keys()] });\n } catch (error) {\n // A failed nudge costs latency, never delivery: the scheduled sweep is the guarantee.\n console.warn(\"[pgxsinkit] the `onEventsEnqueued` hook threw; the events are enqueued regardless\", error);\n }\n }\n }\n\n return finish(Response.json({ acks }), events.length);\n };\n\n return handle;\n}\n",
|
|
11
|
+
"import type { EventStreamIdentityField, JwtClaims } from \"@pgxsinkit/contracts\";\n\n/**\n * Identity stamping (ADR-0053 decisions 1 and 5): resolve an Event stream's declared identity fields against\n * the **verified** claims of the ingesting request.\n *\n * This is the security-sensitive step of the lane — the point where a client-supplied event becomes an\n * attributed fact. The client's envelope carries no identity at all, so everything the consumer callback sees\n * under `identity` comes from here, and only from claims the server itself verified.\n */\n\n/** A resolved stamp, or the first field that could not be resolved (which makes the event `rejected`). */\nexport type IdentityResolution =\n | { ok: true; identity: Record<string, string> }\n | { ok: false; field: string; claimPath: readonly string[]; detail: string };\n\n/**\n * Walk a claim path the way the managed-field `authClaim` strategy does (`ManagedFieldSpec.claimPath`), so\n * the toolkit's two claim-stamping surfaces address claims identically: each segment is a plain key into a\n * plain object, `[\"sub\"]` for the auth subject, `[\"app_metadata\", \"person_id\"]` for an app-minted identity.\n *\n * Arrays are NOT indexed (the SQL twin's `#>> '{a,b}'` would, but an identity addressed by array position is\n * not a shape the registry validates or the toolkit wants to encourage), and the walk stops at the first\n * segment that is not a plain object.\n */\nfunction readClaimAtPath(claims: JwtClaims, claimPath: readonly string[]): unknown {\n let current: unknown = claims;\n for (const segment of claimPath) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * Coerce a resolved claim to the stamped string value, or `null` when it is not stampable.\n *\n * A JSON scalar (number/boolean) is coerced to its text form deliberately: that is exactly what the SQL twin\n * (`current_setting('request.jwt.claims')::jsonb #>> '{…}'`) does for a managed `authClaim` field, so an\n * issuer that mints `person_id` as a JSON number stamps the same value on both surfaces. Anything else —\n * absent, null, an object, an array, or an empty/whitespace string — is NOT stampable: an empty identity must\n * never be stamped silently.\n */\nfunction toStampedValue(value: unknown): string | null {\n if (typeof value === \"string\") {\n return value.trim().length > 0 ? value : null;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (typeof value === \"boolean\") {\n return String(value);\n }\n return null;\n}\n\n/**\n * Resolve every declared identity field, or report the FIRST unresolvable one. Fail-closed by construction:\n * there is no partial stamp and no empty-string fallback — an event whose identity cannot be resolved gets a\n * `rejected` verdict naming the field and its claim path.\n */\nexport function resolveEventIdentity(\n claims: JwtClaims,\n identityFields: Record<string, EventStreamIdentityField>,\n): IdentityResolution {\n const identity: Record<string, string> = {};\n\n for (const [field, spec] of Object.entries(identityFields)) {\n const claimPath = spec.claimPath;\n const raw = readClaimAtPath(claims, claimPath);\n const stamped = toStampedValue(raw);\n if (stamped === null) {\n return {\n ok: false,\n field,\n claimPath,\n detail: raw === undefined ? \"the claim is absent\" : `the claim is not a stampable scalar (${typeof raw})`,\n };\n }\n identity[field] = stamped;\n }\n\n return { ok: true, identity };\n}\n",
|
|
12
|
+
"import { and, eq, sql, type AnyRelations } from \"drizzle-orm\";\nimport { getTableConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\nimport type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\nimport { createSchemaFactory } from \"drizzle-orm/zod\";\n\nimport type {\n AuthoritativeWriteRequest,\n BatchMutationRequest,\n JwtClaims,\n ManagedFieldApplyOn,\n MutationAck,\n RegistryRelations,\n SyncTableEntry,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport {\n authoritativeWriteRequestSchema,\n batchMutationRequestSchema,\n getOmittedProjectedColumns as getOmittedProjectionColumns,\n getProjectedColumns,\n isManagedFieldGuarded,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport type { OperationsLogConfig } from \"../operations-log/types\";\nimport { logOperation, logOperationSafely } from \"../operations-log/writer\";\nimport type { FetchHandler } from \"../router\";\nimport { readSqlState } from \"../sql-state\";\nimport {\n executePlpgsqlBatch,\n expectedApplyFingerprint,\n resolveApplyFunctionSchema,\n type ApplyFunctionRenderOptions,\n type MutationConflict,\n verifyRlsAuthHelpers,\n} from \"./plpgsql-apply\";\nimport type { TransactionClient } from \"./types\";\n\n/**\n * How the write path handles its remaining startup query class — the RLS auth-helper verify (ADR-0030\n * decision 3). The apply-function drift guarantee moved into the call itself (self-verifying function),\n * so this now governs ONLY that helper check:\n * - `\"in-process\"` (default): keep today's boot-time `verifyRlsAuthHelpers` and its clear startup error.\n * - `\"deploy-time\"`: skip it — the migration pipeline owns that guarantee, so a fresh (serverless)\n * worker sends ZERO queries before the mutation transaction itself.\n */\nexport type StartupVerificationMode = \"in-process\" | \"deploy-time\";\n\nconst { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({\n // Mutation payloads cross a JSON boundary, so bigint-mode Drizzle columns arrive as decimal strings.\n // Coerce only while validating; the original JSON payload remains string-valued for the SQL apply path.\n coerce: { date: true, bigint: true },\n});\n\ntype RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, \"select\">;\n\nexport const batchMutationPaths = [\"/api/mutations\"] as const;\n/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */\nexport const authoritativeMutationPaths = [\"/api/mutations/unit\"] as const;\n\nexport function createMutationHandler<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n operationsLogConfig: OperationsLogConfig,\n operationsLogReady: Promise<void>,\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null,\n startupVerification: StartupVerificationMode = \"in-process\",\n logTimings = false,\n // ADR-0054: the roles the installed artifact was generated with. The ACL is INSIDE the fingerprinted\n // body, so the expected fingerprint below is only reproducible when this matches the generate flags.\n applyFunctionGrantExecuteTo: readonly string[] = [],\n // The schema the installed artifact was generated into (`pgxsinkit-generate --function-schema`).\n // It is BOTH a fingerprint input (the body embeds the qualified name) and the name this server must\n // CALL, so one value drives both — a server that knows the fingerprint but calls the function\n // unqualified would resolve through `search_path` and, in the usual case, find nothing.\n applyFunctionSchema?: string,\n): { batch: FetchHandler; authoritative: FetchHandler } {\n let startupReadyPromise: Promise<void> | undefined;\n\n const applyFunctionRenderOptions: ApplyFunctionRenderOptions = {\n ...(applyFunctionGrantExecuteTo.length > 0 ? { grantExecuteTo: applyFunctionGrantExecuteTo } : {}),\n ...(applyFunctionSchema ? { functionSchema: applyFunctionSchema } : {}),\n };\n // Validated once here (the same rule the renderer applies) rather than per request, so a bad schema\n // name fails at server construction instead of on the first write.\n const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);\n const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};\n\n // ADR-0030: the fingerprint this server expects for its registry + applier codegen, computed ONCE per\n // server instance. Every `executePlpgsqlBatch` passes it so the installed apply function can verify\n // itself in-body (SQLSTATE 'PXS01' on drift) — this replaces the deleted startup verify.\n const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);\n\n // Per-request timing scratch (opt-in). authMs/applyMs are filled at the narrow phase call sites inside\n // the handler; totalMs + status are measured by `withTiming` wrapping the returned handler. A fresh\n // object per request keeps this concurrency-safe without threading state through the handler internals.\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n interface RequestTiming {\n handlerStart: number;\n preTxMs: number;\n txOpenMs: number;\n authMs: number;\n applyMs: number;\n mutations: number;\n }\n const withTiming = (route: string, handler: (request: Request, timing?: RequestTiming) => Promise<Response>) => {\n if (!logTimings) {\n return (request: Request) => handler(request);\n }\n return async (request: Request): Promise<Response> => {\n const start = perfNow();\n const timing: RequestTiming = {\n handlerStart: start,\n preTxMs: 0,\n txOpenMs: 0,\n authMs: 0,\n applyMs: 0,\n mutations: 0,\n };\n const response = await handler(request, timing);\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route,\n preTxMs: Math.round(timing.preTxMs),\n txOpenMs: Math.round(timing.txOpenMs),\n authMs: Math.round(timing.authMs),\n applyMs: Math.round(timing.applyMs),\n totalMs: Math.round(perfNow() - start),\n mutations: timing.mutations,\n status: response.status,\n }),\n );\n return response;\n };\n };\n // Stamp the two spans the phase timers cannot see: preTxMs = handler entry → transaction call\n // (parse + zod validation), txOpenMs = transaction call → callback entry (the driver's LAZY\n // connection establishment + BEGIN — on serverless this is where a fresh worker's pooler\n // TLS/DNS cost lands, invisible to authMs/applyMs).\n const stampPreTx = (timing: RequestTiming | undefined) => {\n if (timing) timing.preTxMs = perfNow() - timing.handlerStart;\n return timing ? perfNow() : 0;\n };\n const stampTxOpen = (timing: RequestTiming | undefined, txCallAt: number) => {\n if (timing) timing.txOpenMs = perfNow() - txCallAt;\n };\n\n const startupReady = () => {\n if (!startupReadyPromise) {\n // ADR-0030: \"deploy-time\" skips the boot-time RLS auth-helper verify (the migration pipeline owns\n // that guarantee), so a fresh worker sends no query here — combined with a declared operations-log\n // posture, the first statement a serverless worker sends is the mutation transaction itself.\n startupReadyPromise = startupVerification === \"in-process\" ? installStartupDdl(db, registry) : Promise.resolve();\n }\n\n return startupReadyPromise;\n };\n\n // Per-mutation payload validation shared by the batch and authoritative endpoints (security: both must\n // reject client-omitted projection fields, server-managed fields, and malformed payloads before apply).\n // Logs each offender and returns the attributable 400 Response, or null when every mutation is valid.\n const validateMutationsOrRespond = async (\n mutations: BatchMutationRequest[\"mutations\"],\n requestPath: string,\n ): Promise<Response | null> => {\n const validationErrors: string[] = [];\n const invalidMutations: Array<{\n mutation: BatchMutationRequest[\"mutations\"][number];\n message: string;\n }> = [];\n\n for (const mutation of mutations) {\n if (!(mutation.tableName in registry)) {\n const message = `Unknown table: ${mutation.tableName}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const entry = registry[mutation.tableName as keyof TRegistry]!;\n const syncEntry = entry as SyncTableEntry;\n const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);\n // Surface (once per table+key) only a payload key the apply path would SILENTLY drop — a truly\n // unknown key, never a projected-away/server-only column (those are 400-rejected just below, so\n // the helper excludes them; warning \"the write succeeds\" then rejecting was the misleading overlap).\n warnOnSilentlyDroppedPayloadKeys(syncEntry, mutation.tableName, mutation.kind, normalizedPayload);\n const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (projectedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (managedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n try {\n if (mutation.kind === \"update\") {\n const payloadKeys =\n typeof normalizedPayload === \"object\" && normalizedPayload !== null\n ? Object.keys(normalizedPayload as object)\n : [];\n if (payloadKeys.length === 0) {\n throw new Error(\"At least one field must be provided\");\n }\n buildUpdateValidationSchema(syncEntry).parse(normalizedPayload);\n } else if (mutation.kind === \"create\") {\n buildCreateValidationSchema(syncEntry).parse(normalizedPayload);\n }\n // delete has no payload to validate\n } catch (error) {\n const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : \"\";\n const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n }\n }\n\n if (validationErrors.length > 0) {\n for (const invalidMutation of invalidMutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: invalidMutation.mutation.tableName,\n operationKind: invalidMutation.mutation.kind,\n entityKey: invalidMutation.mutation.entityKey,\n payload: invalidMutation.mutation.payload,\n status: \"validation_failed\",\n errorMessage: invalidMutation.message,\n httpStatus: 400,\n mutationId: invalidMutation.mutation.mutationId,\n mutationSeq: invalidMutation.mutation.mutationSeq,\n clientTimestampUs: invalidMutation.mutation.clientTimestampUs,\n requestPath: requestPath,\n });\n }\n\n // Attribute the rejection to the specific offending mutations. The batch is atomic\n // (nothing was applied), so the client can quarantine exactly these and keep the\n // innocent siblings retryable — one bad mutation never poisons the whole offline queue.\n return Response.json(\n {\n message: `Payload validation failed: ${validationErrors.join(\"; \")}`,\n rejections: invalidMutations.map(({ mutation, message }) => ({\n tableName: mutation.tableName,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n reason: message,\n })),\n },\n { status: 400 },\n );\n }\n\n return null;\n };\n\n const handleBatchMutation = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: [],\n },\n { status: 400 },\n );\n }\n\n let body: BatchMutationRequest;\n\n try {\n body = batchMutationRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid batch mutation request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const acks: MutationAck[] = [];\n let actorUserId: string | null = null;\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const batchRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n batchRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n applyInvocationOptions,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n // ADR-0015: a reject-if-stale stale write was NOT applied — the applier returned it here.\n // Surface a `conflicted` ack (distinct from a failure) carrying the row's current Server\n // version, so the client keeps the optimistic overlay and resolves it as a new write.\n const conflictByMutationId = new Map(conflicts.map((conflict) => [conflict.mutationId, conflict]));\n\n for (const mutation of batchRequest.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n\n if (conflict) {\n // #6: a null currentServerVersion means the target row no longer exists (an UPDATE whose\n // row was deleted by another writer), distinct from a stale write over a row that moved.\n const conflictReason =\n conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no ` +\n `longer exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`;\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n continue;\n }\n\n const serverUpdatedAtUs = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n const errorMessage = formatBatchExecutionError(error);\n\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage,\n httpStatus: 500,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n }\n\n return Response.json({ message: errorMessage }, { status: 500 });\n }\n\n return Response.json({ acks });\n };\n\n // ADR-0022 §3 (mechanism c): the authoritative (pessimistic) write endpoint. One write-**unit** per POST,\n // applied in its OWN isolated transaction, atomically — so a constraint/trigger exception becomes a clean\n // per-mutation `rejected` ack (the whole unit rolls back, overlays auto-discard) instead of the batch\n // path's whole-batch 500, and a stale member surfaces `conflicted` (overlays kept) without partial apply.\n const handleAuthoritativeWrite = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json({ message: \"Invalid authoritative write request\", issues: [] }, { status: 400 });\n }\n\n let body: AuthoritativeWriteRequest;\n\n try {\n body = authoritativeWriteRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid authoritative write request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json(\n {\n message: \"Invalid authoritative write request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n let actorUserId: string | null = null;\n // The unit's outcome, decided inside its OWN transaction: applied (Server versions per member) or\n // conflicted (a stale member → rolled back, overlays kept). An execution exception is handled in catch.\n let appliedServerVersions: Map<string, string | null> | null = null;\n let unitConflicts: MutationConflict[] | null = null;\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const unitRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n unitRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n applyInvocationOptions,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n if (conflicts.length > 0) {\n // The unit is atomic — a stale member means none of it applies. Roll back; report all members as\n // conflicted (overlays kept, re-resolve the unit) below.\n unitConflicts = conflicts;\n throw new UnitNotCommittedError();\n }\n\n // Applied cleanly. Read each member's resulting Server version INSIDE the txn, before it commits.\n const versions = new Map<string, string | null>();\n for (const mutation of unitRequest.mutations) {\n const version = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n versions.set(mutation.mutationId, version ?? null);\n }\n appliedServerVersions = versions;\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n if (!(error instanceof UnitNotCommittedError)) {\n // A DB-enforced invariant (capacity/quota/uniqueness constraint or trigger) declined the unit. The\n // whole unit rolled back; surface a per-mutation `rejected` ack so the client auto-discards the\n // unit's optimistic overlay (ADR-0022 §4). The ack carries a SANITISED reason — the raw DB error\n // (constraint names, offending values/PII, schema, hints) stays in the operations log only.\n const internalDetail = formatBatchExecutionError(error);\n const publicReason = toPublicRejectionReason(error);\n const rejectedAcks: MutationAck[] = [];\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage: internalDetail,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n rejectedAcks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"rejected\",\n rejectionReason: publicReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks: rejectedAcks });\n }\n // UnitNotCommittedError — `unitConflicts` is set; fall through to conflicted-ack building.\n }\n\n const acks: MutationAck[] = [];\n\n if (unitConflicts) {\n const conflictByMutationId = new Map(\n (unitConflicts as MutationConflict[]).map((conflict) => [conflict.mutationId, conflict]),\n );\n for (const mutation of body.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n const conflictReason = conflict\n ? conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no longer ` +\n `exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`\n : `Atomic write-unit not committed (ADR-0022): a sibling write in the same unit was rejected as ` +\n `stale, so this write rolled back too. Re-resolve the unit.`;\n\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict?.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks });\n }\n\n // Applied: ack every member, carrying the Server version each converged to.\n const serverVersions = appliedServerVersions ?? new Map<string, string | null>();\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n const serverUpdatedAtUs = serverVersions.get(mutation.mutationId) ?? undefined;\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n\n return Response.json({ acks });\n };\n\n return {\n batch: withTiming(\"mutations\", handleBatchMutation),\n authoritative: withTiming(\"mutations\", handleAuthoritativeWrite),\n };\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatBatchExecutionError(error: unknown): string {\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return \"Batch mutation failed\";\n }\n\n const details = [rootCause.message];\n const errorCode = getErrorStringProperty(rootCause, \"code\");\n const errorDetail = getErrorStringProperty(rootCause, \"detail\");\n const errorHint = getErrorStringProperty(rootCause, \"hint\");\n\n if (errorCode) {\n details.push(`code: ${errorCode}`);\n }\n\n if (errorDetail) {\n details.push(`detail: ${errorDetail}`);\n }\n\n if (errorHint) {\n details.push(`hint: ${errorHint}`);\n }\n\n return details.join(\" | \");\n}\n\n/**\n * Map a DB exception to a **client-safe** rejection reason for an authoritative `rejected` ack (ADR-0022 §4).\n * The raw error text (`formatBatchExecutionError`) leaks constraint names, schema/table, the offending\n * VALUES (potential PII), and trigger hints — and a `rejected` ack is success-path copy the app surfaces to\n * users, so it must not echo that. Two cases:\n *\n * - **App-authored `RAISE`** (PL/pgSQL `RAISE EXCEPTION 'cohort is full'`, SQLSTATE `P0001` / a custom `P0…`\n * class): the message IS the consumer's own user-facing copy — pass it through. This is the intended way\n * to give a friendly capacity/quota message.\n * - **Built-in integrity violations** (SQLSTATE class `23`) and everything else: return a stable generic\n * message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.\n */\nexport function toPublicRejectionReason(error: unknown): string {\n const fallback = \"The write was rejected by a server rule.\";\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return fallback;\n }\n\n // Resolve the SQLSTATE with the driver-agnostic helper (bun-sql — this project's runtime driver —\n // carries it on `errno`, not `code`; postgres.js / pg on `code`). Reading `error.code` directly, as\n // this did, returned bun's generic \"ERR_POSTGRES_SERVER_ERROR\" and dropped every app-authored `P0…`\n // and constraint code into the generic fallback, breaking ADR-0022's friendly rejection channel.\n // `readSqlState` walks the cause chain itself, so it runs on the ORIGINAL error; the app-authored\n // RAISE MESSAGE below still comes from the root cause.\n const code = readSqlState(error);\n\n // ADR-0030: the self-verifying apply function raises SQLSTATE 'PXS01' when its installed fingerprint\n // does not match this server's registry/codegen — the drift the deleted startup verify used to catch.\n // Surface the same actionable operator guidance the old startup error gave (it carries no PII, only the\n // regenerate-and-apply instruction), rather than the generic rejection fallback.\n if (code === \"PXS01\") {\n return (\n \"The server's apply function is out of date: its installed fingerprint does not match this \" +\n \"server's registry/codegen. Regenerate the sync-function migration (pgxsinkit-generate) and apply \" +\n \"it before serving writes.\"\n );\n }\n\n // App-authored RAISE — the message is the consumer's own copy, safe to surface.\n if (code && (code === \"P0001\" || code.startsWith(\"P0\"))) {\n return rootCause.message.trim() || fallback;\n }\n\n // Built-in integrity violations: generic, code-keyed messages only (no raw constraint names / values).\n const genericByCode: Record<string, string> = {\n \"23505\": \"This conflicts with an existing record (a uniqueness rule was violated).\",\n \"23514\": \"A validation rule rejected this write.\",\n \"23503\": \"A referenced record is missing (a relationship rule was violated).\",\n \"23502\": \"A required value was missing.\",\n \"23P01\": \"An exclusion rule rejected this write.\",\n };\n\n if (code && genericByCode[code]) {\n return genericByCode[code]!;\n }\n\n if (code && code.startsWith(\"23\")) {\n return \"A data-integrity rule rejected this write.\";\n }\n\n return fallback;\n}\n\nfunction getRootCauseError(error: unknown): Error | null {\n let current = error;\n let lastError: Error | null = null;\n const seen = new Set<unknown>();\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n lastError = current;\n current = current.cause;\n }\n\n return lastError;\n}\n\nfunction getErrorStringProperty(error: Error, key: string): string | null {\n if (!(key in error)) {\n return null;\n }\n\n const value = (error as unknown as Record<string, unknown>)[key];\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction isRlsAuthContextRequired(registry: SyncTableRegistry): boolean {\n return Object.values(registry).some(\n (entry) =>\n getTableConfig(entry.table as AnyPgTable).policies.length > 0 ||\n (entry.governance?.managedFields ?? []).some((field) => field.strategy === \"authClaim\"),\n );\n}\n\nclass UnauthorizedBatchMutationError extends Error {}\n\n/**\n * Thrown inside the authoritative write's transaction to roll the whole unit back when a member is a stale\n * write (ADR-0015) — distinct from an execution exception (a capacity/constraint rejection). The handler\n * catches it and reports every member `conflicted` (overlays kept), having committed nothing.\n */\nclass UnitNotCommittedError extends Error {}\n\nfunction getUuidClaim(claims: JwtClaims, key: string): string | null {\n const value = claims[key];\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n 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;\n}\n\n/**\n * The server-managed payload keys a mutation must not carry — the 400 guard (see\n * {@link getGuardedManagedFields} for what counts as managed per operation, notably that a create-only\n * managed field is guarded on update too). Exported for direct unit coverage.\n */\nexport function findManagedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const managedFields = getGuardedManagedFields(entry, mutationKind);\n if (managedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);\n}\n\n// One structured warning per (table, dropped-key) per process. The apply path is hot; a memoized set\n// keeps a recurring silent-drop from spamming the log while still surfacing it once. The keys are\n// client-controlled (a malicious/buggy client can send unbounded junk keys), so the set is capped: past\n// the cap we stop memoizing AND stop warning, so the process can never accumulate unbounded entries.\nconst warnedDroppedPayloadKeys = new Set<string>();\nconst MAX_WARNED_DROPPED_KEYS = 10_000;\n// Set true after the one-time \"warnings suppressed\" notice fires, so the cap notice logs exactly once.\nlet droppedKeyWarningSuppressed = false;\n\n/**\n * Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path\n * will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,\n * nor a projected-away column that request validation already 400-rejects. The generated apply function\n * reads only the table's PROJECTED columns from the payload jsonb, so such a key never lands — were it\n * \"applied\" the write would collapse to a bare server-version (`updated_at_us`) bump. This is the clean\n * two-case split (ADR-0022 posture docs):\n *\n * - **Projected-away / server-only columns** (`clientProjection.omitColumns`) sent explicitly are\n * **400-rejected** by {@link findProjectedFieldViolations} — they are NOT silently dropped, so this\n * helper deliberately does **not** warn for them (warning \"the write still succeeds\" and then\n * rejecting was the misleading overlap the review flagged).\n * - **Unknown non-column keys** (a typo, a stale field) are what the apply path silently ignores — those\n * are exactly the keys this warns about, once, as a debugging aid. It is NOT an error and changes no\n * semantics.\n *\n * Exported for direct unit coverage.\n */\nexport function warnOnSilentlyDroppedPayloadKeys(\n entry: SyncTableEntry,\n tableName: string,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): void {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return;\n }\n\n // The keys the apply path will actually write: the projected columns (what it reads from payload) plus\n // the managed fields for this operation (server-stamped, legitimately present). Both property key and\n // DB column name are accepted, so a payload keyed either way is not falsely flagged.\n const writable = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedColumns(entry)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n for (const { propertyKey, columnName } of getManagedFieldsForOperation(entry, mutationKind)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n\n // Keys request validation will 400-REJECT (an explicitly-sent projected-away / server-only column):\n // those never reach apply, so they are NOT a silent drop — exclude them so the warning is reserved for\n // truly-unknown keys the apply path drops without validation rejecting.\n const rejectedAtValidation = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedAwayFields(entry)) {\n rejectedAtValidation.add(propertyKey);\n rejectedAtValidation.add(columnName);\n }\n\n for (const key of Object.keys(payload)) {\n if (writable.has(key) || rejectedAtValidation.has(key)) {\n continue;\n }\n const memoKey = `${tableName}::${key}`;\n if (warnedDroppedPayloadKeys.has(memoKey)) {\n continue;\n }\n // Cap the memo set against client-controlled key spray: once full, emit one final suppression notice\n // and stop both memoizing and warning — the set never grows past the cap.\n if (warnedDroppedPayloadKeys.size >= MAX_WARNED_DROPPED_KEYS) {\n if (!droppedKeyWarningSuppressed) {\n droppedKeyWarningSuppressed = true;\n console.warn(\n `[pgxsinkit] Dropped-key warnings suppressed: more than ${MAX_WARNED_DROPPED_KEYS} distinct ` +\n `(table, key) pairs have been reported this process. Further dropped payload keys will not be logged.`,\n );\n }\n return;\n }\n warnedDroppedPayloadKeys.add(memoKey);\n console.warn(\n `[pgxsinkit] Payload for table \"${tableName}\" carries key \"${key}\", which is not a column of that ` +\n `table — the apply path silently ignores it (a write that reached apply would collapse to a bare ` +\n `server-version bump). This is almost always a typo or a stale field: check the spelling against ` +\n `the table's columns, or remove \"${key}\" if the schema no longer has it. (A projected-away/` +\n `server-only column would instead be 400-rejected, not dropped, so it is not what this warns about.) ` +\n `(Logged once per table+key per process.)`,\n { table: tableName, droppedKey: key, hint: \"unknown-non-column-key\" },\n );\n }\n}\n\nfunction findProjectedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const projectedFields = getProjectedAwayFields(entry);\n if (projectedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n\n return [\n ...new Set(\n projectedFields\n .filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName))\n .map((field) => field.propertyKey),\n ),\n ];\n}\n\n/**\n * Defense in depth behind the 400 guard: strip every server-owned key from each payload before apply, so\n * a caller that reaches this code path without the request-level check (or a key spelled as the DB column\n * name rather than the property key) still cannot set a managed or projected-away column. Exported for\n * direct unit coverage.\n */\nexport function sanitizeRestrictedFields(\n batch: BatchMutationRequest,\n registry: SyncTableRegistry,\n): BatchMutationRequest {\n return {\n mutations: batch.mutations.map((mutation) => {\n if (mutation.kind === \"delete\") {\n return mutation;\n }\n\n const entry = registry[mutation.tableName];\n\n if (!entry) {\n return mutation;\n }\n\n const managedFields = getGuardedManagedFields(entry as SyncTableEntry, mutation.kind);\n const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);\n\n if (managedFields.length === 0 && projectedFields.length === 0) {\n return mutation;\n }\n\n const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};\n\n for (const field of managedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n for (const field of projectedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n return {\n ...mutation,\n payload,\n };\n }),\n };\n}\n\n/**\n * The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /\n * `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —\n * and {@link findManagedFieldViolations} already rejects a payload that includes them. They are\n * omitted from the insert schema so a NOT NULL managed column without a SQL DEFAULT (e.g. an `authUid`\n * author/owner/created_by) is not falsely required. (A column carrying a DEFAULT is already optional\n * in the drizzle insert schema; this also covers a managed column that has none.)\n */\nexport function buildCreateValidationSchema(entry: SyncTableEntry) {\n const createSchema = createMutationInsertSchema(entry.table as AnyPgTable);\n const managedCreateKeys = getGuardedManagedFields(entry, \"create\").map((field) => field.propertyKey);\n if (managedCreateKeys.length === 0) {\n return createSchema;\n }\n // The omit-mask keys are derived from governance at runtime, so they cannot be narrowed to the\n // schema's literal-key mask type — cast through the parameter type.\n const omitMask = Object.fromEntries(managedCreateKeys.map((key) => [key, true as const])) as Parameters<\n typeof createSchema.omit\n >[0];\n return createSchema.omit(omitMask);\n}\n\n/**\n * The zod schema used to validate an `update` payload: the insert schema made `partial()` (an update is a\n * patch — only the sent keys are validated), minus every server-managed key. This is the update-side\n * counterpart of {@link buildCreateValidationSchema}: a field managed on update is stamped by the server,\n * and a **create-only** managed field is inert on update (the generated apply function omits it from the\n * UPDATE SET candidates), so neither is a settable key of an update payload. Both are already\n * 400-rejected by {@link findManagedFieldViolations}; omitting them keeps the schema an accurate\n * statement of what an update may carry.\n */\nexport function buildUpdateValidationSchema(entry: SyncTableEntry) {\n const updateSchema = createMutationInsertSchema(entry.table as AnyPgTable).partial();\n const managedKeys = getGuardedManagedFields(entry, \"update\").map((field) => field.propertyKey);\n if (managedKeys.length === 0) {\n return updateSchema;\n }\n const omitMask = Object.fromEntries(managedKeys.map((key) => [key, true as const])) as Parameters<\n typeof updateSchema.omit\n >[0];\n return updateSchema.omit(omitMask);\n}\n\nfunction getManagedFields(\n entry: SyncTableEntry,\n matches: (field: { applyOn: readonly ManagedFieldApplyOn[] }) => boolean,\n) {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? [])\n .filter((field) => matches(field))\n .map((field) => ({\n propertyKey: field.column,\n columnName: columnMap.get(field.column) ?? field.column,\n strategy: field.strategy,\n }));\n}\n\nfunction getManagedFieldsForOperation(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n if (mutationKind === \"delete\") {\n return [];\n }\n\n return getManagedFields(entry, (field) => field.applyOn.includes(mutationKind));\n}\n\n/**\n * The fields the request-path guards treat as **server-owned** for `mutationKind` — the one set the\n * violation check flags, the sanitizer strips, and the validation schema omits. This resolves the\n * governance specs to `{ propertyKey, columnName, strategy }`; WHICH of them are server-owned is not\n * decided here but by contracts' {@link isManagedFieldGuarded}, the single definition of the guard rule\n * (shared with the client's `stripManagedFields` and the apply-function generator).\n */\nfunction getGuardedManagedFields(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n return getManagedFields(entry, (field) => isManagedFieldGuarded(field, mutationKind));\n}\n\nfunction getProjectedAwayFields(entry: SyncTableEntry) {\n return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({\n propertyKey,\n columnName,\n }));\n}\n\nfunction toSchemaPayload(entry: SyncTableEntry, payload: unknown): unknown {\n if (!isPlainObject(payload)) {\n return payload;\n }\n\n const columns = getColumns(entry.table as AnyPgTable);\n const keyMap = new Map<string, string>();\n\n for (const [propertyKey, column] of Object.entries(columns)) {\n keyMap.set(propertyKey, propertyKey);\n keyMap.set(column.name, propertyKey);\n }\n\n return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));\n}\n\nfunction resolveServerUpdatedAtColumnName(entry: SyncTableEntry): string {\n // The single source for the Server version column (ADR-0010 / ADR-0004): resolves the\n // managed field's property key to its column name. Falls back to the conventional name for\n // resilience, though registry validation now guarantees a writable table declares one.\n return resolveServerVersionColumnName(entry) ?? \"updated_at_us\";\n}\n\nasync function readServerUpdatedAtUs(\n tx: RouteReadQueryClient,\n entry: SyncTableEntry,\n entityKey: Record<string, string>,\n): Promise<string | undefined> {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnName = resolveServerUpdatedAtColumnName(entry);\n const updatedAtColumn = Object.values(columns).find((column) => column.name === columnName);\n\n if (!updatedAtColumn) {\n return undefined;\n }\n\n const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {\n const rawValue = entityKey[primaryKeyColumn];\n\n if (rawValue === undefined) {\n throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);\n }\n\n const primaryKeyTableColumn = Object.values(columns).find((column) => column.name === primaryKeyColumn);\n\n if (!primaryKeyTableColumn) {\n throw new Error(`Missing table column metadata for primary key column ${primaryKeyColumn}`);\n }\n\n return eq(primaryKeyTableColumn, rawValue);\n });\n\n const whereClause = conditions.length === 1 ? conditions[0]! : and(...conditions);\n const rows = await tx\n .select({ updatedAtUs: sql<string>`${updatedAtColumn}::text` })\n .from(entry.table as AnyPgTable)\n .where(whereClause)\n .limit(1);\n\n return rows[0]?.updatedAtUs ?? undefined;\n}\n\n// ADR-0030: the apply-function drift verify is gone from startup — the function verifies itself in-body\n// (SQLSTATE 'PXS01'). The only remaining boot-time check is the RLS auth-helper presence, and only when\n// the registry actually needs it. Reached only under `startupVerification: \"in-process\"`.\nasync function installStartupDdl<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n): Promise<void> {\n if (isRlsAuthContextRequired(registry)) {\n await verifyRlsAuthHelpers(db);\n }\n}\n",
|
|
8
13
|
"import { bigint, bigserial, index, integer, jsonb, pgTable, text, timestamp, uuid, varchar } from \"drizzle-orm/pg-core\";\n\nimport { clockMicrosecondsSql } from \"@pgxsinkit/contracts\";\n\nexport const operationsLogTable = pgTable(\n \"operations_log\",\n {\n id: bigserial(\"id\", { mode: \"number\" }).primaryKey(),\n tableName: varchar(\"table_name\", { length: 255 }),\n operationKind: varchar(\"operation_kind\", { length: 24 }),\n userId: uuid(\"user_id\"),\n entityKeyJson: jsonb(\"entity_key_json\"),\n payloadJson: jsonb(\"payload_json\"),\n status: varchar(\"status\", { length: 32 }).notNull(),\n errorMessage: text(\"error_message\"),\n httpStatus: integer(\"http_status\"),\n // Text, NOT uuid: derived child envelopes (the expander tier) carry composite non-UUID ids of the\n // form `${parentMutationId}:<tag>:<n>`, so the log column must accept any string the apply path may\n // record. This is the server-side tier of the two-tier mutation-id invariant (see plpgsql-apply.ts\n // and packages/contracts/src/mutation.ts): the apply function + this log accept opaque text for a\n // direct caller deriving children, while pgxsinkit's public surface (route schemas, client journal)\n // stays UUID-only. (The ::uuid casts on this id were dropped for the same reason.)\n mutationId: text(\"mutation_id\"),\n mutationSeq: integer(\"mutation_seq\"),\n clientTimestampUs: bigint(\"client_timestamp_us\", { mode: \"bigint\" }),\n requestPath: text(\"request_path\"),\n serverTimestampUs: bigint(\"server_timestamp_us\", { mode: \"bigint\" }).notNull().default(clockMicrosecondsSql),\n createdAt: timestamp(\"created_at\", { mode: \"date\", withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index(\"operations_log_created_at_idx\").on(table.createdAt.desc()),\n index(\"operations_log_table_name_idx\").on(table.tableName),\n index(\"operations_log_user_id_idx\").on(table.userId),\n index(\"operations_log_status_idx\").on(table.status),\n index(\"operations_log_mutation_id_idx\").on(table.mutationId),\n ],\n);\n\nexport type OperationsLogRow = typeof operationsLogTable.$inferSelect;\nexport type NewOperationsLogRow = typeof operationsLogTable.$inferInsert;\n",
|
|
9
14
|
"import { operationsLogTable } from \"./schema\";\nimport type { OpsLogEntry, OperationsLogConfig, SqlExecutor } from \"./types\";\n\nfunction toJsonValue(value: unknown): unknown {\n if (value === undefined) {\n return null;\n }\n\n return value;\n}\n\nfunction toBigIntValue(value: string | null | undefined): bigint | null {\n if (value === undefined || value === null) {\n return null;\n }\n\n return BigInt(value);\n}\n\nexport async function logOperation(\n executor: SqlExecutor,\n config: OperationsLogConfig,\n entry: OpsLogEntry,\n): Promise<void> {\n if (!config.enabled) {\n return;\n }\n\n await executor.insert(operationsLogTable).values({\n tableName: entry.tableName ?? null,\n operationKind: entry.operationKind ?? null,\n userId: entry.userId ?? null,\n entityKeyJson: toJsonValue(entry.entityKey ?? null),\n payloadJson: toJsonValue(entry.payload),\n status: entry.status,\n errorMessage: entry.errorMessage ?? null,\n httpStatus: entry.httpStatus ?? null,\n mutationId: entry.mutationId ?? null,\n mutationSeq: entry.mutationSeq ?? null,\n clientTimestampUs: toBigIntValue(entry.clientTimestampUs),\n requestPath: entry.requestPath ?? null,\n });\n}\n\nexport async function logOperationSafely(\n executor: SqlExecutor,\n config: OperationsLogConfig,\n entry: OpsLogEntry,\n): Promise<void> {\n try {\n await logOperation(executor, config, entry);\n } catch {\n // Failure-path logging must not hide the original route response/error.\n }\n}\n",
|
|
10
15
|
"/**\n * Read the Postgres `SQLSTATE` (the five-character error class, e.g. `\"23505\"` unique_violation) off a\n * thrown database error.\n *\n * **Why this helper exists — the bun-sql gotcha.** Bun's built-in `SQL`/`sql` driver (what pgxsinkit and\n * its consumers run against Postgres) surfaces the server's SQLSTATE on the error's **`errno`** property.\n * Its **`code`** property is bun's own generic string (`\"ERR_POSTGRES_SERVER_ERROR\"`), NOT the SQLSTATE —\n * so the intuitive `error.code` read (which worked under `postgres.js` / `pg`, where `code` carried the\n * SQLSTATE) silently returns the wrong thing under bun-sql. Consumers reaching for a stable, driver-agnostic\n * SQLSTATE (to map `23505`→\"already exists\", `P0001`→a raised app rule, etc.) kept re-deriving this by hand;\n * this is the one canonical extraction.\n *\n * Resolution order, returning the first well-formed SQLSTATE found:\n * 1. `errno` on the error (bun-sql),\n * 2. `code` on the error (postgres.js / node-postgres, and any driver that follows that convention),\n * 3. the same two properties walked down the `cause` chain (a wrapped/re-thrown error).\n *\n * A \"well-formed\" SQLSTATE is exactly five characters of `[0-9A-Z]` — this is what rejects bun's generic\n * `code` string, an `errno` that is a numeric OS errno, and any other non-SQLSTATE noise. A non-object\n * error (string, number, `null`, `undefined`) yields `undefined`.\n */\nexport function readSqlState(error: unknown): string | undefined {\n // Guard against a self-referential (or pathologically deep) `cause` chain — walk a bounded number of\n // links, never a `while (true)`.\n const MAX_CAUSE_DEPTH = 16;\n\n let current: unknown = error;\n for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) {\n if (!current || typeof current !== \"object\") {\n return undefined;\n }\n\n const candidate = current as { errno?: unknown; code?: unknown; cause?: unknown };\n\n // bun-sql: SQLSTATE on `errno`. postgres.js / pg: SQLSTATE on `code`. Prefer `errno`, fall back to\n // `code`, and accept only a value that is actually shaped like a SQLSTATE.\n const fromErrno = asSqlState(candidate.errno);\n if (fromErrno !== undefined) {\n return fromErrno;\n }\n const fromCode = asSqlState(candidate.code);\n if (fromCode !== undefined) {\n return fromCode;\n }\n\n // Not on this error — descend into a wrapped cause (Error.cause / a driver's nested original error).\n if (candidate.cause === current) {\n return undefined;\n }\n current = candidate.cause;\n }\n\n return undefined;\n}\n\n/** A value is a SQLSTATE only if it is a string of exactly five `[0-9A-Z]` characters. */\nfunction asSqlState(value: unknown): string | undefined {\n return typeof value === \"string\" && /^[0-9A-Z]{5}$/u.test(value) ? value : undefined;\n}\n",
|
|
11
|
-
"import { getTableName, sql } from \"drizzle-orm\";\nimport { getTableConfig, type AnyPgTable, type PgAsyncDatabase, type PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport {\n CLOCK_US_CALL_SQL_TEXT,\n escapeSqlLiteral as toSqlLiteral,\n getProjectedColumns,\n hashString,\n quoteIdentifier as quoteIdent,\n resolveServerVersionColumnName,\n type BatchMutationRequest,\n type RegistryRelations,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { TransactionClient } from \"./types\";\n\nfunction qualifyIdent(schemaName: string | undefined, name: string): string {\n if (!schemaName) {\n return quoteIdent(name);\n }\n\n return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;\n}\n\nfunction toSqlTextOrNull(value: string): string {\n return value.length > 0 ? `'${toSqlLiteral(value)}'` : \"NULL\";\n}\n\ninterface ResolvedManagedField {\n propertyKey: string;\n columnName: string;\n strategy: \"nowMicroseconds\" | \"authClaim\";\n claimPath?: string[];\n cast?: string;\n columnSqlType: string;\n}\n\n// The single claim-stamping strategy (ADR-0026): `authClaim` reads the verified request claim at its JSON\n// path — `auth.uid()` is just `{ claimPath: [\"sub\"], cast: \"uuid\" }`, so there is one mechanism. The path\n// segments are validated plain identifiers at registry build, so the `'{a,b}'` text-array literal is\n// injection-safe; `current_setting('request.jwt.claims', …)` is set by this function before the apply DML\n// (it is what RLS reads), NULLIF guards an unset GUC (an absent claim stamps NULL, never errors), and the\n// cast defaults to the target column's own SQL type so a `uuid` column needs no explicit cast.\nfunction buildManagedFieldExpression(field: ResolvedManagedField): string {\n if (field.strategy === \"authClaim\") {\n const path = (field.claimPath ?? []).join(\",\");\n const castType = field.cast ?? field.columnSqlType;\n return `(NULLIF(current_setting('request.jwt.claims', true), '')::jsonb #>> '{${path}}')::${castType}`;\n }\n\n // Call the canonical microsecond-clock DB function, never inline the expression. The rendered\n // artifact therefore DEPENDS on the utilities function (public.pgxsinkit_clock_us()): the utilities\n // migration (renderPgxsinkitUtilitiesMigration) must precede this artifact in any consumer's chain.\n // The ADR-0030 fingerprint recomputes from this rendered text, so a change to the call form is\n // coordinated through the normal regenerate-and-commit flow.\n return CLOCK_US_CALL_SQL_TEXT;\n}\n\nfunction getManagedFieldsForOperation(entry: SyncTableEntry, operation: \"create\" | \"update\"): ResolvedManagedField[] {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? []).flatMap((field) => {\n if (!field.applyOn.includes(operation)) {\n return [];\n }\n\n const columnName = columnNameMap.get(field.column);\n if (!columnName) {\n return [];\n }\n\n const column =\n (columns as Record<string, { getSQLType: () => string } | undefined>)[field.column] ??\n Object.values(columns).find((candidate) => candidate.name === field.column);\n\n return [\n {\n propertyKey: field.column,\n columnName,\n strategy: field.strategy,\n ...(field.claimPath ? { claimPath: field.claimPath } : {}),\n ...(field.cast ? { cast: field.cast } : {}),\n columnSqlType: column?.getSQLType() ?? \"text\",\n },\n ];\n });\n}\n\nfunction buildTableBranch(entry: SyncTableEntry): string {\n const tableName = getTableName(entry.table as AnyPgTable);\n const { schema } = getTableConfig(entry.table as AnyPgTable);\n const qualifiedTableName = qualifyIdent(schema, tableName);\n const columns = getColumns(entry.table as AnyPgTable);\n const projectedColumns = getProjectedColumns(entry);\n // The canonical Entity identity is the full server primary-key tuple, by column name with\n // typed values (ADR-0012): the applier matches update/delete over EVERY pk column. Keying on\n // only the first column (the old `columns[0]`) matched too many rows on a composite-PK table.\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const columnObject = Object.values(columns).find((column) => column.name === columnName);\n if (!columnObject) {\n // Hard error, not a silent `text` fallback: an unmatched PK column means the primaryKey spec\n // has drifted from the table (e.g. a rename) — a generated applier keyed on a mistyped tuple\n // would mis-match rows at apply time.\n throw new Error(\n `plpgsql apply generator: primary key column ${columnName} not found on table ${tableName}; ` +\n `the entry's primaryKey spec has drifted from its Drizzle table`,\n );\n }\n return { name: columnName, type: columnObject.getSQLType() };\n });\n const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));\n\n const createManagedFields = getManagedFieldsForOperation(entry, \"create\");\n const updateManagedFields = getManagedFieldsForOperation(entry, \"update\");\n const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));\n const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));\n\n const allColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !createManagedFieldNames.has(column.name))\n .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)\n .join(\",\\n \");\n\n const nonPrimaryKeyColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !primaryKeyColumnNames.has(column.name) && !updateManagedFieldNames.has(column.name))\n .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)\n .join(\",\\n \");\n\n const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(\", \");\n const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field)).join(\", \");\n // ADR-0010: the Server version (the nowMicroseconds-on-update managed field) must be strictly\n // monotonic per row, so its on-update stamp is floored at the previous value + 1 — it can never\n // repeat or step backwards under wall-clock (NTP) skew, which would let a stale echo clear an\n // optimistic write early. The bare column on the RHS of an UPDATE SET is the pre-update value.\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n const updateManagedAssignmentsSql = updateManagedFields\n .map((field) => {\n const expression =\n field.strategy === \"nowMicroseconds\" && field.columnName === serverVersionColumn\n ? `GREATEST(${buildManagedFieldExpression(field)}, ${quoteIdent(field.columnName)} + 1)`\n : buildManagedFieldExpression(field);\n return `${quoteIdent(field.columnName)} = ${expression}`;\n })\n .join(\", \");\n\n // Set-based apply (ADR-0014 Phase 4): one statement per (table, kind, payload column-set) group,\n // over the group's rows materialised by jsonb_to_recordset. The PK match spans the full tuple\n // (ADR-0012): DELETE matches the recordset's typed PK columns directly; UPDATE matches each row's\n // entity key carried as `x.k` jsonb. Safe from the same-PK `UPDATE … FROM` join hazard because the\n // Per-entity flush serialization invariant leaves at most one mutation per entity in a batch.\n const pkRecordDef = primaryKeyColumns.map((pk) => `${quoteIdent(pk.name)} ${pk.type}`).join(\", \");\n const pkDeleteJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = x.${quoteIdent(pk.name)}`)\n .join(\" AND \");\n const pkUpdateJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = (x.k->>'${toSqlLiteral(pk.name)}')::${pk.type}`)\n .join(\" AND \");\n\n // Templates the runtime format() fills with the per-group column list. Single quotes are doubled\n // because these are embedded as PL/pgSQL string literals.\n const insertTemplate =\n `INSERT INTO ${qualifiedTableName} (%s) SELECT %s FROM jsonb_to_recordset($1) AS x(p jsonb)`.replace(/'/g, \"''\");\n const updateTemplate =\n `UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb) WHERE ${pkUpdateJoin}`.replace(\n /'/g,\n \"''\",\n );\n const deleteSql =\n `DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}) WHERE ${pkDeleteJoin}`.replace(\n /'/g,\n \"''\",\n );\n\n // The create/update column fragments come from the group signature (∩ writable columns) plus the\n // static managed fields. An empty intersection ⇒ NULL fragment ⇒ a managed-only statement (the\n // Server version still bumps on a PK-only update, exactly as the per-mutation path did).\n const createColumnSelect = allColumnPairs.length\n ? `SELECT\n string_agg(quote_ident(col_name), ', ' ORDER BY col_name),\n string_agg(format('(x.p->>%L)::%s', col_name, col_type), ', ' ORDER BY col_name)\n INTO v_cols, v_vals\n FROM (VALUES\n ${allColumnPairs}\n ) AS col_types(col_name, col_type)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_cols := NULL; v_vals := NULL;`;\n\n const updateSetSelect = nonPrimaryKeyColumnPairs.length\n ? `SELECT string_agg(format('%I = (x.p->>%L)::%s', col_name, col_name, col_type), ', ' ORDER BY col_name)\n INTO v_set\n FROM (VALUES\n ${nonPrimaryKeyColumnPairs}\n ) AS col_types(col_name, col_type)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_set := NULL;`;\n\n const createBranch = `\n ${createColumnSelect}\n\n dml_sql := format(\n '${insertTemplate}',\n concat_ws(', ', nullif(v_cols, ''), ${toSqlTextOrNull(createManagedColumnsSql)}),\n concat_ws(', ', nullif(v_vals, ''), ${toSqlTextOrNull(createManagedValuesSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n // ADR-0015: a `reject-if-stale` table compares each targeted row's current Server version to the\n // mutation's Base server version (`x.b`). `current > base` ⇒ stale (an external write interleaved):\n // the row is NOT applied, and the conflict (mutation id + the row's current Server version) is\n // collected for the handler to turn into a `conflicted` ack. `last-write-wins` keeps today's apply\n // (now a named choice). The policy is known here at DDL-generation time, so each table emits the SQL\n // its policy needs; a create has no base (its conflict is a PK collision), so it is unchanged.\n // #6: an UPDATE whose target row is MISSING (deleted by another writer after authoring) is also a\n // conflict ('target row no longer exists', `currentServerVersion` NULL) — otherwise the edit would\n // silently no-op and ack as success. A DELETE of a missing row stays idempotent success (the user\n // wanted it gone), so the delete branch keeps its inner join and does not report missing targets.\n const serverVersionRef = serverVersionColumn ? quoteIdent(serverVersionColumn) : null;\n const rejectIfStale = entry.conflictPolicy === \"reject-if-stale\" && serverVersionRef != null;\n // For the missing-target conflict (ADR-0015 #6): a LEFT JOIN whose right side is absent leaves the\n // first PK column NULL. The Server version is NOT NULL on any existing writable row, so a NULL\n // `currentServerVersion` in a returned conflict means exactly \"the target row no longer exists\".\n const firstPkRef = quoteIdent(primaryKeyColumns[0]!.name);\n\n // The conflict-collect SELECT and the staleness guard need the base + mutation id alongside each\n // row, so reject-if-stale carries them in the recordset (`b bigint, m text`). The mutation id is\n // `text` (not `uuid`): a derived child envelope's id is a composite non-UUID string, and a `m uuid`\n // recordset column would raise 22P02 the moment such a write is stale.\n const conflictObjectSql = (alias: string) =>\n `jsonb_build_object('mutationId', ${alias}.m, 'tableName', '${toSqlLiteral(tableName)}', 'currentServerVersion', t.${serverVersionRef})`;\n\n const updateBranch = rejectIfStale\n ? `\n ${updateSetSelect}\n\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) LEFT JOIN ${qualifiedTableName} AS t ON ${pkUpdateJoin} WHERE t.${firstPkRef} IS NULL OR (x.b IS NOT NULL AND t.${serverVersionRef} > x.b)`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n dml_sql := format(\n '${`UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) WHERE ${pkUpdateJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n ${updateSetSelect}\n\n dml_sql := format(\n '${updateTemplate}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n const deleteBranch = rejectIfStale\n ? `\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) JOIN ${qualifiedTableName} AS t ON ${pkDeleteJoin} WHERE x.b IS NOT NULL AND t.${serverVersionRef} > x.b`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n EXECUTE '${`DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) WHERE ${pkDeleteJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}' USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n EXECUTE '${deleteSql}' USING (\n SELECT COALESCE(jsonb_agg(elem->'entityKey'), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n return `\n ELSIF v_table = '${toSqlLiteral(tableName)}' THEN\n IF v_kind = 'create' THEN\n ${createBranch}\n ELSIF v_kind = 'update' THEN\n ${updateBranch}\n ELSIF v_kind = 'delete' THEN\n ${deleteBranch}\n ELSE\n RAISE EXCEPTION 'Unsupported mutation kind \"%\" for table \"%\"', v_kind, v_table;\n END IF;\n `.trim();\n}\n\nconst APPLY_FUNCTION_NAME = \"pgxsinkit_apply_mutations\";\n// ADR-0030: the trailing `text` is `p_expected_fingerprint` — the running server passes the fingerprint\n// it expects for its registry + codegen, and the function verifies itself against its stamped comment\n// before touching any table.\nconst APPLY_FUNCTION_ARG_TYPES = \"jsonb, text, boolean, boolean, jsonb, text\";\n// ADR-0018: the prefix namespaces the strict fingerprint format. Any absent or different prefix is\n// an identity mismatch and the apply function refuses the write.\nconst APPLY_FINGERPRINT_PREFIX = \"pgxsinkit:fp1:\";\n\nfunction buildApplyFunctionBody(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n const tableBranches = Object.values(registry)\n // A read projection (ADR-0027) owns no writable table — its `table` IS the owner's, so the owner's\n // branch already handles that physical table. Emitting a branch for the projection too would\n // DUPLICATE the owner's table branch (same table name). Read projections are readonly and never\n // reach the write path, so exclude them from the apply function entirely.\n .filter((entry) => !(entry as SyncTableEntry).readProjection)\n .map((entry) => buildTableBranch(entry as SyncTableEntry))\n .join(\"\\n\");\n const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);\n\n return `\n-- Install idempotently by dropping the current signature first. PostgreSQL cannot change a function's\n-- return type through CREATE OR REPLACE, while a generated artifact must install its complete definition.\n--\n-- TWO-TIER MUTATION-ID INVARIANT. \\`mutation_id\\` is TEXT here (RETURNS TABLE + operations_log), not\n-- uuid, so this apply function can serve a DIRECT server-side caller that derives child envelopes with\n-- composite non-UUID ids (\\`\\${parentId}:<tag>:<n>\\`). That is the ONLY non-UUID path. pgxsinkit's public\n-- surface — the HTTP route's request/ack schemas and the client's \\`mutation_id UUID\\` journal — stays\n-- UUID-only (see packages/contracts/src/mutation.ts): the route validates every request id as a UUID and\n-- builds every ack from that request id, never from the TEXT conflict rows this returns. A non-UUID id\n-- therefore never crosses into the UUID-typed surface.\n--\nDROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES});\n\nCREATE OR REPLACE FUNCTION ${functionName}(\n p_batch jsonb,\n p_request_path text,\n p_log_enabled boolean,\n p_rls_enabled boolean,\n p_user_claims jsonb,\n p_expected_fingerprint text\n) RETURNS TABLE(mutation_id text, table_name text, current_server_version bigint) LANGUAGE plpgsql AS $$\nDECLARE\n dml_sql text;\n v_table text;\n v_kind text;\n v_sig text;\n v_rows jsonb;\n v_cols text;\n v_vals text;\n v_set text;\n -- ADR-0015: stale-write conflicts collected across the batch (mutationId + the row's current\n -- Server version), returned to the handler which turns them into 'conflicted' acks.\n v_conflicts jsonb := '[]'::jsonb;\n v_group_conflicts jsonb;\n -- ADR-0030: the fingerprint this installed function was stamped with (its own ADR-0018 comment),\n -- read back once for the self-verification gate below.\n _installed_fingerprint text;\n _claims jsonb;\n _target_role text;\n _previous_role text;\n _previous_claims text;\n _previous_claim_sub text;\nBEGIN\n -- ADR-0030: the apply function verifies ITSELF against its ADR-0018 fingerprint comment before it\n -- touches any table. p_expected_fingerprint is what the running server expects for its registry +\n -- codegen; obj_description(...) is the fingerprint this installed function was stamped with, atomically,\n -- by the same migration. A mismatch — INCLUDING an absent comment (an unstamped hand-installed\n -- function ⇒ NULL, refused per ADR-0030) — means the installed function is stale relative to the caller,\n -- so raise SQLSTATE 'PXS01' and apply nothing. The check IS the call (no read-then-call TOCTOU) and\n -- costs no extra round trip (the argument rides the existing invocation; the comparison is one text\n -- equality). The signature literal is embedded, never the fingerprint hash itself — baking the hash\n -- into the body would be circular with the hash-of-body the fingerprint is.\n _installed_fingerprint := obj_description('${functionName}(${APPLY_FUNCTION_ARG_TYPES})'::regprocedure, 'pg_proc');\n IF p_expected_fingerprint IS DISTINCT FROM _installed_fingerprint THEN\n RAISE EXCEPTION 'pgxsinkit_apply_mutations is stale: the installed apply-function fingerprint (%) does not match the fingerprint this server expects (%). Regenerate the sync-function migration (pgxsinkit-generate) and apply it before serving writes.', COALESCE(_installed_fingerprint, '(none)'), p_expected_fingerprint\n USING ERRCODE = 'PXS01';\n END IF;\n\n IF p_rls_enabled THEN\n -- Capture the caller's role/claims before switching into the RLS actor context, so the\n -- batch does not leak that context into the rest of the caller's transaction. The HTTP\n -- route RESET ROLEs after calling this function, but in-transaction callers cannot —\n -- restoring here leaves every caller exactly as it was found.\n _previous_role := current_setting('role', true);\n _previous_claims := current_setting('request.jwt.claims', true);\n _previous_claim_sub := current_setting('request.jwt.claim.sub', true);\n _claims := COALESCE(p_user_claims, '{}'::jsonb);\n _target_role := COALESCE(NULLIF(_claims ->> 'role', ''), 'authenticated');\n BEGIN\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = _target_role) THEN\n PERFORM set_config('role', _target_role, true);\n ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN\n PERFORM set_config('role', 'authenticated', true);\n END IF;\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', _claims::text, true);\n IF _claims ? 'sub' THEN\n PERFORM set_config('request.jwt.claim.sub', _claims ->> 'sub', true);\n END IF;\n END IF;\n\n IF jsonb_typeof(p_batch) <> 'object' THEN\n RAISE EXCEPTION 'Batch payload must be a JSON object';\n END IF;\n\n IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN\n RAISE EXCEPTION 'Batch payload mutations must be a JSON array';\n END IF;\n\n -- Group the batch by (table, kind, payload column-set) and apply each group with one statement\n -- (ADR-0014 Phase 4). mutationSeq is table-local, so it cannot order groups across tables: parent\n -- and child journals can both start at 1. WITH ORDINALITY preserves the submitted JSON array order\n -- across tables (FK-safe; the batch transaction also runs SET CONSTRAINTS ALL DEFERRED).\n FOR v_table, v_kind, v_sig, v_rows IN\n SELECT\n grouped.table_name,\n grouped.kind,\n grouped.sig,\n jsonb_agg(grouped.mutation ORDER BY grouped.batch_position)\n FROM (\n SELECT\n entries.m->>'tableName' AS table_name,\n entries.m->>'kind' AS kind,\n COALESCE((\n SELECT string_agg(payload_key, ',' ORDER BY payload_key)\n FROM jsonb_object_keys(COALESCE(entries.m->'payload', '{}'::jsonb)) AS payload_key\n ), '') AS sig,\n entries.m AS mutation,\n entries.batch_position\n FROM jsonb_array_elements(p_batch->'mutations') WITH ORDINALITY AS entries(m, batch_position)\n ) AS grouped\n GROUP BY grouped.table_name, grouped.kind, grouped.sig\n ORDER BY MIN(grouped.batch_position)\n LOOP\n dml_sql := NULL;\n v_cols := NULL;\n v_vals := NULL;\n v_set := NULL;\n\n IF FALSE THEN\n NULL;\n ${tableBranches}\n ELSE\n RAISE EXCEPTION 'Unknown table \"%\" in batch mutation', v_table;\n END IF;\n END LOOP;\n\n IF p_log_enabled THEN\n -- One batched log insert (the whole batch is a single transaction, so a per-mutation loop\n -- bought nothing): a runtime apply failure above rolls the whole transaction back, log rows\n -- included, preserving the existing whole-batch-failure semantics.\n INSERT INTO operations_log (\n table_name,\n operation_kind,\n entity_key_json,\n payload_json,\n status,\n http_status,\n mutation_id,\n mutation_seq,\n client_timestamp_us,\n request_path,\n server_timestamp_us\n )\n SELECT\n m->>'tableName',\n m->>'kind',\n COALESCE(m->'entityKey', '{}'::jsonb),\n COALESCE(m->'payload', '{}'::jsonb),\n 'succeeded',\n 200,\n -- mutation_id is text: a derived child envelope carries a composite non-UUID id\n -- (parent-id + tag + index), so no ::uuid cast (it would raise 22P02 on such an id).\n m->>'mutationId',\n (m->>'mutationSeq')::integer,\n NULLIF(m->>'clientTimestampUs', '')::bigint,\n p_request_path,\n -- The canonical microsecond clock (utilities migration); never the inline expression.\n ${CLOCK_US_CALL_SQL_TEXT}\n FROM jsonb_array_elements(p_batch->'mutations') AS m;\n END IF;\n\n IF p_rls_enabled THEN\n -- Restore the caller's prior role/claims captured above, so the RLS context applied for\n -- the batch does not persist into subsequent statements of the caller's transaction.\n BEGIN\n PERFORM set_config('role', COALESCE(NULLIF(_previous_role, ''), 'none'), true);\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', COALESCE(_previous_claims, ''), true);\n PERFORM set_config('request.jwt.claim.sub', COALESCE(_previous_claim_sub, ''), true);\n END IF;\n\n -- ADR-0015: return the collected stale-write conflicts. Empty under last-write-wins (or when no\n -- write was stale), so the handler simply acks everything as today.\n RETURN QUERY\n SELECT\n -- mutation_id is text (see RETURNS TABLE): a stale derived child envelope's id is a composite\n -- non-UUID string, so return it verbatim — a ::uuid cast here would raise 22P02 and abort the batch.\n c->>'mutationId',\n c->>'tableName',\n (c->>'currentServerVersion')::bigint\n FROM jsonb_array_elements(v_conflicts) AS c;\nEND;\n$$;\n`.trim();\n}\n\n/**\n * The fingerprint the installed apply function should carry for this registry + applier codegen\n * (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape\n * change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the\n * two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /\n * customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).\n */\nexport function expectedApplyFingerprint(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));\n}\n\nexport function buildPlpgsqlBatchFunctionDdl(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n const body = buildApplyFunctionBody(registry, options);\n const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);\n const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);\n\n // ADR-0018: stamp the function with the fingerprint of this exact DDL body. Stored as a COMMENT\n // because it is function-scoped, replaced atomically with the function, and read back in one line\n // via obj_description — so the server (startup) and CI (pre-deploy) can both detect a function\n // that is stale relative to the registry + codegen it is meant to serve.\n return `${body}\\n\\nCOMMENT ON FUNCTION ${functionName}(${APPLY_FUNCTION_ARG_TYPES}) IS '${fingerprint}';`;\n}\n\nexport async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): Promise<void> {\n const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);\n await db.execute(sql.raw(ddl));\n}\n\ntype AuthHelperPresenceRow = {\n authUid: string | null;\n};\n\nexport async function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n): Promise<void> {\n const result = await db.execute<AuthHelperPresenceRow>(sql`\n SELECT\n to_regprocedure('auth.uid()')::text AS \"authUid\"\n `);\n\n const row = Array.from(result as Iterable<unknown>, (entry) => entry as AuthHelperPresenceRow)[0];\n const missingHelpers = [row?.authUid ? null : \"auth.uid()\"].filter((value): value is string => value !== null);\n\n if (missingHelpers.length > 0) {\n throw new Error(\n `The write path requires Supabase auth helpers. Missing: ${missingHelpers.join(\", \")}. ` +\n \"Ensure auth.uid() is available (standard on Supabase-managed databases).\",\n );\n }\n}\n\n/**\n * A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the\n * Base server version the row has since advanced past — `currentServerVersion` is the row's current\n * version) or an UPDATE whose **target row is missing** (deleted by another writer —\n * `currentServerVersion` is `null`, the #6 discriminator). The handler surfaces it on the\n * `conflicted` ack.\n */\nexport interface MutationConflict {\n mutationId: string;\n tableName: string;\n currentServerVersion: string | null;\n}\n\ninterface MutationConflictRow {\n mutationId: string | null;\n tableName: string | null;\n currentServerVersion: string | null;\n}\n\nexport async function executePlpgsqlBatch(\n tx: TransactionClient,\n batch: BatchMutationRequest,\n requestPath: string,\n logEnabled: boolean,\n rlsEnabled: boolean,\n userClaims: Record<string, unknown>,\n // ADR-0030: the fingerprint the running server expects for its registry + codegen\n // (`expectedApplyFingerprint(registry)`, computed once per server instance). The installed apply\n // function compares it against its own stamped comment and raises SQLSTATE 'PXS01' on a mismatch —\n // in-body, atomic with the call, before it touches any table.\n expectedFingerprint: string,\n options: {\n functionSchema?: string;\n } = {},\n): Promise<MutationConflict[]> {\n const normalizedClaims = userClaims ?? {};\n // Typed identifier interpolation (never `sql.raw` of a hand-quoted name); the OUT-column aliases\n // are the generated function's fixed names.\n const functionRef = options.functionSchema\n ? sql`${sql.identifier(options.functionSchema)}.${sql.identifier(\"pgxsinkit_apply_mutations\")}`\n : sql`${sql.identifier(\"pgxsinkit_apply_mutations\")}`;\n\n // The applier RETURNS the stale-write conflicts (ADR-0015). Read them from the function's result\n // set; an empty set (the last-write-wins case, or nothing stale) means every mutation applied.\n const result = await tx.execute(\n 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})`,\n );\n\n const rows = Array.from(result as Iterable<unknown>, (row) => row as MutationConflictRow);\n return rows.flatMap((row) =>\n row.mutationId != null\n ? [\n {\n mutationId: row.mutationId,\n tableName: row.tableName ?? \"\",\n currentServerVersion: row.currentServerVersion,\n } satisfies MutationConflict,\n ]\n : [],\n );\n}\n",
|
|
16
|
+
"import { getTableName, sql } from \"drizzle-orm\";\nimport { getTableConfig, type AnyPgTable, type PgAsyncDatabase, type PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport {\n buildRoleGuardedStatement,\n CLOCK_US_CALL_SQL_TEXT,\n escapeSqlLiteral as toSqlLiteral,\n getProjectedColumns,\n hashString,\n isManagedFieldGuarded,\n quoteIdentifier as quoteIdent,\n resolveServerVersionColumnName,\n type BatchMutationRequest,\n type ManagedFieldApplyOn,\n type RegistryRelations,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { TransactionClient } from \"./types\";\n\nfunction qualifyIdent(schemaName: string | undefined, name: string): string {\n if (!schemaName) {\n return quoteIdent(name);\n }\n\n return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;\n}\n\nfunction toSqlTextOrNull(value: string): string {\n return value.length > 0 ? `'${toSqlLiteral(value)}'` : \"NULL\";\n}\n\n/**\n * The array dimensionality Drizzle records for a column (0 = scalar). It is carried SEPARATELY from\n * `getSQLType()`, which returns the ELEMENT type for an array column (`uuid` for a `uuid[]`) — reading\n * only the type string is what silently emitted a scalar cast for an array column and killed every\n * non-null array write with 22P02.\n */\nfunction columnDimensions(column: { dimensions?: number }): number {\n return column.dimensions ?? 0;\n}\n\n/**\n * The SQL expression that reads one writable column out of a mutation's payload (`x.p`), by column\n * name and Drizzle type. It is embedded in the branch's `(col_name, col_value)` candidate list and\n * substituted verbatim into the INSERT/UPDATE `format()` template at runtime.\n *\n * Scalars keep the long-standing `(x.p->>'col')::type` form. A one-dimensional array column expands\n * the JSON array element-wise and applies the terminal `::<element>[]` cast, which IS the type check\n * (no element-type allowlist: an element the target type cannot accept raises, exactly as a scalar\n * cast does). The three payload shapes match the scalar semantics exactly:\n *\n * - **absent key** — never reaches here (the branch intersects the candidate list with the group's\n * payload signature, so an unsent column is not in the statement at all);\n * - **JSON null** — `jsonb_typeof` is `'null'`, the CASE has no ELSE ⇒ SQL NULL, mirroring\n * `(x.p->>'col')::type` on a JSON null;\n * - **`[]`** — an empty typed array, NOT NULL (an empty list is a value the client meant to write).\n *\n * Element order is pinned with `WITH ORDINALITY … ORDER BY`, so the stored array order is the\n * client's array order by construction rather than by set-returning-function evaluation order.\n * A JSON null ELEMENT becomes a SQL NULL element (`jsonb_array_elements_text` semantics) — except for\n * the JSON element types, see below.\n *\n * The one branch inside the array branch is the ELEMENT type: `json`/`jsonb` elements expand with\n * `jsonb_array_elements` (the JSON-valued expansion), never `jsonb_array_elements_text`. Text expansion\n * of a JSON element STRIPS its JSON quoting, which is silent type corruption for a `jsonb[]`: the element\n * `\"123\"` (a JSON string) re-parses as the JSON NUMBER `123`, and `\"hi\"` fails the cast outright with\n * `invalid input syntax for type json`. `jsonb_array_elements` preserves each element VERBATIM, so a JSON\n * null element stays a JSON null value (`jsonb_typeof(e) = 'null'`, not SQL NULL) — the faithful reading\n * for a JSON-typed element, and what round-trips back to the client unchanged. The column-level shapes\n * (absent key / JSON null / `[]`) are identical to the text branch.\n */\nfunction buildPayloadValueExpression(\n tableName: string,\n column: { name: string; getSQLType: () => string; dimensions?: number },\n): string {\n const columnLiteral = `'${toSqlLiteral(column.name)}'`;\n const dimensions = columnDimensions(column);\n const sqlType = column.getSQLType();\n\n if (dimensions === 0) {\n return `(x.p->>${columnLiteral})::${sqlType}`;\n }\n\n if (dimensions > 1) {\n // Loud at GENERATE time, never a silently wrong cast: a multi-dimensional array cannot be\n // reconstructed from a flat element expansion, and Postgres additionally requires every\n // sub-array to be the same length — a validity rule this renderer cannot express.\n throw new Error(\n `plpgsql apply generator: column ${tableName}.${column.name} is a ${dimensions}-dimensional array; ` +\n `multi-dimensional arrays are not supported by the apply function (use a single-dimension array, ` +\n `or a jsonb column)`,\n );\n }\n\n // A `json`/`jsonb` ELEMENT type must keep its JSON value (quoting included); every other element type\n // is reconstructed from the element's TEXT rendering, which is what the terminal `::<type>[]` cast reads.\n const elementExpansion = isJsonElementType(sqlType) ? \"jsonb_array_elements\" : \"jsonb_array_elements_text\";\n\n return (\n `CASE WHEN jsonb_typeof(x.p->${columnLiteral}) = 'array' THEN ` +\n `ARRAY(SELECT e FROM ${elementExpansion}(x.p->${columnLiteral}) WITH ORDINALITY AS a(e, ord) ORDER BY ord)` +\n `::${sqlType}[] END`\n );\n}\n\n/** `json` / `jsonb` — the element types whose VALUE (not text rendering) must survive the expansion. */\nfunction isJsonElementType(sqlType: string): boolean {\n const normalized = sqlType.trim().toLowerCase();\n return normalized === \"json\" || normalized === \"jsonb\";\n}\n\n/** One `(column name, payload value expression)` row of a branch's runtime candidate list. */\nfunction toColumnCandidateRow(tableName: string, column: { name: string; getSQLType: () => string }): string {\n return `('${toSqlLiteral(column.name)}', '${toSqlLiteral(buildPayloadValueExpression(tableName, column))}')`;\n}\n\ninterface ResolvedManagedField {\n propertyKey: string;\n columnName: string;\n applyOn: readonly ManagedFieldApplyOn[];\n strategy: \"nowMicroseconds\" | \"authClaim\";\n claimPath?: string[];\n cast?: string;\n columnSqlType: string;\n}\n\n// The single claim-stamping strategy (ADR-0026): `authClaim` reads the verified request claim at its JSON\n// path — `auth.uid()` is just `{ claimPath: [\"sub\"], cast: \"uuid\" }`, so there is one mechanism. The path\n// segments are validated plain identifiers at registry build, so the `'{a,b}'` text-array literal is\n// injection-safe; `current_setting('request.jwt.claims', …)` is set by this function before the apply DML\n// (it is what RLS reads), NULLIF guards an unset GUC (an absent claim stamps NULL, never errors), and the\n// cast defaults to the target column's own SQL type so a `uuid` column needs no explicit cast.\nfunction buildManagedFieldExpression(field: ResolvedManagedField): string {\n if (field.strategy === \"authClaim\") {\n const path = (field.claimPath ?? []).join(\",\");\n const castType = field.cast ?? field.columnSqlType;\n return `(NULLIF(current_setting('request.jwt.claims', true), '')::jsonb #>> '{${path}}')::${castType}`;\n }\n\n // Call the canonical microsecond-clock DB function, never inline the expression. The rendered\n // artifact therefore DEPENDS on the utilities function (public.pgxsinkit_clock_us()): the utilities\n // migration (renderPgxsinkitUtilitiesMigration) must precede this artifact in any consumer's chain.\n // The ADR-0030 fingerprint recomputes from this rendered text, so a change to the call form is\n // coordinated through the normal regenerate-and-commit flow.\n return CLOCK_US_CALL_SQL_TEXT;\n}\n\n// Every managed field of the entry, resolved to its SQL column name and type. The two consumers slice it\n// differently and the distinction is load-bearing: STAMPING is operation-scoped (`applyOn.includes(op)`)\n// and decides what the applier writes, while GUARDING (contracts' `isManagedFieldGuarded`) decides which\n// columns a client payload may never move, and so which are excluded from the candidate lists below.\nfunction resolveManagedFields(entry: SyncTableEntry): ResolvedManagedField[] {\n const tableName = getTableName(entry.table as AnyPgTable);\n const columns = getColumns(entry.table as AnyPgTable);\n const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? []).flatMap((field) => {\n const columnName = columnNameMap.get(field.column);\n if (!columnName) {\n return [];\n }\n\n const column =\n (columns as Record<string, { getSQLType: () => string; dimensions?: number } | undefined>)[field.column] ??\n Object.values(columns).find((candidate) => candidate.name === field.column);\n\n if (column && columnDimensions(column) > 0) {\n // Both stamping strategies produce a SCALAR (a microsecond clock read, or one claim at a JSON\n // path), so an array-typed managed column could only ever be assigned a scalar — a type error at\n // every write. Refuse at generate time instead.\n throw new Error(\n `plpgsql apply generator: managed field ${tableName}.${columnName} is an array column; ` +\n `managed fields stamp a single scalar value and are not supported on array columns`,\n );\n }\n\n return [\n {\n propertyKey: field.column,\n columnName,\n applyOn: field.applyOn,\n strategy: field.strategy,\n ...(field.claimPath ? { claimPath: field.claimPath } : {}),\n ...(field.cast ? { cast: field.cast } : {}),\n columnSqlType: column?.getSQLType() ?? \"text\",\n },\n ];\n });\n}\n\nfunction buildTableBranch(entry: SyncTableEntry): string {\n const tableName = getTableName(entry.table as AnyPgTable);\n const { schema } = getTableConfig(entry.table as AnyPgTable);\n const qualifiedTableName = qualifyIdent(schema, tableName);\n const columns = getColumns(entry.table as AnyPgTable);\n const projectedColumns = getProjectedColumns(entry);\n // The canonical Entity identity is the full server primary-key tuple, by column name with\n // typed values (ADR-0012): the applier matches update/delete over EVERY pk column. Keying on\n // only the first column (the old `columns[0]`) matched too many rows on a composite-PK table.\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const columnObject = Object.values(columns).find((column) => column.name === columnName);\n if (!columnObject) {\n // Hard error, not a silent `text` fallback: an unmatched PK column means the primaryKey spec\n // has drifted from the table (e.g. a rename) — a generated applier keyed on a mistyped tuple\n // would mis-match rows at apply time.\n throw new Error(\n `plpgsql apply generator: primary key column ${columnName} not found on table ${tableName}; ` +\n `the entry's primaryKey spec has drifted from its Drizzle table`,\n );\n }\n if (columnDimensions(columnObject) > 0) {\n // The canonical identity is carried as typed recordset columns and as `(x.k->>'col')::type`\n // join predicates — both scalar forms. An array PK would need array equality semantics the\n // entity-key wire shape (a JSON object of scalar strings) cannot express, so refuse it here\n // rather than emit a cast that would raise 22P02 on the first update/delete.\n throw new Error(\n `plpgsql apply generator: primary key column ${tableName}.${columnName} is an array column; ` +\n `array columns are not supported as primary keys by the apply function`,\n );\n }\n return { name: columnName, type: columnObject.getSQLType() };\n });\n const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));\n\n const managedFields = resolveManagedFields(entry);\n // STAMPING sets — operation-scoped: what the applier itself writes (the INSERT column/value fragments\n // and the UPDATE managed-assignment fragment below).\n const createManagedFields = managedFields.filter((field) => field.applyOn.includes(\"create\"));\n const updateManagedFields = managedFields.filter((field) => field.applyOn.includes(\"update\"));\n // EXCLUSION sets — the guard rule, from contracts' single definition: a column that is server-owned for\n // the operation is not a candidate a client payload key can move. On create that is the create-managed\n // columns (the applier stamps them itself); on update it is EVERY managed column, so a create-only\n // field (`applyOn: [\"create\"]`, e.g. an `authClaim` owner) is inert thereafter, and an update-managed\n // one is assigned by the static managed-assignment fragment instead.\n const createGuardedColumnNames = new Set(\n managedFields.filter((field) => isManagedFieldGuarded(field, \"create\")).map((field) => field.columnName),\n );\n const updateGuardedColumnNames = new Set(\n managedFields.filter((field) => isManagedFieldGuarded(field, \"update\")).map((field) => field.columnName),\n );\n\n // Each candidate row carries the column's NAME and its fully-rendered payload value EXPRESSION.\n // The expression is precomputed here (rather than `format()`-ed from a type at runtime) because it\n // is no longer uniform: an array column needs an element-wise expansion, not a `->>` cast.\n const allColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !createGuardedColumnNames.has(column.name))\n .map((column) => toColumnCandidateRow(tableName, column))\n .join(\",\\n \");\n\n const nonPrimaryKeyColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !primaryKeyColumnNames.has(column.name) && !updateGuardedColumnNames.has(column.name))\n .map((column) => toColumnCandidateRow(tableName, column))\n .join(\",\\n \");\n\n const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(\", \");\n const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field)).join(\", \");\n // ADR-0010: the Server version (the nowMicroseconds-on-update managed field) must be strictly\n // monotonic per row, so its on-update stamp is floored at the previous value + 1 — it can never\n // repeat or step backwards under wall-clock (NTP) skew, which would let a stale echo clear an\n // optimistic write early. The bare column on the RHS of an UPDATE SET is the pre-update value.\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n const updateManagedAssignmentsSql = updateManagedFields\n .map((field) => {\n const expression =\n field.strategy === \"nowMicroseconds\" && field.columnName === serverVersionColumn\n ? `GREATEST(${buildManagedFieldExpression(field)}, ${quoteIdent(field.columnName)} + 1)`\n : buildManagedFieldExpression(field);\n return `${quoteIdent(field.columnName)} = ${expression}`;\n })\n .join(\", \");\n\n // Set-based apply (ADR-0014 Phase 4): one statement per (table, kind, payload column-set) group,\n // over the group's rows materialised by jsonb_to_recordset. The PK match spans the full tuple\n // (ADR-0012): DELETE matches the recordset's typed PK columns directly; UPDATE matches each row's\n // entity key carried as `x.k` jsonb. Safe from the same-PK `UPDATE … FROM` join hazard because the\n // Per-entity flush serialization invariant leaves at most one mutation per entity in a batch.\n const pkRecordDef = primaryKeyColumns.map((pk) => `${quoteIdent(pk.name)} ${pk.type}`).join(\", \");\n const pkDeleteJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = x.${quoteIdent(pk.name)}`)\n .join(\" AND \");\n const pkUpdateJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = (x.k->>'${toSqlLiteral(pk.name)}')::${pk.type}`)\n .join(\" AND \");\n\n // Templates the runtime format() fills with the per-group column list. Single quotes are doubled\n // because these are embedded as PL/pgSQL string literals.\n const insertTemplate =\n `INSERT INTO ${qualifiedTableName} (%s) SELECT %s FROM jsonb_to_recordset($1) AS x(p jsonb)`.replace(/'/g, \"''\");\n const updateTemplate =\n `UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb) WHERE ${pkUpdateJoin}`.replace(\n /'/g,\n \"''\",\n );\n const deleteSql =\n `DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}) WHERE ${pkDeleteJoin}`.replace(\n /'/g,\n \"''\",\n );\n\n // The create/update column fragments come from the group signature (∩ writable columns) plus the\n // static managed fields. An empty intersection ⇒ NULL fragment ⇒ a managed-only statement (the\n // Server version still bumps on a PK-only update, exactly as the per-mutation path did).\n const createColumnSelect = allColumnPairs.length\n ? `SELECT\n string_agg(quote_ident(col_name), ', ' ORDER BY col_name),\n string_agg(col_value, ', ' ORDER BY col_name)\n INTO v_cols, v_vals\n FROM (VALUES\n ${allColumnPairs}\n ) AS col_types(col_name, col_value)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_cols := NULL; v_vals := NULL;`;\n\n const updateSetSelect = nonPrimaryKeyColumnPairs.length\n ? `SELECT string_agg(format('%I = %s', col_name, col_value), ', ' ORDER BY col_name)\n INTO v_set\n FROM (VALUES\n ${nonPrimaryKeyColumnPairs}\n ) AS col_types(col_name, col_value)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_set := NULL;`;\n\n const createBranch = `\n ${createColumnSelect}\n\n dml_sql := format(\n '${insertTemplate}',\n concat_ws(', ', nullif(v_cols, ''), ${toSqlTextOrNull(createManagedColumnsSql)}),\n concat_ws(', ', nullif(v_vals, ''), ${toSqlTextOrNull(createManagedValuesSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n // ADR-0015: a `reject-if-stale` table compares each targeted row's current Server version to the\n // mutation's Base server version (`x.b`). `current > base` ⇒ stale (an external write interleaved):\n // the row is NOT applied, and the conflict (mutation id + the row's current Server version) is\n // collected for the handler to turn into a `conflicted` ack. `last-write-wins` keeps today's apply\n // (now a named choice). The policy is known here at DDL-generation time, so each table emits the SQL\n // its policy needs; a create has no base (its conflict is a PK collision), so it is unchanged.\n // #6: an UPDATE whose target row is MISSING (deleted by another writer after authoring) is also a\n // conflict ('target row no longer exists', `currentServerVersion` NULL) — otherwise the edit would\n // silently no-op and ack as success. A DELETE of a missing row stays idempotent success (the user\n // wanted it gone), so the delete branch keeps its inner join and does not report missing targets.\n const serverVersionRef = serverVersionColumn ? quoteIdent(serverVersionColumn) : null;\n const rejectIfStale = entry.conflictPolicy === \"reject-if-stale\" && serverVersionRef != null;\n // For the missing-target conflict (ADR-0015 #6): a LEFT JOIN whose right side is absent leaves the\n // first PK column NULL. The Server version is NOT NULL on any existing writable row, so a NULL\n // `currentServerVersion` in a returned conflict means exactly \"the target row no longer exists\".\n const firstPkRef = quoteIdent(primaryKeyColumns[0]!.name);\n\n // The conflict-collect SELECT and the staleness guard need the base + mutation id alongside each\n // row, so reject-if-stale carries them in the recordset (`b bigint, m text`). The mutation id is\n // `text` (not `uuid`): a derived child envelope's id is a composite non-UUID string, and a `m uuid`\n // recordset column would raise 22P02 the moment such a write is stale.\n const conflictObjectSql = (alias: string) =>\n `jsonb_build_object('mutationId', ${alias}.m, 'tableName', '${toSqlLiteral(tableName)}', 'currentServerVersion', t.${serverVersionRef})`;\n\n const updateBranch = rejectIfStale\n ? `\n ${updateSetSelect}\n\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) LEFT JOIN ${qualifiedTableName} AS t ON ${pkUpdateJoin} WHERE t.${firstPkRef} IS NULL OR (x.b IS NOT NULL AND t.${serverVersionRef} > x.b)`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n dml_sql := format(\n '${`UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) WHERE ${pkUpdateJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n ${updateSetSelect}\n\n dml_sql := format(\n '${updateTemplate}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n const deleteBranch = rejectIfStale\n ? `\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) JOIN ${qualifiedTableName} AS t ON ${pkDeleteJoin} WHERE x.b IS NOT NULL AND t.${serverVersionRef} > x.b`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n EXECUTE '${`DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) WHERE ${pkDeleteJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}' USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n EXECUTE '${deleteSql}' USING (\n SELECT COALESCE(jsonb_agg(elem->'entityKey'), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n return `\n ELSIF v_table = '${toSqlLiteral(tableName)}' THEN\n IF v_kind = 'create' THEN\n ${createBranch}\n ELSIF v_kind = 'update' THEN\n ${updateBranch}\n ELSIF v_kind = 'delete' THEN\n ${deleteBranch}\n ELSE\n RAISE EXCEPTION 'Unsupported mutation kind \"%\" for table \"%\"', v_kind, v_table;\n END IF;\n `.trim();\n}\n\nconst APPLY_FUNCTION_NAME = \"pgxsinkit_apply_mutations\";\n// ADR-0030: the trailing `text` is `p_expected_fingerprint` — the running server passes the fingerprint\n// it expects for its registry + codegen, and the function verifies itself against its stamped comment\n// before touching any table.\nconst APPLY_FUNCTION_ARG_TYPES = \"jsonb, text, boolean, boolean, jsonb, text\";\n// ADR-0018: the prefix namespaces the strict fingerprint format. Any absent or different prefix is\n// an identity mismatch and the apply function refuses the write.\nconst APPLY_FINGERPRINT_PREFIX = \"pgxsinkit:fp1:\";\n\n/**\n * The roles Supabase's `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS` re-grants at every CREATE\n * (ADR-0054). The artifact's `DROP FUNCTION` makes each install a fresh creation, so these grants come\n * BACK on every regenerate — hence an unconditional revoke per install, not a one-off hardening.\n */\nconst SUPABASE_DEFAULT_PRIVILEGE_ROLES = [\"anon\", \"authenticated\", \"service_role\"] as const;\n\n/**\n * How the generated apply function is rendered. Both fields are part of the artifact's IDENTITY: they\n * change the fingerprinted body, so a change to either forces the regenerate-and-commit flow, and the\n * SERVER must be configured with the same values (it recomputes the expected fingerprint at runtime).\n */\nexport interface ApplyFunctionRenderOptions {\n /** Schema to qualify the function with. Default: unqualified (resolved through `search_path`). */\n functionSchema?: string;\n /**\n * Roles that receive `GRANT EXECUTE` on the apply function (ADR-0054 decision 2). Default `[]` —\n * **owner-only**, which is right whenever the server connects as the function's owner or a\n * superuser. Name ONLY server roles: the function trusts the `p_user_claims` it is handed, so a\n * granted role can pass any claims it likes. The grant list IS the write path's trust boundary.\n */\n grantExecuteTo?: readonly string[];\n}\n\n/** An unquoted-safe SQL role name: what `GRANT … TO <role>` may name without surprises. */\nconst GRANT_ROLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * Validate a `functionSchema` — the ONE definition, shared by the renderer (which qualifies the emitted\n * DDL with it) and by the running server (`applyFunctionSchema`, which must qualify its invocation the\n * same way and recompute the same fingerprint). A schema name reaches SQL as a quoted identifier, so the\n * rule is the same plain-identifier rule role names get: an unusable name is refused loudly at generate\n * / server-construction time rather than producing an artifact nobody can call.\n *\n * Returns `undefined` for an absent schema — the default, an unqualified name resolved through\n * `search_path`.\n */\nexport function resolveApplyFunctionSchema(functionSchema: string | undefined): string | undefined {\n if (functionSchema === undefined) {\n return undefined;\n }\n if (typeof functionSchema !== \"string\" || functionSchema.trim().length === 0) {\n throw new Error(\"plpgsql apply generator: functionSchema is empty\");\n }\n if (!GRANT_ROLE_NAME_PATTERN.test(functionSchema)) {\n throw new Error(\n `plpgsql apply generator: functionSchema '${functionSchema}' is not a plain SQL identifier ` +\n `(letters, digits, '_' and '$', not starting with a digit)`,\n );\n }\n if (functionSchema.length > 63) {\n throw new Error(\n `plpgsql apply generator: functionSchema '${functionSchema}' exceeds PostgreSQL's 63-byte name limit`,\n );\n }\n return functionSchema;\n}\n\n/**\n * Validate `grantExecuteTo` at GENERATE time, fail-closed. A role name is emitted into DDL (as a\n * quoted identifier and as a `pg_roles` literal), and the whole point of ADR-0054 is that who may\n * execute is named explicitly — so an unusable name is refused loudly here rather than silently\n * producing an artifact whose ACL does not say what its author meant.\n */\nfunction resolveGrantExecuteRoles(grantExecuteTo: readonly string[] | undefined): readonly string[] {\n const roles = grantExecuteTo ?? [];\n const seen = new Set<string>();\n\n for (const role of roles) {\n if (typeof role !== \"string\" || role.trim().length === 0) {\n throw new Error(\"plpgsql apply generator: grantExecuteTo contains an empty role name\");\n }\n if (!GRANT_ROLE_NAME_PATTERN.test(role)) {\n throw new Error(\n `plpgsql apply generator: grantExecuteTo role '${role}' is not a plain SQL identifier ` +\n `(letters, digits, '_' and '$', not starting with a digit)`,\n );\n }\n if (role.length > 63) {\n throw new Error(`plpgsql apply generator: grantExecuteTo role '${role}' exceeds PostgreSQL's 63-byte name limit`);\n }\n if (seen.has(role)) {\n throw new Error(`plpgsql apply generator: grantExecuteTo lists role '${role}' more than once`);\n }\n seen.add(role);\n }\n\n // Canonical (byte) order, so an equivalent SET of roles is one artifact whatever order the caller\n // listed them in. The list is emitted into the FINGERPRINTED body, so without this\n // `[\"a\",\"b\"]` and `[\"b\",\"a\"]` — the same authorization posture — would be two different artifacts,\n // and a server configured with one ordering would fail `PXS01` against the other's install. Role names\n // are validated plain identifiers (ASCII only), so JS's default code-unit sort IS byte order.\n return [...roles].sort();\n}\n\n/**\n * The GUARANTEE behind the readable revokes: converge the installed function's ACL to\n * `owner + grantExecuteTo`, whatever it actually contains.\n *\n * The named revokes above close the two exposures we can NAME (Postgres's PUBLIC default, Supabase's\n * default-privilege trio). They cannot close a grant to a role we cannot name — and a consumer's own\n * `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS TO <their role>` re-grants at every `CREATE`\n * exactly like Supabase's does, so a deployment-specific grantee would survive every install and keep a\n * forged-claims caller on the write path indefinitely. So the artifact ENUMERATES the installed\n * function's real grantees (`aclexplode(pg_proc.proacl)`) and revokes EXECUTE from each one that is\n * neither the function's OWNER (`proowner` — revoking the owner is meaningless, they can re-grant at\n * will) nor in the explicit allowlist.\n *\n * Two details make it total:\n * - **A default (NULL) `proacl` explodes to nothing.** That is why the unconditional\n * `REVOKE ALL … FROM PUBLIC` is emitted FIRST: revoking materializes the previously-implicit ACL\n * (`NULL` → `{owner=X/owner}`), so by the time this block runs the catalog states the truth. Pinned by\n * the PGlite unit lane, and by the integration lane against a real cluster.\n * - **Grantee `0` is PUBLIC**, which has no role name (`pg_get_userbyid(0)` returns a placeholder\n * string), so it is revoked by the `FROM PUBLIC` spelling rather than by name.\n *\n * The grantee list is snapshotted into an array BEFORE any revoke runs, so the loop never revokes while\n * scanning the catalog it is mutating. Identifiers go through `format('%I', …)` (= `quote_ident`), and\n * the function is named by `oid::regprocedure::text`, which schema-qualifies and quotes as required.\n */\nfunction buildApplyFunctionAclConvergerSql(signature: string, grantExecuteTo: readonly string[]): string {\n const keepList =\n grantExecuteTo.length > 0\n ? `ARRAY[${grantExecuteTo.map((role) => `'${toSqlLiteral(role)}'`).join(\", \")}]::text[]`\n : `ARRAY[]::text[]`;\n\n return `DO $$\nDECLARE\n _fn oid := '${toSqlLiteral(signature)}'::regprocedure;\n _owner oid;\n _keep text[] := ${keepList};\n _grantees oid[];\n _grantee oid;\n _grantee_name text;\nBEGIN\n SELECT p.proowner INTO _owner FROM pg_proc AS p WHERE p.oid = _fn;\n SELECT array_agg(DISTINCT acl.grantee) INTO _grantees\n FROM pg_proc AS p, aclexplode(p.proacl) AS acl\n WHERE p.oid = _fn;\n\n FOREACH _grantee IN ARRAY COALESCE(_grantees, ARRAY[]::oid[]) LOOP\n IF _grantee = _owner THEN\n CONTINUE;\n END IF;\n IF _grantee = 0 THEN\n EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', _fn::regprocedure::text);\n CONTINUE;\n END IF;\n _grantee_name := pg_get_userbyid(_grantee);\n IF _grantee_name = ANY (_keep) THEN\n CONTINUE;\n END IF;\n EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM %I', _fn::regprocedure::text, _grantee_name);\n END LOOP;\nEND;\n$$;`;\n}\n\n/**\n * ADR-0054: the apply function is DENY-BY-DEFAULT, and converges on every install.\n *\n * The function trusts `p_user_claims` — it copies them into `request.jwt.claims` and switches `role`\n * before running RLS-governed DML — which is correct for the consumer server (it passes claims it\n * VERIFIED) and catastrophic for anyone else, who would simply choose their own. Postgres grants\n * EXECUTE to PUBLIC on every new function and Supabase-shaped clusters additionally re-grant the\n * `anon`/`authenticated`/`service_role` trio via default privileges; because the artifact begins with\n * `DROP FUNCTION`, EVERY install recreates that exposure. So the revokes are emitted unconditionally\n * (convergence must not depend on install history), the Supabase-trio ones through the shared\n * role-existence guard so the artifact stays portable to PGlite and plain-Postgres lanes.\n *\n * Those named revokes are the READABLE fast path — a reviewer sees the two known exposures closed in\n * plain SQL. The guarantee is {@link buildApplyFunctionAclConvergerSql}, which then revokes EVERY\n * remaining grantee outside `owner + grantExecuteTo`, including ones this renderer cannot name.\n *\n * Grants come last, so naming a revoked role in `grantExecuteTo` is a deliberate, explicit grant.\n */\nfunction buildApplyFunctionAclSql(functionName: string, grantExecuteTo: readonly string[]): string {\n const signature = `${functionName}(${APPLY_FUNCTION_ARG_TYPES})`;\n\n return [\n `REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC;`,\n ...SUPABASE_DEFAULT_PRIVILEGE_ROLES.map((role) =>\n buildRoleGuardedStatement(role, `REVOKE ALL ON FUNCTION ${signature} FROM ${quoteIdent(role)}`),\n ),\n buildApplyFunctionAclConvergerSql(signature, grantExecuteTo),\n ...grantExecuteTo.map((role) =>\n buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${signature} TO ${quoteIdent(role)}`),\n ),\n ].join(\"\\n\\n\");\n}\n\nfunction buildApplyFunctionBody(registry: SyncTableRegistry, options: ApplyFunctionRenderOptions = {}): string {\n const tableBranches = Object.values(registry)\n // A read projection (ADR-0027) owns no writable table — its `table` IS the owner's, so the owner's\n // branch already handles that physical table. Emitting a branch for the projection too would\n // DUPLICATE the owner's table branch (same table name). Read projections are readonly and never\n // reach the write path, so exclude them from the apply function entirely.\n .filter((entry) => !(entry as SyncTableEntry).readProjection)\n .map((entry) => buildTableBranch(entry as SyncTableEntry))\n .join(\"\\n\");\n const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);\n // ADR-0054 decision 3: the ACL is rendered INSIDE the fingerprinted body (unlike the COMMENT, which\n // is appended around it) — an install without the revokes IS a different fingerprint and is refused\n // at call time, so a stale PUBLIC-executable install cannot run while `--check` stays green.\n const aclSql = buildApplyFunctionAclSql(functionName, resolveGrantExecuteRoles(options.grantExecuteTo));\n\n return `\n-- Install idempotently by dropping the current signature first. PostgreSQL cannot change a function's\n-- return type through CREATE OR REPLACE, while a generated artifact must install its complete definition.\n--\n-- TWO-TIER MUTATION-ID INVARIANT. \\`mutation_id\\` is TEXT here (RETURNS TABLE + operations_log), not\n-- uuid, so this apply function can serve a DIRECT server-side caller that derives child envelopes with\n-- composite non-UUID ids (\\`\\${parentId}:<tag>:<n>\\`). That is the ONLY non-UUID path. pgxsinkit's public\n-- surface — the HTTP route's request/ack schemas and the client's \\`mutation_id UUID\\` journal — stays\n-- UUID-only (see packages/contracts/src/mutation.ts): the route validates every request id as a UUID and\n-- builds every ack from that request id, never from the TEXT conflict rows this returns. A non-UUID id\n-- therefore never crosses into the UUID-typed surface.\n--\nDROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES});\n\nCREATE OR REPLACE FUNCTION ${functionName}(\n p_batch jsonb,\n p_request_path text,\n p_log_enabled boolean,\n p_rls_enabled boolean,\n p_user_claims jsonb,\n p_expected_fingerprint text\n) RETURNS TABLE(mutation_id text, table_name text, current_server_version bigint) LANGUAGE plpgsql AS $$\nDECLARE\n dml_sql text;\n v_table text;\n v_kind text;\n v_sig text;\n v_rows jsonb;\n v_cols text;\n v_vals text;\n v_set text;\n -- ADR-0015: stale-write conflicts collected across the batch (mutationId + the row's current\n -- Server version), returned to the handler which turns them into 'conflicted' acks.\n v_conflicts jsonb := '[]'::jsonb;\n v_group_conflicts jsonb;\n -- ADR-0030: the fingerprint this installed function was stamped with (its own ADR-0018 comment),\n -- read back once for the self-verification gate below.\n _installed_fingerprint text;\n _claims jsonb;\n _target_role text;\n _previous_role text;\n _previous_claims text;\n _previous_claim_sub text;\nBEGIN\n -- ADR-0030: the apply function verifies ITSELF against its ADR-0018 fingerprint comment before it\n -- touches any table. p_expected_fingerprint is what the running server expects for its registry +\n -- codegen; obj_description(...) is the fingerprint this installed function was stamped with, atomically,\n -- by the same migration. A mismatch — INCLUDING an absent comment (an unstamped hand-installed\n -- function ⇒ NULL, refused per ADR-0030) — means the installed function is stale relative to the caller,\n -- so raise SQLSTATE 'PXS01' and apply nothing. The check IS the call (no read-then-call TOCTOU) and\n -- costs no extra round trip (the argument rides the existing invocation; the comparison is one text\n -- equality). The signature literal is embedded, never the fingerprint hash itself — baking the hash\n -- into the body would be circular with the hash-of-body the fingerprint is.\n _installed_fingerprint := obj_description('${functionName}(${APPLY_FUNCTION_ARG_TYPES})'::regprocedure, 'pg_proc');\n IF p_expected_fingerprint IS DISTINCT FROM _installed_fingerprint THEN\n RAISE EXCEPTION 'pgxsinkit_apply_mutations is stale: the installed apply-function fingerprint (%) does not match the fingerprint this server expects (%). Regenerate the sync-function migration (pgxsinkit-generate) and apply it before serving writes.', COALESCE(_installed_fingerprint, '(none)'), p_expected_fingerprint\n USING ERRCODE = 'PXS01';\n END IF;\n\n IF p_rls_enabled THEN\n -- Capture the caller's role/claims before switching into the RLS actor context, so the\n -- batch does not leak that context into the rest of the caller's transaction. The HTTP\n -- route RESET ROLEs after calling this function, but in-transaction callers cannot —\n -- restoring here leaves every caller exactly as it was found.\n _previous_role := current_setting('role', true);\n _previous_claims := current_setting('request.jwt.claims', true);\n _previous_claim_sub := current_setting('request.jwt.claim.sub', true);\n _claims := COALESCE(p_user_claims, '{}'::jsonb);\n _target_role := COALESCE(NULLIF(_claims ->> 'role', ''), 'authenticated');\n BEGIN\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = _target_role) THEN\n PERFORM set_config('role', _target_role, true);\n ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN\n PERFORM set_config('role', 'authenticated', true);\n END IF;\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', _claims::text, true);\n IF _claims ? 'sub' THEN\n PERFORM set_config('request.jwt.claim.sub', _claims ->> 'sub', true);\n END IF;\n END IF;\n\n IF jsonb_typeof(p_batch) <> 'object' THEN\n RAISE EXCEPTION 'Batch payload must be a JSON object';\n END IF;\n\n IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN\n RAISE EXCEPTION 'Batch payload mutations must be a JSON array';\n END IF;\n\n -- Group the batch by (table, kind, payload column-set) and apply each group with one statement\n -- (ADR-0014 Phase 4). mutationSeq is table-local, so it cannot order groups across tables: parent\n -- and child journals can both start at 1. WITH ORDINALITY preserves the submitted JSON array order\n -- across tables (FK-safe; the batch transaction also runs SET CONSTRAINTS ALL DEFERRED).\n FOR v_table, v_kind, v_sig, v_rows IN\n SELECT\n grouped.table_name,\n grouped.kind,\n grouped.sig,\n jsonb_agg(grouped.mutation ORDER BY grouped.batch_position)\n FROM (\n SELECT\n entries.m->>'tableName' AS table_name,\n entries.m->>'kind' AS kind,\n COALESCE((\n SELECT string_agg(payload_key, ',' ORDER BY payload_key)\n FROM jsonb_object_keys(COALESCE(entries.m->'payload', '{}'::jsonb)) AS payload_key\n ), '') AS sig,\n entries.m AS mutation,\n entries.batch_position\n FROM jsonb_array_elements(p_batch->'mutations') WITH ORDINALITY AS entries(m, batch_position)\n ) AS grouped\n GROUP BY grouped.table_name, grouped.kind, grouped.sig\n ORDER BY MIN(grouped.batch_position)\n LOOP\n dml_sql := NULL;\n v_cols := NULL;\n v_vals := NULL;\n v_set := NULL;\n\n IF FALSE THEN\n NULL;\n ${tableBranches}\n ELSE\n RAISE EXCEPTION 'Unknown table \"%\" in batch mutation', v_table;\n END IF;\n END LOOP;\n\n IF p_log_enabled THEN\n -- One batched log insert (the whole batch is a single transaction, so a per-mutation loop\n -- bought nothing): a runtime apply failure above rolls the whole transaction back, log rows\n -- included, preserving the existing whole-batch-failure semantics.\n INSERT INTO operations_log (\n table_name,\n operation_kind,\n entity_key_json,\n payload_json,\n status,\n http_status,\n mutation_id,\n mutation_seq,\n client_timestamp_us,\n request_path,\n server_timestamp_us\n )\n SELECT\n m->>'tableName',\n m->>'kind',\n COALESCE(m->'entityKey', '{}'::jsonb),\n COALESCE(m->'payload', '{}'::jsonb),\n 'succeeded',\n 200,\n -- mutation_id is text: a derived child envelope carries a composite non-UUID id\n -- (parent-id + tag + index), so no ::uuid cast (it would raise 22P02 on such an id).\n m->>'mutationId',\n (m->>'mutationSeq')::integer,\n NULLIF(m->>'clientTimestampUs', '')::bigint,\n p_request_path,\n -- The canonical microsecond clock (utilities migration); never the inline expression.\n ${CLOCK_US_CALL_SQL_TEXT}\n FROM jsonb_array_elements(p_batch->'mutations') AS m;\n END IF;\n\n IF p_rls_enabled THEN\n -- Restore the caller's prior role/claims captured above, so the RLS context applied for\n -- the batch does not persist into subsequent statements of the caller's transaction.\n BEGIN\n PERFORM set_config('role', COALESCE(NULLIF(_previous_role, ''), 'none'), true);\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', COALESCE(_previous_claims, ''), true);\n PERFORM set_config('request.jwt.claim.sub', COALESCE(_previous_claim_sub, ''), true);\n END IF;\n\n -- ADR-0015: return the collected stale-write conflicts. Empty under last-write-wins (or when no\n -- write was stale), so the handler simply acks everything as today.\n RETURN QUERY\n SELECT\n -- mutation_id is text (see RETURNS TABLE): a stale derived child envelope's id is a composite\n -- non-UUID string, so return it verbatim — a ::uuid cast here would raise 22P02 and abort the batch.\n c->>'mutationId',\n c->>'tableName',\n (c->>'currentServerVersion')::bigint\n FROM jsonb_array_elements(v_conflicts) AS c;\nEND;\n$$;\n\n-- ADR-0054: deny by default. Emitted on EVERY install because the DROP above resets the ACL to\n-- Postgres's PUBLIC default (plus Supabase's default-privilege grants), so convergence cannot depend\n-- on install history. EXECUTE is owner-only unless the artifact was generated with an explicit\n-- --grant-execute-to; the grant list is the write path's ENTIRE trust boundary, because this function\n-- trusts the claims it is handed.\n${aclSql}\n`.trim();\n}\n\n/**\n * The fingerprint the installed apply function should carry for this registry + applier codegen\n * (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape\n * change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the\n * two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /\n * customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).\n */\nexport function expectedApplyFingerprint(\n registry: SyncTableRegistry,\n options: ApplyFunctionRenderOptions = {},\n): string {\n return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));\n}\n\nexport function buildPlpgsqlBatchFunctionDdl(\n registry: SyncTableRegistry,\n options: ApplyFunctionRenderOptions = {},\n): string {\n const body = buildApplyFunctionBody(registry, options);\n const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);\n const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);\n\n // ADR-0018: stamp the function with the fingerprint of this exact DDL body. Stored as a COMMENT\n // because it is function-scoped, replaced atomically with the function, and read back in one line\n // via obj_description — so the server (startup) and CI (pre-deploy) can both detect a function\n // that is stale relative to the registry + codegen it is meant to serve.\n return `${body}\\n\\nCOMMENT ON FUNCTION ${functionName}(${APPLY_FUNCTION_ARG_TYPES}) IS '${fingerprint}';`;\n}\n\nexport async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n options: ApplyFunctionRenderOptions = {},\n): Promise<void> {\n const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);\n await db.execute(sql.raw(ddl));\n}\n\ntype AuthHelperPresenceRow = {\n authUid: string | null;\n};\n\nexport async function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n): Promise<void> {\n const result = await db.execute<AuthHelperPresenceRow>(sql`\n SELECT\n to_regprocedure('auth.uid()')::text AS \"authUid\"\n `);\n\n const row = Array.from(result as Iterable<unknown>, (entry) => entry as AuthHelperPresenceRow)[0];\n const missingHelpers = [row?.authUid ? null : \"auth.uid()\"].filter((value): value is string => value !== null);\n\n if (missingHelpers.length > 0) {\n throw new Error(\n `The write path requires Supabase auth helpers. Missing: ${missingHelpers.join(\", \")}. ` +\n \"Ensure auth.uid() is available (standard on Supabase-managed databases).\",\n );\n }\n}\n\n/**\n * A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the\n * Base server version the row has since advanced past — `currentServerVersion` is the row's current\n * version) or an UPDATE whose **target row is missing** (deleted by another writer —\n * `currentServerVersion` is `null`, the #6 discriminator). The handler surfaces it on the\n * `conflicted` ack.\n */\nexport interface MutationConflict {\n mutationId: string;\n tableName: string;\n currentServerVersion: string | null;\n}\n\ninterface MutationConflictRow {\n mutationId: string | null;\n tableName: string | null;\n currentServerVersion: string | null;\n}\n\nexport async function executePlpgsqlBatch(\n tx: TransactionClient,\n batch: BatchMutationRequest,\n requestPath: string,\n logEnabled: boolean,\n rlsEnabled: boolean,\n userClaims: Record<string, unknown>,\n // ADR-0030: the fingerprint the running server expects for its registry + codegen\n // (`expectedApplyFingerprint(registry)`, computed once per server instance). The installed apply\n // function compares it against its own stamped comment and raises SQLSTATE 'PXS01' on a mismatch —\n // in-body, atomic with the call, before it touches any table.\n expectedFingerprint: string,\n options: {\n functionSchema?: string;\n } = {},\n): Promise<MutationConflict[]> {\n const normalizedClaims = userClaims ?? {};\n // Typed identifier interpolation (never `sql.raw` of a hand-quoted name); the OUT-column aliases\n // are the generated function's fixed names. The schema goes through the SAME validator the renderer\n // uses, so a server configured with `applyFunctionSchema` names exactly what the artifact installed.\n const functionSchema = resolveApplyFunctionSchema(options.functionSchema);\n const functionRef = functionSchema\n ? sql`${sql.identifier(functionSchema)}.${sql.identifier(\"pgxsinkit_apply_mutations\")}`\n : sql`${sql.identifier(\"pgxsinkit_apply_mutations\")}`;\n\n // The applier RETURNS the stale-write conflicts (ADR-0015). Read them from the function's result\n // set; an empty set (the last-write-wins case, or nothing stale) means every mutation applied.\n const result = await tx.execute(\n 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})`,\n );\n\n const rows = Array.from(result as Iterable<unknown>, (row) => row as MutationConflictRow);\n return rows.flatMap((row) =>\n row.mutationId != null\n ? [\n {\n mutationId: row.mutationId,\n tableName: row.tableName ?? \"\",\n currentServerVersion: row.currentServerVersion,\n } satisfies MutationConflict,\n ]\n : [],\n );\n}\n",
|
|
12
17
|
"import { getTableName, sql } from \"drizzle-orm\";\nimport type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type { RegistryRelations, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { operationsLogTable } from \"./schema\";\nimport type { OperationsLogConfig } from \"./types\";\n\ntype OperationsLogPresenceRow = {\n tableName: string | null;\n};\n\n/**\n * The `to_regclass` presence-probe target, derived from the real pgTable so the probe (and the\n * warning below) track a rename of `operationsLogTable`. Exported for the integration suite that\n * asserts the degraded no-log path against the same identity.\n */\nexport function operationsLogRegclassTarget(): string {\n return `public.${getTableName(operationsLogTable)}`;\n}\n\n/**\n * Ensures the operations_log table exists in the database.\n *\n * Returns `true` if the table is present, `false` if missing.\n * Consumers should include `operationsLogTable` from `@pgxsinkit/server`\n * in their Drizzle schema so `drizzle-kit generate`/`push` creates it.\n */\nexport async function ensureOperationsLogSchema<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n config: OperationsLogConfig,\n): Promise<boolean> {\n if (!config.enabled) {\n return false;\n }\n\n try {\n const result = await db.execute<OperationsLogPresenceRow>(sql`\n SELECT to_regclass(${operationsLogRegclassTarget()})::text AS \"tableName\"\n `);\n\n const row = Array.from(result as Iterable<unknown>, (entry) => entry as OperationsLogPresenceRow)[0];\n\n if (!row?.tableName) {\n console.warn(\n `${getTableName(operationsLogTable)} table is missing. Add operationsLogTable from @pgxsinkit/server ` +\n \"to your Drizzle schema and run drizzle-kit generate/push to create it. \" +\n \"Operation logging will be disabled until the table exists.\",\n );\n return false;\n }\n\n return true;\n } catch (error) {\n console.warn(\"Unable to verify operations_log table:\", (error as Error)?.message ?? error);\n return false;\n }\n}\n",
|
|
13
18
|
"// A tiny web-standard `fetch` router for the pgxsinkit server (ADR-0017). The server needs only\n// exact-path GET/POST routing, a small CORS layer, and an error boundary, so a focused router keeps\n// `@pgxsinkit/server` dependency-light and runnable on any `fetch` runtime — no web framework required.\n// `proxyElectricShapeRequest` and the mutation handler are plain `(Request) => Response` functions, so\n// they can equally be mounted in someone else's framework.\n\nimport { resolveCorsOrigin } from \"./cors-origin\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nexport interface CorsConfig {\n /** Exact origins, or a `\"*\"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}). */\n origins: string[];\n allowMethods: string[];\n allowHeaders: string[];\n}\n\n/** A CORS scope is matched either by exact pathname or by pathname prefix (e.g. `/api/`). */\nexport type CorsScope = { exact: string } | { prefix: string };\n\nexport type RouterErrorHandler = (error: unknown, request: Request) => Response | Promise<Response>;\n\nexport class FetchRouter {\n readonly #routes = new Map<string, FetchHandler>();\n #cors: CorsConfig | undefined;\n #corsMatchers: Array<(pathname: string) => boolean> = [];\n #onError: RouterErrorHandler | undefined;\n\n get(path: string, handler: FetchHandler): void {\n this.#routes.set(`GET ${path}`, handler);\n }\n\n post(path: string, handler: FetchHandler): void {\n this.#routes.set(`POST ${path}`, handler);\n }\n\n setCors(config: CorsConfig, scopes: CorsScope[]): void {\n this.#cors = config;\n this.#corsMatchers = scopes.map((scope) =>\n \"exact\" in scope\n ? (pathname: string) => pathname === scope.exact\n : (pathname: string) => pathname.startsWith(scope.prefix),\n );\n }\n\n setErrorHandler(handler: RouterErrorHandler): void {\n this.#onError = handler;\n }\n\n readonly fetch = async (request: Request): Promise<Response> => {\n const pathname = new URL(request.url).pathname;\n const corsApplies = this.#cors !== undefined && this.#corsMatchers.some((matches) => matches(pathname));\n\n // A preflight short-circuits before routing, exactly as a CORS middleware mounted on the scope would.\n if (request.method === \"OPTIONS\" && corsApplies) {\n return this.#preflight(request);\n }\n\n let response: Response;\n const handler = this.#routes.get(`${request.method} ${pathname}`);\n if (handler) {\n try {\n response = await handler(request);\n } catch (error) {\n if (!this.#onError) {\n throw error;\n }\n response = await this.#onError(error, request);\n }\n } else {\n response = new Response(\"Not Found\", { status: 404 });\n }\n\n return corsApplies ? this.#withCorsHeaders(request, response) : response;\n };\n\n #allowedOrigin(request: Request): string | null {\n return this.#cors ? resolveCorsOrigin(request, this.#cors.origins) : null;\n }\n\n #preflight(request: Request): Response {\n const headers = new Headers();\n const origin = this.#allowedOrigin(request);\n if (origin) {\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n }\n if (this.#cors) {\n headers.set(\"Access-Control-Allow-Methods\", this.#cors.allowMethods.join(\",\"));\n // Echo what the browser asks to send (e.g. a deployment gateway's `apikey` alongside the\n // toolkit's `Authorization`), falling back to the declared list — so a client header the app\n // legitimately sets is never rejected just because it wasn't enumerated here.\n headers.set(\n \"Access-Control-Allow-Headers\",\n request.headers.get(\"access-control-request-headers\") ?? this.#cors.allowHeaders.join(\",\"),\n );\n }\n return new Response(null, { status: 204, headers });\n }\n\n #withCorsHeaders(request: Request, response: Response): Response {\n const origin = this.#allowedOrigin(request);\n if (!origin) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n }\n}\n",
|
|
14
|
-
"import { NOW_MICROSECONDS_SQL_TEXT } from \"@pgxsinkit/contracts\";\n\n/**\n * The canonical microsecond-clock DB function `public.pgxsinkit_clock_us()` — the ONE home for the\n * `clock_timestamp()`-epoch-microseconds semantics. Every surface (column DEFAULTs, the generated\n * apply function's managed `nowMicroseconds` fields, the operations-log server stamp) CALLS this\n * function; nothing inlines the expression. This migration installs it, and — because the generated\n * apply function calls it — it MUST be the FIRST folder in any consumer's migration chain (before the\n * schema and the sync-artifact folder).\n *\n * The body is composed from the single source {@link NOW_MICROSECONDS_SQL_TEXT} in @pgxsinkit/contracts\n * (CREATE FUNCTION is the sanctioned raw-SQL case — Drizzle cannot express a PL/pgSQL/SQL function body).\n */\nexport function renderPgxsinkitUtilitiesMigration(): string {\n return `-- The pgxsinkit canonical microsecond clock. Deliberately clock_timestamp() (advances WITHIN a\n-- transaction — LWW/audit ordering of multi-row applies depends on it), never now()/transaction_timestamp()\n-- (frozen at tx start). FLOOR + BIGINT: whole microseconds since epoch.\nCREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()\n RETURNS bigint\n LANGUAGE sql\n VOLATILE\nAS $$\n SELECT ${NOW_MICROSECONDS_SQL_TEXT}\n
|
|
15
|
-
"import type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type {\n JwtClaims,\n RegistryRelations,\n RegistryTables,\n SyncRuntimeStatus,\n SyncServerAddress,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { proxyElectricShapeRequest } from \"./electric-proxy\";\nimport {\n authoritativeMutationPaths,\n batchMutationPaths,\n createMutationHandler,\n type StartupVerificationMode,\n} from \"./mutations/route\";\nimport { ensureOperationsLogSchema } from \"./operations-log/ddl\";\nimport type { OperationsLogConfig } from \"./operations-log/types\";\nimport { FetchRouter, type CorsScope } from \"./router\";\n\nconst defaultAllowedOrigins = [\"http://localhost:5173\", \"http://localhost:5174\"];\n\ninterface BunServerHandle {\n stop: () => void;\n}\n\ninterface BunNamespace {\n serve: (options: {\n port: number;\n hostname?: string;\n idleTimeout?: number;\n fetch: (request: Request) => Response | Promise<Response>;\n }) => BunServerHandle;\n}\n\n/**\n * How the operations-log table's presence is resolved at startup (ADR-0030 decision 3):\n * - `\"probe\"` (default): the safe degradation posture (ADR-0030) — one query ensures/confirms the table,\n * and logging is disabled at runtime (with a warning) if it is absent, so a missing table degrades\n * gracefully instead of failing writes.\n * - `\"enabled\"`: assume the table exists — NO query. If it is actually absent, writes then fail loudly.\n * - `\"disabled\"`: turn logging off with NO query.\n *\n * `\"enabled\" | \"disabled\"` are the serverless posture: paired with `startupVerification: \"deploy-time\"`,\n * a fresh worker sends zero queries before the mutation transaction itself.\n */\nexport type OperationsLogStartupMode = \"probe\" | \"enabled\" | \"disabled\";\n\n/**\n * The `deployment` profile owns the server's startup query posture (ADR-0030 decision 3). Its defaults\n * are the safe degradation posture — probe-and-verify at startup — so a long-lived host that never sets\n * it still verifies and degrades gracefully; serverless / per-request workers set\n * `{ startupVerification: \"deploy-time\", operationsLog: \"enabled\" | \"disabled\" }` for a\n * zero-startup-query first write.\n */\nexport interface DeploymentProfile {\n /** Governs ONLY the RLS auth-helper verify now (apply-fn drift is self-verifying). Default `\"in-process\"`. */\n startupVerification?: StartupVerificationMode;\n /** How the operations-log table presence is resolved. Default `\"probe\"`. */\n operationsLog?: OperationsLogStartupMode;\n}\n\nexport interface CreateSyncServerOptions<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n registry: TRegistry;\n db: TDb;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n /**\n * When set, the server serves a read-path Electric shape proxy that shares the\n * single `resolveAuthClaims` adapter with the write path (ADR-0003). Without it,\n * no shape proxy is registered.\n */\n electricUrl?: string;\n /** Path for the shape proxy route. Defaults to `/api/shape`. */\n shapeProxyPath?: string;\n /** Optional per-request extra params passed to customWhere/shared filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\n operationsLog?: {\n enabled?: boolean;\n };\n /** Health check endpoint. Enabled by default at `/health`; `false` disables it, `{ path }` relocates it. */\n healthCheck?: boolean | { path: string };\n port?: number;\n host?: string;\n idleTimeoutSeconds?: number;\n allowedOrigins?: string[];\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n /**\n * The startup query posture (ADR-0030). The apply function now verifies its own ADR-0018 fingerprint\n * in-body on every call (SQLSTATE `PXS01` on drift), so there is no startup drift check to configure;\n * this governs only the RLS auth-helper verify and the operations-log presence resolution. Defaults\n * are the safe degradation posture (ADR-0030). See {@link DeploymentProfile}.\n */\n deployment?: DeploymentProfile;\n /**\n * Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits\n * one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for\n * attributing wall-clock latency against the client's `syncDebug` lines. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n}\n\nexport interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {\n tables: Array<keyof TRegistry & string>;\n modes: Record<string, TRegistry[keyof TRegistry][\"mode\"]>;\n}\n\nexport interface SyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n drizzle: TDb;\n fetch: (request: Request) => Promise<Response>;\n request: (path: string, init?: RequestInit) => Promise<Response>;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n status: SyncRuntimeStatus;\n address: SyncServerAddress | null;\n diagnostics: () => ServerDiagnostics<TRegistry>;\n}\n\nexport function createSyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n>(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {\n const db = options.db;\n const router = new FetchRouter();\n let bunServer: BunServerHandle | undefined;\n\n const status: SyncRuntimeStatus = {\n phase: \"ready\",\n isRunning: false,\n };\n\n let address: SyncServerAddress | null = null;\n const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);\n const operationsLogStartup = options.deployment?.operationsLog ?? \"probe\";\n // ADR-0030: how operations_log presence is resolved decides whether startup issues a query at all.\n // - \"probe\" (default): thread the presence probe into the effective config. operations_log is an\n // *optional* feature (default-enabled), so if logging was requested but the table is absent, disable\n // it at runtime rather than letting every write fail on a missing table — the documented degradation\n // (ensureOperationsLogSchema warns and returns `false`). The route awaits `operationsLogReady` before\n // any logOperation, so the corrected flag is in effect by the time logging runs, and the route holds\n // this same config object. (Board dogfooding: discarding this boolean 500'd every mutation on a\n // missing optional table.)\n // - \"enabled\": assume the table exists — NO query; logging stays on (an actual absence then fails\n // writes loudly, by design). \"disabled\": logging off — NO query.\n let operationsLogReady: Promise<void>;\n if (operationsLogStartup === \"probe\") {\n operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig).then((present) => {\n operationsLogConfig.enabled = operationsLogConfig.enabled && present;\n });\n } else {\n if (operationsLogStartup === \"disabled\") {\n operationsLogConfig.enabled = false;\n }\n operationsLogReady = Promise.resolve();\n }\n\n const shapeProxyPath = options.shapeProxyPath ?? \"/api/shape\";\n\n // CORS covers the canonical /api/* routes and the shape proxy path when it is relocated outside /api/.\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }];\n if (options.electricUrl) {\n corsScopes.push({ exact: shapeProxyPath });\n }\n router.setCors(\n {\n origins: options.allowedOrigins ?? defaultAllowedOrigins,\n allowMethods: [\"GET\", \"POST\", \"OPTIONS\"],\n // `apikey`: a deployment gateway (Supabase) expects it on every request, so the browser client\n // sends it; it must be allowed in the preflight even though the server itself ignores it.\n allowHeaders: [\"Content-Type\", \"Authorization\", \"apikey\"],\n },\n corsScopes,\n );\n\n router.setErrorHandler((error) => {\n status.phase = \"degraded\";\n status.lastError = error instanceof Error ? error.message : \"Unexpected error\";\n options.onStatusChange?.(status);\n\n if (isValidationError(error)) {\n return Response.json({ message: \"Validation failed\", issues: error.issues }, { status: 400 });\n }\n\n return Response.json({ message: error instanceof Error ? error.message : \"Unexpected error\" }, { status: 500 });\n });\n\n const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);\n if (healthCheckPath) {\n router.get(healthCheckPath, () => Response.json({ ok: true }));\n }\n\n // The single mutation ingress point — all writes go through POST /api/mutations.\n const mutationHandlers = createMutationHandler(\n db,\n options.registry,\n operationsLogConfig,\n operationsLogReady,\n options.resolveAuthClaims,\n options.deployment?.startupVerification ?? \"in-process\",\n options.logTimings ?? false,\n );\n for (const path of batchMutationPaths) {\n router.post(path, mutationHandlers.batch);\n }\n for (const path of authoritativeMutationPaths) {\n router.post(path, mutationHandlers.authoritative);\n }\n\n // The read-path shape proxy shares the same resolveAuthClaims adapter, so read and\n // write authorization can never diverge (ADR-0003).\n if (options.electricUrl) {\n const electricUrl = options.electricUrl;\n const resolveAuthClaims = options.resolveAuthClaims;\n const resolveShapeParams = options.resolveShapeParams;\n router.get(shapeProxyPath, async (request) => {\n const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;\n const extraParams = resolveShapeParams?.(request);\n return proxyElectricShapeRequest(request, claims, {\n registry: options.registry,\n electricUrl,\n ...(extraParams ? { extraParams } : {}),\n ...(options.logTimings ? { logTimings: true } : {}),\n });\n });\n }\n\n const fetch = router.fetch;\n\n return {\n drizzle: db,\n fetch,\n request: (path, init) => {\n const baseUrl = address === null ? \"http://localhost\" : `http://${address.host}:${address.port}`;\n return fetch(new Request(new URL(path, baseUrl).toString(), init));\n },\n start: async () => {\n if (bunServer) {\n return;\n }\n\n const bun = getBunNamespace();\n if (!bun) {\n throw new Error(\"createSyncServer.start() requires the Bun runtime\");\n }\n\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3001;\n const idleTimeout = options.idleTimeoutSeconds;\n\n bunServer = bun.serve({\n hostname: host,\n port,\n ...(idleTimeout !== undefined ? { idleTimeout } : {}),\n fetch,\n });\n\n status.isRunning = true;\n status.phase = \"ready\";\n delete status.lastError;\n address = { host, port };\n options.onStatusChange?.(status);\n },\n stop: async () => {\n bunServer?.stop();\n bunServer = undefined;\n status.isRunning = false;\n options.onStatusChange?.(status);\n },\n status,\n get address() {\n return address;\n },\n diagnostics: () => ({\n tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,\n modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),\n }),\n };\n}\n\nexport function buildRegistrySchema<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): RegistryTables<TRegistry> {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction resolveHealthCheckPath(config?: boolean | { path: string }, defaultEnabled = false): string | null {\n if (config === false) {\n return null;\n }\n\n if (config === undefined && !defaultEnabled) {\n return null;\n }\n\n if (typeof config === \"object\" && \"path\" in config) {\n return config.path;\n }\n\n return \"/health\";\n}\n\nfunction getBunNamespace(): BunNamespace | undefined {\n const maybeBun = (globalThis as { Bun?: BunNamespace }).Bun;\n return maybeBun;\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction resolveOperationsLogConfig(options?: { enabled?: boolean }): OperationsLogConfig {\n return {\n enabled: options?.enabled ?? true,\n };\n}\n\nexport { authoritativeMutationPaths, batchMutationPaths, createMutationHandler } from \"./mutations/route\";\nexport type { StartupVerificationMode } from \"./mutations/route\";\nexport type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from \"./router\";\nexport { FetchRouter } from \"./router\";\nexport { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from \"./mutations/plpgsql-apply\";\nexport { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { proxyElectricShapeRequest } from \"./electric-proxy\";\nexport type { ElectricProxyOptions } from \"./electric-proxy\";\nexport { readSqlState } from \"./sql-state\";\n"
|
|
19
|
+
"import { buildRoleGuardedStatement, NOW_MICROSECONDS_SQL_TEXT, quoteIdentifier } from \"@pgxsinkit/contracts\";\n\n/**\n * ADR-0054 decision 5: `pgxsinkit_clock_us()` is hardened in the same pass as the apply function — no\n * pgxsinkit-emitted function relies on default privileges. Unlike the apply function it is a harmless\n * monotonic-clock read whose legitimate callers INCLUDE RLS-context sessions (a column DEFAULT\n * evaluates as whatever role is writing the row), so PUBLIC is revoked and the Supabase trio is\n * granted back explicitly, through the shared role-existence guard so the migration stays portable.\n */\nconst CLOCK_US_SIGNATURE = \"public.pgxsinkit_clock_us()\";\nconst CLOCK_US_GRANTEES = [\"anon\", \"authenticated\", \"service_role\"] as const;\n\n/**\n * The canonical microsecond-clock DB function `public.pgxsinkit_clock_us()` — the ONE home for the\n * `clock_timestamp()`-epoch-microseconds semantics. Every surface (column DEFAULTs, the generated\n * apply function's managed `nowMicroseconds` fields, the operations-log server stamp) CALLS this\n * function; nothing inlines the expression. This migration installs it, and — because the generated\n * apply function calls it — it MUST be the FIRST folder in any consumer's migration chain (before the\n * schema and the sync-artifact folder).\n *\n * The body is composed from the single source {@link NOW_MICROSECONDS_SQL_TEXT} in @pgxsinkit/contracts\n * (CREATE FUNCTION is the sanctioned raw-SQL case — Drizzle cannot express a PL/pgSQL/SQL function body).\n */\nexport function renderPgxsinkitUtilitiesMigration(): string {\n return `-- The pgxsinkit canonical microsecond clock. Deliberately clock_timestamp() (advances WITHIN a\n-- transaction — LWW/audit ordering of multi-row applies depends on it), never now()/transaction_timestamp()\n-- (frozen at tx start). FLOOR + BIGINT: whole microseconds since epoch.\nCREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()\n RETURNS bigint\n LANGUAGE sql\n VOLATILE\nAS $$\n SELECT ${NOW_MICROSECONDS_SQL_TEXT}\n$$;\n\n-- Deny by default, then grant back deliberately (ADR-0054 decision 5). Stated on every install: a\n-- first install on a Supabase-shaped cluster otherwise picks up ALTER DEFAULT PRIVILEGES ... GRANT ALL\n-- ON FUNCTIONS TO anon, authenticated, service_role, so the posture is declared here, never inherited.\n-- The grants are real: a column DEFAULT calling this clock is evaluated as whatever role writes the row.\nREVOKE ALL ON FUNCTION ${CLOCK_US_SIGNATURE} FROM PUBLIC;\n\n${CLOCK_US_GRANTEES.map((role) =>\n buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${CLOCK_US_SIGNATURE} TO ${quoteIdentifier(role)}`),\n).join(\"\\n\\n\")}`;\n}\n",
|
|
20
|
+
"import {\n getSyncRegistryStreams,\n type EventQueueMessage,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n MalformedEventQueueMessageError,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueReceipt,\n} from \"./queue\";\n\n/**\n * The **Event lane**'s consumer runner (ADR-0053 decisions 6 and 7): the library defines it, the app hosts it.\n *\n * `defineEventConsumer` returns a `start()`/`stop()` handle the app runs in its OWN long-lived Bun process —\n * the toolkit's first long-lived server artifact, deliberately separate from `createSyncServer`'s\n * zero-startup-query serverless posture. There is no supervisor, no CLI entrypoint, no daemon and no signal\n * handling here: the app owns its process lifecycle and calls `stop()` from wherever it already handles\n * shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside\n * `start()`.\n *\n * One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in\n * one stream must never head-of-line-block another), so small deployments run one process and large ones split\n * `streams` across processes.\n *\n * **Pacing is adaptive interval polling, and it is INTERNAL** (ADR-0053 decision 7 — out of consumer-app design\n * space by ratified requirement; only the floor/ceiling/factor are exposed as tuning, never as contract):\n *\n * - a NON-EMPTY read is followed by an immediate re-read, so a backlog drains back-to-back;\n * - consecutive EMPTY reads grow the wait from a floor ({@link DEFAULT_EVENT_POLL_FLOOR_MS}) toward an idle\n * ceiling ({@link DEFAULT_EVENT_POLL_CEILING_MS}) by {@link DEFAULT_EVENT_POLL_FACTOR};\n * - one non-empty read resets the wait to the floor.\n *\n * LISTEN/NOTIFY and `pgmq.read_with_poll` long-polling are REJECTED as wake mechanisms (ADR-0053, maintainer\n * decision): Bun's native `SQL` — the sanctioned Postgres driver — has no LISTEN/NOTIFY, and both mechanisms\n * hold a connection per stream through the transaction poolers the consumers' stacks run behind. Because\n * pacing is internal, the mechanism can change later without any contract change.\n *\n * **Leases are RENEWED while a read is being worked through; a thrown sub-batch's lease is deliberately left\n * to lapse** (ADR-0053 decision 7: visibility renewal is internal). One read makes up to `batchSize` messages\n * invisible at once, so the timeout cannot be \"the processing budget\": ten ordinary ten-second callbacks\n * would outlive a 60-second window for the later messages, and in a documented multi-runner deployment\n * another process would pick them up while the first is still working toward them. So for as long as a read\n * is in flight the runner extends EVERY not-yet-settled receipt of that read — the one running plus the ones\n * still queued behind it — every `visibilityTimeoutSeconds / 2`. Renewal is best-effort: a failure is\n * warn-logged and the loop carries on, because redelivery is the safety net it would fall back on anyway.\n *\n * `visibilityTimeoutSeconds` therefore means two retry-shaped things, never a budget:\n *\n * - **the redelivery delay of a FAILED sub-batch.** A callback that throws is not acked AND is dropped from\n * renewal immediately, so its lease lapses and the queue redelivers it with an incremented `deliveryCount`.\n * That lapse IS the retry pacing — the runner never sleeps \"on behalf of\" a failed message, and if a\n * backend ever wants exponential redelivery backoff it belongs INSIDE that backend, behind the\n * {@link EventQueue} seam, so the runner stays backend-agnostic;\n * - **the crash-recovery bound.** A runner that dies takes its renewals with it, so everything it held comes\n * back one timeout later.\n *\n * **A graceful stop does not cancel renewal — it narrows it.** `stop()` starts no further read and no further\n * callback, but the callbacks already in flight are AWAITED and then acked, so their receipts must stay\n * invisible until they settle: cancelling renewal at `stop()` would hand a second runner the very message\n * this one is deliberately finishing, on every ordinary SIGTERM/rollout. What IS released at `stop()` is the\n * rest of that read — the messages no callback has started — which drop out of the renewal set so their\n * leases lapse and the queue redelivers them promptly. `stop()` therefore resolves only once every in-flight\n * callback has settled AND its renewal task has shut down.\n *\n * **The SECOND pacing mode: `drainOnce()`, for hosts that cannot hold a process** (ADR-0053 amendment,\n * 2026-08-02). Everything above describes the primary mode. A serverless-only deployment — managed\n * Supabase, whose edge functions are the only compute — has nowhere to put a `start()`; its queue would\n * simply never drain. So the SAME handle also answers `drainOnce({ budgetMs })`: one bounded pass that\n * reads/delivers/acks through the identical internals until every stream reads empty or the wall-clock\n * budget runs out. Nothing about the delivery contract moves — at-least-once, batch-internal order only,\n * dead-lettering to the backend's archive are all the same code — because pacing was internal from the\n * start (decision 7), which is exactly what makes this a HOSTING addition rather than a contract change.\n * The long-lived runner remains the primary mode; `drainOnce` is what a scheduled invocation calls.\n */\n\n/** Max messages (each ONE single-stream sub-batch) a single read delivers, when the app sets nothing. */\nexport const DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;\n/**\n * How long a delivered sub-batch stays invisible, when the app sets nothing — and how long the runner extends\n * it by on each renewal (it renews at half this). Healthy long processing is covered by renewal, so this is\n * the REDELIVERY DELAY of a sub-batch whose callback threw and the crash-recovery bound, not a budget: it\n * wants to sit above a single callback's worst case (too short redelivers a callback that is merely slower\n * than one renewal interval), never above the whole batch's.\n */\nexport const DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;\n/** Deliveries a sub-batch gets before a further callback failure dead-letters it, when the app sets nothing. */\nexport const DEFAULT_EVENT_MAX_ATTEMPTS = 5;\n/** The adaptive poll's floor — the wait after the FIRST empty read (ADR-0053 decision 7: ~250 ms). */\nexport const DEFAULT_EVENT_POLL_FLOOR_MS = 250;\n/** The adaptive poll's idle ceiling — the longest an idle stream ever waits between reads. */\nexport const DEFAULT_EVENT_POLL_CEILING_MS = 5_000;\n/** How fast consecutive empty reads grow the wait from the floor toward the ceiling. */\nexport const DEFAULT_EVENT_POLL_FACTOR = 2;\n/**\n * The wall-clock budget one {@link EventConsumer.drainOnce} pass gets, when the caller sets nothing.\n *\n * **Set it under your platform's invocation wall-clock cap**, with head-room for one callback: the budget is\n * only ever checked BETWEEN sub-batches, so a pass can overrun it by however long the callback that was\n * already running takes. 25 s suits the common serverless caps (Supabase Edge, Vercel, Cloud Run jobs); a\n * platform with a tighter cap wants a tighter budget, and a generous one (a cron container) can raise it.\n */\nexport const DEFAULT_EVENT_DRAIN_BUDGET_MS = 25_000;\n\n/**\n * Adaptive-poll tuning. Defaults are the ADR's; they are TUNING, not contract — the pacing mechanism itself is\n * internal and may change.\n */\nexport interface EventConsumerPollOptions {\n /** The wait after the first empty read. Defaults to {@link DEFAULT_EVENT_POLL_FLOOR_MS}. */\n floorMs?: number;\n /** The longest wait an idle stream reaches. Defaults to {@link DEFAULT_EVENT_POLL_CEILING_MS}. */\n ceilingMs?: number;\n /** The growth factor per consecutive empty read. Defaults to {@link DEFAULT_EVENT_POLL_FACTOR}. */\n factor?: number;\n}\n\n/** One callback invocation: exactly ONE delivered queue message, i.e. one single-stream sub-batch. */\nexport interface EventConsumerBatch {\n /** The Event stream these events were appended under. */\n stream: string;\n /**\n * The stamped envelopes, EXACTLY as the ingestion endpoint enqueued them (ADR-0053 decision 5) — in append\n * order within this sub-batch. Across sub-batches there is no ordering promise (decision 6).\n */\n events: readonly StampedEvent[];\n}\n\n/**\n * The consumer callback. Returning (resolving) ACKS the sub-batch; THROWING retries it — the message stays\n * invisible until its visibility timeout lapses and the queue redelivers it.\n *\n * It MUST be idempotent (ADR-0053 decision 6, at-least-once): the blessed pattern is deduping on `eventId`\n * against the app's own durable store, which composes to effectively-exactly-once.\n */\nexport type EventConsumerCallback = (batch: EventConsumerBatch) => void | Promise<void>;\n\n/** What {@link DefineEventConsumerOptions.onDeadLetter} is told about a sub-batch the runner gave up on. */\nexport interface EventDeadLetterReport {\n stream: string;\n /** Why it was dead-lettered — the same reason recorded in the backend's dead-letter storage. */\n reason: string;\n /** Deliveries this message had received. `0` when the body was unreadable (nothing was ever delivered from it). */\n attempts: number;\n /** The receipt it was dead-lettered under — always present, including for an unparseable body. */\n receipt: EventQueueReceipt;\n /** The message, when it was readable. Absent for a malformed body (that is exactly what could not be parsed). */\n message?: EventQueueMessage;\n /** The error behind it: the callback's throw, or the {@link MalformedEventQueueMessageError}. */\n cause?: unknown;\n}\n\n/**\n * The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never\n * lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.\n */\nexport type EventConsumerSleep = (ms: number, signal: AbortSignal) => Promise<void>;\n\n/** What {@link EventConsumer.drainOnce} is tuned with. */\nexport interface EventDrainOptions {\n /**\n * The pass's wall-clock budget. Defaults to {@link DEFAULT_EVENT_DRAIN_BUDGET_MS}. Checked between\n * sub-batches only, never inside a callback — so size it under the invocation's cap with head-room for\n * one callback's worst case.\n */\n budgetMs?: number;\n}\n\n/** What one {@link EventConsumer.drainOnce} pass reports back. Counts are SUB-BATCHES (one queue message,\n * one callback invocation), the unit the queue and the dead-letter archive both work in. */\nexport interface EventDrainSummary {\n /**\n * Sub-batches whose callback completed during this pass. An ack that then failed still counts — the work\n * was delivered, and at-least-once means it may be delivered again later (the callback is idempotent).\n */\n delivered: number;\n /** Sub-batches this pass moved to the backend's dead-letter storage. */\n deadLettered: number;\n /**\n * `true` when every configured Event stream read empty before the budget ran out — the queue is drained\n * as far as this pass can see.\n *\n * `false` means the pass ended with work possibly still queued: the budget cut it short, or a stream's\n * read faulted. It is the caller's signal that another tick has something to do — a scheduler that\n * chains passes should invoke again promptly rather than waiting out its full period.\n */\n empty: boolean;\n}\n\nexport interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry> {\n /** The sync registry whose `streams` this runner consumes. */\n registry: TRegistry;\n /**\n * The queue to consume from — REQUIRED, and the reason the runner is backend-agnostic by construction. The\n * ordinary wiring is `createPgmqEventQueue({ db })` with the app's own drizzle handle; constructing it here\n * from a `db` option would bake the shipped backend into the runner for one line of ergonomics.\n */\n queue: EventQueue;\n callback: EventConsumerCallback;\n /**\n * Narrow to a subset of the registered Event streams — the knob that splits streams across processes.\n * Defaults to ALL registered streams. An unknown name is a definition-time throw (fail-closed): a runner\n * that silently consumed nothing is the failure mode this forbids.\n */\n streams?: readonly string[];\n /** Max messages per read. Defaults to {@link DEFAULT_EVENT_CONSUMER_BATCH_SIZE}. */\n batchSize?: number;\n /**\n * The delivered-message invisibility window, renewed at half of it while the runner is still working\n * through a read. Defaults to {@link DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS}. Size it above ONE\n * callback's worst case (renewal covers the rest of the batch), not above the whole batch's.\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Max CONCURRENT callback invocations per Event stream. Defaults to `1` (strictly sequential). Values above 1\n * are safe for the idempotent callback the lane already requires: ADR-0053 decision 6 disclaims any ordering\n * across sub-batches precisely so concurrency is available. Reads stay serial — only the callbacks of one\n * delivered read run in parallel.\n */\n concurrency?: number;\n /**\n * Deliveries a sub-batch gets before a further callback failure dead-letters it. Defaults to\n * {@link DEFAULT_EVENT_MAX_ATTEMPTS}. A malformed body never gets attempts — it dead-letters on sight.\n */\n maxAttempts?: number;\n /** Adaptive-poll tuning. See {@link EventConsumerPollOptions}. */\n poll?: EventConsumerPollOptions;\n /**\n * Notified for every dead-lettered sub-batch. The runner ALSO warn-logs each one unconditionally: loudness is\n * the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.\n */\n onDeadLetter?: (report: EventDeadLetterReport) => void;\n /** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */\n sleep?: EventConsumerSleep;\n /** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */\n now?: () => number;\n /**\n * @internal The injectable RENEWAL wait, deliberately a second seam rather than `sleep`: the two cadences\n * are independent (one paces reads, one paces lease renewal) and sharing one would make every pacing\n * assertion depend on renewal timing. Defaults to `setTimeout`.\n */\n renewalSleep?: EventConsumerSleep;\n}\n\nexport interface EventConsumer {\n /**\n * Begin every stream's loop. Idempotent; a no-op after {@link EventConsumer.stop}. Throws while a\n * {@link EventConsumer.drainOnce} pass is in flight — one handle drives one pacing mode at a time.\n */\n start: () => void;\n /**\n * Graceful stop: no new reads, no new callbacks, in-flight callbacks are awaited (and their leases KEPT\n * renewed until they ack or dead-letter), and the promise resolves when every loop — and every renewal\n * task it still owned — is quiet. Safe to call twice (the second call awaits the first). Messages of an\n * in-progress read whose callback had not started are released at once: they stop being renewed and are\n * left unacked, so at-least-once redelivers them as soon as their lease lapses.\n *\n * A `drainOnce` pass in flight is treated the same way: it starts no further read, finishes the callback\n * it is on, and `stop()` resolves once it has.\n */\n stop: () => Promise<void>;\n /**\n * One bounded drain pass — the pacing mode for a host that cannot hold a process (ADR-0053 amendment,\n * 2026-08-02).\n *\n * It walks every configured Event stream, read → deliver → ack, and keeps going until EITHER every stream\n * has returned an empty read OR the wall-clock budget is spent. Same internals as the loop mode\n * throughout: the same read/deliver/ack path, the same lease renewal while a callback runs, the same\n * per-sub-batch retry-by-lapsing-lease, the same dead-lettering after `maxAttempts` with the same\n * `onDeadLetter` hook and unconditional warn log. It never sleeps: a stream that reads empty is finished\n * for this pass, and there is no adaptive interval to wait out.\n *\n * **The budget is checked BETWEEN sub-batches, never inside one.** A callback already running is awaited\n * and acked exactly as the runner would (its lease stays renewed throughout), and no new read starts once\n * the budget is gone — so a pass can overrun its budget by one callback, and `budgetMs` must leave\n * head-room for that under the platform's invocation cap. A sub-batch whose callback THROWS near the\n * budget edge is not special-cased: it is left unacked and dropped from renewal, its lease lapses, and the\n * queue redelivers it on a later pass with an incremented delivery count. That is at-least-once working as\n * designed, not a lost event — and it is why the callback must be idempotent.\n *\n * **Hosting it.** Wire a SCHEDULED invocation (a platform cron, e.g. every 10 s) that calls `drainOnce`\n * and, optionally, an ingest-side nudge (`createSyncServer({ onEventsEnqueued })` firing a\n * fetch-and-forget at the same endpoint) so an interactive append is drained in milliseconds instead of\n * waiting for the next tick. The **schedule is the delivery guarantee; the nudge is only latency** — a\n * lost nudge costs nothing but time. Overlapping invocations are SAFE: two processes reading the same\n * queue are arbitrated by the visibility timeout, exactly as two long-lived runners would be. (Two passes\n * on ONE handle are not — that is a bug, and throws; see below.)\n *\n * **One handle, one pacing mode.** Throws if `start()` is live, if another `drainOnce` is already in\n * flight on this handle, or if the handle has been stopped — the lifecycle is one-way, so the next drain\n * builds a fresh `defineEventConsumer` (construction is query-free, so that costs nothing).\n */\n drainOnce: (options?: EventDrainOptions) => Promise<EventDrainSummary>;\n}\n\n/**\n * The adaptive wait for `idleCount` CONSECUTIVE unproductive reads (an empty read or a queue fault), clamped to\n * the ceiling. `idleCount` is 1 for the first one; a productive read resets it to 0 and re-reads immediately.\n */\nexport function computeEventPollWaitMs(idleCount: number, options: EventConsumerPollOptions = {}): number {\n const floorMs = options.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS;\n const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS;\n const factor = options.factor ?? DEFAULT_EVENT_POLL_FACTOR;\n const exponent = Math.max(idleCount - 1, 0);\n return Math.min(Math.round(floorMs * factor ** exponent), ceilingMs);\n}\n\n/** The production wait: a `setTimeout` that is CLEARED on abort, so `stop()` never leaves a timer holding the process open. */\nconst abortableSleep: EventConsumerSleep = (ms, signal) =>\n new Promise<void>((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n let handle: ReturnType<typeof setTimeout> | undefined;\n const finish = (): void => {\n if (handle !== undefined) {\n clearTimeout(handle);\n }\n signal.removeEventListener(\"abort\", finish);\n resolve();\n };\n handle = setTimeout(finish, ms);\n signal.addEventListener(\"abort\", finish, { once: true });\n });\n\nfunction assertPositive(label: string, value: number, minimum: number): number {\n if (!Number.isFinite(value) || value < minimum) {\n throw new Error(\n `pgxsinkit: defineEventConsumer's \\`${label}\\` must be a finite number >= ${minimum} (got ${value}).`,\n );\n }\n return value;\n}\n\nexport function defineEventConsumer<TRegistry extends SyncTableRegistry>(\n options: DefineEventConsumerOptions<TRegistry>,\n): EventConsumer {\n // ─── Definition-time resolution (fail-closed, and query-free) ────────────────────────────────────────\n const registered = getSyncRegistryStreams(options.registry) ?? {};\n const registeredNames = Object.keys(registered);\n if (registeredNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is nothing for a consumer runner to \" +\n \"consume. Register one with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n\n let streams: string[];\n if (options.streams) {\n const unknown = options.streams.filter((stream) => !Object.hasOwn(registered, stream));\n if (unknown.length > 0) {\n // Every offender is named: a typo'd stream on a runner would otherwise present as \"the events never\n // arrive\", which is the most expensive shape of silence in the lane.\n throw new Error(\n `pgxsinkit: defineEventConsumer was asked for Event stream(s) [${unknown.join(\", \")}] this registry ` +\n `does not register — it registers [${registeredNames.join(\", \")}].`,\n );\n }\n streams = [...new Set(options.streams)];\n if (streams.length === 0) {\n throw new Error(\n \"pgxsinkit: defineEventConsumer was given an empty `streams` list. Omit it to consume every registered \" +\n \"Event stream, or name at least one.\",\n );\n }\n } else {\n streams = registeredNames;\n }\n\n const batchSize = assertPositive(\"batchSize\", options.batchSize ?? DEFAULT_EVENT_CONSUMER_BATCH_SIZE, 1);\n const visibilityTimeoutSeconds = assertPositive(\n \"visibilityTimeoutSeconds\",\n options.visibilityTimeoutSeconds ?? DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n 1,\n );\n const concurrency = assertPositive(\"concurrency\", options.concurrency ?? 1, 1);\n const maxAttempts = assertPositive(\"maxAttempts\", options.maxAttempts ?? DEFAULT_EVENT_MAX_ATTEMPTS, 1);\n const poll = options.poll ?? {};\n const floorMs = assertPositive(\"poll.floorMs\", poll.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS, 0);\n const ceilingMs = assertPositive(\"poll.ceilingMs\", poll.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS, floorMs);\n const factor = assertPositive(\"poll.factor\", poll.factor ?? DEFAULT_EVENT_POLL_FACTOR, 1);\n const pollOptions: EventConsumerPollOptions = { floorMs, ceilingMs, factor };\n\n const queue = options.queue;\n const sleep = options.sleep ?? abortableSleep;\n const renewalSleep = options.renewalSleep ?? abortableSleep;\n const now = options.now ?? Date.now;\n /** Renew at HALF the window: one missed renewal still leaves a full half-window of head-room. */\n const renewalIntervalMs = Math.max(1, Math.floor((visibilityTimeoutSeconds * 1000) / 2));\n\n // ─── Lifecycle state ─────────────────────────────────────────────────────────────────────────────────\n const stopController = new AbortController();\n let started = false;\n let stopping = false;\n let loops: Promise<void>[] = [];\n let stopPromise: Promise<void> | null = null;\n /** The in-flight bounded drain, if any — the second pacing mode's whole lifecycle state. */\n let activeDrain: Promise<EventDrainSummary> | null = null;\n /**\n * The counters of the drain pass in flight, or `null` in loop mode. The settle points below feed it\n * rather than returning counts, so `drainOnce` reports on the SAME delivery path the runner uses instead\n * of a parallel one. Exactly one pass can be in flight (the mode is mutually exclusive), so one slot is\n * all this needs.\n */\n let drainStats: { delivered: number; deadLettered: number } | null = null;\n\n // ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────\n const reportDeadLetter = (report: EventDeadLetterReport): void => {\n // Unconditional, and deliberately not the client report surface's \"warn only when nobody subscribed\"\n // rule: a dead letter is rare and terminal, so it is worth a line in the operator's log even when the\n // app also handles it.\n console.warn(\n `pgxsinkit: dead-lettered an event sub-batch on Event stream \"${report.stream}\" (receipt ${report.receipt}, ` +\n `${report.attempts} delivery attempt(s)) — ${report.reason}. It is in the queue's dead-letter storage; ` +\n \"requeue it deliberately with `requeueDeadLetter` once the cause is fixed.\",\n report.cause,\n );\n if (!options.onDeadLetter) {\n return;\n }\n try {\n options.onDeadLetter(report);\n } catch (error) {\n console.error(\"pgxsinkit: the `onDeadLetter` hook threw; the message is dead-lettered regardless\", error);\n }\n };\n\n /** Move one message to dead-letter storage and report it. Resolves `false` when the QUEUE refused the move. */\n const deadLetter = async (\n stream: string,\n receipt: EventQueueReceipt,\n attempts: number,\n reason: string,\n cause: unknown,\n message?: EventQueueMessage,\n ): Promise<boolean> => {\n try {\n await queue.deadLetter(stream, [receipt], reason);\n } catch (error) {\n // The message is still queued and still invisible; it redelivers and dead-letters on a later pass.\n console.warn(\n `pgxsinkit: could not dead-letter message ${receipt} on Event stream \"${stream}\"; it stays queued and ` +\n \"will be retried\",\n error,\n );\n return false;\n }\n if (drainStats) {\n drainStats.deadLettered += 1;\n }\n reportDeadLetter({ stream, reason, attempts, receipt, ...(message ? { message } : {}), cause });\n return true;\n };\n\n // ─── Lease renewal (ADR-0053 decision 7: internal, and not optional) ─────────────────────────────────\n /**\n * Keep every UNSETTLED receipt of one read invisible for as long as that read is being worked through.\n * Returns the stopper, which the caller awaits so no renewal outlives its read (a stray timer would hold\n * the app's process open, and a stray extension would delay a redelivery the runner no longer wants).\n *\n * Its lifetime is the READ's, deliberately NOT the runner's: this task is wired to its OWN controller and\n * never to `stopController`. A graceful stop still awaits the callbacks already in flight, so aborting\n * renewal there would let their leases lapse mid-callback and let another runner take the work this one is\n * finishing. `stop()` instead shrinks `unsettled` (see `processDelivered`), and the loop below exits on its\n * own the moment that set drains.\n */\n const startRenewal = (stream: string, unsettled: Set<EventQueueReceipt>): (() => Promise<void>) => {\n const controller = new AbortController();\n\n const task = (async () => {\n while (!controller.signal.aborted && unsettled.size > 0) {\n await renewalSleep(renewalIntervalMs, controller.signal);\n if (controller.signal.aborted || unsettled.size === 0) {\n return;\n }\n try {\n await queue.extendVisibility(stream, [...unsettled], visibilityTimeoutSeconds);\n } catch (error) {\n // Best-effort by design: the worst case of a failed renewal is the behaviour there would be with\n // no renewal at all — the lease lapses and the sub-batch is redelivered to an idempotent callback.\n console.warn(\n `pgxsinkit: could not renew the visibility lease on Event stream \"${stream}\" (receipts ` +\n `${[...unsettled].join(\", \")}); the sub-batch may be redelivered while it is still being processed`,\n error,\n );\n }\n }\n })();\n\n return async () => {\n controller.abort();\n await task;\n };\n };\n\n // ─── One delivered message ───────────────────────────────────────────────────────────────────────────\n const processMessage = async (\n stream: string,\n delivered: DeliveredEventMessage,\n /** Drop this message from the read's renewal set — it is settled, one way or the other. */\n settle: () => void,\n ): Promise<void> => {\n try {\n await options.callback({ stream, events: delivered.message.events });\n } catch (error) {\n // Settled the moment it throws, and settled FIRST: a failed sub-batch's lease is deliberately allowed\n // to lapse, because that lapse IS the retry pacing. Renewing it would postpone its own redelivery.\n settle();\n const detail = error instanceof Error ? error.message : String(error);\n if (delivered.deliveryCount >= maxAttempts) {\n await deadLetter(\n stream,\n delivered.receipt,\n delivered.deliveryCount,\n `the consumer callback failed on delivery ${delivered.deliveryCount} of ${maxAttempts}: ${detail}`,\n error,\n delivered.message,\n );\n return;\n }\n // NOT acked, and no longer renewed: the lapsing lease IS the retry pacing (see the module note).\n console.warn(\n `pgxsinkit: the event consumer callback failed for Event stream \"${stream}\" (receipt ${delivered.receipt}, ` +\n `delivery ${delivered.deliveryCount} of ${maxAttempts}); the sub-batch will be redelivered after its ` +\n `${visibilityTimeoutSeconds}s visibility timeout`,\n error,\n );\n return;\n }\n\n if (drainStats) {\n // Counted on the callback's success, before the ack: the work was delivered either way, and an ack\n // that fails only means at-least-once will deliver it again to an idempotent callback.\n drainStats.delivered += 1;\n }\n\n try {\n await queue.ack(stream, [delivered.receipt]);\n } catch (error) {\n // At-least-once's honest failure mode: the work succeeded but the ack did not, so the sub-batch will be\n // redelivered. The idempotent callback the lane requires is exactly what makes that harmless.\n console.warn(\n `pgxsinkit: could not ack message ${delivered.receipt} on Event stream \"${stream}\"; it will be ` +\n \"redelivered (the callback must be idempotent)\",\n error,\n );\n }\n // Settled either way: an acked message is gone, and one whose ack failed is meant to be redelivered.\n settle();\n };\n\n /**\n * Process one read's messages, at most `concurrency` callbacks at a time. Never throws.\n *\n * The renewal task spans the WHOLE read, not one callback: the messages queued behind the one in flight are\n * just as invisible, and they are precisely the ones a long first callback would otherwise let lapse.\n *\n * `halted` is the \"enter no further callback\" predicate — a graceful stop in loop mode, and additionally\n * the spent wall-clock budget under {@link EventConsumer.drainOnce}. It is consulted BETWEEN sub-batches\n * only, so whatever is already running is always awaited and settled first; the messages of this read no\n * callback ever entered are then released from renewal so their leases lapse and they redeliver at once,\n * rather than staying invisible behind work this pass will not do.\n */\n const processDelivered = async (\n stream: string,\n messages: readonly DeliveredEventMessage[],\n halted: () => boolean,\n ): Promise<void> => {\n const unsettled = new Set(messages.map((delivered) => delivered.receipt));\n const settleOf = (delivered: DeliveredEventMessage) => () => unsettled.delete(delivered.receipt);\n /** Receipts a callback has actually been entered for — the ones a graceful stop must keep renewing. */\n const startedReceipts = new Set<EventQueueReceipt>();\n /**\n * A graceful stop enters no further callback, so every message of this read the workers never reached is\n * released HERE: dropping it from the renewal set lets its lease lapse and the queue redeliver it at once,\n * instead of holding it invisible for as long as the in-flight callbacks still take. The started ones stay\n * in the set and keep being renewed until `processMessage` settles them.\n */\n const releaseUnstarted = (): void => {\n for (const delivered of messages) {\n if (!startedReceipts.has(delivered.receipt)) {\n unsettled.delete(delivered.receipt);\n }\n }\n };\n if (stopController.signal.aborted) {\n releaseUnstarted();\n } else {\n stopController.signal.addEventListener(\"abort\", releaseUnstarted, { once: true });\n }\n const stopRenewal = startRenewal(stream, unsettled);\n\n // The `halted` check and this call are one synchronous step, so a stop (or an expiring budget) can never\n // land between \"we decided to run it\" and \"it counts as started\".\n const runOne = async (delivered: DeliveredEventMessage): Promise<void> => {\n startedReceipts.add(delivered.receipt);\n await processMessage(stream, delivered, settleOf(delivered));\n };\n\n try {\n if (concurrency <= 1) {\n for (const delivered of messages) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n await runOne(delivered);\n }\n return;\n }\n\n let cursor = 0;\n const worker = async (): Promise<void> => {\n for (;;) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n const delivered = messages[cursor++];\n if (!delivered) {\n return;\n }\n await runOne(delivered);\n }\n };\n await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, worker));\n } finally {\n // Every callback of this read has settled by now (the workers await theirs), so the renewal task has\n // nothing left to protect — and `stop()`, which awaits this loop, therefore awaits the shutdown too.\n stopController.signal.removeEventListener(\"abort\", releaseUnstarted);\n await stopRenewal();\n }\n };\n\n // ─── One stream's loop ───────────────────────────────────────────────────────────────────────────────\n const runStream = async (stream: string): Promise<void> => {\n let idleCount = 0;\n\n while (!stopping) {\n let productive = false;\n try {\n const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n if (messages.length > 0) {\n productive = true;\n await processDelivered(stream, messages, () => stopping);\n }\n } catch (error) {\n if (error instanceof MalformedEventQueueMessageError) {\n // The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a\n // hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges\n // the stream: dead-letter exactly the named receipt, then re-read for the rest of the batch.\n productive = await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n } else {\n // A queue/database fault. A runner NEVER exits on a transient one — it backs off exactly like an\n // idle stream and keeps trying.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\"; backing off and retrying`,\n error,\n );\n }\n }\n\n if (productive) {\n // A backlog drains back-to-back: read again immediately, at the floor again once it runs dry.\n idleCount = 0;\n continue;\n }\n\n idleCount += 1;\n if (stopping) {\n break;\n }\n await sleep(computeEventPollWaitMs(idleCount, pollOptions), stopController.signal);\n }\n };\n\n // ─── One bounded drain pass (the serverless pacing mode) ─────────────────────────────────────────────\n /**\n * Read → deliver → ack across every stream until they all read empty or the budget is spent. Deliberately\n * built out of `processDelivered` and `deadLetter` — the loop mode's own path — so retry, renewal and\n * dead-lettering cannot drift between the two modes.\n */\n const runDrain = async (budgetMs: number): Promise<EventDrainSummary> => {\n const stats = { delivered: 0, deadLettered: 0 };\n drainStats = stats;\n const deadline = now() + budgetMs;\n /** Streams not yet known to be empty. A stream leaves the set on an empty read, or on a read fault. */\n const pending = new Set(streams);\n /** Anything that ended the pass with work possibly still queued — the `empty: false` reasons. */\n let unfinished = false;\n // Budget AND stop: a `stop()` during a pass must wind it down just as it winds down a loop.\n const halted = (): boolean => stopping || now() >= deadline;\n\n try {\n while (pending.size > 0) {\n if (halted()) {\n unfinished = true;\n break;\n }\n for (const stream of [...pending]) {\n if (halted()) {\n unfinished = true;\n break;\n }\n\n let messages: readonly DeliveredEventMessage[];\n try {\n messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n } catch (error) {\n if (error instanceof MalformedEventQueueMessageError) {\n // Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays\n // pending for the re-read that fetches the rest of the batch.\n await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n continue;\n }\n // A queue/database fault. The loop mode backs off and retries; a bounded pass has nothing to\n // back off INTO (it must not busy-spin against a broken queue for the whole budget), so the\n // stream is left for the next invocation and the pass reports itself unfinished.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\" during a bounded drain; ` +\n \"leaving it for the next pass\",\n error,\n );\n pending.delete(stream);\n unfinished = true;\n continue;\n }\n\n if (messages.length === 0) {\n pending.delete(stream);\n continue;\n }\n await processDelivered(stream, messages, halted);\n }\n }\n } finally {\n drainStats = null;\n }\n\n return { delivered: stats.delivered, deadLettered: stats.deadLettered, empty: !unfinished };\n };\n\n return {\n start: () => {\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: this event consumer is running a bounded `drainOnce()` pass, so `start()` cannot also \" +\n \"run its polling loops — one handle drives one pacing mode at a time. Await the pass first.\",\n );\n }\n if (started || stopping) {\n // Idempotent, and a no-op after `stop()` — the handle's lifecycle is one-way, matching the client's\n // flush driver. A restart is a new `defineEventConsumer`.\n return;\n }\n started = true;\n loops = streams.map((stream) =>\n // The catch is attached HERE, at creation: a loop is only awaited by `stop()`, so an unexpected\n // rejection must never be able to surface as an unhandled promise in the app's process.\n runStream(stream).catch((error: unknown) => {\n console.error(`pgxsinkit: the event consumer loop for Event stream \"${stream}\" ended unexpectedly`, error);\n }),\n );\n },\n\n stop: () => {\n stopping = true;\n stopController.abort();\n stopPromise ??= (async () => {\n await Promise.all(loops);\n loops = [];\n // A bounded pass is stopped like a loop: `halted()` already saw `stopping`, so it enters no further\n // callback — this just makes `stop()` resolve only once the one it was on has settled.\n await activeDrain?.catch(() => undefined);\n })();\n return stopPromise;\n },\n\n // Deliberately `async`, so every refusal below is a REJECTION rather than a synchronous throw from a\n // promise-returning function — a caller that only wired `.catch()` must not lose one.\n drainOnce: async (drainOptions = {}) => {\n if (started) {\n throw new Error(\n \"pgxsinkit: `drainOnce()` cannot run while this consumer's polling loops are live — one handle \" +\n \"drives one pacing mode at a time. Use the long-lived runner OR bounded drains, not both on one \" +\n \"handle. (Two separate PROCESSES draining the same queues concurrently is safe: the visibility \" +\n \"timeout arbitrates them.)\",\n );\n }\n if (stopping) {\n throw new Error(\n \"pgxsinkit: this event consumer handle is stopped — its lifecycle is one-way. Build a fresh \" +\n \"`defineEventConsumer` for the next drain pass; construction is query-free, so that costs nothing.\",\n );\n }\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: a `drainOnce()` pass is already in flight on this handle. Two SEPARATE PROCESSES \" +\n \"draining concurrently is safe (the queue's visibility timeouts arbitrate); two passes on one \" +\n \"handle would share its internal state, so it is refused. Await the first pass.\",\n );\n }\n\n const budgetMs = drainOptions.budgetMs ?? DEFAULT_EVENT_DRAIN_BUDGET_MS;\n if (!Number.isFinite(budgetMs) || budgetMs < 0) {\n throw new Error(`pgxsinkit: drainOnce's \\`budgetMs\\` must be a finite number >= 0 (got ${budgetMs}).`);\n }\n const pass = runDrain(budgetMs).finally(() => {\n activeDrain = null;\n });\n activeDrain = pass;\n return pass;\n },\n };\n}\n",
|
|
21
|
+
"import { getSyncRegistryStreams, hashString, quoteSqlLiteral, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { eventStreamQueueName } from \"./queue\";\n\n/**\n * The Event lane's **deploy-time** DDL (ADR-0053 decision 5): the pgmq extension plus one queue per registered\n * Event stream, derived from the registry.\n *\n * Provisioning is deploy-time and never runtime create-if-missing — the ingestion endpoint may enqueue long\n * before any consumer runner first starts, and a create-if-missing probe would put a query back in front of\n * the server's zero-startup-query posture.\n *\n * **pgmq assumptions** (read off pgmq's own extension SQL, and pinned by the integration lane):\n * - `CREATE EXTENSION IF NOT EXISTS pgmq` needs **no `CASCADE`**: pgmq's control file declares no `requires`.\n * (pg_partman is needed only for PARTITIONED queues, which this DDL never creates.) `CASCADE` would be\n * harmless but would also silently install whatever a future control file starts requiring.\n * - **No schema qualification is configurable**: the control file is `relocatable = false` with\n * `schema = 'pgmq'`, so the extension always lives in `pgmq` and every call is `pgmq.`-qualified.\n * - `pgmq.create()` is **idempotent**: it delegates to `create_non_partitioned`, whose tables and indexes are\n * `IF NOT EXISTS` and whose `pgmq.meta` insert is `ON CONFLICT DO NOTHING`. So the emitted statements need\n * no guard block and re-applying the migration is a no-op.\n *\n * The artifact is a MIGRATION body (raw SQL text) — `CREATE EXTENSION` and a SQL function call are outside\n * anything Drizzle's builders can express, which is the sanctioned raw-SQL case. Every interpolated queue\n * name is a registry-validated `[a-z][a-z0-9_]*` name, emitted through `quoteSqlLiteral`.\n */\n\n/** Stamped into the emitted DDL so `--check` can detect drift between the registry and a committed migration. */\nexport const EVENT_LANE_FINGERPRINT_PREFIX = \"pgxsinkit:events:fp1:\";\n\n/** The registered Event-stream names, SORTED — so the artifact and its fingerprint are registry-order-independent. */\nexport function eventLaneStreamNames(registry: SyncTableRegistry): string[] {\n return Object.keys(getSyncRegistryStreams(registry) ?? {}).sort();\n}\n\nfunction buildEventLaneDdlBody(streamNames: readonly string[]): string {\n const header =\n \"-- The pgxsinkit event lane's queues (ADR-0053 decision 5): one pgmq queue per registered Event stream.\\n\" +\n \"-- Provisioning is DEPLOY-TIME: the ingestion endpoint may enqueue long before any consumer runner starts.\\n\" +\n \"-- No CASCADE: pgmq's control file declares no `requires`. pgmq is non-relocatable (schema = 'pgmq').\\n\" +\n \"-- pgmq.create() is idempotent (IF NOT EXISTS tables/indexes + ON CONFLICT DO NOTHING meta), so\\n\" +\n \"-- re-applying this migration is a no-op and adding a stream only appends a line.\";\n\n const statements = streamNames.map(\n (stream) => `SELECT pgmq.create(${quoteSqlLiteral(eventStreamQueueName(stream))});`,\n );\n\n return `${header}\\nCREATE EXTENSION IF NOT EXISTS pgmq;\\n${statements.join(\"\\n\")}`;\n}\n\nfunction assertHasStreams(registry: SyncTableRegistry): string[] {\n const streamNames = eventLaneStreamNames(registry);\n if (streamNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is no event-lane DDL to emit. Register one \" +\n \"with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n return streamNames;\n}\n\n/**\n * The fingerprint the event-lane artifact carries for this registry. Derived from the emitted DDL body, so it\n * moves when a stream is added or removed (and when this generator's output changes) — and does NOT move for a\n * payload-schema change, which provisions nothing.\n */\nexport function eventLaneDdlFingerprint(registry: SyncTableRegistry): string {\n return EVENT_LANE_FINGERPRINT_PREFIX + hashString(buildEventLaneDdlBody(assertHasStreams(registry)));\n}\n\n/**\n * The full migration body: the DDL plus its fingerprint as a SQL comment. The comment is what\n * `pgxsinkit-generate --events --check` scans committed migrations for — the same pre-deploy drift detection\n * the apply-function artifact gets, minus the in-database stamp (there is no function here to comment on).\n */\nexport function renderEventLaneMigration(registry: SyncTableRegistry): string {\n const body = buildEventLaneDdlBody(assertHasStreams(registry));\n return `-- ${EVENT_LANE_FINGERPRINT_PREFIX + hashString(body)}\\n${body}`;\n}\n"
|
|
16
22
|
],
|
|
17
|
-
"mappings": ";;AAAA;AAAA;AAAA;AAAA;;;ACcO,SAAS,iBAAiB,CAAC,SAAkB,SAA2C;AAAA,EAC7F,MAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ;AAAA,EAC3C,IAAI,CAAC,QAAQ;AAAA,IACX,OAAO;AAAA,EACT;AAAA,EACA,OAAO,QAAQ,SAAS,GAAG,KAAK,QAAQ,SAAS,MAAM,IAAI,SAAS;AAAA;;;ADgCtE,IAAM,UAAU,MAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAWzF,IAAM,2BAA2B;AAUjC,eAAsB,yBAAyB,CAC7C,SACA,QACA,SACmB;AAAA,EACnB,IAAI,QAAQ,QAAQ,QAAQ,WAAW,WAAW;AAA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