@pgxsinkit/client 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mutation.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AnyPgTable } from "drizzle-orm/pg-core";
1
+ import { getViewConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
2
  import { ZodObject } from "zod";
3
3
 
4
4
  import type {
@@ -66,7 +66,6 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
66
66
  db: MutationDb;
67
67
  registry: TRegistry;
68
68
  writeUrl: string;
69
- batchWriteUrl?: string;
70
69
  getAuthToken?: () => Promise<string | undefined>;
71
70
  }
72
71
 
@@ -78,7 +77,6 @@ interface TableContext {
78
77
  overlayTable: string;
79
78
  journalTable: string;
80
79
  journalSequence: string;
81
- routeBasePath?: string;
82
80
  pkColumnNames: string[];
83
81
  pkPropertyKeys: string[];
84
82
  recordIncludesOverlayState: boolean;
@@ -86,11 +84,6 @@ interface TableContext {
86
84
  propertyKey: string;
87
85
  column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number]["column"];
88
86
  }>;
89
- /** Column name for the "last updated" timestamp on the synced table,
90
- * used by reconcileTable to verify the sync echo has arrived.
91
- * Derived from governance.managedFields with strategy "nowMicroseconds"
92
- * on "update", or defaulting to "updated_at_us". */
93
- updatedAtColumn: string;
94
87
  }
95
88
 
96
89
  export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
@@ -130,15 +123,6 @@ export function computeNextRetryAtUs(nowUs: string, attemptCount: number) {
130
123
  return (BigInt(nowUs) + BigInt(computeBackoffDelayMs(attemptCount)) * 1000n).toString();
131
124
  }
132
125
 
133
- export function shouldClearOverlayRow(syncedUpdatedAtUs: string, serverUpdatedAtUs: string | null) {
134
- console.log("Comparing timestamps for overlay clearing:", { syncedUpdatedAtUs, serverUpdatedAtUs });
135
- if (serverUpdatedAtUs === null) {
136
- return false;
137
- }
138
-
139
- return BigInt(syncedUpdatedAtUs) >= BigInt(serverUpdatedAtUs);
140
- }
141
-
142
126
  export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
143
127
  options: CreateMutationRuntimeOptions<TRegistry>,
144
128
  ): MutationRuntime<TRegistry> {
@@ -150,7 +134,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
150
134
  return undefined;
151
135
  };
152
136
 
153
- const tableContexts = buildTableContexts(options.registry, options.batchWriteUrl === undefined);
137
+ const tableContexts = buildTableContexts(options.registry);
154
138
  let flushQueue = Promise.resolve();
155
139
 
156
140
  const getTableContext = (table: SyncTableName<TRegistry>) => {
@@ -408,42 +392,27 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
408
392
  };
409
393
 
410
394
  const runFlush = async (table?: SyncTableName<TRegistry>) => {
411
- console.log(`Running runFlush for table: ${table ?? "all tables"}`);
412
- if (options.batchWriteUrl) {
413
- const affectedContexts = new Map<string, TableContext>();
414
- let processedCount = 0;
415
-
416
- do {
417
- const batchResult = await flushBatch(
418
- options.db,
419
- tableContexts as Record<string, TableContext>,
420
- options.batchWriteUrl,
421
- table,
422
- resolveAuthToken,
423
- );
424
-
425
- processedCount = batchResult.processedCount;
395
+ const affectedContexts = new Map<string, TableContext>();
396
+ let processedCount = 0;
397
+
398
+ do {
399
+ const batchResult = await flushBatch(
400
+ options.db,
401
+ tableContexts as Record<string, TableContext>,
402
+ options.writeUrl,
403
+ table,
404
+ resolveAuthToken,
405
+ );
426
406
 
427
- for (const context of batchResult.affectedContexts) {
428
- affectedContexts.set(context.key, context);
429
- }
430
- } while (processedCount > 0);
407
+ processedCount = batchResult.processedCount;
431
408
 
432
- for (const context of affectedContexts.values()) {
433
- await reconcileTable(options.db, context);
409
+ for (const context of batchResult.affectedContexts) {
410
+ affectedContexts.set(context.key, context);
434
411
  }
435
- } else {
436
- let processedCount = 0;
412
+ } while (processedCount > 0);
437
413
 
438
- do {
439
- processedCount = 0;
440
-
441
- const contexts = filterContexts(tableContexts, table);
442
-
443
- for (const context of contexts) {
444
- processedCount += await flushTable(options.db, context, options.writeUrl, resolveAuthToken);
445
- }
446
- } while (processedCount > 0);
414
+ for (const context of affectedContexts.values()) {
415
+ await reconcileTable(options.db, context);
447
416
  }
448
417
  };
449
418
 
@@ -488,7 +457,6 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
488
457
  });
