@pgxsinkit/client 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +57 -326
- package/dist/index.js.map +5 -5
- package/package.json +3 -3
- package/src/index.ts +10 -5
- package/src/mutation.ts +93 -512
- package/src/schema.ts +48 -5
package/dist/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import { getSyncRegistrySchema as getSyncRegistrySchema3 } from "@pgxsinkit/cont
|
|
|
8
8
|
import { createElectricExtension, startConfiguredSync } from "@pgxsinkit/sync-engine";
|
|
9
9
|
|
|
10
10
|
// packages/client/src/mutation.ts
|
|
11
|
+
import { getViewConfig } from "drizzle-orm/pg-core";
|
|
11
12
|
import { ZodObject } from "zod";
|
|
12
13
|
import { getProjectedColumns as getProjectedTableColumns, getSyncRegistrySchema } from "@pgxsinkit/contracts";
|
|
13
14
|
var DEFAULT_FLUSH_BATCH_SIZE = 100;
|
|
@@ -28,7 +29,7 @@ function createMutationRuntime(options) {
|
|
|
28
29
|
}
|
|
29
30
|
return;
|
|
30
31
|
};
|
|
31
|
-
const tableContexts = buildTableContexts(options.registry
|
|
32
|
+
const tableContexts = buildTableContexts(options.registry);
|
|
32
33
|
let flushQueue = Promise.resolve();
|
|
33
34
|
const getTableContext = (table) => {
|
|
34
35
|
const context = tableContexts[table];
|
|
@@ -248,29 +249,17 @@ function createMutationRuntime(options) {
|
|
|
248
249
|
}
|
|
249
250
|
};
|
|
250
251
|
const runFlush = async (table) => {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
for (const context of batchResult.affectedContexts) {
|
|
259
|
-
affectedContexts.set(context.key, context);
|
|
260
|
-
}
|
|
261
|
-
} while (processedCount > 0);
|
|
262
|
-
for (const context of affectedContexts.values()) {
|
|
263
|
-
await reconcileTable(options.db, context);
|
|
252
|
+
const affectedContexts = new Map;
|
|
253
|
+
let processedCount = 0;
|
|
254
|
+
do {
|
|
255
|
+
const batchResult = await flushBatch(options.db, tableContexts, options.writeUrl, table, resolveAuthToken);
|
|
256
|
+
processedCount = batchResult.processedCount;
|
|
257
|
+
for (const context of batchResult.affectedContexts) {
|
|
258
|
+
affectedContexts.set(context.key, context);
|
|
264
259
|
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
processedCount = 0;
|
|
269
|
-
const contexts = filterContexts(tableContexts, table);
|
|
270
|
-
for (const context of contexts) {
|
|
271
|
-
processedCount += await flushTable(options.db, context, options.writeUrl, resolveAuthToken);
|
|
272
|
-
}
|
|
273
|
-
} while (processedCount > 0);
|
|
260
|
+
} while (processedCount > 0);
|
|
261
|
+
for (const context of affectedContexts.values()) {
|
|
262
|
+
await reconcileTable(options.db, context);
|
|
274
263
|
}
|
|
275
264
|
};
|
|
276
265
|
return {
|
|
@@ -314,7 +303,6 @@ function createMutationRuntime(options) {
|
|
|
314
303
|
});
|
|
315
304
|
},
|
|
316
305
|
flush: async (table) => {
|
|
317
|
-
console.log(`Initiating flush for table: ${table ?? "all tables"}`);
|
|
318
306
|
const nextFlush = flushQueue.then(() => runFlush(table));
|
|
319
307
|
flushQueue = nextFlush.catch(() => {
|
|
320
308
|
return;
|
|
@@ -433,29 +421,14 @@ function createMutationRuntime(options) {
|
|
|
433
421
|
}
|
|
434
422
|
};
|
|
435
423
|
}
|
|
436
|
-
function
|
|
437
|
-
const managedTimestamp = (entry.governance?.managedFields ?? []).find((f) => f.strategy === "nowMicroseconds" && f.applyOn.includes("update"));
|
|
438
|
-
const candidatePropertyKey = managedTimestamp?.column;
|
|
439
|
-
const candidate = candidatePropertyKey ? columns.find((c) => c.propertyKey === candidatePropertyKey)?.column.name : "updated_at_us";
|
|
440
|
-
if (!candidate) {
|
|
441
|
-
throw new Error(`Table "${key}" has managed field "${candidatePropertyKey}" with strategy "nowMicroseconds" ` + `on "update", but no matching column exists in the synced projection.`);
|
|
442
|
-
}
|
|
443
|
-
if (!columns.some((c) => c.column.name === candidate)) {
|
|
444
|
-
throw new Error(`Table "${key}" has updatedAtColumn "${candidate}" but no matching column exists ` + `in the synced projection (via managed field "${candidatePropertyKey}").`);
|
|
445
|
-
}
|
|
446
|
-
return candidate;
|
|
447
|
-
}
|
|
448
|
-
function buildTableContexts(registry, requireRouteBasePath) {
|
|
424
|
+
function buildTableContexts(registry) {
|
|
449
425
|
const localSchema = getSyncRegistrySchema(registry);
|
|
450
|
-
return Object.fromEntries(Object.entries(registry).filter(([, entry]) => entry.mode !== "readonly").map(([key, entry]) => [key, buildTableContext(key, entry, localSchema
|
|
426
|
+
return Object.fromEntries(Object.entries(registry).filter(([, entry]) => entry.mode !== "readonly").map(([key, entry]) => [key, buildTableContext(key, entry, localSchema)]));
|
|
451
427
|
}
|
|
452
|
-
function buildTableContext(key, entry, localSchema
|
|
428
|
+
function buildTableContext(key, entry, localSchema) {
|
|
453
429
|
if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
|
|
454
430
|
throw new Error(`overlay and journal tables are required for writable table ${key}`);
|
|
455
431
|
}
|
|
456
|
-
if (requireRouteBasePath && !entry.routes?.basePath) {
|
|
457
|
-
throw new Error(`routes.basePath is required for writable table ${key}`);
|
|
458
|
-
}
|
|
459
432
|
const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({
|
|
460
433
|
propertyKey,
|
|
461
434
|
column
|
|
@@ -467,20 +440,17 @@ function buildTableContext(key, entry, localSchema, requireRouteBasePath) {
|
|
|
467
440
|
}
|
|
468
441
|
return column.propertyKey;
|
|
469
442
|
});
|
|
470
|
-
const updatedAtColumn = resolveUpdatedAtColumn(key, entry, columns);
|
|
471
443
|
return {
|
|
472
444
|
key,
|
|
473
445
|
entry,
|
|
474
|
-
readModel: qualifyLocalIdentifier(localSchema, entry.clientProjection.
|
|
446
|
+
readModel: qualifyLocalIdentifier(localSchema, entry.view != null ? getViewConfig(entry.view).name : entry.clientProjection.syncedTable),
|
|
475
447
|
syncedTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.syncedTable),
|
|
476
448
|
overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),
|
|
477
449
|
journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),
|
|
478
450
|
journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),
|
|
479
|
-
...entry.routes?.basePath ? { routeBasePath: entry.routes.basePath } : {},
|
|
480
451
|
pkColumnNames: [...entry.primaryKey.columns],
|
|
481
452
|
pkPropertyKeys,
|
|
482
453
|
recordIncludesOverlayState: recordSchemaIncludesOverlayState(entry.schemas?.recordSchema),
|
|
483
|
-
updatedAtColumn,
|
|
484
454
|
columns
|
|
485
455
|
};
|
|
486
456
|
}
|
|
@@ -983,13 +953,9 @@ async function flushBatch(db, tableContexts, batchWriteUrl, tableFilter, getAuth
|
|
|
983
953
|
};
|
|
984
954
|
}));
|
|
985
955
|
}
|
|
986
|
-
const reconciledContexts = [...new Set(pending.map((row) => row.context))];
|
|
987
|
-
for (const context of reconciledContexts) {
|
|
988
|
-
await reconcileTable(db, context);
|
|
989
|
-
}
|
|
990
956
|
return {
|
|
991
957
|
processedCount: pending.length,
|
|
992
|
-
affectedContexts:
|
|
958
|
+
affectedContexts: [...new Set(pending.map((row) => row.context))]
|
|
993
959
|
};
|
|
994
960
|
}
|
|
995
961
|
function resolveBatchMutationUrl(batchWriteUrl) {
|
|
@@ -999,33 +965,6 @@ function resolveBatchMutationUrl(batchWriteUrl) {
|
|
|
999
965
|
}
|
|
1000
966
|
return `${trimmed}/mutations`;
|
|
1001
967
|
}
|
|
1002
|
-
function toSqlColumnPayload(context, payload) {
|
|
1003
|
-
const normalized = {};
|
|
1004
|
-
for (const { propertyKey, column } of context.columns) {
|
|
1005
|
-
const columnName = column.name;
|
|
1006
|
-
if (Object.prototype.hasOwnProperty.call(payload, columnName)) {
|
|
1007
|
-
normalized[columnName] = payload[columnName];
|
|
1008
|
-
continue;
|
|
1009
|
-
}
|
|
1010
|
-
if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
|
|
1011
|
-
normalized[columnName] = payload[propertyKey];
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
return normalized;
|
|
1015
|
-
}
|
|
1016
|
-
function filterProjectedPayload(context, payload) {
|
|
1017
|
-
const normalized = {};
|
|
1018
|
-
for (const { propertyKey, column } of context.columns) {
|
|
1019
|
-
if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
|
|
1020
|
-
normalized[propertyKey] = payload[propertyKey];
|
|
1021
|
-
continue;
|
|
1022
|
-
}
|
|
1023
|
-
if (Object.prototype.hasOwnProperty.call(payload, column.name)) {
|
|
1024
|
-
normalized[column.name] = payload[column.name];
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
return normalized;
|
|
1028
|
-
}
|
|
1029
968
|
function stripManagedFields(context, payload, operation) {
|
|
1030
969
|
const managedColumns = new Set;
|
|
1031
970
|
for (const mf of context.entry.governance?.managedFields ?? []) {
|
|
@@ -1037,173 +976,31 @@ function stripManagedFields(context, payload, operation) {
|
|
|
1037
976
|
return payload;
|
|
1038
977
|
return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));
|
|
1039
978
|
}
|
|
1040
|
-
|
|
1041
|
-
const
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
last_http_status AS "lastHttpStatus",
|
|
1051
|
-
last_error AS "lastError",
|
|
1052
|
-
conflict_reason AS "conflictReason",
|
|
1053
|
-
next_retry_at_us::text AS "nextRetryAtUs",
|
|
1054
|
-
server_updated_at_us::text AS "serverUpdatedAtUs"
|
|
1055
|
-
FROM ${context.journalTable}
|
|
1056
|
-
WHERE status IN ('pending', 'failed')
|
|
1057
|
-
AND COALESCE(next_retry_at_us, 0) <= $1::bigint
|
|
1058
|
-
AND NOT EXISTS (
|
|
1059
|
-
SELECT 1
|
|
1060
|
-
FROM ${context.journalTable} AS earlier
|
|
1061
|
-
WHERE earlier.entity_key_json = ${context.journalTable}.entity_key_json
|
|
1062
|
-
AND earlier.mutation_seq < ${context.journalTable}.mutation_seq
|
|
1063
|
-
AND earlier.status IN ('pending', 'failed', 'sending')
|
|
1064
|
-
)
|
|
1065
|
-
ORDER BY enqueued_at_us ASC, mutation_seq ASC
|
|
1066
|
-
LIMIT ${DEFAULT_FLUSH_BATCH_SIZE}
|
|
1067
|
-
`, [nowMicroseconds()]);
|
|
1068
|
-
if (result.rows.length === 0) {
|
|
1069
|
-
return 0;
|
|
1070
|
-
}
|
|
1071
|
-
for (const mutation of result.rows) {
|
|
1072
|
-
const sentAtUs = nowMicroseconds();
|
|
1073
|
-
await setMutationStatus(db, context, mutation.mutationId, "sending", {
|
|
1074
|
-
attemptCount: mutation.attemptCount + 1,
|
|
1075
|
-
sentAtUs,
|
|
1076
|
-
updatedAtUs: sentAtUs,
|
|
1077
|
-
lastError: null,
|
|
1078
|
-
nextRetryAtUs: null,
|
|
1079
|
-
lastHttpStatus: null,
|
|
1080
|
-
conflictReason: null
|
|
1081
|
-
});
|
|
1082
|
-
try {
|
|
1083
|
-
const entityKey = JSON.parse(mutation.entityKeyJson);
|
|
1084
|
-
const payload = JSON.parse(mutation.payloadJson);
|
|
1085
|
-
let response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken?.());
|
|
1086
|
-
if ([401, 403].includes(response.status) && getAuthToken) {
|
|
1087
|
-
response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken());
|
|
1088
|
-
}
|
|
1089
|
-
const responseText = await response.text();
|
|
1090
|
-
const responseJson = responseText.length > 0 ? JSON.parse(responseText) : null;
|
|
1091
|
-
if (!response.ok) {
|
|
1092
|
-
const errorMessage = responseJson && typeof responseJson.message === "string" ? responseJson.message : `Write API responded with ${response.status}`;
|
|
1093
|
-
if (mutation.mutationKind === "delete" && response.status === 404) {
|
|
1094
|
-
await markDeleteAcknowledged(db, context, mutation.mutationId);
|
|
1095
|
-
continue;
|
|
1096
|
-
}
|
|
1097
|
-
throw new MutationRequestError(errorMessage, response.status);
|
|
1098
|
-
}
|
|
1099
|
-
const ackedAtUs = nowMicroseconds();
|
|
1100
|
-
if (mutation.mutationKind === "delete") {
|
|
1101
|
-
await markDeleteAcknowledged(db, context, mutation.mutationId);
|
|
1102
|
-
} else {
|
|
1103
|
-
const created = parseRecord(context, responseJson);
|
|
1104
|
-
const createdRecord = ensureRecord(created);
|
|
1105
|
-
const serverUpdatedAtUs = toOptionalString(createdRecord.updatedAtUs);
|
|
1106
|
-
await db.query(`
|
|
1107
|
-
UPDATE ${context.journalTable}
|
|
1108
|
-
SET
|
|
1109
|
-
status = 'acked',
|
|
1110
|
-
acked_at_us = $2::bigint,
|
|
1111
|
-
updated_at_us = $2::bigint,
|
|
1112
|
-
server_updated_at_us = $3::bigint,
|
|
1113
|
-
last_error = NULL,
|
|
1114
|
-
last_http_status = 200,
|
|
1115
|
-
conflict_reason = NULL,
|
|
1116
|
-
next_retry_at_us = NULL
|
|
1117
|
-
WHERE mutation_id = $1
|
|
1118
|
-
`, [mutation.mutationId, ackedAtUs, serverUpdatedAtUs]);
|
|
1119
|
-
if (!await hasLaterMutations(db, context, mutation.entityKeyJson, mutation.mutationSeq)) {
|
|
1120
|
-
await updateOverlayTimestamps(db, context, entityKey, createdRecord, ackedAtUs);
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
} catch (error) {
|
|
1124
|
-
const failedAtUs = nowMicroseconds();
|
|
1125
|
-
const attemptCount = mutation.attemptCount + 1;
|
|
1126
|
-
const nextRetryAtUs = computeNextRetryAtUs(failedAtUs, attemptCount);
|
|
1127
|
-
const lastHttpStatus = error instanceof MutationRequestError ? error.status : null;
|
|
1128
|
-
const conflictReason = lastHttpStatus === 404 || lastHttpStatus === 409 ? error instanceof Error ? error.message : "Server conflict" : null;
|
|
1129
|
-
await setMutationStatus(db, context, mutation.mutationId, "failed", {
|
|
1130
|
-
attemptCount,
|
|
1131
|
-
updatedAtUs: failedAtUs,
|
|
1132
|
-
lastError: error instanceof Error ? error.message : "Unknown write failure",
|
|
1133
|
-
nextRetryAtUs,
|
|
1134
|
-
lastHttpStatus,
|
|
1135
|
-
conflictReason
|
|
1136
|
-
});
|
|
979
|
+
function toSqlColumnPayload(context, payload) {
|
|
980
|
+
const normalized = {};
|
|
981
|
+
for (const { propertyKey, column } of context.columns) {
|
|
982
|
+
const columnName = column.name;
|
|
983
|
+
if (Object.prototype.hasOwnProperty.call(payload, columnName)) {
|
|
984
|
+
normalized[columnName] = payload[columnName];
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
|
|
988
|
+
normalized[columnName] = payload[propertyKey];
|
|
1137
989
|
}
|
|
1138
990
|
}
|
|
1139
|
-
|
|
1140
|
-
return result.rows.length;
|
|
991
|
+
return normalized;
|
|
1141
992
|
}
|
|
1142
993
|
async function reconcileTable(db, context) {
|
|
1143
|
-
await clearAcknowledgedDeletes(db, context);
|
|
1144
994
|
await db.exec("BEGIN");
|
|
1145
995
|
try {
|
|
1146
|
-
await db.query("WITH
|
|
996
|
+
await db.query("WITH cleared_journal AS (" + "DELETE FROM " + context.journalTable + " AS journal " + "WHERE journal.status = 'acked' " + "AND journal.server_updated_at_us IS NOT NULL " + "AND journal.mutation_kind <> 'delete' " + "RETURNING journal.entity_key_json, " + context.pkColumnNames.map((cn) => "journal." + cn).join(", ") + ") " + "DELETE FROM " + context.overlayTable + " AS overlay " + "USING cleared_journal AS cj " + "WHERE " + buildColumnEquality(context.pkColumnNames, "overlay", "cj") + " " + "AND NOT EXISTS (" + "SELECT 1 FROM " + context.journalTable + " AS j " + "WHERE j.entity_key_json = cj.entity_key_json " + "AND j.status IN ('pending', 'sending', 'failed')" + ")");
|
|
997
|
+
await db.query("WITH clearable_entities AS (" + "SELECT DISTINCT journal.entity_key_json, " + context.pkColumnNames.map((cn) => "journal." + cn).join(", ") + " FROM " + context.journalTable + " AS journal " + "LEFT JOIN " + context.syncedTable + " AS synced " + "ON " + buildColumnEquality(context.pkColumnNames, "journal", "synced") + " " + "WHERE journal.status = 'acked' " + "AND journal.mutation_kind = 'delete' " + "AND synced." + context.pkColumnNames[0] + " IS NULL" + "), " + "deleted_overlay AS (" + "DELETE FROM " + context.overlayTable + " AS overlay " + "USING clearable_entities AS ce " + "WHERE " + buildColumnEquality(context.pkColumnNames, "overlay", "ce") + ") " + "DELETE FROM " + context.journalTable + " AS journal " + "USING clearable_entities AS ce " + "WHERE " + buildColumnEquality(context.pkColumnNames, "journal", "ce") + " " + "AND journal.status = 'acked' " + "AND journal.mutation_kind = 'delete'");
|
|
1147
998
|
await db.exec("COMMIT");
|
|
1148
999
|
} catch (error) {
|
|
1149
1000
|
await db.exec("ROLLBACK");
|
|
1150
1001
|
throw error;
|
|
1151
1002
|
}
|
|
1152
1003
|
}
|
|
1153
|
-
async function clearAcknowledgedDeletes(db, context) {
|
|
1154
|
-
await db.exec("BEGIN");
|
|
1155
|
-
try {
|
|
1156
|
-
await db.query(`
|
|
1157
|
-
WITH clearable_entities AS (
|
|
1158
|
-
SELECT DISTINCT journal.entity_key_json, ${context.pkColumnNames.map((columnName) => `journal.${columnName}`).join(", ")}
|
|
1159
|
-
FROM ${context.journalTable} AS journal
|
|
1160
|
-
LEFT JOIN ${context.syncedTable} AS synced
|
|
1161
|
-
ON ${buildColumnEquality(context.pkColumnNames, "journal", "synced")}
|
|
1162
|
-
WHERE journal.status = 'acked'
|
|
1163
|
-
AND journal.mutation_kind = 'delete'
|
|
1164
|
-
AND synced.${context.pkColumnNames[0]} IS NULL
|
|
1165
|
-
),
|
|
1166
|
-
deleted_overlay AS (
|
|
1167
|
-
DELETE FROM ${context.overlayTable} AS overlay
|
|
1168
|
-
USING clearable_entities
|
|
1169
|
-
WHERE ${buildColumnEquality(context.pkColumnNames, "overlay", "clearable_entities")}
|
|
1170
|
-
)
|
|
1171
|
-
DELETE FROM ${context.journalTable} AS journal
|
|
1172
|
-
USING clearable_entities
|
|
1173
|
-
WHERE journal.entity_key_json = clearable_entities.entity_key_json
|
|
1174
|
-
`);
|
|
1175
|
-
await db.exec("COMMIT");
|
|
1176
|
-
} catch (error) {
|
|
1177
|
-
await db.exec("ROLLBACK");
|
|
1178
|
-
throw error;
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
async function sendMutationRequest(writeUrl, context, entityKey, payload, bearerToken) {
|
|
1182
|
-
if (!context.routeBasePath) {
|
|
1183
|
-
throw new Error(`routes.basePath is required for direct mutation requests on table ${context.key}`);
|
|
1184
|
-
}
|
|
1185
|
-
switch (payload.kind) {
|
|
1186
|
-
case "create":
|
|
1187
|
-
return fetch(`${writeUrl}${context.routeBasePath}`, {
|
|
1188
|
-
method: "POST",
|
|
1189
|
-
headers: buildRequestHeaders(bearerToken),
|
|
1190
|
-
body: JSON.stringify(filterProjectedPayload(context, ensureRecord(payload.value)))
|
|
1191
|
-
});
|
|
1192
|
-
case "update":
|
|
1193
|
-
return fetch(`${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`, {
|
|
1194
|
-
method: "PATCH",
|
|
1195
|
-
headers: buildRequestHeaders(bearerToken),
|
|
1196
|
-
body: JSON.stringify(filterProjectedPayload(context, ensureRecord(payload.patch)))
|
|
1197
|
-
});
|
|
1198
|
-
case "delete":
|
|
1199
|
-
return fetch(`${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`, {
|
|
1200
|
-
method: "DELETE",
|
|
1201
|
-
headers: buildRequestHeaders(bearerToken)
|
|
1202
|
-
});
|
|
1203
|
-
default:
|
|
1204
|
-
throw new Error(`Unknown mutation kind for table ${context.key}`);
|
|
1205
|
-
}
|
|
1206
|
-
}
|
|
1207
1004
|
function buildRequestHeaders(bearerToken) {
|
|
1208
1005
|
if (!bearerToken) {
|
|
1209
1006
|
return {
|
|
@@ -1215,37 +1012,6 @@ function buildRequestHeaders(bearerToken) {
|
|
|
1215
1012
|
Authorization: `Bearer ${bearerToken}`
|
|
1216
1013
|
};
|
|
1217
1014
|
}
|
|
1218
|
-
function getSingleEntityKeyValue(context, entityKey) {
|
|
1219
|
-
if (context.pkPropertyKeys.length !== 1) {
|
|
1220
|
-
throw new Error(`Only single-column primary keys are supported for routes on table ${context.key}`);
|
|
1221
|
-
}
|
|
1222
|
-
return entityKey[context.pkPropertyKeys[0]];
|
|
1223
|
-
}
|
|
1224
|
-
async function setMutationStatus(db, context, mutationId, status, options) {
|
|
1225
|
-
await db.query(`
|
|
1226
|
-
UPDATE ${context.journalTable}
|
|
1227
|
-
SET
|
|
1228
|
-
status = $2,
|
|
1229
|
-
attempt_count = $3,
|
|
1230
|
-
sent_at_us = COALESCE($4::bigint, sent_at_us),
|
|
1231
|
-
updated_at_us = $5::bigint,
|
|
1232
|
-
last_error = $6,
|
|
1233
|
-
next_retry_at_us = $7::bigint,
|
|
1234
|
-
last_http_status = $8,
|
|
1235
|
-
conflict_reason = $9
|
|
1236
|
-
WHERE mutation_id = $1
|
|
1237
|
-
`, [
|
|
1238
|
-
mutationId,
|
|
1239
|
-
status,
|
|
1240
|
-
options.attemptCount,
|
|
1241
|
-
options.sentAtUs ?? null,
|
|
1242
|
-
options.updatedAtUs,
|
|
1243
|
-
options.lastError ?? null,
|
|
1244
|
-
options.nextRetryAtUs ?? null,
|
|
1245
|
-
options.lastHttpStatus ?? null,
|
|
1246
|
-
options.conflictReason ?? null
|
|
1247
|
-
]);
|
|
1248
|
-
}
|
|
1249
1015
|
async function applyMutationStatusUpdates(db, context, updates) {
|
|
1250
1016
|
if (updates.length === 0) {
|
|
1251
1017
|
return;
|
|
@@ -1328,46 +1094,6 @@ async function applyMutationStatusUpdates(db, context, updates) {
|
|
|
1328
1094
|
WHERE journal.mutation_id = updates.mutation_id::uuid
|
|
1329
1095
|
`, params);
|
|
1330
1096
|
}
|
|
1331
|
-
async function markDeleteAcknowledged(db, context, mutationId) {
|
|
1332
|
-
const ackedAtUs = nowMicroseconds();
|
|
1333
|
-
await db.query(`
|
|
1334
|
-
UPDATE ${context.journalTable}
|
|
1335
|
-
SET
|
|
1336
|
-
status = 'acked',
|
|
1337
|
-
acked_at_us = $2::bigint,
|
|
1338
|
-
updated_at_us = $2::bigint,
|
|
1339
|
-
last_error = NULL,
|
|
1340
|
-
last_http_status = 204,
|
|
1341
|
-
conflict_reason = NULL,
|
|
1342
|
-
next_retry_at_us = NULL
|
|
1343
|
-
WHERE mutation_id = $1
|
|
1344
|
-
`, [mutationId, ackedAtUs]);
|
|
1345
|
-
}
|
|
1346
|
-
async function hasLaterMutations(db, context, entityKeyJson, mutationSeq) {
|
|
1347
|
-
const result = await db.query(`
|
|
1348
|
-
SELECT COUNT(*)::int AS count
|
|
1349
|
-
FROM ${context.journalTable}
|
|
1350
|
-
WHERE entity_key_json = $1
|
|
1351
|
-
AND mutation_seq > $2
|
|
1352
|
-
`, [entityKeyJson, mutationSeq]);
|
|
1353
|
-
return (result.rows[0]?.count ?? 0) > 0;
|
|
1354
|
-
}
|
|
1355
|
-
async function updateOverlayTimestamps(db, context, entityKey, record, localUpdatedAtUs) {
|
|
1356
|
-
if (!hasProperty(context, "createdAtUs") || !hasProperty(context, "updatedAtUs")) {
|
|
1357
|
-
return;
|
|
1358
|
-
}
|
|
1359
|
-
await db.query(`
|
|
1360
|
-
UPDATE ${context.overlayTable}
|
|
1361
|
-
SET
|
|
1362
|
-
created_at_us = $${context.pkPropertyKeys.length + 1}::bigint,
|
|
1363
|
-
updated_at_us = $${context.pkPropertyKeys.length + 2}::bigint,
|
|
1364
|
-
local_updated_at_us = $${context.pkPropertyKeys.length + 3}::bigint
|
|
1365
|
-
WHERE ${buildWhereClause(context)}
|
|
1366
|
-
`, [...buildWhereParams(context, entityKey), String(record.createdAtUs), String(record.updatedAtUs), localUpdatedAtUs]);
|
|
1367
|
-
}
|
|
1368
|
-
function buildWhereClause(context) {
|
|
1369
|
-
return context.pkColumnNames.map((columnName, index) => `${columnName} = $${index + 1}`).join(" AND ");
|
|
1370
|
-
}
|
|
1371
1097
|
function buildColumnEquality(columnNames, leftAlias, rightAlias) {
|
|
1372
1098
|
return columnNames.map((columnName) => `${leftAlias}.${columnName} = ${rightAlias}.${columnName}`).join(" AND ");
|
|
1373
1099
|
}
|
|
@@ -1386,9 +1112,6 @@ function buildJournalSequenceName(journalTable) {
|
|
|
1386
1112
|
function escapeSqlString(value) {
|
|
1387
1113
|
return value.replace(/'/g, "''");
|
|
1388
1114
|
}
|
|
1389
|
-
function buildWhereParams(context, entityKey) {
|
|
1390
|
-
return context.pkPropertyKeys.map((propertyKey) => entityKey[propertyKey]);
|
|
1391
|
-
}
|
|
1392
1115
|
function formatSqlValuePlaceholder(position, columnName) {
|
|
1393
1116
|
return /_at_us$/.test(columnName) ? `$${position}::bigint` : `$${position}`;
|
|
1394
1117
|
}
|
|
@@ -1407,21 +1130,6 @@ function extractRecordFromState(context, state) {
|
|
|
1407
1130
|
function isRecord(value) {
|
|
1408
1131
|
return typeof value === "object" && value !== null;
|
|
1409
1132
|
}
|
|
1410
|
-
function toOptionalString(value) {
|
|
1411
|
-
if (value === undefined || value === null) {
|
|
1412
|
-
return null;
|
|
1413
|
-
}
|
|
1414
|
-
switch (typeof value) {
|
|
1415
|
-
case "string":
|
|
1416
|
-
return value;
|
|
1417
|
-
case "number":
|
|
1418
|
-
case "boolean":
|
|
1419
|
-
case "bigint":
|
|
1420
|
-
return String(value);
|
|
1421
|
-
default:
|
|
1422
|
-
return JSON.stringify(value);
|
|
1423
|
-
}
|
|
1424
|
-
}
|
|
1425
1133
|
|
|
1426
1134
|
class MutationRequestError extends Error {
|
|
1427
1135
|
status;
|
|
@@ -1433,6 +1141,7 @@ class MutationRequestError extends Error {
|
|
|
1433
1141
|
}
|
|
1434
1142
|
|
|
1435
1143
|
// packages/client/src/schema.ts
|
|
1144
|
+
import { getViewConfig as getViewConfig2 } from "drizzle-orm/pg-core";
|
|
1436
1145
|
import {
|
|
1437
1146
|
getLocalSyncPrimaryKeyColumns,
|
|
1438
1147
|
getSyncRegistrySchema as getSyncRegistrySchema2,
|
|
@@ -1513,6 +1222,25 @@ function generateLocalSchemaSql(registry) {
|
|
|
1513
1222
|
statements.push(`CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_pk_seq_idx ON ${projection.journalTable} (${entry.primaryKey.columns.join(", ")}, mutation_seq);`);
|
|
1514
1223
|
statements.push(`CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_seq_idx ON ${projection.journalTable} (entity_key_json, mutation_seq);`);
|
|
1515
1224
|
statements.push(`CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_status_seq_idx ON ${projection.journalTable} (entity_key_json, status, mutation_seq);`);
|
|
1225
|
+
const triggerFnName = `${projection.syncedTable}_reconcile_on_sync`;
|
|
1226
|
+
const pkMatchSql = (alias) => primaryKeyColumns.map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`).join(" AND ");
|
|
1227
|
+
const pkOverlayMatchSql = primaryKeyColumns.map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`).join(" AND ");
|
|
1228
|
+
statements.push(`CREATE OR REPLACE FUNCTION ${triggerFnName}() RETURNS TRIGGER AS $$
|
|
1229
|
+
` + `BEGIN
|
|
1230
|
+
` + ` DELETE FROM ${projection.journalTable}
|
|
1231
|
+
` + ` WHERE status = 'acked' AND (${pkMatchSql(projection.journalTable)});
|
|
1232
|
+
` + ` DELETE FROM ${projection.overlayTable} AS "overlay"
|
|
1233
|
+
` + ` WHERE (${pkOverlayMatchSql})
|
|
1234
|
+
` + ` AND NOT EXISTS (
|
|
1235
|
+
` + ` SELECT 1 FROM ${projection.journalTable} AS j
|
|
1236
|
+
` + ` WHERE (${pkMatchSql("j")})
|
|
1237
|
+
` + ` );
|
|
1238
|
+
` + ` RETURN COALESCE(NEW, OLD);
|
|
1239
|
+
` + `END;
|
|
1240
|
+
` + `$$ LANGUAGE plpgsql;`);
|
|
1241
|
+
statements.push(`CREATE OR REPLACE TRIGGER ${triggerFnName}
|
|
1242
|
+
` + `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}
|
|
1243
|
+
` + `FOR EACH ROW EXECUTE FUNCTION ${triggerFnName}();`);
|
|
1516
1244
|
statements.push(`CREATE OR REPLACE VIEW ${projection.readModel} AS
|
|
1517
1245
|
${buildReadModelViewSql(entry, projection, columns.map((column) => column.name))};`);
|
|
1518
1246
|
}
|
|
@@ -1714,11 +1442,12 @@ function buildPrimaryKeyMatch(primaryKeyColumns) {
|
|
|
1714
1442
|
}
|
|
1715
1443
|
function getClientProjection(entry, tableKey, localSchema) {
|
|
1716
1444
|
const projection = baseProjection(entry, tableKey);
|
|
1445
|
+
const readModelName = entry.view != null ? getViewConfig2(entry.view).name : projection.syncedTable;
|
|
1717
1446
|
return {
|
|
1718
1447
|
syncedTable: qualifyIdentifier(localSchema, projection.syncedTable),
|
|
1719
1448
|
...projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {},
|
|
1720
1449
|
...projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {},
|
|
1721
|
-
readModel: qualifyIdentifier(localSchema,
|
|
1450
|
+
readModel: qualifyIdentifier(localSchema, readModelName)
|
|
1722
1451
|
};
|
|
1723
1452
|
}
|
|
1724
1453
|
function baseProjection(entry, tableKey) {
|
|
@@ -1800,7 +1529,6 @@ async function createSyncClient(options) {
|
|
|
1800
1529
|
db: pglite,
|
|
1801
1530
|
registry: options.registry,
|
|
1802
1531
|
writeUrl: options.writeUrl,
|
|
1803
|
-
batchWriteUrl: options.batchWriteUrl ?? options.writeUrl,
|
|
1804
1532
|
...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}
|
|
1805
1533
|
});
|
|
1806
1534
|
await mutationRuntime.recoverSending();
|
|
@@ -1813,6 +1541,7 @@ async function createSyncClient(options) {
|
|
|
1813
1541
|
const client = {
|
|
1814
1542
|
drizzle: drizzleDb,
|
|
1815
1543
|
pglite,
|
|
1544
|
+
views: buildViews(options.registry),
|
|
1816
1545
|
tables: Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
|
|
1817
1546
|
tableKey,
|
|
1818
1547
|
{
|
|
@@ -1871,6 +1600,9 @@ function createDrizzleDatabase(client, schema) {
|
|
|
1871
1600
|
function buildSchema(registry) {
|
|
1872
1601
|
return Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, entry.table]));
|
|
1873
1602
|
}
|
|
1603
|
+
function buildViews(registry) {
|
|
1604
|
+
return Object.fromEntries(Object.entries(registry).flatMap(([key, entry]) => entry.view != null ? [[key, entry.view]] : []));
|
|
1605
|
+
}
|
|
1874
1606
|
function buildSyncConfigFromRegistry(registry, electricUrl) {
|
|
1875
1607
|
return {
|
|
1876
1608
|
electricUrl,
|
|
@@ -1885,7 +1617,6 @@ function buildSyncTableInput(entry, tableKey) {
|
|
|
1885
1617
|
mode: entry.mode,
|
|
1886
1618
|
primaryKey: entry.primaryKey,
|
|
1887
1619
|
shape: entry.shape,
|
|
1888
|
-
routes: entry.routes,
|
|
1889
1620
|
clientProjection
|
|
1890
1621
|
};
|
|
1891
1622
|
}
|
|
@@ -1900,4 +1631,4 @@ export {
|
|
|
1900
1631
|
createSyncClient
|
|
1901
1632
|
};
|
|
1902
1633
|
|
|
1903
|
-
//# debugId=
|
|
1634
|
+
//# debugId=630ADC166CA4025464756E2164756E21
|