@pgxsinkit/client 0.1.48 → 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 +84 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1549 -333
- package/dist/index.js.map +15 -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 +17 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-fingerprint.d.ts +14 -0
- package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts +130 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +53 -2
- 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 +29 -1
- package/src/boot-report.ts +108 -0
- package/src/index.ts +648 -152
- 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 +193 -15
- package/src/worker/define-sync-worker.ts +267 -53
- package/src/worker/live-query-fingerprint.ts +128 -0
- package/src/worker/live-query-manager.ts +591 -0
- package/src/worker/protocol.ts +49 -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
|
}
|
|
@@ -5140,6 +5558,7 @@ async function createSyncEngine(pg, options) {
|
|
|
5140
5558
|
close
|
|
5141
5559
|
};
|
|
5142
5560
|
}
|
|
5561
|
+
|
|
5143
5562
|
// packages/client/src/worker/live-diff.ts
|
|
5144
5563
|
var KEY_SEP = String.fromCharCode(0);
|
|
5145
5564
|
function rowKey(row, pkColumns) {
|
|
@@ -5226,6 +5645,362 @@ class LiveRowsMaterializer {
|
|
|
5226
5645
|
}
|
|
5227
5646
|
}
|
|
5228
5647
|
|
|
5648
|
+
// packages/client/src/worker/live-query-fingerprint.ts
|
|
5649
|
+
var opaqueCounter = 0;
|
|
5650
|
+
function opaqueToken() {
|
|
5651
|
+
return `${(opaqueCounter++).toString(36)}.${Math.random().toString(36).slice(2)}`;
|
|
5652
|
+
}
|
|
5653
|
+
function toHex(bytes) {
|
|
5654
|
+
let hex = "";
|
|
5655
|
+
for (const byte of bytes)
|
|
5656
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
5657
|
+
return hex;
|
|
5658
|
+
}
|
|
5659
|
+
function isPlainObject(value) {
|
|
5660
|
+
const proto = Object.getPrototypeOf(value);
|
|
5661
|
+
return proto === Object.prototype || proto === null;
|
|
5662
|
+
}
|
|
5663
|
+
function encodeValue(value) {
|
|
5664
|
+
if (value === null)
|
|
5665
|
+
return ["z"];
|
|
5666
|
+
if (value === undefined)
|
|
5667
|
+
return ["v"];
|
|
5668
|
+
switch (typeof value) {
|
|
5669
|
+
case "boolean":
|
|
5670
|
+
return ["b", value];
|
|
5671
|
+
case "number":
|
|
5672
|
+
return ["n", String(value)];
|
|
5673
|
+
case "bigint":
|
|
5674
|
+
return ["i", value.toString()];
|
|
5675
|
+
case "string":
|
|
5676
|
+
return ["s", value];
|
|
5677
|
+
case "object": {
|
|
5678
|
+
if (value instanceof Date)
|
|
5679
|
+
return ["d", value.getTime()];
|
|
5680
|
+
if (value instanceof Uint8Array)
|
|
5681
|
+
return ["x", toHex(value)];
|
|
5682
|
+
if (value instanceof ArrayBuffer)
|
|
5683
|
+
return ["x", toHex(new Uint8Array(value))];
|
|
5684
|
+
if (ArrayBuffer.isView(value)) {
|
|
5685
|
+
const view = value;
|
|
5686
|
+
return ["x", toHex(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))];
|
|
5687
|
+
}
|
|
5688
|
+
if (Array.isArray(value))
|
|
5689
|
+
return ["a", value.map(encodeValue)];
|
|
5690
|
+
if (isPlainObject(value)) {
|
|
5691
|
+
const record = value;
|
|
5692
|
+
const members = Object.keys(record).sort().map((k) => [k, encodeValue(record[k])]);
|
|
5693
|
+
return ["o", members];
|
|
5694
|
+
}
|
|
5695
|
+
return ["q", opaqueToken()];
|
|
5696
|
+
}
|
|
5697
|
+
default:
|
|
5698
|
+
return ["q", opaqueToken()];
|
|
5699
|
+
}
|
|
5700
|
+
}
|
|
5701
|
+
function shortDigest(key) {
|
|
5702
|
+
let hash = 2166136261;
|
|
5703
|
+
for (let i = 0;i < key.length; i++) {
|
|
5704
|
+
hash ^= key.charCodeAt(i);
|
|
5705
|
+
hash = Math.imul(hash, 16777619);
|
|
5706
|
+
}
|
|
5707
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
5708
|
+
}
|
|
5709
|
+
function fingerprintLiveQuery(materialSql, params, pkColumns) {
|
|
5710
|
+
const mode = pkColumns && pkColumns.length === 1 ? "inc" : "full";
|
|
5711
|
+
const key = JSON.stringify({
|
|
5712
|
+
sql: materialSql,
|
|
5713
|
+
params: params.map(encodeValue),
|
|
5714
|
+
pk: pkColumns ? [...pkColumns] : null,
|
|
5715
|
+
mode
|
|
5716
|
+
});
|
|
5717
|
+
return { key, digest: shortDigest(key) };
|
|
5718
|
+
}
|
|
5719
|
+
|
|
5720
|
+
// packages/client/src/worker/live-query-manager.ts
|
|
5721
|
+
var MAX_KEEP_ALIVE_MS = 2147483647;
|
|
5722
|
+
function validateLiveQueryPolicy(policy) {
|
|
5723
|
+
if (policy == null)
|
|
5724
|
+
return;
|
|
5725
|
+
const ms = (name, value) => {
|
|
5726
|
+
if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
|
|
5727
|
+
throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a finite number >= 0 (got ${value})`);
|
|
5728
|
+
}
|
|
5729
|
+
if (value !== undefined && value > MAX_KEEP_ALIVE_MS) {
|
|
5730
|
+
throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${value})`);
|
|
5731
|
+
}
|
|
5732
|
+
};
|
|
5733
|
+
const int = (name, value) => {
|
|
5734
|
+
if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
|
|
5735
|
+
throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a non-negative integer (got ${value})`);
|
|
5736
|
+
}
|
|
5737
|
+
};
|
|
5738
|
+
ms("defaultKeepAliveMs", policy.defaultKeepAliveMs);
|
|
5739
|
+
int("maxRetainedQueries", policy.maxRetainedQueries);
|
|
5740
|
+
int("maxRetainedRows", policy.maxRetainedRows);
|
|
5741
|
+
}
|
|
5742
|
+
function createLiveQueryManager(deps) {
|
|
5743
|
+
validateLiveQueryPolicy(deps.policy);
|
|
5744
|
+
const { live } = deps;
|
|
5745
|
+
const policy = {
|
|
5746
|
+
defaultKeepAliveMs: deps.policy?.defaultKeepAliveMs ?? 0,
|
|
5747
|
+
maxRetainedQueries: deps.policy?.maxRetainedQueries ?? 16,
|
|
5748
|
+
maxRetainedRows: deps.policy?.maxRetainedRows ?? 50000
|
|
5749
|
+
};
|
|
5750
|
+
const now2 = deps.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
5751
|
+
const setTimer = deps.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
|
|
5752
|
+
const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
|
|
5753
|
+
const pendingTeardowns = new Set;
|
|
5754
|
+
const entries = new Map;
|
|
5755
|
+
const retained = new Set;
|
|
5756
|
+
const setups = new Set;
|
|
5757
|
+
let dedupHits = 0;
|
|
5758
|
+
let disposed = false;
|
|
5759
|
+
const createEntry = (key, digest, spec) => {
|
|
5760
|
+
const entry = {
|
|
5761
|
+
key,
|
|
5762
|
+
digest,
|
|
5763
|
+
subscribers: new Map,
|
|
5764
|
+
torn: false,
|
|
5765
|
+
generationKeepAliveMs: 0,
|
|
5766
|
+
createdAt: now2(),
|
|
5767
|
+
dedupHits: 0,
|
|
5768
|
+
refreshCount: 0,
|
|
5769
|
+
refreshTotalMs: 0,
|
|
5770
|
+
refreshMaxMs: 0,
|
|
5771
|
+
teardownPending: false,
|
|
5772
|
+
setup: undefined
|
|
5773
|
+
};
|
|
5774
|
+
entry.setup = (async () => {
|
|
5775
|
+
const setupStartedAt = now2();
|
|
5776
|
+
const { materialSql, params, pkColumns } = spec;
|
|
5777
|
+
const registered = pkColumns && pkColumns.length === 1 ? await live.incrementalQuery(materialSql, params, pkColumns[0]) : await live.query(materialSql, params);
|
|
5778
|
+
const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
|
|
5779
|
+
const listener = (results) => {
|
|
5780
|
+
const diff = computeLiveDiff(state, results.rows);
|
|
5781
|
+
for (const record of entry.subscribers.values()) {
|
|
5782
|
+
try {
|
|
5783
|
+
record.subscriber.deliverDiff(diff);
|
|
5784
|
+
} catch {
|
|
5785
|
+
syncDebug("live-query subscriber-error", { digest: entry.digest });
|
|
5786
|
+
}
|
|
5787
|
+
}
|
|
5788
|
+
if (retained.has(entry))
|
|
5789
|
+
queueMicrotask(() => enforceBudgets());
|
|
5790
|
+
};
|
|
5791
|
+
registered.subscribe(listener);
|
|
5792
|
+
entry.registered = registered;
|
|
5793
|
+
entry.state = state;
|
|
5794
|
+
entry.listener = listener;
|
|
5795
|
+
entry.setupMs = now2() - setupStartedAt;
|
|
5796
|
+
syncDebug("live-query register", { digest, setupMs: Math.round(entry.setupMs) });
|
|
5797
|
+
})();
|
|
5798
|
+
entry.setup.catch(() => {
|
|
5799
|
+
if (entries.get(key) === entry)
|
|
5800
|
+
entries.delete(key);
|
|
5801
|
+
});
|
|
5802
|
+
return entry;
|
|
5803
|
+
};
|
|
5804
|
+
const tearDownEntry = (entry) => {
|
|
5805
|
+
if (entry.torn)
|
|
5806
|
+
return entry.teardown ?? Promise.resolve();
|
|
5807
|
+
entry.torn = true;
|
|
5808
|
+
entry.teardownPending = true;
|
|
5809
|
+
const teardown = (async () => {
|
|
5810
|
+
await entry.setup.catch(() => {});
|
|
5811
|
+
if (entry.registered && entry.listener)
|
|
5812
|
+
await entry.registered.unsubscribe(entry.listener);
|
|
5813
|
+
})().catch(() => {
|
|
5814
|
+
syncDebug("live-query teardown-failed", { digest: entry.digest });
|
|
5815
|
+
}).finally(() => {
|
|
5816
|
+
entry.teardownPending = false;
|
|
5817
|
+
if (entries.get(entry.key) === entry)
|
|
5818
|
+
entries.delete(entry.key);
|
|
5819
|
+
syncDebug("live-query teardown-complete", { digest: entry.digest });
|
|
5820
|
+
});
|
|
5821
|
+
entry.teardown = teardown;
|
|
5822
|
+
pendingTeardowns.add(teardown);
|
|
5823
|
+
teardown.finally(() => pendingTeardowns.delete(teardown));
|
|
5824
|
+
return teardown;
|
|
5825
|
+
};
|
|
5826
|
+
const cancelEviction = (entry) => {
|
|
5827
|
+
if (entry.evictionTimer !== undefined) {
|
|
5828
|
+
clearTimer(entry.evictionTimer);
|
|
5829
|
+
entry.evictionTimer = undefined;
|
|
5830
|
+
}
|
|
5831
|
+
retained.delete(entry);
|
|
5832
|
+
};
|
|
5833
|
+
const retainedRowTotal = () => {
|
|
5834
|
+
let total = 0;
|
|
5835
|
+
for (const entry of retained)
|
|
5836
|
+
total += entry.state?.previous.size ?? 0;
|
|
5837
|
+
return total;
|
|
5838
|
+
};
|
|
5839
|
+
const enforceBudgets = () => {
|
|
5840
|
+
if (disposed)
|
|
5841
|
+
return;
|
|
5842
|
+
while (retained.size > policy.maxRetainedQueries || retainedRowTotal() > policy.maxRetainedRows) {
|
|
5843
|
+
const reason = retained.size > policy.maxRetainedQueries ? "count-budget" : "row-budget";
|
|
5844
|
+
let victim;
|
|
5845
|
+
for (const entry of retained) {
|
|
5846
|
+
if (victim === undefined || (entry.lastUsedAt ?? 0) < (victim.lastUsedAt ?? 0))
|
|
5847
|
+
victim = entry;
|
|
5848
|
+
}
|
|
5849
|
+
if (victim === undefined)
|
|
5850
|
+
break;
|
|
5851
|
+
cancelEviction(victim);
|
|
5852
|
+
syncDebug("live-query evicted", { digest: victim.digest, reason });
|
|
5853
|
+
tearDownEntry(victim);
|
|
5854
|
+
}
|
|
5855
|
+
};
|
|
5856
|
+
const onEvictionTimer = (entry) => {
|
|
5857
|
+
entry.evictionTimer = undefined;
|
|
5858
|
+
if (entry.torn || !retained.has(entry) || entry.subscribers.size > 0)
|
|
5859
|
+
return;
|
|
5860
|
+
retained.delete(entry);
|
|
5861
|
+
syncDebug("live-query evicted", { digest: entry.digest, reason: "expiry" });
|
|
5862
|
+
tearDownEntry(entry);
|
|
5863
|
+
};
|
|
5864
|
+
const removeSubscriber = (entry, token) => {
|
|
5865
|
+
if (!entry.subscribers.has(token))
|
|
5866
|
+
return entry.teardown ?? Promise.resolve();
|
|
5867
|
+
entry.subscribers.delete(token);
|
|
5868
|
+
if (entry.subscribers.size > 0)
|
|
5869
|
+
return Promise.resolve();
|
|
5870
|
+
const effective = Math.max(policy.defaultKeepAliveMs, entry.generationKeepAliveMs);
|
|
5871
|
+
if (effective <= 0 || disposed || entry.torn)
|
|
5872
|
+
return tearDownEntry(entry);
|
|
5873
|
+
entry.lastUsedAt = now2();
|
|
5874
|
+
retained.add(entry);
|
|
5875
|
+
entry.evictionTimer = setTimer(() => onEvictionTimer(entry), effective);
|
|
5876
|
+
syncDebug("live-query retained", { digest: entry.digest, keepAliveMs: effective });
|
|
5877
|
+
enforceBudgets();
|
|
5878
|
+
return Promise.resolve();
|
|
5879
|
+
};
|
|
5880
|
+
const refreshEntry = (entry) => {
|
|
5881
|
+
if (entry.torn || !entry.registered)
|
|
5882
|
+
return Promise.resolve();
|
|
5883
|
+
if (entry.refreshInFlight === undefined) {
|
|
5884
|
+
const startedAt = now2();
|
|
5885
|
+
entry.refreshInFlight = entry.registered.refresh().finally(() => {
|
|
5886
|
+
const ms = now2() - startedAt;
|
|
5887
|
+
entry.refreshCount++;
|
|
5888
|
+
entry.refreshLastMs = ms;
|
|
5889
|
+
entry.refreshTotalMs += ms;
|
|
5890
|
+
if (ms > entry.refreshMaxMs)
|
|
5891
|
+
entry.refreshMaxMs = ms;
|
|
5892
|
+
delete entry.refreshInFlight;
|
|
5893
|
+
});
|
|
5894
|
+
}
|
|
5895
|
+
return entry.refreshInFlight;
|
|
5896
|
+
};
|
|
5897
|
+
const subscribe = async (spec, subscriber, opts) => {
|
|
5898
|
+
if (disposed)
|
|
5899
|
+
throw new Error("[pgxsinkit] live-query subscribe after dispose \u2014 the engine is closing");
|
|
5900
|
+
const hint = opts?.keepAliveMs;
|
|
5901
|
+
if (hint !== undefined && (!Number.isFinite(hint) || hint < 0)) {
|
|
5902
|
+
throw new TypeError(`[pgxsinkit] keepAliveMs must be a finite number >= 0 (got ${hint})`);
|
|
5903
|
+
}
|
|
5904
|
+
if (hint !== undefined && hint > MAX_KEEP_ALIVE_MS) {
|
|
5905
|
+
throw new TypeError(`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`);
|
|
5906
|
+
}
|
|
5907
|
+
const keepAliveMs = hint ?? 0;
|
|
5908
|
+
const scope = opts?.scope;
|
|
5909
|
+
let markSetupDone;
|
|
5910
|
+
const setupDone = new Promise((resolve) => {
|
|
5911
|
+
markSetupDone = resolve;
|
|
5912
|
+
});
|
|
5913
|
+
setups.add(setupDone);
|
|
5914
|
+
try {
|
|
5915
|
+
const { key, digest } = fingerprintLiveQuery(spec.materialSql, spec.params, spec.pkColumns);
|
|
5916
|
+
let entry = entries.get(key);
|
|
5917
|
+
while (entry && entry.torn) {
|
|
5918
|
+
await entry.teardown;
|
|
5919
|
+
entry = entries.get(key);
|
|
5920
|
+
}
|
|
5921
|
+
if (entry && retained.has(entry))
|
|
5922
|
+
cancelEviction(entry);
|
|
5923
|
+
const isDedupHit = entry != null;
|
|
5924
|
+
if (!entry) {
|
|
5925
|
+
entry = createEntry(key, digest, spec);
|
|
5926
|
+
entries.set(key, entry);
|
|
5927
|
+
}
|
|
5928
|
+
const joined = entry;
|
|
5929
|
+
if (isDedupHit) {
|
|
5930
|
+
dedupHits++;
|
|
5931
|
+
joined.dedupHits++;
|
|
5932
|
+
syncDebug("live-query dedup-hit", { digest: joined.digest, dedupHits });
|
|
5933
|
+
}
|
|
5934
|
+
await joined.setup;
|
|
5935
|
+
const firstOfGeneration = joined.subscribers.size === 0;
|
|
5936
|
+
joined.generationKeepAliveMs = firstOfGeneration ? keepAliveMs : Math.max(joined.generationKeepAliveMs, keepAliveMs);
|
|
5937
|
+
const token = Symbol("live-subscriber");
|
|
5938
|
+
const snapshot2 = [...joined.state.previous.values()];
|
|
5939
|
+
joined.subscribers.set(token, { subscriber, keepAliveMs, scope });
|
|
5940
|
+
try {
|
|
5941
|
+
subscriber.deliverInitial(snapshot2);
|
|
5942
|
+
} catch (error) {
|
|
5943
|
+
joined.subscribers.delete(token);
|
|
5944
|
+
if (joined.subscribers.size === 0)
|
|
5945
|
+
tearDownEntry(joined);
|
|
5946
|
+
throw error;
|
|
5947
|
+
}
|
|
5948
|
+
return {
|
|
5949
|
+
unsubscribe: () => removeSubscriber(joined, token),
|
|
5950
|
+
refresh: () => refreshEntry(joined)
|
|
5951
|
+
};
|
|
5952
|
+
} finally {
|
|
5953
|
+
setups.delete(setupDone);
|
|
5954
|
+
markSetupDone();
|
|
5955
|
+
}
|
|
5956
|
+
};
|
|
5957
|
+
const dispose = async () => {
|
|
5958
|
+
disposed = true;
|
|
5959
|
+
for (const entry of entries.values()) {
|
|
5960
|
+
if (entry.evictionTimer !== undefined) {
|
|
5961
|
+
clearTimer(entry.evictionTimer);
|
|
5962
|
+
entry.evictionTimer = undefined;
|
|
5963
|
+
}
|
|
5964
|
+
}
|
|
5965
|
+
retained.clear();
|
|
5966
|
+
while (setups.size > 0 || entries.size > 0 || pendingTeardowns.size > 0) {
|
|
5967
|
+
await Promise.allSettled([...setups]);
|
|
5968
|
+
for (const entry of entries.values())
|
|
5969
|
+
tearDownEntry(entry);
|
|
5970
|
+
await Promise.allSettled([...pendingTeardowns]);
|
|
5971
|
+
}
|
|
5972
|
+
};
|
|
5973
|
+
const snapshot = () => {
|
|
5974
|
+
const records = [];
|
|
5975
|
+
for (const entry of entries.values()) {
|
|
5976
|
+
const isRetained = retained.has(entry);
|
|
5977
|
+
const scopes = new Set;
|
|
5978
|
+
for (const { scope } of entry.subscribers.values())
|
|
5979
|
+
scopes.add(scope);
|
|
5980
|
+
records.push({
|
|
5981
|
+
digest: entry.digest,
|
|
5982
|
+
subscriberCount: entry.subscribers.size,
|
|
5983
|
+
scopeCount: scopes.size,
|
|
5984
|
+
rowCount: entry.state?.previous.size ?? 0,
|
|
5985
|
+
retained: isRetained,
|
|
5986
|
+
dedupHits: entry.dedupHits,
|
|
5987
|
+
createdAt: entry.createdAt,
|
|
5988
|
+
setupMs: entry.setupMs ?? null,
|
|
5989
|
+
refresh: {
|
|
5990
|
+
count: entry.refreshCount,
|
|
5991
|
+
lastMs: entry.refreshLastMs ?? null,
|
|
5992
|
+
totalMs: entry.refreshTotalMs,
|
|
5993
|
+
maxMs: entry.refreshMaxMs
|
|
5994
|
+
},
|
|
5995
|
+
lastUsedAt: entry.lastUsedAt ?? null,
|
|
5996
|
+
retainedSinceMs: isRetained && entry.lastUsedAt != null ? Math.max(0, now2() - entry.lastUsedAt) : null,
|
|
5997
|
+
teardownPending: entry.teardownPending
|
|
5998
|
+
});
|
|
5999
|
+
}
|
|
6000
|
+
return records;
|
|
6001
|
+
};
|
|
6002
|
+
return { subscribe, dispose, snapshot };
|
|
6003
|
+
}
|
|
5229
6004
|
// packages/client/src/worker/protocol.ts
|
|
5230
6005
|
var BRIDGE_CHANNEL = "pgxsinkit-bridge";
|
|
5231
6006
|
var BRIDGE_PROTOCOL_VERSION = 1;
|
|
@@ -5267,10 +6042,17 @@ async function attachSyncClient(options) {
|
|
|
5267
6042
|
const initialPending = new Map;
|
|
5268
6043
|
const diffHandlers = new Map;
|
|
5269
6044
|
const hydratedPending = new Map;
|
|
6045
|
+
let detached = false;
|
|
6046
|
+
const detachError = () => new Error("[pgxsinkit] client detached \u2014 the tab released its worker attachment");
|
|
5270
6047
|
const status = { phase: "booting", isRunning: false };
|
|
5271
6048
|
let resolveReady;
|
|
5272
|
-
|
|
6049
|
+
let rejectReady;
|
|
6050
|
+
const ready = new Promise((resolve, reject) => {
|
|
5273
6051
|
resolveReady = resolve;
|
|
6052
|
+
rejectReady = reject;
|
|
6053
|
+
});
|
|
6054
|
+
ready.catch(() => {
|
|
6055
|
+
return;
|
|
5274
6056
|
});
|
|
5275
6057
|
let readyResolved = false;
|
|
5276
6058
|
const readyGroups = new Set;
|
|
@@ -5315,6 +6097,20 @@ async function attachSyncClient(options) {
|
|
|
5315
6097
|
markGroupReady(event.groupKey);
|
|
5316
6098
|
break;
|
|
5317
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
|
+
}
|
|
5318
6114
|
case "conflict":
|
|
5319
6115
|
options.onConflict?.(event.details);
|
|
5320
6116
|
break;
|
|
@@ -5362,6 +6158,15 @@ async function attachSyncClient(options) {
|
|
|
5362
6158
|
} else {
|
|
5363
6159
|
if (ack.engineReady)
|
|
5364
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));
|
|
5365
6170
|
attachAckResolve?.(ack);
|
|
5366
6171
|
}
|
|
5367
6172
|
break;
|
|
@@ -5423,6 +6228,8 @@ async function attachSyncClient(options) {
|
|
|
5423
6228
|
port.addEventListener("message", listener);
|
|
5424
6229
|
port.start?.();
|
|
5425
6230
|
const rpc = (op, args) => {
|
|
6231
|
+
if (detached)
|
|
6232
|
+
return Promise.reject(detachError());
|
|
5426
6233
|
const id = newId("rpc");
|
|
5427
6234
|
return new Promise((resolve, reject) => {
|
|
5428
6235
|
rpcPending.set(id, { resolve, reject });
|
|
@@ -5435,6 +6242,99 @@ async function attachSyncClient(options) {
|
|
|
5435
6242
|
attachAckResolve = resolve;
|
|
5436
6243
|
attachAckReject = reject;
|
|
5437
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
|
+
};
|
|
6296
|
+
const detachFromWorker = () => {
|
|
6297
|
+
if (detached)
|
|
6298
|
+
return;
|
|
6299
|
+
detached = true;
|
|
6300
|
+
status.isRunning = false;
|
|
6301
|
+
for (const queryId of diffHandlers.keys())
|
|
6302
|
+
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
6303
|
+
diffHandlers.clear();
|
|
6304
|
+
postBridgeMessage(port, codec, "detach", null);
|
|
6305
|
+
attachAckReject?.(detachError());
|
|
6306
|
+
const disposedError = new ClientDisposedError;
|
|
6307
|
+
failWriteReady(disposedError);
|
|
6308
|
+
failBootSettled(disposedError);
|
|
6309
|
+
if (!readyResolved) {
|
|
6310
|
+
readyResolved = true;
|
|
6311
|
+
rejectReady(disposedError);
|
|
6312
|
+
}
|
|
6313
|
+
for (const pending of rpcPending.values())
|
|
6314
|
+
pending.reject(detachError());
|
|
6315
|
+
rpcPending.clear();
|
|
6316
|
+
for (const pending of initialPending.values())
|
|
6317
|
+
pending.reject(detachError());
|
|
6318
|
+
initialPending.clear();
|
|
6319
|
+
for (const resolve of hydratedPending.values())
|
|
6320
|
+
resolve();
|
|
6321
|
+
hydratedPending.clear();
|
|
6322
|
+
for (const waiters of groupWaiters.values())
|
|
6323
|
+
for (const resolve of waiters)
|
|
6324
|
+
resolve();
|
|
6325
|
+
groupWaiters.clear();
|
|
6326
|
+
if (pagehideListener)
|
|
6327
|
+
pageWindow?.removeEventListener("pagehide", pagehideListener);
|
|
6328
|
+
port.removeEventListener("message", listener);
|
|
6329
|
+
port.close?.();
|
|
6330
|
+
};
|
|
6331
|
+
const pageWindow = globalThis.window;
|
|
6332
|
+
const pagehideListener = pageWindow ? (event) => {
|
|
6333
|
+
if (!event.persisted)
|
|
6334
|
+
detachFromWorker();
|
|
6335
|
+
} : undefined;
|
|
6336
|
+
if (pagehideListener)
|
|
6337
|
+
pageWindow?.addEventListener("pagehide", pagehideListener);
|
|
5438
6338
|
const initialToken = options.getToken ? await options.getToken() : null;
|
|
5439
6339
|
const memoryOverride = readTestStoreMarker(options) === "memory";
|
|
5440
6340
|
const restoreWire = options.restoreFrom ? {
|
|
@@ -5460,11 +6360,13 @@ async function attachSyncClient(options) {
|
|
|
5460
6360
|
try {
|
|
5461
6361
|
await attachAck;
|
|
5462
6362
|
} catch (error) {
|
|
5463
|
-
|
|
6363
|
+
detachFromWorker();
|
|
5464
6364
|
throw error;
|
|
5465
6365
|
}
|
|
5466
6366
|
status.isRunning = true;
|
|
5467
6367
|
const subscribeLiveRows = async (input, onRows) => {
|
|
6368
|
+
if (detached)
|
|
6369
|
+
throw detachError();
|
|
5468
6370
|
const queryId = newId("live");
|
|
5469
6371
|
const id = newId("sub");
|
|
5470
6372
|
const materializer = new LiveRowsMaterializer(input.pkColumns);
|
|
@@ -5481,7 +6383,8 @@ async function attachSyncClient(options) {
|
|
|
5481
6383
|
params: [...input.params],
|
|
5482
6384
|
...input.fields ? { fields: [...input.fields] } : {},
|
|
5483
6385
|
...input.pkColumns ? { pkColumns: [...input.pkColumns] } : {},
|
|
5484
|
-
...input.use ? { use: [...input.use] } : {}
|
|
6386
|
+
...input.use ? { use: [...input.use] } : {},
|
|
6387
|
+
...input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}
|
|
5485
6388
|
}, id);
|
|
5486
6389
|
});
|
|
5487
6390
|
} catch (error) {
|
|
@@ -5507,7 +6410,7 @@ async function attachSyncClient(options) {
|
|
|
5507
6410
|
...hydrated ? { hydrated } : {}
|
|
5508
6411
|
};
|
|
5509
6412
|
};
|
|
5510
|
-
const { drizzle:
|
|
6413
|
+
const { drizzle: drizzle5, views } = buildRegistryReadHandles(options.registry);
|
|
5511
6414
|
const notSupported = (name) => () => {
|
|
5512
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.`);
|
|
5513
6416
|
};
|
|
@@ -5516,7 +6419,7 @@ async function attachSyncClient(options) {
|
|
|
5516
6419
|
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
5517
6420
|
};
|
|
5518
6421
|
const client = {
|
|
5519
|
-
drizzle:
|
|
6422
|
+
drizzle: drizzle5,
|
|
5520
6423
|
views,
|
|
5521
6424
|
pglite: new Proxy({}, {
|
|
5522
6425
|
get: notSupported("client.pglite")
|
|
@@ -5531,19 +6434,16 @@ async function attachSyncClient(options) {
|
|
|
5531
6434
|
delete: (entityKey) => rpc("delete", [tableKey, entityKey])
|
|
5532
6435
|
}
|
|
5533
6436
|
])),
|
|
6437
|
+
localReadReady,
|
|
6438
|
+
writeReady,
|
|
6439
|
+
bootSettled,
|
|
5534
6440
|
ready,
|
|
5535
6441
|
status,
|
|
5536
6442
|
start: async () => {
|
|
5537
6443
|
await ready;
|
|
5538
6444
|
},
|
|
5539
6445
|
stop: async () => {
|
|
5540
|
-
|
|
5541
|
-
for (const queryId of diffHandlers.keys())
|
|
5542
|
-
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
5543
|
-
diffHandlers.clear();
|
|
5544
|
-
postBridgeMessage(port, codec, "detach", null);
|
|
5545
|
-
port.removeEventListener("message", listener);
|
|
5546
|
-
port.close?.();
|
|
6446
|
+
detachFromWorker();
|
|
5547
6447
|
},
|
|
5548
6448
|
destroy: notSupported("client.destroy"),
|
|
5549
6449
|
dropReadCache: notSupported("client.dropReadCache"),
|
|
@@ -5552,8 +6452,8 @@ async function attachSyncClient(options) {
|
|
|
5552
6452
|
retryFailed: (table) => rpc("retryFailed", [table]),
|
|
5553
6453
|
recoverSending: (table) => rpc("recoverSending", [table]),
|
|
5554
6454
|
readMutationDetails: (table) => rpc("readMutationDetails", [table]),
|
|
5555
|
-
rawQuery: (
|
|
5556
|
-
rawExec: (
|
|
6455
|
+
rawQuery: (sql7, params, options2) => rpc("rawQuery", [sql7, params, options2]),
|
|
6456
|
+
rawExec: (sql7, options2) => rpc("rawExec", [sql7, options2]),
|
|
5557
6457
|
mutate: {
|
|
5558
6458
|
create: (table, input) => rpc("create", [table, input]),
|
|
5559
6459
|
update: (table, entityKey, patch) => rpc("update", [table, entityKey, patch]),
|
|
@@ -5563,6 +6463,11 @@ async function attachSyncClient(options) {
|
|
|
5563
6463
|
discardConflict: (table, entityKey) => rpc("discardConflict", [table, entityKey]),
|
|
5564
6464
|
discardQuarantined: (table, entityKey) => rpc("discardQuarantined", [table, entityKey]),
|
|
5565
6465
|
diagnostics: (table) => rpc("diagnostics", [table]),
|
|
6466
|
+
mutations: createMutationsApi({
|
|
6467
|
+
registry: options.registry,
|
|
6468
|
+
subscribeLiveRows,
|
|
6469
|
+
query: (sql7, params) => rpc("rawQuery", [sql7, params])
|
|
6470
|
+
}),
|
|
5566
6471
|
query: notSupported("client.query"),
|
|
5567
6472
|
queryRow: notSupported("client.queryRow"),
|
|
5568
6473
|
queryRaw: notSupported("client.queryRaw"),
|
|
@@ -5604,6 +6509,8 @@ async function attachSyncClient(options) {
|
|
|
5604
6509
|
return rpc("transaction", [{ mode, items: collected }]);
|
|
5605
6510
|
},
|
|
5606
6511
|
groupReady: async (table) => {
|
|
6512
|
+
if (detached)
|
|
6513
|
+
throw detachError();
|
|
5607
6514
|
const groupKey = groupKeyForTable(table);
|
|
5608
6515
|
if (groupKey == null || readyGroups.has(groupKey))
|
|
5609
6516
|
return;
|
|
@@ -5615,6 +6522,7 @@ async function attachSyncClient(options) {
|
|
|
5615
6522
|
},
|
|
5616
6523
|
subscribeLiveRows,
|
|
5617
6524
|
bootReport: () => rpc("bootReport", []),
|
|
6525
|
+
liveQueryDiagnostics: () => rpc("liveQueryDiagnostics", []),
|
|
5618
6526
|
exportStore: async (exportOptions) => {
|
|
5619
6527
|
const wire = await rpc("exportStore", [exportOptions]);
|
|
5620
6528
|
return {
|
|
@@ -5746,6 +6654,7 @@ function createWorkerTokenCache(options) {
|
|
|
5746
6654
|
|
|
5747
6655
|
// packages/client/src/worker/define-sync-worker.ts
|
|
5748
6656
|
function defineSyncWorker(options) {
|
|
6657
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
5749
6658
|
const codec = options.codec ?? identityCodec;
|
|
5750
6659
|
const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30000;
|
|
5751
6660
|
const convergenceIntervalMs = options.convergenceIntervalMs ?? 15000;
|
|
@@ -5753,6 +6662,24 @@ function defineSyncWorker(options) {
|
|
|
5753
6662
|
const workerTestMarker = readTestStoreMarker(options);
|
|
5754
6663
|
const ports = new Set;
|
|
5755
6664
|
const liveSubs = new Map;
|
|
6665
|
+
let liveManager = null;
|
|
6666
|
+
const ensureLiveManager = (active) => liveManager ??= createLiveQueryManager({
|
|
6667
|
+
live: active.pglite.live,
|
|
6668
|
+
...options.liveQueries ? { policy: options.liveQueries } : {}
|
|
6669
|
+
});
|
|
6670
|
+
const pendingSubscribes = new Map;
|
|
6671
|
+
let closing = false;
|
|
6672
|
+
const inFlightSubscribes = new Set;
|
|
6673
|
+
const portScopes = new WeakMap;
|
|
6674
|
+
let nextScopeId = 0;
|
|
6675
|
+
const scopeForPort = (port) => {
|
|
6676
|
+
let scope = portScopes.get(port);
|
|
6677
|
+
if (scope === undefined) {
|
|
6678
|
+
scope = `port-${nextScopeId++}`;
|
|
6679
|
+
portScopes.set(port, scope);
|
|
6680
|
+
}
|
|
6681
|
+
return scope;
|
|
6682
|
+
};
|
|
5756
6683
|
let provisioned = null;
|
|
5757
6684
|
let convergenceSuppressed = false;
|
|
5758
6685
|
let fireConvergence = null;
|
|
@@ -5828,6 +6755,28 @@ function defineSyncWorker(options) {
|
|
|
5828
6755
|
const bootedPromise = new Promise((resolve) => {
|
|
5829
6756
|
resolveBooted = resolve;
|
|
5830
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
|
+
});
|
|
5831
6780
|
const boot = (attach) => {
|
|
5832
6781
|
if (bootPromise)
|
|
5833
6782
|
return bootPromise;
|
|
@@ -5930,6 +6879,8 @@ function defineSyncWorker(options) {
|
|
|
5930
6879
|
return active.rawExec(args[0], args[1]);
|
|
5931
6880
|
case "bootReport":
|
|
5932
6881
|
return active.bootReport();
|
|
6882
|
+
case "liveQueryDiagnostics":
|
|
6883
|
+
return liveManager?.snapshot() ?? [];
|
|
5933
6884
|
case "exportStore": {
|
|
5934
6885
|
const { file, report } = await active.exportStore(args[0]);
|
|
5935
6886
|
const buffer = await file.arrayBuffer();
|
|
@@ -5951,38 +6902,62 @@ function defineSyncWorker(options) {
|
|
|
5951
6902
|
}
|
|
5952
6903
|
}
|
|
5953
6904
|
};
|
|
5954
|
-
const
|
|
6905
|
+
const subKeyFor = (port, queryId) => `${scopeForPort(port)}:${queryId}`;
|
|
6906
|
+
const handleSubscribe = (port, id, payload) => {
|
|
6907
|
+
const pending = { port, cancelled: false };
|
|
6908
|
+
const subKey = subKeyFor(port, payload.queryId);
|
|
6909
|
+
pendingSubscribes.set(subKey, pending);
|
|
6910
|
+
let task;
|
|
6911
|
+
task = (async () => {
|
|
6912
|
+
try {
|
|
6913
|
+
await handleSubscribeInner(port, id, payload, pending, subKey);
|
|
6914
|
+
} finally {
|
|
6915
|
+
pendingSubscribes.delete(subKey);
|
|
6916
|
+
inFlightSubscribes.delete(task);
|
|
6917
|
+
}
|
|
6918
|
+
})();
|
|
6919
|
+
inFlightSubscribes.add(task);
|
|
6920
|
+
return task;
|
|
6921
|
+
};
|
|
6922
|
+
const handleSubscribeInner = async (port, id, payload, pending, subKey) => {
|
|
5955
6923
|
const active = client ?? await bootPromise;
|
|
5956
6924
|
if (!active)
|
|
5957
6925
|
throw new Error("subscribe before attach");
|
|
5958
|
-
const { queryId, sql:
|
|
5959
|
-
const prepared = await active.prepareQuery({ sql:
|
|
5960
|
-
const hydratingTables = active.hydratingTablesFor({ sql:
|
|
5961
|
-
const
|
|
5962
|
-
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
|
|
5973
|
-
|
|
5974
|
-
|
|
5975
|
-
|
|
5976
|
-
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
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);
|
|
6930
|
+
if (closing || pending.cancelled || !ports.has(port)) {
|
|
6931
|
+
postBridgeMessage(port, codec, "rpc-result", {
|
|
6932
|
+
ok: false,
|
|
6933
|
+
error: { message: "[pgxsinkit] subscribe cancelled \u2014 the worker is closing or the port detached" }
|
|
6934
|
+
}, id);
|
|
6935
|
+
return;
|
|
6936
|
+
}
|
|
6937
|
+
const subscription = await ensureLiveManager(active).subscribe({ materialSql, params, ...pkColumns ? { pkColumns } : {} }, {
|
|
6938
|
+
deliverInitial: (rows) => {
|
|
6939
|
+
postBridgeMessage(port, codec, "live-initial", {
|
|
6940
|
+
queryId,
|
|
6941
|
+
rows,
|
|
6942
|
+
...prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {},
|
|
6943
|
+
...hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}
|
|
6944
|
+
}, id);
|
|
6945
|
+
},
|
|
6946
|
+
deliverDiff: (diff) => {
|
|
6947
|
+
postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
|
|
6948
|
+
}
|
|
6949
|
+
}, { ...keepAliveMs != null ? { keepAliveMs } : {}, scope: scopeForPort(port) });
|
|
6950
|
+
if (closing || pending.cancelled || !ports.has(port)) {
|
|
6951
|
+
subscription.unsubscribe();
|
|
6952
|
+
return;
|
|
6953
|
+
}
|
|
6954
|
+
liveSubs.set(subKey, { port, subscription });
|
|
5980
6955
|
if (hydratingTables.length > 0) {
|
|
5981
6956
|
Promise.all(hydratingTables.map((key) => active.groupReady(key))).then(async () => {
|
|
5982
|
-
if (!liveSubs.has(
|
|
6957
|
+
if (!liveSubs.has(subKey))
|
|
5983
6958
|
return;
|
|
5984
|
-
await
|
|
5985
|
-
if (!liveSubs.has(
|
|
6959
|
+
await subscription.refresh();
|
|
6960
|
+
if (!liveSubs.has(subKey))
|
|
5986
6961
|
return;
|
|
5987
6962
|
postBridgeMessage(port, codec, "live-hydrated", { queryId });
|
|
5988
6963
|
}).catch(() => {
|
|
@@ -6065,14 +7040,22 @@ function defineSyncWorker(options) {
|
|
|
6065
7040
|
boot(attach).then((booted) => {
|
|
6066
7041
|
client = booted;
|
|
6067
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
|
+
}
|
|
6068
7048
|
if (!engineReadyFired) {
|
|
6069
7049
|
booted.ready.then(() => {
|
|
6070
7050
|
engineReadyFired = true;
|
|
7051
|
+
}, () => {
|
|
7052
|
+
return;
|
|
6071
7053
|
});
|
|
6072
7054
|
}
|
|
6073
7055
|
postBridgeMessage(port, codec, "attach-ack", {
|
|
6074
7056
|
alreadyBooted,
|
|
6075
|
-
...engineReadyFired ? { engineReady: true } : {}
|
|
7057
|
+
...engineReadyFired ? { engineReady: true } : {},
|
|
7058
|
+
...milestoneAckFields()
|
|
6076
7059
|
});
|
|
6077
7060
|
postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
|
|
6078
7061
|
}, (error) => {
|
|
@@ -6119,10 +7102,15 @@ function defineSyncWorker(options) {
|
|
|
6119
7102
|
}
|
|
6120
7103
|
case "unsubscribe": {
|
|
6121
7104
|
const { queryId } = payload;
|
|
6122
|
-
const
|
|
7105
|
+
const subKey = subKeyFor(port, queryId);
|
|
7106
|
+
const sub = liveSubs.get(subKey);
|
|
6123
7107
|
if (sub) {
|
|
6124
|
-
sub.unsubscribe();
|
|
6125
|
-
liveSubs.delete(
|
|
7108
|
+
sub.subscription.unsubscribe();
|
|
7109
|
+
liveSubs.delete(subKey);
|
|
7110
|
+
} else {
|
|
7111
|
+
const inFlight = pendingSubscribes.get(subKey);
|
|
7112
|
+
if (inFlight)
|
|
7113
|
+
inFlight.cancelled = true;
|
|
6126
7114
|
}
|
|
6127
7115
|
break;
|
|
6128
7116
|
}
|
|
@@ -6137,12 +7125,16 @@ function defineSyncWorker(options) {
|
|
|
6137
7125
|
};
|
|
6138
7126
|
const detachPort = (port) => {
|
|
6139
7127
|
ports.delete(port);
|
|
6140
|
-
for (const [
|
|
7128
|
+
for (const [subKey, sub] of liveSubs) {
|
|
6141
7129
|
if (sub.port === port) {
|
|
6142
|
-
sub.unsubscribe();
|
|
6143
|
-
liveSubs.delete(
|
|
7130
|
+
sub.subscription.unsubscribe();
|
|
7131
|
+
liveSubs.delete(subKey);
|
|
6144
7132
|
}
|
|
6145
7133
|
}
|
|
7134
|
+
for (const pending of pendingSubscribes.values()) {
|
|
7135
|
+
if (pending.port === port)
|
|
7136
|
+
pending.cancelled = true;
|
|
7137
|
+
}
|
|
6146
7138
|
};
|
|
6147
7139
|
const connect = (port) => {
|
|
6148
7140
|
ports.add(port);
|
|
@@ -6163,9 +7155,12 @@ function defineSyncWorker(options) {
|
|
|
6163
7155
|
connect,
|
|
6164
7156
|
whenBooted,
|
|
6165
7157
|
close: async () => {
|
|
6166
|
-
|
|
6167
|
-
|
|
7158
|
+
closing = true;
|
|
7159
|
+
for (const pending of pendingSubscribes.values())
|
|
7160
|
+
pending.cancelled = true;
|
|
7161
|
+
await Promise.allSettled([...inFlightSubscribes]);
|
|
6168
7162
|
liveSubs.clear();
|
|
7163
|
+
await liveManager?.dispose();
|
|
6169
7164
|
ports.clear();
|
|
6170
7165
|
setSyncDebugSink(undefined);
|
|
6171
7166
|
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
@@ -6201,6 +7196,19 @@ function bindGlobalScope(connect) {
|
|
|
6201
7196
|
}
|
|
6202
7197
|
}
|
|
6203
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
|
+
}
|
|
6204
7212
|
async function createClientPGlite(store, options) {
|
|
6205
7213
|
const normalised = normaliseStorePathInput(store);
|
|
6206
7214
|
const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);
|
|
@@ -6218,18 +7226,37 @@ async function createClientPGlite(store, options) {
|
|
|
6218
7226
|
}
|
|
6219
7227
|
function replAdapter(client) {
|
|
6220
7228
|
return {
|
|
6221
|
-
query: (
|
|
6222
|
-
exec: (
|
|
7229
|
+
query: (sql7, params, options) => client.rawQuery(sql7, params, options),
|
|
7230
|
+
exec: (sql7, options) => client.rawExec(sql7, options)
|
|
6223
7231
|
};
|
|
6224
7232
|
}
|
|
6225
7233
|
async function createSyncClient(options) {
|
|
7234
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
6226
7235
|
const status = {
|
|
6227
7236
|
phase: "booting",
|
|
6228
7237
|
isRunning: false
|
|
6229
7238
|
};
|
|
6230
7239
|
let resolveReady;
|
|
6231
|
-
|
|
7240
|
+
let rejectReady;
|
|
7241
|
+
const ready = new Promise((resolve, reject) => {
|
|
6232
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;
|
|
6233
7260
|
});
|
|
6234
7261
|
if (options.pgliteInstance && options.precreatedPglite) {
|
|
6235
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).");
|
|
@@ -6246,9 +7273,11 @@ async function createSyncClient(options) {
|
|
|
6246
7273
|
}
|
|
6247
7274
|
const syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
|
|
6248
7275
|
const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
|
|
7276
|
+
const storeKind = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
|
|
6249
7277
|
const bootReportBuilder = createBootReportBuilder({
|
|
6250
7278
|
mode: options.bootMode ?? "in-process",
|
|
6251
7279
|
freshStore: options.freshStore === true,
|
|
7280
|
+
storeKind,
|
|
6252
7281
|
overlapPrefetch,
|
|
6253
7282
|
registryFingerprint: fingerprintRegistry2(options.registry)
|
|
6254
7283
|
});
|
|
@@ -6398,8 +7427,22 @@ async function createSyncClient(options) {
|
|
|
6398
7427
|
const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
|
|
6399
7428
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
6400
7429
|
}
|
|
6401
|
-
|
|
6402
|
-
|
|
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
|
+
});
|
|
6403
7446
|
if (options.prepareLocalDb) {
|
|
6404
7447
|
const prepareLocalDb = options.prepareLocalDb;
|
|
6405
7448
|
await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDb(pglite));
|
|
@@ -6411,6 +7454,7 @@ async function createSyncClient(options) {
|
|
|
6411
7454
|
db: pglite,
|
|
6412
7455
|
registry: options.registry,
|
|
6413
7456
|
writeUrl: options.writeUrl,
|
|
7457
|
+
ownsMetaTable: !options.pgliteInstance,
|
|
6414
7458
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
6415
7459
|
...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
|
|
6416
7460
|
...writePathHeaders ? { requestHeaders: writePathHeaders } : {},
|
|
@@ -6419,45 +7463,103 @@ async function createSyncClient(options) {
|
|
|
6419
7463
|
...options.onConflict ? { onConflict: options.onConflict } : {},
|
|
6420
7464
|
...options.onReject ? { onReject: options.onReject } : {}
|
|
6421
7465
|
});
|
|
6422
|
-
|
|
6423
|
-
if (restoreBoot) {
|
|
6424
|
-
await mutationRuntime.quarantineRecovered();
|
|
6425
|
-
}
|
|
7466
|
+
let pendingActivations = new Set;
|
|
6426
7467
|
let versionEvent = null;
|
|
6427
|
-
|
|
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;
|
|
6428
7475
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () => reconcileLocalStoreVersion({
|
|
6429
7476
|
db: pglite,
|
|
6430
7477
|
registry: options.registry,
|
|
6431
7478
|
runtime: mutationRuntime,
|
|
6432
7479
|
...options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}
|
|
6433
7480
|
}));
|
|
7481
|
+
};
|
|
7482
|
+
if (restoreBoot) {
|
|
7483
|
+
await runBootRecoveryStage();
|
|
7484
|
+
await runReconcileStage();
|
|
7485
|
+
} else {
|
|
7486
|
+
await runReconcileStage();
|
|
6434
7487
|
}
|
|
6435
7488
|
const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
|
|
6436
7489
|
const lazyGuardIndex = buildLazyGuardIndex(options.registry);
|
|
6437
7490
|
let sync = null;
|
|
6438
7491
|
let convergenceDriver = null;
|
|
6439
|
-
|
|
6440
|
-
|
|
6441
|
-
|
|
6442
|
-
|
|
6443
|
-
|
|
6444
|
-
|
|
6445
|
-
|
|
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
|
+
}
|
|
6446
7550
|
} else {
|
|
6447
|
-
|
|
6448
|
-
await resetSubscriptionsIfRequested(pglite, resetKeys);
|
|
6449
|
-
status.phase = "syncing";
|
|
7551
|
+
status.phase = "ready";
|
|
6450
7552
|
options.onStatusChange?.(status);
|
|
6451
|
-
|
|
6452
|
-
|
|
6453
|
-
bootReportBuilder.markSyncStartDone();
|
|
7553
|
+
finalizeBootReport();
|
|
7554
|
+
resolveReady();
|
|
6454
7555
|
}
|
|
6455
|
-
|
|
6456
|
-
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6460
|
-
|
|
7556
|
+
const buffered = pendingActivations;
|
|
7557
|
+
pendingActivations = null;
|
|
7558
|
+
if (sync != null && buffered && buffered.size > 0) {
|
|
7559
|
+
await ensureSynced([...buffered]);
|
|
7560
|
+
}
|
|
7561
|
+
resolveSyncWired();
|
|
7562
|
+
};
|
|
6461
7563
|
if (options.autoSync && !restoreBoot) {
|
|
6462
7564
|
convergenceDriver = createConvergenceDriver({
|
|
6463
7565
|
client: {
|
|
@@ -6467,23 +7569,29 @@ async function createSyncClient(options) {
|
|
|
6467
7569
|
trigger: options.autoSync,
|
|
6468
7570
|
...options.onConvergencePass ? { onPass: options.onConvergencePass } : {}
|
|
6469
7571
|
});
|
|
6470
|
-
ready.then(() => convergenceDriver?.start())
|
|
7572
|
+
ready.then(() => convergenceDriver?.start(), () => {
|
|
7573
|
+
return;
|
|
7574
|
+
});
|
|
6471
7575
|
}
|
|
6472
7576
|
const requestConvergence = () => convergenceDriver?.requestPass();
|
|
6473
7577
|
const mutate = {
|
|
6474
7578
|
create: async (table, input) => {
|
|
7579
|
+
await writeReady;
|
|
6475
7580
|
await mutationRuntime.create(table, input);
|
|
6476
7581
|
requestConvergence();
|
|
6477
7582
|
},
|
|
6478
7583
|
update: async (table, entityKey, patch) => {
|
|
7584
|
+
await writeReady;
|
|
6479
7585
|
await mutationRuntime.update(table, entityKey, patch);
|
|
6480
7586
|
requestConvergence();
|
|
6481
7587
|
},
|
|
6482
7588
|
delete: async (table, entityKey) => {
|
|
7589
|
+
await writeReady;
|
|
6483
7590
|
await mutationRuntime.delete(table, entityKey);
|
|
6484
7591
|
requestConvergence();
|
|
6485
7592
|
},
|
|
6486
7593
|
batch: async (items) => {
|
|
7594
|
+
await writeReady;
|
|
6487
7595
|
await mutationRuntime.batch(items);
|
|
6488
7596
|
requestConvergence();
|
|
6489
7597
|
}
|
|
@@ -6533,8 +7641,16 @@ async function createSyncClient(options) {
|
|
|
6533
7641
|
})();
|
|
6534
7642
|
};
|
|
6535
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
|
+
}
|
|
6536
7652
|
const activeSync = sync;
|
|
6537
|
-
if (activeSync == null
|
|
7653
|
+
if (activeSync == null)
|
|
6538
7654
|
return;
|
|
6539
7655
|
const groupKeys = new Set;
|
|
6540
7656
|
for (const key of keys) {
|
|
@@ -6549,6 +7665,12 @@ async function createSyncClient(options) {
|
|
|
6549
7665
|
await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
|
|
6550
7666
|
};
|
|
6551
7667
|
activateOrdinaryWriteTables = (tables) => {
|
|
7668
|
+
if (sync == null) {
|
|
7669
|
+
if (pendingActivations != null)
|
|
7670
|
+
for (const table of tables)
|
|
7671
|
+
pendingActivations.add(table);
|
|
7672
|
+
return;
|
|
7673
|
+
}
|
|
6552
7674
|
const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table));
|
|
6553
7675
|
if (lazyTables.length === 0)
|
|
6554
7676
|
return;
|
|
@@ -6557,6 +7679,9 @@ async function createSyncClient(options) {
|
|
|
6557
7679
|
});
|
|
6558
7680
|
};
|
|
6559
7681
|
const groupReadyForTable = async (table) => {
|
|
7682
|
+
if (sync == null && isSyncPending()) {
|
|
7683
|
+
await syncWired;
|
|
7684
|
+
}
|
|
6560
7685
|
const activeSync = sync;
|
|
6561
7686
|
if (activeSync == null)
|
|
6562
7687
|
return;
|
|
@@ -6567,15 +7692,16 @@ async function createSyncClient(options) {
|
|
|
6567
7692
|
};
|
|
6568
7693
|
const isGroupReadyForTable = (table) => {
|
|
6569
7694
|
const activeSync = sync;
|
|
6570
|
-
if (activeSync == null)
|
|
6571
|
-
return
|
|
7695
|
+
if (activeSync == null) {
|
|
7696
|
+
return !isSyncPending();
|
|
7697
|
+
}
|
|
6572
7698
|
const groupKey = activeSync.groupKeyForTable(table);
|
|
6573
7699
|
if (groupKey == null)
|
|
6574
7700
|
return true;
|
|
6575
7701
|
return activeSync.isGroupReady(groupKey);
|
|
6576
7702
|
};
|
|
6577
7703
|
const hydratingTablesFor = (query) => {
|
|
6578
|
-
if (sync == null)
|
|
7704
|
+
if (sync == null && !isSyncPending())
|
|
6579
7705
|
return [];
|
|
6580
7706
|
const referenced = new Set(query.use ?? []);
|
|
6581
7707
|
for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex))
|
|
@@ -6584,8 +7710,9 @@ async function createSyncClient(options) {
|
|
|
6584
7710
|
};
|
|
6585
7711
|
const isSynced = (key) => {
|
|
6586
7712
|
const activeSync = sync;
|
|
6587
|
-
if (activeSync == null)
|
|
6588
|
-
return
|
|
7713
|
+
if (activeSync == null) {
|
|
7714
|
+
return !isSyncPending();
|
|
7715
|
+
}
|
|
6589
7716
|
return activeSync.isTableStarted(key);
|
|
6590
7717
|
};
|
|
6591
7718
|
const groupTableKeysFor = (key, entry) => {
|
|
@@ -6617,6 +7744,7 @@ async function createSyncClient(options) {
|
|
|
6617
7744
|
}
|
|
6618
7745
|
};
|
|
6619
7746
|
const desync = async (key) => {
|
|
7747
|
+
await bootSettled;
|
|
6620
7748
|
const entry = options.registry[key];
|
|
6621
7749
|
if (entry == null)
|
|
6622
7750
|
throw new Error(`desync: unknown table ${String(key)}`);
|
|
@@ -6625,21 +7753,25 @@ async function createSyncClient(options) {
|
|
|
6625
7753
|
}
|
|
6626
7754
|
await tearDownLazyGroup(key, entry, "desync");
|
|
6627
7755
|
};
|
|
6628
|
-
const discardEphemeral =
|
|
6629
|
-
|
|
6630
|
-
|
|
6631
|
-
|
|
6632
|
-
|
|
6633
|
-
|
|
6634
|
-
|
|
6635
|
-
|
|
6636
|
-
if ((options.registry[member].retention ?? "persistent") !== "ephemeral") {
|
|
6637
|
-
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.`);
|
|
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.`);
|
|
6638
7764
|
}
|
|
6639
|
-
|
|
6640
|
-
|
|
6641
|
-
|
|
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
|
+
}
|
|
7769
|
+
}
|
|
7770
|
+
await tearDownLazyGroup(key, entry, "discardEphemeral");
|
|
7771
|
+
});
|
|
7772
|
+
};
|
|
6642
7773
|
const transaction = async ({ mode }, run) => {
|
|
7774
|
+
await writeReady;
|
|
6643
7775
|
const collected = [];
|
|
6644
7776
|
const txTables = Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
|
|
6645
7777
|
tableKey,
|
|
@@ -6676,24 +7808,29 @@ async function createSyncClient(options) {
|
|
|
6676
7808
|
}
|
|
6677
7809
|
return await mutationRuntime.flushUnit(unit.id);
|
|
6678
7810
|
};
|
|
6679
|
-
const prepareQuery = async ({ sql:
|
|
7811
|
+
const prepareQuery = async ({ sql: sql7, use }) => {
|
|
6680
7812
|
const toActivate = new Set(use ?? []);
|
|
6681
|
-
for (const key of findReferencedLazyKeysInSql(
|
|
7813
|
+
for (const key of findReferencedLazyKeysInSql(sql7, lazyGuardIndex))
|
|
6682
7814
|
toActivate.add(key);
|
|
6683
7815
|
const lazyTables = [...toActivate];
|
|
6684
7816
|
await ensureSynced(lazyTables);
|
|
6685
7817
|
assertLazyRefsActivated({
|
|
6686
|
-
sql:
|
|
7818
|
+
sql: sql7,
|
|
6687
7819
|
index: lazyGuardIndex,
|
|
6688
7820
|
isActive: (key) => isSynced(key)
|
|
6689
7821
|
});
|
|
6690
7822
|
return { lazyTables };
|
|
6691
7823
|
};
|
|
6692
7824
|
const runGuardedQuery = async (build, use) => {
|
|
7825
|
+
await localReadReady;
|
|
6693
7826
|
const builder = build(client);
|
|
6694
7827
|
await prepareQuery({ sql: builder.toSQL().sql, ...use ? { use } : {} });
|
|
6695
7828
|
return builder;
|
|
6696
7829
|
};
|
|
7830
|
+
const liveManager = createLiveQueryManager({
|
|
7831
|
+
live: pglite.live,
|
|
7832
|
+
...options.liveQueries ? { policy: options.liveQueries } : {}
|
|
7833
|
+
});
|
|
6697
7834
|
const client = {
|
|
6698
7835
|
drizzle: drizzleDb,
|
|
6699
7836
|
pglite,
|
|
@@ -6708,20 +7845,26 @@ async function createSyncClient(options) {
|
|
|
6708
7845
|
delete: (entityKey) => mutate.delete(tableKey, entityKey)
|
|
6709
7846
|
}
|
|
6710
7847
|
])),
|
|
7848
|
+
localReadReady,
|
|
7849
|
+
writeReady,
|
|
7850
|
+
bootSettled,
|
|
6711
7851
|
ready,
|
|
6712
7852
|
status,
|
|
6713
7853
|
start: async () => {
|
|
6714
7854
|
await ready;
|
|
6715
7855
|
},
|
|
6716
7856
|
stop: async () => {
|
|
7857
|
+
await quiesceTailForTeardown();
|
|
6717
7858
|
await convergenceDriver?.stop();
|
|
6718
7859
|
sync?.unsubscribe();
|
|
6719
7860
|
status.isRunning = false;
|
|
6720
7861
|
options.onStatusChange?.(status);
|
|
6721
7862
|
await engine.close();
|
|
7863
|
+
await liveManager.dispose();
|
|
6722
7864
|
await pglite.close();
|
|
6723
7865
|
},
|
|
6724
7866
|
destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
|
|
7867
|
+
await quiesceTailForTeardown();
|
|
6725
7868
|
if (!destroyOptions?.force) {
|
|
6726
7869
|
const stats = await mutationRuntime.readMutationStats();
|
|
6727
7870
|
const owed = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
|
|
@@ -6735,26 +7878,50 @@ async function createSyncClient(options) {
|
|
|
6735
7878
|
options.onStatusChange?.(status);
|
|
6736
7879
|
await pglite.exec(buildWipeLocalStoreSql(options.registry));
|
|
6737
7880
|
await engine.close();
|
|
7881
|
+
await liveManager.dispose();
|
|
6738
7882
|
await pglite.close();
|
|
6739
7883
|
}),
|
|
6740
|
-
dropReadCache:
|
|
6741
|
-
await
|
|
6742
|
-
|
|
6743
|
-
|
|
6744
|
-
|
|
6745
|
-
|
|
6746
|
-
|
|
6747
|
-
|
|
6748
|
-
|
|
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
|
+
},
|
|
6749
7909
|
readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
|
|
6750
7910
|
mutate,
|
|
6751
|
-
discardConflict: (table, entityKey) =>
|
|
6752
|
-
|
|
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
|
+
},
|
|
6753
7919
|
diagnostics: async (table) => ({
|
|
6754
7920
|
mutation: await mutationRuntime.readMutationStats(table)
|
|
6755
7921
|
}),
|
|
6756
|
-
|
|
6757
|
-
|
|
7922
|
+
mutations: undefined,
|
|
7923
|
+
rawQuery: (sql7, params, options2) => pglite.query(sql7, params, options2),
|
|
7924
|
+
rawExec: (sql7, options2) => pglite.exec(sql7, options2),
|
|
6758
7925
|
query: (build) => runGuardedQuery(build),
|
|
6759
7926
|
queryRow: async (build) => {
|
|
6760
7927
|
const rows = await runGuardedQuery(build);
|
|
@@ -6773,36 +7940,43 @@ async function createSyncClient(options) {
|
|
|
6773
7940
|
transaction,
|
|
6774
7941
|
groupReady: groupReadyForTable,
|
|
6775
7942
|
hydratingTablesFor,
|
|
6776
|
-
subscribeLiveRows: async ({ sql:
|
|
6777
|
-
|
|
6778
|
-
const
|
|
6779
|
-
const
|
|
6780
|
-
|
|
6781
|
-
|
|
6782
|
-
|
|
7943
|
+
subscribeLiveRows: async ({ sql: sql7, params, fields, use, keepAliveMs }, onRows) => {
|
|
7944
|
+
await localReadReady;
|
|
7945
|
+
const materialSql = wrapLiveQueryForMaterialization(sql7, fields);
|
|
7946
|
+
const materializer = new LiveRowsMaterializer(undefined);
|
|
7947
|
+
const subscription = await liveManager.subscribe({ materialSql, params }, {
|
|
7948
|
+
deliverInitial: (rows) => {
|
|
7949
|
+
materializer.seed(rows);
|
|
7950
|
+
},
|
|
7951
|
+
deliverDiff: (diff) => {
|
|
7952
|
+
onRows(materializer.apply(diff));
|
|
7953
|
+
}
|
|
7954
|
+
}, keepAliveMs != null ? { keepAliveMs } : undefined);
|
|
7955
|
+
const initialRows = materializer.current();
|
|
6783
7956
|
let unsubscribed = false;
|
|
6784
7957
|
const lazySet = new Set(use ?? []);
|
|
6785
|
-
for (const key of findReferencedLazyKeysInSql(
|
|
7958
|
+
for (const key of findReferencedLazyKeysInSql(sql7, lazyGuardIndex))
|
|
6786
7959
|
lazySet.add(key);
|
|
6787
7960
|
const lazyTables = [...lazySet];
|
|
6788
|
-
const hydratingTables = hydratingTablesFor({ sql:
|
|
7961
|
+
const hydratingTables = hydratingTablesFor({ sql: sql7, ...use ? { use } : {} });
|
|
6789
7962
|
const hydrated = hydratingTables.length > 0 ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table))).then(async () => {
|
|
6790
7963
|
if (!unsubscribed)
|
|
6791
|
-
await
|
|
7964
|
+
await subscription.refresh();
|
|
6792
7965
|
}).catch(() => {
|
|
6793
7966
|
return;
|
|
6794
7967
|
}) : undefined;
|
|
6795
7968
|
return {
|
|
6796
|
-
initialRows
|
|
7969
|
+
initialRows,
|
|
6797
7970
|
unsubscribe: () => {
|
|
6798
7971
|
unsubscribed = true;
|
|
6799
|
-
|
|
7972
|
+
subscription.unsubscribe();
|
|
6800
7973
|
},
|
|
6801
7974
|
...lazyTables.length > 0 ? { lazyTables } : {},
|
|
6802
7975
|
...hydrated ? { hydrated } : {}
|
|
6803
7976
|
};
|
|
6804
7977
|
},
|
|
6805
7978
|
bootReport: async () => finalizedBootReport,
|
|
7979
|
+
liveQueryDiagnostics: async () => liveManager.snapshot(),
|
|
6806
7980
|
exportStore: async (exportOptions) => {
|
|
6807
7981
|
await ready;
|
|
6808
7982
|
return lifecycleSlot.run("exportStore", () => performStoreExport({
|
|
@@ -6832,6 +8006,44 @@ async function createSyncClient(options) {
|
|
|
6832
8006
|
}, exportOptions));
|
|
6833
8007
|
}
|
|
6834
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
|
+
});
|
|
6835
8047
|
return client;
|
|
6836
8048
|
}
|
|
6837
8049
|
function allGroupSubscriptionKeys(registry) {
|
|
@@ -6851,7 +8063,7 @@ async function resetSubscriptionsIfRequested(pglite, keys) {
|
|
|
6851
8063
|
}
|
|
6852
8064
|
function createDrizzleDatabase(client, schema) {
|
|
6853
8065
|
const relations = defineRelations(schema);
|
|
6854
|
-
const createDatabase =
|
|
8066
|
+
const createDatabase = drizzle5;
|
|
6855
8067
|
return createDatabase({ client, relations });
|
|
6856
8068
|
}
|
|
6857
8069
|
function buildSchema(registry) {
|
|
@@ -6920,6 +8132,7 @@ export {
|
|
|
6920
8132
|
getOverlayTable,
|
|
6921
8133
|
getLocalMetaTable,
|
|
6922
8134
|
getJournalTable,
|
|
8135
|
+
getAllMutationsView,
|
|
6923
8136
|
generateLocalSchemaSql,
|
|
6924
8137
|
findReferencedSyncedKeysInSql,
|
|
6925
8138
|
findReferencedLazyKeysInSql,
|
|
@@ -6928,6 +8141,7 @@ export {
|
|
|
6928
8141
|
defineSyncWorker,
|
|
6929
8142
|
createWorkerTokenCache,
|
|
6930
8143
|
createSyncClient,
|
|
8144
|
+
createMutationsApi,
|
|
6931
8145
|
createLifecycleSlot,
|
|
6932
8146
|
createIntervalConvergenceTrigger,
|
|
6933
8147
|
createConvergenceDriver,
|
|
@@ -6938,6 +8152,7 @@ export {
|
|
|
6938
8152
|
buildLazyGuardIndex,
|
|
6939
8153
|
attachSyncClient,
|
|
6940
8154
|
assertLazyRefsActivated,
|
|
8155
|
+
WriteNotReadyError,
|
|
6941
8156
|
RestoreTargetExistsError,
|
|
6942
8157
|
NonPersistentStoreError,
|
|
6943
8158
|
LiveRowsMaterializer,
|
|
@@ -6946,8 +8161,9 @@ export {
|
|
|
6946
8161
|
InvalidStorePathError,
|
|
6947
8162
|
DataExportDrainError,
|
|
6948
8163
|
DEFAULT_DRAIN_TIMEOUT_MS,
|
|
8164
|
+
ClientDisposedError,
|
|
6949
8165
|
BRIDGE_PROTOCOL_VERSION,
|
|
6950
8166
|
BRIDGE_CHANNEL
|
|
6951
8167
|
};
|
|
6952
8168
|
|
|
6953
|
-
//# debugId=
|
|
8169
|
+
//# debugId=804640A8064D585A64756E2164756E21
|