489
458
  },
490
459
  flush: async (table) => {
491
- console.log(`Initiating flush for table: ${table ?? "all tables"}`);
492
460
  const nextFlush = flushQueue.then(() => runFlush(table));
493
461
  flushQueue = nextFlush.catch(() => undefined);
494
462
  await nextFlush;
@@ -739,65 +707,21 @@ type NormalizedBatchItem =
739
707
  order: number;
740
708
  };
741
709
 
742
- function resolveUpdatedAtColumn(
743
- key: string,
744
- entry: SyncTableEntry<AnyPgTable>,
745
- columns: TableContext["columns"],
746
- ): string {
747
- // Derive from governance.managedFields: the "nowMicroseconds" field
748
- // that applies to "update" operations is the authoritative timestamp.
749
- const managedTimestamp = (entry.governance?.managedFields ?? []).find(
750
- (f) => f.strategy === "nowMicroseconds" && f.applyOn.includes("update"),
751
- );
752
-
753
- // The managed field spec uses Drizzle property keys (camelCase).
754
- // Resolve to the SQL column name used on the synced table.
755
- const candidatePropertyKey = managedTimestamp?.column;
756
- const candidate = candidatePropertyKey
757
- ? columns.find((c) => c.propertyKey === candidatePropertyKey)?.column.name
758
- : "updated_at_us";
759
-
760
- if (!candidate) {
761
- throw new Error(
762
- `Table "${key}" has managed field "${candidatePropertyKey}" with strategy "nowMicroseconds" ` +
763
- `on "update", but no matching column exists in the synced projection.`,
764
- );
765
- }
766
-
767
- if (!columns.some((c) => c.column.name === candidate)) {
768
- throw new Error(
769
- `Table "${key}" has updatedAtColumn "${candidate}" but no matching column exists ` +
770
- `in the synced projection (via managed field "${candidatePropertyKey}").`,
771
- );
772
- }
773
-
774
- return candidate;
775
- }
776
-
777
- function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry, requireRouteBasePath: boolean) {
710
+ function buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
778
711
  const localSchema = getSyncRegistrySchema(registry);
779
712
 
780
713
  return Object.fromEntries(
781
714
  Object.entries(registry)
782
715
  .filter(([, entry]) => entry.mode !== "readonly")
783
- .map(([key, entry]) => [key, buildTableContext(key, entry, localSchema, requireRouteBasePath)]),
716
+ .map(([key, entry]) => [key, buildTableContext(key, entry, localSchema)]),
784
717
  ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;
785
718
  }
786
719
 
787
- function buildTableContext(
788
- key: string,
789
- entry: SyncTableEntry<AnyPgTable>,
790
- localSchema: string,
791
- requireRouteBasePath: boolean,
792
- ): TableContext {
720
+ function buildTableContext(key: string, entry: SyncTableEntry<AnyPgTable>, localSchema: string): TableContext {
793
721
  if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
794
722
  throw new Error(`overlay and journal tables are required for writable table ${key}`);
795
723
  }
796
724
 
797
- if (requireRouteBasePath && !entry.routes?.basePath) {
798
- throw new Error(`routes.basePath is required for writable table ${key}`);
799
- }
800
-
801
725
  const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({
802
726
  propertyKey,
803
727
  column,
@@ -813,21 +737,20 @@ function buildTableContext(
813
737
  return column.propertyKey;
814
738
  });
815
739
 
816
- const updatedAtColumn = resolveUpdatedAtColumn(key, entry, columns);
817
-
818
740
  return {
819
741
  key,
820
742
  entry,
821
- readModel: qualifyLocalIdentifier(localSchema, entry.clientProjection.readModel),
743
+ readModel: qualifyLocalIdentifier(
744
+ localSchema,
745
+ entry.view != null ? getViewConfig(entry.view).name : entry.clientProjection.syncedTable,
746
+ ),
822
747
  syncedTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.syncedTable),
823
748
  overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),
824
749
  journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),
825
750
  journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),
