@pgxsinkit/client 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.
- package/dist/index.js +1815 -0
- package/dist/index.js.map +12 -0
- package/package.json +33 -0
- package/src/index.ts +276 -0
- package/src/mutation.ts +2103 -0
- package/src/schema.ts +302 -0
package/src/mutation.ts
ADDED
|
@@ -0,0 +1,2103 @@
|
|
|
1
|
+
import type { AnyPgTable } from "drizzle-orm/pg-core";
|
|
2
|
+
import { ZodObject } from "zod";
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
BatchMutationAck,
|
|
6
|
+
MutationDiagnostics,
|
|
7
|
+
SyncTableCreateInput,
|
|
8
|
+
SyncTableEntry,
|
|
9
|
+
SyncTableName,
|
|
10
|
+
SyncTableRecord,
|
|
11
|
+
SyncTableRegistry,
|
|
12
|
+
SyncTableUpdateInput,
|
|
13
|
+
} from "@pgxsinkit/contracts";
|
|
14
|
+
import { getProjectedColumns as getProjectedTableColumns, getSyncRegistrySchema } from "@pgxsinkit/contracts";
|
|
15
|
+
|
|
16
|
+
export type MutationStatus = "pending" | "sending" | "acked" | "failed";
|
|
17
|
+
export type MutationKind = "create" | "update" | "delete";
|
|
18
|
+
|
|
19
|
+
export type MutationBatchItem<TRegistry extends SyncTableRegistry> = {
|
|
20
|
+
[TKey in SyncTableName<TRegistry>]:
|
|
21
|
+
| {
|
|
22
|
+
table: TKey;
|
|
23
|
+
kind: "create";
|
|
24
|
+
input: SyncTableCreateInput<TRegistry, TKey>;
|
|
25
|
+
}
|
|
26
|
+
| {
|
|
27
|
+
table: TKey;
|
|
28
|
+
kind: "update";
|
|
29
|
+
entityKey: Record<string, string>;
|
|
30
|
+
patch: SyncTableUpdateInput<TRegistry, TKey>;
|
|
31
|
+
}
|
|
32
|
+
| {
|
|
33
|
+
table: TKey;
|
|
34
|
+
kind: "delete";
|
|
35
|
+
entityKey: Record<string, string>;
|
|
36
|
+
};
|
|
37
|
+
}[SyncTableName<TRegistry>];
|
|
38
|
+
|
|
39
|
+
export const DEFAULT_FLUSH_BATCH_SIZE = 100;
|
|
40
|
+
|
|
41
|
+
export interface MutationDetail {
|
|
42
|
+
tableName: string;
|
|
43
|
+
entityKey: Record<string, string>;
|
|
44
|
+
mutationId: string;
|
|
45
|
+
mutationSeq: number;
|
|
46
|
+
mutationKind: MutationKind;
|
|
47
|
+
status: MutationStatus;
|
|
48
|
+
attemptCount: number;
|
|
49
|
+
lastHttpStatus: number | null;
|
|
50
|
+
lastError: string | null;
|
|
51
|
+
conflictReason: string | null;
|
|
52
|
+
nextRetryAtUs: string | null;
|
|
53
|
+
serverUpdatedAtUs: string | null;
|
|
54
|
+
updatedAtUs: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface MutationDb {
|
|
58
|
+
exec: (sql: string) => Promise<unknown>;
|
|
59
|
+
query: <TRow extends Record<string, unknown> = Record<string, unknown>>(
|
|
60
|
+
sql: string,
|
|
61
|
+
params?: unknown[],
|
|
62
|
+
) => Promise<{ rows: TRow[] }>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {
|
|
66
|
+
db: MutationDb;
|
|
67
|
+
registry: TRegistry;
|
|
68
|
+
writeUrl: string;
|
|
69
|
+
batchWriteUrl?: string;
|
|
70
|
+
authToken?: string;
|
|
71
|
+
getAuthToken?: () => Promise<string | undefined>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface TableContext {
|
|
75
|
+
key: string;
|
|
76
|
+
entry: SyncTableEntry<AnyPgTable>;
|
|
77
|
+
readModel: string;
|
|
78
|
+
syncedTable: string;
|
|
79
|
+
overlayTable: string;
|
|
80
|
+
journalTable: string;
|
|
81
|
+
journalSequence: string;
|
|
82
|
+
routeBasePath?: string;
|
|
83
|
+
pkColumnNames: string[];
|
|
84
|
+
pkPropertyKeys: string[];
|
|
85
|
+
recordIncludesOverlayState: boolean;
|
|
86
|
+
columns: Array<{
|
|
87
|
+
propertyKey: string;
|
|
88
|
+
column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number]["column"];
|
|
89
|
+
}>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
|
|
93
|
+
create: <TKey extends SyncTableName<TRegistry>>(
|
|
94
|
+
table: TKey,
|
|
95
|
+
input: SyncTableCreateInput<TRegistry, TKey>,
|
|
96
|
+
) => Promise<void>;
|
|
97
|
+
update: <TKey extends SyncTableName<TRegistry>>(
|
|
98
|
+
table: TKey,
|
|
99
|
+
entityKey: Record<string, string>,
|
|
100
|
+
patch: SyncTableUpdateInput<TRegistry, TKey>,
|
|
101
|
+
) => Promise<void>;
|
|
102
|
+
delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
103
|
+
batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;
|
|
104
|
+
flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
105
|
+
reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
106
|
+
retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
107
|
+
recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
108
|
+
readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;
|
|
109
|
+
readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;
|
|
110
|
+
createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(
|
|
111
|
+
table: TKey,
|
|
112
|
+
input: SyncTableCreateInput<TRegistry, TKey>,
|
|
113
|
+
) => SyncTableRecord<TRegistry, TKey>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function nowMicroseconds(): string {
|
|
117
|
+
return (BigInt(Date.now()) * 1000n).toString();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function computeBackoffDelayMs(attemptCount: number) {
|
|
121
|
+
const exponent = Math.max(attemptCount - 1, 0);
|
|
122
|
+
return Math.min(1000 * 2 ** exponent, 30_000);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function computeNextRetryAtUs(nowUs: string, attemptCount: number) {
|
|
126
|
+
return (BigInt(nowUs) + BigInt(computeBackoffDelayMs(attemptCount)) * 1000n).toString();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function shouldClearOverlayRow(syncedUpdatedAtUs: string, serverUpdatedAtUs: string | null) {
|
|
130
|
+
if (serverUpdatedAtUs === null) {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return BigInt(syncedUpdatedAtUs) >= BigInt(serverUpdatedAtUs);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
138
|
+
options: CreateMutationRuntimeOptions<TRegistry>,
|
|
139
|
+
): MutationRuntime<TRegistry> {
|
|
140
|
+
const resolveAuthToken = async () => {
|
|
141
|
+
if (options.getAuthToken) {
|
|
142
|
+
return await options.getAuthToken();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return options.authToken;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const tableContexts = buildTableContexts(options.registry, options.batchWriteUrl === undefined);
|
|
149
|
+
let flushQueue = Promise.resolve();
|
|
150
|
+
|
|
151
|
+
const getTableContext = (table: SyncTableName<TRegistry>) => {
|
|
152
|
+
const context = tableContexts[table];
|
|
153
|
+
|
|
154
|
+
if (!context) {
|
|
155
|
+
throw new Error(`Unknown mutation table: ${String(table)}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return context;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const runInTransaction = async (operation: () => Promise<void>) => {
|
|
162
|
+
await options.db.exec("BEGIN");
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
await operation();
|
|
166
|
+
await options.db.exec("COMMIT");
|
|
167
|
+
} catch (error) {
|
|
168
|
+
await options.db.exec("ROLLBACK");
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const normalizeBatchItem = (item: MutationBatchItem<TRegistry>, order: number): NormalizedBatchItem => {
|
|
174
|
+
const context = getTableContext(item.table as SyncTableName<TRegistry>);
|
|
175
|
+
const mutationId = globalThis.crypto.randomUUID();
|
|
176
|
+
const nowUs = nowMicroseconds();
|
|
177
|
+
|
|
178
|
+
switch (item.kind) {
|
|
179
|
+
case "create": {
|
|
180
|
+
const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, item.input));
|
|
181
|
+
const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
context,
|
|
185
|
+
kind: "create",
|
|
186
|
+
entityKey,
|
|
187
|
+
entityKeyJson: serializeEntityKey(entityKey),
|
|
188
|
+
optimisticRecord,
|
|
189
|
+
input: item.input,
|
|
190
|
+
mutationId,
|
|
191
|
+
nowUs,
|
|
192
|
+
order,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
case "update": {
|
|
196
|
+
const entityKey = normalizeEntityKey(context, item.entityKey);
|
|
197
|
+
const patch = ensureRecord(parseUpdateInput(context, item.patch));
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
context,
|
|
201
|
+
kind: "update",
|
|
202
|
+
entityKey,
|
|
203
|
+
entityKeyJson: serializeEntityKey(entityKey),
|
|
204
|
+
patch,
|
|
205
|
+
mutationId,
|
|
206
|
+
nowUs,
|
|
207
|
+
order,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
case "delete": {
|
|
211
|
+
const entityKey = normalizeEntityKey(context, item.entityKey);
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
context,
|
|
215
|
+
kind: "delete",
|
|
216
|
+
entityKey,
|
|
217
|
+
entityKeyJson: serializeEntityKey(entityKey),
|
|
218
|
+
mutationId,
|
|
219
|
+
nowUs,
|
|
220
|
+
order,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const enqueueBatch = async (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => {
|
|
227
|
+
if (items.length === 0) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index));
|
|
232
|
+
const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();
|
|
233
|
+
|
|
234
|
+
for (const item of normalizedItems) {
|
|
235
|
+
const existing = batchGroups.get(item.context.key);
|
|
236
|
+
|
|
237
|
+
if (existing) {
|
|
238
|
+
existing.items.push(item);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
batchGroups.set(item.context.key, {
|
|
243
|
+
context: item.context,
|
|
244
|
+
items: [item],
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
for (const { context, items: groupedItems } of batchGroups.values()) {
|
|
249
|
+
groupedItems.sort((left, right) => left.order - right.order);
|
|
250
|
+
const uniqueEntities = dedupeBatchEntities(groupedItems);
|
|
251
|
+
const latestMutationStates = await readLatestMutationStates(options.db, context, uniqueEntities);
|
|
252
|
+
const currentRecordStates = await readCurrentRecordStates(options.db, context, uniqueEntities);
|
|
253
|
+
const entityStates = new Map<string, BatchEntityState>();
|
|
254
|
+
|
|
255
|
+
for (const entity of uniqueEntities) {
|
|
256
|
+
const latestState = latestMutationStates.get(entity.entityKeyJson);
|
|
257
|
+
const currentState = currentRecordStates.get(entity.entityKeyJson);
|
|
258
|
+
|
|
259
|
+
entityStates.set(entity.entityKeyJson, {
|
|
260
|
+
entityKey: entity.entityKey,
|
|
261
|
+
entityKeyJson: entity.entityKeyJson,
|
|
262
|
+
record: currentState ? extractRecordFromState(context, currentState) : null,
|
|
263
|
+
overlayKind: currentState?.overlayKind ?? null,
|
|
264
|
+
localUpdatedAtUs: currentState?.localUpdatedAtUs ?? null,
|
|
265
|
+
latestMutationSeq: latestState?.latestMutationSeq ?? null,
|
|
266
|
+
latestMutationKind: latestState?.latestMutationKind ?? null,
|
|
267
|
+
latestMutationStatus: latestState?.latestMutationStatus ?? null,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const plannedMutations: PlannedMutationInsert[] = [];
|
|
272
|
+
const plannedOverlays = new Map<string, PlannedOverlayUpsert>();
|
|
273
|
+
|
|
274
|
+
for (const item of groupedItems) {
|
|
275
|
+
const entityState = entityStates.get(item.entityKeyJson);
|
|
276
|
+
|
|
277
|
+
if (!entityState) {
|
|
278
|
+
throw new Error(`Missing batch state for table ${context.key}`);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
switch (item.kind) {
|
|
282
|
+
case "create": {
|
|
283
|
+
if ((entityState.latestMutationSeq ?? 0) !== 0) {
|
|
284
|
+
throw new Error(`${context.key} already has queued mutations`);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
plannedMutations.push({
|
|
288
|
+
mutationId: item.mutationId,
|
|
289
|
+
entityKey: item.entityKey,
|
|
290
|
+
entityKeyJson: item.entityKeyJson,
|
|
291
|
+
mutationKind: "create",
|
|
292
|
+
payloadJson: JSON.stringify({
|
|
293
|
+
kind: "create",
|
|
294
|
+
value: item.input,
|
|
295
|
+
}),
|
|
296
|
+
nowUs: item.nowUs,
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
entityState.record = item.optimisticRecord;
|
|
300
|
+
entityState.overlayKind = "pending_create";
|
|
301
|
+
entityState.localUpdatedAtUs = item.nowUs;
|
|
302
|
+
entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;
|
|
303
|
+
entityState.latestMutationKind = "create";
|
|
304
|
+
entityState.latestMutationStatus = "pending";
|
|
305
|
+
plannedOverlays.set(item.entityKeyJson, {
|
|
306
|
+
entityKey: item.entityKey,
|
|
307
|
+
record: item.optimisticRecord,
|
|
308
|
+
overlayKind: "pending_create",
|
|
309
|
+
localUpdatedAtUs: item.nowUs,
|
|
310
|
+
});
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
case "update": {
|
|
314
|
+
if (!entityState.record) {
|
|
315
|
+
throw new Error(`${context.key} not found in local read model`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (entityState.latestMutationKind === "delete" && entityState.latestMutationStatus !== "acked") {
|
|
319
|
+
throw new Error(`${context.key} is already queued for deletion`);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const overlayKind = entityState.overlayKind === "pending_create" ? "pending_create" : "pending_update";
|
|
323
|
+
const optimisticRecord = ensureRecord(
|
|
324
|
+
buildOptimisticRecord(
|
|
325
|
+
context,
|
|
326
|
+
{
|
|
327
|
+
...entityState.record,
|
|
328
|
+
...item.patch,
|
|
329
|
+
updatedAtUs: item.nowUs,
|
|
330
|
+
},
|
|
331
|
+
{
|
|
332
|
+
overlayKind,
|
|
333
|
+
localUpdatedAtUs: item.nowUs,
|
|
334
|
+
},
|
|
335
|
+
),
|
|
336
|
+
);
|
|
337
|
+
plannedMutations.push({
|
|
338
|
+
mutationId: item.mutationId,
|
|
339
|
+
entityKey: item.entityKey,
|
|
340
|
+
entityKeyJson: item.entityKeyJson,
|
|
341
|
+
mutationKind: "update",
|
|
342
|
+
payloadJson: JSON.stringify({
|
|
343
|
+
kind: "update",
|
|
344
|
+
patch: item.patch,
|
|
345
|
+
}),
|
|
346
|
+
nowUs: item.nowUs,
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
entityState.record = optimisticRecord;
|
|
350
|
+
entityState.overlayKind = overlayKind;
|
|
351
|
+
entityState.localUpdatedAtUs = item.nowUs;
|
|
352
|
+
entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;
|
|
353
|
+
entityState.latestMutationKind = "update";
|
|
354
|
+
entityState.latestMutationStatus = "pending";
|
|
355
|
+
plannedOverlays.set(item.entityKeyJson, {
|
|
356
|
+
entityKey: item.entityKey,
|
|
357
|
+
record: optimisticRecord,
|
|
358
|
+
overlayKind,
|
|
359
|
+
localUpdatedAtUs: item.nowUs,
|
|
360
|
+
});
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
case "delete": {
|
|
364
|
+
if (!entityState.record) {
|
|
365
|
+
throw new Error(`${context.key} not found in local read model`);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (entityState.latestMutationKind === "delete" && entityState.latestMutationStatus !== "acked") {
|
|
369
|
+
throw new Error(`${context.key} is already queued for deletion`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
plannedMutations.push({
|
|
373
|
+
mutationId: item.mutationId,
|
|
374
|
+
entityKey: item.entityKey,
|
|
375
|
+
entityKeyJson: item.entityKeyJson,
|
|
376
|
+
mutationKind: "delete",
|
|
377
|
+
payloadJson: JSON.stringify({
|
|
378
|
+
kind: "delete",
|
|
379
|
+
entityKey: item.entityKey,
|
|
380
|
+
}),
|
|
381
|
+
nowUs: item.nowUs,
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
entityState.overlayKind = "pending_delete";
|
|
385
|
+
entityState.localUpdatedAtUs = item.nowUs;
|
|
386
|
+
entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;
|
|
387
|
+
entityState.latestMutationKind = "delete";
|
|
388
|
+
entityState.latestMutationStatus = "pending";
|
|
389
|
+
plannedOverlays.set(item.entityKeyJson, {
|
|
390
|
+
entityKey: item.entityKey,
|
|
391
|
+
record: entityState.record,
|
|
392
|
+
overlayKind: "pending_delete",
|
|
393
|
+
localUpdatedAtUs: item.nowUs,
|
|
394
|
+
});
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
await insertMutationsBulk(options.db, context, plannedMutations);
|
|
401
|
+
await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
const runFlush = async (table?: SyncTableName<TRegistry>) => {
|
|
406
|
+
if (options.batchWriteUrl) {
|
|
407
|
+
const affectedContexts = new Map<string, TableContext>();
|
|
408
|
+
let processedCount = 0;
|
|
409
|
+
|
|
410
|
+
do {
|
|
411
|
+
const batchResult = await flushBatch(
|
|
412
|
+
options.db,
|
|
413
|
+
tableContexts as Record<string, TableContext>,
|
|
414
|
+
options.batchWriteUrl,
|
|
415
|
+
table,
|
|
416
|
+
resolveAuthToken,
|
|
417
|
+
);
|
|
418
|
+
|
|
419
|
+
processedCount = batchResult.processedCount;
|
|
420
|
+
|
|
421
|
+
for (const context of batchResult.affectedContexts) {
|
|
422
|
+
affectedContexts.set(context.key, context);
|
|
423
|
+
}
|
|
424
|
+
} while (processedCount > 0);
|
|
425
|
+
|
|
426
|
+
for (const context of affectedContexts.values()) {
|
|
427
|
+
await reconcileTable(options.db, context);
|
|
428
|
+
}
|
|
429
|
+
} else {
|
|
430
|
+
let processedCount = 0;
|
|
431
|
+
|
|
432
|
+
do {
|
|
433
|
+
processedCount = 0;
|
|
434
|
+
|
|
435
|
+
const contexts = filterContexts(tableContexts, table);
|
|
436
|
+
|
|
437
|
+
for (const context of contexts) {
|
|
438
|
+
processedCount += await flushTable(options.db, context, options.writeUrl, resolveAuthToken);
|
|
439
|
+
}
|
|
440
|
+
} while (processedCount > 0);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
return {
|
|
445
|
+
create: async (table, input) => {
|
|
446
|
+
await runInTransaction(async () => {
|
|
447
|
+
await enqueueBatch([
|
|
448
|
+
{
|
|
449
|
+
table,
|
|
450
|
+
kind: "create",
|
|
451
|
+
input,
|
|
452
|
+
},
|
|
453
|
+
]);
|
|
454
|
+
});
|
|
455
|
+
},
|
|
456
|
+
update: async (table, entityKeyInput, patch) => {
|
|
457
|
+
await runInTransaction(async () => {
|
|
458
|
+
await enqueueBatch([
|
|
459
|
+
{
|
|
460
|
+
table,
|
|
461
|
+
kind: "update",
|
|
462
|
+
entityKey: entityKeyInput,
|
|
463
|
+
patch,
|
|
464
|
+
},
|
|
465
|
+
]);
|
|
466
|
+
});
|
|
467
|
+
},
|
|
468
|
+
delete: async (table, entityKeyInput) => {
|
|
469
|
+
await runInTransaction(async () => {
|
|
470
|
+
await enqueueBatch([
|
|
471
|
+
{
|
|
472
|
+
table,
|
|
473
|
+
kind: "delete",
|
|
474
|
+
entityKey: entityKeyInput,
|
|
475
|
+
},
|
|
476
|
+
]);
|
|
477
|
+
});
|
|
478
|
+
},
|
|
479
|
+
batch: async (items) => {
|
|
480
|
+
await runInTransaction(async () => {
|
|
481
|
+
await enqueueBatch(items);
|
|
482
|
+
});
|
|
483
|
+
},
|
|
484
|
+
flush: async (table) => {
|
|
485
|
+
const nextFlush = flushQueue.then(() => runFlush(table));
|
|
486
|
+
flushQueue = nextFlush.catch(() => undefined);
|
|
487
|
+
await nextFlush;
|
|
488
|
+
},
|
|
489
|
+
reconcile: async (table) => {
|
|
490
|
+
const contexts = filterContexts(tableContexts, table);
|
|
491
|
+
|
|
492
|
+
for (const context of contexts) {
|
|
493
|
+
await reconcileTable(options.db, context);
|
|
494
|
+
}
|
|
495
|
+
},
|
|
496
|
+
retryFailed: async (table) => {
|
|
497
|
+
const contexts = filterContexts(tableContexts, table);
|
|
498
|
+
const nowUs = nowMicroseconds();
|
|
499
|
+
|
|
500
|
+
for (const context of contexts) {
|
|
501
|
+
await options.db.query(
|
|
502
|
+
`
|
|
503
|
+
UPDATE ${context.journalTable}
|
|
504
|
+
SET
|
|
505
|
+
status = 'pending',
|
|
506
|
+
next_retry_at_us = $1::bigint,
|
|
507
|
+
updated_at_us = $1::bigint,
|
|
508
|
+
conflict_reason = NULL
|
|
509
|
+
WHERE status = 'failed'
|
|
510
|
+
`,
|
|
511
|
+
[nowUs],
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
recoverSending: async (table) => {
|
|
516
|
+
const contexts = filterContexts(tableContexts, table);
|
|
517
|
+
const nowUs = nowMicroseconds();
|
|
518
|
+
|
|
519
|
+
for (const context of contexts) {
|
|
520
|
+
await options.db.query(
|
|
521
|
+
`
|
|
522
|
+
UPDATE ${context.journalTable}
|
|
523
|
+
SET
|
|
524
|
+
status = 'pending',
|
|
525
|
+
updated_at_us = $1::bigint,
|
|
526
|
+
sent_at_us = NULL,
|
|
527
|
+
next_retry_at_us = $1::bigint,
|
|
528
|
+
last_error = NULL,
|
|
529
|
+
last_http_status = NULL,
|
|
530
|
+
conflict_reason = NULL
|
|
531
|
+
WHERE status = 'sending'
|
|
532
|
+
`,
|
|
533
|
+
[nowUs],
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
},
|
|
537
|
+
readMutationStats: async (table) => {
|
|
538
|
+
const contexts = filterContexts(tableContexts, table);
|
|
539
|
+
const totals: MutationDiagnostics = {
|
|
540
|
+
pendingCount: 0,
|
|
541
|
+
sendingCount: 0,
|
|
542
|
+
failedCount: 0,
|
|
543
|
+
ackedCount: 0,
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
for (const context of contexts) {
|
|
547
|
+
const result = await options.db.query<MutationDiagnostics>(`
|
|
548
|
+
SELECT
|
|
549
|
+
COUNT(*) FILTER (WHERE status = 'pending')::int AS "pendingCount",
|
|
550
|
+
COUNT(*) FILTER (WHERE status = 'sending')::int AS "sendingCount",
|
|
551
|
+
COUNT(*) FILTER (WHERE status = 'failed')::int AS "failedCount",
|
|
552
|
+
COUNT(*) FILTER (WHERE status = 'acked')::int AS "ackedCount"
|
|
553
|
+
FROM ${context.journalTable}
|
|
554
|
+
`);
|
|
555
|
+
|
|
556
|
+
const row = result.rows[0];
|
|
557
|
+
if (!row) {
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
totals.pendingCount += row.pendingCount;
|
|
562
|
+
totals.sendingCount += row.sendingCount;
|
|
563
|
+
totals.failedCount += row.failedCount;
|
|
564
|
+
totals.ackedCount += row.ackedCount;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
return totals;
|
|
568
|
+
},
|
|
569
|
+
readMutationDetails: async (table) => {
|
|
570
|
+
const contexts = filterContexts(tableContexts, table);
|
|
571
|
+
const rows: MutationDetail[] = [];
|
|
572
|
+
|
|
573
|
+
for (const context of contexts) {
|
|
574
|
+
const result = await options.db.query<MutationDetailRow>(`
|
|
575
|
+
SELECT
|
|
576
|
+
mutation_id AS "mutationId",
|
|
577
|
+
entity_key_json AS "entityKeyJson",
|
|
578
|
+
mutation_seq AS "mutationSeq",
|
|
579
|
+
mutation_kind AS "mutationKind",
|
|
580
|
+
status,
|
|
581
|
+
attempt_count AS "attemptCount",
|
|
582
|
+
last_http_status AS "lastHttpStatus",
|
|
583
|
+
last_error AS "lastError",
|
|
584
|
+
conflict_reason AS "conflictReason",
|
|
585
|
+
next_retry_at_us::text AS "nextRetryAtUs",
|
|
586
|
+
server_updated_at_us::text AS "serverUpdatedAtUs",
|
|
587
|
+
updated_at_us::text AS "updatedAtUs"
|
|
588
|
+
FROM ${context.journalTable}
|
|
589
|
+
ORDER BY updated_at_us DESC, mutation_seq DESC
|
|
590
|
+
`);
|
|
591
|
+
|
|
592
|
+
rows.push(
|
|
593
|
+
...result.rows.map((row) => ({
|
|
594
|
+
tableName: context.key,
|
|
595
|
+
entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,
|
|
596
|
+
mutationId: row.mutationId,
|
|
597
|
+
mutationSeq: row.mutationSeq,
|
|
598
|
+
mutationKind: row.mutationKind,
|
|
599
|
+
status: row.status,
|
|
600
|
+
attemptCount: row.attemptCount,
|
|
601
|
+
lastHttpStatus: row.lastHttpStatus,
|
|
602
|
+
lastError: row.lastError,
|
|
603
|
+
conflictReason: row.conflictReason,
|
|
604
|
+
nextRetryAtUs: row.nextRetryAtUs,
|
|
605
|
+
serverUpdatedAtUs: row.serverUpdatedAtUs,
|
|
606
|
+
updatedAtUs: row.updatedAtUs,
|
|
607
|
+
})),
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));
|
|
612
|
+
},
|
|
613
|
+
createOptimisticRecord: (table, input) => {
|
|
614
|
+
const context = getTableContext(table);
|
|
615
|
+
return createOptimisticRecordFromContext(context, input);
|
|
616
|
+
},
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
interface MutationRow extends Record<string, unknown> {
|
|
621
|
+
mutationId: string;
|
|
622
|
+
entityKeyJson: string;
|
|
623
|
+
mutationSeq: number;
|
|
624
|
+
mutationKind: MutationKind;
|
|
625
|
+
status: MutationStatus;
|
|
626
|
+
payloadJson: string;
|
|
627
|
+
attemptCount: number;
|
|
628
|
+
lastHttpStatus: number | null;
|
|
629
|
+
lastError: string | null;
|
|
630
|
+
conflictReason: string | null;
|
|
631
|
+
nextRetryAtUs: string | null;
|
|
632
|
+
serverUpdatedAtUs: string | null;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
interface MutationDetailRow extends Record<string, unknown> {
|
|
636
|
+
mutationId: string;
|
|
637
|
+
entityKeyJson: string;
|
|
638
|
+
mutationSeq: number;
|
|
639
|
+
mutationKind: MutationKind;
|
|
640
|
+
status: MutationStatus;
|
|
641
|
+
attemptCount: number;
|
|
642
|
+
lastHttpStatus: number | null;
|
|
643
|
+
lastError: string | null;
|
|
644
|
+
conflictReason: string | null;
|
|
645
|
+
nextRetryAtUs: string | null;
|
|
646
|
+
serverUpdatedAtUs: string | null;
|
|
647
|
+
updatedAtUs: string;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
interface CurrentRecordStateRow extends Record<string, unknown> {
|
|
651
|
+
overlayKind: string;
|
|
652
|
+
localUpdatedAtUs: string;
|
|
653
|
+
latestMutationSeq: number | null;
|
|
654
|
+
latestMutationKind: MutationKind | null;
|
|
655
|
+
latestMutationStatus: MutationStatus | null;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
interface BatchLatestMutationStateRow extends Record<string, unknown> {
|
|
659
|
+
entityKeyJson: string;
|
|
660
|
+
latestMutationSeq: number | null;
|
|
661
|
+
latestMutationKind: MutationKind | null;
|
|
662
|
+
latestMutationStatus: MutationStatus | null;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
interface BatchCurrentRecordStateRow extends Record<string, unknown> {
|
|
666
|
+
entityKeyJson: string;
|
|
667
|
+
overlayKind: string;
|
|
668
|
+
localUpdatedAtUs: string;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
interface BatchEntityRef {
|
|
672
|
+
entityKey: Record<string, string>;
|
|
673
|
+
entityKeyJson: string;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
interface PlannedMutationInsert {
|
|
677
|
+
mutationId: string;
|
|
678
|
+
entityKey: Record<string, string>;
|
|
679
|
+
entityKeyJson: string;
|
|
680
|
+
mutationKind: MutationKind;
|
|
681
|
+
payloadJson: string;
|
|
682
|
+
nowUs: string;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
interface PlannedOverlayUpsert {
|
|
686
|
+
entityKey: Record<string, string>;
|
|
687
|
+
record: Record<string, unknown>;
|
|
688
|
+
overlayKind: string;
|
|
689
|
+
localUpdatedAtUs: string;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
interface BatchEntityState {
|
|
693
|
+
entityKey: Record<string, string>;
|
|
694
|
+
entityKeyJson: string;
|
|
695
|
+
record: Record<string, unknown> | null;
|
|
696
|
+
overlayKind: string | null;
|
|
697
|
+
localUpdatedAtUs: string | null;
|
|
698
|
+
latestMutationSeq: number | null;
|
|
699
|
+
latestMutationKind: MutationKind | null;
|
|
700
|
+
latestMutationStatus: MutationStatus | null;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
type NormalizedBatchItem =
|
|
704
|
+
| {
|
|
705
|
+
context: TableContext;
|
|
706
|
+
kind: "create";
|
|
707
|
+
entityKey: Record<string, string>;
|
|
708
|
+
entityKeyJson: string;
|
|
709
|
+
optimisticRecord: Record<string, unknown>;
|
|
710
|
+
input: unknown;
|
|
711
|
+
mutationId: string;
|
|
712
|
+
nowUs: string;
|
|
713
|
+
order: number;
|
|
714
|
+
}
|
|
715
|
+
| {
|
|
716
|
+
context: TableContext;
|
|
717
|
+
kind: "update";
|
|
718
|
+
entityKey: Record<string, string>;
|
|
719
|
+
entityKeyJson: string;
|
|
720
|
+
patch: Record<string, unknown>;
|
|
721
|
+
mutationId: string;
|
|
722
|
+
nowUs: string;
|
|
723
|
+
order: number;
|
|
724
|
+
}
|
|
725
|
+
| {
|
|
726
|
+
context: TableContext;
|
|
727
|
+
kind: "delete";
|
|
728
|
+
entityKey: Record<string, string>;
|
|
729
|
+
entityKeyJson: string;
|
|
730
|
+
mutationId: string;
|
|
731
|
+
nowUs: string;
|
|
732
|
+
order: number;
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry, requireRouteBasePath: boolean) {
|
|
736
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
737
|
+
|
|
738
|
+
return Object.fromEntries(
|
|
739
|
+
Object.entries(registry)
|
|
740
|
+
.filter(([, entry]) => entry.mode !== "readonly")
|
|
741
|
+
.map(([key, entry]) => [key, buildTableContext(key, entry, localSchema, requireRouteBasePath)]),
|
|
742
|
+
) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
function buildTableContext(
|
|
746
|
+
key: string,
|
|
747
|
+
entry: SyncTableEntry<AnyPgTable>,
|
|
748
|
+
localSchema: string,
|
|
749
|
+
requireRouteBasePath: boolean,
|
|
750
|
+
): TableContext {
|
|
751
|
+
if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
|
|
752
|
+
throw new Error(`overlay and journal tables are required for writable table ${key}`);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
if (requireRouteBasePath && !entry.routes?.basePath) {
|
|
756
|
+
throw new Error(`routes.basePath is required for writable table ${key}`);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({
|
|
760
|
+
propertyKey,
|
|
761
|
+
column,
|
|
762
|
+
}));
|
|
763
|
+
|
|
764
|
+
const pkPropertyKeys = entry.primaryKey.columns.map((columnName) => {
|
|
765
|
+
const column = columns.find((candidate) => candidate.column.name === columnName);
|
|
766
|
+
|
|
767
|
+
if (!column) {
|
|
768
|
+
throw new Error(`Primary key column ${columnName} was not found on table ${key}`);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
return column.propertyKey;
|
|
772
|
+
});
|
|
773
|
+
|
|
774
|
+
return {
|
|
775
|
+
key,
|
|
776
|
+
entry,
|
|
777
|
+
readModel: qualifyLocalIdentifier(localSchema, entry.clientProjection.readModel),
|
|
778
|
+
syncedTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.syncedTable),
|
|
779
|
+
overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),
|
|
780
|
+
journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),
|
|
781
|
+
journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),
|
|
782
|
+
...(entry.routes?.basePath ? { routeBasePath: entry.routes.basePath } : {}),
|
|
783
|
+
pkColumnNames: [...entry.primaryKey.columns],
|
|
784
|
+
pkPropertyKeys,
|
|
785
|
+
recordIncludesOverlayState: recordSchemaIncludesOverlayState(entry.schemas?.recordSchema),
|
|
786
|
+
columns,
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function filterContexts<TRegistry extends SyncTableRegistry>(
|
|
791
|
+
contexts: Partial<Record<SyncTableName<TRegistry>, TableContext>>,
|
|
792
|
+
table?: SyncTableName<TRegistry>,
|
|
793
|
+
) {
|
|
794
|
+
if (table) {
|
|
795
|
+
const context = contexts[table];
|
|
796
|
+
return context ? [context] : [];
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
return Object.values(contexts).filter((context): context is TableContext => context !== undefined);
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function createOptimisticRecordFromContext<TCreate, TRecord>(context: TableContext, input: TCreate): TRecord {
|
|
803
|
+
const parsed = parseCreateInput(context, input);
|
|
804
|
+
const record = {
|
|
805
|
+
...(isRecord(parsed) ? parsed : {}),
|
|
806
|
+
};
|
|
807
|
+
const nowUs = nowMicroseconds();
|
|
808
|
+
|
|
809
|
+
if (hasProperty(context, "createdAtUs") && record.createdAtUs === undefined) {
|
|
810
|
+
record.createdAtUs = nowUs;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
if (hasProperty(context, "updatedAtUs") && record.updatedAtUs === undefined) {
|
|
814
|
+
record.updatedAtUs = nowUs;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
return buildOptimisticRecord(context, record, {
|
|
818
|
+
overlayKind: "pending_create",
|
|
819
|
+
localUpdatedAtUs: nowUs,
|
|
820
|
+
}) as TRecord;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function parseCreateInput(context: TableContext, input: unknown) {
|
|
824
|
+
return context.entry.schemas?.createSchema ? context.entry.schemas.createSchema.parse(input) : input;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function parseUpdateInput(context: TableContext, input: unknown) {
|
|
828
|
+
return context.entry.schemas?.updateSchema ? context.entry.schemas.updateSchema.parse(input) : input;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function parseRecord(context: TableContext, input: unknown) {
|
|
832
|
+
return context.entry.schemas?.recordSchema ? context.entry.schemas.recordSchema.parse(input) : input;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function buildOptimisticRecord(
|
|
836
|
+
context: TableContext,
|
|
837
|
+
record: Record<string, unknown>,
|
|
838
|
+
options: {
|
|
839
|
+
overlayKind: string;
|
|
840
|
+
localUpdatedAtUs: string;
|
|
841
|
+
},
|
|
842
|
+
) {
|
|
843
|
+
if (!context.recordIncludesOverlayState) {
|
|
844
|
+
return parseRecord(context, record);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
return parseRecord(context, {
|
|
848
|
+
...record,
|
|
849
|
+
overlayKind: options.overlayKind,
|
|
850
|
+
localUpdatedAtUs: options.localUpdatedAtUs,
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function recordSchemaIncludesOverlayState(schema: unknown) {
|
|
855
|
+
if (!(schema instanceof ZodObject)) {
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
const shape = schema.shape;
|
|
860
|
+
return "overlayKind" in shape && "localUpdatedAtUs" in shape;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
function buildEntityKeyFromRecord(context: TableContext, record: unknown) {
|
|
864
|
+
const recordObject = ensureRecord(record);
|
|
865
|
+
return normalizeEntityKey(
|
|
866
|
+
context,
|
|
867
|
+
context.entry.adapters?.toEntityKey
|
|
868
|
+
? context.entry.adapters.toEntityKey(recordObject)
|
|
869
|
+
: Object.fromEntries(
|
|
870
|
+
context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])]),
|
|
871
|
+
),
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function normalizeEntityKey(context: TableContext, input: Record<string, string>) {
|
|
876
|
+
return Object.fromEntries(
|
|
877
|
+
context.pkPropertyKeys.map((propertyKey) => {
|
|
878
|
+
const value = input[propertyKey];
|
|
879
|
+
|
|
880
|
+
if (value === undefined) {
|
|
881
|
+
throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
return [propertyKey, String(value)];
|
|
885
|
+
}),
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function serializeEntityKey(entityKey: Record<string, string>) {
|
|
890
|
+
return JSON.stringify(entityKey);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
function dedupeBatchEntities(items: ReadonlyArray<NormalizedBatchItem>): BatchEntityRef[] {
|
|
894
|
+
const entities = new Map<string, BatchEntityRef>();
|
|
895
|
+
|
|
896
|
+
for (const item of items) {
|
|
897
|
+
if (!entities.has(item.entityKeyJson)) {
|
|
898
|
+
entities.set(item.entityKeyJson, {
|
|
899
|
+
entityKey: item.entityKey,
|
|
900
|
+
entityKeyJson: item.entityKeyJson,
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
return [...entities.values()];
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
async function readLatestMutationStates(
|
|
909
|
+
db: MutationDb,
|
|
910
|
+
context: TableContext,
|
|
911
|
+
entities: ReadonlyArray<BatchEntityRef>,
|
|
912
|
+
) {
|
|
913
|
+
if (entities.length === 0) {
|
|
914
|
+
return new Map<string, BatchLatestMutationStateRow>();
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const { cteSql, params } = buildBatchEntityInputCte(context, entities);
|
|
918
|
+
const result = await db.query<BatchLatestMutationStateRow>(
|
|
919
|
+
`
|
|
920
|
+
WITH ${cteSql},
|
|
921
|
+
latest_mutations AS (
|
|
922
|
+
SELECT DISTINCT ON (journal.entity_key_json)
|
|
923
|
+
journal.entity_key_json,
|
|
924
|
+
journal.mutation_seq,
|
|
925
|
+
journal.mutation_kind,
|
|
926
|
+
journal.status
|
|
927
|
+
FROM ${context.journalTable} AS journal
|
|
928
|
+
JOIN input_entities AS input
|
|
929
|
+
ON input.entity_key_json = journal.entity_key_json
|
|
930
|
+
ORDER BY journal.entity_key_json, journal.mutation_seq DESC
|
|
931
|
+
)
|
|
932
|
+
SELECT
|
|
933
|
+
input.entity_key_json AS "entityKeyJson",
|
|
934
|
+
latest.mutation_seq AS "latestMutationSeq",
|
|
935
|
+
latest.mutation_kind AS "latestMutationKind",
|
|
936
|
+
latest.status AS "latestMutationStatus"
|
|
937
|
+
FROM input_entities AS input
|
|
938
|
+
LEFT JOIN latest_mutations AS latest
|
|
939
|
+
ON latest.entity_key_json = input.entity_key_json
|
|
940
|
+
`,
|
|
941
|
+
params,
|
|
942
|
+
);
|
|
943
|
+
|
|
944
|
+
return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
async function readCurrentRecordStates(db: MutationDb, context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {
|
|
948
|
+
if (entities.length === 0) {
|
|
949
|
+
return new Map<string, BatchCurrentRecordStateRow>();
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const { cteSql, params } = buildBatchEntityInputCte(context, entities);
|
|
953
|
+
const overlaySelectColumns = buildContextSelectColumns(context, "overlay");
|
|
954
|
+
const syncedSelectColumns = buildContextSelectColumns(context, "synced");
|
|
955
|
+
const inputOverlayJoin = buildBatchEntityJoinClause(context, "overlay", "input");
|
|
956
|
+
const inputSyncedJoin = buildBatchEntityJoinClause(context, "synced", "input");
|
|
957
|
+
const syncedLocalUpdatedSql = hasProperty(context, "updatedAtUs")
|
|
958
|
+
? 'synced.updated_at_us::text AS "localUpdatedAtUs"'
|
|
959
|
+
: `'0' AS "localUpdatedAtUs"`;
|
|
960
|
+
|
|
961
|
+
const result = await db.query<BatchCurrentRecordStateRow>(
|
|
962
|
+
`
|
|
963
|
+
WITH ${cteSql},
|
|
964
|
+
overlay_rows AS (
|
|
965
|
+
SELECT
|
|
966
|
+
input.entity_key_json AS "entityKeyJson",
|
|
967
|
+
${overlaySelectColumns.join(",\n ")},
|
|
968
|
+
overlay.overlay_kind AS "overlayKind",
|
|
969
|
+
overlay.local_updated_at_us::text AS "localUpdatedAtUs"
|
|
970
|
+
FROM input_entities AS input
|
|
971
|
+
JOIN ${context.overlayTable} AS overlay
|
|
972
|
+
ON ${inputOverlayJoin}
|
|
973
|
+
),
|
|
974
|
+
synced_rows AS (
|
|
975
|
+
SELECT
|
|
976
|
+
input.entity_key_json AS "entityKeyJson",
|
|
977
|
+
${syncedSelectColumns.join(",\n ")},
|
|
978
|
+
'synced' AS "overlayKind",
|
|
979
|
+
${syncedLocalUpdatedSql}
|
|
980
|
+
FROM input_entities AS input
|
|
981
|
+
JOIN ${context.syncedTable} AS synced
|
|
982
|
+
ON ${inputSyncedJoin}
|
|
983
|
+
WHERE NOT EXISTS (
|
|
984
|
+
SELECT 1
|
|
985
|
+
FROM ${context.overlayTable} AS overlay
|
|
986
|
+
WHERE ${inputOverlayJoin}
|
|
987
|
+
)
|
|
988
|
+
)
|
|
989
|
+
SELECT *
|
|
990
|
+
FROM overlay_rows
|
|
991
|
+
UNION ALL
|
|
992
|
+
SELECT *
|
|
993
|
+
FROM synced_rows
|
|
994
|
+
`,
|
|
995
|
+
params,
|
|
996
|
+
);
|
|
997
|
+
|
|
998
|
+
return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
async function insertMutationsBulk(db: MutationDb, context: TableContext, rows: ReadonlyArray<PlannedMutationInsert>) {
|
|
1002
|
+
if (rows.length === 0) {
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
const insertColumnNames = [
|
|
1007
|
+
"mutation_id",
|
|
1008
|
+
...context.pkColumnNames,
|
|
1009
|
+
"entity_key_json",
|
|
1010
|
+
"mutation_seq",
|
|
1011
|
+
"mutation_kind",
|
|
1012
|
+
"status",
|
|
1013
|
+
"payload_json",
|
|
1014
|
+
"enqueued_at_us",
|
|
1015
|
+
"next_retry_at_us",
|
|
1016
|
+
"updated_at_us",
|
|
1017
|
+
];
|
|
1018
|
+
const params: unknown[] = [];
|
|
1019
|
+
const tuples = rows.map((row) => {
|
|
1020
|
+
const start = params.length;
|
|
1021
|
+
const values = [
|
|
1022
|
+
row.mutationId,
|
|
1023
|
+
...context.pkPropertyKeys.map((propertyKey) => row.entityKey[propertyKey]),
|
|
1024
|
+
row.entityKeyJson,
|
|
1025
|
+
row.mutationKind,
|
|
1026
|
+
"pending",
|
|
1027
|
+
row.payloadJson,
|
|
1028
|
+
row.nowUs,
|
|
1029
|
+
row.nowUs,
|
|
1030
|
+
row.nowUs,
|
|
1031
|
+
];
|
|
1032
|
+
|
|
1033
|
+
params.push(...values);
|
|
1034
|
+
|
|
1035
|
+
const valuePlaceholders = [
|
|
1036
|
+
formatSqlValuePlaceholder(start + 1, "mutation_id"),
|
|
1037
|
+
...context.pkColumnNames.map((columnName, index) => formatSqlValuePlaceholder(start + index + 2, columnName)),
|
|
1038
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 2, "entity_key_json"),
|
|
1039
|
+
`nextval('${escapeSqlString(context.journalSequence)}')::integer`,
|
|
1040
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 3, "mutation_kind"),
|
|
1041
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 4, "status"),
|
|
1042
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 5, "payload_json"),
|
|
1043
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 6, "enqueued_at_us"),
|
|
1044
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 7, "next_retry_at_us"),
|
|
1045
|
+
formatSqlValuePlaceholder(start + context.pkColumnNames.length + 8, "updated_at_us"),
|
|
1046
|
+
];
|
|
1047
|
+
|
|
1048
|
+
return `(${valuePlaceholders.join(", ")})`;
|
|
1049
|
+
});
|
|
1050
|
+
|
|
1051
|
+
await db.query(
|
|
1052
|
+
`
|
|
1053
|
+
INSERT INTO ${context.journalTable} (
|
|
1054
|
+
${insertColumnNames.join(", ")}
|
|
1055
|
+
)
|
|
1056
|
+
VALUES ${tuples.join(",\n ")}
|
|
1057
|
+
`,
|
|
1058
|
+
params,
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
async function upsertOverlayRecordsBulk(
|
|
1063
|
+
db: MutationDb,
|
|
1064
|
+
context: TableContext,
|
|
1065
|
+
rows: ReadonlyArray<PlannedOverlayUpsert>,
|
|
1066
|
+
) {
|
|
1067
|
+
if (rows.length === 0) {
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const overlayColumnNames = context.columns.map(({ column }) => column.name);
|
|
1072
|
+
const insertColumns = [...overlayColumnNames, "overlay_kind", "local_updated_at_us"];
|
|
1073
|
+
const updateColumns = [
|
|
1074
|
+
...overlayColumnNames.map((columnName) => `${columnName} = EXCLUDED.${columnName}`),
|
|
1075
|
+
"overlay_kind = EXCLUDED.overlay_kind",
|
|
1076
|
+
"local_updated_at_us = EXCLUDED.local_updated_at_us",
|
|
1077
|
+
];
|
|
1078
|
+
const params: unknown[] = [];
|
|
1079
|
+
const tuples = rows.map((row) => {
|
|
1080
|
+
const start = params.length;
|
|
1081
|
+
const values = [
|
|
1082
|
+
...context.columns.map(({ propertyKey }) => row.record[propertyKey] ?? null),
|
|
1083
|
+
row.overlayKind,
|
|
1084
|
+
row.localUpdatedAtUs,
|
|
1085
|
+
];
|
|
1086
|
+
|
|
1087
|
+
params.push(...values);
|
|
1088
|
+
|
|
1089
|
+
return `(${insertColumns
|
|
1090
|
+
.map((columnName, index) => formatSqlValuePlaceholder(start + index + 1, columnName))
|
|
1091
|
+
.join(", ")})`;
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
await db.query(
|
|
1095
|
+
`
|
|
1096
|
+
INSERT INTO ${context.overlayTable} (
|
|
1097
|
+
${insertColumns.join(", ")}
|
|
1098
|
+
)
|
|
1099
|
+
VALUES ${tuples.join(",\n ")}
|
|
1100
|
+
ON CONFLICT (${context.pkColumnNames.join(", ")})
|
|
1101
|
+
DO UPDATE SET
|
|
1102
|
+
${updateColumns.join(",\n ")}
|
|
1103
|
+
`,
|
|
1104
|
+
params,
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function buildBatchEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {
|
|
1109
|
+
const columns = ["entity_key_json", ...context.pkColumnNames];
|
|
1110
|
+
const params: unknown[] = [];
|
|
1111
|
+
const tuples = entities.map((entity) => {
|
|
1112
|
+
const start = params.length;
|
|
1113
|
+
const values = [
|
|
1114
|
+
entity.entityKeyJson,
|
|
1115
|
+
...context.pkPropertyKeys.map((propertyKey) => entity.entityKey[propertyKey]),
|
|
1116
|
+
];
|
|
1117
|
+
|
|
1118
|
+
params.push(...values);
|
|
1119
|
+
|
|
1120
|
+
return `(${columns
|
|
1121
|
+
.map((columnName, index) => formatBatchEntityInputPlaceholder(context, start + index + 1, columnName))
|
|
1122
|
+
.join(", ")})`;
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
return {
|
|
1126
|
+
cteSql: `input_entities (${columns.join(", ")}) AS (VALUES ${tuples.join(", ")})`,
|
|
1127
|
+
params,
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function formatBatchEntityInputPlaceholder(context: TableContext, position: number, columnName: string) {
|
|
1132
|
+
if (columnName === "entity_key_json") {
|
|
1133
|
+
return `$${position}`;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const columnEntry = context.columns.find(({ column }) => column.name === columnName);
|
|
1137
|
+
|
|
1138
|
+
if (!columnEntry) {
|
|
1139
|
+
return `$${position}`;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
switch (columnEntry.column.columnType) {
|
|
1143
|
+
case "PgUUID":
|
|
1144
|
+
return `$${position}::uuid`;
|
|
1145
|
+
case "PgBigInt64":
|
|
1146
|
+
case "PgBigInt53":
|
|
1147
|
+
return `$${position}::bigint`;
|
|
1148
|
+
case "PgInteger":
|
|
1149
|
+
case "PgSerial":
|
|
1150
|
+
case "PgSmallInt":
|
|
1151
|
+
return `$${position}::int`;
|
|
1152
|
+
case "PgBoolean":
|
|
1153
|
+
return `$${position}::boolean`;
|
|
1154
|
+
case "PgTimestamp":
|
|
1155
|
+
case "PgTimestampString":
|
|
1156
|
+
return `$${position}::timestamp`;
|
|
1157
|
+
default:
|
|
1158
|
+
return `$${position}`;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
function buildContextSelectColumns(context: TableContext, tableAlias: string) {
|
|
1163
|
+
return context.columns.map(({ propertyKey, column }) => {
|
|
1164
|
+
const qualifiedColumn = `${tableAlias}.${column.name}`;
|
|
1165
|
+
|
|
1166
|
+
if (column.columnType === "PgBigInt64" || column.columnType === "PgBigInt53") {
|
|
1167
|
+
return `${qualifiedColumn}::text AS "${propertyKey}"`;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
return `${qualifiedColumn} AS "${propertyKey}"`;
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function buildBatchEntityJoinClause(context: TableContext, tableAlias: string, inputAlias: string) {
|
|
1175
|
+
return context.pkColumnNames
|
|
1176
|
+
.map((columnName) => `${tableAlias}.${columnName} = ${inputAlias}.${columnName}`)
|
|
1177
|
+
.join(" AND ");
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
// ---------------------------------------------------------------------------
|
|
1181
|
+
// Batch flush — sends one send-eligible slice of pending mutations across all
|
|
1182
|
+
// target tables in a single POST /api/mutations call. The public flush()
|
|
1183
|
+
// wrapper loops until no more eligible rows remain.
|
|
1184
|
+
// ---------------------------------------------------------------------------
|
|
1185
|
+
|
|
1186
|
+
interface PendingBatchRow extends MutationRow {
|
|
1187
|
+
tableKey: string;
|
|
1188
|
+
enqueuedAtUs: string;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
interface PreparedBatchRow extends PendingBatchRow {
|
|
1192
|
+
context: TableContext;
|
|
1193
|
+
entityKey: Record<string, string>;
|
|
1194
|
+
envelopePayload: Record<string, unknown>;
|
|
1195
|
+
sqlTableName: string;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
interface FlushBatchResult {
|
|
1199
|
+
processedCount: number;
|
|
1200
|
+
affectedContexts: TableContext[];
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
interface MutationStatusUpdate {
|
|
1204
|
+
mutationId: string;
|
|
1205
|
+
status: MutationStatus;
|
|
1206
|
+
attemptCount: number;
|
|
1207
|
+
updatedAtUs: string;
|
|
1208
|
+
sentAtUs?: string | null;
|
|
1209
|
+
replaceSentAtUs?: boolean;
|
|
1210
|
+
ackedAtUs?: string | null;
|
|
1211
|
+
replaceAckedAtUs?: boolean;
|
|
1212
|
+
serverUpdatedAtUs?: string | null;
|
|
1213
|
+
replaceServerUpdatedAtUs?: boolean;
|
|
1214
|
+
lastError?: string | null;
|
|
1215
|
+
nextRetryAtUs?: string | null;
|
|
1216
|
+
lastHttpStatus?: number | null;
|
|
1217
|
+
conflictReason?: string | null;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
async function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string) {
|
|
1221
|
+
if (contexts.length === 0) {
|
|
1222
|
+
return [] as PendingBatchRow[];
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
const unionSql = contexts
|
|
1226
|
+
.map(
|
|
1227
|
+
(context) => `
|
|
1228
|
+
SELECT
|
|
1229
|
+
'${escapeSqlString(context.key)}' AS "tableKey",
|
|
1230
|
+
mutation_id AS "mutationId",
|
|
1231
|
+
entity_key_json AS "entityKeyJson",
|
|
1232
|
+
mutation_seq AS "mutationSeq",
|
|
1233
|
+
mutation_kind AS "mutationKind",
|
|
1234
|
+
status,
|
|
1235
|
+
payload_json AS "payloadJson",
|
|
1236
|
+
attempt_count AS "attemptCount",
|
|
1237
|
+
last_http_status AS "lastHttpStatus",
|
|
1238
|
+
last_error AS "lastError",
|
|
1239
|
+
conflict_reason AS "conflictReason",
|
|
1240
|
+
next_retry_at_us::text AS "nextRetryAtUs",
|
|
1241
|
+
server_updated_at_us::text AS "serverUpdatedAtUs",
|
|
1242
|
+
enqueued_at_us::text AS "enqueuedAtUs"
|
|
1243
|
+
FROM ${context.journalTable}
|
|
1244
|
+
WHERE status IN ('pending', 'failed')
|
|
1245
|
+
AND COALESCE(next_retry_at_us, 0) <= $1::bigint
|
|
1246
|
+
AND NOT EXISTS (
|
|
1247
|
+
SELECT 1
|
|
1248
|
+
FROM ${context.journalTable} AS earlier
|
|
1249
|
+
WHERE earlier.entity_key_json = ${context.journalTable}.entity_key_json
|
|
1250
|
+
AND earlier.mutation_seq < ${context.journalTable}.mutation_seq
|
|
1251
|
+
AND earlier.status IN ('pending', 'failed', 'sending')
|
|
1252
|
+
)
|
|
1253
|
+
`,
|
|
1254
|
+
)
|
|
1255
|
+
.join("\nUNION ALL\n");
|
|
1256
|
+
|
|
1257
|
+
const result = await db.query<PendingBatchRow>(
|
|
1258
|
+
`
|
|
1259
|
+
SELECT *
|
|
1260
|
+
FROM (
|
|
1261
|
+
${unionSql}
|
|
1262
|
+
) AS pending
|
|
1263
|
+
ORDER BY pending."enqueuedAtUs"::bigint ASC, pending."mutationSeq" ASC
|
|
1264
|
+
LIMIT ${DEFAULT_FLUSH_BATCH_SIZE}
|
|
1265
|
+
`,
|
|
1266
|
+
[nowUs],
|
|
1267
|
+
);
|
|
1268
|
+
|
|
1269
|
+
return result.rows;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
async function flushBatch(
|
|
1273
|
+
db: MutationDb,
|
|
1274
|
+
tableContexts: Record<string, TableContext>,
|
|
1275
|
+
batchWriteUrl: string,
|
|
1276
|
+
tableFilter?: string,
|
|
1277
|
+
getAuthToken?: () => Promise<string | undefined>,
|
|
1278
|
+
): Promise<FlushBatchResult> {
|
|
1279
|
+
const contexts = filterContexts(tableContexts, tableFilter);
|
|
1280
|
+
const nowUs = nowMicroseconds();
|
|
1281
|
+
|
|
1282
|
+
// Collect send-eligible mutations across all target tables.
|
|
1283
|
+
const pendingRows = await readPendingBatchRows(db, contexts, nowUs);
|
|
1284
|
+
const pending: PreparedBatchRow[] = [];
|
|
1285
|
+
const pendingByTable = new Map<string, PreparedBatchRow[]>();
|
|
1286
|
+
|
|
1287
|
+
for (const row of pendingRows) {
|
|
1288
|
+
const context = tableContexts[row.tableKey];
|
|
1289
|
+
|
|
1290
|
+
if (!context) {
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;
|
|
1295
|
+
const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;
|
|
1296
|
+
const preparedRow: PreparedBatchRow = {
|
|
1297
|
+
...row,
|
|
1298
|
+
context,
|
|
1299
|
+
entityKey,
|
|
1300
|
+
envelopePayload:
|
|
1301
|
+
row.mutationKind === "delete"
|
|
1302
|
+
? entityKey
|
|
1303
|
+
: toSqlColumnPayload(
|
|
1304
|
+
context,
|
|
1305
|
+
(rawPayload.value ?? rawPayload.patch ?? rawPayload) as Record<string, unknown>,
|
|
1306
|
+
),
|
|
1307
|
+
sqlTableName: context.entry.shape?.tableName ?? context.key,
|
|
1308
|
+
};
|
|
1309
|
+
|
|
1310
|
+
pending.push(preparedRow);
|
|
1311
|
+
|
|
1312
|
+
const existingTableRows = pendingByTable.get(context.key);
|
|
1313
|
+
|
|
1314
|
+
if (existingTableRows) {
|
|
1315
|
+
existingTableRows.push(preparedRow);
|
|
1316
|
+
} else {
|
|
1317
|
+
pendingByTable.set(context.key, [preparedRow]);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
if (pending.length === 0) {
|
|
1322
|
+
return {
|
|
1323
|
+
processedCount: 0,
|
|
1324
|
+
affectedContexts: [],
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
// Mark all as sending.
|
|
1329
|
+
const sentAtUs = nowMicroseconds();
|
|
1330
|
+
|
|
1331
|
+
for (const rows of pendingByTable.values()) {
|
|
1332
|
+
await applyMutationStatusUpdates(
|
|
1333
|
+
db,
|
|
1334
|
+
rows[0]!.context,
|
|
1335
|
+
rows.map((row) => ({
|
|
1336
|
+
mutationId: row.mutationId,
|
|
1337
|
+
status: "sending",
|
|
1338
|
+
attemptCount: row.attemptCount + 1,
|
|
1339
|
+
updatedAtUs: sentAtUs,
|
|
1340
|
+
sentAtUs,
|
|
1341
|
+
replaceSentAtUs: true,
|
|
1342
|
+
lastError: null,
|
|
1343
|
+
nextRetryAtUs: null,
|
|
1344
|
+
lastHttpStatus: null,
|
|
1345
|
+
conflictReason: null,
|
|
1346
|
+
})),
|
|
1347
|
+
);
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
const mutations = pending.map((row) => {
|
|
1351
|
+
return {
|
|
1352
|
+
tableName: row.sqlTableName,
|
|
1353
|
+
entityKey: row.entityKey,
|
|
1354
|
+
mutationId: row.mutationId,
|
|
1355
|
+
mutationSeq: row.mutationSeq,
|
|
1356
|
+
kind: row.mutationKind as "create" | "update" | "delete",
|
|
1357
|
+
payload: row.envelopePayload,
|
|
1358
|
+
clientTimestampUs: sentAtUs,
|
|
1359
|
+
};
|
|
1360
|
+
});
|
|
1361
|
+
|
|
1362
|
+
let responseOk = false;
|
|
1363
|
+
let acksByMutationId: Map<string, BatchMutationAck["acks"][number]> = new Map();
|
|
1364
|
+
|
|
1365
|
+
try {
|
|
1366
|
+
let response = await fetch(`${batchWriteUrl}/api/mutations`, {
|
|
1367
|
+
method: "POST",
|
|
1368
|
+
headers: buildRequestHeaders(await getAuthToken?.()),
|
|
1369
|
+
body: JSON.stringify({ mutations }),
|
|
1370
|
+
});
|
|
1371
|
+
|
|
1372
|
+
if ([401, 403].includes(response.status) && getAuthToken) {
|
|
1373
|
+
response = await fetch(`${batchWriteUrl}/api/mutations`, {
|
|
1374
|
+
method: "POST",
|
|
1375
|
+
headers: buildRequestHeaders(await getAuthToken()),
|
|
1376
|
+
body: JSON.stringify({ mutations }),
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
if (response.ok) {
|
|
1381
|
+
const responseJson = (await response.json()) as BatchMutationAck;
|
|
1382
|
+
responseOk = true;
|
|
1383
|
+
acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
|
|
1384
|
+
} else {
|
|
1385
|
+
const text = await response.text();
|
|
1386
|
+
throw new MutationRequestError(
|
|
1387
|
+
text.length > 0 ? text : `Bulk write responded with ${response.status}`,
|
|
1388
|
+
response.status,
|
|
1389
|
+
);
|
|
1390
|
+
}
|
|
1391
|
+
} catch (error) {
|
|
1392
|
+
// All mutations in the batch fail together on a transport or server error.
|
|
1393
|
+
const failedAtUs = nowMicroseconds();
|
|
1394
|
+
|
|
1395
|
+
for (const rows of pendingByTable.values()) {
|
|
1396
|
+
await applyMutationStatusUpdates(
|
|
1397
|
+
db,
|
|
1398
|
+
rows[0]!.context,
|
|
1399
|
+
rows.map((row) => {
|
|
1400
|
+
const attemptCount = row.attemptCount + 1;
|
|
1401
|
+
|
|
1402
|
+
return {
|
|
1403
|
+
mutationId: row.mutationId,
|
|
1404
|
+
status: "failed",
|
|
1405
|
+
attemptCount,
|
|
1406
|
+
updatedAtUs: failedAtUs,
|
|
1407
|
+
lastError: error instanceof Error ? error.message : "Unknown batch write failure",
|
|
1408
|
+
nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount),
|
|
1409
|
+
lastHttpStatus: error instanceof MutationRequestError ? error.status : null,
|
|
1410
|
+
conflictReason: null,
|
|
1411
|
+
};
|
|
1412
|
+
}),
|
|
1413
|
+
);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
return {
|
|
1417
|
+
processedCount: pending.length,
|
|
1418
|
+
affectedContexts: [...new Set(pending.map((row) => row.context))],
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
if (!responseOk) {
|
|
1423
|
+
return {
|
|
1424
|
+
processedCount: pending.length,
|
|
1425
|
+
affectedContexts: [...new Set(pending.map((row) => row.context))],
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// Apply per-mutation ack results.
|
|
1430
|
+
const ackedAtUs = nowMicroseconds();
|
|
1431
|
+
const failedAtUs = nowMicroseconds();
|
|
1432
|
+
|
|
1433
|
+
for (const rows of pendingByTable.values()) {
|
|
1434
|
+
await applyMutationStatusUpdates(
|
|
1435
|
+
db,
|
|
1436
|
+
rows[0]!.context,
|
|
1437
|
+
rows.map((row) => {
|
|
1438
|
+
const ack = acksByMutationId.get(row.mutationId);
|
|
1439
|
+
|
|
1440
|
+
if (!ack || ack.status !== "acked") {
|
|
1441
|
+
return {
|
|
1442
|
+
mutationId: row.mutationId,
|
|
1443
|
+
status: "failed",
|
|
1444
|
+
attemptCount: row.attemptCount + 1,
|
|
1445
|
+
updatedAtUs: failedAtUs,
|
|
1446
|
+
lastError: ack?.conflictReason ?? "Batch mutation not acknowledged",
|
|
1447
|
+
nextRetryAtUs: computeNextRetryAtUs(failedAtUs, row.attemptCount + 1),
|
|
1448
|
+
lastHttpStatus: ack?.httpStatus ?? null,
|
|
1449
|
+
conflictReason: ack?.conflictReason ?? null,
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
if (row.mutationKind === "delete") {
|
|
1454
|
+
return {
|
|
1455
|
+
mutationId: row.mutationId,
|
|
1456
|
+
status: "acked",
|
|
1457
|
+
attemptCount: row.attemptCount + 1,
|
|
1458
|
+
updatedAtUs: ackedAtUs,
|
|
1459
|
+
ackedAtUs,
|
|
1460
|
+
replaceAckedAtUs: true,
|
|
1461
|
+
lastError: null,
|
|
1462
|
+
nextRetryAtUs: null,
|
|
1463
|
+
lastHttpStatus: 204,
|
|
1464
|
+
conflictReason: null,
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
return {
|
|
1469
|
+
mutationId: row.mutationId,
|
|
1470
|
+
status: "acked",
|
|
1471
|
+
attemptCount: row.attemptCount + 1,
|
|
1472
|
+
updatedAtUs: ackedAtUs,
|
|
1473
|
+
ackedAtUs,
|
|
1474
|
+
replaceAckedAtUs: true,
|
|
1475
|
+
serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
|
|
1476
|
+
replaceServerUpdatedAtUs: true,
|
|
1477
|
+
lastError: null,
|
|
1478
|
+
nextRetryAtUs: null,
|
|
1479
|
+
lastHttpStatus: 200,
|
|
1480
|
+
conflictReason: null,
|
|
1481
|
+
};
|
|
1482
|
+
}),
|
|
1483
|
+
);
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
return {
|
|
1487
|
+
processedCount: pending.length,
|
|
1488
|
+
affectedContexts: [...new Set(pending.map((row) => row.context))],
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
function toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {
|
|
1493
|
+
const normalized: Record<string, unknown> = {};
|
|
1494
|
+
|
|
1495
|
+
for (const { propertyKey, column } of context.columns) {
|
|
1496
|
+
const columnName = column.name;
|
|
1497
|
+
|
|
1498
|
+
if (Object.prototype.hasOwnProperty.call(payload, columnName)) {
|
|
1499
|
+
normalized[columnName] = payload[columnName];
|
|
1500
|
+
continue;
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
|
|
1504
|
+
normalized[columnName] = payload[propertyKey];
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
return normalized;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
function filterProjectedPayload(context: TableContext, payload: Record<string, unknown>) {
|
|
1512
|
+
const normalized: Record<string, unknown> = {};
|
|
1513
|
+
|
|
1514
|
+
for (const { propertyKey, column } of context.columns) {
|
|
1515
|
+
if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
|
|
1516
|
+
normalized[propertyKey] = payload[propertyKey];
|
|
1517
|
+
continue;
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
if (Object.prototype.hasOwnProperty.call(payload, column.name)) {
|
|
1521
|
+
normalized[column.name] = payload[column.name];
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
return normalized;
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
async function flushTable(
|
|
1529
|
+
db: MutationDb,
|
|
1530
|
+
context: TableContext,
|
|
1531
|
+
writeUrl: string,
|
|
1532
|
+
getAuthToken?: () => Promise<string | undefined>,
|
|
1533
|
+
) {
|
|
1534
|
+
const result = await db.query<MutationRow>(
|
|
1535
|
+
`
|
|
1536
|
+
SELECT
|
|
1537
|
+
mutation_id AS "mutationId",
|
|
1538
|
+
entity_key_json AS "entityKeyJson",
|
|
1539
|
+
mutation_seq AS "mutationSeq",
|
|
1540
|
+
mutation_kind AS "mutationKind",
|
|
1541
|
+
status,
|
|
1542
|
+
payload_json AS "payloadJson",
|
|
1543
|
+
attempt_count AS "attemptCount",
|
|
1544
|
+
last_http_status AS "lastHttpStatus",
|
|
1545
|
+
last_error AS "lastError",
|
|
1546
|
+
conflict_reason AS "conflictReason",
|
|
1547
|
+
next_retry_at_us::text AS "nextRetryAtUs",
|
|
1548
|
+
server_updated_at_us::text AS "serverUpdatedAtUs"
|
|
1549
|
+
FROM ${context.journalTable}
|
|
1550
|
+
WHERE status IN ('pending', 'failed')
|
|
1551
|
+
AND COALESCE(next_retry_at_us, 0) <= $1::bigint
|
|
1552
|
+
AND NOT EXISTS (
|
|
1553
|
+
SELECT 1
|
|
1554
|
+
FROM ${context.journalTable} AS earlier
|
|
1555
|
+
WHERE earlier.entity_key_json = ${context.journalTable}.entity_key_json
|
|
1556
|
+
AND earlier.mutation_seq < ${context.journalTable}.mutation_seq
|
|
1557
|
+
AND earlier.status IN ('pending', 'failed', 'sending')
|
|
1558
|
+
)
|
|
1559
|
+
ORDER BY enqueued_at_us ASC, mutation_seq ASC
|
|
1560
|
+
LIMIT ${DEFAULT_FLUSH_BATCH_SIZE}
|
|
1561
|
+
`,
|
|
1562
|
+
[nowMicroseconds()],
|
|
1563
|
+
);
|
|
1564
|
+
|
|
1565
|
+
if (result.rows.length === 0) {
|
|
1566
|
+
return 0;
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
for (const mutation of result.rows) {
|
|
1570
|
+
const sentAtUs = nowMicroseconds();
|
|
1571
|
+
await setMutationStatus(db, context, mutation.mutationId, "sending", {
|
|
1572
|
+
attemptCount: mutation.attemptCount + 1,
|
|
1573
|
+
sentAtUs,
|
|
1574
|
+
updatedAtUs: sentAtUs,
|
|
1575
|
+
lastError: null,
|
|
1576
|
+
nextRetryAtUs: null,
|
|
1577
|
+
lastHttpStatus: null,
|
|
1578
|
+
conflictReason: null,
|
|
1579
|
+
});
|
|
1580
|
+
|
|
1581
|
+
try {
|
|
1582
|
+
const entityKey = JSON.parse(mutation.entityKeyJson) as Record<string, string>;
|
|
1583
|
+
const payload = JSON.parse(mutation.payloadJson) as Record<string, unknown>;
|
|
1584
|
+
let response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken?.());
|
|
1585
|
+
|
|
1586
|
+
if ([401, 403].includes(response.status) && getAuthToken) {
|
|
1587
|
+
response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken());
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
const responseText = await response.text();
|
|
1591
|
+
const responseJson = responseText.length > 0 ? JSON.parse(responseText) : null;
|
|
1592
|
+
|
|
1593
|
+
if (!response.ok) {
|
|
1594
|
+
const errorMessage =
|
|
1595
|
+
responseJson && typeof responseJson.message === "string"
|
|
1596
|
+
? responseJson.message
|
|
1597
|
+
: `Write API responded with ${response.status}`;
|
|
1598
|
+
|
|
1599
|
+
if (mutation.mutationKind === "delete" && response.status === 404) {
|
|
1600
|
+
await markDeleteAcknowledged(db, context, mutation.mutationId);
|
|
1601
|
+
continue;
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
throw new MutationRequestError(errorMessage, response.status);
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
const ackedAtUs = nowMicroseconds();
|
|
1608
|
+
|
|
1609
|
+
if (mutation.mutationKind === "delete") {
|
|
1610
|
+
await markDeleteAcknowledged(db, context, mutation.mutationId);
|
|
1611
|
+
} else {
|
|
1612
|
+
const created = parseRecord(context, responseJson);
|
|
1613
|
+
const createdRecord = ensureRecord(created);
|
|
1614
|
+
const serverUpdatedAtUs = toOptionalString(createdRecord.updatedAtUs);
|
|
1615
|
+
|
|
1616
|
+
await db.query(
|
|
1617
|
+
`
|
|
1618
|
+
UPDATE ${context.journalTable}
|
|
1619
|
+
SET
|
|
1620
|
+
status = 'acked',
|
|
1621
|
+
acked_at_us = $2::bigint,
|
|
1622
|
+
updated_at_us = $2::bigint,
|
|
1623
|
+
server_updated_at_us = $3::bigint,
|
|
1624
|
+
last_error = NULL,
|
|
1625
|
+
last_http_status = 200,
|
|
1626
|
+
conflict_reason = NULL,
|
|
1627
|
+
next_retry_at_us = NULL
|
|
1628
|
+
WHERE mutation_id = $1
|
|
1629
|
+
`,
|
|
1630
|
+
[mutation.mutationId, ackedAtUs, serverUpdatedAtUs],
|
|
1631
|
+
);
|
|
1632
|
+
|
|
1633
|
+
if (!(await hasLaterMutations(db, context, mutation.entityKeyJson, mutation.mutationSeq))) {
|
|
1634
|
+
await updateOverlayTimestamps(db, context, entityKey, createdRecord, ackedAtUs);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
} catch (error) {
|
|
1638
|
+
const failedAtUs = nowMicroseconds();
|
|
1639
|
+
const attemptCount = mutation.attemptCount + 1;
|
|
1640
|
+
const nextRetryAtUs = computeNextRetryAtUs(failedAtUs, attemptCount);
|
|
1641
|
+
const lastHttpStatus = error instanceof MutationRequestError ? error.status : null;
|
|
1642
|
+
const conflictReason =
|
|
1643
|
+
lastHttpStatus === 404 || lastHttpStatus === 409
|
|
1644
|
+
? error instanceof Error
|
|
1645
|
+
? error.message
|
|
1646
|
+
: "Server conflict"
|
|
1647
|
+
: null;
|
|
1648
|
+
|
|
1649
|
+
await setMutationStatus(db, context, mutation.mutationId, "failed", {
|
|
1650
|
+
attemptCount,
|
|
1651
|
+
updatedAtUs: failedAtUs,
|
|
1652
|
+
lastError: error instanceof Error ? error.message : "Unknown write failure",
|
|
1653
|
+
nextRetryAtUs,
|
|
1654
|
+
lastHttpStatus,
|
|
1655
|
+
conflictReason,
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
await reconcileTable(db, context);
|
|
1661
|
+
return result.rows.length;
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
async function reconcileTable(db: MutationDb, context: TableContext) {
|
|
1665
|
+
await clearAcknowledgedDeletes(db, context);
|
|
1666
|
+
|
|
1667
|
+
if (!context.columns.some(({ column }) => column.name === "updated_at_us")) {
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
await db.exec("BEGIN");
|
|
1672
|
+
|
|
1673
|
+
try {
|
|
1674
|
+
await db.query(`
|
|
1675
|
+
WITH deleted AS (
|
|
1676
|
+
DELETE FROM ${context.journalTable} AS journal
|
|
1677
|
+
USING ${context.syncedTable} AS synced
|
|
1678
|
+
WHERE journal.status = 'acked'
|
|
1679
|
+
AND journal.mutation_kind <> 'delete'
|
|
1680
|
+
AND journal.server_updated_at_us IS NOT NULL
|
|
1681
|
+
AND ${buildColumnEquality(context.pkColumnNames, "journal", "synced")}
|
|
1682
|
+
AND synced.updated_at_us >= journal.server_updated_at_us
|
|
1683
|
+
RETURNING journal.mutation_id, journal.entity_key_json, ${context.pkColumnNames.map((columnName) => `journal.${columnName}`).join(", ")}
|
|
1684
|
+
),
|
|
1685
|
+
clearable_entities AS (
|
|
1686
|
+
SELECT DISTINCT deleted.entity_key_json, ${context.pkColumnNames.map((columnName) => `deleted.${columnName}`).join(", ")}
|
|
1687
|
+
FROM deleted
|
|
1688
|
+
WHERE NOT EXISTS (
|
|
1689
|
+
SELECT 1
|
|
1690
|
+
FROM ${context.journalTable} AS remaining
|
|
1691
|
+
WHERE remaining.entity_key_json = deleted.entity_key_json
|
|
1692
|
+
AND remaining.mutation_id NOT IN (
|
|
1693
|
+
SELECT deleted_for_entity.mutation_id
|
|
1694
|
+
FROM deleted AS deleted_for_entity
|
|
1695
|
+
WHERE deleted_for_entity.entity_key_json = deleted.entity_key_json
|
|
1696
|
+
)
|
|
1697
|
+
)
|
|
1698
|
+
)
|
|
1699
|
+
DELETE FROM ${context.overlayTable} AS overlay
|
|
1700
|
+
USING clearable_entities
|
|
1701
|
+
WHERE ${buildColumnEquality(context.pkColumnNames, "overlay", "clearable_entities")}
|
|
1702
|
+
`);
|
|
1703
|
+
await db.exec("COMMIT");
|
|
1704
|
+
} catch (error) {
|
|
1705
|
+
await db.exec("ROLLBACK");
|
|
1706
|
+
throw error;
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
async function clearAcknowledgedDeletes(db: MutationDb, context: TableContext) {
|
|
1711
|
+
await db.exec("BEGIN");
|
|
1712
|
+
|
|
1713
|
+
try {
|
|
1714
|
+
await db.query(`
|
|
1715
|
+
WITH clearable_entities AS (
|
|
1716
|
+
SELECT DISTINCT journal.entity_key_json, ${context.pkColumnNames.map((columnName) => `journal.${columnName}`).join(", ")}
|
|
1717
|
+
FROM ${context.journalTable} AS journal
|
|
1718
|
+
LEFT JOIN ${context.syncedTable} AS synced
|
|
1719
|
+
ON ${buildColumnEquality(context.pkColumnNames, "journal", "synced")}
|
|
1720
|
+
WHERE journal.status = 'acked'
|
|
1721
|
+
AND journal.mutation_kind = 'delete'
|
|
1722
|
+
AND synced.${context.pkColumnNames[0]!} IS NULL
|
|
1723
|
+
),
|
|
1724
|
+
deleted_overlay AS (
|
|
1725
|
+
DELETE FROM ${context.overlayTable} AS overlay
|
|
1726
|
+
USING clearable_entities
|
|
1727
|
+
WHERE ${buildColumnEquality(context.pkColumnNames, "overlay", "clearable_entities")}
|
|
1728
|
+
)
|
|
1729
|
+
DELETE FROM ${context.journalTable} AS journal
|
|
1730
|
+
USING clearable_entities
|
|
1731
|
+
WHERE journal.entity_key_json = clearable_entities.entity_key_json
|
|
1732
|
+
`);
|
|
1733
|
+
await db.exec("COMMIT");
|
|
1734
|
+
} catch (error) {
|
|
1735
|
+
await db.exec("ROLLBACK");
|
|
1736
|
+
throw error;
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
async function sendMutationRequest(
|
|
1741
|
+
writeUrl: string,
|
|
1742
|
+
context: TableContext,
|
|
1743
|
+
entityKey: Record<string, string>,
|
|
1744
|
+
payload: Record<string, unknown>,
|
|
1745
|
+
authToken?: string,
|
|
1746
|
+
) {
|
|
1747
|
+
if (!context.routeBasePath) {
|
|
1748
|
+
throw new Error(`routes.basePath is required for direct mutation requests on table ${context.key}`);
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
switch (payload.kind) {
|
|
1752
|
+
case "create":
|
|
1753
|
+
return fetch(`${writeUrl}${context.routeBasePath}`, {
|
|
1754
|
+
method: "POST",
|
|
1755
|
+
headers: buildRequestHeaders(authToken),
|
|
1756
|
+
body: JSON.stringify(filterProjectedPayload(context, ensureRecord(payload.value))),
|
|
1757
|
+
});
|
|
1758
|
+
case "update":
|
|
1759
|
+
return fetch(
|
|
1760
|
+
`${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`,
|
|
1761
|
+
{
|
|
1762
|
+
method: "PATCH",
|
|
1763
|
+
headers: buildRequestHeaders(authToken),
|
|
1764
|
+
body: JSON.stringify(filterProjectedPayload(context, ensureRecord(payload.patch))),
|
|
1765
|
+
},
|
|
1766
|
+
);
|
|
1767
|
+
case "delete":
|
|
1768
|
+
return fetch(
|
|
1769
|
+
`${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`,
|
|
1770
|
+
{
|
|
1771
|
+
method: "DELETE",
|
|
1772
|
+
headers: buildRequestHeaders(authToken),
|
|
1773
|
+
},
|
|
1774
|
+
);
|
|
1775
|
+
default:
|
|
1776
|
+
throw new Error(`Unknown mutation kind for table ${context.key}`);
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
function buildRequestHeaders(authToken?: string): Record<string, string> {
|
|
1781
|
+
if (!authToken) {
|
|
1782
|
+
return {
|
|
1783
|
+
"Content-Type": "application/json",
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
return {
|
|
1788
|
+
"Content-Type": "application/json",
|
|
1789
|
+
Authorization: `Bearer ${authToken}`,
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
function getSingleEntityKeyValue(context: TableContext, entityKey: Record<string, string>) {
|
|
1794
|
+
if (context.pkPropertyKeys.length !== 1) {
|
|
1795
|
+
throw new Error(`Only single-column primary keys are supported for routes on table ${context.key}`);
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
return entityKey[context.pkPropertyKeys[0]!]!;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
async function setMutationStatus(
|
|
1802
|
+
db: MutationDb,
|
|
1803
|
+
context: TableContext,
|
|
1804
|
+
mutationId: string,
|
|
1805
|
+
status: MutationStatus,
|
|
1806
|
+
options: {
|
|
1807
|
+
attemptCount: number;
|
|
1808
|
+
updatedAtUs: string;
|
|
1809
|
+
sentAtUs?: string | null;
|
|
1810
|
+
nextRetryAtUs?: string | null;
|
|
1811
|
+
lastError?: string | null;
|
|
1812
|
+
lastHttpStatus?: number | null;
|
|
1813
|
+
conflictReason?: string | null;
|
|
1814
|
+
},
|
|
1815
|
+
) {
|
|
1816
|
+
await db.query(
|
|
1817
|
+
`
|
|
1818
|
+
UPDATE ${context.journalTable}
|
|
1819
|
+
SET
|
|
1820
|
+
status = $2,
|
|
1821
|
+
attempt_count = $3,
|
|
1822
|
+
sent_at_us = COALESCE($4::bigint, sent_at_us),
|
|
1823
|
+
updated_at_us = $5::bigint,
|
|
1824
|
+
last_error = $6,
|
|
1825
|
+
next_retry_at_us = $7::bigint,
|
|
1826
|
+
last_http_status = $8,
|
|
1827
|
+
conflict_reason = $9
|
|
1828
|
+
WHERE mutation_id = $1
|
|
1829
|
+
`,
|
|
1830
|
+
[
|
|
1831
|
+
mutationId,
|
|
1832
|
+
status,
|
|
1833
|
+
options.attemptCount,
|
|
1834
|
+
options.sentAtUs ?? null,
|
|
1835
|
+
options.updatedAtUs,
|
|
1836
|
+
options.lastError ?? null,
|
|
1837
|
+
options.nextRetryAtUs ?? null,
|
|
1838
|
+
options.lastHttpStatus ?? null,
|
|
1839
|
+
options.conflictReason ?? null,
|
|
1840
|
+
],
|
|
1841
|
+
);
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
async function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {
|
|
1845
|
+
if (updates.length === 0) {
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
const columns = [
|
|
1850
|
+
"mutation_id",
|
|
1851
|
+
"status",
|
|
1852
|
+
"attempt_count",
|
|
1853
|
+
"updated_at_us",
|
|
1854
|
+
"sent_at_us",
|
|
1855
|
+
"replace_sent_at_us",
|
|
1856
|
+
"acked_at_us",
|
|
1857
|
+
"replace_acked_at_us",
|
|
1858
|
+
"server_updated_at_us",
|
|
1859
|
+
"replace_server_updated_at_us",
|
|
1860
|
+
"last_error",
|
|
1861
|
+
"next_retry_at_us",
|
|
1862
|
+
"last_http_status",
|
|
1863
|
+
"conflict_reason",
|
|
1864
|
+
] as const;
|
|
1865
|
+
const params: unknown[] = [];
|
|
1866
|
+
const tuples = updates.map((update) => {
|
|
1867
|
+
const start = params.length;
|
|
1868
|
+
|
|
1869
|
+
params.push(
|
|
1870
|
+
update.mutationId,
|
|
1871
|
+
update.status,
|
|
1872
|
+
update.attemptCount,
|
|
1873
|
+
update.updatedAtUs,
|
|
1874
|
+
update.sentAtUs ?? null,
|
|
1875
|
+
update.replaceSentAtUs ?? false,
|
|
1876
|
+
update.ackedAtUs ?? null,
|
|
1877
|
+
update.replaceAckedAtUs ?? false,
|
|
1878
|
+
update.serverUpdatedAtUs ?? null,
|
|
1879
|
+
update.replaceServerUpdatedAtUs ?? false,
|
|
1880
|
+
update.lastError ?? null,
|
|
1881
|
+
update.nextRetryAtUs ?? null,
|
|
1882
|
+
update.lastHttpStatus ?? null,
|
|
1883
|
+
update.conflictReason ?? null,
|
|
1884
|
+
);
|
|
1885
|
+
|
|
1886
|
+
return `(${columns
|
|
1887
|
+
.map((columnName, index) => {
|
|
1888
|
+
const position = start + index + 1;
|
|
1889
|
+
|
|
1890
|
+
if (
|
|
1891
|
+
columnName === "updated_at_us" ||
|
|
1892
|
+
columnName === "sent_at_us" ||
|
|
1893
|
+
columnName === "acked_at_us" ||
|
|
1894
|
+
columnName === "server_updated_at_us" ||
|
|
1895
|
+
columnName === "next_retry_at_us"
|
|
1896
|
+
) {
|
|
1897
|
+
return `$${position}::bigint`;
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
if (columnName === "attempt_count" || columnName === "last_http_status") {
|
|
1901
|
+
return `$${position}::int`;
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
if (
|
|
1905
|
+
columnName === "replace_sent_at_us" ||
|
|
1906
|
+
columnName === "replace_acked_at_us" ||
|
|
1907
|
+
columnName === "replace_server_updated_at_us"
|
|
1908
|
+
) {
|
|
1909
|
+
return `$${position}::boolean`;
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
return `$${position}`;
|
|
1913
|
+
})
|
|
1914
|
+
.join(", ")})`;
|
|
1915
|
+
});
|
|
1916
|
+
|
|
1917
|
+
await db.query(
|
|
1918
|
+
`
|
|
1919
|
+
UPDATE ${context.journalTable} AS journal
|
|
1920
|
+
SET
|
|
1921
|
+
status = updates.status,
|
|
1922
|
+
attempt_count = updates.attempt_count,
|
|
1923
|
+
updated_at_us = updates.updated_at_us::bigint,
|
|
1924
|
+
sent_at_us = CASE
|
|
1925
|
+
WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint
|
|
1926
|
+
ELSE journal.sent_at_us
|
|
1927
|
+
END,
|
|
1928
|
+
acked_at_us = CASE
|
|
1929
|
+
WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint
|
|
1930
|
+
ELSE journal.acked_at_us
|
|
1931
|
+
END,
|
|
1932
|
+
server_updated_at_us = CASE
|
|
1933
|
+
WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint
|
|
1934
|
+
ELSE journal.server_updated_at_us
|
|
1935
|
+
END,
|
|
1936
|
+
last_error = updates.last_error,
|
|
1937
|
+
next_retry_at_us = updates.next_retry_at_us::bigint,
|
|
1938
|
+
last_http_status = updates.last_http_status,
|
|
1939
|
+
conflict_reason = updates.conflict_reason
|
|
1940
|
+
FROM (
|
|
1941
|
+
VALUES ${tuples.join(",\n ")}
|
|
1942
|
+
) AS updates (
|
|
1943
|
+
mutation_id,
|
|
1944
|
+
status,
|
|
1945
|
+
attempt_count,
|
|
1946
|
+
updated_at_us,
|
|
1947
|
+
sent_at_us,
|
|
1948
|
+
replace_sent_at_us,
|
|
1949
|
+
acked_at_us,
|
|
1950
|
+
replace_acked_at_us,
|
|
1951
|
+
server_updated_at_us,
|
|
1952
|
+
replace_server_updated_at_us,
|
|
1953
|
+
last_error,
|
|
1954
|
+
next_retry_at_us,
|
|
1955
|
+
last_http_status,
|
|
1956
|
+
conflict_reason
|
|
1957
|
+
)
|
|
1958
|
+
WHERE journal.mutation_id = updates.mutation_id::uuid
|
|
1959
|
+
`,
|
|
1960
|
+
params,
|
|
1961
|
+
);
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
async function markDeleteAcknowledged(db: MutationDb, context: TableContext, mutationId: string) {
|
|
1965
|
+
const ackedAtUs = nowMicroseconds();
|
|
1966
|
+
|
|
1967
|
+
await db.query(
|
|
1968
|
+
`
|
|
1969
|
+
UPDATE ${context.journalTable}
|
|
1970
|
+
SET
|
|
1971
|
+
status = 'acked',
|
|
1972
|
+
acked_at_us = $2::bigint,
|
|
1973
|
+
updated_at_us = $2::bigint,
|
|
1974
|
+
last_error = NULL,
|
|
1975
|
+
last_http_status = 204,
|
|
1976
|
+
conflict_reason = NULL,
|
|
1977
|
+
next_retry_at_us = NULL
|
|
1978
|
+
WHERE mutation_id = $1
|
|
1979
|
+
`,
|
|
1980
|
+
[mutationId, ackedAtUs],
|
|
1981
|
+
);
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
async function hasLaterMutations(db: MutationDb, context: TableContext, entityKeyJson: string, mutationSeq: number) {
|
|
1985
|
+
const result = await db.query<{ count: number }>(
|
|
1986
|
+
`
|
|
1987
|
+
SELECT COUNT(*)::int AS count
|
|
1988
|
+
FROM ${context.journalTable}
|
|
1989
|
+
WHERE entity_key_json = $1
|
|
1990
|
+
AND mutation_seq > $2
|
|
1991
|
+
`,
|
|
1992
|
+
[entityKeyJson, mutationSeq],
|
|
1993
|
+
);
|
|
1994
|
+
|
|
1995
|
+
return (result.rows[0]?.count ?? 0) > 0;
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
async function updateOverlayTimestamps(
|
|
1999
|
+
db: MutationDb,
|
|
2000
|
+
context: TableContext,
|
|
2001
|
+
entityKey: Record<string, string>,
|
|
2002
|
+
record: Record<string, unknown>,
|
|
2003
|
+
localUpdatedAtUs: string,
|
|
2004
|
+
) {
|
|
2005
|
+
if (!hasProperty(context, "createdAtUs") || !hasProperty(context, "updatedAtUs")) {
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
await db.query(
|
|
2010
|
+
`
|
|
2011
|
+
UPDATE ${context.overlayTable}
|
|
2012
|
+
SET
|
|
2013
|
+
created_at_us = $${context.pkPropertyKeys.length + 1}::bigint,
|
|
2014
|
+
updated_at_us = $${context.pkPropertyKeys.length + 2}::bigint,
|
|
2015
|
+
local_updated_at_us = $${context.pkPropertyKeys.length + 3}::bigint
|
|
2016
|
+
WHERE ${buildWhereClause(context)}
|
|
2017
|
+
`,
|
|
2018
|
+
[...buildWhereParams(context, entityKey), String(record.createdAtUs), String(record.updatedAtUs), localUpdatedAtUs],
|
|
2019
|
+
);
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
function buildWhereClause(context: TableContext) {
|
|
2023
|
+
return context.pkColumnNames.map((columnName, index) => `${columnName} = $${index + 1}`).join(" AND ");
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
function buildColumnEquality(columnNames: string[], leftAlias: string, rightAlias: string) {
|
|
2027
|
+
return columnNames.map((columnName) => `${leftAlias}.${columnName} = ${rightAlias}.${columnName}`).join(" AND ");
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
function qualifyLocalIdentifier(schemaName: string, tableName: string) {
|
|
2031
|
+
if (schemaName === "public") {
|
|
2032
|
+
return tableName;
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
function quoteIdentifier(value: string) {
|
|
2039
|
+
return `"${value.replace(/"/g, '""')}"`;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
function buildJournalSequenceName(journalTable: string) {
|
|
2043
|
+
return `${journalTable}_mutation_seq`;
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
function escapeSqlString(value: string) {
|
|
2047
|
+
return value.replace(/'/g, "''");
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
function buildWhereParams(context: TableContext, entityKey: Record<string, string>) {
|
|
2051
|
+
return context.pkPropertyKeys.map((propertyKey) => entityKey[propertyKey]);
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
function formatSqlValuePlaceholder(position: number, columnName: string) {
|
|
2055
|
+
return /_at_us$/.test(columnName) ? `$${position}::bigint` : `$${position}`;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
function hasProperty(context: TableContext, propertyKey: string) {
|
|
2059
|
+
return context.columns.some((column) => column.propertyKey === propertyKey);
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
function ensureRecord(value: unknown) {
|
|
2063
|
+
if (!isRecord(value)) {
|
|
2064
|
+
throw new Error("Mutation runtime expected a record payload");
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
return value;
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
function extractRecordFromState(context: TableContext, state: CurrentRecordStateRow | BatchCurrentRecordStateRow) {
|
|
2071
|
+
return Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, state[propertyKey] ?? null]));
|
|
2072
|
+
}
|
|
2073
|
+
|
|
2074
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2075
|
+
return typeof value === "object" && value !== null;
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
function toOptionalString(value: unknown) {
|
|
2079
|
+
if (value === undefined || value === null) {
|
|
2080
|
+
return null;
|
|
2081
|
+
}
|
|
2082
|
+
|
|
2083
|
+
switch (typeof value) {
|
|
2084
|
+
case "string":
|
|
2085
|
+
return value;
|
|
2086
|
+
case "number":
|
|
2087
|
+
case "boolean":
|
|
2088
|
+
case "bigint":
|
|
2089
|
+
return String(value);
|
|
2090
|
+
default:
|
|
2091
|
+
return JSON.stringify(value);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
class MutationRequestError extends Error {
|
|
2096
|
+
constructor(
|
|
2097
|
+
message: string,
|
|
2098
|
+
readonly status: number,
|
|
2099
|
+
) {
|
|
2100
|
+
super(message);
|
|
2101
|
+
this.name = "MutationRequestError";
|
|
2102
|
+
}
|
|
2103
|
+
}
|