@pgxsinkit/client 0.1.49 → 0.1.50
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/boot-report.d.ts +76 -0
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/index.d.ts +56 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1036 -286
- package/dist/index.js.map +13 -12
- package/dist/local-store.d.ts +58 -0
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +340 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +36 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts +82 -0
- package/dist/mutations-api.d.ts.map +1 -0
- package/dist/schema.d.ts +62 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +44 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +1 -1
- package/src/boot-report.ts +108 -0
- package/src/index.ts +555 -136
- package/src/local-store.ts +150 -3
- package/src/local-tables.ts +49 -1
- package/src/mutation.ts +256 -15
- package/src/mutations-api.ts +310 -0
- package/src/schema.ts +406 -193
- package/src/worker/attach-sync-client.ts +114 -5
- package/src/worker/define-sync-worker.ts +65 -4
- package/src/worker/protocol.ts +38 -1
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ var __require = import.meta.require;
|
|
|
4
4
|
// packages/client/src/index.ts
|
|
5
5
|
import { PGlite as PGlite2 } from "@electric-sql/pglite";
|
|
6
6
|
import { live } from "@electric-sql/pglite/live";
|
|
7
|
-
import { drizzle as
|
|
7
|
+
import { drizzle as drizzle5 } from "drizzle-orm/pglite";
|
|
8
8
|
import { defineRelations } from "drizzle-orm/relations";
|
|
9
9
|
import { fingerprintRegistry as fingerprintRegistry2, getSyncRegistrySchema as getSyncRegistrySchema4, isClaimsDependentRowFilter } from "@pgxsinkit/contracts";
|
|
10
10
|
|
|
@@ -153,7 +153,17 @@ function createBootReportBuilder(init) {
|
|
|
153
153
|
let prepareMs = null;
|
|
154
154
|
let pgliteCreateMs = null;
|
|
155
155
|
let provision = null;
|
|
156
|
+
let warmBoot = {
|
|
157
|
+
schemaSkipped: false,
|
|
158
|
+
schemaFingerprintMatch: false,
|
|
159
|
+
journalRecoverySkipped: false,
|
|
160
|
+
journalRecoveryRequired: true,
|
|
161
|
+
journalTablesVisited: 0,
|
|
162
|
+
journalRowsRecovered: null
|
|
163
|
+
};
|
|
156
164
|
let syncStartDoneOffset = null;
|
|
165
|
+
let localReadReadyMs = null;
|
|
166
|
+
let writeReadyMs = null;
|
|
157
167
|
const groups = [];
|
|
158
168
|
let built = null;
|
|
159
169
|
const duration = (key) => durations.get(key) ?? 0;
|
|
@@ -179,6 +189,26 @@ function createBootReportBuilder(init) {
|
|
|
179
189
|
setProvision: (value) => {
|
|
180
190
|
provision = value;
|
|
181
191
|
},
|
|
192
|
+
setSchemaFastPath: (info) => {
|
|
193
|
+
warmBoot = { ...warmBoot, schemaSkipped: info.skipped, schemaFingerprintMatch: info.fingerprintMatch };
|
|
194
|
+
},
|
|
195
|
+
setJournalRecovery: (info) => {
|
|
196
|
+
warmBoot = {
|
|
197
|
+
...warmBoot,
|
|
198
|
+
journalRecoverySkipped: info.skipped,
|
|
199
|
+
journalRecoveryRequired: info.required,
|
|
200
|
+
journalTablesVisited: info.tablesVisited,
|
|
201
|
+
journalRowsRecovered: info.rowsRecovered
|
|
202
|
+
};
|
|
203
|
+
},
|
|
204
|
+
setLocalReadReadyMs: (ms) => {
|
|
205
|
+
if (localReadReadyMs == null)
|
|
206
|
+
localReadReadyMs = ms;
|
|
207
|
+
},
|
|
208
|
+
setWriteReadyMs: (ms) => {
|
|
209
|
+
if (writeReadyMs == null)
|
|
210
|
+
writeReadyMs = ms;
|
|
211
|
+
},
|
|
182
212
|
setSyncStartMs: (ms) => {
|
|
183
213
|
durations.set("syncStart", ms);
|
|
184
214
|
},
|
|
@@ -199,11 +229,15 @@ function createBootReportBuilder(init) {
|
|
|
199
229
|
reportVersion: 1,
|
|
200
230
|
mode: init.mode,
|
|
201
231
|
freshStore: init.freshStore,
|
|
232
|
+
storeKind: init.storeKind,
|
|
202
233
|
overlapPrefetch: init.overlapPrefetch,
|
|
203
234
|
registryFingerprint: init.registryFingerprint,
|
|
204
235
|
startedAt,
|
|
205
236
|
totalMs,
|
|
237
|
+
localReadReadyMs,
|
|
238
|
+
writeReadyMs,
|
|
206
239
|
provision,
|
|
240
|
+
warmBoot,
|
|
207
241
|
phases: {
|
|
208
242
|
pgliteCreateMs,
|
|
209
243
|
schemaExecMs: duration("schemaExec"),
|
|
@@ -739,7 +773,7 @@ function wrapLiveQueryForMaterialization(sql, fields) {
|
|
|
739
773
|
}
|
|
740
774
|
|
|
741
775
|
// packages/client/src/local-store.ts
|
|
742
|
-
import { eq as eq3, like as like2 } from "drizzle-orm";
|
|
776
|
+
import { and as and3, eq as eq3, like as like2, notExists, sql as sql3 } from "drizzle-orm";
|
|
743
777
|
import { drizzle as drizzle2 } from "drizzle-orm/pglite";
|
|
744
778
|
|
|
745
779
|
// packages/client/src/local-tables.ts
|
|
@@ -771,6 +805,7 @@ import {
|
|
|
771
805
|
getLocalSyncPrimaryKeyColumns,
|
|
772
806
|
getSyncRegistrySchema,
|
|
773
807
|
getProjectedColumns,
|
|
808
|
+
hashString,
|
|
774
809
|
maybeQuoteIdentifier,
|
|
775
810
|
quoteIdentifier as quoteIdentifier4,
|
|
776
811
|
quoteSqlLiteral as quoteSqlStringLiteral
|
|
@@ -1400,9 +1435,38 @@ async function clearShapeTags({
|
|
|
1400
1435
|
// packages/client/src/schema.ts
|
|
1401
1436
|
var LOCAL_META_TABLE = "pgxsinkit_local_meta";
|
|
1402
1437
|
var REGISTRY_FINGERPRINT_KEY = "registry_fingerprint";
|
|
1403
|
-
|
|
1438
|
+
var LOCAL_SCHEMA_FINGERPRINT_KEY = "local_schema_fingerprint";
|
|
1439
|
+
var LOCAL_SCHEMA_FINGERPRINT_PREFIX = "lsf1:";
|
|
1440
|
+
var ALL_MUTATIONS_VIEW = "pgxsinkit_all_mutations";
|
|
1441
|
+
var ALL_MUTATIONS_JOURNAL_COLUMNS = [
|
|
1442
|
+
"mutation_id",
|
|
1443
|
+
"entity_key_json",
|
|
1444
|
+
"mutation_seq",
|
|
1445
|
+
"mutation_kind",
|
|
1446
|
+
"status",
|
|
1447
|
+
"registry_version",
|
|
1448
|
+
"base_server_version",
|
|
1449
|
+
"write_unit",
|
|
1450
|
+
"write_mode",
|
|
1451
|
+
"attempt_count",
|
|
1452
|
+
"last_error",
|
|
1453
|
+
"last_http_status",
|
|
1454
|
+
"conflict_reason",
|
|
1455
|
+
"server_updated_at_us",
|
|
1456
|
+
"enqueued_at_us",
|
|
1457
|
+
"next_retry_at_us",
|
|
1458
|
+
"sent_at_us",
|
|
1459
|
+
"acked_at_us",
|
|
1460
|
+
"updated_at_us"
|
|
1461
|
+
];
|
|
1462
|
+
function joinSchemaStatements(statements) {
|
|
1463
|
+
return `${statements.join(`
|
|
1464
|
+
|
|
1465
|
+
`)}
|
|
1466
|
+
`;
|
|
1467
|
+
}
|
|
1468
|
+
function localMetaBootstrapStatements(localSchema) {
|
|
1404
1469
|
const statements = [];
|
|
1405
|
-
const localSchema = getSyncRegistrySchema(registry);
|
|
1406
1470
|
if (localSchema !== "public") {
|
|
1407
1471
|
statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier4(localSchema)};`);
|
|
1408
1472
|
}
|
|
@@ -1413,104 +1477,103 @@ function generateLocalSchemaSql(registry) {
|
|
|
1413
1477
|
].join(`,
|
|
1414
1478
|
`)}
|
|
1415
1479
|
);`);
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1480
|
+
return statements;
|
|
1481
|
+
}
|
|
1482
|
+
function buildLocalMetaBootstrapSql(registry) {
|
|
1483
|
+
return joinSchemaStatements(localMetaBootstrapStatements(getSyncRegistrySchema(registry)));
|
|
1484
|
+
}
|
|
1485
|
+
function buildEntryClusterStatements(entry, tableKey, localSchema) {
|
|
1486
|
+
const statements = [];
|
|
1487
|
+
const ephemeral = entry.retention === "ephemeral";
|
|
1488
|
+
const objectSchema = ephemeral ? "public" : localSchema;
|
|
1489
|
+
const temp = ephemeral ? "TEMP " : "";
|
|
1490
|
+
const projection = getClientProjection(entry, tableKey, objectSchema);
|
|
1491
|
+
const columns = getProjectedColumns(entry).map(({ column }) => column);
|
|
1492
|
+
const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
|
|
1493
|
+
const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
|
|
1494
|
+
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (
|
|
1429
1495
|
${baseColumnsSql}
|
|
1430
1496
|
);`);
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1497
|
+
if (entry.mode === "readonly") {
|
|
1498
|
+
return statements;
|
|
1499
|
+
}
|
|
1500
|
+
if (!projection.overlayTable || !projection.journalTable) {
|
|
1501
|
+
throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);
|
|
1502
|
+
}
|
|
1503
|
+
const journalTableName = entry.clientProjection?.journalTable;
|
|
1504
|
+
if (!journalTableName) {
|
|
1505
|
+
throw new Error(`journal table is required for writable table ${tableKey}`);
|
|
1506
|
+
}
|
|
1507
|
+
const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {
|
|
1508
|
+
const column = columns.find((candidate) => candidate.name === columnName);
|
|
1509
|
+
if (!column) {
|
|
1510
|
+
throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
|
|
1440
1511
|
}
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
});
|
|
1448
|
-
const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
|
|
1449
|
-
const journalSequenceName = buildJournalSequenceName(journalTableName);
|
|
1450
|
-
const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);
|
|
1451
|
-
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (
|
|
1512
|
+
return column;
|
|
1513
|
+
});
|
|
1514
|
+
const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
|
|
1515
|
+
const journalSequenceName = buildJournalSequenceName(journalTableName);
|
|
1516
|
+
const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);
|
|
1517
|
+
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (
|
|
1452
1518
|
${[
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1519
|
+
...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),
|
|
1520
|
+
"overlay_kind VARCHAR(24) NOT NULL",
|
|
1521
|
+
"local_updated_at_us BIGINT NOT NULL",
|
|
1522
|
+
...buildCompositePrimaryKeyClauses(primaryKeyColumnNames)
|
|
1523
|
+
].join(`,
|
|
1458
1524
|
`)}
|
|
1459
1525
|
);`);
|
|
1460
|
-
|
|
1461
|
-
|
|
1526
|
+
statements.push(`CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`);
|
|
1527
|
+
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (
|
|
1462
1528
|
${[
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1529
|
+
"mutation_id UUID PRIMARY KEY",
|
|
1530
|
+
...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),
|
|
1531
|
+
"entity_key_json TEXT NOT NULL",
|
|
1532
|
+
`mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
|
|
1533
|
+
"mutation_kind VARCHAR(24) NOT NULL",
|
|
1534
|
+
"status VARCHAR(24) NOT NULL",
|
|
1535
|
+
"registry_version TEXT",
|
|
1536
|
+
"base_server_version BIGINT",
|
|
1537
|
+
"write_unit TEXT",
|
|
1538
|
+
"write_mode VARCHAR(24)",
|
|
1539
|
+
"payload_json TEXT NOT NULL",
|
|
1540
|
+
"attempt_count INTEGER NOT NULL DEFAULT 0",
|
|
1541
|
+
"last_error TEXT",
|
|
1542
|
+
"last_http_status INTEGER",
|
|
1543
|
+
"conflict_reason TEXT",
|
|
1544
|
+
"server_updated_at_us BIGINT",
|
|
1545
|
+
"enqueued_at_us BIGINT NOT NULL",
|
|
1546
|
+
"next_retry_at_us BIGINT",
|
|
1547
|
+
"sent_at_us BIGINT",
|
|
1548
|
+
"acked_at_us BIGINT",
|
|
1549
|
+
"updated_at_us BIGINT NOT NULL"
|
|
1550
|
+
].join(`,
|
|
1485
1551
|
`)}
|
|
1486
1552
|
);`);
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: "NEW" });
|
|
1512
|
-
const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;
|
|
1513
|
-
statements.push(`CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$
|
|
1553
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, ["status", "enqueued_at_us"]));
|
|
1554
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [
|
|
1555
|
+
"status",
|
|
1556
|
+
"next_retry_at_us",
|
|
1557
|
+
"enqueued_at_us"
|
|
1558
|
+
]));
|
|
1559
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [
|
|
1560
|
+
...entry.primaryKey.columns,
|
|
1561
|
+
"mutation_seq"
|
|
1562
|
+
]));
|
|
1563
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [
|
|
1564
|
+
"entity_key_json",
|
|
1565
|
+
"mutation_seq"
|
|
1566
|
+
]));
|
|
1567
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [
|
|
1568
|
+
"entity_key_json",
|
|
1569
|
+
"status",
|
|
1570
|
+
"mutation_seq"
|
|
1571
|
+
]));
|
|
1572
|
+
const pkMatchSql = (alias) => primaryKeyColumns.map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`).join(" AND ");
|
|
1573
|
+
const pkOverlayMatchSql = primaryKeyColumns.map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`).join(" AND ");
|
|
1574
|
+
const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: "NEW" });
|
|
1575
|
+
const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;
|
|
1576
|
+
statements.push(`CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$
|
|
1514
1577
|
` + `BEGIN
|
|
1515
1578
|
` + ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has
|
|
1516
1579
|
` + ` -- been acked \u2014 that later write IS the resolution. The acked resolver is cleared by the
|
|
@@ -1540,22 +1603,85 @@ function generateLocalSchemaSql(registry) {
|
|
|
1540
1603
|
` + ` RETURN COALESCE(NEW, OLD);
|
|
1541
1604
|
` + `END;
|
|
1542
1605
|
` + `$$ LANGUAGE plpgsql;`);
|
|
1543
|
-
|
|
1606
|
+
statements.push(`CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}
|
|
1544
1607
|
` + `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}
|
|
1545
1608
|
` + `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`);
|
|
1546
|
-
|
|
1609
|
+
statements.push(`CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS
|
|
1547
1610
|
${buildReadModelViewSql(entry, projection, columns.map((column) => column.name))};`);
|
|
1548
|
-
|
|
1611
|
+
statements.push(`CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS
|
|
1549
1612
|
${buildSyncStateView(entry, {
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1613
|
+
syncedTable: projection.syncedTable,
|
|
1614
|
+
overlayTable: projection.overlayTable,
|
|
1615
|
+
journalTable: projection.journalTable
|
|
1616
|
+
})};`);
|
|
1617
|
+
return statements;
|
|
1618
|
+
}
|
|
1619
|
+
function durableSchemaStatements(registry) {
|
|
1620
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
1621
|
+
const statements = [...localMetaBootstrapStatements(localSchema)];
|
|
1622
|
+
for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {
|
|
1623
|
+
statements.push(buildCreateEnumTypeSql(enumDefinition));
|
|
1554
1624
|
}
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1625
|
+
for (const [tableKey, entry] of Object.entries(registry)) {
|
|
1626
|
+
if (entry.retention === "ephemeral") {
|
|
1627
|
+
continue;
|
|
1628
|
+
}
|
|
1629
|
+
statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));
|
|
1630
|
+
}
|
|
1631
|
+
return statements;
|
|
1632
|
+
}
|
|
1633
|
+
function ephemeralSchemaStatements(registry) {
|
|
1634
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
1635
|
+
const ephemeralEntries = Object.entries(registry).filter(([, entry]) => entry.retention === "ephemeral");
|
|
1636
|
+
const statements = [];
|
|
1637
|
+
if (ephemeralEntries.length > 0) {
|
|
1638
|
+
for (const enumDefinition of collectEnumDefinitionsFromEntries(ephemeralEntries.map(([, entry]) => entry), localSchema)) {
|
|
1639
|
+
statements.push(buildCreateEnumTypeSql(enumDefinition));
|
|
1640
|
+
}
|
|
1641
|
+
for (const [tableKey, entry] of ephemeralEntries) {
|
|
1642
|
+
statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
statements.push(...allMutationsViewStatements(registry));
|
|
1646
|
+
return statements;
|
|
1647
|
+
}
|
|
1648
|
+
function allMutationsViewStatements(registry) {
|
|
1649
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
1650
|
+
const branches = [];
|
|
1651
|
+
for (const [tableKey, entry] of Object.entries(registry)) {
|
|
1652
|
+
if (entry.mode === "readonly" || !entry.clientProjection?.journalTable) {
|
|
1653
|
+
continue;
|
|
1654
|
+
}
|
|
1655
|
+
const objectSchema = entry.retention === "ephemeral" ? "public" : localSchema;
|
|
1656
|
+
const projection = getClientProjection(entry, tableKey, objectSchema);
|
|
1657
|
+
if (!projection.journalTable) {
|
|
1658
|
+
continue;
|
|
1659
|
+
}
|
|
1660
|
+
branches.push(`SELECT ${quoteSqlStringLiteral(tableKey)} AS table_key,
|
|
1661
|
+
${ALL_MUTATIONS_JOURNAL_COLUMNS.join(`,
|
|
1662
|
+
`)}
|
|
1663
|
+
FROM ${projection.journalTable}`);
|
|
1664
|
+
}
|
|
1665
|
+
if (branches.length === 0) {
|
|
1666
|
+
return [];
|
|
1667
|
+
}
|
|
1668
|
+
return [`CREATE OR REPLACE TEMP VIEW ${ALL_MUTATIONS_VIEW} AS
|
|
1669
|
+
${branches.join(`
|
|
1670
|
+
UNION ALL
|
|
1671
|
+
`)};`];
|
|
1672
|
+
}
|
|
1673
|
+
function generateDurableLocalSchemaSql(registry) {
|
|
1674
|
+
return joinSchemaStatements(durableSchemaStatements(registry));
|
|
1675
|
+
}
|
|
1676
|
+
function generateEphemeralLocalSchemaSql(registry) {
|
|
1677
|
+
const statements = ephemeralSchemaStatements(registry);
|
|
1678
|
+
return statements.length === 0 ? "" : joinSchemaStatements(statements);
|
|
1679
|
+
}
|
|
1680
|
+
function generateLocalSchemaSql(registry) {
|
|
1681
|
+
return joinSchemaStatements([...durableSchemaStatements(registry), ...ephemeralSchemaStatements(registry)]);
|
|
1682
|
+
}
|
|
1683
|
+
function computeLocalSchemaFingerprint(registry) {
|
|
1684
|
+
return `${LOCAL_SCHEMA_FINGERPRINT_PREFIX}${hashString(generateDurableLocalSchemaSql(registry))}`;
|
|
1559
1685
|
}
|
|
1560
1686
|
function buildReadModelViewSql(entry, projection, columnNames) {
|
|
1561
1687
|
if (!projection.overlayTable) {
|
|
@@ -2122,6 +2248,34 @@ function resolveApplyTarget(registry, tableKey) {
|
|
|
2122
2248
|
insertRenderCache: new Map
|
|
2123
2249
|
};
|
|
2124
2250
|
}
|
|
2251
|
+
function buildAllMutationsViewColumns() {
|
|
2252
|
+
return {
|
|
2253
|
+
tableKey: text2("table_key").notNull(),
|
|
2254
|
+
mutationId: uuid("mutation_id").notNull(),
|
|
2255
|
+
entityKeyJson: text2("entity_key_json").notNull(),
|
|
2256
|
+
mutationSeq: integer("mutation_seq").notNull(),
|
|
2257
|
+
mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
|
|
2258
|
+
status: varchar("status", { length: 24 }).notNull(),
|
|
2259
|
+
registryVersion: text2("registry_version"),
|
|
2260
|
+
baseServerVersion: bigintText("base_server_version"),
|
|
2261
|
+
writeUnit: text2("write_unit"),
|
|
2262
|
+
writeMode: varchar("write_mode", { length: 24 }),
|
|
2263
|
+
attemptCount: integer("attempt_count").notNull(),
|
|
2264
|
+
lastError: text2("last_error"),
|
|
2265
|
+
lastHttpStatus: integer("last_http_status"),
|
|
2266
|
+
conflictReason: text2("conflict_reason"),
|
|
2267
|
+
serverUpdatedAtUs: bigintText("server_updated_at_us"),
|
|
2268
|
+
enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
|
|
2269
|
+
nextRetryAtUs: bigintText("next_retry_at_us"),
|
|
2270
|
+
sentAtUs: bigintText("sent_at_us"),
|
|
2271
|
+
ackedAtUs: bigintText("acked_at_us"),
|
|
2272
|
+
updatedAtUs: bigintText("updated_at_us").notNull()
|
|
2273
|
+
};
|
|
2274
|
+
}
|
|
2275
|
+
var allMutationsShape = pgView(ALL_MUTATIONS_VIEW, buildAllMutationsViewColumns()).existing();
|
|
2276
|
+
function getAllMutationsView(_registry) {
|
|
2277
|
+
return allMutationsShape;
|
|
2278
|
+
}
|
|
2125
2279
|
function getLocalMetaTable(registry) {
|
|
2126
2280
|
const localSchema = getSyncRegistrySchema2(registry);
|
|
2127
2281
|
const cached = localMetaCache.get(localSchema);
|
|
@@ -2167,6 +2321,49 @@ async function clearLazyGroupActivation(db, registry, groupKey) {
|
|
|
2167
2321
|
async function writeStoredRegistryFingerprint(db, registry, fingerprint) {
|
|
2168
2322
|
await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);
|
|
2169
2323
|
}
|
|
2324
|
+
async function readStoredLocalSchemaFingerprint(db, registry) {
|
|
2325
|
+
const meta = getLocalMetaTable(registry);
|
|
2326
|
+
const query = metaQueryBuilder.select({ value: meta.value }).from(meta).where(eq3(meta.key, LOCAL_SCHEMA_FINGERPRINT_KEY)).limit(1).toSQL();
|
|
2327
|
+
const result = await db.query(query.sql, query.params);
|
|
2328
|
+
return result.rows[0]?.value ?? null;
|
|
2329
|
+
}
|
|
2330
|
+
async function writeStoredLocalSchemaFingerprint(db, registry, fingerprint) {
|
|
2331
|
+
await upsertMetaValue(db, registry, LOCAL_SCHEMA_FINGERPRINT_KEY, fingerprint);
|
|
2332
|
+
}
|
|
2333
|
+
var MUTATION_RECOVERY_REQUIRED_KEY = "mutation_recovery_required";
|
|
2334
|
+
async function readMutationRecoveryRequired(db, registry) {
|
|
2335
|
+
const meta = getLocalMetaTable(registry);
|
|
2336
|
+
const query = metaQueryBuilder.select({ value: meta.value }).from(meta).where(eq3(meta.key, MUTATION_RECOVERY_REQUIRED_KEY)).limit(1).toSQL();
|
|
2337
|
+
const result = await db.query(query.sql, query.params);
|
|
2338
|
+
const value = result.rows[0]?.value;
|
|
2339
|
+
if (value == null) {
|
|
2340
|
+
return null;
|
|
2341
|
+
}
|
|
2342
|
+
if (value === "true")
|
|
2343
|
+
return true;
|
|
2344
|
+
if (value === "false")
|
|
2345
|
+
return false;
|
|
2346
|
+
syncDebug("mutation recovery marker has an unexpected value \u2014 treating as recovery-required (fail closed)", {
|
|
2347
|
+
value
|
|
2348
|
+
});
|
|
2349
|
+
return true;
|
|
2350
|
+
}
|
|
2351
|
+
async function writeMutationRecoveryRequired(db, registry, required) {
|
|
2352
|
+
await upsertMetaValue(db, registry, MUTATION_RECOVERY_REQUIRED_KEY, required ? "true" : "false");
|
|
2353
|
+
}
|
|
2354
|
+
function writableTableKeys(registry) {
|
|
2355
|
+
return Object.keys(registry).filter((key) => registry[key]?.mode !== "readonly");
|
|
2356
|
+
}
|
|
2357
|
+
async function clearMutationRecoveryMarkerIfSettled(db, registry) {
|
|
2358
|
+
const meta = getLocalMetaTable(registry);
|
|
2359
|
+
const noSendingConditions = writableTableKeys(registry).map((key) => {
|
|
2360
|
+
const journal = getJournalTable(registry, key);
|
|
2361
|
+
return notExists(metaQueryBuilder.select({ one: sql3`1` }).from(journal).where(eq3(journal.status, "sending")));
|
|
2362
|
+
});
|
|
2363
|
+
const query = metaQueryBuilder.update(meta).set({ value: "false" }).where(and3(eq3(meta.key, MUTATION_RECOVERY_REQUIRED_KEY), ...noSendingConditions)).toSQL();
|
|
2364
|
+
const result = await db.query(query.sql, query.params);
|
|
2365
|
+
return { cleared: (result.affectedRows ?? 0) > 0 };
|
|
2366
|
+
}
|
|
2170
2367
|
async function reconcileLocalStoreVersion(args) {
|
|
2171
2368
|
const { db, registry, runtime } = args;
|
|
2172
2369
|
const stored = await readStoredRegistryFingerprint(db, registry);
|
|
@@ -2198,6 +2395,7 @@ async function rebuildReadCacheOrDefer(args, previousFingerprint) {
|
|
|
2198
2395
|
await db.exec(buildWipeLocalStoreSql(registry));
|
|
2199
2396
|
await db.exec(generateLocalSchemaSql(registry));
|
|
2200
2397
|
await writeStoredRegistryFingerprint(db, registry, current);
|
|
2398
|
+
await writeStoredLocalSchemaFingerprint(db, registry, computeLocalSchemaFingerprint(registry));
|
|
2201
2399
|
const event = {
|
|
2202
2400
|
status: "rebuilt",
|
|
2203
2401
|
previousFingerprint,
|
|
@@ -2210,7 +2408,7 @@ async function rebuildReadCacheOrDefer(args, previousFingerprint) {
|
|
|
2210
2408
|
|
|
2211
2409
|
// packages/client/src/mutation.ts
|
|
2212
2410
|
import {
|
|
2213
|
-
and as
|
|
2411
|
+
and as and4,
|
|
2214
2412
|
desc,
|
|
2215
2413
|
eq as eq4,
|
|
2216
2414
|
exists,
|
|
@@ -2222,9 +2420,9 @@ import {
|
|
|
2222
2420
|
isNull,
|
|
2223
2421
|
lt,
|
|
2224
2422
|
ne,
|
|
2225
|
-
notExists,
|
|
2423
|
+
notExists as notExists2,
|
|
2226
2424
|
SQL,
|
|
2227
|
-
sql as
|
|
2425
|
+
sql as sql4
|
|
2228
2426
|
} from "drizzle-orm";
|
|
2229
2427
|
import {
|
|
2230
2428
|
alias,
|
|
@@ -2352,6 +2550,44 @@ function createMutationRuntime(options) {
|
|
|
2352
2550
|
const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
|
|
2353
2551
|
const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
|
|
2354
2552
|
let flushQueue = Promise.resolve();
|
|
2553
|
+
const ownsMetaTable = options.ownsMetaTable ?? true;
|
|
2554
|
+
let recoveryMarkerDirty = false;
|
|
2555
|
+
let markSendingInFlight = 0;
|
|
2556
|
+
const markSendingScope = {
|
|
2557
|
+
enter: () => {
|
|
2558
|
+
markSendingInFlight += 1;
|
|
2559
|
+
},
|
|
2560
|
+
exit: () => {
|
|
2561
|
+
markSendingInFlight -= 1;
|
|
2562
|
+
}
|
|
2563
|
+
};
|
|
2564
|
+
const ensureRecoveryMarker = async () => {
|
|
2565
|
+
if (!ownsMetaTable || recoveryMarkerDirty) {
|
|
2566
|
+
return;
|
|
2567
|
+
}
|
|
2568
|
+
await writeMutationRecoveryRequired(options.db, options.registry, true);
|
|
2569
|
+
recoveryMarkerDirty = true;
|
|
2570
|
+
};
|
|
2571
|
+
const settleRecoveryMarker = async () => {
|
|
2572
|
+
if (!ownsMetaTable) {
|
|
2573
|
+
return;
|
|
2574
|
+
}
|
|
2575
|
+
if (markSendingInFlight > 0) {
|
|
2576
|
+
return;
|
|
2577
|
+
}
|
|
2578
|
+
recoveryMarkerDirty = false;
|
|
2579
|
+
await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);
|
|
2580
|
+
};
|
|
2581
|
+
const buildRecoverSendingQuery = (journal, nowUs) => queryBuilder.update(journal).set({
|
|
2582
|
+
status: "pending",
|
|
2583
|
+
updatedAtUs: nowUs,
|
|
2584
|
+
sentAtUs: null,
|
|
2585
|
+
nextRetryAtUs: nowUs,
|
|
2586
|
+
lastError: null,
|
|
2587
|
+
lastHttpStatus: null,
|
|
2588
|
+
conflictReason: null
|
|
2589
|
+
}).where(eq4(journal.status, "sending")).toSQL();
|
|
2590
|
+
const readAffectedRows = (result) => result.affectedRows ?? 0;
|
|
2355
2591
|
const getTableContext = (table) => {
|
|
2356
2592
|
const context = tableContexts[table];
|
|
2357
2593
|
if (!context) {
|
|
@@ -2628,7 +2864,7 @@ function createMutationRuntime(options) {
|
|
|
2628
2864
|
const conflictedMutationIds = new Set;
|
|
2629
2865
|
let processedCount = 0;
|
|
2630
2866
|
do {
|
|
2631
|
-
const batchResult = await flushBatch(options.db, tableContexts, options.writeUrl, maxMutationAttempts, flushBatchSize, table, resolveAuthToken, options.requestHeaders);
|
|
2867
|
+
const batchResult = await flushBatch(options.db, tableContexts, options.writeUrl, maxMutationAttempts, flushBatchSize, table, resolveAuthToken, options.requestHeaders, ensureRecoveryMarker, markSendingScope);
|
|
2632
2868
|
processedCount = batchResult.processedCount;
|
|
2633
2869
|
for (const context of batchResult.affectedContexts) {
|
|
2634
2870
|
affectedContexts.set(context.key, context);
|
|
@@ -2643,6 +2879,7 @@ function createMutationRuntime(options) {
|
|
|
2643
2879
|
for (const context of affectedContexts.values()) {
|
|
2644
2880
|
await reconcileTable(options.db, context);
|
|
2645
2881
|
}
|
|
2882
|
+
await settleRecoveryMarker();
|
|
2646
2883
|
if (quarantinedMutationIds.size > 0 && options.onQuarantine) {
|
|
2647
2884
|
const details = await readMutationDetailsForContexts(options.db, [...affectedContexts.values()], quarantinedMutationIds);
|
|
2648
2885
|
if (details.length > 0) {
|
|
@@ -2760,7 +2997,7 @@ function createMutationRuntime(options) {
|
|
|
2760
2997
|
nextRetryAtUs: null,
|
|
2761
2998
|
lastHttpStatus: null,
|
|
2762
2999
|
conflictReason: null
|
|
2763
|
-
})));
|
|
3000
|
+
})), ensureRecoveryMarker, markSendingScope);
|
|
2764
3001
|
}
|
|
2765
3002
|
const mutations = prepared.map((row) => ({
|
|
2766
3003
|
tableName: row.sqlTableName,
|
|
@@ -2902,6 +3139,7 @@ function createMutationRuntime(options) {
|
|
|
2902
3139
|
await options.onConflict(details);
|
|
2903
3140
|
}
|
|
2904
3141
|
}
|
|
3142
|
+
await settleRecoveryMarker();
|
|
2905
3143
|
return { acks: [...acksByMutationId.values()] };
|
|
2906
3144
|
},
|
|
2907
3145
|
reconcile: async (table) => {
|
|
@@ -2925,19 +3163,47 @@ function createMutationRuntime(options) {
|
|
|
2925
3163
|
const contexts = filterContexts(tableContexts, table);
|
|
2926
3164
|
const nowUs = nowMicroseconds();
|
|
2927
3165
|
for (const context of contexts) {
|
|
2928
|
-
const
|
|
2929
|
-
const query = queryBuilder.update(journal).set({
|
|
2930
|
-
status: "pending",
|
|
2931
|
-
updatedAtUs: nowUs,
|
|
2932
|
-
sentAtUs: null,
|
|
2933
|
-
nextRetryAtUs: nowUs,
|
|
2934
|
-
lastError: null,
|
|
2935
|
-
lastHttpStatus: null,
|
|
2936
|
-
conflictReason: null
|
|
2937
|
-
}).where(eq4(journal.status, "sending")).toSQL();
|
|
3166
|
+
const query = buildRecoverSendingQuery(context.tables.journal, nowUs);
|
|
2938
3167
|
await options.db.query(query.sql, query.params);
|
|
2939
3168
|
}
|
|
2940
3169
|
},
|
|
3170
|
+
runBootRecovery: async ({ ownsMetaTable: bootOwnsMetaTable, restore }) => {
|
|
3171
|
+
assertValidMutationTransition("sending", "pending");
|
|
3172
|
+
const contexts = filterContexts(tableContexts, undefined);
|
|
3173
|
+
const tablesVisited = contexts.length;
|
|
3174
|
+
if (!bootOwnsMetaTable) {
|
|
3175
|
+
await runtime.recoverSending();
|
|
3176
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
3177
|
+
}
|
|
3178
|
+
if (restore) {
|
|
3179
|
+
await runtime.recoverSending();
|
|
3180
|
+
await runtime.quarantineRecovered();
|
|
3181
|
+
await settleRecoveryMarker();
|
|
3182
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
3183
|
+
}
|
|
3184
|
+
const marker = await readMutationRecoveryRequired(options.db, options.registry);
|
|
3185
|
+
if (marker === false) {
|
|
3186
|
+
return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };
|
|
3187
|
+
}
|
|
3188
|
+
if (marker === null) {
|
|
3189
|
+
await runtime.recoverSending();
|
|
3190
|
+
await writeMutationRecoveryRequired(options.db, options.registry, false);
|
|
3191
|
+
recoveryMarkerDirty = false;
|
|
3192
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
3193
|
+
}
|
|
3194
|
+
const nowUs = nowMicroseconds();
|
|
3195
|
+
let rowsRecovered = 0;
|
|
3196
|
+
await runInTransaction(async () => {
|
|
3197
|
+
for (const context of contexts) {
|
|
3198
|
+
const query = buildRecoverSendingQuery(context.tables.journal, nowUs);
|
|
3199
|
+
const result = await options.db.query(query.sql, query.params);
|
|
3200
|
+
rowsRecovered += readAffectedRows(result);
|
|
3201
|
+
}
|
|
3202
|
+
await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);
|
|
3203
|
+
});
|
|
3204
|
+
recoveryMarkerDirty = false;
|
|
3205
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered };
|
|
3206
|
+
},
|
|
2941
3207
|
quarantineRecovered: async (table) => {
|
|
2942
3208
|
assertValidMutationTransition("pending", "quarantined");
|
|
2943
3209
|
assertValidMutationTransition("sending", "quarantined");
|
|
@@ -2964,17 +3230,19 @@ function createMutationRuntime(options) {
|
|
|
2964
3230
|
failedCount: 0,
|
|
2965
3231
|
quarantinedCount: 0,
|
|
2966
3232
|
conflictedCount: 0,
|
|
3233
|
+
rejectedCount: 0,
|
|
2967
3234
|
ackedCount: 0
|
|
2968
3235
|
};
|
|
2969
3236
|
for (const context of contexts) {
|
|
2970
3237
|
const journal = context.tables.journal;
|
|
2971
|
-
const filteredCount = (status, columnAlias) =>
|
|
3238
|
+
const filteredCount = (status, columnAlias) => sql4`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);
|
|
2972
3239
|
const query = queryBuilder.select({
|
|
2973
3240
|
pendingCount: filteredCount("pending", "pendingCount"),
|
|
2974
3241
|
sendingCount: filteredCount("sending", "sendingCount"),
|
|
2975
3242
|
failedCount: filteredCount("failed", "failedCount"),
|
|
2976
3243
|
quarantinedCount: filteredCount("quarantined", "quarantinedCount"),
|
|
2977
3244
|
conflictedCount: filteredCount("conflicted", "conflictedCount"),
|
|
3245
|
+
rejectedCount: filteredCount("rejected", "rejectedCount"),
|
|
2978
3246
|
ackedCount: filteredCount("acked", "ackedCount")
|
|
2979
3247
|
}).from(journal).toSQL();
|
|
2980
3248
|
const result = await options.db.query(query.sql, query.params);
|
|
@@ -2987,6 +3255,7 @@ function createMutationRuntime(options) {
|
|
|
2987
3255
|
totals.failedCount += row.failedCount;
|
|
2988
3256
|
totals.quarantinedCount += row.quarantinedCount;
|
|
2989
3257
|
totals.conflictedCount += row.conflictedCount;
|
|
3258
|
+
totals.rejectedCount += row.rejectedCount;
|
|
2990
3259
|
totals.ackedCount += row.ackedCount;
|
|
2991
3260
|
}
|
|
2992
3261
|
return totals;
|
|
@@ -3007,19 +3276,19 @@ async function readMutationDetailsForContexts(db, contexts, mutationIds) {
|
|
|
3007
3276
|
for (const context of contexts) {
|
|
3008
3277
|
const journal = context.tables.journal;
|
|
3009
3278
|
const query = queryBuilder.select({
|
|
3010
|
-
mutationId:
|
|
3011
|
-
entityKeyJson:
|
|
3012
|
-
mutationSeq:
|
|
3013
|
-
mutationKind:
|
|
3279
|
+
mutationId: sql4`${journal.mutationId}`.as("mutationId"),
|
|
3280
|
+
entityKeyJson: sql4`${journal.entityKeyJson}`.as("entityKeyJson"),
|
|
3281
|
+
mutationSeq: sql4`${journal.mutationSeq}`.as("mutationSeq"),
|
|
3282
|
+
mutationKind: sql4`${journal.mutationKind}`.as("mutationKind"),
|
|
3014
3283
|
status: journal.status,
|
|
3015
|
-
attemptCount:
|
|
3016
|
-
lastHttpStatus:
|
|
3017
|
-
lastError:
|
|
3018
|
-
conflictReason:
|
|
3019
|
-
nextRetryAtUs:
|
|
3020
|
-
serverUpdatedAtUs:
|
|
3021
|
-
updatedAtUs:
|
|
3022
|
-
registryVersion:
|
|
3284
|
+
attemptCount: sql4`${journal.attemptCount}`.as("attemptCount"),
|
|
3285
|
+
lastHttpStatus: sql4`${journal.lastHttpStatus}`.as("lastHttpStatus"),
|
|
3286
|
+
lastError: sql4`${journal.lastError}`.as("lastError"),
|
|
3287
|
+
conflictReason: sql4`${journal.conflictReason}`.as("conflictReason"),
|
|
3288
|
+
nextRetryAtUs: sql4`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
3289
|
+
serverUpdatedAtUs: sql4`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
3290
|
+
updatedAtUs: sql4`${journal.updatedAtUs}::text`.as("updatedAtUs"),
|
|
3291
|
+
registryVersion: sql4`${journal.registryVersion}`.as("registryVersion")
|
|
3023
3292
|
}).from(journal).orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq)).toSQL();
|
|
3024
3293
|
const result = await db.query(query.sql, query.params);
|
|
3025
3294
|
for (const row of result.rows) {
|
|
@@ -3235,10 +3504,10 @@ async function readLatestMutationStates(db, context, entities) {
|
|
|
3235
3504
|
}
|
|
3236
3505
|
const journal = context.tables.journal;
|
|
3237
3506
|
const query = queryBuilder.selectDistinctOn([journal.entityKeyJson], {
|
|
3238
|
-
entityKeyJson:
|
|
3239
|
-
latestMutationSeq:
|
|
3240
|
-
latestMutationKind:
|
|
3241
|
-
latestMutationStatus:
|
|
3507
|
+
entityKeyJson: sql4`${journal.entityKeyJson}`.as("entityKeyJson"),
|
|
3508
|
+
latestMutationSeq: sql4`${journal.mutationSeq}`.as("latestMutationSeq"),
|
|
3509
|
+
latestMutationKind: sql4`${journal.mutationKind}`.as("latestMutationKind"),
|
|
3510
|
+
latestMutationStatus: sql4`${journal.status}`.as("latestMutationStatus")
|
|
3242
3511
|
}).from(journal).where(inArray2(journal.entityKeyJson, entities.map((entity) => entity.entityKeyJson))).orderBy(journal.entityKeyJson, desc(journal.mutationSeq)).toSQL();
|
|
3243
3512
|
const result = await db.query(query.sql, query.params);
|
|
3244
3513
|
return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
|
|
@@ -3255,8 +3524,8 @@ async function readCurrentRecordStates(db, context, entities) {
|
|
|
3255
3524
|
const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);
|
|
3256
3525
|
const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);
|
|
3257
3526
|
const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey["updatedAtUs"];
|
|
3258
|
-
const syncedLocalUpdated = hasProperty(context, "updatedAtUs") && syncedUpdatedAtColumn ?
|
|
3259
|
-
const query = queryDialect.sqlToQuery(
|
|
3527
|
+
const syncedLocalUpdated = hasProperty(context, "updatedAtUs") && syncedUpdatedAtColumn ? sql4`${syncedUpdatedAtColumn}::text AS "localUpdatedAtUs"` : sql4`'0' AS "localUpdatedAtUs"`;
|
|
3528
|
+
const query = queryDialect.sqlToQuery(sql4`
|
|
3260
3529
|
WITH ${inputCte},
|
|
3261
3530
|
overlay_rows AS (
|
|
3262
3531
|
SELECT
|
|
@@ -3330,9 +3599,9 @@ async function upsertOverlayRecordsBulk(db, context, rows) {
|
|
|
3330
3599
|
localUpdatedAtUs: row.localUpdatedAtUs
|
|
3331
3600
|
}));
|
|
3332
3601
|
const excludedSet = Object.fromEntries([
|
|
3333
|
-
...context.columns.map(({ propertyKey, column }) => [propertyKey,
|
|
3334
|
-
["overlayKind",
|
|
3335
|
-
["localUpdatedAtUs",
|
|
3602
|
+
...context.columns.map(({ propertyKey, column }) => [propertyKey, sql4`excluded.${sql4.identifier(column.name)}`]),
|
|
3603
|
+
["overlayKind", sql4`excluded.${sql4.identifier(overlay.overlayKind.name)}`],
|
|
3604
|
+
["localUpdatedAtUs", sql4`excluded.${sql4.identifier(overlay.localUpdatedAtUs.name)}`]
|
|
3336
3605
|
]);
|
|
3337
3606
|
const query = queryBuilder.insert(overlay).values(values).onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet }).toSQL();
|
|
3338
3607
|
await db.query(query.sql, query.params);
|
|
@@ -3341,16 +3610,16 @@ function buildEntityInputCte(context, entities) {
|
|
|
3341
3610
|
const columnNames = ["entity_key_json", ...context.pkColumnNames];
|
|
3342
3611
|
const tuples = entities.map((entity) => {
|
|
3343
3612
|
const values = [
|
|
3344
|
-
|
|
3613
|
+
sql4`${entity.entityKeyJson}`,
|
|
3345
3614
|
...context.pkColumnNames.map((columnName) => {
|
|
3346
3615
|
const columnEntry = context.columns.find(({ column }) => column.name === columnName);
|
|
3347
3616
|
const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : "";
|
|
3348
|
-
return castSuffix ?
|
|
3617
|
+
return castSuffix ? sql4`${entity.entityKey[columnName]}${sql4.raw(castSuffix)}` : sql4`${entity.entityKey[columnName]}`;
|
|
3349
3618
|
})
|
|
3350
3619
|
];
|
|
3351
|
-
return
|
|
3620
|
+
return sql4`(${sql4.join(values, sql4`, `)})`;
|
|
3352
3621
|
});
|
|
3353
|
-
return
|
|
3622
|
+
return sql4`input_entities (${sql4.join(columnNames.map((columnName) => sql4.identifier(columnName)), sql4`, `)}) AS (VALUES ${sql4.join(tuples, sql4`, `)})`;
|
|
3354
3623
|
}
|
|
3355
3624
|
function resolveInputCastSuffix(columnType) {
|
|
3356
3625
|
switch (columnType) {
|
|
@@ -3373,49 +3642,49 @@ function resolveInputCastSuffix(columnType) {
|
|
|
3373
3642
|
}
|
|
3374
3643
|
}
|
|
3375
3644
|
function buildProjectedSelectColumns(context, columnsByPropertyKey) {
|
|
3376
|
-
return
|
|
3645
|
+
return sql4.join(context.columns.map(({ propertyKey, column }) => {
|
|
3377
3646
|
const target = columnsByPropertyKey[propertyKey];
|
|
3378
3647
|
if (!target) {
|
|
3379
3648
|
throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);
|
|
3380
3649
|
}
|
|
3381
3650
|
if (column.columnType === "PgBigInt64" || column.columnType === "PgBigInt53") {
|
|
3382
|
-
return
|
|
3651
|
+
return sql4`${target}::text AS ${sql4.identifier(propertyKey)}`;
|
|
3383
3652
|
}
|
|
3384
|
-
return
|
|
3385
|
-
}),
|
|
3653
|
+
return sql4`${target} AS ${sql4.identifier(propertyKey)}`;
|
|
3654
|
+
}), sql4`, `);
|
|
3386
3655
|
}
|
|
3387
3656
|
function buildEntityInputJoin(pkColumnNames, pkColumns) {
|
|
3388
|
-
return
|
|
3657
|
+
return sql4.join(pkColumnNames.map((columnName, index2) => sql4`${pkColumns[index2]} = input.${sql4.identifier(columnName)}`), sql4` AND `);
|
|
3389
3658
|
}
|
|
3390
3659
|
function buildResolvedBaseServerVersion(context) {
|
|
3391
3660
|
const journal = context.tables.journal;
|
|
3392
3661
|
const synced = context.tables.synced;
|
|
3393
3662
|
const pred = alias(journal, "pred");
|
|
3394
|
-
const predecessor = queryBuilder.select({ value:
|
|
3663
|
+
const predecessor = queryBuilder.select({ value: sql4`MAX(${pred.serverUpdatedAtUs})` }).from(pred).where(and4(eq4(pred.entityKeyJson, journal.entityKeyJson), lt(pred.mutationSeq, journal.mutationSeq), eq4(pred.status, "acked")));
|
|
3395
3664
|
if (!context.syncedServerVersionColumn) {
|
|
3396
|
-
return
|
|
3665
|
+
return sql4`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;
|
|
3397
3666
|
}
|
|
3398
|
-
const syncedFallback = queryBuilder.select({ value:
|
|
3399
|
-
return
|
|
3667
|
+
const syncedFallback = queryBuilder.select({ value: sql4`${context.syncedServerVersionColumn}` }).from(synced).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.syncedPkColumns[index2], journal[columnName]))));
|
|
3668
|
+
return sql4`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;
|
|
3400
3669
|
}
|
|
3401
3670
|
function buildPendingRowsProjection(context) {
|
|
3402
3671
|
const journal = context.tables.journal;
|
|
3403
3672
|
return {
|
|
3404
|
-
tableKey:
|
|
3405
|
-
mutationId:
|
|
3406
|
-
entityKeyJson:
|
|
3407
|
-
mutationSeq:
|
|
3408
|
-
mutationKind:
|
|
3673
|
+
tableKey: sql4`${context.key}`.as("tableKey"),
|
|
3674
|
+
mutationId: sql4`${journal.mutationId}`.as("mutationId"),
|
|
3675
|
+
entityKeyJson: sql4`${journal.entityKeyJson}`.as("entityKeyJson"),
|
|
3676
|
+
mutationSeq: sql4`${journal.mutationSeq}`.as("mutationSeq"),
|
|
3677
|
+
mutationKind: sql4`${journal.mutationKind}`.as("mutationKind"),
|
|
3409
3678
|
status: journal.status,
|
|
3410
|
-
payloadJson:
|
|
3411
|
-
attemptCount:
|
|
3412
|
-
lastHttpStatus:
|
|
3413
|
-
lastError:
|
|
3414
|
-
conflictReason:
|
|
3415
|
-
nextRetryAtUs:
|
|
3416
|
-
serverUpdatedAtUs:
|
|
3679
|
+
payloadJson: sql4`${journal.payloadJson}`.as("payloadJson"),
|
|
3680
|
+
attemptCount: sql4`${journal.attemptCount}`.as("attemptCount"),
|
|
3681
|
+
lastHttpStatus: sql4`${journal.lastHttpStatus}`.as("lastHttpStatus"),
|
|
3682
|
+
lastError: sql4`${journal.lastError}`.as("lastError"),
|
|
3683
|
+
conflictReason: sql4`${journal.conflictReason}`.as("conflictReason"),
|
|
3684
|
+
nextRetryAtUs: sql4`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
3685
|
+
serverUpdatedAtUs: sql4`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
3417
3686
|
baseServerVersion: buildResolvedBaseServerVersion(context).as("baseServerVersion"),
|
|
3418
|
-
enqueuedAtUs:
|
|
3687
|
+
enqueuedAtUs: sql4`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs")
|
|
3419
3688
|
};
|
|
3420
3689
|
}
|
|
3421
3690
|
async function readPendingBatchRows(db, contexts, nowUs, batchSize) {
|
|
@@ -3425,9 +3694,9 @@ async function readPendingBatchRows(db, contexts, nowUs, batchSize) {
|
|
|
3425
3694
|
const branches = contexts.map((context) => {
|
|
3426
3695
|
const journal = context.tables.journal;
|
|
3427
3696
|
const earlier = alias(journal, "earlier");
|
|
3428
|
-
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(
|
|
3697
|
+
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and4(inArray2(journal.status, ["pending", "failed"]), sql4`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`, sql4`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`, notExists2(queryBuilder.select({ one: sql4`1` }).from(earlier).where(and4(eq4(earlier.entityKeyJson, journal.entityKeyJson), lt(earlier.mutationSeq, journal.mutationSeq), inArray2(earlier.status, ["pending", "failed", "sending", "quarantined"]))))));
|
|
3429
3698
|
});
|
|
3430
|
-
const query = queryDialect.sqlToQuery(
|
|
3699
|
+
const query = queryDialect.sqlToQuery(sql4`SELECT * FROM (${sql4.join(branches, sql4` UNION ALL `)}) AS pending ORDER BY pending."enqueuedAtUs"::bigint ASC, pending."mutationSeq" ASC LIMIT ${batchSize}`);
|
|
3431
3700
|
const result = await db.query(query.sql, query.params);
|
|
3432
3701
|
return result.rows;
|
|
3433
3702
|
}
|
|
@@ -3437,13 +3706,13 @@ async function readUnitPendingRows(db, contexts, unitId) {
|
|
|
3437
3706
|
}
|
|
3438
3707
|
const branches = contexts.map((context) => {
|
|
3439
3708
|
const journal = context.tables.journal;
|
|
3440
|
-
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(
|
|
3709
|
+
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and4(eq4(journal.writeUnit, unitId), inArray2(journal.status, ["pending", "failed"])));
|
|
3441
3710
|
});
|
|
3442
|
-
const query = queryDialect.sqlToQuery(
|
|
3711
|
+
const query = queryDialect.sqlToQuery(sql4`SELECT * FROM (${sql4.join(branches, sql4` UNION ALL `)}) AS unit ORDER BY unit."mutationSeq" ASC`);
|
|
3443
3712
|
const result = await db.query(query.sql, query.params);
|
|
3444
3713
|
return result.rows;
|
|
3445
3714
|
}
|
|
3446
|
-
async function flushBatch(db, tableContexts, batchWriteUrl, maxAttempts, batchSize, tableFilter, getAuthToken, requestHeaders) {
|
|
3715
|
+
async function flushBatch(db, tableContexts, batchWriteUrl, maxAttempts, batchSize, tableFilter, getAuthToken, requestHeaders, ensureRecoveryMarker, markSendingScope) {
|
|
3447
3716
|
const contexts = filterContexts(tableContexts, tableFilter);
|
|
3448
3717
|
const nowUs = nowMicroseconds();
|
|
3449
3718
|
const quarantinedMutationIds = [];
|
|
@@ -3498,7 +3767,7 @@ async function flushBatch(db, tableContexts, batchWriteUrl, maxAttempts, batchSi
|
|
|
3498
3767
|
nextRetryAtUs: null,
|
|
3499
3768
|
lastHttpStatus: null,
|
|
3500
3769
|
conflictReason: null
|
|
3501
|
-
})));
|
|
3770
|
+
})), ensureRecoveryMarker, markSendingScope);
|
|
3502
3771
|
}
|
|
3503
3772
|
const mutations = pending.map((row) => {
|
|
3504
3773
|
return {
|
|
@@ -3736,7 +4005,7 @@ async function discardTerminalEntity(db, context, entityKey, entityKeyJson, term
|
|
|
3736
4005
|
await db.exec("BEGIN");
|
|
3737
4006
|
try {
|
|
3738
4007
|
const journal = context.tables.journal;
|
|
3739
|
-
const clearQuery = queryBuilder.delete(journal).where(
|
|
4008
|
+
const clearQuery = queryBuilder.delete(journal).where(and4(eq4(journal.status, terminalStatus), eq4(journal.entityKeyJson, entityKeyJson))).toSQL();
|
|
3740
4009
|
await db.query(clearQuery.sql, clearQuery.params);
|
|
3741
4010
|
const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);
|
|
3742
4011
|
await db.query(overlayQuery.sql, overlayQuery.params);
|
|
@@ -3749,8 +4018,8 @@ async function discardTerminalEntity(db, context, entityKey, entityKeyJson, term
|
|
|
3749
4018
|
function buildOverlayDiscardQuery(context, entityKey, entityKeyJson, owedStatuses) {
|
|
3750
4019
|
const overlay = context.tables.overlay;
|
|
3751
4020
|
const journal = context.tables.journal;
|
|
3752
|
-
const owed = queryBuilder.select({ one:
|
|
3753
|
-
return queryBuilder.delete(overlay).where(
|
|
4021
|
+
const owed = queryBuilder.select({ one: sql4`1` }).from(journal).where(owedStatuses ? and4(eq4(journal.entityKeyJson, entityKeyJson), inArray2(journal.status, owedStatuses)) : eq4(journal.entityKeyJson, entityKeyJson));
|
|
4022
|
+
return queryBuilder.delete(overlay).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.overlayPkColumns[index2], entityKey[columnName])), notExists2(owed))).toSQL();
|
|
3754
4023
|
}
|
|
3755
4024
|
async function discardOverlayForSettledEntity(db, context, entityKey, entityKeyJson) {
|
|
3756
4025
|
const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
|
|
@@ -3762,7 +4031,7 @@ async function reconcileTable(db, context) {
|
|
|
3762
4031
|
const synced = context.tables.synced;
|
|
3763
4032
|
let idleProbe = context.reconcileIdleProbe;
|
|
3764
4033
|
if (!idleProbe) {
|
|
3765
|
-
const probeQuery = queryDialect.sqlToQuery(
|
|
4034
|
+
const probeQuery = queryDialect.sqlToQuery(sql4`SELECT ${exists(queryBuilder.select({ one: sql4`1` }).from(journal).where(inArray2(journal.status, ["acked", "conflicted"])))} AS "hasWork"`);
|
|
3766
4035
|
idleProbe = { sql: probeQuery.sql, params: probeQuery.params };
|
|
3767
4036
|
context.reconcileIdleProbe = idleProbe;
|
|
3768
4037
|
}
|
|
@@ -3773,28 +4042,28 @@ async function reconcileTable(db, context) {
|
|
|
3773
4042
|
await db.exec("BEGIN");
|
|
3774
4043
|
try {
|
|
3775
4044
|
const resolver = alias(journal, "resolver");
|
|
3776
|
-
const retireQuery = queryBuilder.delete(journal).where(
|
|
4045
|
+
const retireQuery = queryBuilder.delete(journal).where(and4(eq4(journal.status, "conflicted"), exists(queryBuilder.select({ one: sql4`1` }).from(resolver).where(and4(eq4(resolver.entityKeyJson, journal.entityKeyJson), gt(resolver.mutationSeq, journal.mutationSeq), eq4(resolver.status, "acked")))))).toSQL();
|
|
3777
4046
|
await db.query(retireQuery.sql, retireQuery.params);
|
|
3778
|
-
const blindRetireQuery = queryBuilder.delete(journal).where(
|
|
4047
|
+
const blindRetireQuery = queryBuilder.delete(journal).where(and4(eq4(journal.status, "acked"), eq4(journal.writeMode, "pessimistic-blind"))).toSQL();
|
|
3779
4048
|
await db.query(blindRetireQuery.sql, blindRetireQuery.params);
|
|
3780
|
-
const barrier =
|
|
4049
|
+
const barrier = sql4.raw(buildOverlayResolutionBarrier2(context.entry, {
|
|
3781
4050
|
journalAlias: quoteIdentifier5(getTableConfig6(journal).name),
|
|
3782
4051
|
syncedAlias: quoteIdentifier5(getTableConfig6(synced).name)
|
|
3783
4052
|
}));
|
|
3784
|
-
const clearedJournal = queryBuilder.$with("cleared_journal").as(queryBuilder.delete(journal).where(
|
|
4053
|
+
const clearedJournal = queryBuilder.$with("cleared_journal").as(queryBuilder.delete(journal).where(and4(eq4(journal.status, "acked"), isNotNull(journal.serverUpdatedAtUs), ne(journal.mutationKind, "delete"), exists(queryBuilder.select({ one: sql4`1` }).from(synced).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.syncedPkColumns[index2], journal[columnName])), barrier))))).returning(Object.fromEntries([
|
|
3785
4054
|
["entity_key_json", journal.entityKeyJson],
|
|
3786
4055
|
...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]])
|
|
3787
4056
|
])));
|
|
3788
4057
|
const clearedJournalColumns = clearedJournal;
|
|
3789
|
-
const ackedClearQuery = queryBuilder.with(clearedJournal).delete(overlay).where(exists(queryBuilder.select({ one:
|
|
4058
|
+
const ackedClearQuery = queryBuilder.with(clearedJournal).delete(overlay).where(exists(queryBuilder.select({ one: sql4`1` }).from(clearedJournal).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.overlayPkColumns[index2], clearedJournalColumns[columnName])), notExists2(queryBuilder.select({ one: sql4`1` }).from(journal).where(and4(eq4(journal.entityKeyJson, clearedJournalColumns["entity_key_json"]), inArray2(journal.status, ["pending", "sending", "failed"])))))))).toSQL();
|
|
3790
4059
|
await db.query(ackedClearQuery.sql, ackedClearQuery.params);
|
|
3791
4060
|
const clearableEntities = queryBuilder.$with("clearable_entities").as(queryBuilder.selectDistinct(Object.fromEntries([
|
|
3792
4061
|
["entity_key_json", journal.entityKeyJson],
|
|
3793
4062
|
...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]])
|
|
3794
|
-
])).from(journal).leftJoin(synced,
|
|
4063
|
+
])).from(journal).leftJoin(synced, and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.syncedPkColumns[index2], journal[columnName])))).where(and4(eq4(journal.status, "acked"), eq4(journal.mutationKind, "delete"), isNull(context.syncedPkColumns[0]))));
|
|
3795
4064
|
const clearableEntityColumns = clearableEntities;
|
|
3796
|
-
const deletedOverlay = queryBuilder.$with("deleted_overlay").as(queryBuilder.delete(overlay).where(exists(queryBuilder.select({ one:
|
|
3797
|
-
const deleteClearQuery = queryBuilder.with(clearableEntities, deletedOverlay).delete(journal).where(
|
|
4065
|
+
const deletedOverlay = queryBuilder.$with("deleted_overlay").as(queryBuilder.delete(overlay).where(exists(queryBuilder.select({ one: sql4`1` }).from(clearableEntities).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.overlayPkColumns[index2], clearableEntityColumns[columnName])))))));
|
|
4066
|
+
const deleteClearQuery = queryBuilder.with(clearableEntities, deletedOverlay).delete(journal).where(and4(eq4(journal.status, "acked"), eq4(journal.mutationKind, "delete"), exists(queryBuilder.select({ one: sql4`1` }).from(clearableEntities).where(and4(...context.pkColumnNames.map((columnName) => eq4(journal[columnName], clearableEntityColumns[columnName]))))))).toSQL();
|
|
3798
4067
|
await db.query(deleteClearQuery.sql, deleteClearQuery.params);
|
|
3799
4068
|
await db.exec("COMMIT");
|
|
3800
4069
|
} catch (error) {
|
|
@@ -3809,26 +4078,40 @@ function buildRequestHeaders(bearerToken, requestHeaders) {
|
|
|
3809
4078
|
...bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}
|
|
3810
4079
|
};
|
|
3811
4080
|
}
|
|
3812
|
-
async function applyMutationStatusUpdates(db, context, updates) {
|
|
4081
|
+
async function applyMutationStatusUpdates(db, context, updates, onBeforeMarkSending, markSendingScope) {
|
|
3813
4082
|
if (updates.length === 0) {
|
|
3814
4083
|
return;
|
|
3815
4084
|
}
|
|
4085
|
+
const marksSending = updates.some((update) => update.status === "sending");
|
|
4086
|
+
if (marksSending)
|
|
4087
|
+
markSendingScope?.enter();
|
|
4088
|
+
try {
|
|
4089
|
+
if (onBeforeMarkSending && marksSending) {
|
|
4090
|
+
await onBeforeMarkSending();
|
|
4091
|
+
}
|
|
4092
|
+
await execMutationStatusUpdates(db, context, updates);
|
|
4093
|
+
} finally {
|
|
4094
|
+
if (marksSending)
|
|
4095
|
+
markSendingScope?.exit();
|
|
4096
|
+
}
|
|
4097
|
+
}
|
|
4098
|
+
async function execMutationStatusUpdates(db, context, updates) {
|
|
3816
4099
|
const journal = context.tables.journal;
|
|
3817
|
-
const tuples = updates.map((update) =>
|
|
3818
|
-
const updatesTable =
|
|
4100
|
+
const tuples = updates.map((update) => sql4`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${update.sentAtUs ?? null}::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${update.replaceAckedAtUs ?? false}::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${update.baseServerVersion ?? null}::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${update.nextRetryAtUs ?? null}::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`);
|
|
4101
|
+
const updatesTable = sql4`(VALUES ${sql4.join(tuples, sql4`, `)}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;
|
|
3819
4102
|
const query = queryBuilder.update(journal).set({
|
|
3820
|
-
status:
|
|
3821
|
-
attemptCount:
|
|
3822
|
-
updatedAtUs:
|
|
3823
|
-
sentAtUs:
|
|
3824
|
-
ackedAtUs:
|
|
3825
|
-
serverUpdatedAtUs:
|
|
3826
|
-
baseServerVersion:
|
|
3827
|
-
lastError:
|
|
3828
|
-
nextRetryAtUs:
|
|
3829
|
-
lastHttpStatus:
|
|
3830
|
-
conflictReason:
|
|
3831
|
-
}).from(updatesTable).where(eq4(journal.mutationId,
|
|
4103
|
+
status: sql4`updates.status`,
|
|
4104
|
+
attemptCount: sql4`updates.attempt_count`,
|
|
4105
|
+
updatedAtUs: sql4`updates.updated_at_us::bigint`,
|
|
4106
|
+
sentAtUs: sql4`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,
|
|
4107
|
+
ackedAtUs: sql4`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,
|
|
4108
|
+
serverUpdatedAtUs: sql4`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,
|
|
4109
|
+
baseServerVersion: sql4`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,
|
|
4110
|
+
lastError: sql4`updates.last_error`,
|
|
4111
|
+
nextRetryAtUs: sql4`updates.next_retry_at_us::bigint`,
|
|
4112
|
+
lastHttpStatus: sql4`updates.last_http_status`,
|
|
4113
|
+
conflictReason: sql4`updates.conflict_reason`
|
|
4114
|
+
}).from(updatesTable).where(eq4(journal.mutationId, sql4`updates.mutation_id::uuid`)).toSQL();
|
|
3832
4115
|
await db.query(query.sql, query.params);
|
|
3833
4116
|
}
|
|
3834
4117
|
function qualifyLocalIdentifier(schemaName, tableName) {
|
|
@@ -3881,6 +4164,141 @@ function parseBatchRejections(body) {
|
|
|
3881
4164
|
return rejections && rejections.length > 0 ? rejections : null;
|
|
3882
4165
|
}
|
|
3883
4166
|
|
|
4167
|
+
// packages/client/src/mutations-api.ts
|
|
4168
|
+
import { and as and5, desc as desc2, eq as eq5, inArray as inArray3, sql as sql5 } from "drizzle-orm";
|
|
4169
|
+
import { drizzle as drizzle4 } from "drizzle-orm/pglite";
|
|
4170
|
+
var queryBuilderInstance;
|
|
4171
|
+
function queryBuilder2() {
|
|
4172
|
+
return queryBuilderInstance ??= drizzle4.mock();
|
|
4173
|
+
}
|
|
4174
|
+
var STATUS_TO_SUMMARY_KEY = {
|
|
4175
|
+
pending: "pendingCount",
|
|
4176
|
+
sending: "sendingCount",
|
|
4177
|
+
acked: "ackedCount",
|
|
4178
|
+
failed: "failedCount",
|
|
4179
|
+
quarantined: "quarantinedCount",
|
|
4180
|
+
conflicted: "conflictedCount",
|
|
4181
|
+
rejected: "rejectedCount"
|
|
4182
|
+
};
|
|
4183
|
+
function emptySummary() {
|
|
4184
|
+
return {
|
|
4185
|
+
pendingCount: 0,
|
|
4186
|
+
sendingCount: 0,
|
|
4187
|
+
ackedCount: 0,
|
|
4188
|
+
failedCount: 0,
|
|
4189
|
+
rejectedCount: 0,
|
|
4190
|
+
conflictedCount: 0,
|
|
4191
|
+
quarantinedCount: 0,
|
|
4192
|
+
unsettledCount: 0,
|
|
4193
|
+
settledCount: 0
|
|
4194
|
+
};
|
|
4195
|
+
}
|
|
4196
|
+
function foldSummary(rows) {
|
|
4197
|
+
const summary = emptySummary();
|
|
4198
|
+
for (const row of rows) {
|
|
4199
|
+
const key = STATUS_TO_SUMMARY_KEY[row.status];
|
|
4200
|
+
if (key) {
|
|
4201
|
+
summary[key] = Number(row.count);
|
|
4202
|
+
}
|
|
4203
|
+
}
|
|
4204
|
+
summary.unsettledCount = summary.pendingCount + summary.sendingCount + summary.failedCount + summary.conflictedCount + summary.quarantinedCount;
|
|
4205
|
+
summary.settledCount = summary.ackedCount + summary.rejectedCount;
|
|
4206
|
+
return summary;
|
|
4207
|
+
}
|
|
4208
|
+
function mapDetailRow(row) {
|
|
4209
|
+
return {
|
|
4210
|
+
tableName: row.tableName,
|
|
4211
|
+
entityKey: JSON.parse(row.entityKeyJson),
|
|
4212
|
+
mutationId: row.mutationId,
|
|
4213
|
+
mutationSeq: Number(row.mutationSeq),
|
|
4214
|
+
mutationKind: row.mutationKind,
|
|
4215
|
+
status: row.status,
|
|
4216
|
+
attemptCount: Number(row.attemptCount),
|
|
4217
|
+
lastHttpStatus: row.lastHttpStatus,
|
|
4218
|
+
lastError: row.lastError,
|
|
4219
|
+
conflictReason: row.conflictReason,
|
|
4220
|
+
nextRetryAtUs: row.nextRetryAtUs,
|
|
4221
|
+
serverUpdatedAtUs: row.serverUpdatedAtUs,
|
|
4222
|
+
updatedAtUs: row.updatedAtUs,
|
|
4223
|
+
registryVersion: row.registryVersion
|
|
4224
|
+
};
|
|
4225
|
+
}
|
|
4226
|
+
function hasWritableTable(registry) {
|
|
4227
|
+
return Object.values(registry).some((entry) => entry.mode !== "readonly" && entry.clientProjection?.journalTable);
|
|
4228
|
+
}
|
|
4229
|
+
function buildSummarySql(registry) {
|
|
4230
|
+
const view = getAllMutationsView(registry);
|
|
4231
|
+
return queryBuilder2().select({ status: view.status, count: sql5`count(*)::int`.as("count") }).from(view).groupBy(view.status).toSQL();
|
|
4232
|
+
}
|
|
4233
|
+
function buildDetailSql(registry, options) {
|
|
4234
|
+
const view = getAllMutationsView(registry);
|
|
4235
|
+
const conditions = [];
|
|
4236
|
+
if (options?.table != null) {
|
|
4237
|
+
conditions.push(eq5(view.tableKey, options.table));
|
|
4238
|
+
}
|
|
4239
|
+
if (options?.entityKey != null) {
|
|
4240
|
+
conditions.push(eq5(view.entityKeyJson, JSON.stringify(options.entityKey)));
|
|
4241
|
+
}
|
|
4242
|
+
if (options?.statuses != null && options.statuses.length > 0) {
|
|
4243
|
+
conditions.push(inArray3(view.status, options.statuses));
|
|
4244
|
+
}
|
|
4245
|
+
const base = queryBuilder2().select({
|
|
4246
|
+
tableName: sql5`${view.tableKey}`.as("tableName"),
|
|
4247
|
+
entityKeyJson: sql5`${view.entityKeyJson}`.as("entityKeyJson"),
|
|
4248
|
+
mutationId: sql5`${view.mutationId}`.as("mutationId"),
|
|
4249
|
+
mutationSeq: sql5`${view.mutationSeq}`.as("mutationSeq"),
|
|
4250
|
+
mutationKind: sql5`${view.mutationKind}`.as("mutationKind"),
|
|
4251
|
+
status: sql5`${view.status}`.as("status"),
|
|
4252
|
+
attemptCount: sql5`${view.attemptCount}`.as("attemptCount"),
|
|
4253
|
+
lastHttpStatus: sql5`${view.lastHttpStatus}`.as("lastHttpStatus"),
|
|
4254
|
+
lastError: sql5`${view.lastError}`.as("lastError"),
|
|
4255
|
+
conflictReason: sql5`${view.conflictReason}`.as("conflictReason"),
|
|
4256
|
+
nextRetryAtUs: sql5`${view.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
4257
|
+
serverUpdatedAtUs: sql5`${view.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
4258
|
+
updatedAtUs: sql5`${view.updatedAtUs}::text`.as("updatedAtUs"),
|
|
4259
|
+
registryVersion: sql5`${view.registryVersion}`.as("registryVersion")
|
|
4260
|
+
}).from(view).where(conditions.length > 0 ? and5(...conditions) : undefined).orderBy(desc2(view.enqueuedAtUs), desc2(view.mutationId));
|
|
4261
|
+
return (options?.limit != null ? base.limit(options.limit) : base).toSQL();
|
|
4262
|
+
}
|
|
4263
|
+
function createMutationsApi(deps) {
|
|
4264
|
+
const { registry, subscribeLiveRows, query } = deps;
|
|
4265
|
+
const writable = hasWritableTable(registry);
|
|
4266
|
+
return {
|
|
4267
|
+
summary: async () => {
|
|
4268
|
+
if (!writable) {
|
|
4269
|
+
return emptySummary();
|
|
4270
|
+
}
|
|
4271
|
+
const built = buildSummarySql(registry);
|
|
4272
|
+
const { rows } = await query(built.sql, built.params);
|
|
4273
|
+
return foldSummary(rows);
|
|
4274
|
+
},
|
|
4275
|
+
subscribeSummary: async (listener) => {
|
|
4276
|
+
if (!writable) {
|
|
4277
|
+
return { initial: emptySummary(), unsubscribe: () => {} };
|
|
4278
|
+
}
|
|
4279
|
+
const built = buildSummarySql(registry);
|
|
4280
|
+
const subscription = await subscribeLiveRows({ sql: built.sql, params: built.params }, (rows) => listener(foldSummary(rows)));
|
|
4281
|
+
return { initial: foldSummary(subscription.initialRows), unsubscribe: subscription.unsubscribe };
|
|
4282
|
+
},
|
|
4283
|
+
list: async (options) => {
|
|
4284
|
+
if (!writable) {
|
|
4285
|
+
return [];
|
|
4286
|
+
}
|
|
4287
|
+
const built = buildDetailSql(registry, options);
|
|
4288
|
+
const { rows } = await query(built.sql, built.params);
|
|
4289
|
+
return rows.map(mapDetailRow);
|
|
4290
|
+
},
|
|
4291
|
+
subscribe: async (options, listener) => {
|
|
4292
|
+
if (!writable) {
|
|
4293
|
+
return { initial: [], unsubscribe: () => {} };
|
|
4294
|
+
}
|
|
4295
|
+
const built = buildDetailSql(registry, options);
|
|
4296
|
+
const subscription = await subscribeLiveRows({ sql: built.sql, params: built.params }, (rows) => listener(rows.map(mapDetailRow)));
|
|
4297
|
+
return { initial: subscription.initialRows.map(mapDetailRow), unsubscribe: subscription.unsubscribe };
|
|
4298
|
+
}
|
|
4299
|
+
};
|
|
4300
|
+
}
|
|
4301
|
+
|
|
3884
4302
|
// packages/client/src/sync-auth.ts
|
|
3885
4303
|
function buildShapeHeaders(input) {
|
|
3886
4304
|
const headers = { ...input.requestHeaders ?? {} };
|
|
@@ -4123,7 +4541,7 @@ function groupSubscriptionKey(spec) {
|
|
|
4123
4541
|
// packages/client/src/sync/index.ts
|
|
4124
4542
|
import { isChangeMessage, isControlMessage } from "@electric-sql/client";
|
|
4125
4543
|
import { MultiShapeStream } from "@electric-sql/experimental";
|
|
4126
|
-
import { sql as
|
|
4544
|
+
import { sql as sql6 } from "drizzle-orm";
|
|
4127
4545
|
import { getTableConfig as getTableConfig7 } from "drizzle-orm/pg-core";
|
|
4128
4546
|
import { classifyTableApplyStrategy } from "@pgxsinkit/contracts";
|
|
4129
4547
|
|
|
@@ -4434,7 +4852,7 @@ function foldKey(key, ops, folded) {
|
|
|
4434
4852
|
}
|
|
4435
4853
|
|
|
4436
4854
|
// packages/client/src/sync/subscription-state.ts
|
|
4437
|
-
import { eq as
|
|
4855
|
+
import { eq as eq6 } from "drizzle-orm";
|
|
4438
4856
|
import { quoteIdentifier as quoteIdentifier6 } from "@pgxsinkit/contracts";
|
|
4439
4857
|
async function getSubscriptionState({
|
|
4440
4858
|
pg,
|
|
@@ -4442,7 +4860,7 @@ async function getSubscriptionState({
|
|
|
4442
4860
|
subscriptionKey
|
|
4443
4861
|
}) {
|
|
4444
4862
|
const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
|
|
4445
|
-
const rows = await drizzleOverPg(pg).select().from(subscriptionsMetadata).where(
|
|
4863
|
+
const rows = await drizzleOverPg(pg).select().from(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
|
|
4446
4864
|
if (rows.length === 0) {
|
|
4447
4865
|
return null;
|
|
4448
4866
|
}
|
|
@@ -4488,7 +4906,7 @@ async function updateSubscriptionState({
|
|
|
4488
4906
|
}
|
|
4489
4907
|
async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }) {
|
|
4490
4908
|
const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
|
|
4491
|
-
await drizzleOverPg(pg).delete(subscriptionsMetadata).where(
|
|
4909
|
+
await drizzleOverPg(pg).delete(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
|
|
4492
4910
|
}
|
|
4493
4911
|
async function migrateSubscriptionMetadataTables({
|
|
4494
4912
|
pg,
|
|
@@ -4704,7 +5122,7 @@ async function createSyncEngine(pg, options) {
|
|
|
4704
5122
|
if (shape.onMustRefetch) {
|
|
4705
5123
|
await shape.onMustRefetch(drizzleOverPg(tx));
|
|
4706
5124
|
} else {
|
|
4707
|
-
await drizzleOverPg(tx).execute(
|
|
5125
|
+
await drizzleOverPg(tx).execute(sql6`TRUNCATE ${target.table}`);
|
|
4708
5126
|
}
|
|
4709
5127
|
await clearShapeTags({ pg: tx, metadataSchema, shapeTable });
|
|
4710
5128
|
}
|
|
@@ -5628,8 +6046,13 @@ async function attachSyncClient(options) {
|
|
|
5628
6046
|
const detachError = () => new Error("[pgxsinkit] client detached \u2014 the tab released its worker attachment");
|
|
5629
6047
|
const status = { phase: "booting", isRunning: false };
|
|
5630
6048
|
let resolveReady;
|
|
5631
|
-
|
|
6049
|
+
let rejectReady;
|
|
6050
|
+
const ready = new Promise((resolve, reject) => {
|
|
5632
6051
|
resolveReady = resolve;
|
|
6052
|
+
rejectReady = reject;
|
|
6053
|
+
});
|
|
6054
|
+
ready.catch(() => {
|
|
6055
|
+
return;
|
|
5633
6056
|
});
|
|
5634
6057
|
let readyResolved = false;
|
|
5635
6058
|
const readyGroups = new Set;
|
|
@@ -5674,6 +6097,20 @@ async function attachSyncClient(options) {
|
|
|
5674
6097
|
markGroupReady(event.groupKey);
|
|
5675
6098
|
break;
|
|
5676
6099
|
}
|
|
6100
|
+
case "milestone": {
|
|
6101
|
+
if (event.stage === "writeReady")
|
|
6102
|
+
settleWriteReady();
|
|
6103
|
+
else if (event.stage === "bootSettled")
|
|
6104
|
+
settleBootSettled();
|
|
6105
|
+
break;
|
|
6106
|
+
}
|
|
6107
|
+
case "milestone-error": {
|
|
6108
|
+
if (event.stage === "writeReady")
|
|
6109
|
+
failWriteReady(rebuildError(event.error));
|
|
6110
|
+
else if (event.stage === "bootSettled")
|
|
6111
|
+
failBootSettled(rebuildError(event.error));
|
|
6112
|
+
break;
|
|
6113
|
+
}
|
|
5677
6114
|
case "conflict":
|
|
5678
6115
|
options.onConflict?.(event.details);
|
|
5679
6116
|
break;
|
|
@@ -5721,6 +6158,15 @@ async function attachSyncClient(options) {
|
|
|
5721
6158
|
} else {
|
|
5722
6159
|
if (ack.engineReady)
|
|
5723
6160
|
markReady();
|
|
6161
|
+
resolveLocalReadReady();
|
|
6162
|
+
if (ack.writeReady)
|
|
6163
|
+
settleWriteReady();
|
|
6164
|
+
if (ack.writeReadyError)
|
|
6165
|
+
failWriteReady(rebuildError(ack.writeReadyError));
|
|
6166
|
+
if (ack.bootSettled)
|
|
6167
|
+
settleBootSettled();
|
|
6168
|
+
if (ack.bootSettledError)
|
|
6169
|
+
failBootSettled(rebuildError(ack.bootSettledError));
|
|
5724
6170
|
attachAckResolve?.(ack);
|
|
5725
6171
|
}
|
|
5726
6172
|
break;
|
|
@@ -5796,6 +6242,57 @@ async function attachSyncClient(options) {
|
|
|
5796
6242
|
attachAckResolve = resolve;
|
|
5797
6243
|
attachAckReject = reject;
|
|
5798
6244
|
});
|
|
6245
|
+
let resolveLocalReadReady;
|
|
6246
|
+
const localReadReady = new Promise((resolve) => {
|
|
6247
|
+
resolveLocalReadReady = resolve;
|
|
6248
|
+
});
|
|
6249
|
+
let resolveWriteReady;
|
|
6250
|
+
let rejectWriteReady;
|
|
6251
|
+
const writeReady = new Promise((resolve, reject) => {
|
|
6252
|
+
resolveWriteReady = resolve;
|
|
6253
|
+
rejectWriteReady = reject;
|
|
6254
|
+
});
|
|
6255
|
+
let resolveBootSettled;
|
|
6256
|
+
let rejectBootSettled;
|
|
6257
|
+
const bootSettled = new Promise((resolve, reject) => {
|
|
6258
|
+
resolveBootSettled = resolve;
|
|
6259
|
+
rejectBootSettled = reject;
|
|
6260
|
+
});
|
|
6261
|
+
localReadReady.catch(() => {
|
|
6262
|
+
return;
|
|
6263
|
+
});
|
|
6264
|
+
writeReady.catch(() => {
|
|
6265
|
+
return;
|
|
6266
|
+
});
|
|
6267
|
+
bootSettled.catch(() => {
|
|
6268
|
+
return;
|
|
6269
|
+
});
|
|
6270
|
+
let writeReadySettled = false;
|
|
6271
|
+
let bootSettledSettled = false;
|
|
6272
|
+
const settleWriteReady = () => {
|
|
6273
|
+
if (writeReadySettled)
|
|
6274
|
+
return;
|
|
6275
|
+
writeReadySettled = true;
|
|
6276
|
+
resolveWriteReady();
|
|
6277
|
+
};
|
|
6278
|
+
const failWriteReady = (error) => {
|
|
6279
|
+
if (writeReadySettled)
|
|
6280
|
+
return;
|
|
6281
|
+
writeReadySettled = true;
|
|
6282
|
+
rejectWriteReady(error);
|
|
6283
|
+
};
|
|
6284
|
+
const settleBootSettled = () => {
|
|
6285
|
+
if (bootSettledSettled)
|
|
6286
|
+
return;
|
|
6287
|
+
bootSettledSettled = true;
|
|
6288
|
+
resolveBootSettled();
|
|
6289
|
+
};
|
|
6290
|
+
const failBootSettled = (error) => {
|
|
6291
|
+
if (bootSettledSettled)
|
|
6292
|
+
return;
|
|
6293
|
+
bootSettledSettled = true;
|
|
6294
|
+
rejectBootSettled(error);
|
|
6295
|
+
};
|
|
5799
6296
|
const detachFromWorker = () => {
|
|
5800
6297
|
if (detached)
|
|
5801
6298
|
return;
|
|
@@ -5806,6 +6303,13 @@ async function attachSyncClient(options) {
|
|
|
5806
6303
|
diffHandlers.clear();
|
|
5807
6304
|
postBridgeMessage(port, codec, "detach", null);
|
|
5808
6305
|
attachAckReject?.(detachError());
|
|
6306
|
+
const disposedError = new ClientDisposedError;
|
|
6307
|
+
failWriteReady(disposedError);
|
|
6308
|
+
failBootSettled(disposedError);
|
|
6309
|
+
if (!readyResolved) {
|
|
6310
|
+
readyResolved = true;
|
|
6311
|
+
rejectReady(disposedError);
|
|
6312
|
+
}
|
|
5809
6313
|
for (const pending of rpcPending.values())
|
|
5810
6314
|
pending.reject(detachError());
|
|
5811
6315
|
rpcPending.clear();
|
|
@@ -5906,7 +6410,7 @@ async function attachSyncClient(options) {
|
|
|
5906
6410
|
...hydrated ? { hydrated } : {}
|
|
5907
6411
|
};
|
|
5908
6412
|
};
|
|
5909
|
-
const { drizzle:
|
|
6413
|
+
const { drizzle: drizzle5, views } = buildRegistryReadHandles(options.registry);
|
|
5910
6414
|
const notSupported = (name) => () => {
|
|
5911
6415
|
throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`);
|
|
5912
6416
|
};
|
|
@@ -5915,7 +6419,7 @@ async function attachSyncClient(options) {
|
|
|
5915
6419
|
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
5916
6420
|
};
|
|
5917
6421
|
const client = {
|
|
5918
|
-
drizzle:
|
|
6422
|
+
drizzle: drizzle5,
|
|
5919
6423
|
views,
|
|
5920
6424
|
pglite: new Proxy({}, {
|
|
5921
6425
|
get: notSupported("client.pglite")
|
|
@@ -5930,6 +6434,9 @@ async function attachSyncClient(options) {
|
|
|
5930
6434
|
delete: (entityKey) => rpc("delete", [tableKey, entityKey])
|
|
5931
6435
|
}
|
|
5932
6436
|
])),
|
|
6437
|
+
localReadReady,
|
|
6438
|
+
writeReady,
|
|
6439
|
+
bootSettled,
|
|
5933
6440
|
ready,
|
|
5934
6441
|
status,
|
|
5935
6442
|
start: async () => {
|
|
@@ -5945,8 +6452,8 @@ async function attachSyncClient(options) {
|
|
|
5945
6452
|
retryFailed: (table) => rpc("retryFailed", [table]),
|
|
5946
6453
|
recoverSending: (table) => rpc("recoverSending", [table]),
|
|
5947
6454
|
readMutationDetails: (table) => rpc("readMutationDetails", [table]),
|
|
5948
|
-
rawQuery: (
|
|
5949
|
-
rawExec: (
|
|
6455
|
+
rawQuery: (sql7, params, options2) => rpc("rawQuery", [sql7, params, options2]),
|
|
6456
|
+
rawExec: (sql7, options2) => rpc("rawExec", [sql7, options2]),
|
|
5950
6457
|
mutate: {
|
|
5951
6458
|
create: (table, input) => rpc("create", [table, input]),
|
|
5952
6459
|
update: (table, entityKey, patch) => rpc("update", [table, entityKey, patch]),
|
|
@@ -5956,6 +6463,11 @@ async function attachSyncClient(options) {
|
|
|
5956
6463
|
discardConflict: (table, entityKey) => rpc("discardConflict", [table, entityKey]),
|
|
5957
6464
|
discardQuarantined: (table, entityKey) => rpc("discardQuarantined", [table, entityKey]),
|
|
5958
6465
|
diagnostics: (table) => rpc("diagnostics", [table]),
|
|
6466
|
+
mutations: createMutationsApi({
|
|
6467
|
+
registry: options.registry,
|
|
6468
|
+
subscribeLiveRows,
|
|
6469
|
+
query: (sql7, params) => rpc("rawQuery", [sql7, params])
|
|
6470
|
+
}),
|
|
5959
6471
|
query: notSupported("client.query"),
|
|
5960
6472
|
queryRow: notSupported("client.queryRow"),
|
|
5961
6473
|
queryRaw: notSupported("client.queryRaw"),
|
|
@@ -6243,6 +6755,28 @@ function defineSyncWorker(options) {
|
|
|
6243
6755
|
const bootedPromise = new Promise((resolve) => {
|
|
6244
6756
|
resolveBooted = resolve;
|
|
6245
6757
|
});
|
|
6758
|
+
const milestones = { writeReady: false, bootSettled: false };
|
|
6759
|
+
const stageErrors = {};
|
|
6760
|
+
let milestonesWired = false;
|
|
6761
|
+
const markMilestone = (stage) => {
|
|
6762
|
+
if (milestones[stage])
|
|
6763
|
+
return;
|
|
6764
|
+
milestones[stage] = true;
|
|
6765
|
+
broadcastEvent({ kind: "milestone", stage });
|
|
6766
|
+
};
|
|
6767
|
+
const failMilestone = (stage, error) => {
|
|
6768
|
+
if (stageErrors[stage])
|
|
6769
|
+
return;
|
|
6770
|
+
const serialized = serializeError(error);
|
|
6771
|
+
stageErrors[stage] = serialized;
|
|
6772
|
+
broadcastEvent({ kind: "milestone-error", stage, error: serialized });
|
|
6773
|
+
};
|
|
6774
|
+
const milestoneAckFields = () => ({
|
|
6775
|
+
...milestones.writeReady ? { writeReady: true } : {},
|
|
6776
|
+
...milestones.bootSettled ? { bootSettled: true } : {},
|
|
6777
|
+
...stageErrors.writeReady ? { writeReadyError: stageErrors.writeReady } : {},
|
|
6778
|
+
...stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}
|
|
6779
|
+
});
|
|
6246
6780
|
const boot = (attach) => {
|
|
6247
6781
|
if (bootPromise)
|
|
6248
6782
|
return bootPromise;
|
|
@@ -6389,10 +6923,10 @@ function defineSyncWorker(options) {
|
|
|
6389
6923
|
const active = client ?? await bootPromise;
|
|
6390
6924
|
if (!active)
|
|
6391
6925
|
throw new Error("subscribe before attach");
|
|
6392
|
-
const { queryId, sql:
|
|
6393
|
-
const prepared = await active.prepareQuery({ sql:
|
|
6394
|
-
const hydratingTables = active.hydratingTablesFor({ sql:
|
|
6395
|
-
const materialSql = wrapLiveQueryForMaterialization(
|
|
6926
|
+
const { queryId, sql: sql7, params, pkColumns, use, fields, keepAliveMs } = payload;
|
|
6927
|
+
const prepared = await active.prepareQuery({ sql: sql7, ...use ? { use } : {} });
|
|
6928
|
+
const hydratingTables = active.hydratingTablesFor({ sql: sql7, ...use ? { use } : {} });
|
|
6929
|
+
const materialSql = wrapLiveQueryForMaterialization(sql7, fields);
|
|
6396
6930
|
if (closing || pending.cancelled || !ports.has(port)) {
|
|
6397
6931
|
postBridgeMessage(port, codec, "rpc-result", {
|
|
6398
6932
|
ok: false,
|
|
@@ -6506,14 +7040,22 @@ function defineSyncWorker(options) {
|
|
|
6506
7040
|
boot(attach).then((booted) => {
|
|
6507
7041
|
client = booted;
|
|
6508
7042
|
resolveBooted(booted);
|
|
7043
|
+
if (!milestonesWired) {
|
|
7044
|
+
milestonesWired = true;
|
|
7045
|
+
booted.writeReady.then(() => markMilestone("writeReady"), (error) => failMilestone("writeReady", error));
|
|
7046
|
+
booted.bootSettled.then(() => markMilestone("bootSettled"), (error) => failMilestone("bootSettled", error));
|
|
7047
|
+
}
|
|
6509
7048
|
if (!engineReadyFired) {
|
|
6510
7049
|
booted.ready.then(() => {
|
|
6511
7050
|
engineReadyFired = true;
|
|
7051
|
+
}, () => {
|
|
7052
|
+
return;
|
|
6512
7053
|
});
|
|
6513
7054
|
}
|
|
6514
7055
|
postBridgeMessage(port, codec, "attach-ack", {
|
|
6515
7056
|
alreadyBooted,
|
|
6516
|
-
...engineReadyFired ? { engineReady: true } : {}
|
|
7057
|
+
...engineReadyFired ? { engineReady: true } : {},
|
|
7058
|
+
...milestoneAckFields()
|
|
6517
7059
|
});
|
|
6518
7060
|
postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
|
|
6519
7061
|
}, (error) => {
|
|
@@ -6654,6 +7196,19 @@ function bindGlobalScope(connect) {
|
|
|
6654
7196
|
}
|
|
6655
7197
|
}
|
|
6656
7198
|
// packages/client/src/index.ts
|
|
7199
|
+
class WriteNotReadyError extends Error {
|
|
7200
|
+
constructor() {
|
|
7201
|
+
super("pgxsinkit: write attempted before `writeReady` resolved. Await `client.writeReady` (the default write " + "methods do this for you) before enqueuing, or gate the write on it.");
|
|
7202
|
+
this.name = "WriteNotReadyError";
|
|
7203
|
+
}
|
|
7204
|
+
}
|
|
7205
|
+
|
|
7206
|
+
class ClientDisposedError extends Error {
|
|
7207
|
+
constructor() {
|
|
7208
|
+
super("pgxsinkit: the client was stopped/destroyed before this readiness stage resolved.");
|
|
7209
|
+
this.name = "ClientDisposedError";
|
|
7210
|
+
}
|
|
7211
|
+
}
|
|
6657
7212
|
async function createClientPGlite(store, options) {
|
|
6658
7213
|
const normalised = normaliseStorePathInput(store);
|
|
6659
7214
|
const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);
|
|
@@ -6671,8 +7226,8 @@ async function createClientPGlite(store, options) {
|
|
|
6671
7226
|
}
|
|
6672
7227
|
function replAdapter(client) {
|
|
6673
7228
|
return {
|
|
6674
|
-
query: (
|
|
6675
|
-
exec: (
|
|
7229
|
+
query: (sql7, params, options) => client.rawQuery(sql7, params, options),
|
|
7230
|
+
exec: (sql7, options) => client.rawExec(sql7, options)
|
|
6676
7231
|
};
|
|
6677
7232
|
}
|
|
6678
7233
|
async function createSyncClient(options) {
|
|
@@ -6682,8 +7237,26 @@ async function createSyncClient(options) {
|
|
|
6682
7237
|
isRunning: false
|
|
6683
7238
|
};
|
|
6684
7239
|
let resolveReady;
|
|
6685
|
-
|
|
7240
|
+
let rejectReady;
|
|
7241
|
+
const ready = new Promise((resolve, reject) => {
|
|
6686
7242
|
resolveReady = resolve;
|
|
7243
|
+
rejectReady = reject;
|
|
7244
|
+
});
|
|
7245
|
+
let resolveLocalReadReady;
|
|
7246
|
+
const localReadReady = new Promise((resolve) => {
|
|
7247
|
+
resolveLocalReadReady = resolve;
|
|
7248
|
+
});
|
|
7249
|
+
let resolveWriteReady;
|
|
7250
|
+
let rejectWriteReady;
|
|
7251
|
+
const writeReady = new Promise((resolve, reject) => {
|
|
7252
|
+
resolveWriteReady = resolve;
|
|
7253
|
+
rejectWriteReady = reject;
|
|
7254
|
+
});
|
|
7255
|
+
let resolveBootSettled;
|
|
7256
|
+
let rejectBootSettled;
|
|
7257
|
+
const bootSettled = new Promise((resolve, reject) => {
|
|
7258
|
+
resolveBootSettled = resolve;
|
|
7259
|
+
rejectBootSettled = reject;
|
|
6687
7260
|
});
|
|
6688
7261
|
if (options.pgliteInstance && options.precreatedPglite) {
|
|
6689
7262
|
throw new Error("createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` \u2014 they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).");
|
|
@@ -6700,9 +7273,11 @@ async function createSyncClient(options) {
|
|
|
6700
7273
|
}
|
|
6701
7274
|
const syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
|
|
6702
7275
|
const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
|
|
7276
|
+
const storeKind = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
|
|
6703
7277
|
const bootReportBuilder = createBootReportBuilder({
|
|
6704
7278
|
mode: options.bootMode ?? "in-process",
|
|
6705
7279
|
freshStore: options.freshStore === true,
|
|
7280
|
+
storeKind,
|
|
6706
7281
|
overlapPrefetch,
|
|
6707
7282
|
registryFingerprint: fingerprintRegistry2(options.registry)
|
|
6708
7283
|
});
|
|
@@ -6852,8 +7427,22 @@ async function createSyncClient(options) {
|
|
|
6852
7427
|
const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
|
|
6853
7428
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
6854
7429
|
}
|
|
6855
|
-
|
|
6856
|
-
|
|
7430
|
+
await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
|
|
7431
|
+
await pglite.exec(buildLocalMetaBootstrapSql(options.registry));
|
|
7432
|
+
const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
|
|
7433
|
+
const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
|
|
7434
|
+
if (storedFingerprint === currentFingerprint) {
|
|
7435
|
+
bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
|
|
7436
|
+
} else {
|
|
7437
|
+
await pglite.exec(generateDurableLocalSchemaSql(options.registry));
|
|
7438
|
+
await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
|
|
7439
|
+
bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
|
|
7440
|
+
}
|
|
7441
|
+
const ephemeralSql = generateEphemeralLocalSchemaSql(options.registry);
|
|
7442
|
+
if (ephemeralSql.length > 0) {
|
|
7443
|
+
await pglite.exec(ephemeralSql);
|
|
7444
|
+
}
|
|
7445
|
+
});
|
|
6857
7446
|
if (options.prepareLocalDb) {
|
|
6858
7447
|
const prepareLocalDb = options.prepareLocalDb;
|
|
6859
7448
|
await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDb(pglite));
|
|
@@ -6865,6 +7454,7 @@ async function createSyncClient(options) {
|
|
|
6865
7454
|
db: pglite,
|
|
6866
7455
|
registry: options.registry,
|
|
6867
7456
|
writeUrl: options.writeUrl,
|
|
7457
|
+
ownsMetaTable: !options.pgliteInstance,
|
|
6868
7458
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
6869
7459
|
...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
|
|
6870
7460
|
...writePathHeaders ? { requestHeaders: writePathHeaders } : {},
|
|
@@ -6873,45 +7463,103 @@ async function createSyncClient(options) {
|
|
|
6873
7463
|
...options.onConflict ? { onConflict: options.onConflict } : {},
|
|
6874
7464
|
...options.onReject ? { onReject: options.onReject } : {}
|
|
6875
7465
|
});
|
|
6876
|
-
|
|
6877
|
-
if (restoreBoot) {
|
|
6878
|
-
await mutationRuntime.quarantineRecovered();
|
|
6879
|
-
}
|
|
7466
|
+
let pendingActivations = new Set;
|
|
6880
7467
|
let versionEvent = null;
|
|
6881
|
-
|
|
7468
|
+
const runBootRecoveryStage = async () => {
|
|
7469
|
+
const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgliteInstance, restore: restoreBoot }));
|
|
7470
|
+
bootReportBuilder.setJournalRecovery(recoveryOutcome);
|
|
7471
|
+
};
|
|
7472
|
+
const runReconcileStage = async () => {
|
|
7473
|
+
if (options.pgliteInstance)
|
|
7474
|
+
return;
|
|
6882
7475
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () => reconcileLocalStoreVersion({
|
|
6883
7476
|
db: pglite,
|
|
6884
7477
|
registry: options.registry,
|
|
6885
7478
|
runtime: mutationRuntime,
|
|
6886
7479
|
...options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}
|
|
6887
7480
|
}));
|
|
7481
|
+
};
|
|
7482
|
+
if (restoreBoot) {
|
|
7483
|
+
await runBootRecoveryStage();
|
|
7484
|
+
await runReconcileStage();
|
|
7485
|
+
} else {
|
|
7486
|
+
await runReconcileStage();
|
|
6888
7487
|
}
|
|
6889
7488
|
const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
|
|
6890
7489
|
const lazyGuardIndex = buildLazyGuardIndex(options.registry);
|
|
6891
7490
|
let sync = null;
|
|
6892
7491
|
let convergenceDriver = null;
|
|
6893
|
-
|
|
6894
|
-
|
|
6895
|
-
|
|
6896
|
-
|
|
6897
|
-
|
|
6898
|
-
|
|
6899
|
-
|
|
7492
|
+
let disposed = false;
|
|
7493
|
+
let resolveSyncWired;
|
|
7494
|
+
let rejectSyncWired;
|
|
7495
|
+
const syncWired = new Promise((resolve, reject) => {
|
|
7496
|
+
resolveSyncWired = resolve;
|
|
7497
|
+
rejectSyncWired = reject;
|
|
7498
|
+
});
|
|
7499
|
+
syncWired.catch(() => {
|
|
7500
|
+
return;
|
|
7501
|
+
});
|
|
7502
|
+
const isSyncPending = () => syncEnabled && sync == null && !disposed;
|
|
7503
|
+
const quiesceTailForTeardown = async () => {
|
|
7504
|
+
disposed = true;
|
|
7505
|
+
const disposedError = new ClientDisposedError;
|
|
7506
|
+
rejectWriteReady(disposedError);
|
|
7507
|
+
rejectReady(disposedError);
|
|
7508
|
+
resolveSyncWired();
|
|
7509
|
+
await bootSettled.catch(() => {
|
|
7510
|
+
return;
|
|
7511
|
+
});
|
|
7512
|
+
};
|
|
7513
|
+
const runWriteAndSyncTail = async () => {
|
|
7514
|
+
if (disposed)
|
|
7515
|
+
return;
|
|
7516
|
+
if (!restoreBoot) {
|
|
7517
|
+
await runBootRecoveryStage();
|
|
7518
|
+
}
|
|
7519
|
+
if (disposed)
|
|
7520
|
+
return;
|
|
7521
|
+
bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
|
|
7522
|
+
resolveWriteReady();
|
|
7523
|
+
if (disposed)
|
|
7524
|
+
return;
|
|
7525
|
+
status.isRunning = true;
|
|
7526
|
+
openDbGate();
|
|
7527
|
+
if (syncEnabled) {
|
|
7528
|
+
if (earlySync) {
|
|
7529
|
+
sync = await earlySync;
|
|
7530
|
+
bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
|
|
7531
|
+
bootReportBuilder.markSyncStartDone();
|
|
7532
|
+
} else {
|
|
7533
|
+
const resetKeys = versionEvent?.status === "rebuilt" ? [...options.resetSubscriptionKeys ?? [], ...allGroupSubscriptionKeys(options.registry)] : options.resetSubscriptionKeys;
|
|
7534
|
+
await resetSubscriptionsIfRequested(pglite, resetKeys);
|
|
7535
|
+
if (disposed)
|
|
7536
|
+
return;
|
|
7537
|
+
status.phase = "syncing";
|
|
7538
|
+
options.onStatusChange?.(status);
|
|
7539
|
+
const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
|
|
7540
|
+
if (disposed)
|
|
7541
|
+
return;
|
|
7542
|
+
sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startConfiguredSync(pglite, buildStartOptions(promotedGroups)));
|
|
7543
|
+
bootReportBuilder.markSyncStartDone();
|
|
7544
|
+
}
|
|
7545
|
+
if (disposed) {
|
|
7546
|
+
sync?.unsubscribe();
|
|
7547
|
+
sync = null;
|
|
7548
|
+
return;
|
|
7549
|
+
}
|
|
6900
7550
|
} else {
|
|
6901
|
-
|
|
6902
|
-
await resetSubscriptionsIfRequested(pglite, resetKeys);
|
|
6903
|
-
status.phase = "syncing";
|
|
7551
|
+
status.phase = "ready";
|
|
6904
7552
|
options.onStatusChange?.(status);
|
|
6905
|
-
|
|
6906
|
-
|
|
6907
|
-
bootReportBuilder.markSyncStartDone();
|
|
7553
|
+
finalizeBootReport();
|
|
7554
|
+
resolveReady();
|
|
6908
7555
|
}
|
|
6909
|
-
|
|
6910
|
-
|
|
6911
|
-
|
|
6912
|
-
|
|
6913
|
-
|
|
6914
|
-
|
|
7556
|
+
const buffered = pendingActivations;
|
|
7557
|
+
pendingActivations = null;
|
|
7558
|
+
if (sync != null && buffered && buffered.size > 0) {
|
|
7559
|
+
await ensureSynced([...buffered]);
|
|
7560
|
+
}
|
|
7561
|
+
resolveSyncWired();
|
|
7562
|
+
};
|
|
6915
7563
|
if (options.autoSync && !restoreBoot) {
|
|
6916
7564
|
convergenceDriver = createConvergenceDriver({
|
|
6917
7565
|
client: {
|
|
@@ -6921,23 +7569,29 @@ async function createSyncClient(options) {
|
|
|
6921
7569
|
trigger: options.autoSync,
|
|
6922
7570
|
...options.onConvergencePass ? { onPass: options.onConvergencePass } : {}
|
|
6923
7571
|
});
|
|
6924
|
-
ready.then(() => convergenceDriver?.start())
|
|
7572
|
+
ready.then(() => convergenceDriver?.start(), () => {
|
|
7573
|
+
return;
|
|
7574
|
+
});
|
|
6925
7575
|
}
|
|
6926
7576
|
const requestConvergence = () => convergenceDriver?.requestPass();
|
|
6927
7577
|
const mutate = {
|
|
6928
7578
|
create: async (table, input) => {
|
|
7579
|
+
await writeReady;
|
|
6929
7580
|
await mutationRuntime.create(table, input);
|
|
6930
7581
|
requestConvergence();
|
|
6931
7582
|
},
|
|
6932
7583
|
update: async (table, entityKey, patch) => {
|
|
7584
|
+
await writeReady;
|
|
6933
7585
|
await mutationRuntime.update(table, entityKey, patch);
|
|
6934
7586
|
requestConvergence();
|
|
6935
7587
|
},
|
|
6936
7588
|
delete: async (table, entityKey) => {
|
|
7589
|
+
await writeReady;
|
|
6937
7590
|
await mutationRuntime.delete(table, entityKey);
|
|
6938
7591
|
requestConvergence();
|
|
6939
7592
|
},
|
|
6940
7593
|
batch: async (items) => {
|
|
7594
|
+
await writeReady;
|
|
6941
7595
|
await mutationRuntime.batch(items);
|
|
6942
7596
|
requestConvergence();
|
|
6943
7597
|
}
|
|
@@ -6987,8 +7641,16 @@ async function createSyncClient(options) {
|
|
|
6987
7641
|
})();
|
|
6988
7642
|
};
|
|
6989
7643
|
const ensureSynced = async (keys) => {
|
|
7644
|
+
if (keys.length === 0)
|
|
7645
|
+
return;
|
|
7646
|
+
if (sync == null && isSyncPending()) {
|
|
7647
|
+
if (pendingActivations != null)
|
|
7648
|
+
for (const key of keys)
|
|
7649
|
+
pendingActivations.add(key);
|
|
7650
|
+
await syncWired;
|
|
7651
|
+
}
|
|
6990
7652
|
const activeSync = sync;
|
|
6991
|
-
if (activeSync == null
|
|
7653
|
+
if (activeSync == null)
|
|
6992
7654
|
return;
|
|
6993
7655
|
const groupKeys = new Set;
|
|
6994
7656
|
for (const key of keys) {
|
|
@@ -7003,6 +7665,12 @@ async function createSyncClient(options) {
|
|
|
7003
7665
|
await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
|
|
7004
7666
|
};
|
|
7005
7667
|
activateOrdinaryWriteTables = (tables) => {
|
|
7668
|
+
if (sync == null) {
|
|
7669
|
+
if (pendingActivations != null)
|
|
7670
|
+
for (const table of tables)
|
|
7671
|
+
pendingActivations.add(table);
|
|
7672
|
+
return;
|
|
7673
|
+
}
|
|
7006
7674
|
const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table));
|
|
7007
7675
|
if (lazyTables.length === 0)
|
|
7008
7676
|
return;
|
|
@@ -7011,6 +7679,9 @@ async function createSyncClient(options) {
|
|
|
7011
7679
|
});
|
|
7012
7680
|
};
|
|
7013
7681
|
const groupReadyForTable = async (table) => {
|
|
7682
|
+
if (sync == null && isSyncPending()) {
|
|
7683
|
+
await syncWired;
|
|
7684
|
+
}
|
|
7014
7685
|
const activeSync = sync;
|
|
7015
7686
|
if (activeSync == null)
|
|
7016
7687
|
return;
|
|
@@ -7021,15 +7692,16 @@ async function createSyncClient(options) {
|
|
|
7021
7692
|
};
|
|
7022
7693
|
const isGroupReadyForTable = (table) => {
|
|
7023
7694
|
const activeSync = sync;
|
|
7024
|
-
if (activeSync == null)
|
|
7025
|
-
return
|
|
7695
|
+
if (activeSync == null) {
|
|
7696
|
+
return !isSyncPending();
|
|
7697
|
+
}
|
|
7026
7698
|
const groupKey = activeSync.groupKeyForTable(table);
|
|
7027
7699
|
if (groupKey == null)
|
|
7028
7700
|
return true;
|
|
7029
7701
|
return activeSync.isGroupReady(groupKey);
|
|
7030
7702
|
};
|
|
7031
7703
|
const hydratingTablesFor = (query) => {
|
|
7032
|
-
if (sync == null)
|
|
7704
|
+
if (sync == null && !isSyncPending())
|
|
7033
7705
|
return [];
|
|
7034
7706
|
const referenced = new Set(query.use ?? []);
|
|
7035
7707
|
for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex))
|
|
@@ -7038,8 +7710,9 @@ async function createSyncClient(options) {
|
|
|
7038
7710
|
};
|
|
7039
7711
|
const isSynced = (key) => {
|
|
7040
7712
|
const activeSync = sync;
|
|
7041
|
-
if (activeSync == null)
|
|
7042
|
-
return
|
|
7713
|
+
if (activeSync == null) {
|
|
7714
|
+
return !isSyncPending();
|
|
7715
|
+
}
|
|
7043
7716
|
return activeSync.isTableStarted(key);
|
|
7044
7717
|
};
|
|
7045
7718
|
const groupTableKeysFor = (key, entry) => {
|
|
@@ -7071,6 +7744,7 @@ async function createSyncClient(options) {
|
|
|
7071
7744
|
}
|
|
7072
7745
|
};
|
|
7073
7746
|
const desync = async (key) => {
|
|
7747
|
+
await bootSettled;
|
|
7074
7748
|
const entry = options.registry[key];
|
|
7075
7749
|
if (entry == null)
|
|
7076
7750
|
throw new Error(`desync: unknown table ${String(key)}`);
|
|
@@ -7079,21 +7753,25 @@ async function createSyncClient(options) {
|
|
|
7079
7753
|
}
|
|
7080
7754
|
await tearDownLazyGroup(key, entry, "desync");
|
|
7081
7755
|
};
|
|
7082
|
-
const discardEphemeral =
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
|
|
7086
|
-
|
|
7087
|
-
|
|
7088
|
-
|
|
7089
|
-
|
|
7090
|
-
|
|
7091
|
-
|
|
7756
|
+
const discardEphemeral = async (key) => {
|
|
7757
|
+
await bootSettled;
|
|
7758
|
+
return lifecycleSlot.run("discardEphemeral", async () => {
|
|
7759
|
+
const entry = options.registry[key];
|
|
7760
|
+
if (entry == null)
|
|
7761
|
+
throw new Error(`discardEphemeral: unknown table ${String(key)}`);
|
|
7762
|
+
if (entry.subscription !== "lazy") {
|
|
7763
|
+
throw new Error(`discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded \u2014 an eager relation is always-on and would immediately re-sync.`);
|
|
7764
|
+
}
|
|
7765
|
+
for (const member of groupTableKeysFor(key, entry)) {
|
|
7766
|
+
if ((options.registry[member].retention ?? "persistent") !== "ephemeral") {
|
|
7767
|
+
throw new Error(`discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent \u2014 ` + `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`);
|
|
7768
|
+
}
|
|
7092
7769
|
}
|
|
7093
|
-
|
|
7094
|
-
|
|
7095
|
-
}
|
|
7770
|
+
await tearDownLazyGroup(key, entry, "discardEphemeral");
|
|
7771
|
+
});
|
|
7772
|
+
};
|
|
7096
7773
|
const transaction = async ({ mode }, run) => {
|
|
7774
|
+
await writeReady;
|
|
7097
7775
|
const collected = [];
|
|
7098
7776
|
const txTables = Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
|
|
7099
7777
|
tableKey,
|
|
@@ -7130,20 +7808,21 @@ async function createSyncClient(options) {
|
|
|
7130
7808
|
}
|
|
7131
7809
|
return await mutationRuntime.flushUnit(unit.id);
|
|
7132
7810
|
};
|
|
7133
|
-
const prepareQuery = async ({ sql:
|
|
7811
|
+
const prepareQuery = async ({ sql: sql7, use }) => {
|
|
7134
7812
|
const toActivate = new Set(use ?? []);
|
|
7135
|
-
for (const key of findReferencedLazyKeysInSql(
|
|
7813
|
+
for (const key of findReferencedLazyKeysInSql(sql7, lazyGuardIndex))
|
|
7136
7814
|
toActivate.add(key);
|
|
7137
7815
|
const lazyTables = [...toActivate];
|
|
7138
7816
|
await ensureSynced(lazyTables);
|
|
7139
7817
|
assertLazyRefsActivated({
|
|
7140
|
-
sql:
|
|
7818
|
+
sql: sql7,
|
|
7141
7819
|
index: lazyGuardIndex,
|
|
7142
7820
|
isActive: (key) => isSynced(key)
|
|
7143
7821
|
});
|
|
7144
7822
|
return { lazyTables };
|
|
7145
7823
|
};
|
|
7146
7824
|
const runGuardedQuery = async (build, use) => {
|
|
7825
|
+
await localReadReady;
|
|
7147
7826
|
const builder = build(client);
|
|
7148
7827
|
await prepareQuery({ sql: builder.toSQL().sql, ...use ? { use } : {} });
|
|
7149
7828
|
return builder;
|
|
@@ -7166,12 +7845,16 @@ async function createSyncClient(options) {
|
|
|
7166
7845
|
delete: (entityKey) => mutate.delete(tableKey, entityKey)
|
|
7167
7846
|
}
|
|
7168
7847
|
])),
|
|
7848
|
+
localReadReady,
|
|
7849
|
+
writeReady,
|
|
7850
|
+
bootSettled,
|
|
7169
7851
|
ready,
|
|
7170
7852
|
status,
|
|
7171
7853
|
start: async () => {
|
|
7172
7854
|
await ready;
|
|
7173
7855
|
},
|
|
7174
7856
|
stop: async () => {
|
|
7857
|
+
await quiesceTailForTeardown();
|
|
7175
7858
|
await convergenceDriver?.stop();
|
|
7176
7859
|
sync?.unsubscribe();
|
|
7177
7860
|
status.isRunning = false;
|
|
@@ -7181,6 +7864,7 @@ async function createSyncClient(options) {
|
|
|
7181
7864
|
await pglite.close();
|
|
7182
7865
|
},
|
|
7183
7866
|
destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
|
|
7867
|
+
await quiesceTailForTeardown();
|
|
7184
7868
|
if (!destroyOptions?.force) {
|
|
7185
7869
|
const stats = await mutationRuntime.readMutationStats();
|
|
7186
7870
|
const owed = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
|
|
@@ -7197,24 +7881,47 @@ async function createSyncClient(options) {
|
|
|
7197
7881
|
await liveManager.dispose();
|
|
7198
7882
|
await pglite.close();
|
|
7199
7883
|
}),
|
|
7200
|
-
dropReadCache:
|
|
7201
|
-
await
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
|
|
7207
|
-
|
|
7208
|
-
|
|
7884
|
+
dropReadCache: async () => {
|
|
7885
|
+
await bootSettled;
|
|
7886
|
+
return lifecycleSlot.run("dropReadCache", async () => {
|
|
7887
|
+
await pglite.exec(buildDropReadCacheSql(options.registry));
|
|
7888
|
+
await pglite.exec(generateLocalSchemaSql(options.registry));
|
|
7889
|
+
await writeStoredLocalSchemaFingerprint(pglite, options.registry, computeLocalSchemaFingerprint(options.registry));
|
|
7890
|
+
await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
|
|
7891
|
+
});
|
|
7892
|
+
},
|
|
7893
|
+
flush: async (table) => {
|
|
7894
|
+
await writeReady;
|
|
7895
|
+
return mutationRuntime.flush(table);
|
|
7896
|
+
},
|
|
7897
|
+
reconcile: async (table) => {
|
|
7898
|
+
await writeReady;
|
|
7899
|
+
return mutationRuntime.reconcile(table);
|
|
7900
|
+
},
|
|
7901
|
+
retryFailed: async (table) => {
|
|
7902
|
+
await writeReady;
|
|
7903
|
+
return mutationRuntime.retryFailed(table);
|
|
7904
|
+
},
|
|
7905
|
+
recoverSending: async (table) => {
|
|
7906
|
+
await writeReady;
|
|
7907
|
+
return mutationRuntime.recoverSending(table);
|
|
7908
|
+
},
|
|
7209
7909
|
readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
|
|
7210
7910
|
mutate,
|
|
7211
|
-
discardConflict: (table, entityKey) =>
|
|
7212
|
-
|
|
7911
|
+
discardConflict: async (table, entityKey) => {
|
|
7912
|
+
await writeReady;
|
|
7913
|
+
return mutationRuntime.discardConflict(table, entityKey);
|
|
7914
|
+
},
|
|
7915
|
+
discardQuarantined: async (table, entityKey) => {
|
|
7916
|
+
await writeReady;
|
|
7917
|
+
return mutationRuntime.discardQuarantined(table, entityKey);
|
|
7918
|
+
},
|
|
7213
7919
|
diagnostics: async (table) => ({
|
|
7214
7920
|
mutation: await mutationRuntime.readMutationStats(table)
|
|
7215
7921
|
}),
|
|
7216
|
-
|
|
7217
|
-
|
|
7922
|
+
mutations: undefined,
|
|
7923
|
+
rawQuery: (sql7, params, options2) => pglite.query(sql7, params, options2),
|
|
7924
|
+
rawExec: (sql7, options2) => pglite.exec(sql7, options2),
|
|
7218
7925
|
query: (build) => runGuardedQuery(build),
|
|
7219
7926
|
queryRow: async (build) => {
|
|
7220
7927
|
const rows = await runGuardedQuery(build);
|
|
@@ -7233,8 +7940,9 @@ async function createSyncClient(options) {
|
|
|
7233
7940
|
transaction,
|
|
7234
7941
|
groupReady: groupReadyForTable,
|
|
7235
7942
|
hydratingTablesFor,
|
|
7236
|
-
subscribeLiveRows: async ({ sql:
|
|
7237
|
-
|
|
7943
|
+
subscribeLiveRows: async ({ sql: sql7, params, fields, use, keepAliveMs }, onRows) => {
|
|
7944
|
+
await localReadReady;
|
|
7945
|
+
const materialSql = wrapLiveQueryForMaterialization(sql7, fields);
|
|
7238
7946
|
const materializer = new LiveRowsMaterializer(undefined);
|
|
7239
7947
|
const subscription = await liveManager.subscribe({ materialSql, params }, {
|
|
7240
7948
|
deliverInitial: (rows) => {
|
|
@@ -7247,10 +7955,10 @@ async function createSyncClient(options) {
|
|
|
7247
7955
|
const initialRows = materializer.current();
|
|
7248
7956
|
let unsubscribed = false;
|
|
7249
7957
|
const lazySet = new Set(use ?? []);
|
|
7250
|
-
for (const key of findReferencedLazyKeysInSql(
|
|
7958
|
+
for (const key of findReferencedLazyKeysInSql(sql7, lazyGuardIndex))
|
|
7251
7959
|
lazySet.add(key);
|
|
7252
7960
|
const lazyTables = [...lazySet];
|
|
7253
|
-
const hydratingTables = hydratingTablesFor({ sql:
|
|
7961
|
+
const hydratingTables = hydratingTablesFor({ sql: sql7, ...use ? { use } : {} });
|
|
7254
7962
|
const hydrated = hydratingTables.length > 0 ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table))).then(async () => {
|
|
7255
7963
|
if (!unsubscribed)
|
|
7256
7964
|
await subscription.refresh();
|
|
@@ -7298,6 +8006,44 @@ async function createSyncClient(options) {
|
|
|
7298
8006
|
}, exportOptions));
|
|
7299
8007
|
}
|
|
7300
8008
|
};
|
|
8009
|
+
client.mutations = createMutationsApi({
|
|
8010
|
+
registry: options.registry,
|
|
8011
|
+
subscribeLiveRows: client.subscribeLiveRows,
|
|
8012
|
+
query: (sql7, params) => pglite.query(sql7, params)
|
|
8013
|
+
});
|
|
8014
|
+
bootReportBuilder.setLocalReadReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
|
|
8015
|
+
resolveLocalReadReady();
|
|
8016
|
+
if (restoreBoot) {
|
|
8017
|
+
bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
|
|
8018
|
+
resolveWriteReady();
|
|
8019
|
+
}
|
|
8020
|
+
writeReady.catch(() => {
|
|
8021
|
+
return;
|
|
8022
|
+
});
|
|
8023
|
+
bootSettled.catch(() => {
|
|
8024
|
+
return;
|
|
8025
|
+
});
|
|
8026
|
+
ready.catch(() => {
|
|
8027
|
+
return;
|
|
8028
|
+
});
|
|
8029
|
+
runWriteAndSyncTail().then(() => {
|
|
8030
|
+
resolveBootSettled();
|
|
8031
|
+
pendingActivations = null;
|
|
8032
|
+
resolveSyncWired();
|
|
8033
|
+
}, (error) => {
|
|
8034
|
+
syncDebug("boot write/sync tail failed after localReadReady", { error });
|
|
8035
|
+
if (pendingActivations != null && pendingActivations.size > 0) {
|
|
8036
|
+
syncDebug("boot tail failure dropped buffered activations", { tables: [...pendingActivations] });
|
|
8037
|
+
}
|
|
8038
|
+
pendingActivations = null;
|
|
8039
|
+
status.phase = "degraded";
|
|
8040
|
+
status.lastError = error instanceof Error ? error.message : String(error);
|
|
8041
|
+
options.onStatusChange?.(status);
|
|
8042
|
+
rejectWriteReady(error);
|
|
8043
|
+
rejectReady(error);
|
|
8044
|
+
rejectBootSettled(error);
|
|
8045
|
+
rejectSyncWired(error);
|
|
8046
|
+
});
|
|
7301
8047
|
return client;
|
|
7302
8048
|
}
|
|
7303
8049
|
function allGroupSubscriptionKeys(registry) {
|
|
@@ -7317,7 +8063,7 @@ async function resetSubscriptionsIfRequested(pglite, keys) {
|
|
|
7317
8063
|
}
|
|
7318
8064
|
function createDrizzleDatabase(client, schema) {
|
|
7319
8065
|
const relations = defineRelations(schema);
|
|
7320
|
-
const createDatabase =
|
|
8066
|
+
const createDatabase = drizzle5;
|
|
7321
8067
|
return createDatabase({ client, relations });
|
|
7322
8068
|
}
|
|
7323
8069
|
function buildSchema(registry) {
|
|
@@ -7386,6 +8132,7 @@ export {
|
|
|
7386
8132
|
getOverlayTable,
|
|
7387
8133
|
getLocalMetaTable,
|
|
7388
8134
|
getJournalTable,
|
|
8135
|
+
getAllMutationsView,
|
|
7389
8136
|
generateLocalSchemaSql,
|
|
7390
8137
|
findReferencedSyncedKeysInSql,
|
|
7391
8138
|
findReferencedLazyKeysInSql,
|
|
@@ -7394,6 +8141,7 @@ export {
|
|
|
7394
8141
|
defineSyncWorker,
|
|
7395
8142
|
createWorkerTokenCache,
|
|
7396
8143
|
createSyncClient,
|
|
8144
|
+
createMutationsApi,
|
|
7397
8145
|
createLifecycleSlot,
|
|
7398
8146
|
createIntervalConvergenceTrigger,
|
|
7399
8147
|
createConvergenceDriver,
|
|
@@ -7404,6 +8152,7 @@ export {
|
|
|
7404
8152
|
buildLazyGuardIndex,
|
|
7405
8153
|
attachSyncClient,
|
|
7406
8154
|
assertLazyRefsActivated,
|
|
8155
|
+
WriteNotReadyError,
|
|
7407
8156
|
RestoreTargetExistsError,
|
|
7408
8157
|
NonPersistentStoreError,
|
|
7409
8158
|
LiveRowsMaterializer,
|
|
@@ -7412,8 +8161,9 @@ export {
|
|
|
7412
8161
|
InvalidStorePathError,
|
|
7413
8162
|
DataExportDrainError,
|
|
7414
8163
|
DEFAULT_DRAIN_TIMEOUT_MS,
|
|
8164
|
+
ClientDisposedError,
|
|
7415
8165
|
BRIDGE_PROTOCOL_VERSION,
|
|
7416
8166
|
BRIDGE_CHANNEL
|
|
7417
8167
|
};
|
|
7418
8168
|
|
|
7419
|
-
//# debugId=
|
|
8169
|
+
//# debugId=804640A8064D585A64756E2164756E21
|