826
- ...(entry.routes?.basePath ? { routeBasePath: entry.routes.basePath } : {}),
827
751
  pkColumnNames: [...entry.primaryKey.columns],
828
752
  pkPropertyKeys,
829
753
  recordIncludesOverlayState: recordSchemaIncludesOverlayState(entry.schemas?.recordSchema),
830
- updatedAtColumn,
831
754
  columns,
832
755
  };
833
756
  }
@@ -1533,17 +1456,9 @@ async function flushBatch(
1533
1456
  );
1534
1457
  }
1535
1458
 
1536
- // Reconcile overlays for affected tables so acknowledged
1537
- // mutations are cleared from the local overlay.
1538
- const reconciledContexts = [...new Set(pending.map((row) => row.context))];
1539
-
1540
- for (const context of reconciledContexts) {
1541
- await reconcileTable(db, context);
1542
- }
1543
-
1544
1459
  return {
1545
1460
  processedCount: pending.length,
1546
- affectedContexts: reconciledContexts,
1461
+ affectedContexts: [...new Set(pending.map((row) => row.context))],
1547
1462
  };
1548
1463
  }
1549
1464
 
@@ -1557,42 +1472,6 @@ function resolveBatchMutationUrl(batchWriteUrl: string): string {
1557
1472
  return `${trimmed}/mutations`;
1558
1473
  }
1559
1474
 
1560
- function toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {
1561
- const normalized: Record<string, unknown> = {};
1562
-
1563
- for (const { propertyKey, column } of context.columns) {
1564
- const columnName = column.name;
1565
-
1566
- if (Object.prototype.hasOwnProperty.call(payload, columnName)) {
1567
- normalized[columnName] = payload[columnName];
1568
- continue;
1569
- }
1570
-
1571
- if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
1572
- normalized[columnName] = payload[propertyKey];
1573
- }
1574
- }
1575
-
1576
- return normalized;
1577
- }
1578
-
1579
- function filterProjectedPayload(context: TableContext, payload: Record<string, unknown>) {
1580
- const normalized: Record<string, unknown> = {};
1581
-
1582
- for (const { propertyKey, column } of context.columns) {
1583
- if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
1584
- normalized[propertyKey] = payload[propertyKey];
1585
- continue;
1586
- }
1587
-
1588
- if (Object.prototype.hasOwnProperty.call(payload, column.name)) {
1589
- normalized[column.name] = payload[column.name];
1590
- }
1591
- }
1592
-
1593
- return normalized;
1594
- }
1595
-
1596
1475
  function stripManagedFields(
1597
1476
  context: TableContext,
1598
1477
  payload: Record<string, unknown>,
@@ -1611,222 +1490,98 @@ function stripManagedFields(
1611
1490
  return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));
1612
1491
  }
1613
1492
 
