@pgxsinkit/server 0.1.31 → 0.1.36

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.
Files changed (52) hide show
  1. package/README.md +12 -0
  2. package/bin/pgxsinkit-generate.mjs +25 -0
  3. package/dist/cli/generate.d.ts +14 -2
  4. package/dist/cli/generate.d.ts.map +1 -1
  5. package/dist/electric-proxy.d.ts +30 -2
  6. package/dist/electric-proxy.d.ts.map +1 -1
  7. package/dist/index.d.ts +56 -9
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3935 -936
  10. package/dist/index.js.map +40 -25
  11. package/dist/migrations/utilities.d.ts +13 -0
  12. package/dist/migrations/utilities.d.ts.map +1 -0
  13. package/dist/mutations/plpgsql-apply.d.ts +36 -0
  14. package/dist/mutations/plpgsql-apply.d.ts.map +1 -0
  15. package/dist/mutations/route.d.ts +64 -0
  16. package/dist/mutations/route.d.ts.map +1 -0
  17. package/dist/mutations/types.d.ts +4 -0
  18. package/dist/mutations/types.d.ts.map +1 -0
  19. package/dist/operations-log/ddl.d.ts +6 -0
  20. package/dist/operations-log/ddl.d.ts.map +1 -1
  21. package/dist/operations-log/schema.d.ts +2 -32
  22. package/dist/operations-log/schema.d.ts.map +1 -1
  23. package/dist/operations-log/types.d.ts +1 -5
  24. package/dist/operations-log/types.d.ts.map +1 -1
  25. package/dist/operations-log/writer.d.ts.map +1 -1
  26. package/dist/router.d.ts +22 -0
  27. package/dist/router.d.ts.map +1 -0
  28. package/dist/sql-state.d.ts +23 -0
  29. package/dist/sql-state.d.ts.map +1 -0
  30. package/package.json +15 -6
  31. package/skills/deploying/SKILL.md +162 -0
  32. package/src/cli/generate.ts +292 -21
  33. package/src/electric-proxy.ts +274 -42
  34. package/src/index.ts +146 -59
  35. package/src/migrations/utilities.ts +25 -0
  36. package/src/mutations/plpgsql-apply.ts +658 -0
  37. package/src/mutations/route.ts +1176 -0
  38. package/src/mutations/{bulk/types.ts → types.ts} +0 -2
  39. package/src/operations-log/ddl.ts +13 -3
  40. package/src/operations-log/schema.ts +9 -6
  41. package/src/operations-log/types.ts +1 -7
  42. package/src/operations-log/writer.ts +0 -2
  43. package/src/router.ts +109 -0
  44. package/src/sql-state.ts +59 -0
  45. package/dist/mutations/bulk/plpgsql-strategy.d.ts +0 -17
  46. package/dist/mutations/bulk/plpgsql-strategy.d.ts.map +0 -1
  47. package/dist/mutations/bulk/route.d.ts +0 -7
  48. package/dist/mutations/bulk/route.d.ts.map +0 -1
  49. package/dist/mutations/bulk/types.d.ts +0 -5
  50. package/dist/mutations/bulk/types.d.ts.map +0 -1
  51. package/src/mutations/bulk/plpgsql-strategy.ts +0 -370
  52. package/src/mutations/bulk/route.ts +0 -580
