@pgxsinkit/server 0.1.0

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.
@@ -0,0 +1,613 @@
1
+ import { getTableName, sql } from "drizzle-orm";
2
+ import type { AnyPgTable } from "drizzle-orm/pg-core";
3
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
4
+ import { getColumns } from "drizzle-orm/utils";
5
+ import type { Hono } from "hono";
6
+
7
+ import type {
8
+ BatchMutationRequest,
9
+ MutationAck,
10
+ RegistryTables,
11
+ SyncTableEntry,
12
+ SyncTableRegistry,
13
+ } from "@pgxsinkit/contracts";
14
+ import {
15
+ batchMutationRequestSchema,
16
+ getOmittedProjectedColumns as getOmittedProjectionColumns,
17
+ } from "@pgxsinkit/contracts";
18
+
19
+ import type { OperationsLogConfig } from "../../operations-log/types";
20
+ import { logOperation, logOperationSafely } from "../../operations-log/writer";
21
+ import { executeDynamicMutation, installDynamicMutationFunction } from "./dynamic-strategy";
22
+ import {
23
+ executePlpgsqlBatch,
24
+ installPlpgsqlBatchFunction,
25
+ verifyArtifactRlsAuthHelpers,
26
+ verifyPlpgsqlBatchFunction,
27
+ } from "./plpgsql-strategy";
28
+ import { executePregeneratedMutation, installPregeneratedMutationFunctions } from "./pregenerated-strategy";
29
+ import type { BulkMutationBackend, TransactionClient } from "./types";
30
+
31
+ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
32
+ app: Hono,
33
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
34
+ registry: TRegistry,
35
+ backend: BulkMutationBackend,
36
+ operationsLogConfig: OperationsLogConfig,
37
+ operationsLogReady: Promise<void>,
38
+ resolveAuthClaims?: (request: Request) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null,
39
+ ) {
40
+ const startupReady = installBulkStartupDdl(db, registry, backend);
41
+
42
+ app.post("/api/mutations", async (context) => {
43
+ await Promise.all([startupReady, operationsLogReady]);
44
+
45
+ let rawBody: unknown;
46
+
47
+ try {
48
+ rawBody = await context.req.json();
49
+ } catch (error) {
50
+ await logOperationSafely(db, operationsLogConfig, {
51
+ source: "batch",
52
+ backend,
53
+ tableName: null,
54
+ operationKind: null,
55
+ entityKey: null,
56
+ payload: null,
57
+ status: "validation_failed",
58
+ errorMessage: error instanceof Error ? error.message : "Invalid JSON request body",
59
+ httpStatus: 400,
60
+ requestPath: context.req.path,
61
+ });
62
+
63
+ return context.json(
64
+ {
65
+ message: "Invalid batch mutation request",
66
+ issues: [],
67
+ },
68
+ 400,
69
+ );
70
+ }
71
+
72
+ let body: BatchMutationRequest;
73
+
74
+ try {
75
+ body = batchMutationRequestSchema.parse(rawBody);
76
+ } catch (error) {
77
+ await logOperationSafely(db, operationsLogConfig, {
78
+ source: "batch",
79
+ backend,
80
+ tableName: null,
81
+ operationKind: null,
82
+ entityKey: null,
83
+ payload: rawBody,
84
+ status: "validation_failed",
85
+ errorMessage: error instanceof Error ? error.message : "Invalid batch mutation request",
86
+ httpStatus: 400,
87
+ requestPath: context.req.path,
88
+ });
89
+
90
+ return context.json(
91
+ {
92
+ message: "Invalid batch mutation request",
93
+ issues: isValidationError(error) ? error.issues : [],
94
+ },
95
+ 400,
96
+ );
97
+ }
98
+
99
+ const validationErrors: string[] = [];
100
+ const invalidMutations: Array<{
101
+ mutation: BatchMutationRequest["mutations"][number];
102
+ message: string;
103
+ }> = [];
104
+
105
+ for (const mutation of body.mutations) {
106
+ if (!(mutation.tableName in registry)) {
107
+ const message = `Unknown table: ${mutation.tableName}`;
108
+ validationErrors.push(message);
109
+ invalidMutations.push({ mutation, message });
110
+ continue;
111
+ }
112
+
113
+ const entry = registry[mutation.tableName as keyof TRegistry]!;
114
+ const syncEntry = entry as SyncTableEntry;
115
+ const schemas = syncEntry.schemas;
116
+ const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);
117
+ const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
118
+
119
+ if (projectedFieldViolations.length > 0) {
120
+ const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(", ")}`;
121
+ validationErrors.push(message);
122
+ invalidMutations.push({ mutation, message });
123
+ continue;
124
+ }
125
+
126
+ if (backend === "bulk-plpgsql-artifact") {
127
+ const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
128
+
129
+ if (managedFieldViolations.length > 0) {
130
+ const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
131
+ validationErrors.push(message);
132
+ invalidMutations.push({ mutation, message });
133
+ continue;
134
+ }
135
+ }
136
+
137
+ try {
138
+ if (mutation.kind === "create" && schemas?.createSchema) {
139
+ schemas.createSchema.parse(normalizedPayload);
140
+ } else if (mutation.kind === "update" && schemas?.updateSchema) {
141
+ schemas.updateSchema.parse(normalizedPayload);
142
+ }
143
+ // delete has no payload schema
144
+ } catch (error) {
145
+ const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : "";
146
+ const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;
147
+ validationErrors.push(message);
148
+ invalidMutations.push({ mutation, message });
149
+ }
150
+ }
151
+
152
+ if (validationErrors.length > 0) {
153
+ for (const invalidMutation of invalidMutations) {
154
+ await logOperationSafely(db, operationsLogConfig, {
155
+ source: "batch",
156
+ backend,
157
+ tableName: invalidMutation.mutation.tableName,
158
+ operationKind: invalidMutation.mutation.kind,
159
+ entityKey: invalidMutation.mutation.entityKey,
160
+ payload: invalidMutation.mutation.payload,
161
+ status: "validation_failed",
162
+ errorMessage: invalidMutation.message,
163
+ httpStatus: 400,
164
+ mutationId: invalidMutation.mutation.mutationId,
165
+ mutationSeq: invalidMutation.mutation.mutationSeq,
166
+ clientTimestampUs: invalidMutation.mutation.clientTimestampUs,
167
+ requestPath: context.req.path,
168
+ });
169
+ }
170
+
171
+ return context.json({ message: `Payload validation failed: ${validationErrors.join("; ")}` }, 400);
172
+ }
173
+
174
+ const acks: MutationAck[] = [];
175
+ let actorUserId: string | null = null;
176
+ const artifactAuthContextRequired = backend === "bulk-plpgsql-artifact" && isArtifactAuthContextRequired(registry);
177
+
178
+ try {
179
+ await db.transaction(async (tx) => {
180
+ if (backend === "bulk-plpgsql" || backend === "bulk-plpgsql-artifact") {
181
+ const shouldApplyRlsContext = artifactAuthContextRequired;
182
+ let userClaims: Record<string, unknown> = {};
183
+
184
+ if (shouldApplyRlsContext) {
185
+ const resolvedClaims = await resolveAuthClaims?.(context.req.raw);
186
+
187
+ if (!isPlainObject(resolvedClaims)) {
188
+ await logOperationSafely(db, operationsLogConfig, {
189
+ source: "batch",
190
+ backend,
191
+ tableName: null,
192
+ operationKind: null,
193
+ entityKey: null,
194
+ payload: rawBody,
195
+ status: "validation_failed",
196
+ errorMessage: "Missing validated JWT claims for RLS-enabled artifact backend",
197
+ httpStatus: 401,
198
+ requestPath: context.req.path,
199
+ });
200
+
201
+ throw new UnauthorizedBatchMutationError(
202
+ "RLS-enabled artifact backend requires validated JWT claims in request context",
203
+ );
204
+ }
205
+
206
+ userClaims = resolvedClaims;
207
+ actorUserId = getUuidClaim(userClaims, "sub");
208
+ }
209
+
210
+ const batchRequest =
211
+ backend === "bulk-plpgsql-artifact" ? sanitizeArtifactRestrictedFields(body, registry) : body;
212
+
213
+ if (backend === "bulk-plpgsql-artifact") {
214
+ await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);
215
+ }
216
+
217
+ await executePlpgsqlBatch(
218
+ tx as unknown as TransactionClient,
219
+ batchRequest,
220
+ context.req.path,
221
+ operationsLogConfig.enabled && backend === "bulk-plpgsql",
222
+ shouldApplyRlsContext,
223
+ userClaims,
224
+ );
225
+
226
+ if (shouldApplyRlsContext) {
227
+ await tx.execute(sql`RESET ROLE`);
228
+ }
229
+
230
+ for (const mutation of batchRequest.mutations) {
231
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(
232
+ tx as unknown as TransactionClient,
233
+ registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,
234
+ mutation.entityKey,
235
+ );
236
+
237
+ if (backend === "bulk-plpgsql-artifact") {
238
+ await logOperation(tx, operationsLogConfig, {
239
+ source: "batch",
240
+ backend,
241
+ tableName: mutation.tableName,
242
+ operationKind: mutation.kind,
243
+ entityKey: mutation.entityKey,
244
+ payload: mutation.payload,
245
+ status: "succeeded",
246
+ httpStatus: 200,
247
+ mutationId: mutation.mutationId,
248
+ mutationSeq: mutation.mutationSeq,
249
+ clientTimestampUs: mutation.clientTimestampUs,
250
+ requestPath: context.req.path,
251
+ userId: actorUserId,
252
+ });
253
+ }
254
+
255
+ acks.push({
256
+ tableName: mutation.tableName,
257
+ entityKey: mutation.entityKey,
258
+ mutationId: mutation.mutationId,
259
+ mutationSeq: mutation.mutationSeq,
260
+ status: "acked",
261
+ ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),
262
+ });
263
+ }
264
+
265
+ return;
266
+ }
267
+
268
+ for (const mutation of body.mutations) {
269
+ const entry = registry[mutation.tableName as keyof TRegistry]!;
270
+ const primaryKeyColumnName = (entry as SyncTableEntry).primaryKey.columns[0]!;
271
+
272
+ if (backend === "bulk-dynamic") {
273
+ await executeDynamicMutation(tx as unknown as TransactionClient, mutation, primaryKeyColumnName);
274
+ } else {
275
+ await executePregeneratedMutation(tx as unknown as TransactionClient, mutation);
276
+ }
277
+
278
+ await logOperation(tx, operationsLogConfig, {
279
+ source: "batch",
280
+ backend,
281
+ tableName: mutation.tableName,
282
+ operationKind: mutation.kind,
283
+ entityKey: mutation.entityKey,
284
+ payload: mutation.payload,
285
+ status: "succeeded",
286
+ httpStatus: 200,
287
+ mutationId: mutation.mutationId,
288
+ mutationSeq: mutation.mutationSeq,
289
+ clientTimestampUs: mutation.clientTimestampUs,
290
+ requestPath: context.req.path,
291
+ userId: actorUserId,
292
+ });
293
+
294
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(
295
+ tx as unknown as TransactionClient,
296
+ entry as SyncTableEntry,
297
+ mutation.entityKey,
298
+ );
299
+
300
+ acks.push({
301
+ tableName: mutation.tableName,
302
+ entityKey: mutation.entityKey,
303
+ mutationId: mutation.mutationId,
304
+ mutationSeq: mutation.mutationSeq,
305
+ status: "acked",
306
+ ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),
307
+ });
308
+ }
309
+ });
310
+ } catch (error) {
311
+ if (error instanceof UnauthorizedBatchMutationError) {
312
+ return context.json({ message: error.message }, 401);
313
+ }
314
+
315
+ const errorMessage = formatBatchExecutionError(error);
316
+
317
+ for (const mutation of body.mutations) {
318
+ await logOperationSafely(db, operationsLogConfig, {
319
+ source: "batch",
320
+ backend,
321
+ tableName: mutation.tableName,
322
+ operationKind: mutation.kind,
323
+ entityKey: mutation.entityKey,
324
+ payload: mutation.payload,
325
+ status: "execution_failed",
326
+ errorMessage,
327
+ httpStatus: 500,
328
+ mutationId: mutation.mutationId,
329
+ mutationSeq: mutation.mutationSeq,
330
+ clientTimestampUs: mutation.clientTimestampUs,
331
+ requestPath: context.req.path,
332
+ userId: actorUserId,
333
+ });
334
+ }
335
+
336
+ return context.json({ message: errorMessage }, 500);
337
+ }
338
+
339
+ return context.json({ acks });
340
+ });
341
+ }
342
+
343
+ function isValidationError(error: unknown): error is { issues: unknown[] } {
344
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
345
+ }
346
+
347
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
348
+ return typeof value === "object" && value !== null && !Array.isArray(value);
349
+ }
350
+
351
+ function formatBatchExecutionError(error: unknown): string {
352
+ const rootCause = getRootCauseError(error);
353
+
354
+ if (!rootCause) {
355
+ return "Batch mutation failed";
356
+ }
357
+
358
+ const details = [rootCause.message];
359
+ const errorCode = getErrorStringProperty(rootCause, "code");
360
+ const errorDetail = getErrorStringProperty(rootCause, "detail");
361
+ const errorHint = getErrorStringProperty(rootCause, "hint");
362
+
363
+ if (errorCode) {
364
+ details.push(`code: ${errorCode}`);
365
+ }
366
+
367
+ if (errorDetail) {
368
+ details.push(`detail: ${errorDetail}`);
369
+ }
370
+
371
+ if (errorHint) {
372
+ details.push(`hint: ${errorHint}`);
373
+ }
374
+
375
+ return details.join(" | ");
376
+ }
377
+
378
+ function getRootCauseError(error: unknown): Error | null {
379
+ let current = error;
380
+ let lastError: Error | null = null;
381
+ const seen = new Set<unknown>();
382
+
383
+ while (current instanceof Error && !seen.has(current)) {
384
+ seen.add(current);
385
+ lastError = current;
386
+ current = current.cause;
387
+ }
388
+
389
+ return lastError;
390
+ }
391
+
392
+ function getErrorStringProperty(error: Error, key: string): string | null {
393
+ if (!(key in error)) {
394
+ return null;
395
+ }
396
+
397
+ const value = (error as unknown as Record<string, unknown>)[key];
398
+ return typeof value === "string" && value.length > 0 ? value : null;
399
+ }
400
+
401
+ function isArtifactAuthContextRequired(registry: SyncTableRegistry): boolean {
402
+ return Object.values(registry).some(
403
+ (entry) =>
404
+ entry.governance?.rls?.enabled === true ||
405
+ (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authUid"),
406
+ );
407
+ }
408
+
409
+ class UnauthorizedBatchMutationError extends Error {}
410
+
411
+ function getUuidClaim(claims: Record<string, unknown>, key: string): string | null {
412
+ const value = claims[key];
413
+
414
+ if (typeof value !== "string") {
415
+ return null;
416
+ }
417
+
418
+ 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;
419
+ }
420
+
421
+ function findManagedFieldViolations(
422
+ entry: SyncTableEntry,
423
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
424
+ payload: unknown,
425
+ ): string[] {
426
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
427
+ return [];
428
+ }
429
+
430
+ const managedFields = getManagedFieldsForOperation(entry, mutationKind);
431
+ if (managedFields.length === 0) {
432
+ return [];
433
+ }
434
+
435
+ const payloadKeys = new Set(Object.keys(payload));
436
+ return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);
437
+ }
438
+
439
+ function findProjectedFieldViolations(
440
+ entry: SyncTableEntry,
441
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
442
+ payload: unknown,
443
+ ): string[] {
444
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
445
+ return [];
446
+ }
447
+
448
+ const projectedFields = getProjectedAwayFields(entry);
449
+ if (projectedFields.length === 0) {
450
+ return [];
451
+ }
452
+
453
+ const payloadKeys = new Set(Object.keys(payload));
454
+
455
+ return [
456
+ ...new Set(
457
+ projectedFields
458
+ .filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName))
459
+ .map((field) => field.propertyKey),
460
+ ),
461
+ ];
462
+ }
463
+
464
+ function sanitizeArtifactRestrictedFields(
465
+ batch: BatchMutationRequest,
466
+ registry: SyncTableRegistry,
467
+ ): BatchMutationRequest {
468
+ return {
469
+ mutations: batch.mutations.map((mutation) => {
470
+ if (mutation.kind === "delete") {
471
+ return mutation;
472
+ }
473
+
474
+ const entry = registry[mutation.tableName];
475
+
476
+ if (!entry) {
477
+ return mutation;
478
+ }
479
+
480
+ const managedFields = getManagedFieldsForOperation(entry as SyncTableEntry, mutation.kind);
481
+ const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);
482
+
483
+ if (managedFields.length === 0 && projectedFields.length === 0) {
484
+ return mutation;
485
+ }
486
+
487
+ const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};
488
+
489
+ for (const field of managedFields) {
490
+ delete payload[field.propertyKey];
491
+ delete payload[field.columnName];
492
+ }
493
+
494
+ for (const field of projectedFields) {
495
+ delete payload[field.propertyKey];
496
+ delete payload[field.columnName];
497
+ }
498
+
499
+ return {
500
+ ...mutation,
501
+ payload,
502
+ };
503
+ }),
504
+ };
505
+ }
506
+
507
+ function getManagedFieldsForOperation(
508
+ entry: SyncTableEntry,
509
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
510
+ ) {
511
+ if (mutationKind === "delete") {
512
+ return [];
513
+ }
514
+
515
+ const columns = getColumns(entry.table as AnyPgTable);
516
+ const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
517
+
518
+ return (entry.governance?.managedFields ?? [])
519
+ .filter((field) => field.applyOn.includes(mutationKind))
520
+ .map((field) => ({
521
+ propertyKey: field.column,
522
+ columnName: columnMap.get(field.column) ?? field.column,
523
+ strategy: field.strategy,
524
+ }));
525
+ }
526
+
527
+ function getProjectedAwayFields(entry: SyncTableEntry) {
528
+ return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({
529
+ propertyKey,
530
+ columnName,
531
+ }));
532
+ }
533
+
534
+ function toSchemaPayload(entry: SyncTableEntry, payload: unknown): unknown {
535
+ if (!isPlainObject(payload)) {
536
+ return payload;
537
+ }
538
+
539
+ const columns = getColumns(entry.table as AnyPgTable);
540
+ const keyMap = new Map<string, string>();
541
+
542
+ for (const [propertyKey, column] of Object.entries(columns)) {
543
+ keyMap.set(propertyKey, propertyKey);
544
+ keyMap.set(column.name, propertyKey);
545
+ }
546
+
547
+ return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));
548
+ }
549
+
550
+ async function readServerUpdatedAtUs(
551
+ tx: TransactionClient,
552
+ entry: SyncTableEntry,
553
+ entityKey: Record<string, string>,
554
+ ): Promise<string | undefined> {
555
+ const columns = getColumns(entry.table as AnyPgTable);
556
+ const updatedAtColumn = Object.values(columns).find((column) => column.name === "updated_at_us");
557
+
558
+ if (!updatedAtColumn) {
559
+ return undefined;
560
+ }
561
+
562
+ const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {
563
+ const rawValue = entityKey[primaryKeyColumn];
564
+
565
+ if (rawValue === undefined) {
566
+ throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);
567
+ }
568
+
569
+ return sql`${quoteIdentifier(primaryKeyColumn)} = ${rawValue}`;
570
+ });
571
+
572
+ const result = (await tx.execute(sql`
573
+ SELECT ${quoteIdentifier("updated_at_us")}::text AS "updatedAtUs"
574
+ FROM ${quoteIdentifier(getTableName(entry.table as AnyPgTable))}
575
+ WHERE ${sql.join(conditions, sql` AND `)}
576
+ LIMIT 1
577
+ `)) as Iterable<{ updatedAtUs: string | null }>;
578
+
579
+ const row = Array.from(result)[0];
580
+ return row?.updatedAtUs ?? undefined;
581
+ }
582
+
583
+ function quoteIdentifier(identifier: string) {
584
+ return sql.raw(`"${identifier.replace(/"/g, '""')}"`);
585
+ }
586
+
587
+ async function installBulkStartupDdl<TRegistry extends SyncTableRegistry>(
588
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
589
+ registry: TRegistry,
590
+ backend: BulkMutationBackend,
591
+ ): Promise<void> {
592
+ if (backend === "bulk-dynamic") {
593
+ await installDynamicMutationFunction(db);
594
+ return;
595
+ }
596
+
597
+ if (backend === "bulk-plpgsql") {
598
+ await installPlpgsqlBatchFunction(db, registry);
599
+ return;
600
+ }
601
+
602
+ if (backend === "bulk-plpgsql-artifact") {
603
+ await verifyPlpgsqlBatchFunction(db);
604
+
605
+ if (isArtifactAuthContextRequired(registry)) {
606
+ await verifyArtifactRlsAuthHelpers(db);
607
+ }
608
+
609
+ return;
610
+ }
611
+
612
+ await installPregeneratedMutationFunctions(db, registry);
613
+ }
@@ -0,0 +1,5 @@
1
+ export type BulkMutationBackend = "bulk-dynamic" | "bulk-pregenerated" | "bulk-plpgsql" | "bulk-plpgsql-artifact";
2
+
3
+ export interface TransactionClient {
4
+ execute: (query: unknown) => Promise<unknown>;
5
+ }
@@ -0,0 +1,29 @@
1
+ import { sql } from "drizzle-orm";
2
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
+
4
+ import type { RegistryTables, SyncTableRegistry } from "@pgxsinkit/contracts";
5
+
6
+ import type { OperationsLogConfig } from "./types";
7
+
8
+ type OperationsLogPresenceRow = {
9
+ tableName: string | null;
10
+ };
11
+
12
+ export async function ensureOperationsLogSchema<TRegistry extends SyncTableRegistry>(
13
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
14
+ config: OperationsLogConfig,
15
+ ): Promise<void> {
16
+ if (!config.enabled) {
17
+ return;
18
+ }
19
+
20
+ const result = await db.execute<OperationsLogPresenceRow>(sql`
21
+ SELECT to_regclass('public.operations_log')::text AS "tableName"
22
+ `);
23
+
24
+ const row = Array.from(result, (entry) => entry as OperationsLogPresenceRow)[0];
25
+
26
+ if (!row?.tableName) {
27
+ throw new Error("operations_log table is missing. Run bun run db:push before starting the write API.");
28
+ }
29
+ }
@@ -0,0 +1,37 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { bigint, bigserial, index, integer, jsonb, pgTable, text, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
3
+
4
+ const nowMicrosecondsSql = sql`(floor((EXTRACT(epoch FROM clock_timestamp()) * (1000000)::numeric)))`;
5
+
6
+ export const operationsLogTable = pgTable(
7
+ "operations_log",
8
+ {
9
+ id: bigserial("id", { mode: "number" }).primaryKey(),
10
+ source: varchar("source", { length: 24 }).notNull(),
11
+ backend: varchar("backend", { length: 24 }).notNull(),
12
+ tableName: varchar("table_name", { length: 255 }),
13
+ operationKind: varchar("operation_kind", { length: 24 }),
14
+ userId: uuid("user_id"),
15
+ entityKeyJson: jsonb("entity_key_json"),
16
+ payloadJson: jsonb("payload_json"),
17
+ status: varchar("status", { length: 32 }).notNull(),
18
+ errorMessage: text("error_message"),
19
+ httpStatus: integer("http_status"),
20
+ mutationId: uuid("mutation_id"),
21
+ mutationSeq: integer("mutation_seq"),
22
+ clientTimestampUs: bigint("client_timestamp_us", { mode: "bigint" }),
23
+ requestPath: text("request_path"),
24
+ serverTimestampUs: bigint("server_timestamp_us", { mode: "bigint" }).notNull().default(nowMicrosecondsSql),
25
+ createdAt: timestamp("created_at", { mode: "date", withTimezone: true }).notNull().defaultNow(),
26
+ },
27
+ (table) => [
28
+ index("operations_log_created_at_idx").on(table.createdAt.desc()),
29
+ index("operations_log_table_name_idx").on(table.tableName),
30
+ index("operations_log_user_id_idx").on(table.userId),
31
+ index("operations_log_status_idx").on(table.status),
32
+ index("operations_log_mutation_id_idx").on(table.mutationId),
33
+ ],
34
+ );
35
+
36
+ export type OperationsLogRow = typeof operationsLogTable.$inferSelect;
37
+ export type NewOperationsLogRow = typeof operationsLogTable.$inferInsert;