1614
- async function flushTable(
1615
- db: MutationDb,
1616
- context: TableContext,
1617
- writeUrl: string,
1618
- getAuthToken?: () => Promise<string | undefined>,
1619
- ) {
1620
- const result = await db.query<MutationRow>(
1621
- `
1622
- SELECT
1623
- mutation_id AS "mutationId",
1624
- entity_key_json AS "entityKeyJson",
1625
- mutation_seq AS "mutationSeq",
1626
- mutation_kind AS "mutationKind",
1627
- status,
1628
- payload_json AS "payloadJson",
1629
- attempt_count AS "attemptCount",
1630
- last_http_status AS "lastHttpStatus",
1631
- last_error AS "lastError",
1632
- conflict_reason AS "conflictReason",
1633
- next_retry_at_us::text AS "nextRetryAtUs",
1634
- server_updated_at_us::text AS "serverUpdatedAtUs"
1635
- FROM ${context.journalTable}
1636
- WHERE status IN ('pending', 'failed')
1637
- AND COALESCE(next_retry_at_us, 0) <= $1::bigint
1638
- AND NOT EXISTS (
1639
- SELECT 1
1640
- FROM ${context.journalTable} AS earlier
1641
- WHERE earlier.entity_key_json = ${context.journalTable}.entity_key_json
1642
- AND earlier.mutation_seq < ${context.journalTable}.mutation_seq
1643
- AND earlier.status IN ('pending', 'failed', 'sending')
1644
- )
1645
- ORDER BY enqueued_at_us ASC, mutation_seq ASC
1646
- LIMIT ${DEFAULT_FLUSH_BATCH_SIZE}
1647
- `,
1648
- [nowMicroseconds()],
1649
- );
1650
-
1651
- if (result.rows.length === 0) {
1652
- return 0;
1653
- }
1654
-
1655
- for (const mutation of result.rows) {
1656
- const sentAtUs = nowMicroseconds();
1657
- await setMutationStatus(db, context, mutation.mutationId, "sending", {
1658
- attemptCount: mutation.attemptCount + 1,
1659
- sentAtUs,
1660
- updatedAtUs: sentAtUs,
1661
- lastError: null,
1662
- nextRetryAtUs: null,
1663
- lastHttpStatus: null,
1664
- conflictReason: null,
1665
- });
1666
-
1667
- try {
1668
- const entityKey = JSON.parse(mutation.entityKeyJson) as Record<string, string>;
1669
- const payload = JSON.parse(mutation.payloadJson) as Record<string, unknown>;
1670
- let response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken?.());
1671
-
1672
- if ([401, 403].includes(response.status) && getAuthToken) {
1673
- response = await sendMutationRequest(writeUrl, context, entityKey, payload, await getAuthToken());
1674
- }
1675
-
1676
- const responseText = await response.text();
1677
- const responseJson = responseText.length > 0 ? JSON.parse(responseText) : null;
1678
-
1679
- if (!response.ok) {
1680
- const errorMessage =
1681
- responseJson && typeof responseJson.message === "string"
1682
- ? responseJson.message
1683
- : `Write API responded with ${response.status}`;
1684
-
1685
- if (mutation.mutationKind === "delete" && response.status === 404) {
1686
- await markDeleteAcknowledged(db, context, mutation.mutationId);
1687
- continue;
1688
- }
1689
-
1690
- throw new MutationRequestError(errorMessage, response.status);
1691
- }
1692
-
1693
- const ackedAtUs = nowMicroseconds();
1493
+ function toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {
1494
+ const normalized: Record<string, unknown> = {};
1694
1495
 
1695
- if (mutation.mutationKind === "delete") {
1696
- await markDeleteAcknowledged(db, context, mutation.mutationId);
1697
- } else {
1698
- const created = parseRecord(context, responseJson);
1699
- const createdRecord = ensureRecord(created);
1700
- const serverUpdatedAtUs = toOptionalString(createdRecord.updatedAtUs);
1496
+ for (const { propertyKey, column } of context.columns) {
1497
+ const columnName = column.name;
1701
1498
 
1702
- await db.query(
1703
- `
1704
- UPDATE ${context.journalTable}
1705
- SET
1706
- status = 'acked',
1707
- acked_at_us = $2::bigint,
1708
- updated_at_us = $2::bigint,
1709
- server_updated_at_us = $3::bigint,
1710
- last_error = NULL,
1711
- last_http_status = 200,
1712
- conflict_reason = NULL,
1713
- next_retry_at_us = NULL
1714
- WHERE mutation_id = $1
1715
- `,
1716
- [mutation.mutationId, ackedAtUs, serverUpdatedAtUs],
1717
- );
1499
+ if (Object.prototype.hasOwnProperty.call(payload, columnName)) {
1500
+ normalized[columnName] = payload[columnName];
1501
+ continue;
1502
+ }
1718
1503
 
1719
- if (!(await hasLaterMutations(db, context, mutation.entityKeyJson, mutation.mutationSeq))) {
1720
- await updateOverlayTimestamps(db, context, entityKey, createdRecord, ackedAtUs);
1721
- }
1722
- }
1723
- } catch (error) {
1724
- const failedAtUs = nowMicroseconds();
1725
- const attemptCount = mutation.attemptCount + 1;
1726
- const nextRetryAtUs = computeNextRetryAtUs(failedAtUs, attemptCount);
1727
- const lastHttpStatus = error instanceof MutationRequestError ? error.status : null;
1728
- const conflictReason =
1729
- lastHttpStatus === 404 || lastHttpStatus === 409
1730
- ? error instanceof Error
1731
- ? error.message
1732
- : "Server conflict"
1733
- : null;
1734
-
1735
- await setMutationStatus(db, context, mutation.mutationId, "failed", {
1736
- attemptCount,
1737
- updatedAtUs: failedAtUs,
1738
- lastError: error instanceof Error ? error.message : "Unknown write failure",
1739
- nextRetryAtUs,
1740
- lastHttpStatus,
1741
- conflictReason,
1742
- });
1504
+ if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {
1505
+ normalized[columnName] = payload[propertyKey];
1743
1506
  }
1744
1507
  }
1745
1508
 
1746
- await reconcileTable(db, context);
1747
- return result.rows.length;
1509
+ return normalized;
1748
1510
  }
1749
1511
 
1750
1512
  async function reconcileTable(db: MutationDb, context: TableContext) {
1751
- await clearAcknowledgedDeletes(db, context);
1752
-
1513
+ // PK-match only — no timestamp gate. The trigger on the synced table
1514
+ // handles real-time cleanup; this is a bulk recovery/fallback path.
1753
1515
  await db.exec("BEGIN");
1754
1516
 
1755
1517
  try {
1518
+ // Clear acknowledged non-delete mutations + matching overlays
1756
1519
  await db.query(
1757
- "WITH deleted AS (" +
1520
+ "WITH cleared_journal AS (" +
1758
1521
  "DELETE FROM " +
1759
1522
  context.journalTable +
1760
1523
  " AS journal " +
1761
- "USING " +
1762
- context.syncedTable +
1763
- " AS synced " +
1764
1524
  "WHERE journal.status = 'acked' " +
1765
- "AND journal.mutation_kind <> 'delete' " +
1766
1525
  "AND journal.server_updated_at_us IS NOT NULL " +
1767
- "AND " +
1768
- buildColumnEquality(context.pkColumnNames, "journal", "synced") +
1769
- " " +
1770
- "AND synced." +
1771
- context.updatedAtColumn +
1772
- " >= journal.server_updated_at_us " +
1773
- "RETURNING journal.mutation_id, journal.entity_key_json, " +
1526
+ "AND journal.mutation_kind <> 'delete' " +
1527
+ "RETURNING journal.entity_key_json, " +
1774
1528
  context.pkColumnNames.map((cn) => "journal." + cn).join(", ") +
1775
- ")," +
1776
- "clearable_entities AS (" +
1777
- "SELECT DISTINCT deleted.entity_key_json, " +
1778
- context.pkColumnNames.map((cn) => "deleted." + cn).join(", ") +
1779
- " FROM deleted " +
1780
- "WHERE NOT EXISTS (" +
1781
- "SELECT 1 " +
1782
- "FROM " +
1783
- context.journalTable +
1784
- " AS remaining " +
1785
- "WHERE remaining.entity_key_json = deleted.entity_key_json " +
1786
- "AND remaining.mutation_id NOT IN (" +
1787
- "SELECT deleted_for_entity.mutation_id " +
1788
- "FROM deleted AS deleted_for_entity " +
1789
- "WHERE deleted_for_entity.entity_key_json = deleted.entity_key_json" +
1790
- ")" +
1791
- ")" +
1792
1529
  ") " +
1793
1530
  "DELETE FROM " +
1794
1531
  context.overlayTable +
1795
1532
  " AS overlay " +
1796
- "USING clearable_entities " +
1533
+ "USING cleared_journal AS cj " +
1797
1534
  "WHERE " +
1798
- buildColumnEquality(context.pkColumnNames, "overlay", "clearable_entities"),
1535
+ buildColumnEquality(context.pkColumnNames, "overlay", "cj") +
1536
+ " " +
1537
+ "AND NOT EXISTS (" +
1538
+ "SELECT 1 FROM " +
1539
+ context.journalTable +
1540
+ " AS j " +
1541
+ "WHERE j.entity_key_json = cj.entity_key_json " +
1542
+ "AND j.status IN ('pending', 'sending', 'failed')" +
1543
+ ")",
1799
1544
  );
1800
- await db.exec("COMMIT");
1801
- } catch (error) {
1802
- await db.exec("ROLLBACK");
1803
- throw error;
1804
- }
1805
- }
1806
-
1807
- async function clearAcknowledgedDeletes(db: MutationDb, context: TableContext) {
1808
- await db.exec("BEGIN");
1809
1545
 
1810
- try {
1811
- await db.query(`
1812
- WITH clearable_entities AS (
1813
- SELECT DISTINCT journal.entity_key_json, ${context.pkColumnNames.map((columnName) => `journal.${columnName}`).join(", ")}
1814
- FROM ${context.journalTable} AS journal
1815
- LEFT JOIN ${context.syncedTable} AS synced
1816
- ON ${buildColumnEquality(context.pkColumnNames, "journal", "synced")}
1817
- WHERE journal.status = 'acked'
1818
- AND journal.mutation_kind = 'delete'
1819
- AND synced.${context.pkColumnNames[0]!} IS NULL
1820
- ),
1821
- deleted_overlay AS (
1822
- DELETE FROM ${context.overlayTable} AS overlay
1823
- USING clearable_entities
1824
- WHERE ${buildColumnEquality(context.pkColumnNames, "overlay", "clearable_entities")}
1825
- )
1826
- DELETE FROM ${context.journalTable} AS journal
1827
- USING clearable_entities
1828
- WHERE journal.entity_key_json = clearable_entities.entity_key_json
1829
- `);
1546
+ // Clear acknowledged delete mutations where synced row is absent
1547
+ // Single compound CTE — PGlite does not support multi-statement query().
1548
+ await db.query(
1549
+ "WITH clearable_entities AS (" +
1550
+ "SELECT DISTINCT journal.entity_key_json, " +
1551
+ context.pkColumnNames.map((cn) => "journal." + cn).join(", ") +
1552
+ " FROM " +
1553
+ context.journalTable +
1554
+ " AS journal " +
1555
+ "LEFT JOIN " +
1556
+ context.syncedTable +
1557
+ " AS synced " +
1558
+ "ON " +
1559
+ buildColumnEquality(context.pkColumnNames, "journal", "synced") +
1560
+ " " +
1561
+ "WHERE journal.status = 'acked' " +
1562
+ "AND journal.mutation_kind = 'delete' " +
1563
+ "AND synced." +
1564
+ context.pkColumnNames[0] +
1565
+ " IS NULL" +
1566
+ "), " +
1567
+ "deleted_overlay AS (" +
1568
+ "DELETE FROM " +
1569
+ context.overlayTable +
1570
+ " AS overlay " +
1571
+ "USING clearable_entities AS ce " +
1572
+ "WHERE " +
1573
+ buildColumnEquality(context.pkColumnNames, "overlay", "ce") +
1574
+ ") " +
1575
+ "DELETE FROM " +
1576
+ context.journalTable +
1577
+ " AS journal " +
1578
+ "USING clearable_entities AS ce " +
1579
+ "WHERE " +
1580
+ buildColumnEquality(context.pkColumnNames, "journal", "ce") +
1581
+ " " +
1582
+ "AND journal.status = 'acked' " +
1583
+ "AND journal.mutation_kind = 'delete'",
1584
+ );
1830
1585
  await db.exec("COMMIT");
1831
1586
  } catch (error) {
1832
1587
  await db.exec("ROLLBACK");
@@ -1834,46 +1589,6 @@ async function clearAcknowledgedDeletes(db: MutationDb, context: TableContext) {
1834
1589
  }
1835
1590
  }
1836
1591
 
1837
- async function sendMutationRequest(
1838
- writeUrl: string,
1839
- context: TableContext,
1840
- entityKey: Record<string, string>,
1841
- payload: Record<string, unknown>,
1842
- bearerToken?: string,
1843
- ) {
1844
- if (!context.routeBasePath) {
1845
- throw new Error(`routes.basePath is required for direct mutation requests on table ${context.key}`);
1846
- }
1847
-
1848
- switch (payload.kind) {
1849
- case "create":
1850
- return fetch(`${writeUrl}${context.routeBasePath}`, {
1851
- method: "POST",
1852
- headers: buildRequestHeaders(bearerToken),
1853
- body: JSON.stringify(filterProjectedPayload(context, ensureRecord(payload.value))),
1854
- });
1855
- case "update":
1856
- return fetch(
1857
- `${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`,
1858
- {
1859
- method: "PATCH",
1860
- headers: buildRequestHeaders(bearerToken),
1861
- body: JSON.stringify(filterProjectedPayload(context, ensureRecord(payload.patch))),
1862
- },
1863
- );
1864
- case "delete":
1865
- return fetch(
1866
- `${writeUrl}${context.routeBasePath}/${encodeURIComponent(getSingleEntityKeyValue(context, entityKey))}`,
1867
- {
1868
- method: "DELETE",
1869
- headers: buildRequestHeaders(bearerToken),
1870
- },
1871
- );
1872
- default:
1873
- throw new Error(`Unknown mutation kind for table ${context.key}`);
1874
- }
1875
- }
1876
-
1877
1592
  function buildRequestHeaders(bearerToken?: string): Record<string, string> {
1878
1593
  if (!bearerToken) {
1879
1594
  return {
@@ -1887,57 +1602,6 @@ function buildRequestHeaders(bearerToken?: string): Record<string, string> {
1887
1602
  };
1888
1603
  }
1889
1604
 
1890
- function getSingleEntityKeyValue(context: TableContext, entityKey: Record<string, string>) {
1891
- if (context.pkPropertyKeys.length !== 1) {
1892
- throw new Error(`Only single-column primary keys are supported for routes on table ${context.key}`);
1893
- }
1894
-
1895
- return entityKey[context.pkPropertyKeys[0]!]!;
1896
- }
1897
-
1898
- async function setMutationStatus(
1899
- db: MutationDb,
1900
- context: TableContext,
1901
- mutationId: string,
1902
- status: MutationStatus,
1903
- options: {
1904
- attemptCount: number;
1905
- updatedAtUs: string;
1906
- sentAtUs?: string | null;
1907
- nextRetryAtUs?: string | null;
1908
- lastError?: string | null;
1909
- lastHttpStatus?: number | null;
1910
- conflictReason?: string | null;
1911
- },
1912
- ) {
1913
- await db.query(
1914
- `
1915
- UPDATE ${context.journalTable}
1916
- SET
1917
- status = $2,
1918
- attempt_count = $3,
1919
- sent_at_us = COALESCE($4::bigint, sent_at_us),
1920
- updated_at_us = $5::bigint,
1921
- last_error = $6,
1922
- next_retry_at_us = $7::bigint,
1923
- last_http_status = $8,
1924
- conflict_reason = $9
1925
- WHERE mutation_id = $1
1926
- `,
1927
- [
1928
- mutationId,
1929
- status,
1930
- options.attemptCount,
1931
- options.sentAtUs ?? null,
1932
- options.updatedAtUs,
1933
- options.lastError ?? null,
1934
- options.nextRetryAtUs ?? null,
1935
- options.lastHttpStatus ?? null,
1936
- options.conflictReason ?? null,
1937
- ],
1938
- );
1939
- }
1940
-
1941
1605
  async function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {
1942
1606
  if (updates.length === 0) {
1943
1607
  return;
@@ -2058,68 +1722,6 @@ async function applyMutationStatusUpdates(db: MutationDb, context: TableContext,
2058
1722
  );
2059
1723
  }
2060
1724
 
2061
- async function markDeleteAcknowledged(db: MutationDb, context: TableContext, mutationId: string) {
2062
- const ackedAtUs = nowMicroseconds();
2063
-
2064
- await db.query(
2065
- `
2066
- UPDATE ${context.journalTable}
2067
- SET
2068
- status = 'acked',
2069
- acked_at_us = $2::bigint,
2070
- updated_at_us = $2::bigint,
2071
- last_error = NULL,
2072
- last_http_status = 204,
2073
- conflict_reason = NULL,
2074
- next_retry_at_us = NULL
2075
- WHERE mutation_id = $1
2076
- `,
2077
- [mutationId, ackedAtUs],
2078
- );
2079
- }
2080
-
2081
- async function hasLaterMutations(db: MutationDb, context: TableContext, entityKeyJson: string, mutationSeq: number) {
2082
- const result = await db.query<{ count: number }>(
2083
- `
2084
- SELECT COUNT(*)::int AS count
2085
- FROM ${context.journalTable}
2086
- WHERE entity_key_json = $1
2087
- AND mutation_seq > $2
2088
- `,
2089
- [entityKeyJson, mutationSeq],
2090
- );
2091
-
2092
- return (result.rows[0]?.count ?? 0) > 0;
2093
- }
2094
-
2095
- async function updateOverlayTimestamps(
2096
- db: MutationDb,
2097
- context: TableContext,
2098
- entityKey: Record<string, string>,
2099
- record: Record<string, unknown>,
2100
- localUpdatedAtUs: string,
2101
- ) {
2102
- if (!hasProperty(context, "createdAtUs") || !hasProperty(context, "updatedAtUs")) {
2103
- return;
2104
- }
2105
-
2106
- await db.query(
2107
- `
2108
- UPDATE ${context.overlayTable}
2109
- SET
2110
- created_at_us = $${context.pkPropertyKeys.length + 1}::bigint,
2111
- updated_at_us = $${context.pkPropertyKeys.length + 2}::bigint,
2112
- local_updated_at_us = $${context.pkPropertyKeys.length + 3}::bigint
2113
- WHERE ${buildWhereClause(context)}
2114
- `,
2115
- [...buildWhereParams(context, entityKey), String(record.createdAtUs), String(record.updatedAtUs), localUpdatedAtUs],
2116
- );
2117
- }
2118
-
2119
- function buildWhereClause(context: TableContext) {
2120
- return context.pkColumnNames.map((columnName, index) => `${columnName} = $${index + 1}`).join(" AND ");
2121
- }
2122
-
2123
1725
  function buildColumnEquality(columnNames: string[], leftAlias: string, rightAlias: string) {
2124
1726
  return columnNames.map((columnName) => `${leftAlias}.${columnName} = ${rightAlias}.${columnName}`).join(" AND ");
2125
1727
  }
@@ -2144,10 +1746,6 @@ function escapeSqlString(value: string) {
2144
1746
  return value.replace(/'/g, "''");
2145
1747
  }
2146
1748
 
2147
- function buildWhereParams(context: TableContext, entityKey: Record<string, string>) {
2148
- return context.pkPropertyKeys.map((propertyKey) => entityKey[propertyKey]);
2149
- }
2150
-
2151
1749
  function formatSqlValuePlaceholder(position: number, columnName: string) {
2152
1750
  return /_at_us$/.test(columnName) ? `$${position}::bigint` : `$${position}`;
2153
1751
  }
@@ -2172,23 +1770,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
2172
1770
  return typeof value === "object" && value !== null;
2173
1771
  }
2174
1772
 
2175
- function toOptionalString(value: unknown) {
2176
- if (value === undefined || value === null) {
2177
- return null;
2178
- }
2179
-
2180
- switch (typeof value) {
2181
- case "string":
2182
- return value;
2183
- case "number":
2184
- case "boolean":
2185
- case "bigint":
2186
- return String(value);
2187
- default:
2188
- return JSON.stringify(value);
2189
- }
2190
- }
2191
-
2192
1773
  class MutationRequestError extends Error {
2193
1774
  constructor(
2194
1775
  message: string,