@pgxsinkit/client 0.1.2 → 0.1.4

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