@@ -0,0 +1,1176 @@
1
+ import { and, eq, sql, type AnyRelations } from "drizzle-orm";
2
+ import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
3
+ import type { PgAsyncDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";
4
+ import { getColumns } from "drizzle-orm/utils";
5
+ import { createSchemaFactory } from "drizzle-orm/zod";
6
+
7
+ import type {
8
+ AuthoritativeWriteRequest,
9
+ BatchMutationRequest,
10
+ JwtClaims,
11
+ MutationAck,
12
+ RegistryRelations,
13
+ SyncTableEntry,
14
+ SyncTableRegistry,
15
+ } from "@pgxsinkit/contracts";
16
+ import {
17
+ authoritativeWriteRequestSchema,
18
+ batchMutationRequestSchema,
19
+ getOmittedProjectedColumns as getOmittedProjectionColumns,
20
+ getProjectedColumns,
21
+ resolveServerVersionColumnName,
22
+ } from "@pgxsinkit/contracts";
23
+
24
+ import type { OperationsLogConfig } from "../operations-log/types";
25
+ import { logOperation, logOperationSafely } from "../operations-log/writer";
26
+ import type { FetchHandler } from "../router";
27
+ import { readSqlState } from "../sql-state";
28
+ import {
29
+ executePlpgsqlBatch,
30
+ expectedApplyFingerprint,
31
+ type MutationConflict,
32
+ verifyRlsAuthHelpers,
33
+ } from "./plpgsql-apply";
34
+ import type { TransactionClient } from "./types";
35
+
36
+ /**
37
+ * How the write path handles its remaining startup query class — the RLS auth-helper verify (ADR-0030
38
+ * decision 3). The apply-function drift guarantee moved into the call itself (self-verifying function),
39
+ * so this now governs ONLY that helper check:
40
+ * - `"in-process"` (default): keep today's boot-time `verifyRlsAuthHelpers` and its clear startup error.
41
+ * - `"deploy-time"`: skip it — the migration pipeline owns that guarantee, so a fresh (serverless)
42
+ * worker sends ZERO queries before the mutation transaction itself.
43
+ */
44
+ export type StartupVerificationMode = "in-process" | "deploy-time";
45
+
46
+ const { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({
47
+ coerce: { date: true },
48
+ });
49
+
50
+ type RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, "select">;
51
+
52
+ export const batchMutationPaths = ["/api/mutations", "/mutations"] as const;
53
+ /** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */
54
+ export const authoritativeMutationPaths = ["/api/mutations/unit", "/mutations/unit"] as const;
55
+
56
+ export function createMutationHandler<TRegistry extends SyncTableRegistry>(
57
+ db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,
58
+ registry: TRegistry,
59
+ operationsLogConfig: OperationsLogConfig,
60
+ operationsLogReady: Promise<void>,
61
+ resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null,
62
+ startupVerification: StartupVerificationMode = "in-process",
63
+ logTimings = false,
64
+ ): { batch: FetchHandler; authoritative: FetchHandler } {
65
+ let startupReadyPromise: Promise<void> | undefined;
66
+
67
+ // ADR-0030: the fingerprint this server expects for its registry + applier codegen, computed ONCE per
68
+ // server instance. Every `executePlpgsqlBatch` passes it so the installed apply function can verify
69
+ // itself in-body (SQLSTATE 'PXS01' on drift) — this replaces the deleted startup verify.
70
+ const expectedFingerprint = expectedApplyFingerprint(registry);
71
+
72
+ // Per-request timing scratch (opt-in). authMs/applyMs are filled at the narrow phase call sites inside
73
+ // the handler; totalMs + status are measured by `withTiming` wrapping the returned handler. A fresh
74
+ // object per request keeps this concurrency-safe without threading state through the handler internals.
75
+ const perfNow = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
76
+ interface RequestTiming {
77
+ handlerStart: number;
78
+ preTxMs: number;
79
+ txOpenMs: number;
80
+ authMs: number;
81
+ applyMs: number;
82
+ mutations: number;
83
+ }
84
+ const withTiming = (route: string, handler: (request: Request, timing?: RequestTiming) => Promise<Response>) => {
85
+ if (!logTimings) {
86
+ return (request: Request) => handler(request);
87
+ }
88
+ return async (request: Request): Promise<Response> => {
89
+ const start = perfNow();
90
+ const timing: RequestTiming = {
91
+ handlerStart: start,
92
+ preTxMs: 0,
93
+ txOpenMs: 0,
94
+ authMs: 0,
95
+ applyMs: 0,
96
+ mutations: 0,
97
+ };
98
+ const response = await handler(request, timing);
99
+ console.log(
100
+ "[pgxsinkit-timing]",
101
+ JSON.stringify({
102
+ route,
103
+ preTxMs: Math.round(timing.preTxMs),
104
+ txOpenMs: Math.round(timing.txOpenMs),
105
+ authMs: Math.round(timing.authMs),
106
+ applyMs: Math.round(timing.applyMs),
107
+ totalMs: Math.round(perfNow() - start),
108
+ mutations: timing.mutations,
109
+ status: response.status,
110
+ }),
111
+ );
112
+ return response;
113
+ };
114
+ };
115
+ // Stamp the two spans the phase timers cannot see: preTxMs = handler entry → transaction call
116
+ // (parse + zod validation), txOpenMs = transaction call → callback entry (the driver's LAZY
117
+ // connection establishment + BEGIN — on serverless this is where a fresh worker's pooler
118
+ // TLS/DNS cost lands, invisible to authMs/applyMs).
119
+ const stampPreTx = (timing: RequestTiming | undefined) => {
120
+ if (timing) timing.preTxMs = perfNow() - timing.handlerStart;
121
+ return timing ? perfNow() : 0;
122
+ };
123
+ const stampTxOpen = (timing: RequestTiming | undefined, txCallAt: number) => {
124
+ if (timing) timing.txOpenMs = perfNow() - txCallAt;
125
+ };
126
+
127
+ const startupReady = () => {
128
+ if (!startupReadyPromise) {
129
+ // ADR-0030: "deploy-time" skips the boot-time RLS auth-helper verify (the migration pipeline owns
130
+ // that guarantee), so a fresh worker sends no query here — combined with a declared operations-log
131
+ // posture, the first statement a serverless worker sends is the mutation transaction itself.
132
+ startupReadyPromise = startupVerification === "in-process" ? installStartupDdl(db, registry) : Promise.resolve();
133
+ }
134
+
135
+ return startupReadyPromise;
136
+ };
137
+
138
+ // Per-mutation payload validation shared by the batch and authoritative endpoints (security: both must
139
+ // reject client-omitted projection fields, server-managed fields, and malformed payloads before apply).
140
+ // Logs each offender and returns the attributable 400 Response, or null when every mutation is valid.
141
+ const validateMutationsOrRespond = async (
142
+ mutations: BatchMutationRequest["mutations"],
143
+ requestPath: string,
144
+ ): Promise<Response | null> => {
145
+ const validationErrors: string[] = [];
146
+ const invalidMutations: Array<{
147
+ mutation: BatchMutationRequest["mutations"][number];
148
+ message: string;
149
+ }> = [];
150
+
151
+ for (const mutation of mutations) {
152
+ if (!(mutation.tableName in registry)) {
153
+ const message = `Unknown table: ${mutation.tableName}`;
154
+ validationErrors.push(message);
155
+ invalidMutations.push({ mutation, message });
156
+ continue;
157
+ }
158
+
159
+ const entry = registry[mutation.tableName as keyof TRegistry]!;
160
+ const syncEntry = entry as SyncTableEntry;
161
+ const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);
162
+ // Surface (once per table+key) only a payload key the apply path would SILENTLY drop — a truly
163
+ // unknown key, never a projected-away/server-only column (those are 400-rejected just below, so
164
+ // the helper excludes them; warning "the write succeeds" then rejecting was the misleading overlap).
165
+ warnOnSilentlyDroppedPayloadKeys(syncEntry, mutation.tableName, mutation.kind, normalizedPayload);
166
+ const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
167
+
168
+ if (projectedFieldViolations.length > 0) {
169
+ const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(", ")}`;
170
+ validationErrors.push(message);
171
+ invalidMutations.push({ mutation, message });
172
+ continue;
173
+ }
174
+
175
+ const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
176
+
177
+ if (managedFieldViolations.length > 0) {
178
+ const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
179
+ validationErrors.push(message);
180
+ invalidMutations.push({ mutation, message });
181
+ continue;
182
+ }
183
+
184
+ try {
185
+ if (mutation.kind === "update") {
186
+ const payloadKeys =
187
+ typeof normalizedPayload === "object" && normalizedPayload !== null
188
+ ? Object.keys(normalizedPayload as object)
189
+ : [];
190
+ if (payloadKeys.length === 0) {
191
+ throw new Error("At least one field must be provided");
192
+ }
193
+ createMutationInsertSchema(syncEntry.table as AnyPgTable)
194
+ .partial()
195
+ .parse(normalizedPayload);
196
+ } else if (mutation.kind === "create") {
197
+ buildCreateValidationSchema(syncEntry).parse(normalizedPayload);
198
+ }
199
+ // delete has no payload to validate
200
+ } catch (error) {
201
+ const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : "";
202
+ const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;
203
+ validationErrors.push(message);
204
+ invalidMutations.push({ mutation, message });
205
+ }
206
+ }
207
+
208
+ if (validationErrors.length > 0) {
209
+ for (const invalidMutation of invalidMutations) {
210
+ await logOperationSafely(db, operationsLogConfig, {
211
+ tableName: invalidMutation.mutation.tableName,
212
+ operationKind: invalidMutation.mutation.kind,
213
+ entityKey: invalidMutation.mutation.entityKey,
214
+ payload: invalidMutation.mutation.payload,
215
+ status: "validation_failed",
216
+ errorMessage: invalidMutation.message,
217
+ httpStatus: 400,
218
+ mutationId: invalidMutation.mutation.mutationId,
219
+ mutationSeq: invalidMutation.mutation.mutationSeq,
220
+ clientTimestampUs: invalidMutation.mutation.clientTimestampUs,
221
+ requestPath: requestPath,
222
+ });
223
+ }
224
+
225
+ // Attribute the rejection to the specific offending mutations. The batch is atomic
226
+ // (nothing was applied), so the client can quarantine exactly these and keep the
227
+ // innocent siblings retryable — one bad mutation never poisons the whole offline queue.
228
+ return Response.json(
229
+ {
230
+ message: `Payload validation failed: ${validationErrors.join("; ")}`,
231
+ rejections: invalidMutations.map(({ mutation, message }) => ({
232
+ tableName: mutation.tableName,
233
+ mutationId: mutation.mutationId,
234
+ mutationSeq: mutation.mutationSeq,
235
+ reason: message,
236
+ })),
237
+ },
238
+ { status: 400 },
239
+ );
240
+ }
241
+
242
+ return null;
243
+ };
244
+
245
+ const handleBatchMutation = async (request: Request, timing?: RequestTiming): Promise<Response> => {
246
+ await Promise.all([startupReady(), operationsLogReady]);
247
+
248
+ const requestPath = new URL(request.url).pathname;
249
+ let rawBody: unknown;
250
+
251
+ try {
252
+ rawBody = await request.json();
253
+ } catch (error) {
254
+ await logOperationSafely(db, operationsLogConfig, {
255
+ tableName: null,
256
+ operationKind: null,
257
+ entityKey: null,
258
+ payload: null,
259
+ status: "validation_failed",
260
+ errorMessage: error instanceof Error ? error.message : "Invalid JSON request body",
261
+ httpStatus: 400,
262
+ requestPath: requestPath,
263
+ });
264
+
265
+ return Response.json(
266
+ {
267
+ message: "Invalid batch mutation request",
268
+ issues: [],
269
+ },
270
+ { status: 400 },
271
+ );
272
+ }
273
+
274
+ let body: BatchMutationRequest;
275
+
276
+ try {
277
+ body = batchMutationRequestSchema.parse(rawBody);
278
+ } catch (error) {
279
+ await logOperationSafely(db, operationsLogConfig, {
280
+ tableName: null,
281
+ operationKind: null,
282
+ entityKey: null,
283
+ payload: rawBody,
284
+ status: "validation_failed",
285
+ errorMessage: error instanceof Error ? error.message : "Invalid batch mutation request",
286
+ httpStatus: 400,
287
+ requestPath: requestPath,
288
+ });
289
+
290
+ return Response.json(
291
+ {
292
+ message: "Invalid batch mutation request",
293
+ issues: isValidationError(error) ? error.issues : [],
294
+ },
295
+ { status: 400 },
296
+ );
297
+ }
298
+
299
+ const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);
300
+ if (invalidResponse) {
301
+ return invalidResponse;
302
+ }
303
+
304
+ if (timing) timing.mutations = body.mutations.length;
305
+
306
+ const acks: MutationAck[] = [];
307
+ let actorUserId: string | null = null;
308
+ const rlsAuthContextRequired = isRlsAuthContextRequired(registry);
309
+
310
+ try {
311
+ const txCallAt = stampPreTx(timing);
312
+ await db.transaction(async (tx) => {
313
+ stampTxOpen(timing, txCallAt);
314
+ const shouldApplyRlsContext = rlsAuthContextRequired;
315
+ let userClaims: Record<string, unknown> = {};
316
+
317
+ if (shouldApplyRlsContext) {
318
+ const authStart = timing ? perfNow() : 0;
319
+ const resolvedClaims = await resolveAuthClaims?.(request);
320
+ if (timing) timing.authMs = perfNow() - authStart;
321
+
322
+ if (!isPlainObject(resolvedClaims)) {
323
+ await logOperationSafely(db, operationsLogConfig, {
324
+ tableName: null,
325
+ operationKind: null,
326
+ entityKey: null,
327
+ payload: rawBody,
328
+ status: "validation_failed",
329
+ errorMessage: "Missing validated JWT claims for RLS-enabled tables",
330
+ httpStatus: 401,
331
+ requestPath: requestPath,
332
+ });
333
+
334
+ throw new UnauthorizedBatchMutationError(
335
+ "RLS-enabled tables require validated JWT claims in request context",
336
+ );
337
+ }
338
+
339
+ userClaims = resolvedClaims;
340
+ actorUserId = getUuidClaim(userClaims, "sub");
341
+ }
342
+
343
+ const batchRequest = sanitizeRestrictedFields(body, registry);
344
+ await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);
345
+
346
+ const applyStart = timing ? perfNow() : 0;
347
+ const conflicts = await executePlpgsqlBatch(
348
+ tx as unknown as TransactionClient,
349
+ batchRequest,
350
+ requestPath,
351
+ false,
352
+ shouldApplyRlsContext,
353
+ userClaims,
354
+ expectedFingerprint,
355
+ );
356
+ if (timing) timing.applyMs = perfNow() - applyStart;
357
+
358
+ if (shouldApplyRlsContext) {
359
+ await tx.execute(sql`RESET ROLE`);
360
+ }
361
+
362
+ // ADR-0015: a reject-if-stale stale write was NOT applied — the applier returned it here.
363
+ // Surface a `conflicted` ack (distinct from a failure) carrying the row's current Server
364
+ // version, so the client keeps the optimistic overlay and resolves it as a new write.
365
+ const conflictByMutationId = new Map(conflicts.map((conflict) => [conflict.mutationId, conflict]));
366
+
367
+ for (const mutation of batchRequest.mutations) {
368
+ const conflict = conflictByMutationId.get(mutation.mutationId);
369
+
370
+ if (conflict) {
371
+ // #6: a null currentServerVersion means the target row no longer exists (an UPDATE whose
372
+ // row was deleted by another writer), distinct from a stale write over a row that moved.
373
+ const conflictReason =
374
+ conflict.currentServerVersion == null
375
+ ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no ` +
376
+ `longer exists on the server (deleted by another writer after this write was authored).`
377
+ : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +
378
+ `server version ${conflict.currentServerVersion} is ahead of the base ` +
379
+ `${mutation.baseServerVersion ?? "(unknown)"} this write was authored against.`;
380
+
381
+ await logOperation(tx, operationsLogConfig, {
382
+ tableName: mutation.tableName,
383
+ operationKind: mutation.kind,
384
+ entityKey: mutation.entityKey,
385
+ payload: mutation.payload,
386
+ status: "conflicted",
387
+ errorMessage: conflictReason,
388
+ httpStatus: 409,
389
+ mutationId: mutation.mutationId,
390
+ mutationSeq: mutation.mutationSeq,
391
+ clientTimestampUs: mutation.clientTimestampUs,
392
+ requestPath: requestPath,
393
+ userId: actorUserId,
394
+ });
395
+
396
+ acks.push({
397
+ tableName: mutation.tableName,
398
+ entityKey: mutation.entityKey,
399
+ mutationId: mutation.mutationId,
400
+ mutationSeq: mutation.mutationSeq,
401
+ status: "conflicted",
402
+ ...(conflict.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),
403
+ conflictReason,
404
+ httpStatus: 409,
405
+ });
406
+ continue;
407
+ }
408
+
409
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(
410
+ tx,
411
+ registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,
412
+ mutation.entityKey,
413
+ );
414
+
415
+ await logOperation(tx, operationsLogConfig, {
416
+ tableName: mutation.tableName,
417
+ operationKind: mutation.kind,
418
+ entityKey: mutation.entityKey,
419
+ payload: mutation.payload,
420
+ status: "succeeded",
421
+ httpStatus: 200,
422
+ mutationId: mutation.mutationId,
423
+ mutationSeq: mutation.mutationSeq,
424
+ clientTimestampUs: mutation.clientTimestampUs,
425
+ requestPath: requestPath,
426
+ userId: actorUserId,
427
+ });
428
+
429
+ acks.push({
430
+ tableName: mutation.tableName,
431
+ entityKey: mutation.entityKey,
432
+ mutationId: mutation.mutationId,
433
+ mutationSeq: mutation.mutationSeq,
434
+ status: "acked",
435
+ ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),
436
+ });
437
+ }
438
+ });
439
+ } catch (error) {
440
+ if (error instanceof UnauthorizedBatchMutationError) {
441
+ return Response.json({ message: error.message }, { status: 401 });
442
+ }
443
+
444
+ const errorMessage = formatBatchExecutionError(error);
445
+
446
+ for (const mutation of body.mutations) {
447
+ await logOperationSafely(db, operationsLogConfig, {
448
+ tableName: mutation.tableName,
449
+ operationKind: mutation.kind,
450
+ entityKey: mutation.entityKey,
451
+ payload: mutation.payload,
452
+ status: "execution_failed",
453
+ errorMessage,
454
+ httpStatus: 500,
455
+ mutationId: mutation.mutationId,
456
+ mutationSeq: mutation.mutationSeq,
457
+ clientTimestampUs: mutation.clientTimestampUs,
458
+ requestPath: requestPath,
459
+ userId: actorUserId,
460
+ });
461
+ }
462
+
463
+ return Response.json({ message: errorMessage }, { status: 500 });
464
+ }
465
+
466
+ return Response.json({ acks });
467
+ };
468
+
469
+ // ADR-0022 §3 (mechanism c): the authoritative (pessimistic) write endpoint. One write-**unit** per POST,
470
+ // applied in its OWN isolated transaction, atomically — so a constraint/trigger exception becomes a clean
471
+ // per-mutation `rejected` ack (the whole unit rolls back, overlays auto-discard) instead of the batch
472
+ // path's whole-batch 500, and a stale member surfaces `conflicted` (overlays kept) without partial apply.
473
+ const handleAuthoritativeWrite = async (request: Request, timing?: RequestTiming): Promise<Response> => {
474
+ await Promise.all([startupReady(), operationsLogReady]);
475
+
476
+ const requestPath = new URL(request.url).pathname;
477
+ let rawBody: unknown;
478
+
479
+ try {
480
+ rawBody = await request.json();
481
+ } catch (error) {
482
+ await logOperationSafely(db, operationsLogConfig, {
483
+ tableName: null,
484
+ operationKind: null,
485
+ entityKey: null,
486
+ payload: null,
487
+ status: "validation_failed",
488
+ errorMessage: error instanceof Error ? error.message : "Invalid JSON request body",
489
+ httpStatus: 400,
490
+ requestPath: requestPath,
491
+ });
492
+ return Response.json({ message: "Invalid authoritative write request", issues: [] }, { status: 400 });
493
+ }
494
+
495
+ let body: AuthoritativeWriteRequest;
496
+
497
+ try {
498
+ body = authoritativeWriteRequestSchema.parse(rawBody);
499
+ } catch (error) {
500
+ await logOperationSafely(db, operationsLogConfig, {
501
+ tableName: null,
502
+ operationKind: null,
503
+ entityKey: null,
504
+ payload: rawBody,
505
+ status: "validation_failed",
506
+ errorMessage: error instanceof Error ? error.message : "Invalid authoritative write request",
507
+ httpStatus: 400,
508
+ requestPath: requestPath,
509
+ });
510
+ return Response.json(
511
+ {
512
+ message: "Invalid authoritative write request",
513
+ issues: isValidationError(error) ? error.issues : [],
514
+ },
515
+ { status: 400 },
516
+ );
517
+ }
518
+
519
+ const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);
520
+ if (invalidResponse) {
521
+ return invalidResponse;
522
+ }
523
+
524
+ if (timing) timing.mutations = body.mutations.length;
525
+
526
+ const rlsAuthContextRequired = isRlsAuthContextRequired(registry);
527
+ let actorUserId: string | null = null;
528
+ // The unit's outcome, decided inside its OWN transaction: applied (Server versions per member) or
529
+ // conflicted (a stale member → rolled back, overlays kept). An execution exception is handled in catch.
530
+ let appliedServerVersions: Map<string, string | null> | null = null;
531
+ let unitConflicts: MutationConflict[] | null = null;
532
+
533
+ try {
534
+ const txCallAt = stampPreTx(timing);
535
+ await db.transaction(async (tx) => {
536
+ stampTxOpen(timing, txCallAt);
537
+ const shouldApplyRlsContext = rlsAuthContextRequired;
538
+ let userClaims: Record<string, unknown> = {};
539
+
540
+ if (shouldApplyRlsContext) {
541
+ const authStart = timing ? perfNow() : 0;
542
+ const resolvedClaims = await resolveAuthClaims?.(request);
543
+ if (timing) timing.authMs = perfNow() - authStart;
544
+
545
+ if (!isPlainObject(resolvedClaims)) {
546
+ await logOperationSafely(db, operationsLogConfig, {
547
+ tableName: null,
548
+ operationKind: null,
549
+ entityKey: null,
550
+ payload: rawBody,
551
+ status: "validation_failed",
552
+ errorMessage: "Missing validated JWT claims for RLS-enabled tables",
553
+ httpStatus: 401,
554
+ requestPath: requestPath,
555
+ });
556
+
557
+ throw new UnauthorizedBatchMutationError(
558
+ "RLS-enabled tables require validated JWT claims in request context",
559
+ );
560
+ }
561
+
562
+ userClaims = resolvedClaims;
563
+ actorUserId = getUuidClaim(userClaims, "sub");
564
+ }
565
+
566
+ const unitRequest = sanitizeRestrictedFields(body, registry);
567
+ await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);
568
+
569
+ const applyStart = timing ? perfNow() : 0;
570
+ const conflicts = await executePlpgsqlBatch(
571
+ tx as unknown as TransactionClient,
572
+ unitRequest,
573
+ requestPath,
574
+ false,
575
+ shouldApplyRlsContext,
576
+ userClaims,
577
+ expectedFingerprint,
578
+ );
579
+ if (timing) timing.applyMs = perfNow() - applyStart;
580
+
581
+ if (shouldApplyRlsContext) {
582
+ await tx.execute(sql`RESET ROLE`);
583
+ }
584
+
585
+ if (conflicts.length > 0) {
586
+ // The unit is atomic — a stale member means none of it applies. Roll back; report all members as
587
+ // conflicted (overlays kept, re-resolve the unit) below.
588
+ unitConflicts = conflicts;
589
+ throw new UnitNotCommittedError();
590
+ }
591
+
592
+ // Applied cleanly. Read each member's resulting Server version INSIDE the txn, before it commits.
593
+ const versions = new Map<string, string | null>();
594
+ for (const mutation of unitRequest.mutations) {
595
+ const version = await readServerUpdatedAtUs(
596
+ tx,
597
+ registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,
598
+ mutation.entityKey,
599
+ );
600
+ versions.set(mutation.mutationId, version ?? null);
601
+ }
602
+ appliedServerVersions = versions;
603
+ });
604
+ } catch (error) {
605
+ if (error instanceof UnauthorizedBatchMutationError) {
606
+ return Response.json({ message: error.message }, { status: 401 });
607
+ }
608
+
609
+ if (!(error instanceof UnitNotCommittedError)) {
610
+ // A DB-enforced invariant (capacity/quota/uniqueness constraint or trigger) declined the unit. The
611
+ // whole unit rolled back; surface a per-mutation `rejected` ack so the client auto-discards the
612
+ // unit's optimistic overlay (ADR-0022 §4). The ack carries a SANITISED reason — the raw DB error
613
+ // (constraint names, offending values/PII, schema, hints) stays in the operations log only.
614
+ const internalDetail = formatBatchExecutionError(error);
615
+ const publicReason = toPublicRejectionReason(error);
616
+ const rejectedAcks: MutationAck[] = [];
617
+ for (const mutation of body.mutations) {
618
+ await logOperationSafely(db, operationsLogConfig, {
619
+ tableName: mutation.tableName,
620
+ operationKind: mutation.kind,
621
+ entityKey: mutation.entityKey,
622
+ payload: mutation.payload,
623
+ status: "execution_failed",
624
+ errorMessage: internalDetail,
625
+ httpStatus: 409,
626
+ mutationId: mutation.mutationId,
627
+ mutationSeq: mutation.mutationSeq,
628
+ clientTimestampUs: mutation.clientTimestampUs,
629
+ requestPath: requestPath,
630
+ userId: actorUserId,
631
+ });
632
+ rejectedAcks.push({
633
+ tableName: mutation.tableName,
634
+ entityKey: mutation.entityKey,
635
+ mutationId: mutation.mutationId,
636
+ mutationSeq: mutation.mutationSeq,
637
+ status: "rejected",
638
+ rejectionReason: publicReason,
639
+ httpStatus: 409,
640
+ });
641
+ }
642
+ return Response.json({ acks: rejectedAcks });
643
+ }
644
+ // UnitNotCommittedError — `unitConflicts` is set; fall through to conflicted-ack building.
645
+ }
646
+
647
+ const acks: MutationAck[] = [];
648
+
649
+ if (unitConflicts) {
650
+ const conflictByMutationId = new Map(
651
+ (unitConflicts as MutationConflict[]).map((conflict) => [conflict.mutationId, conflict]),
652
+ );
653
+ for (const mutation of body.mutations) {
654
+ const conflict = conflictByMutationId.get(mutation.mutationId);
655
+ const conflictReason = conflict
656
+ ? conflict.currentServerVersion == null
657
+ ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no longer ` +
658
+ `exists on the server (deleted by another writer after this write was authored).`
659
+ : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +
660
+ `server version ${conflict.currentServerVersion} is ahead of the base ` +
661
+ `${mutation.baseServerVersion ?? "(unknown)"} this write was authored against.`
662
+ : `Atomic write-unit not committed (ADR-0022): a sibling write in the same unit was rejected as ` +
663
+ `stale, so this write rolled back too. Re-resolve the unit.`;
664
+
665
+ await logOperationSafely(db, operationsLogConfig, {
666
+ tableName: mutation.tableName,
667
+ operationKind: mutation.kind,
668
+ entityKey: mutation.entityKey,
669
+ payload: mutation.payload,
670
+ status: "conflicted",
671
+ errorMessage: conflictReason,
672
+ httpStatus: 409,
673
+ mutationId: mutation.mutationId,
674
+ mutationSeq: mutation.mutationSeq,
675
+ clientTimestampUs: mutation.clientTimestampUs,
676
+ requestPath: requestPath,
677
+ userId: actorUserId,
678
+ });
679
+
680
+ acks.push({
681
+ tableName: mutation.tableName,
682
+ entityKey: mutation.entityKey,
683
+ mutationId: mutation.mutationId,
684
+ mutationSeq: mutation.mutationSeq,
685
+ status: "conflicted",
686
+ ...(conflict?.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),
687
+ conflictReason,
688
+ httpStatus: 409,
689
+ });
690
+ }
691
+ return Response.json({ acks });
692
+ }
693
+
694
+ // Applied: ack every member, carrying the Server version each converged to.
695
+ const serverVersions = appliedServerVersions ?? new Map<string, string | null>();
696
+ for (const mutation of body.mutations) {
697
+ await logOperationSafely(db, operationsLogConfig, {
698
+ tableName: mutation.tableName,
699
+ operationKind: mutation.kind,
700
+ entityKey: mutation.entityKey,
701
+ payload: mutation.payload,
702
+ status: "succeeded",
703
+ httpStatus: 200,
704
+ mutationId: mutation.mutationId,
705
+ mutationSeq: mutation.mutationSeq,
706
+ clientTimestampUs: mutation.clientTimestampUs,
707
+ requestPath: requestPath,
708
+ userId: actorUserId,
709
+ });
710
+ const serverUpdatedAtUs = serverVersions.get(mutation.mutationId) ?? undefined;
711
+ acks.push({
712
+ tableName: mutation.tableName,
713
+ entityKey: mutation.entityKey,
714
+ mutationId: mutation.mutationId,
715
+ mutationSeq: mutation.mutationSeq,
716
+ status: "acked",
717
+ ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),
718
+ });
719
+ }
720
+
721
+ return Response.json({ acks });
722
+ };
723
+
724
+ return {
725
+ batch: withTiming("mutations", handleBatchMutation),
726
+ authoritative: withTiming("mutations", handleAuthoritativeWrite),
727
+ };
728
+ }
729
+
730
+ function isValidationError(error: unknown): error is { issues: unknown[] } {
731
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
732
+ }
733
+
734
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
735
+ return typeof value === "object" && value !== null && !Array.isArray(value);
736
+ }
737
+
738
+ function formatBatchExecutionError(error: unknown): string {
739
+ const rootCause = getRootCauseError(error);
740
+
741
+ if (!rootCause) {
742
+ return "Batch mutation failed";
743
+ }
744
+
745
+ const details = [rootCause.message];
746
+ const errorCode = getErrorStringProperty(rootCause, "code");
747
+ const errorDetail = getErrorStringProperty(rootCause, "detail");
748
+ const errorHint = getErrorStringProperty(rootCause, "hint");
749
+
750
+ if (errorCode) {
751
+ details.push(`code: ${errorCode}`);
752
+ }
753
+
754
+ if (errorDetail) {
755
+ details.push(`detail: ${errorDetail}`);
756
+ }
757
+
758
+ if (errorHint) {
759
+ details.push(`hint: ${errorHint}`);
760
+ }
761
+
762
+ return details.join(" | ");
763
+ }
764
+
765
+ /**
766
+ * Map a DB exception to a **client-safe** rejection reason for an authoritative `rejected` ack (ADR-0022 §4).
767
+ * The raw error text (`formatBatchExecutionError`) leaks constraint names, schema/table, the offending
768
+ * VALUES (potential PII), and trigger hints — and a `rejected` ack is success-path copy the app surfaces to
769
+ * users, so it must not echo that. Two cases:
770
+ *
771
+ * - **App-authored `RAISE`** (PL/pgSQL `RAISE EXCEPTION 'cohort is full'`, SQLSTATE `P0001` / a custom `P0…`
772
+ * class): the message IS the consumer's own user-facing copy — pass it through. This is the intended way
773
+ * to give a friendly capacity/quota message.
774
+ * - **Built-in integrity violations** (SQLSTATE class `23`) and everything else: return a stable generic
775
+ * message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.
776
+ */
777
+ export function toPublicRejectionReason(error: unknown): string {
778
+ const fallback = "The write was rejected by a server rule.";
779
+ const rootCause = getRootCauseError(error);
780
+
781
+ if (!rootCause) {
782
+ return fallback;
783
+ }
784
+
785
+ // Resolve the SQLSTATE with the driver-agnostic helper (bun-sql — this project's runtime driver —
786
+ // carries it on `errno`, not `code`; postgres.js / pg on `code`). Reading `error.code` directly, as
787
+ // this did, returned bun's generic "ERR_POSTGRES_SERVER_ERROR" and dropped every app-authored `P0…`
788
+ // and constraint code into the generic fallback, breaking ADR-0022's friendly rejection channel.
789
+ // `readSqlState` walks the cause chain itself, so it runs on the ORIGINAL error; the app-authored
790
+ // RAISE MESSAGE below still comes from the root cause.
791
+ const code = readSqlState(error);
792
+
793
+ // ADR-0030: the self-verifying apply function raises SQLSTATE 'PXS01' when its installed fingerprint
794
+ // does not match this server's registry/codegen — the drift the deleted startup verify used to catch.
795
+ // Surface the same actionable operator guidance the old startup error gave (it carries no PII, only the
796
+ // regenerate-and-apply instruction), rather than the generic rejection fallback.
797
+ if (code === "PXS01") {
798
+ return (
799
+ "The server's apply function is out of date: its installed fingerprint does not match this " +
800
+ "server's registry/codegen. Regenerate the sync-function migration (pgxsinkit-generate) and apply " +
801
+ "it before serving writes."
802
+ );
803
+ }
804
+
805
+ // App-authored RAISE — the message is the consumer's own copy, safe to surface.
806
+ if (code && (code === "P0001" || code.startsWith("P0"))) {
807
+ return rootCause.message.trim() || fallback;
808
+ }
809
+
810
+ // Built-in integrity violations: generic, code-keyed messages only (no raw constraint names / values).
811
+ const genericByCode: Record<string, string> = {
812
+ "23505": "This conflicts with an existing record (a uniqueness rule was violated).",
813
+ "23514": "A validation rule rejected this write.",
814
+ "23503": "A referenced record is missing (a relationship rule was violated).",
815
+ "23502": "A required value was missing.",
816
+ "23P01": "An exclusion rule rejected this write.",
817
+ };
818
+
819
+ if (code && genericByCode[code]) {
820
+ return genericByCode[code]!;
821
+ }
822
+
823
+ if (code && code.startsWith("23")) {
824
+ return "A data-integrity rule rejected this write.";
825
+ }
826
+
827
+ return fallback;
828
+ }
829
+
830
+ function getRootCauseError(error: unknown): Error | null {
831
+ let current = error;
832
+ let lastError: Error | null = null;
833
+ const seen = new Set<unknown>();
834
+
835
+ while (current instanceof Error && !seen.has(current)) {
836
+ seen.add(current);
837
+ lastError = current;
838
+ current = current.cause;
839
+ }
840
+
841
+ return lastError;
842
+ }
843
+
844
+ function getErrorStringProperty(error: Error, key: string): string | null {
845
+ if (!(key in error)) {
846
+ return null;
847
+ }
848
+
849
+ const value = (error as unknown as Record<string, unknown>)[key];
850
+ return typeof value === "string" && value.length > 0 ? value : null;
851
+ }
852
+
853
+ function isRlsAuthContextRequired(registry: SyncTableRegistry): boolean {
854
+ return Object.values(registry).some(
855
+ (entry) =>
856
+ getTableConfig(entry.table as AnyPgTable).policies.length > 0 ||
857
+ (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authClaim"),
858
+ );
859
+ }
860
+
861
+ class UnauthorizedBatchMutationError extends Error {}
862
+
863
+ /**
864
+ * Thrown inside the authoritative write's transaction to roll the whole unit back when a member is a stale
865
+ * write (ADR-0015) — distinct from an execution exception (a capacity/constraint rejection). The handler
866
+ * catches it and reports every member `conflicted` (overlays kept), having committed nothing.
867
+ */
868
+ class UnitNotCommittedError extends Error {}
869
+
870
+ function getUuidClaim(claims: JwtClaims, key: string): string | null {
871
+ const value = claims[key];
872
+
873
+ if (typeof value !== "string") {
874
+ return null;
875
+ }
876
+
877
+ 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;
878
+ }
879
+
880
+ function findManagedFieldViolations(
881
+ entry: SyncTableEntry,
882
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
883
+ payload: unknown,
884
+ ): string[] {
885
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
886
+ return [];
887
+ }
888
+
889
+ const managedFields = getManagedFieldsForOperation(entry, mutationKind);
890
+ if (managedFields.length === 0) {
891
+ return [];
892
+ }
893
+
894
+ const payloadKeys = new Set(Object.keys(payload));
895
+ return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);
896
+ }
897
+
898
+ // One structured warning per (table, dropped-key) per process. The apply path is hot; a memoized set
899
+ // keeps a recurring silent-drop from spamming the log while still surfacing it once. The keys are
900
+ // client-controlled (a malicious/buggy client can send unbounded junk keys), so the set is capped: past
901
+ // the cap we stop memoizing AND stop warning, so the process can never accumulate unbounded entries.
902
+ const warnedDroppedPayloadKeys = new Set<string>();
903
+ const MAX_WARNED_DROPPED_KEYS = 10_000;
904
+ // Set true after the one-time "warnings suppressed" notice fires, so the cap notice logs exactly once.
905
+ let droppedKeyWarningSuppressed = false;
906
+
907
+ /**
908
+ * Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path
909
+ * will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,
910
+ * nor a projected-away column that request validation already 400-rejects. The generated apply function
911
+ * reads only the table's PROJECTED columns from the payload jsonb, so such a key never lands — were it
912
+ * "applied" the write would collapse to a bare server-version (`updated_at_us`) bump. This is the clean
913
+ * two-case split (ADR-0022 posture docs):
914
+ *
915
+ * - **Projected-away / server-only columns** (`clientProjection.omitColumns`) sent explicitly are
916
+ * **400-rejected** by {@link findProjectedFieldViolations} — they are NOT silently dropped, so this
917
+ * helper deliberately does **not** warn for them (warning "the write still succeeds" and then
918
+ * rejecting was the misleading overlap the review flagged).
919
+ * - **Unknown non-column keys** (a typo, a stale field) are what the apply path silently ignores — those
920
+ * are exactly the keys this warns about, once, as a debugging aid. It is NOT an error and changes no
921
+ * semantics.
922
+ *
923
+ * Exported for direct unit coverage.
924
+ */
925
+ export function warnOnSilentlyDroppedPayloadKeys(
926
+ entry: SyncTableEntry,
927
+ tableName: string,
928
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
929
+ payload: unknown,
930
+ ): void {
931
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
932
+ return;
933
+ }
934
+
935
+ // The keys the apply path will actually write: the projected columns (what it reads from payload) plus
936
+ // the managed fields for this operation (server-stamped, legitimately present). Both property key and
937
+ // DB column name are accepted, so a payload keyed either way is not falsely flagged.
938
+ const writable = new Set<string>();
939
+ for (const { propertyKey, columnName } of getProjectedColumns(entry)) {
940
+ writable.add(propertyKey);
941
+ writable.add(columnName);
942
+ }
943
+ for (const { propertyKey, columnName } of getManagedFieldsForOperation(entry, mutationKind)) {
944
+ writable.add(propertyKey);
945
+ writable.add(columnName);
946
+ }
947
+
948
+ // Keys request validation will 400-REJECT (an explicitly-sent projected-away / server-only column):
949
+ // those never reach apply, so they are NOT a silent drop — exclude them so the warning is reserved for
950
+ // truly-unknown keys the apply path drops without validation rejecting.
951
+ const rejectedAtValidation = new Set<string>();
952
+ for (const { propertyKey, columnName } of getProjectedAwayFields(entry)) {
953
+ rejectedAtValidation.add(propertyKey);
954
+ rejectedAtValidation.add(columnName);
955
+ }
956
+
957
+ for (const key of Object.keys(payload)) {
958
+ if (writable.has(key) || rejectedAtValidation.has(key)) {
959
+ continue;
960
+ }
961
+ const memoKey = `${tableName}::${key}`;
962
+ if (warnedDroppedPayloadKeys.has(memoKey)) {
963
+ continue;
964
+ }
965
+ // Cap the memo set against client-controlled key spray: once full, emit one final suppression notice
966
+ // and stop both memoizing and warning — the set never grows past the cap.
967
+ if (warnedDroppedPayloadKeys.size >= MAX_WARNED_DROPPED_KEYS) {
968
+ if (!droppedKeyWarningSuppressed) {
969
+ droppedKeyWarningSuppressed = true;
970
+ console.warn(
971
+ `[pgxsinkit] Dropped-key warnings suppressed: more than ${MAX_WARNED_DROPPED_KEYS} distinct ` +
972
+ `(table, key) pairs have been reported this process. Further dropped payload keys will not be logged.`,
973
+ );
974
+ }
975
+ return;
976
+ }
977
+ warnedDroppedPayloadKeys.add(memoKey);
978
+ console.warn(
979
+ `[pgxsinkit] Payload for table "${tableName}" carries key "${key}", which is not a column of that ` +
980
+ `table — the apply path silently ignores it (a write that reached apply would collapse to a bare ` +
981
+ `server-version bump). This is almost always a typo or a stale field: check the spelling against ` +
982
+ `the table's columns, or remove "${key}" if the schema no longer has it. (A projected-away/` +
983
+ `server-only column would instead be 400-rejected, not dropped, so it is not what this warns about.) ` +
984
+ `(Logged once per table+key per process.)`,
985
+ { table: tableName, droppedKey: key, hint: "unknown-non-column-key" },
986
+ );
987
+ }
988
+ }
989
+
990
+ function findProjectedFieldViolations(
991
+ entry: SyncTableEntry,
992
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
993
+ payload: unknown,
994
+ ): string[] {
995
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
996
+ return [];
997
+ }
998
+
999
+ const projectedFields = getProjectedAwayFields(entry);
1000
+ if (projectedFields.length === 0) {
1001
+ return [];
1002
+ }
1003
+
1004
+ const payloadKeys = new Set(Object.keys(payload));
1005
+
1006
+ return [
1007
+ ...new Set(
1008
+ projectedFields
1009
+ .filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName))
1010
+ .map((field) => field.propertyKey),
1011
+ ),
1012
+ ];
1013
+ }
1014
+
1015
+ function sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTableRegistry): BatchMutationRequest {
1016
+ return {
1017
+ mutations: batch.mutations.map((mutation) => {
1018
+ if (mutation.kind === "delete") {
1019
+ return mutation;
1020
+ }
1021
+
1022
+ const entry = registry[mutation.tableName];
1023
+
1024
+ if (!entry) {
1025
+ return mutation;
1026
+ }
1027
+
1028
+ const managedFields = getManagedFieldsForOperation(entry as SyncTableEntry, mutation.kind);
1029
+ const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);
1030
+
1031
+ if (managedFields.length === 0 && projectedFields.length === 0) {
1032
+ return mutation;
1033
+ }
1034
+
1035
+ const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};
1036
+
1037
+ for (const field of managedFields) {
1038
+ delete payload[field.propertyKey];
1039
+ delete payload[field.columnName];
1040
+ }
1041
+
1042
+ for (const field of projectedFields) {
1043
+ delete payload[field.propertyKey];
1044
+ delete payload[field.columnName];
1045
+ }
1046
+
1047
+ return {
1048
+ ...mutation,
1049
+ payload,
1050
+ };
1051
+ }),
1052
+ };
1053
+ }
1054
+
1055
+ /**
1056
+ * The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /
1057
+ * `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —
1058
+ * and {@link findManagedFieldViolations} already rejects a payload that includes them. They are
1059
+ * omitted from the insert schema so a NOT NULL managed column without a SQL DEFAULT (e.g. an `authUid`
1060
+ * author/owner/created_by) is not falsely required. (A column carrying a DEFAULT is already optional
1061
+ * in the drizzle insert schema; this also covers a managed column that has none.)
1062
+ */
1063
+ export function buildCreateValidationSchema(entry: SyncTableEntry) {
1064
+ const createSchema = createMutationInsertSchema(entry.table as AnyPgTable);
1065
+ const managedCreateKeys = getManagedFieldsForOperation(entry, "create").map((field) => field.propertyKey);
1066
+ if (managedCreateKeys.length === 0) {
1067
+ return createSchema;
1068
+ }
1069
+ // The omit-mask keys are derived from governance at runtime, so they cannot be narrowed to the
1070
+ // schema's literal-key mask type — cast through the parameter type.
1071
+ const omitMask = Object.fromEntries(managedCreateKeys.map((key) => [key, true as const])) as Parameters<
1072
+ typeof createSchema.omit
1073
+ >[0];
1074
+ return createSchema.omit(omitMask);
1075
+ }
1076
+
1077
+ function getManagedFieldsForOperation(
1078
+ entry: SyncTableEntry,
1079
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
1080
+ ) {
1081
+ if (mutationKind === "delete") {
1082
+ return [];
1083
+ }
1084
+
1085
+ const columns = getColumns(entry.table as AnyPgTable);
1086
+ const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
1087
+
1088
+ return (entry.governance?.managedFields ?? [])
1089
+ .filter((field) => field.applyOn.includes(mutationKind))
1090
+ .map((field) => ({
1091
+ propertyKey: field.column,
1092
+ columnName: columnMap.get(field.column) ?? field.column,
1093
+ strategy: field.strategy,
1094
+ }));
1095
+ }
1096
+
1097
+ function getProjectedAwayFields(entry: SyncTableEntry) {
1098
+ return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({
1099
+ propertyKey,
1100
+ columnName,
1101
+ }));
1102
+ }
1103
+
1104
+ function toSchemaPayload(entry: SyncTableEntry, payload: unknown): unknown {
1105
+ if (!isPlainObject(payload)) {
1106
+ return payload;
1107
+ }
1108
+
1109
+ const columns = getColumns(entry.table as AnyPgTable);
1110
+ const keyMap = new Map<string, string>();
1111
+
1112
+ for (const [propertyKey, column] of Object.entries(columns)) {
1113
+ keyMap.set(propertyKey, propertyKey);
1114
+ keyMap.set(column.name, propertyKey);
1115
+ }
1116
+
1117
+ return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));
1118
+ }
1119
+
1120
+ function resolveServerUpdatedAtColumnName(entry: SyncTableEntry): string {
1121
+ // The single source for the Server version column (ADR-0010 / ADR-0004): resolves the
1122
+ // managed field's property key to its column name. Falls back to the conventional name for
1123
+ // resilience, though registry validation now guarantees a writable table declares one.
1124
+ return resolveServerVersionColumnName(entry) ?? "updated_at_us";
1125
+ }
1126
+
1127
+ async function readServerUpdatedAtUs(
1128
+ tx: RouteReadQueryClient,
1129
+ entry: SyncTableEntry,
1130
+ entityKey: Record<string, string>,
1131
+ ): Promise<string | undefined> {
1132
+ const columns = getColumns(entry.table as AnyPgTable);
1133
+ const columnName = resolveServerUpdatedAtColumnName(entry);
1134
+ const updatedAtColumn = Object.values(columns).find((column) => column.name === columnName);
1135
+
1136
+ if (!updatedAtColumn) {
1137
+ return undefined;
1138
+ }
1139
+
1140
+ const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {
1141
+ const rawValue = entityKey[primaryKeyColumn];
1142
+
1143
+ if (rawValue === undefined) {
1144
+ throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);
1145
+ }
1146
+
1147
+ const primaryKeyTableColumn = Object.values(columns).find((column) => column.name === primaryKeyColumn);
1148
+
1149
+ if (!primaryKeyTableColumn) {
1150
+ throw new Error(`Missing table column metadata for primary key column ${primaryKeyColumn}`);
1151
+ }
1152
+
1153
+ return eq(primaryKeyTableColumn, rawValue);
1154
+ });
1155
+
1156
+ const whereClause = conditions.length === 1 ? conditions[0]! : and(...conditions);
1157
+ const rows = await tx
1158
+ .select({ updatedAtUs: sql<string>`${updatedAtColumn}::text` })
1159
+ .from(entry.table as AnyPgTable)
1160
+ .where(whereClause)
1161
+ .limit(1);
1162
+
1163
+ return rows[0]?.updatedAtUs ?? undefined;
1164
+ }
1165
+
1166
+ // ADR-0030: the apply-function drift verify is gone from startup — the function verifies itself in-body
1167
+ // (SQLSTATE 'PXS01'). The only remaining boot-time check is the RLS auth-helper presence, and only when
1168
+ // the registry actually needs it. Reached only under `startupVerification: "in-process"`.
1169
+ async function installStartupDdl<TRegistry extends SyncTableRegistry>(
1170
+ db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,
1171
+ registry: TRegistry,
1172
+ ): Promise<void> {
1173
+ if (isRlsAuthContextRequired(registry)) {
1174
+ await verifyRlsAuthHelpers(db);
1175
+ }
1176
+ }