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