@pgxsinkit/client 0.1.49 → 0.1.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/boot-report.d.ts +76 -0
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/index.d.ts +56 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1106 -312
- package/dist/index.js.map +19 -18
- 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 +80 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +6 -0
- package/dist/shape-sync.d.ts.map +1 -1
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/metadata-tables.d.ts +16 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +10 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/tags.d.ts +16 -4
- package/dist/sync/tags.d.ts.map +1 -1
- package/dist/sync/types.d.ts +12 -0
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +44 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +1 -1
- package/src/boot-report.ts +108 -0
- package/src/index.ts +555 -136
- package/src/local-store.ts +150 -3
- package/src/local-tables.ts +49 -1
- package/src/mutation.ts +256 -15
- package/src/mutations-api.ts +310 -0
- package/src/schema.ts +428 -197
- package/src/shape-sync.ts +11 -0
- package/src/sync/index.ts +14 -1
- package/src/sync/metadata-tables.ts +41 -0
- package/src/sync/subscription-state.ts +29 -4
- package/src/sync/tags.ts +34 -9
- package/src/sync/types.ts +12 -0
- package/src/worker/attach-sync-client.ts +114 -5
- package/src/worker/define-sync-worker.ts +65 -4
- package/src/worker/protocol.ts +38 -1
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ var __require = import.meta.require;
|
|
|
4
4
|
// packages/client/src/index.ts
|
|
5
5
|
import { PGlite as PGlite2 } from "@electric-sql/pglite";
|
|
6
6
|
import { live } from "@electric-sql/pglite/live";
|
|
7
|
-
import { drizzle as
|
|
7
|
+
import { drizzle as drizzle5 } from "drizzle-orm/pglite";
|
|
8
8
|
import { defineRelations } from "drizzle-orm/relations";
|
|
9
9
|
import { fingerprintRegistry as fingerprintRegistry2, getSyncRegistrySchema as getSyncRegistrySchema4, isClaimsDependentRowFilter } from "@pgxsinkit/contracts";
|
|
10
10
|
|
|
@@ -153,7 +153,17 @@ function createBootReportBuilder(init) {
|
|
|
153
153
|
let prepareMs = null;
|
|
154
154
|
let pgliteCreateMs = null;
|
|
155
155
|
let provision = null;
|
|
156
|
+
let warmBoot = {
|
|
157
|
+
schemaSkipped: false,
|
|
158
|
+
schemaFingerprintMatch: false,
|
|
159
|
+
journalRecoverySkipped: false,
|
|
160
|
+
journalRecoveryRequired: true,
|
|
161
|
+
journalTablesVisited: 0,
|
|
162
|
+
journalRowsRecovered: null
|
|
163
|
+
};
|
|
156
164
|
let syncStartDoneOffset = null;
|
|
165
|
+
let localReadReadyMs = null;
|
|
166
|
+
let writeReadyMs = null;
|
|
157
167
|
const groups = [];
|
|
158
168
|
let built = null;
|
|
159
169
|
const duration = (key) => durations.get(key) ?? 0;
|
|
@@ -179,6 +189,26 @@ function createBootReportBuilder(init) {
|
|
|
179
189
|
setProvision: (value) => {
|
|
180
190
|
provision = value;
|
|
181
191
|
},
|
|
192
|
+
setSchemaFastPath: (info) => {
|
|
193
|
+
warmBoot = { ...warmBoot, schemaSkipped: info.skipped, schemaFingerprintMatch: info.fingerprintMatch };
|
|
194
|
+
},
|
|
195
|
+
setJournalRecovery: (info) => {
|
|
196
|
+
warmBoot = {
|
|
197
|
+
...warmBoot,
|
|
198
|
+
journalRecoverySkipped: info.skipped,
|
|
199
|
+
journalRecoveryRequired: info.required,
|
|
200
|
+
journalTablesVisited: info.tablesVisited,
|
|
201
|
+
journalRowsRecovered: info.rowsRecovered
|
|
202
|
+
};
|
|
203
|
+
},
|
|
204
|
+
setLocalReadReadyMs: (ms) => {
|
|
205
|
+
if (localReadReadyMs == null)
|
|
206
|
+
localReadReadyMs = ms;
|
|
207
|
+
},
|
|
208
|
+
setWriteReadyMs: (ms) => {
|
|
209
|
+
if (writeReadyMs == null)
|
|
210
|
+
writeReadyMs = ms;
|
|
211
|
+
},
|
|
182
212
|
setSyncStartMs: (ms) => {
|
|
183
213
|
durations.set("syncStart", ms);
|
|
184
214
|
},
|
|
@@ -199,11 +229,15 @@ function createBootReportBuilder(init) {
|
|
|
199
229
|
reportVersion: 1,
|
|
200
230
|
mode: init.mode,
|
|
201
231
|
freshStore: init.freshStore,
|
|
232
|
+
storeKind: init.storeKind,
|
|
202
233
|
overlapPrefetch: init.overlapPrefetch,
|
|
203
234
|
registryFingerprint: init.registryFingerprint,
|
|
204
235
|
startedAt,
|
|
205
236
|
totalMs,
|
|
237
|
+
localReadReadyMs,
|
|
238
|
+
writeReadyMs,
|
|
206
239
|
provision,
|
|
240
|
+
warmBoot,
|
|
207
241
|
phases: {
|
|
208
242
|
pgliteCreateMs,
|
|
209
243
|
schemaExecMs: duration("schemaExec"),
|
|
@@ -739,7 +773,7 @@ function wrapLiveQueryForMaterialization(sql, fields) {
|
|
|
739
773
|
}
|
|
740
774
|
|
|
741
775
|
// packages/client/src/local-store.ts
|
|
742
|
-
import { eq as eq3, like as like2 } from "drizzle-orm";
|
|
776
|
+
import { and as and3, eq as eq3, like as like2, notExists, sql as sql3 } from "drizzle-orm";
|
|
743
777
|
import { drizzle as drizzle2 } from "drizzle-orm/pglite";
|
|
744
778
|
|
|
745
779
|
// packages/client/src/local-tables.ts
|
|
@@ -771,6 +805,7 @@ import {
|
|
|
771
805
|
getLocalSyncPrimaryKeyColumns,
|
|
772
806
|
getSyncRegistrySchema,
|
|
773
807
|
getProjectedColumns,
|
|
808
|
+
hashString,
|
|
774
809
|
maybeQuoteIdentifier,
|
|
775
810
|
quoteIdentifier as quoteIdentifier4,
|
|
776
811
|
quoteSqlLiteral as quoteSqlStringLiteral
|
|
@@ -1209,6 +1244,7 @@ async function applyBulkUpdatesToTable({ pg, target, messages, debug }) {
|
|
|
1209
1244
|
|
|
1210
1245
|
// packages/client/src/sync/metadata-tables.ts
|
|
1211
1246
|
import { index, jsonb, pgSchema, primaryKey, text } from "drizzle-orm/pg-core";
|
|
1247
|
+
var SESSION_METADATA_SCHEMA = "pg_temp";
|
|
1212
1248
|
function buildSubscriptionsMetadata(schema) {
|
|
1213
1249
|
return schema.table("subscriptions_metadata", {
|
|
1214
1250
|
key: text("key").primaryKey(),
|
|
@@ -1239,6 +1275,20 @@ function getMetadataTables(metadataSchema) {
|
|
|
1239
1275
|
}
|
|
1240
1276
|
return tables;
|
|
1241
1277
|
}
|
|
1278
|
+
var sessionCache;
|
|
1279
|
+
function getSessionMetadataTables() {
|
|
1280
|
+
if (!sessionCache) {
|
|
1281
|
+
const schema = pgSchema(SESSION_METADATA_SCHEMA);
|
|
1282
|
+
sessionCache = {
|
|
1283
|
+
subscriptionsMetadata: buildSubscriptionsMetadata(schema),
|
|
1284
|
+
shapeRowTags: buildShapeRowTags(schema)
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
return sessionCache;
|
|
1288
|
+
}
|
|
1289
|
+
function pickMetadataTables(metadataSchema, sessionScoped) {
|
|
1290
|
+
return sessionScoped ? getSessionMetadataTables() : getMetadataTables(metadataSchema);
|
|
1291
|
+
}
|
|
1242
1292
|
|
|
1243
1293
|
// packages/client/src/sync/tags.ts
|
|
1244
1294
|
var DEFAULT_METADATA_SCHEMA = "pgxsinkit";
|
|
@@ -1252,15 +1302,20 @@ function shapeRowTagsTableName(metadataSchema) {
|
|
|
1252
1302
|
const config = getTableConfig3(getMetadataTables(metadataSchema).shapeRowTags);
|
|
1253
1303
|
return `${quoteIdentifier3(config.schema ?? "public")}.${quoteIdentifier3(config.name)}`;
|
|
1254
1304
|
}
|
|
1305
|
+
function shapeRowTagsSessionTableName() {
|
|
1306
|
+
const config = getTableConfig3(getSessionMetadataTables().shapeRowTags);
|
|
1307
|
+
return `${quoteIdentifier3(config.schema ?? "public")}.${quoteIdentifier3(config.name)}`;
|
|
1308
|
+
}
|
|
1255
1309
|
function shapeTableId(schema, table) {
|
|
1256
1310
|
return `${schema ?? "public"}.${table}`;
|
|
1257
1311
|
}
|
|
1258
1312
|
function buildClearShapeTagsSql(shapeTable, metadataSchema = DEFAULT_METADATA_SCHEMA) {
|
|
1259
|
-
const
|
|
1260
|
-
return `DO $$ BEGIN
|
|
1261
|
-
IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
|
|
1313
|
+
const clearOne = (table) => ` IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
|
|
1262
1314
|
DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};
|
|
1263
|
-
END IF
|
|
1315
|
+
END IF;`;
|
|
1316
|
+
return `DO $$ BEGIN
|
|
1317
|
+
${clearOne(shapeRowTagsTableName(metadataSchema))}
|
|
1318
|
+
${clearOne(shapeRowTagsSessionTableName())}
|
|
1264
1319
|
END $$;`;
|
|
1265
1320
|
}
|
|
1266
1321
|
function serializeRowPk(value, primaryKey2) {
|
|
@@ -1301,9 +1356,10 @@ async function applyShapeTagSync({
|
|
|
1301
1356
|
metadataSchema,
|
|
1302
1357
|
shapeTable,
|
|
1303
1358
|
messages,
|
|
1304
|
-
primaryKey: primaryKey2
|
|
1359
|
+
primaryKey: primaryKey2,
|
|
1360
|
+
sessionScoped = false
|
|
1305
1361
|
}) {
|
|
1306
|
-
const { shapeRowTags } =
|
|
1362
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
1307
1363
|
const db = drizzleOverPg(pg);
|
|
1308
1364
|
for (const message of messages) {
|
|
1309
1365
|
const data = message.value;
|
|
@@ -1331,9 +1387,10 @@ async function addShapeRowTags({
|
|
|
1331
1387
|
metadataSchema,
|
|
1332
1388
|
shapeTable,
|
|
1333
1389
|
messages,
|
|
1334
|
-
primaryKey: primaryKey2
|
|
1390
|
+
primaryKey: primaryKey2,
|
|
1391
|
+
sessionScoped = false
|
|
1335
1392
|
}) {
|
|
1336
|
-
const { shapeRowTags } =
|
|
1393
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
1337
1394
|
const db = drizzleOverPg(pg);
|
|
1338
1395
|
for (const message of messages) {
|
|
1339
1396
|
const tags = message.headers.tags;
|
|
@@ -1350,9 +1407,10 @@ async function applyShapeMoveOut({
|
|
|
1350
1407
|
shapeTable,
|
|
1351
1408
|
target,
|
|
1352
1409
|
patternSets,
|
|
1353
|
-
debug
|
|
1410
|
+
debug,
|
|
1411
|
+
sessionScoped = false
|
|
1354
1412
|
}) {
|
|
1355
|
-
const { shapeRowTags } =
|
|
1413
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
1356
1414
|
const db = drizzleOverPg(pg);
|
|
1357
1415
|
const evictedPkJsons = new Set;
|
|
1358
1416
|
for (const patterns of patternSets) {
|
|
@@ -1391,18 +1449,48 @@ async function applyShapeMoveOut({
|
|
|
1391
1449
|
async function clearShapeTags({
|
|
1392
1450
|
pg,
|
|
1393
1451
|
metadataSchema,
|
|
1394
|
-
shapeTable
|
|
1452
|
+
shapeTable,
|
|
1453
|
+
sessionScoped = false
|
|
1395
1454
|
}) {
|
|
1396
|
-
const { shapeRowTags } =
|
|
1455
|
+
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
1397
1456
|
await drizzleOverPg(pg).delete(shapeRowTags).where(eq2(shapeRowTags.shape_table, shapeTable));
|
|
1398
1457
|
}
|
|
1399
1458
|
|
|
1400
1459
|
// packages/client/src/schema.ts
|
|
1401
1460
|
var LOCAL_META_TABLE = "pgxsinkit_local_meta";
|
|
1402
1461
|
var REGISTRY_FINGERPRINT_KEY = "registry_fingerprint";
|
|
1403
|
-
|
|
1462
|
+
var LOCAL_SCHEMA_FINGERPRINT_KEY = "local_schema_fingerprint";
|
|
1463
|
+
var LOCAL_SCHEMA_FINGERPRINT_PREFIX = "lsf1:";
|
|
1464
|
+
var ALL_MUTATIONS_VIEW = "pgxsinkit_all_mutations";
|
|
1465
|
+
var ALL_MUTATIONS_JOURNAL_COLUMNS = [
|
|
1466
|
+
"mutation_id",
|
|
1467
|
+
"entity_key_json",
|
|
1468
|
+
"mutation_seq",
|
|
1469
|
+
"mutation_kind",
|
|
1470
|
+
"status",
|
|
1471
|
+
"registry_version",
|
|
1472
|
+
"base_server_version",
|
|
1473
|
+
"write_unit",
|
|
1474
|
+
"write_mode",
|
|
1475
|
+
"attempt_count",
|
|
1476
|
+
"last_error",
|
|
1477
|
+
"last_http_status",
|
|
1478
|
+
"conflict_reason",
|
|
1479
|
+
"server_updated_at_us",
|
|
1480
|
+
"enqueued_at_us",
|
|
1481
|
+
"next_retry_at_us",
|
|
1482
|
+
"sent_at_us",
|
|
1483
|
+
"acked_at_us",
|
|
1484
|
+
"updated_at_us"
|
|
1485
|
+
];
|
|
1486
|
+
function joinSchemaStatements(statements) {
|
|
1487
|
+
return `${statements.join(`
|
|
1488
|
+
|
|
1489
|
+
`)}
|
|
1490
|
+
`;
|
|
1491
|
+
}
|
|
1492
|
+
function localMetaBootstrapStatements(localSchema) {
|
|
1404
1493
|
const statements = [];
|
|
1405
|
-
const localSchema = getSyncRegistrySchema(registry);
|
|
1406
1494
|
if (localSchema !== "public") {
|
|
1407
1495
|
statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier4(localSchema)};`);
|
|
1408
1496
|
}
|
|
@@ -1413,104 +1501,103 @@ function generateLocalSchemaSql(registry) {
|
|
|
1413
1501
|
].join(`,
|
|
1414
1502
|
`)}
|
|
1415
1503
|
);`);
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1504
|
+
return statements;
|
|
1505
|
+
}
|
|
1506
|
+
function buildLocalMetaBootstrapSql(registry) {
|
|
1507
|
+
return joinSchemaStatements(localMetaBootstrapStatements(getSyncRegistrySchema(registry)));
|
|
1508
|
+
}
|
|
1509
|
+
function buildEntryClusterStatements(entry, tableKey, localSchema) {
|
|
1510
|
+
const statements = [];
|
|
1511
|
+
const ephemeral = entry.retention === "ephemeral";
|
|
1512
|
+
const objectSchema = ephemeral ? "public" : localSchema;
|
|
1513
|
+
const temp = ephemeral ? "TEMP " : "";
|
|
1514
|
+
const projection = getClientProjection(entry, tableKey, objectSchema);
|
|
1515
|
+
const columns = getProjectedColumns(entry).map(({ column }) => column);
|
|
1516
|
+
const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
|
|
1517
|
+
const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
|
|
1518
|
+
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (
|
|
1429
1519
|
${baseColumnsSql}
|
|
1430
1520
|
);`);
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1521
|
+
if (entry.mode === "readonly") {
|
|
1522
|
+
return statements;
|
|
1523
|
+
}
|
|
1524
|
+
if (!projection.overlayTable || !projection.journalTable) {
|
|
1525
|
+
throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);
|
|
1526
|
+
}
|
|
1527
|
+
const journalTableName = entry.clientProjection?.journalTable;
|
|
1528
|
+
if (!journalTableName) {
|
|
1529
|
+
throw new Error(`journal table is required for writable table ${tableKey}`);
|
|
1530
|
+
}
|
|
1531
|
+
const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {
|
|
1532
|
+
const column = columns.find((candidate) => candidate.name === columnName);
|
|
1533
|
+
if (!column) {
|
|
1534
|
+
throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
|
|
1440
1535
|
}
|
|
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} (
|
|
1536
|
+
return column;
|
|
1537
|
+
});
|
|
1538
|
+
const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
|
|
1539
|
+
const journalSequenceName = buildJournalSequenceName(journalTableName);
|
|
1540
|
+
const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);
|
|
1541
|
+
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (
|
|
1452
1542
|
${[
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1543
|
+
...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),
|
|
1544
|
+
"overlay_kind VARCHAR(24) NOT NULL",
|
|
1545
|
+
"local_updated_at_us BIGINT NOT NULL",
|
|
1546
|
+
...buildCompositePrimaryKeyClauses(primaryKeyColumnNames)
|
|
1547
|
+
].join(`,
|
|
1458
1548
|
`)}
|
|
1459
1549
|
);`);
|
|
1460
|
-
|
|
1461
|
-
|
|
1550
|
+
statements.push(`CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`);
|
|
1551
|
+
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (
|
|
1462
1552
|
${[
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1553
|
+
"mutation_id UUID PRIMARY KEY",
|
|
1554
|
+
...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),
|
|
1555
|
+
"entity_key_json TEXT NOT NULL",
|
|
1556
|
+
`mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
|
|
1557
|
+
"mutation_kind VARCHAR(24) NOT NULL",
|
|
1558
|
+
"status VARCHAR(24) NOT NULL",
|
|
1559
|
+
"registry_version TEXT",
|
|
1560
|
+
"base_server_version BIGINT",
|
|
1561
|
+
"write_unit TEXT",
|
|
1562
|
+
"write_mode VARCHAR(24)",
|
|
1563
|
+
"payload_json TEXT NOT NULL",
|
|
1564
|
+
"attempt_count INTEGER NOT NULL DEFAULT 0",
|
|
1565
|
+
"last_error TEXT",
|
|
1566
|
+
"last_http_status INTEGER",
|
|
1567
|
+
"conflict_reason TEXT",
|
|
1568
|
+
"server_updated_at_us BIGINT",
|
|
1569
|
+
"enqueued_at_us BIGINT NOT NULL",
|
|
1570
|
+
"next_retry_at_us BIGINT",
|
|
1571
|
+
"sent_at_us BIGINT",
|
|
1572
|
+
"acked_at_us BIGINT",
|
|
1573
|
+
"updated_at_us BIGINT NOT NULL"
|
|
1574
|
+
].join(`,
|
|
1485
1575
|
`)}
|
|
1486
1576
|
);`);
|
|
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 $$
|
|
1577
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, ["status", "enqueued_at_us"]));
|
|
1578
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [
|
|
1579
|
+
"status",
|
|
1580
|
+
"next_retry_at_us",
|
|
1581
|
+
"enqueued_at_us"
|
|
1582
|
+
]));
|
|
1583
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [
|
|
1584
|
+
...entry.primaryKey.columns,
|
|
1585
|
+
"mutation_seq"
|
|
1586
|
+
]));
|
|
1587
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [
|
|
1588
|
+
"entity_key_json",
|
|
1589
|
+
"mutation_seq"
|
|
1590
|
+
]));
|
|
1591
|
+
statements.push(renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [
|
|
1592
|
+
"entity_key_json",
|
|
1593
|
+
"status",
|
|
1594
|
+
"mutation_seq"
|
|
1595
|
+
]));
|
|
1596
|
+
const pkMatchSql = (alias) => primaryKeyColumns.map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`).join(" AND ");
|
|
1597
|
+
const pkOverlayMatchSql = primaryKeyColumns.map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`).join(" AND ");
|
|
1598
|
+
const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: "NEW" });
|
|
1599
|
+
const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;
|
|
1600
|
+
statements.push(`CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$
|
|
1514
1601
|
` + `BEGIN
|
|
1515
1602
|
` + ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has
|
|
1516
1603
|
` + ` -- been acked \u2014 that later write IS the resolution. The acked resolver is cleared by the
|
|
@@ -1540,22 +1627,85 @@ function generateLocalSchemaSql(registry) {
|
|
|
1540
1627
|
` + ` RETURN COALESCE(NEW, OLD);
|
|
1541
1628
|
` + `END;
|
|
1542
1629
|
` + `$$ LANGUAGE plpgsql;`);
|
|
1543
|
-
|
|
1630
|
+
statements.push(`CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}
|
|
1544
1631
|
` + `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}
|
|
1545
1632
|
` + `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`);
|
|
1546
|
-
|
|
1633
|
+
statements.push(`CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS
|
|
1547
1634
|
${buildReadModelViewSql(entry, projection, columns.map((column) => column.name))};`);
|
|
1548
|
-
|
|
1635
|
+
statements.push(`CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS
|
|
1549
1636
|
${buildSyncStateView(entry, {
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1637
|
+
syncedTable: projection.syncedTable,
|
|
1638
|
+
overlayTable: projection.overlayTable,
|
|
1639
|
+
journalTable: projection.journalTable
|
|
1640
|
+
})};`);
|
|
1641
|
+
return statements;
|
|
1642
|
+
}
|
|
1643
|
+
function durableSchemaStatements(registry) {
|
|
1644
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
1645
|
+
const statements = [...localMetaBootstrapStatements(localSchema)];
|
|
1646
|
+
for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {
|
|
1647
|
+
statements.push(buildCreateEnumTypeSql(enumDefinition));
|
|
1554
1648
|
}
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1649
|
+
for (const [tableKey, entry] of Object.entries(registry)) {
|
|
1650
|
+
if (entry.retention === "ephemeral") {
|
|
1651
|
+
continue;
|
|
1652
|
+
}
|
|
1653
|
+
statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));
|
|
1654
|
+
}
|
|
1655
|
+
return statements;
|
|
1656
|
+
}
|
|
1657
|
+
function ephemeralSchemaStatements(registry) {
|
|
1658
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
1659
|
+
const ephemeralEntries = Object.entries(registry).filter(([, entry]) => entry.retention === "ephemeral");
|
|
1660
|
+
const statements = [];
|
|
1661
|
+
if (ephemeralEntries.length > 0) {
|
|
1662
|
+
for (const enumDefinition of collectEnumDefinitionsFromEntries(ephemeralEntries.map(([, entry]) => entry), localSchema)) {
|
|
1663
|
+
statements.push(buildCreateEnumTypeSql(enumDefinition));
|
|
1664
|
+
}
|
|
1665
|
+
for (const [tableKey, entry] of ephemeralEntries) {
|
|
1666
|
+
statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
statements.push(...allMutationsViewStatements(registry));
|
|
1670
|
+
return statements;
|
|
1671
|
+
}
|
|
1672
|
+
function allMutationsViewStatements(registry) {
|
|
1673
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
1674
|
+
const branches = [];
|
|
1675
|
+
for (const [tableKey, entry] of Object.entries(registry)) {
|
|
1676
|
+
if (entry.mode === "readonly" || !entry.clientProjection?.journalTable) {
|
|
1677
|
+
continue;
|
|
1678
|
+
}
|
|
1679
|
+
const objectSchema = entry.retention === "ephemeral" ? "public" : localSchema;
|
|
1680
|
+
const projection = getClientProjection(entry, tableKey, objectSchema);
|
|
1681
|
+
if (!projection.journalTable) {
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
branches.push(`SELECT ${quoteSqlStringLiteral(tableKey)} AS table_key,
|
|
1685
|
+
${ALL_MUTATIONS_JOURNAL_COLUMNS.join(`,
|
|
1686
|
+
`)}
|
|
1687
|
+
FROM ${projection.journalTable}`);
|
|
1688
|
+
}
|
|
1689
|
+
if (branches.length === 0) {
|
|
1690
|
+
return [];
|
|
1691
|
+
}
|
|
1692
|
+
return [`CREATE OR REPLACE TEMP VIEW ${ALL_MUTATIONS_VIEW} AS
|
|
1693
|
+
${branches.join(`
|
|
1694
|
+
UNION ALL
|
|
1695
|
+
`)};`];
|
|
1696
|
+
}
|
|
1697
|
+
function generateDurableLocalSchemaSql(registry) {
|
|
1698
|
+
return joinSchemaStatements(durableSchemaStatements(registry));
|
|
1699
|
+
}
|
|
1700
|
+
function generateEphemeralLocalSchemaSql(registry) {
|
|
1701
|
+
const statements = ephemeralSchemaStatements(registry);
|
|
1702
|
+
return statements.length === 0 ? "" : joinSchemaStatements(statements);
|
|
1703
|
+
}
|
|
1704
|
+
function generateLocalSchemaSql(registry) {
|
|
1705
|
+
return joinSchemaStatements([...durableSchemaStatements(registry), ...ephemeralSchemaStatements(registry)]);
|
|
1706
|
+
}
|
|
1707
|
+
function computeLocalSchemaFingerprint(registry) {
|
|
1708
|
+
return `${LOCAL_SCHEMA_FINGERPRINT_PREFIX}${hashString(generateDurableLocalSchemaSql(registry))}`;
|
|
1559
1709
|
}
|
|
1560
1710
|
function buildReadModelViewSql(entry, projection, columnNames) {
|
|
1561
1711
|
if (!projection.overlayTable) {
|
|
@@ -1593,17 +1743,19 @@ function buildTableColumnSql(columns, primaryKeyColumns, localSchema) {
|
|
|
1593
1743
|
].join(`,
|
|
1594
1744
|
`);
|
|
1595
1745
|
}
|
|
1596
|
-
function renderCreateTableSql(table) {
|
|
1746
|
+
function renderCreateTableSql(table, options = {}) {
|
|
1597
1747
|
const config = getTableConfig4(table);
|
|
1748
|
+
const temp = options.temp === true;
|
|
1598
1749
|
const schemaName = config.schema ?? "public";
|
|
1599
|
-
const
|
|
1750
|
+
const tableRef = temp ? maybeQuoteIdentifier(config.name) : qualifyIdentifier(schemaName, config.name);
|
|
1600
1751
|
const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);
|
|
1601
1752
|
const columnSql = buildTableColumnSql(config.columns, primaryKeyColumns, schemaName);
|
|
1602
|
-
const
|
|
1753
|
+
const createKeyword = temp ? "CREATE TEMP TABLE" : "CREATE TABLE";
|
|
1754
|
+
const statements = [`${createKeyword} IF NOT EXISTS ${tableRef} (
|
|
1603
1755
|
${columnSql}
|
|
1604
1756
|
);`];
|
|
1605
1757
|
for (const index2 of config.indexes) {
|
|
1606
|
-
statements.push(renderCreateIndexSql(
|
|
1758
|
+
statements.push(renderCreateIndexSql(tableRef, index2));
|
|
1607
1759
|
}
|
|
1608
1760
|
return statements;
|
|
1609
1761
|
}
|
|
@@ -2122,6 +2274,34 @@ function resolveApplyTarget(registry, tableKey) {
|
|
|
2122
2274
|
insertRenderCache: new Map
|
|
2123
2275
|
};
|
|
2124
2276
|
}
|
|
2277
|
+
function buildAllMutationsViewColumns() {
|
|
2278
|
+
return {
|
|
2279
|
+
tableKey: text2("table_key").notNull(),
|
|
2280
|
+
mutationId: uuid("mutation_id").notNull(),
|
|
2281
|
+
entityKeyJson: text2("entity_key_json").notNull(),
|
|
2282
|
+
mutationSeq: integer("mutation_seq").notNull(),
|
|
2283
|
+
mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
|
|
2284
|
+
status: varchar("status", { length: 24 }).notNull(),
|
|
2285
|
+
registryVersion: text2("registry_version"),
|
|
2286
|
+
baseServerVersion: bigintText("base_server_version"),
|
|
2287
|
+
writeUnit: text2("write_unit"),
|
|
2288
|
+
writeMode: varchar("write_mode", { length: 24 }),
|
|
2289
|
+
attemptCount: integer("attempt_count").notNull(),
|
|
2290
|
+
lastError: text2("last_error"),
|
|
2291
|
+
lastHttpStatus: integer("last_http_status"),
|
|
2292
|
+
conflictReason: text2("conflict_reason"),
|
|
2293
|
+
serverUpdatedAtUs: bigintText("server_updated_at_us"),
|
|
2294
|
+
enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
|
|
2295
|
+
nextRetryAtUs: bigintText("next_retry_at_us"),
|
|
2296
|
+
sentAtUs: bigintText("sent_at_us"),
|
|
2297
|
+
ackedAtUs: bigintText("acked_at_us"),
|
|
2298
|
+
updatedAtUs: bigintText("updated_at_us").notNull()
|
|
2299
|
+
};
|
|
2300
|
+
}
|
|
2301
|
+
var allMutationsShape = pgView(ALL_MUTATIONS_VIEW, buildAllMutationsViewColumns()).existing();
|
|
2302
|
+
function getAllMutationsView(_registry) {
|
|
2303
|
+
return allMutationsShape;
|
|
2304
|
+
}
|
|
2125
2305
|
function getLocalMetaTable(registry) {
|
|
2126
2306
|
const localSchema = getSyncRegistrySchema2(registry);
|
|
2127
2307
|
const cached = localMetaCache.get(localSchema);
|
|
@@ -2167,6 +2347,49 @@ async function clearLazyGroupActivation(db, registry, groupKey) {
|
|
|
2167
2347
|
async function writeStoredRegistryFingerprint(db, registry, fingerprint) {
|
|
2168
2348
|
await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);
|
|
2169
2349
|
}
|
|
2350
|
+
async function readStoredLocalSchemaFingerprint(db, registry) {
|
|
2351
|
+
const meta = getLocalMetaTable(registry);
|
|
2352
|
+
const query = metaQueryBuilder.select({ value: meta.value }).from(meta).where(eq3(meta.key, LOCAL_SCHEMA_FINGERPRINT_KEY)).limit(1).toSQL();
|
|
2353
|
+
const result = await db.query(query.sql, query.params);
|
|
2354
|
+
return result.rows[0]?.value ?? null;
|
|
2355
|
+
}
|
|
2356
|
+
async function writeStoredLocalSchemaFingerprint(db, registry, fingerprint) {
|
|
2357
|
+
await upsertMetaValue(db, registry, LOCAL_SCHEMA_FINGERPRINT_KEY, fingerprint);
|
|
2358
|
+
}
|
|
2359
|
+
var MUTATION_RECOVERY_REQUIRED_KEY = "mutation_recovery_required";
|
|
2360
|
+
async function readMutationRecoveryRequired(db, registry) {
|
|
2361
|
+
const meta = getLocalMetaTable(registry);
|
|
2362
|
+
const query = metaQueryBuilder.select({ value: meta.value }).from(meta).where(eq3(meta.key, MUTATION_RECOVERY_REQUIRED_KEY)).limit(1).toSQL();
|
|
2363
|
+
const result = await db.query(query.sql, query.params);
|
|
2364
|
+
const value = result.rows[0]?.value;
|
|
2365
|
+
if (value == null) {
|
|
2366
|
+
return null;
|
|
2367
|
+
}
|
|
2368
|
+
if (value === "true")
|
|
2369
|
+
return true;
|
|
2370
|
+
if (value === "false")
|
|
2371
|
+
return false;
|
|
2372
|
+
syncDebug("mutation recovery marker has an unexpected value \u2014 treating as recovery-required (fail closed)", {
|
|
2373
|
+
value
|
|
2374
|
+
});
|
|
2375
|
+
return true;
|
|
2376
|
+
}
|
|
2377
|
+
async function writeMutationRecoveryRequired(db, registry, required) {
|
|
2378
|
+
await upsertMetaValue(db, registry, MUTATION_RECOVERY_REQUIRED_KEY, required ? "true" : "false");
|
|
2379
|
+
}
|
|
2380
|
+
function writableTableKeys(registry) {
|
|
2381
|
+
return Object.keys(registry).filter((key) => registry[key]?.mode !== "readonly");
|
|
2382
|
+
}
|
|
2383
|
+
async function clearMutationRecoveryMarkerIfSettled(db, registry) {
|
|
2384
|
+
const meta = getLocalMetaTable(registry);
|
|
2385
|
+
const noSendingConditions = writableTableKeys(registry).map((key) => {
|
|
2386
|
+
const journal = getJournalTable(registry, key);
|
|
2387
|
+
return notExists(metaQueryBuilder.select({ one: sql3`1` }).from(journal).where(eq3(journal.status, "sending")));
|
|
2388
|
+
});
|
|
2389
|
+
const query = metaQueryBuilder.update(meta).set({ value: "false" }).where(and3(eq3(meta.key, MUTATION_RECOVERY_REQUIRED_KEY), ...noSendingConditions)).toSQL();
|
|
2390
|
+
const result = await db.query(query.sql, query.params);
|
|
2391
|
+
return { cleared: (result.affectedRows ?? 0) > 0 };
|
|
2392
|
+
}
|
|
2170
2393
|
async function reconcileLocalStoreVersion(args) {
|
|
2171
2394
|
const { db, registry, runtime } = args;
|
|
2172
2395
|
const stored = await readStoredRegistryFingerprint(db, registry);
|
|
@@ -2198,6 +2421,7 @@ async function rebuildReadCacheOrDefer(args, previousFingerprint) {
|
|
|
2198
2421
|
await db.exec(buildWipeLocalStoreSql(registry));
|
|
2199
2422
|
await db.exec(generateLocalSchemaSql(registry));
|
|
2200
2423
|
await writeStoredRegistryFingerprint(db, registry, current);
|
|
2424
|
+
await writeStoredLocalSchemaFingerprint(db, registry, computeLocalSchemaFingerprint(registry));
|
|
2201
2425
|
const event = {
|
|
2202
2426
|
status: "rebuilt",
|
|
2203
2427
|
previousFingerprint,
|
|
@@ -2210,7 +2434,7 @@ async function rebuildReadCacheOrDefer(args, previousFingerprint) {
|
|
|
2210
2434
|
|
|
2211
2435
|
// packages/client/src/mutation.ts
|
|
2212
2436
|
import {
|
|
2213
|
-
and as
|
|
2437
|
+
and as and4,
|
|
2214
2438
|
desc,
|
|
2215
2439
|
eq as eq4,
|
|
2216
2440
|
exists,
|
|
@@ -2222,9 +2446,9 @@ import {
|
|
|
2222
2446
|
isNull,
|
|
2223
2447
|
lt,
|
|
2224
2448
|
ne,
|
|
2225
|
-
notExists,
|
|
2449
|
+
notExists as notExists2,
|
|
2226
2450
|
SQL,
|
|
2227
|
-
sql as
|
|
2451
|
+
sql as sql4
|
|
2228
2452
|
} from "drizzle-orm";
|
|
2229
2453
|
import {
|
|
2230
2454
|
alias,
|
|
@@ -2352,6 +2576,44 @@ function createMutationRuntime(options) {
|
|
|
2352
2576
|
const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
|
|
2353
2577
|
const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
|
|
2354
2578
|
let flushQueue = Promise.resolve();
|
|
2579
|
+
const ownsMetaTable = options.ownsMetaTable ?? true;
|
|
2580
|
+
let recoveryMarkerDirty = false;
|
|
2581
|
+
let markSendingInFlight = 0;
|
|
2582
|
+
const markSendingScope = {
|
|
2583
|
+
enter: () => {
|
|
2584
|
+
markSendingInFlight += 1;
|
|
2585
|
+
},
|
|
2586
|
+
exit: () => {
|
|
2587
|
+
markSendingInFlight -= 1;
|
|
2588
|
+
}
|
|
2589
|
+
};
|
|
2590
|
+
const ensureRecoveryMarker = async () => {
|
|
2591
|
+
if (!ownsMetaTable || recoveryMarkerDirty) {
|
|
2592
|
+
return;
|
|
2593
|
+
}
|
|
2594
|
+
await writeMutationRecoveryRequired(options.db, options.registry, true);
|
|
2595
|
+
recoveryMarkerDirty = true;
|
|
2596
|
+
};
|
|
2597
|
+
const settleRecoveryMarker = async () => {
|
|
2598
|
+
if (!ownsMetaTable) {
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
if (markSendingInFlight > 0) {
|
|
2602
|
+
return;
|
|
2603
|
+
}
|
|
2604
|
+
recoveryMarkerDirty = false;
|
|
2605
|
+
await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);
|
|
2606
|
+
};
|
|
2607
|
+
const buildRecoverSendingQuery = (journal, nowUs) => queryBuilder.update(journal).set({
|
|
2608
|
+
status: "pending",
|
|
2609
|
+
updatedAtUs: nowUs,
|
|
2610
|
+
sentAtUs: null,
|
|
2611
|
+
nextRetryAtUs: nowUs,
|
|
2612
|
+
lastError: null,
|
|
2613
|
+
lastHttpStatus: null,
|
|
2614
|
+
conflictReason: null
|
|
2615
|
+
}).where(eq4(journal.status, "sending")).toSQL();
|
|
2616
|
+
const readAffectedRows = (result) => result.affectedRows ?? 0;
|
|
2355
2617
|
const getTableContext = (table) => {
|
|
2356
2618
|
const context = tableContexts[table];
|
|
2357
2619
|
if (!context) {
|
|
@@ -2628,7 +2890,7 @@ function createMutationRuntime(options) {
|
|
|
2628
2890
|
const conflictedMutationIds = new Set;
|
|
2629
2891
|
let processedCount = 0;
|
|
2630
2892
|
do {
|
|
2631
|
-
const batchResult = await flushBatch(options.db, tableContexts, options.writeUrl, maxMutationAttempts, flushBatchSize, table, resolveAuthToken, options.requestHeaders);
|
|
2893
|
+
const batchResult = await flushBatch(options.db, tableContexts, options.writeUrl, maxMutationAttempts, flushBatchSize, table, resolveAuthToken, options.requestHeaders, ensureRecoveryMarker, markSendingScope);
|
|
2632
2894
|
processedCount = batchResult.processedCount;
|
|
2633
2895
|
for (const context of batchResult.affectedContexts) {
|
|
2634
2896
|
affectedContexts.set(context.key, context);
|
|
@@ -2643,6 +2905,7 @@ function createMutationRuntime(options) {
|
|
|
2643
2905
|
for (const context of affectedContexts.values()) {
|
|
2644
2906
|
await reconcileTable(options.db, context);
|
|
2645
2907
|
}
|
|
2908
|
+
await settleRecoveryMarker();
|
|
2646
2909
|
if (quarantinedMutationIds.size > 0 && options.onQuarantine) {
|
|
2647
2910
|
const details = await readMutationDetailsForContexts(options.db, [...affectedContexts.values()], quarantinedMutationIds);
|
|
2648
2911
|
if (details.length > 0) {
|
|
@@ -2760,7 +3023,7 @@ function createMutationRuntime(options) {
|
|
|
2760
3023
|
nextRetryAtUs: null,
|
|
2761
3024
|
lastHttpStatus: null,
|
|
2762
3025
|
conflictReason: null
|
|
2763
|
-
})));
|
|
3026
|
+
})), ensureRecoveryMarker, markSendingScope);
|
|
2764
3027
|
}
|
|
2765
3028
|
const mutations = prepared.map((row) => ({
|
|
2766
3029
|
tableName: row.sqlTableName,
|
|
@@ -2902,6 +3165,7 @@ function createMutationRuntime(options) {
|
|
|
2902
3165
|
await options.onConflict(details);
|
|
2903
3166
|
}
|
|
2904
3167
|
}
|
|
3168
|
+
await settleRecoveryMarker();
|
|
2905
3169
|
return { acks: [...acksByMutationId.values()] };
|
|
2906
3170
|
},
|
|
2907
3171
|
reconcile: async (table) => {
|
|
@@ -2925,19 +3189,47 @@ function createMutationRuntime(options) {
|
|
|
2925
3189
|
const contexts = filterContexts(tableContexts, table);
|
|
2926
3190
|
const nowUs = nowMicroseconds();
|
|
2927
3191
|
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();
|
|
3192
|
+
const query = buildRecoverSendingQuery(context.tables.journal, nowUs);
|
|
2938
3193
|
await options.db.query(query.sql, query.params);
|
|
2939
3194
|
}
|
|
2940
3195
|
},
|
|
3196
|
+
runBootRecovery: async ({ ownsMetaTable: bootOwnsMetaTable, restore }) => {
|
|
3197
|
+
assertValidMutationTransition("sending", "pending");
|
|
3198
|
+
const contexts = filterContexts(tableContexts, undefined);
|
|
3199
|
+
const tablesVisited = contexts.length;
|
|
3200
|
+
if (!bootOwnsMetaTable) {
|
|
3201
|
+
await runtime.recoverSending();
|
|
3202
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
3203
|
+
}
|
|
3204
|
+
if (restore) {
|
|
3205
|
+
await runtime.recoverSending();
|
|
3206
|
+
await runtime.quarantineRecovered();
|
|
3207
|
+
await settleRecoveryMarker();
|
|
3208
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
3209
|
+
}
|
|
3210
|
+
const marker = await readMutationRecoveryRequired(options.db, options.registry);
|
|
3211
|
+
if (marker === false) {
|
|
3212
|
+
return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };
|
|
3213
|
+
}
|
|
3214
|
+
if (marker === null) {
|
|
3215
|
+
await runtime.recoverSending();
|
|
3216
|
+
await writeMutationRecoveryRequired(options.db, options.registry, false);
|
|
3217
|
+
recoveryMarkerDirty = false;
|
|
3218
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
3219
|
+
}
|
|
3220
|
+
const nowUs = nowMicroseconds();
|
|
3221
|
+
let rowsRecovered = 0;
|
|
3222
|
+
await runInTransaction(async () => {
|
|
3223
|
+
for (const context of contexts) {
|
|
3224
|
+
const query = buildRecoverSendingQuery(context.tables.journal, nowUs);
|
|
3225
|
+
const result = await options.db.query(query.sql, query.params);
|
|
3226
|
+
rowsRecovered += readAffectedRows(result);
|
|
3227
|
+
}
|
|
3228
|
+
await clearMutationRecoveryMarkerIfSettled(options.db, options.registry);
|
|
3229
|
+
});
|
|
3230
|
+
recoveryMarkerDirty = false;
|
|
3231
|
+
return { skipped: false, required: true, tablesVisited, rowsRecovered };
|
|
3232
|
+
},
|
|
2941
3233
|
quarantineRecovered: async (table) => {
|
|
2942
3234
|
assertValidMutationTransition("pending", "quarantined");
|
|
2943
3235
|
assertValidMutationTransition("sending", "quarantined");
|
|
@@ -2964,17 +3256,19 @@ function createMutationRuntime(options) {
|
|
|
2964
3256
|
failedCount: 0,
|
|
2965
3257
|
quarantinedCount: 0,
|
|
2966
3258
|
conflictedCount: 0,
|
|
3259
|
+
rejectedCount: 0,
|
|
2967
3260
|
ackedCount: 0
|
|
2968
3261
|
};
|
|
2969
3262
|
for (const context of contexts) {
|
|
2970
3263
|
const journal = context.tables.journal;
|
|
2971
|
-
const filteredCount = (status, columnAlias) =>
|
|
3264
|
+
const filteredCount = (status, columnAlias) => sql4`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);
|
|
2972
3265
|
const query = queryBuilder.select({
|
|
2973
3266
|
pendingCount: filteredCount("pending", "pendingCount"),
|
|
2974
3267
|
sendingCount: filteredCount("sending", "sendingCount"),
|
|
2975
3268
|
failedCount: filteredCount("failed", "failedCount"),
|
|
2976
3269
|
quarantinedCount: filteredCount("quarantined", "quarantinedCount"),
|
|
2977
3270
|
conflictedCount: filteredCount("conflicted", "conflictedCount"),
|
|
3271
|
+
rejectedCount: filteredCount("rejected", "rejectedCount"),
|
|
2978
3272
|
ackedCount: filteredCount("acked", "ackedCount")
|
|
2979
3273
|
}).from(journal).toSQL();
|
|
2980
3274
|
const result = await options.db.query(query.sql, query.params);
|
|
@@ -2987,6 +3281,7 @@ function createMutationRuntime(options) {
|
|
|
2987
3281
|
totals.failedCount += row.failedCount;
|
|
2988
3282
|
totals.quarantinedCount += row.quarantinedCount;
|
|
2989
3283
|
totals.conflictedCount += row.conflictedCount;
|
|
3284
|
+
totals.rejectedCount += row.rejectedCount;
|
|
2990
3285
|
totals.ackedCount += row.ackedCount;
|
|
2991
3286
|
}
|
|
2992
3287
|
return totals;
|
|
@@ -3007,19 +3302,19 @@ async function readMutationDetailsForContexts(db, contexts, mutationIds) {
|
|
|
3007
3302
|
for (const context of contexts) {
|
|
3008
3303
|
const journal = context.tables.journal;
|
|
3009
3304
|
const query = queryBuilder.select({
|
|
3010
|
-
mutationId:
|
|
3011
|
-
entityKeyJson:
|
|
3012
|
-
mutationSeq:
|
|
3013
|
-
mutationKind:
|
|
3305
|
+
mutationId: sql4`${journal.mutationId}`.as("mutationId"),
|
|
3306
|
+
entityKeyJson: sql4`${journal.entityKeyJson}`.as("entityKeyJson"),
|
|
3307
|
+
mutationSeq: sql4`${journal.mutationSeq}`.as("mutationSeq"),
|
|
3308
|
+
mutationKind: sql4`${journal.mutationKind}`.as("mutationKind"),
|
|
3014
3309
|
status: journal.status,
|
|
3015
|
-
attemptCount:
|
|
3016
|
-
lastHttpStatus:
|
|
3017
|
-
lastError:
|
|
3018
|
-
conflictReason:
|
|
3019
|
-
nextRetryAtUs:
|
|
3020
|
-
serverUpdatedAtUs:
|
|
3021
|
-
updatedAtUs:
|
|
3022
|
-
registryVersion:
|
|
3310
|
+
attemptCount: sql4`${journal.attemptCount}`.as("attemptCount"),
|
|
3311
|
+
lastHttpStatus: sql4`${journal.lastHttpStatus}`.as("lastHttpStatus"),
|
|
3312
|
+
lastError: sql4`${journal.lastError}`.as("lastError"),
|
|
3313
|
+
conflictReason: sql4`${journal.conflictReason}`.as("conflictReason"),
|
|
3314
|
+
nextRetryAtUs: sql4`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
3315
|
+
serverUpdatedAtUs: sql4`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
3316
|
+
updatedAtUs: sql4`${journal.updatedAtUs}::text`.as("updatedAtUs"),
|
|
3317
|
+
registryVersion: sql4`${journal.registryVersion}`.as("registryVersion")
|
|
3023
3318
|
}).from(journal).orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq)).toSQL();
|
|
3024
3319
|
const result = await db.query(query.sql, query.params);
|
|
3025
3320
|
for (const row of result.rows) {
|
|
@@ -3235,10 +3530,10 @@ async function readLatestMutationStates(db, context, entities) {
|
|
|
3235
3530
|
}
|
|
3236
3531
|
const journal = context.tables.journal;
|
|
3237
3532
|
const query = queryBuilder.selectDistinctOn([journal.entityKeyJson], {
|
|
3238
|
-
entityKeyJson:
|
|
3239
|
-
latestMutationSeq:
|
|
3240
|
-
latestMutationKind:
|
|
3241
|
-
latestMutationStatus:
|
|
3533
|
+
entityKeyJson: sql4`${journal.entityKeyJson}`.as("entityKeyJson"),
|
|
3534
|
+
latestMutationSeq: sql4`${journal.mutationSeq}`.as("latestMutationSeq"),
|
|
3535
|
+
latestMutationKind: sql4`${journal.mutationKind}`.as("latestMutationKind"),
|
|
3536
|
+
latestMutationStatus: sql4`${journal.status}`.as("latestMutationStatus")
|
|
3242
3537
|
}).from(journal).where(inArray2(journal.entityKeyJson, entities.map((entity) => entity.entityKeyJson))).orderBy(journal.entityKeyJson, desc(journal.mutationSeq)).toSQL();
|
|
3243
3538
|
const result = await db.query(query.sql, query.params);
|
|
3244
3539
|
return new Map(result.rows.map((row) => [row.entityKeyJson, row]));
|
|
@@ -3255,8 +3550,8 @@ async function readCurrentRecordStates(db, context, entities) {
|
|
|
3255
3550
|
const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);
|
|
3256
3551
|
const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);
|
|
3257
3552
|
const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey["updatedAtUs"];
|
|
3258
|
-
const syncedLocalUpdated = hasProperty(context, "updatedAtUs") && syncedUpdatedAtColumn ?
|
|
3259
|
-
const query = queryDialect.sqlToQuery(
|
|
3553
|
+
const syncedLocalUpdated = hasProperty(context, "updatedAtUs") && syncedUpdatedAtColumn ? sql4`${syncedUpdatedAtColumn}::text AS "localUpdatedAtUs"` : sql4`'0' AS "localUpdatedAtUs"`;
|
|
3554
|
+
const query = queryDialect.sqlToQuery(sql4`
|
|
3260
3555
|
WITH ${inputCte},
|
|
3261
3556
|
overlay_rows AS (
|
|
3262
3557
|
SELECT
|
|
@@ -3330,9 +3625,9 @@ async function upsertOverlayRecordsBulk(db, context, rows) {
|
|
|
3330
3625
|
localUpdatedAtUs: row.localUpdatedAtUs
|
|
3331
3626
|
}));
|
|
3332
3627
|
const excludedSet = Object.fromEntries([
|
|
3333
|
-
...context.columns.map(({ propertyKey, column }) => [propertyKey,
|
|
3334
|
-
["overlayKind",
|
|
3335
|
-
["localUpdatedAtUs",
|
|
3628
|
+
...context.columns.map(({ propertyKey, column }) => [propertyKey, sql4`excluded.${sql4.identifier(column.name)}`]),
|
|
3629
|
+
["overlayKind", sql4`excluded.${sql4.identifier(overlay.overlayKind.name)}`],
|
|
3630
|
+
["localUpdatedAtUs", sql4`excluded.${sql4.identifier(overlay.localUpdatedAtUs.name)}`]
|
|
3336
3631
|
]);
|
|
3337
3632
|
const query = queryBuilder.insert(overlay).values(values).onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet }).toSQL();
|
|
3338
3633
|
await db.query(query.sql, query.params);
|
|
@@ -3341,16 +3636,16 @@ function buildEntityInputCte(context, entities) {
|
|
|
3341
3636
|
const columnNames = ["entity_key_json", ...context.pkColumnNames];
|
|
3342
3637
|
const tuples = entities.map((entity) => {
|
|
3343
3638
|
const values = [
|
|
3344
|
-
|
|
3639
|
+
sql4`${entity.entityKeyJson}`,
|
|
3345
3640
|
...context.pkColumnNames.map((columnName) => {
|
|
3346
3641
|
const columnEntry = context.columns.find(({ column }) => column.name === columnName);
|
|
3347
3642
|
const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : "";
|
|
3348
|
-
return castSuffix ?
|
|
3643
|
+
return castSuffix ? sql4`${entity.entityKey[columnName]}${sql4.raw(castSuffix)}` : sql4`${entity.entityKey[columnName]}`;
|
|
3349
3644
|
})
|
|
3350
3645
|
];
|
|
3351
|
-
return
|
|
3646
|
+
return sql4`(${sql4.join(values, sql4`, `)})`;
|
|
3352
3647
|
});
|
|
3353
|
-
return
|
|
3648
|
+
return sql4`input_entities (${sql4.join(columnNames.map((columnName) => sql4.identifier(columnName)), sql4`, `)}) AS (VALUES ${sql4.join(tuples, sql4`, `)})`;
|
|
3354
3649
|
}
|
|
3355
3650
|
function resolveInputCastSuffix(columnType) {
|
|
3356
3651
|
switch (columnType) {
|
|
@@ -3373,49 +3668,49 @@ function resolveInputCastSuffix(columnType) {
|
|
|
3373
3668
|
}
|
|
3374
3669
|
}
|
|
3375
3670
|
function buildProjectedSelectColumns(context, columnsByPropertyKey) {
|
|
3376
|
-
return
|
|
3671
|
+
return sql4.join(context.columns.map(({ propertyKey, column }) => {
|
|
3377
3672
|
const target = columnsByPropertyKey[propertyKey];
|
|
3378
3673
|
if (!target) {
|
|
3379
3674
|
throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);
|
|
3380
3675
|
}
|
|
3381
3676
|
if (column.columnType === "PgBigInt64" || column.columnType === "PgBigInt53") {
|
|
3382
|
-
return
|
|
3677
|
+
return sql4`${target}::text AS ${sql4.identifier(propertyKey)}`;
|
|
3383
3678
|
}
|
|
3384
|
-
return
|
|
3385
|
-
}),
|
|
3679
|
+
return sql4`${target} AS ${sql4.identifier(propertyKey)}`;
|
|
3680
|
+
}), sql4`, `);
|
|
3386
3681
|
}
|
|
3387
3682
|
function buildEntityInputJoin(pkColumnNames, pkColumns) {
|
|
3388
|
-
return
|
|
3683
|
+
return sql4.join(pkColumnNames.map((columnName, index2) => sql4`${pkColumns[index2]} = input.${sql4.identifier(columnName)}`), sql4` AND `);
|
|
3389
3684
|
}
|
|
3390
3685
|
function buildResolvedBaseServerVersion(context) {
|
|
3391
3686
|
const journal = context.tables.journal;
|
|
3392
3687
|
const synced = context.tables.synced;
|
|
3393
3688
|
const pred = alias(journal, "pred");
|
|
3394
|
-
const predecessor = queryBuilder.select({ value:
|
|
3689
|
+
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
3690
|
if (!context.syncedServerVersionColumn) {
|
|
3396
|
-
return
|
|
3691
|
+
return sql4`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;
|
|
3397
3692
|
}
|
|
3398
|
-
const syncedFallback = queryBuilder.select({ value:
|
|
3399
|
-
return
|
|
3693
|
+
const syncedFallback = queryBuilder.select({ value: sql4`${context.syncedServerVersionColumn}` }).from(synced).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.syncedPkColumns[index2], journal[columnName]))));
|
|
3694
|
+
return sql4`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;
|
|
3400
3695
|
}
|
|
3401
3696
|
function buildPendingRowsProjection(context) {
|
|
3402
3697
|
const journal = context.tables.journal;
|
|
3403
3698
|
return {
|
|
3404
|
-
tableKey:
|
|
3405
|
-
mutationId:
|
|
3406
|
-
entityKeyJson:
|
|
3407
|
-
mutationSeq:
|
|
3408
|
-
mutationKind:
|
|
3699
|
+
tableKey: sql4`${context.key}`.as("tableKey"),
|
|
3700
|
+
mutationId: sql4`${journal.mutationId}`.as("mutationId"),
|
|
3701
|
+
entityKeyJson: sql4`${journal.entityKeyJson}`.as("entityKeyJson"),
|
|
3702
|
+
mutationSeq: sql4`${journal.mutationSeq}`.as("mutationSeq"),
|
|
3703
|
+
mutationKind: sql4`${journal.mutationKind}`.as("mutationKind"),
|
|
3409
3704
|
status: journal.status,
|
|
3410
|
-
payloadJson:
|
|
3411
|
-
attemptCount:
|
|
3412
|
-
lastHttpStatus:
|
|
3413
|
-
lastError:
|
|
3414
|
-
conflictReason:
|
|
3415
|
-
nextRetryAtUs:
|
|
3416
|
-
serverUpdatedAtUs:
|
|
3705
|
+
payloadJson: sql4`${journal.payloadJson}`.as("payloadJson"),
|
|
3706
|
+
attemptCount: sql4`${journal.attemptCount}`.as("attemptCount"),
|
|
3707
|
+
lastHttpStatus: sql4`${journal.lastHttpStatus}`.as("lastHttpStatus"),
|
|
3708
|
+
lastError: sql4`${journal.lastError}`.as("lastError"),
|
|
3709
|
+
conflictReason: sql4`${journal.conflictReason}`.as("conflictReason"),
|
|
3710
|
+
nextRetryAtUs: sql4`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
3711
|
+
serverUpdatedAtUs: sql4`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
3417
3712
|
baseServerVersion: buildResolvedBaseServerVersion(context).as("baseServerVersion"),
|
|
3418
|
-
enqueuedAtUs:
|
|
3713
|
+
enqueuedAtUs: sql4`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs")
|
|
3419
3714
|
};
|
|
3420
3715
|
}
|
|
3421
3716
|
async function readPendingBatchRows(db, contexts, nowUs, batchSize) {
|
|
@@ -3425,9 +3720,9 @@ async function readPendingBatchRows(db, contexts, nowUs, batchSize) {
|
|
|
3425
3720
|
const branches = contexts.map((context) => {
|
|
3426
3721
|
const journal = context.tables.journal;
|
|
3427
3722
|
const earlier = alias(journal, "earlier");
|
|
3428
|
-
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(
|
|
3723
|
+
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
3724
|
});
|
|
3430
|
-
const query = queryDialect.sqlToQuery(
|
|
3725
|
+
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
3726
|
const result = await db.query(query.sql, query.params);
|
|
3432
3727
|
return result.rows;
|
|
3433
3728
|
}
|
|
@@ -3437,13 +3732,13 @@ async function readUnitPendingRows(db, contexts, unitId) {
|
|
|
3437
3732
|
}
|
|
3438
3733
|
const branches = contexts.map((context) => {
|
|
3439
3734
|
const journal = context.tables.journal;
|
|
3440
|
-
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(
|
|
3735
|
+
return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and4(eq4(journal.writeUnit, unitId), inArray2(journal.status, ["pending", "failed"])));
|
|
3441
3736
|
});
|
|
3442
|
-
const query = queryDialect.sqlToQuery(
|
|
3737
|
+
const query = queryDialect.sqlToQuery(sql4`SELECT * FROM (${sql4.join(branches, sql4` UNION ALL `)}) AS unit ORDER BY unit."mutationSeq" ASC`);
|
|
3443
3738
|
const result = await db.query(query.sql, query.params);
|
|
3444
3739
|
return result.rows;
|
|
3445
3740
|
}
|
|
3446
|
-
async function flushBatch(db, tableContexts, batchWriteUrl, maxAttempts, batchSize, tableFilter, getAuthToken, requestHeaders) {
|
|
3741
|
+
async function flushBatch(db, tableContexts, batchWriteUrl, maxAttempts, batchSize, tableFilter, getAuthToken, requestHeaders, ensureRecoveryMarker, markSendingScope) {
|
|
3447
3742
|
const contexts = filterContexts(tableContexts, tableFilter);
|
|
3448
3743
|
const nowUs = nowMicroseconds();
|
|
3449
3744
|
const quarantinedMutationIds = [];
|
|
@@ -3498,7 +3793,7 @@ async function flushBatch(db, tableContexts, batchWriteUrl, maxAttempts, batchSi
|
|
|
3498
3793
|
nextRetryAtUs: null,
|
|
3499
3794
|
lastHttpStatus: null,
|
|
3500
3795
|
conflictReason: null
|
|
3501
|
-
})));
|
|
3796
|
+
})), ensureRecoveryMarker, markSendingScope);
|
|
3502
3797
|
}
|
|
3503
3798
|
const mutations = pending.map((row) => {
|
|
3504
3799
|
return {
|
|
@@ -3736,7 +4031,7 @@ async function discardTerminalEntity(db, context, entityKey, entityKeyJson, term
|
|
|
3736
4031
|
await db.exec("BEGIN");
|
|
3737
4032
|
try {
|
|
3738
4033
|
const journal = context.tables.journal;
|
|
3739
|
-
const clearQuery = queryBuilder.delete(journal).where(
|
|
4034
|
+
const clearQuery = queryBuilder.delete(journal).where(and4(eq4(journal.status, terminalStatus), eq4(journal.entityKeyJson, entityKeyJson))).toSQL();
|
|
3740
4035
|
await db.query(clearQuery.sql, clearQuery.params);
|
|
3741
4036
|
const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);
|
|
3742
4037
|
await db.query(overlayQuery.sql, overlayQuery.params);
|
|
@@ -3749,8 +4044,8 @@ async function discardTerminalEntity(db, context, entityKey, entityKeyJson, term
|
|
|
3749
4044
|
function buildOverlayDiscardQuery(context, entityKey, entityKeyJson, owedStatuses) {
|
|
3750
4045
|
const overlay = context.tables.overlay;
|
|
3751
4046
|
const journal = context.tables.journal;
|
|
3752
|
-
const owed = queryBuilder.select({ one:
|
|
3753
|
-
return queryBuilder.delete(overlay).where(
|
|
4047
|
+
const owed = queryBuilder.select({ one: sql4`1` }).from(journal).where(owedStatuses ? and4(eq4(journal.entityKeyJson, entityKeyJson), inArray2(journal.status, owedStatuses)) : eq4(journal.entityKeyJson, entityKeyJson));
|
|
4048
|
+
return queryBuilder.delete(overlay).where(and4(...context.pkColumnNames.map((columnName, index2) => eq4(context.overlayPkColumns[index2], entityKey[columnName])), notExists2(owed))).toSQL();
|
|
3754
4049
|
}
|
|
3755
4050
|
async function discardOverlayForSettledEntity(db, context, entityKey, entityKeyJson) {
|
|
3756
4051
|
const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
|
|
@@ -3762,7 +4057,7 @@ async function reconcileTable(db, context) {
|
|
|
3762
4057
|
const synced = context.tables.synced;
|
|
3763
4058
|
let idleProbe = context.reconcileIdleProbe;
|
|
3764
4059
|
if (!idleProbe) {
|
|
3765
|
-
const probeQuery = queryDialect.sqlToQuery(
|
|
4060
|
+
const probeQuery = queryDialect.sqlToQuery(sql4`SELECT ${exists(queryBuilder.select({ one: sql4`1` }).from(journal).where(inArray2(journal.status, ["acked", "conflicted"])))} AS "hasWork"`);
|
|
3766
4061
|
idleProbe = { sql: probeQuery.sql, params: probeQuery.params };
|
|
3767
4062
|
context.reconcileIdleProbe = idleProbe;
|
|
3768
4063
|
}
|
|
@@ -3773,28 +4068,28 @@ async function reconcileTable(db, context) {
|
|
|
3773
4068
|
await db.exec("BEGIN");
|
|
3774
4069
|
try {
|
|
3775
4070
|
const resolver = alias(journal, "resolver");
|
|
3776
|
-
const retireQuery = queryBuilder.delete(journal).where(
|
|
4071
|
+
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
4072
|
await db.query(retireQuery.sql, retireQuery.params);
|
|
3778
|
-
const blindRetireQuery = queryBuilder.delete(journal).where(
|
|
4073
|
+
const blindRetireQuery = queryBuilder.delete(journal).where(and4(eq4(journal.status, "acked"), eq4(journal.writeMode, "pessimistic-blind"))).toSQL();
|
|
3779
4074
|
await db.query(blindRetireQuery.sql, blindRetireQuery.params);
|
|
3780
|
-
const barrier =
|
|
4075
|
+
const barrier = sql4.raw(buildOverlayResolutionBarrier2(context.entry, {
|
|
3781
4076
|
journalAlias: quoteIdentifier5(getTableConfig6(journal).name),
|
|
3782
4077
|
syncedAlias: quoteIdentifier5(getTableConfig6(synced).name)
|
|
3783
4078
|
}));
|
|
3784
|
-
const clearedJournal = queryBuilder.$with("cleared_journal").as(queryBuilder.delete(journal).where(
|
|
4079
|
+
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
4080
|
["entity_key_json", journal.entityKeyJson],
|
|
3786
4081
|
...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]])
|
|
3787
4082
|
])));
|
|
3788
4083
|
const clearedJournalColumns = clearedJournal;
|
|
3789
|
-
const ackedClearQuery = queryBuilder.with(clearedJournal).delete(overlay).where(exists(queryBuilder.select({ one:
|
|
4084
|
+
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
4085
|
await db.query(ackedClearQuery.sql, ackedClearQuery.params);
|
|
3791
4086
|
const clearableEntities = queryBuilder.$with("clearable_entities").as(queryBuilder.selectDistinct(Object.fromEntries([
|
|
3792
4087
|
["entity_key_json", journal.entityKeyJson],
|
|
3793
4088
|
...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]])
|
|
3794
|
-
])).from(journal).leftJoin(synced,
|
|
4089
|
+
])).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
4090
|
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(
|
|
4091
|
+
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])))))));
|
|
4092
|
+
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
4093
|
await db.query(deleteClearQuery.sql, deleteClearQuery.params);
|
|
3799
4094
|
await db.exec("COMMIT");
|
|
3800
4095
|
} catch (error) {
|
|
@@ -3809,26 +4104,40 @@ function buildRequestHeaders(bearerToken, requestHeaders) {
|
|
|
3809
4104
|
...bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}
|
|
3810
4105
|
};
|
|
3811
4106
|
}
|
|
3812
|
-
async function applyMutationStatusUpdates(db, context, updates) {
|
|
4107
|
+
async function applyMutationStatusUpdates(db, context, updates, onBeforeMarkSending, markSendingScope) {
|
|
3813
4108
|
if (updates.length === 0) {
|
|
3814
4109
|
return;
|
|
3815
4110
|
}
|
|
4111
|
+
const marksSending = updates.some((update) => update.status === "sending");
|
|
4112
|
+
if (marksSending)
|
|
4113
|
+
markSendingScope?.enter();
|
|
4114
|
+
try {
|
|
4115
|
+
if (onBeforeMarkSending && marksSending) {
|
|
4116
|
+
await onBeforeMarkSending();
|
|
4117
|
+
}
|
|
4118
|
+
await execMutationStatusUpdates(db, context, updates);
|
|
4119
|
+
} finally {
|
|
4120
|
+
if (marksSending)
|
|
4121
|
+
markSendingScope?.exit();
|
|
4122
|
+
}
|
|
4123
|
+
}
|
|
4124
|
+
async function execMutationStatusUpdates(db, context, updates) {
|
|
3816
4125
|
const journal = context.tables.journal;
|
|
3817
|
-
const tuples = updates.map((update) =>
|
|
3818
|
-
const updatesTable =
|
|
4126
|
+
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})`);
|
|
4127
|
+
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
4128
|
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,
|
|
4129
|
+
status: sql4`updates.status`,
|
|
4130
|
+
attemptCount: sql4`updates.attempt_count`,
|
|
4131
|
+
updatedAtUs: sql4`updates.updated_at_us::bigint`,
|
|
4132
|
+
sentAtUs: sql4`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,
|
|
4133
|
+
ackedAtUs: sql4`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,
|
|
4134
|
+
serverUpdatedAtUs: sql4`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,
|
|
4135
|
+
baseServerVersion: sql4`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,
|
|
4136
|
+
lastError: sql4`updates.last_error`,
|
|
4137
|
+
nextRetryAtUs: sql4`updates.next_retry_at_us::bigint`,
|
|
4138
|
+
lastHttpStatus: sql4`updates.last_http_status`,
|
|
4139
|
+
conflictReason: sql4`updates.conflict_reason`
|
|
4140
|
+
}).from(updatesTable).where(eq4(journal.mutationId, sql4`updates.mutation_id::uuid`)).toSQL();
|
|
3832
4141
|
await db.query(query.sql, query.params);
|
|
3833
4142
|
}
|
|
3834
4143
|
function qualifyLocalIdentifier(schemaName, tableName) {
|
|
@@ -3881,6 +4190,141 @@ function parseBatchRejections(body) {
|
|
|
3881
4190
|
return rejections && rejections.length > 0 ? rejections : null;
|
|
3882
4191
|
}
|
|
3883
4192
|
|
|
4193
|
+
// packages/client/src/mutations-api.ts
|
|
4194
|
+
import { and as and5, desc as desc2, eq as eq5, inArray as inArray3, sql as sql5 } from "drizzle-orm";
|
|
4195
|
+
import { drizzle as drizzle4 } from "drizzle-orm/pglite";
|
|
4196
|
+
var queryBuilderInstance;
|
|
4197
|
+
function queryBuilder2() {
|
|
4198
|
+
return queryBuilderInstance ??= drizzle4.mock();
|
|
4199
|
+
}
|
|
4200
|
+
var STATUS_TO_SUMMARY_KEY = {
|
|
4201
|
+
pending: "pendingCount",
|
|
4202
|
+
sending: "sendingCount",
|
|
4203
|
+
acked: "ackedCount",
|
|
4204
|
+
failed: "failedCount",
|
|
4205
|
+
quarantined: "quarantinedCount",
|
|
4206
|
+
conflicted: "conflictedCount",
|
|
4207
|
+
rejected: "rejectedCount"
|
|
4208
|
+
};
|
|
4209
|
+
function emptySummary() {
|
|
4210
|
+
return {
|
|
4211
|
+
pendingCount: 0,
|
|
4212
|
+
sendingCount: 0,
|
|
4213
|
+
ackedCount: 0,
|
|
4214
|
+
failedCount: 0,
|
|
4215
|
+
rejectedCount: 0,
|
|
4216
|
+
conflictedCount: 0,
|
|
4217
|
+
quarantinedCount: 0,
|
|
4218
|
+
unsettledCount: 0,
|
|
4219
|
+
settledCount: 0
|
|
4220
|
+
};
|
|
4221
|
+
}
|
|
4222
|
+
function foldSummary(rows) {
|
|
4223
|
+
const summary = emptySummary();
|
|
4224
|
+
for (const row of rows) {
|
|
4225
|
+
const key = STATUS_TO_SUMMARY_KEY[row.status];
|
|
4226
|
+
if (key) {
|
|
4227
|
+
summary[key] = Number(row.count);
|
|
4228
|
+
}
|
|
4229
|
+
}
|
|
4230
|
+
summary.unsettledCount = summary.pendingCount + summary.sendingCount + summary.failedCount + summary.conflictedCount + summary.quarantinedCount;
|
|
4231
|
+
summary.settledCount = summary.ackedCount + summary.rejectedCount;
|
|
4232
|
+
return summary;
|
|
4233
|
+
}
|
|
4234
|
+
function mapDetailRow(row) {
|
|
4235
|
+
return {
|
|
4236
|
+
tableName: row.tableName,
|
|
4237
|
+
entityKey: JSON.parse(row.entityKeyJson),
|
|
4238
|
+
mutationId: row.mutationId,
|
|
4239
|
+
mutationSeq: Number(row.mutationSeq),
|
|
4240
|
+
mutationKind: row.mutationKind,
|
|
4241
|
+
status: row.status,
|
|
4242
|
+
attemptCount: Number(row.attemptCount),
|
|
4243
|
+
lastHttpStatus: row.lastHttpStatus,
|
|
4244
|
+
lastError: row.lastError,
|
|
4245
|
+
conflictReason: row.conflictReason,
|
|
4246
|
+
nextRetryAtUs: row.nextRetryAtUs,
|
|
4247
|
+
serverUpdatedAtUs: row.serverUpdatedAtUs,
|
|
4248
|
+
updatedAtUs: row.updatedAtUs,
|
|
4249
|
+
registryVersion: row.registryVersion
|
|
4250
|
+
};
|
|
4251
|
+
}
|
|
4252
|
+
function hasWritableTable(registry) {
|
|
4253
|
+
return Object.values(registry).some((entry) => entry.mode !== "readonly" && entry.clientProjection?.journalTable);
|
|
4254
|
+
}
|
|
4255
|
+
function buildSummarySql(registry) {
|
|
4256
|
+
const view = getAllMutationsView(registry);
|
|
4257
|
+
return queryBuilder2().select({ status: view.status, count: sql5`count(*)::int`.as("count") }).from(view).groupBy(view.status).toSQL();
|
|
4258
|
+
}
|
|
4259
|
+
function buildDetailSql(registry, options) {
|
|
4260
|
+
const view = getAllMutationsView(registry);
|
|
4261
|
+
const conditions = [];
|
|
4262
|
+
if (options?.table != null) {
|
|
4263
|
+
conditions.push(eq5(view.tableKey, options.table));
|
|
4264
|
+
}
|
|
4265
|
+
if (options?.entityKey != null) {
|
|
4266
|
+
conditions.push(eq5(view.entityKeyJson, JSON.stringify(options.entityKey)));
|
|
4267
|
+
}
|
|
4268
|
+
if (options?.statuses != null && options.statuses.length > 0) {
|
|
4269
|
+
conditions.push(inArray3(view.status, options.statuses));
|
|
4270
|
+
}
|
|
4271
|
+
const base = queryBuilder2().select({
|
|
4272
|
+
tableName: sql5`${view.tableKey}`.as("tableName"),
|
|
4273
|
+
entityKeyJson: sql5`${view.entityKeyJson}`.as("entityKeyJson"),
|
|
4274
|
+
mutationId: sql5`${view.mutationId}`.as("mutationId"),
|
|
4275
|
+
mutationSeq: sql5`${view.mutationSeq}`.as("mutationSeq"),
|
|
4276
|
+
mutationKind: sql5`${view.mutationKind}`.as("mutationKind"),
|
|
4277
|
+
status: sql5`${view.status}`.as("status"),
|
|
4278
|
+
attemptCount: sql5`${view.attemptCount}`.as("attemptCount"),
|
|
4279
|
+
lastHttpStatus: sql5`${view.lastHttpStatus}`.as("lastHttpStatus"),
|
|
4280
|
+
lastError: sql5`${view.lastError}`.as("lastError"),
|
|
4281
|
+
conflictReason: sql5`${view.conflictReason}`.as("conflictReason"),
|
|
4282
|
+
nextRetryAtUs: sql5`${view.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
4283
|
+
serverUpdatedAtUs: sql5`${view.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
4284
|
+
updatedAtUs: sql5`${view.updatedAtUs}::text`.as("updatedAtUs"),
|
|
4285
|
+
registryVersion: sql5`${view.registryVersion}`.as("registryVersion")
|
|
4286
|
+
}).from(view).where(conditions.length > 0 ? and5(...conditions) : undefined).orderBy(desc2(view.enqueuedAtUs), desc2(view.mutationId));
|
|
4287
|
+
return (options?.limit != null ? base.limit(options.limit) : base).toSQL();
|
|
4288
|
+
}
|
|
4289
|
+
function createMutationsApi(deps) {
|
|
4290
|
+
const { registry, subscribeLiveRows, query } = deps;
|
|
4291
|
+
const writable = hasWritableTable(registry);
|
|
4292
|
+
return {
|
|
4293
|
+
summary: async () => {
|
|
4294
|
+
if (!writable) {
|
|
4295
|
+
return emptySummary();
|
|
4296
|
+
}
|
|
4297
|
+
const built = buildSummarySql(registry);
|
|
4298
|
+
const { rows } = await query(built.sql, built.params);
|
|
4299
|
+
return foldSummary(rows);
|
|
4300
|
+
},
|
|
4301
|
+
subscribeSummary: async (listener) => {
|
|
4302
|
+
if (!writable) {
|
|
4303
|
+
return { initial: emptySummary(), unsubscribe: () => {} };
|
|
4304
|
+
}
|
|
4305
|
+
const built = buildSummarySql(registry);
|
|
4306
|
+
const subscription = await subscribeLiveRows({ sql: built.sql, params: built.params }, (rows) => listener(foldSummary(rows)));
|
|
4307
|
+
return { initial: foldSummary(subscription.initialRows), unsubscribe: subscription.unsubscribe };
|
|
4308
|
+
},
|
|
4309
|
+
list: async (options) => {
|
|
4310
|
+
if (!writable) {
|
|
4311
|
+
return [];
|
|
4312
|
+
}
|
|
4313
|
+
const built = buildDetailSql(registry, options);
|
|
4314
|
+
const { rows } = await query(built.sql, built.params);
|
|
4315
|
+
return rows.map(mapDetailRow);
|
|
4316
|
+
},
|
|
4317
|
+
subscribe: async (options, listener) => {
|
|
4318
|
+
if (!writable) {
|
|
4319
|
+
return { initial: [], unsubscribe: () => {} };
|
|
4320
|
+
}
|
|
4321
|
+
const built = buildDetailSql(registry, options);
|
|
4322
|
+
const subscription = await subscribeLiveRows({ sql: built.sql, params: built.params }, (rows) => listener(rows.map(mapDetailRow)));
|
|
4323
|
+
return { initial: subscription.initialRows.map(mapDetailRow), unsubscribe: subscription.unsubscribe };
|
|
4324
|
+
}
|
|
4325
|
+
};
|
|
4326
|
+
}
|
|
4327
|
+
|
|
3884
4328
|
// packages/client/src/sync-auth.ts
|
|
3885
4329
|
function buildShapeHeaders(input) {
|
|
3886
4330
|
const headers = { ...input.requestHeaders ?? {} };
|
|
@@ -3992,6 +4436,7 @@ async function startConfiguredSync(pg, input) {
|
|
|
3992
4436
|
groupKey: group.groupKey,
|
|
3993
4437
|
specs: group.specs,
|
|
3994
4438
|
registry: input.registry,
|
|
4439
|
+
...group.retention === "ephemeral" ? { sessionScoped: true } : {},
|
|
3995
4440
|
...bootStamp ? { bootStamp } : {},
|
|
3996
4441
|
...countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {},
|
|
3997
4442
|
...input.shapeHeaders ? { headers: input.shapeHeaders } : {},
|
|
@@ -4089,6 +4534,7 @@ async function startGroupSync(pg, input) {
|
|
|
4089
4534
|
key: input.groupKey,
|
|
4090
4535
|
registry: input.registry,
|
|
4091
4536
|
shapes,
|
|
4537
|
+
...input.sessionScoped ? { sessionScoped: input.sessionScoped } : {},
|
|
4092
4538
|
...input.dbReady ? { dbReady: input.dbReady } : {},
|
|
4093
4539
|
...input.bootStamp ? { bootStamp: input.bootStamp } : {},
|
|
4094
4540
|
...input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {},
|
|
@@ -4123,7 +4569,7 @@ function groupSubscriptionKey(spec) {
|
|
|
4123
4569
|
// packages/client/src/sync/index.ts
|
|
4124
4570
|
import { isChangeMessage, isControlMessage } from "@electric-sql/client";
|
|
4125
4571
|
import { MultiShapeStream } from "@electric-sql/experimental";
|
|
4126
|
-
import { sql as
|
|
4572
|
+
import { sql as sql6 } from "drizzle-orm";
|
|
4127
4573
|
import { getTableConfig as getTableConfig7 } from "drizzle-orm/pg-core";
|
|
4128
4574
|
import { classifyTableApplyStrategy } from "@pgxsinkit/contracts";
|
|
4129
4575
|
|
|
@@ -4434,15 +4880,16 @@ function foldKey(key, ops, folded) {
|
|
|
4434
4880
|
}
|
|
4435
4881
|
|
|
4436
4882
|
// packages/client/src/sync/subscription-state.ts
|
|
4437
|
-
import { eq as
|
|
4883
|
+
import { eq as eq6 } from "drizzle-orm";
|
|
4438
4884
|
import { quoteIdentifier as quoteIdentifier6 } from "@pgxsinkit/contracts";
|
|
4439
4885
|
async function getSubscriptionState({
|
|
4440
4886
|
pg,
|
|
4441
4887
|
metadataSchema,
|
|
4442
|
-
subscriptionKey
|
|
4888
|
+
subscriptionKey,
|
|
4889
|
+
sessionScoped = false
|
|
4443
4890
|
}) {
|
|
4444
|
-
const { subscriptionsMetadata } =
|
|
4445
|
-
const rows = await drizzleOverPg(pg).select().from(subscriptionsMetadata).where(
|
|
4891
|
+
const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
4892
|
+
const rows = await drizzleOverPg(pg).select().from(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
|
|
4446
4893
|
if (rows.length === 0) {
|
|
4447
4894
|
return null;
|
|
4448
4895
|
}
|
|
@@ -4474,12 +4921,13 @@ async function updateSubscriptionState({
|
|
|
4474
4921
|
subscriptionKey,
|
|
4475
4922
|
shapeMetadata,
|
|
4476
4923
|
lastLsn,
|
|
4477
|
-
debug
|
|
4924
|
+
debug,
|
|
4925
|
+
sessionScoped = false
|
|
4478
4926
|
}) {
|
|
4479
4927
|
if (debug) {
|
|
4480
4928
|
console.log("updating subscription state", subscriptionKey, shapeMetadata, lastLsn);
|
|
4481
4929
|
}
|
|
4482
|
-
const { subscriptionsMetadata } =
|
|
4930
|
+
const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
4483
4931
|
const lastLsnText = lastLsn.toString();
|
|
4484
4932
|
await drizzleOverPg(pg).insert(subscriptionsMetadata).values({ key: subscriptionKey, shape_metadata: shapeMetadata, last_lsn: lastLsnText }).onConflictDoUpdate({
|
|
4485
4933
|
target: subscriptionsMetadata.key,
|
|
@@ -4487,19 +4935,25 @@ async function updateSubscriptionState({
|
|
|
4487
4935
|
});
|
|
4488
4936
|
}
|
|
4489
4937
|
async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }) {
|
|
4938
|
+
const db = drizzleOverPg(pg);
|
|
4490
4939
|
const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
|
|
4491
|
-
|
|
4940
|
+
const session = getSessionMetadataTables();
|
|
4941
|
+
await db.delete(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
|
|
4942
|
+
await db.delete(session.subscriptionsMetadata).where(eq6(session.subscriptionsMetadata.key, subscriptionKey));
|
|
4492
4943
|
}
|
|
4493
4944
|
async function migrateSubscriptionMetadataTables({
|
|
4494
4945
|
pg,
|
|
4495
4946
|
metadataSchema
|
|
4496
4947
|
}) {
|
|
4497
4948
|
const { subscriptionsMetadata, shapeRowTags } = getMetadataTables(metadataSchema);
|
|
4949
|
+
const session = getSessionMetadataTables();
|
|
4498
4950
|
const statements = [
|
|
4499
4951
|
`SET ${metadataSchema}.syncing = false;`,
|
|
4500
4952
|
`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier6(metadataSchema)};`,
|
|
4501
4953
|
...renderCreateTableSql(subscriptionsMetadata),
|
|
4502
|
-
...renderCreateTableSql(shapeRowTags)
|
|
4954
|
+
...renderCreateTableSql(shapeRowTags),
|
|
4955
|
+
...renderCreateTableSql(session.subscriptionsMetadata, { temp: true }),
|
|
4956
|
+
...renderCreateTableSql(session.shapeRowTags, { temp: true })
|
|
4503
4957
|
];
|
|
4504
4958
|
await pg.exec(statements.join(`
|
|
4505
4959
|
`));
|
|
@@ -4559,6 +5013,7 @@ async function createSyncEngine(pg, options) {
|
|
|
4559
5013
|
key,
|
|
4560
5014
|
registry,
|
|
4561
5015
|
shapes,
|
|
5016
|
+
sessionScoped = false,
|
|
4562
5017
|
initialInsertMethod,
|
|
4563
5018
|
onInitialSync,
|
|
4564
5019
|
onError,
|
|
@@ -4600,7 +5055,8 @@ async function createSyncEngine(pg, options) {
|
|
|
4600
5055
|
subState = await getSubscriptionState({
|
|
4601
5056
|
pg,
|
|
4602
5057
|
metadataSchema,
|
|
4603
|
-
subscriptionKey: key
|
|
5058
|
+
subscriptionKey: key,
|
|
5059
|
+
sessionScoped
|
|
4604
5060
|
});
|
|
4605
5061
|
if (debug && subState) {
|
|
4606
5062
|
console.log("resuming from subscription state", subState);
|
|
@@ -4704,9 +5160,9 @@ async function createSyncEngine(pg, options) {
|
|
|
4704
5160
|
if (shape.onMustRefetch) {
|
|
4705
5161
|
await shape.onMustRefetch(drizzleOverPg(tx));
|
|
4706
5162
|
} else {
|
|
4707
|
-
await drizzleOverPg(tx).execute(
|
|
5163
|
+
await drizzleOverPg(tx).execute(sql6`TRUNCATE ${target.table}`);
|
|
4708
5164
|
}
|
|
4709
|
-
await clearShapeTags({ pg: tx, metadataSchema, shapeTable });
|
|
5165
|
+
await clearShapeTags({ pg: tx, metadataSchema, shapeTable, sessionScoped });
|
|
4710
5166
|
}
|
|
4711
5167
|
const moveInMessages = moveInsToCommit.get(shapeName) ?? [];
|
|
4712
5168
|
if (moveInMessages.length > 0) {
|
|
@@ -4715,7 +5171,8 @@ async function createSyncEngine(pg, options) {
|
|
|
4715
5171
|
metadataSchema,
|
|
4716
5172
|
shapeTable,
|
|
4717
5173
|
messages: moveInMessages,
|
|
4718
|
-
primaryKey: target.primaryKey
|
|
5174
|
+
primaryKey: target.primaryKey,
|
|
5175
|
+
sessionScoped
|
|
4719
5176
|
});
|
|
4720
5177
|
}
|
|
4721
5178
|
await applyShapeTagSync({
|
|
@@ -4723,7 +5180,8 @@ async function createSyncEngine(pg, options) {
|
|
|
4723
5180
|
metadataSchema,
|
|
4724
5181
|
shapeTable,
|
|
4725
5182
|
messages: initialMessages,
|
|
4726
|
-
primaryKey: target.primaryKey
|
|
5183
|
+
primaryKey: target.primaryKey,
|
|
5184
|
+
sessionScoped
|
|
4727
5185
|
});
|
|
4728
5186
|
if (moveInMessages.length > 0) {
|
|
4729
5187
|
await applyUpsertsToTable({
|
|
@@ -4803,7 +5261,8 @@ async function createSyncEngine(pg, options) {
|
|
|
4803
5261
|
shapeTable,
|
|
4804
5262
|
target,
|
|
4805
5263
|
patternSets,
|
|
4806
|
-
debug
|
|
5264
|
+
debug,
|
|
5265
|
+
sessionScoped
|
|
4807
5266
|
});
|
|
4808
5267
|
}
|
|
4809
5268
|
}
|
|
@@ -4812,6 +5271,7 @@ async function createSyncEngine(pg, options) {
|
|
|
4812
5271
|
pg: tx,
|
|
4813
5272
|
metadataSchema,
|
|
4814
5273
|
subscriptionKey: key,
|
|
5274
|
+
sessionScoped,
|
|
4815
5275
|
shapeMetadata: Object.fromEntries(Object.keys(shapes).map((shapeName) => {
|
|
4816
5276
|
const stream = getShapeStream(shapeName);
|
|
4817
5277
|
return [
|
|
@@ -5096,6 +5556,7 @@ async function createSyncEngine(pg, options) {
|
|
|
5096
5556
|
}
|
|
5097
5557
|
},
|
|
5098
5558
|
key: options2.shapeKey,
|
|
5559
|
+
...options2.sessionScoped ? { sessionScoped: options2.sessionScoped } : {},
|
|
5099
5560
|
onInitialSync: options2.onInitialSync,
|
|
5100
5561
|
onError: options2.onError,
|
|
5101
5562
|
onSyncError: options2.onSyncError,
|
|
@@ -5117,6 +5578,7 @@ async function createSyncEngine(pg, options) {
|
|
|
5117
5578
|
};
|
|
5118
5579
|
};
|
|
5119
5580
|
const deleteSubscription = async (key) => {
|
|
5581
|
+
await initMetadataTables();
|
|
5120
5582
|
await deleteSubscriptionState({
|
|
5121
5583
|
pg,
|
|
5122
5584
|
metadataSchema,
|
|
@@ -5628,8 +6090,13 @@ async function attachSyncClient(options) {
|
|
|
5628
6090
|
const detachError = () => new Error("[pgxsinkit] client detached \u2014 the tab released its worker attachment");
|
|
5629
6091
|
const status = { phase: "booting", isRunning: false };
|
|
5630
6092
|
let resolveReady;
|
|
5631
|
-
|
|
6093
|
+
let rejectReady;
|
|
6094
|
+
const ready = new Promise((resolve, reject) => {
|
|
5632
6095
|
resolveReady = resolve;
|
|
6096
|
+
rejectReady = reject;
|
|
6097
|
+
});
|
|
6098
|
+
ready.catch(() => {
|
|
6099
|
+
return;
|
|
5633
6100
|
});
|
|
5634
6101
|
let readyResolved = false;
|
|
5635
6102
|
const readyGroups = new Set;
|
|
@@ -5674,6 +6141,20 @@ async function attachSyncClient(options) {
|
|
|
5674
6141
|
markGroupReady(event.groupKey);
|
|
5675
6142
|
break;
|
|
5676
6143
|
}
|
|
6144
|
+
case "milestone": {
|
|
6145
|
+
if (event.stage === "writeReady")
|
|
6146
|
+
settleWriteReady();
|
|
6147
|
+
else if (event.stage === "bootSettled")
|
|
6148
|
+
settleBootSettled();
|
|
6149
|
+
break;
|
|
6150
|
+
}
|
|
6151
|
+
case "milestone-error": {
|
|
6152
|
+
if (event.stage === "writeReady")
|
|
6153
|
+
failWriteReady(rebuildError(event.error));
|
|
6154
|
+
else if (event.stage === "bootSettled")
|
|
6155
|
+
failBootSettled(rebuildError(event.error));
|
|
6156
|
+
break;
|
|
6157
|
+
}
|
|
5677
6158
|
case "conflict":
|
|
5678
6159
|
options.onConflict?.(event.details);
|
|
5679
6160
|
break;
|
|
@@ -5721,6 +6202,15 @@ async function attachSyncClient(options) {
|
|
|
5721
6202
|
} else {
|
|
5722
6203
|
if (ack.engineReady)
|
|
5723
6204
|
markReady();
|
|
6205
|
+
resolveLocalReadReady();
|
|
6206
|
+
if (ack.writeReady)
|
|
6207
|
+
settleWriteReady();
|
|
6208
|
+
if (ack.writeReadyError)
|
|
6209
|
+
failWriteReady(rebuildError(ack.writeReadyError));
|
|
6210
|
+
if (ack.bootSettled)
|
|
6211
|
+
settleBootSettled();
|
|
6212
|
+
if (ack.bootSettledError)
|
|
6213
|
+
failBootSettled(rebuildError(ack.bootSettledError));
|
|
5724
6214
|
attachAckResolve?.(ack);
|
|
5725
6215
|
}
|
|
5726
6216
|
break;
|
|
@@ -5796,6 +6286,57 @@ async function attachSyncClient(options) {
|
|
|
5796
6286
|
attachAckResolve = resolve;
|
|
5797
6287
|
attachAckReject = reject;
|
|
5798
6288
|
});
|
|
6289
|
+
let resolveLocalReadReady;
|
|
6290
|
+
const localReadReady = new Promise((resolve) => {
|
|
6291
|
+
resolveLocalReadReady = resolve;
|
|
6292
|
+
});
|
|
6293
|
+
let resolveWriteReady;
|
|
6294
|
+
let rejectWriteReady;
|
|
6295
|
+
const writeReady = new Promise((resolve, reject) => {
|
|
6296
|
+
resolveWriteReady = resolve;
|
|
6297
|
+
rejectWriteReady = reject;
|
|
6298
|
+
});
|
|
6299
|
+
let resolveBootSettled;
|
|
6300
|
+
let rejectBootSettled;
|
|
6301
|
+
const bootSettled = new Promise((resolve, reject) => {
|
|
6302
|
+
resolveBootSettled = resolve;
|
|
6303
|
+
rejectBootSettled = reject;
|
|
6304
|
+
});
|
|
6305
|
+
localReadReady.catch(() => {
|
|
6306
|
+
return;
|
|
6307
|
+
});
|
|
6308
|
+
writeReady.catch(() => {
|
|
6309
|
+
return;
|
|
6310
|
+
});
|
|
6311
|
+
bootSettled.catch(() => {
|
|
6312
|
+
return;
|
|
6313
|
+
});
|
|
6314
|
+
let writeReadySettled = false;
|
|
6315
|
+
let bootSettledSettled = false;
|
|
6316
|
+
const settleWriteReady = () => {
|
|
6317
|
+
if (writeReadySettled)
|
|
6318
|
+
return;
|
|
6319
|
+
writeReadySettled = true;
|
|
6320
|
+
resolveWriteReady();
|
|
6321
|
+
};
|
|
6322
|
+
const failWriteReady = (error) => {
|
|
6323
|
+
if (writeReadySettled)
|
|
6324
|
+
return;
|
|
6325
|
+
writeReadySettled = true;
|
|
6326
|
+
rejectWriteReady(error);
|
|
6327
|
+
};
|
|
6328
|
+
const settleBootSettled = () => {
|
|
6329
|
+
if (bootSettledSettled)
|
|
6330
|
+
return;
|
|
6331
|
+
bootSettledSettled = true;
|
|
6332
|
+
resolveBootSettled();
|
|
6333
|
+
};
|
|
6334
|
+
const failBootSettled = (error) => {
|
|
6335
|
+
if (bootSettledSettled)
|
|
6336
|
+
return;
|
|
6337
|
+
bootSettledSettled = true;
|
|
6338
|
+
rejectBootSettled(error);
|
|
6339
|
+
};
|
|
5799
6340
|
const detachFromWorker = () => {
|
|
5800
6341
|
if (detached)
|
|
5801
6342
|
return;
|
|
@@ -5806,6 +6347,13 @@ async function attachSyncClient(options) {
|
|
|
5806
6347
|
diffHandlers.clear();
|
|
5807
6348
|
postBridgeMessage(port, codec, "detach", null);
|
|
5808
6349
|
attachAckReject?.(detachError());
|
|
6350
|
+
const disposedError = new ClientDisposedError;
|
|
6351
|
+
failWriteReady(disposedError);
|
|
6352
|
+
failBootSettled(disposedError);
|
|
6353
|
+
if (!readyResolved) {
|
|
6354
|
+
readyResolved = true;
|
|
6355
|
+
rejectReady(disposedError);
|
|
6356
|
+
}
|
|
5809
6357
|
for (const pending of rpcPending.values())
|
|
5810
6358
|
pending.reject(detachError());
|
|
5811
6359
|
rpcPending.clear();
|
|
@@ -5906,7 +6454,7 @@ async function attachSyncClient(options) {
|
|
|
5906
6454
|
...hydrated ? { hydrated } : {}
|
|
5907
6455
|
};
|
|
5908
6456
|
};
|
|
5909
|
-
const { drizzle:
|
|
6457
|
+
const { drizzle: drizzle5, views } = buildRegistryReadHandles(options.registry);
|
|
5910
6458
|
const notSupported = (name) => () => {
|
|
5911
6459
|
throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`);
|
|
5912
6460
|
};
|
|
@@ -5915,7 +6463,7 @@ async function attachSyncClient(options) {
|
|
|
5915
6463
|
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
5916
6464
|
};
|
|
5917
6465
|
const client = {
|
|
5918
|
-
drizzle:
|
|
6466
|
+
drizzle: drizzle5,
|
|
5919
6467
|
views,
|
|
5920
6468
|
pglite: new Proxy({}, {
|
|
5921
6469
|
get: notSupported("client.pglite")
|
|
@@ -5930,6 +6478,9 @@ async function attachSyncClient(options) {
|
|
|
5930
6478
|
delete: (entityKey) => rpc("delete", [tableKey, entityKey])
|
|
5931
6479
|
}
|
|
5932
6480
|
])),
|
|
6481
|
+
localReadReady,
|
|
6482
|
+
writeReady,
|
|
6483
|
+
bootSettled,
|
|
5933
6484
|
ready,
|
|
5934
6485
|
status,
|
|
5935
6486
|
start: async () => {
|
|
@@ -5945,8 +6496,8 @@ async function attachSyncClient(options) {
|
|
|
5945
6496
|
retryFailed: (table) => rpc("retryFailed", [table]),
|
|
5946
6497
|
recoverSending: (table) => rpc("recoverSending", [table]),
|
|
5947
6498
|
readMutationDetails: (table) => rpc("readMutationDetails", [table]),
|
|
5948
|
-
rawQuery: (
|
|
5949
|
-
rawExec: (
|
|
6499
|
+
rawQuery: (sql7, params, options2) => rpc("rawQuery", [sql7, params, options2]),
|
|
6500
|
+
rawExec: (sql7, options2) => rpc("rawExec", [sql7, options2]),
|
|
5950
6501
|
mutate: {
|
|
5951
6502
|
create: (table, input) => rpc("create", [table, input]),
|
|
5952
6503
|
update: (table, entityKey, patch) => rpc("update", [table, entityKey, patch]),
|
|
@@ -5956,6 +6507,11 @@ async function attachSyncClient(options) {
|
|
|
5956
6507
|
discardConflict: (table, entityKey) => rpc("discardConflict", [table, entityKey]),
|
|
5957
6508
|
discardQuarantined: (table, entityKey) => rpc("discardQuarantined", [table, entityKey]),
|
|
5958
6509
|
diagnostics: (table) => rpc("diagnostics", [table]),
|
|
6510
|
+
mutations: createMutationsApi({
|
|
6511
|
+
registry: options.registry,
|
|
6512
|
+
subscribeLiveRows,
|
|
6513
|
+
query: (sql7, params) => rpc("rawQuery", [sql7, params])
|
|
6514
|
+
}),
|
|
5959
6515
|
query: notSupported("client.query"),
|
|
5960
6516
|
queryRow: notSupported("client.queryRow"),
|
|
5961
6517
|
queryRaw: notSupported("client.queryRaw"),
|
|
@@ -6243,6 +6799,28 @@ function defineSyncWorker(options) {
|
|
|
6243
6799
|
const bootedPromise = new Promise((resolve) => {
|
|
6244
6800
|
resolveBooted = resolve;
|
|
6245
6801
|
});
|
|
6802
|
+
const milestones = { writeReady: false, bootSettled: false };
|
|
6803
|
+
const stageErrors = {};
|
|
6804
|
+
let milestonesWired = false;
|
|
6805
|
+
const markMilestone = (stage) => {
|
|
6806
|
+
if (milestones[stage])
|
|
6807
|
+
return;
|
|
6808
|
+
milestones[stage] = true;
|
|
6809
|
+
broadcastEvent({ kind: "milestone", stage });
|
|
6810
|
+
};
|
|
6811
|
+
const failMilestone = (stage, error) => {
|
|
6812
|
+
if (stageErrors[stage])
|
|
6813
|
+
return;
|
|
6814
|
+
const serialized = serializeError(error);
|
|
6815
|
+
stageErrors[stage] = serialized;
|
|
6816
|
+
broadcastEvent({ kind: "milestone-error", stage, error: serialized });
|
|
6817
|
+
};
|
|
6818
|
+
const milestoneAckFields = () => ({
|
|
6819
|
+
...milestones.writeReady ? { writeReady: true } : {},
|
|
6820
|
+
...milestones.bootSettled ? { bootSettled: true } : {},
|
|
6821
|
+
...stageErrors.writeReady ? { writeReadyError: stageErrors.writeReady } : {},
|
|
6822
|
+
...stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}
|
|
6823
|
+
});
|
|
6246
6824
|
const boot = (attach) => {
|
|
6247
6825
|
if (bootPromise)
|
|
6248
6826
|
return bootPromise;
|
|
@@ -6389,10 +6967,10 @@ function defineSyncWorker(options) {
|
|
|
6389
6967
|
const active = client ?? await bootPromise;
|
|
6390
6968
|
if (!active)
|
|
6391
6969
|
throw new Error("subscribe before attach");
|
|
6392
|
-
const { queryId, sql:
|
|
6393
|
-
const prepared = await active.prepareQuery({ sql:
|
|
6394
|
-
const hydratingTables = active.hydratingTablesFor({ sql:
|
|
6395
|
-
const materialSql = wrapLiveQueryForMaterialization(
|
|
6970
|
+
const { queryId, sql: sql7, params, pkColumns, use, fields, keepAliveMs } = payload;
|
|
6971
|
+
const prepared = await active.prepareQuery({ sql: sql7, ...use ? { use } : {} });
|
|
6972
|
+
const hydratingTables = active.hydratingTablesFor({ sql: sql7, ...use ? { use } : {} });
|
|
6973
|
+
const materialSql = wrapLiveQueryForMaterialization(sql7, fields);
|
|
6396
6974
|
if (closing || pending.cancelled || !ports.has(port)) {
|
|
6397
6975
|
postBridgeMessage(port, codec, "rpc-result", {
|
|
6398
6976
|
ok: false,
|
|
@@ -6506,14 +7084,22 @@ function defineSyncWorker(options) {
|
|
|
6506
7084
|
boot(attach).then((booted) => {
|
|
6507
7085
|
client = booted;
|
|
6508
7086
|
resolveBooted(booted);
|
|
7087
|
+
if (!milestonesWired) {
|
|
7088
|
+
milestonesWired = true;
|
|
7089
|
+
booted.writeReady.then(() => markMilestone("writeReady"), (error) => failMilestone("writeReady", error));
|
|
7090
|
+
booted.bootSettled.then(() => markMilestone("bootSettled"), (error) => failMilestone("bootSettled", error));
|
|
7091
|
+
}
|
|
6509
7092
|
if (!engineReadyFired) {
|
|
6510
7093
|
booted.ready.then(() => {
|
|
6511
7094
|
engineReadyFired = true;
|
|
7095
|
+
}, () => {
|
|
7096
|
+
return;
|
|
6512
7097
|
});
|
|
6513
7098
|
}
|
|
6514
7099
|
postBridgeMessage(port, codec, "attach-ack", {
|
|
6515
7100
|
alreadyBooted,
|
|
6516
|
-
...engineReadyFired ? { engineReady: true } : {}
|
|
7101
|
+
...engineReadyFired ? { engineReady: true } : {},
|
|
7102
|
+
...milestoneAckFields()
|
|
6517
7103
|
});
|
|
6518
7104
|
postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
|
|
6519
7105
|
}, (error) => {
|
|
@@ -6654,6 +7240,19 @@ function bindGlobalScope(connect) {
|
|
|
6654
7240
|
}
|
|
6655
7241
|
}
|
|
6656
7242
|
// packages/client/src/index.ts
|
|
7243
|
+
class WriteNotReadyError extends Error {
|
|
7244
|
+
constructor() {
|
|
7245
|
+
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.");
|
|
7246
|
+
this.name = "WriteNotReadyError";
|
|
7247
|
+
}
|
|
7248
|
+
}
|
|
7249
|
+
|
|
7250
|
+
class ClientDisposedError extends Error {
|
|
7251
|
+
constructor() {
|
|
7252
|
+
super("pgxsinkit: the client was stopped/destroyed before this readiness stage resolved.");
|
|
7253
|
+
this.name = "ClientDisposedError";
|
|
7254
|
+
}
|
|
7255
|
+
}
|
|
6657
7256
|
async function createClientPGlite(store, options) {
|
|
6658
7257
|
const normalised = normaliseStorePathInput(store);
|
|
6659
7258
|
const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);
|
|
@@ -6671,8 +7270,8 @@ async function createClientPGlite(store, options) {
|
|
|
6671
7270
|
}
|
|
6672
7271
|
function replAdapter(client) {
|
|
6673
7272
|
return {
|
|
6674
|
-
query: (
|
|
6675
|
-
exec: (
|
|
7273
|
+
query: (sql7, params, options) => client.rawQuery(sql7, params, options),
|
|
7274
|
+
exec: (sql7, options) => client.rawExec(sql7, options)
|
|
6676
7275
|
};
|
|
6677
7276
|
}
|
|
6678
7277
|
async function createSyncClient(options) {
|
|
@@ -6682,8 +7281,26 @@ async function createSyncClient(options) {
|
|
|
6682
7281
|
isRunning: false
|
|
6683
7282
|
};
|
|
6684
7283
|
let resolveReady;
|
|
6685
|
-
|
|
7284
|
+
let rejectReady;
|
|
7285
|
+
const ready = new Promise((resolve, reject) => {
|
|
6686
7286
|
resolveReady = resolve;
|
|
7287
|
+
rejectReady = reject;
|
|
7288
|
+
});
|
|
7289
|
+
let resolveLocalReadReady;
|
|
7290
|
+
const localReadReady = new Promise((resolve) => {
|
|
7291
|
+
resolveLocalReadReady = resolve;
|
|
7292
|
+
});
|
|
7293
|
+
let resolveWriteReady;
|
|
7294
|
+
let rejectWriteReady;
|
|
7295
|
+
const writeReady = new Promise((resolve, reject) => {
|
|
7296
|
+
resolveWriteReady = resolve;
|
|
7297
|
+
rejectWriteReady = reject;
|
|
7298
|
+
});
|
|
7299
|
+
let resolveBootSettled;
|
|
7300
|
+
let rejectBootSettled;
|
|
7301
|
+
const bootSettled = new Promise((resolve, reject) => {
|
|
7302
|
+
resolveBootSettled = resolve;
|
|
7303
|
+
rejectBootSettled = reject;
|
|
6687
7304
|
});
|
|
6688
7305
|
if (options.pgliteInstance && options.precreatedPglite) {
|
|
6689
7306
|
throw new Error("createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` \u2014 they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).");
|
|
@@ -6700,9 +7317,11 @@ async function createSyncClient(options) {
|
|
|
6700
7317
|
}
|
|
6701
7318
|
const syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
|
|
6702
7319
|
const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
|
|
7320
|
+
const storeKind = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
|
|
6703
7321
|
const bootReportBuilder = createBootReportBuilder({
|
|
6704
7322
|
mode: options.bootMode ?? "in-process",
|
|
6705
7323
|
freshStore: options.freshStore === true,
|
|
7324
|
+
storeKind,
|
|
6706
7325
|
overlapPrefetch,
|
|
6707
7326
|
registryFingerprint: fingerprintRegistry2(options.registry)
|
|
6708
7327
|
});
|
|
@@ -6852,8 +7471,22 @@ async function createSyncClient(options) {
|
|
|
6852
7471
|
const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
|
|
6853
7472
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
6854
7473
|
}
|
|
6855
|
-
|
|
6856
|
-
|
|
7474
|
+
await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
|
|
7475
|
+
await pglite.exec(buildLocalMetaBootstrapSql(options.registry));
|
|
7476
|
+
const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
|
|
7477
|
+
const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
|
|
7478
|
+
if (storedFingerprint === currentFingerprint) {
|
|
7479
|
+
bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
|
|
7480
|
+
} else {
|
|
7481
|
+
await pglite.exec(generateDurableLocalSchemaSql(options.registry));
|
|
7482
|
+
await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
|
|
7483
|
+
bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
|
|
7484
|
+
}
|
|
7485
|
+
const ephemeralSql = generateEphemeralLocalSchemaSql(options.registry);
|
|
7486
|
+
if (ephemeralSql.length > 0) {
|
|
7487
|
+
await pglite.exec(ephemeralSql);
|
|
7488
|
+
}
|
|
7489
|
+
});
|
|
6857
7490
|
if (options.prepareLocalDb) {
|
|
6858
7491
|
const prepareLocalDb = options.prepareLocalDb;
|
|
6859
7492
|
await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDb(pglite));
|
|
@@ -6865,6 +7498,7 @@ async function createSyncClient(options) {
|
|
|
6865
7498
|
db: pglite,
|
|
6866
7499
|
registry: options.registry,
|
|
6867
7500
|
writeUrl: options.writeUrl,
|
|
7501
|
+
ownsMetaTable: !options.pgliteInstance,
|
|
6868
7502
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
6869
7503
|
...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
|
|
6870
7504
|
...writePathHeaders ? { requestHeaders: writePathHeaders } : {},
|
|
@@ -6873,45 +7507,103 @@ async function createSyncClient(options) {
|
|
|
6873
7507
|
...options.onConflict ? { onConflict: options.onConflict } : {},
|
|
6874
7508
|
...options.onReject ? { onReject: options.onReject } : {}
|
|
6875
7509
|
});
|
|
6876
|
-
|
|
6877
|
-
if (restoreBoot) {
|
|
6878
|
-
await mutationRuntime.quarantineRecovered();
|
|
6879
|
-
}
|
|
7510
|
+
let pendingActivations = new Set;
|
|
6880
7511
|
let versionEvent = null;
|
|
6881
|
-
|
|
7512
|
+
const runBootRecoveryStage = async () => {
|
|
7513
|
+
const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgliteInstance, restore: restoreBoot }));
|
|
7514
|
+
bootReportBuilder.setJournalRecovery(recoveryOutcome);
|
|
7515
|
+
};
|
|
7516
|
+
const runReconcileStage = async () => {
|
|
7517
|
+
if (options.pgliteInstance)
|
|
7518
|
+
return;
|
|
6882
7519
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () => reconcileLocalStoreVersion({
|
|
6883
7520
|
db: pglite,
|
|
6884
7521
|
registry: options.registry,
|
|
6885
7522
|
runtime: mutationRuntime,
|
|
6886
7523
|
...options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}
|
|
6887
7524
|
}));
|
|
7525
|
+
};
|
|
7526
|
+
if (restoreBoot) {
|
|
7527
|
+
await runBootRecoveryStage();
|
|
7528
|
+
await runReconcileStage();
|
|
7529
|
+
} else {
|
|
7530
|
+
await runReconcileStage();
|
|
6888
7531
|
}
|
|
6889
7532
|
const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
|
|
6890
7533
|
const lazyGuardIndex = buildLazyGuardIndex(options.registry);
|
|
6891
7534
|
let sync = null;
|
|
6892
7535
|
let convergenceDriver = null;
|
|
6893
|
-
|
|
6894
|
-
|
|
6895
|
-
|
|
6896
|
-
|
|
6897
|
-
|
|
6898
|
-
|
|
6899
|
-
|
|
7536
|
+
let disposed = false;
|
|
7537
|
+
let resolveSyncWired;
|
|
7538
|
+
let rejectSyncWired;
|
|
7539
|
+
const syncWired = new Promise((resolve, reject) => {
|
|
7540
|
+
resolveSyncWired = resolve;
|
|
7541
|
+
rejectSyncWired = reject;
|
|
7542
|
+
});
|
|
7543
|
+
syncWired.catch(() => {
|
|
7544
|
+
return;
|
|
7545
|
+
});
|
|
7546
|
+
const isSyncPending = () => syncEnabled && sync == null && !disposed;
|
|
7547
|
+
const quiesceTailForTeardown = async () => {
|
|
7548
|
+
disposed = true;
|
|
7549
|
+
const disposedError = new ClientDisposedError;
|
|
7550
|
+
rejectWriteReady(disposedError);
|
|
7551
|
+
rejectReady(disposedError);
|
|
7552
|
+
resolveSyncWired();
|
|
7553
|
+
await bootSettled.catch(() => {
|
|
7554
|
+
return;
|
|
7555
|
+
});
|
|
7556
|
+
};
|
|
7557
|
+
const runWriteAndSyncTail = async () => {
|
|
7558
|
+
if (disposed)
|
|
7559
|
+
return;
|
|
7560
|
+
if (!restoreBoot) {
|
|
7561
|
+
await runBootRecoveryStage();
|
|
7562
|
+
}
|
|
7563
|
+
if (disposed)
|
|
7564
|
+
return;
|
|
7565
|
+
bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
|
|
7566
|
+
resolveWriteReady();
|
|
7567
|
+
if (disposed)
|
|
7568
|
+
return;
|
|
7569
|
+
status.isRunning = true;
|
|
7570
|
+
openDbGate();
|
|
7571
|
+
if (syncEnabled) {
|
|
7572
|
+
if (earlySync) {
|
|
7573
|
+
sync = await earlySync;
|
|
7574
|
+
bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
|
|
7575
|
+
bootReportBuilder.markSyncStartDone();
|
|
7576
|
+
} else {
|
|
7577
|
+
const resetKeys = versionEvent?.status === "rebuilt" ? [...options.resetSubscriptionKeys ?? [], ...allGroupSubscriptionKeys(options.registry)] : options.resetSubscriptionKeys;
|
|
7578
|
+
await resetSubscriptionsIfRequested(pglite, resetKeys);
|
|
7579
|
+
if (disposed)
|
|
7580
|
+
return;
|
|
7581
|
+
status.phase = "syncing";
|
|
7582
|
+
options.onStatusChange?.(status);
|
|
7583
|
+
const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
|
|
7584
|
+
if (disposed)
|
|
7585
|
+
return;
|
|
7586
|
+
sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startConfiguredSync(pglite, buildStartOptions(promotedGroups)));
|
|
7587
|
+
bootReportBuilder.markSyncStartDone();
|
|
7588
|
+
}
|
|
7589
|
+
if (disposed) {
|
|
7590
|
+
sync?.unsubscribe();
|
|
7591
|
+
sync = null;
|
|
7592
|
+
return;
|
|
7593
|
+
}
|
|
6900
7594
|
} else {
|
|
6901
|
-
|
|
6902
|
-
await resetSubscriptionsIfRequested(pglite, resetKeys);
|
|
6903
|
-
status.phase = "syncing";
|
|
7595
|
+
status.phase = "ready";
|
|
6904
7596
|
options.onStatusChange?.(status);
|
|
6905
|
-
|
|
6906
|
-
|
|
6907
|
-
bootReportBuilder.markSyncStartDone();
|
|
7597
|
+
finalizeBootReport();
|
|
7598
|
+
resolveReady();
|
|
6908
7599
|
}
|
|
6909
|
-
|
|
6910
|
-
|
|
6911
|
-
|
|
6912
|
-
|
|
6913
|
-
|
|
6914
|
-
|
|
7600
|
+
const buffered = pendingActivations;
|
|
7601
|
+
pendingActivations = null;
|
|
7602
|
+
if (sync != null && buffered && buffered.size > 0) {
|
|
7603
|
+
await ensureSynced([...buffered]);
|
|
7604
|
+
}
|
|
7605
|
+
resolveSyncWired();
|
|
7606
|
+
};
|
|
6915
7607
|
if (options.autoSync && !restoreBoot) {
|
|
6916
7608
|
convergenceDriver = createConvergenceDriver({
|
|
6917
7609
|
client: {
|
|
@@ -6921,23 +7613,29 @@ async function createSyncClient(options) {
|
|
|
6921
7613
|
trigger: options.autoSync,
|
|
6922
7614
|
...options.onConvergencePass ? { onPass: options.onConvergencePass } : {}
|
|
6923
7615
|
});
|
|
6924
|
-
ready.then(() => convergenceDriver?.start())
|
|
7616
|
+
ready.then(() => convergenceDriver?.start(), () => {
|
|
7617
|
+
return;
|
|
7618
|
+
});
|
|
6925
7619
|
}
|
|
6926
7620
|
const requestConvergence = () => convergenceDriver?.requestPass();
|
|
6927
7621
|
const mutate = {
|
|
6928
7622
|
create: async (table, input) => {
|
|
7623
|
+
await writeReady;
|
|
6929
7624
|
await mutationRuntime.create(table, input);
|
|
6930
7625
|
requestConvergence();
|
|
6931
7626
|
},
|
|
6932
7627
|
update: async (table, entityKey, patch) => {
|
|
7628
|
+
await writeReady;
|
|
6933
7629
|
await mutationRuntime.update(table, entityKey, patch);
|
|
6934
7630
|
requestConvergence();
|
|
6935
7631
|
},
|
|
6936
7632
|
delete: async (table, entityKey) => {
|
|
7633
|
+
await writeReady;
|
|
6937
7634
|
await mutationRuntime.delete(table, entityKey);
|
|
6938
7635
|
requestConvergence();
|
|
6939
7636
|
},
|
|
6940
7637
|
batch: async (items) => {
|
|
7638
|
+
await writeReady;
|
|
6941
7639
|
await mutationRuntime.batch(items);
|
|
6942
7640
|
requestConvergence();
|
|
6943
7641
|
}
|
|
@@ -6987,8 +7685,16 @@ async function createSyncClient(options) {
|
|
|
6987
7685
|
})();
|
|
6988
7686
|
};
|
|
6989
7687
|
const ensureSynced = async (keys) => {
|
|
7688
|
+
if (keys.length === 0)
|
|
7689
|
+
return;
|
|
7690
|
+
if (sync == null && isSyncPending()) {
|
|
7691
|
+
if (pendingActivations != null)
|
|
7692
|
+
for (const key of keys)
|
|
7693
|
+
pendingActivations.add(key);
|
|
7694
|
+
await syncWired;
|
|
7695
|
+
}
|
|
6990
7696
|
const activeSync = sync;
|
|
6991
|
-
if (activeSync == null
|
|
7697
|
+
if (activeSync == null)
|
|
6992
7698
|
return;
|
|
6993
7699
|
const groupKeys = new Set;
|
|
6994
7700
|
for (const key of keys) {
|
|
@@ -7003,6 +7709,12 @@ async function createSyncClient(options) {
|
|
|
7003
7709
|
await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
|
|
7004
7710
|
};
|
|
7005
7711
|
activateOrdinaryWriteTables = (tables) => {
|
|
7712
|
+
if (sync == null) {
|
|
7713
|
+
if (pendingActivations != null)
|
|
7714
|
+
for (const table of tables)
|
|
7715
|
+
pendingActivations.add(table);
|
|
7716
|
+
return;
|
|
7717
|
+
}
|
|
7006
7718
|
const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table));
|
|
7007
7719
|
if (lazyTables.length === 0)
|
|
7008
7720
|
return;
|
|
@@ -7011,6 +7723,9 @@ async function createSyncClient(options) {
|
|
|
7011
7723
|
});
|
|
7012
7724
|
};
|
|
7013
7725
|
const groupReadyForTable = async (table) => {
|
|
7726
|
+
if (sync == null && isSyncPending()) {
|
|
7727
|
+
await syncWired;
|
|
7728
|
+
}
|
|
7014
7729
|
const activeSync = sync;
|
|
7015
7730
|
if (activeSync == null)
|
|
7016
7731
|
return;
|
|
@@ -7021,15 +7736,16 @@ async function createSyncClient(options) {
|
|
|
7021
7736
|
};
|
|
7022
7737
|
const isGroupReadyForTable = (table) => {
|
|
7023
7738
|
const activeSync = sync;
|
|
7024
|
-
if (activeSync == null)
|
|
7025
|
-
return
|
|
7739
|
+
if (activeSync == null) {
|
|
7740
|
+
return !isSyncPending();
|
|
7741
|
+
}
|
|
7026
7742
|
const groupKey = activeSync.groupKeyForTable(table);
|
|
7027
7743
|
if (groupKey == null)
|
|
7028
7744
|
return true;
|
|
7029
7745
|
return activeSync.isGroupReady(groupKey);
|
|
7030
7746
|
};
|
|
7031
7747
|
const hydratingTablesFor = (query) => {
|
|
7032
|
-
if (sync == null)
|
|
7748
|
+
if (sync == null && !isSyncPending())
|
|
7033
7749
|
return [];
|
|
7034
7750
|
const referenced = new Set(query.use ?? []);
|
|
7035
7751
|
for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex))
|
|
@@ -7038,8 +7754,9 @@ async function createSyncClient(options) {
|
|
|
7038
7754
|
};
|
|
7039
7755
|
const isSynced = (key) => {
|
|
7040
7756
|
const activeSync = sync;
|
|
7041
|
-
if (activeSync == null)
|
|
7042
|
-
return
|
|
7757
|
+
if (activeSync == null) {
|
|
7758
|
+
return !isSyncPending();
|
|
7759
|
+
}
|
|
7043
7760
|
return activeSync.isTableStarted(key);
|
|
7044
7761
|
};
|
|
7045
7762
|
const groupTableKeysFor = (key, entry) => {
|
|
@@ -7071,6 +7788,7 @@ async function createSyncClient(options) {
|
|
|
7071
7788
|
}
|
|
7072
7789
|
};
|
|
7073
7790
|
const desync = async (key) => {
|
|
7791
|
+
await bootSettled;
|
|
7074
7792
|
const entry = options.registry[key];
|
|
7075
7793
|
if (entry == null)
|
|
7076
7794
|
throw new Error(`desync: unknown table ${String(key)}`);
|
|
@@ -7079,21 +7797,25 @@ async function createSyncClient(options) {
|
|
|
7079
7797
|
}
|
|
7080
7798
|
await tearDownLazyGroup(key, entry, "desync");
|
|
7081
7799
|
};
|
|
7082
|
-
const discardEphemeral =
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
|
|
7086
|
-
|
|
7087
|
-
|
|
7088
|
-
|
|
7089
|
-
|
|
7090
|
-
|
|
7091
|
-
|
|
7800
|
+
const discardEphemeral = async (key) => {
|
|
7801
|
+
await bootSettled;
|
|
7802
|
+
return lifecycleSlot.run("discardEphemeral", async () => {
|
|
7803
|
+
const entry = options.registry[key];
|
|
7804
|
+
if (entry == null)
|
|
7805
|
+
throw new Error(`discardEphemeral: unknown table ${String(key)}`);
|
|
7806
|
+
if (entry.subscription !== "lazy") {
|
|
7807
|
+
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.`);
|
|
7808
|
+
}
|
|
7809
|
+
for (const member of groupTableKeysFor(key, entry)) {
|
|
7810
|
+
if ((options.registry[member].retention ?? "persistent") !== "ephemeral") {
|
|
7811
|
+
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.`);
|
|
7812
|
+
}
|
|
7092
7813
|
}
|
|
7093
|
-
|
|
7094
|
-
|
|
7095
|
-
}
|
|
7814
|
+
await tearDownLazyGroup(key, entry, "discardEphemeral");
|
|
7815
|
+
});
|
|
7816
|
+
};
|
|
7096
7817
|
const transaction = async ({ mode }, run) => {
|
|
7818
|
+
await writeReady;
|
|
7097
7819
|
const collected = [];
|
|
7098
7820
|
const txTables = Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
|
|
7099
7821
|
tableKey,
|
|
@@ -7130,20 +7852,21 @@ async function createSyncClient(options) {
|
|
|
7130
7852
|
}
|
|
7131
7853
|
return await mutationRuntime.flushUnit(unit.id);
|
|
7132
7854
|
};
|
|
7133
|
-
const prepareQuery = async ({ sql:
|
|
7855
|
+
const prepareQuery = async ({ sql: sql7, use }) => {
|
|
7134
7856
|
const toActivate = new Set(use ?? []);
|
|
7135
|
-
for (const key of findReferencedLazyKeysInSql(
|
|
7857
|
+
for (const key of findReferencedLazyKeysInSql(sql7, lazyGuardIndex))
|
|
7136
7858
|
toActivate.add(key);
|
|
7137
7859
|
const lazyTables = [...toActivate];
|
|
7138
7860
|
await ensureSynced(lazyTables);
|
|
7139
7861
|
assertLazyRefsActivated({
|
|
7140
|
-
sql:
|
|
7862
|
+
sql: sql7,
|
|
7141
7863
|
index: lazyGuardIndex,
|
|
7142
7864
|
isActive: (key) => isSynced(key)
|
|
7143
7865
|
});
|
|
7144
7866
|
return { lazyTables };
|
|
7145
7867
|
};
|
|
7146
7868
|
const runGuardedQuery = async (build, use) => {
|
|
7869
|
+
await localReadReady;
|
|
7147
7870
|
const builder = build(client);
|
|
7148
7871
|
await prepareQuery({ sql: builder.toSQL().sql, ...use ? { use } : {} });
|
|
7149
7872
|
return builder;
|
|
@@ -7166,12 +7889,16 @@ async function createSyncClient(options) {
|
|
|
7166
7889
|
delete: (entityKey) => mutate.delete(tableKey, entityKey)
|
|
7167
7890
|
}
|
|
7168
7891
|
])),
|
|
7892
|
+
localReadReady,
|
|
7893
|
+
writeReady,
|
|
7894
|
+
bootSettled,
|
|
7169
7895
|
ready,
|
|
7170
7896
|
status,
|
|
7171
7897
|
start: async () => {
|
|
7172
7898
|
await ready;
|
|
7173
7899
|
},
|
|
7174
7900
|
stop: async () => {
|
|
7901
|
+
await quiesceTailForTeardown();
|
|
7175
7902
|
await convergenceDriver?.stop();
|
|
7176
7903
|
sync?.unsubscribe();
|
|
7177
7904
|
status.isRunning = false;
|
|
@@ -7181,6 +7908,7 @@ async function createSyncClient(options) {
|
|
|
7181
7908
|
await pglite.close();
|
|
7182
7909
|
},
|
|
7183
7910
|
destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
|
|
7911
|
+
await quiesceTailForTeardown();
|
|
7184
7912
|
if (!destroyOptions?.force) {
|
|
7185
7913
|
const stats = await mutationRuntime.readMutationStats();
|
|
7186
7914
|
const owed = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
|
|
@@ -7197,24 +7925,47 @@ async function createSyncClient(options) {
|
|
|
7197
7925
|
await liveManager.dispose();
|
|
7198
7926
|
await pglite.close();
|
|
7199
7927
|
}),
|
|
7200
|
-
dropReadCache:
|
|
7201
|
-
await
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
|
|
7207
|
-
|
|
7208
|
-
|
|
7928
|
+
dropReadCache: async () => {
|
|
7929
|
+
await bootSettled;
|
|
7930
|
+
return lifecycleSlot.run("dropReadCache", async () => {
|
|
7931
|
+
await pglite.exec(buildDropReadCacheSql(options.registry));
|
|
7932
|
+
await pglite.exec(generateLocalSchemaSql(options.registry));
|
|
7933
|
+
await writeStoredLocalSchemaFingerprint(pglite, options.registry, computeLocalSchemaFingerprint(options.registry));
|
|
7934
|
+
await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
|
|
7935
|
+
});
|
|
7936
|
+
},
|
|
7937
|
+
flush: async (table) => {
|
|
7938
|
+
await writeReady;
|
|
7939
|
+
return mutationRuntime.flush(table);
|
|
7940
|
+
},
|
|
7941
|
+
reconcile: async (table) => {
|
|
7942
|
+
await writeReady;
|
|
7943
|
+
return mutationRuntime.reconcile(table);
|
|
7944
|
+
},
|
|
7945
|
+
retryFailed: async (table) => {
|
|
7946
|
+
await writeReady;
|
|
7947
|
+
return mutationRuntime.retryFailed(table);
|
|
7948
|
+
},
|
|
7949
|
+
recoverSending: async (table) => {
|
|
7950
|
+
await writeReady;
|
|
7951
|
+
return mutationRuntime.recoverSending(table);
|
|
7952
|
+
},
|
|
7209
7953
|
readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
|
|
7210
7954
|
mutate,
|
|
7211
|
-
discardConflict: (table, entityKey) =>
|
|
7212
|
-
|
|
7955
|
+
discardConflict: async (table, entityKey) => {
|
|
7956
|
+
await writeReady;
|
|
7957
|
+
return mutationRuntime.discardConflict(table, entityKey);
|
|
7958
|
+
},
|
|
7959
|
+
discardQuarantined: async (table, entityKey) => {
|
|
7960
|
+
await writeReady;
|
|
7961
|
+
return mutationRuntime.discardQuarantined(table, entityKey);
|
|
7962
|
+
},
|
|
7213
7963
|
diagnostics: async (table) => ({
|
|
7214
7964
|
mutation: await mutationRuntime.readMutationStats(table)
|
|
7215
7965
|
}),
|
|
7216
|
-
|
|
7217
|
-
|
|
7966
|
+
mutations: undefined,
|
|
7967
|
+
rawQuery: (sql7, params, options2) => pglite.query(sql7, params, options2),
|
|
7968
|
+
rawExec: (sql7, options2) => pglite.exec(sql7, options2),
|
|
7218
7969
|
query: (build) => runGuardedQuery(build),
|
|
7219
7970
|
queryRow: async (build) => {
|
|
7220
7971
|
const rows = await runGuardedQuery(build);
|
|
@@ -7233,8 +7984,9 @@ async function createSyncClient(options) {
|
|
|
7233
7984
|
transaction,
|
|
7234
7985
|
groupReady: groupReadyForTable,
|
|
7235
7986
|
hydratingTablesFor,
|
|
7236
|
-
subscribeLiveRows: async ({ sql:
|
|
7237
|
-
|
|
7987
|
+
subscribeLiveRows: async ({ sql: sql7, params, fields, use, keepAliveMs }, onRows) => {
|
|
7988
|
+
await localReadReady;
|
|
7989
|
+
const materialSql = wrapLiveQueryForMaterialization(sql7, fields);
|
|
7238
7990
|
const materializer = new LiveRowsMaterializer(undefined);
|
|
7239
7991
|
const subscription = await liveManager.subscribe({ materialSql, params }, {
|
|
7240
7992
|
deliverInitial: (rows) => {
|
|
@@ -7247,10 +7999,10 @@ async function createSyncClient(options) {
|
|
|
7247
7999
|
const initialRows = materializer.current();
|
|
7248
8000
|
let unsubscribed = false;
|
|
7249
8001
|
const lazySet = new Set(use ?? []);
|
|
7250
|
-
for (const key of findReferencedLazyKeysInSql(
|
|
8002
|
+
for (const key of findReferencedLazyKeysInSql(sql7, lazyGuardIndex))
|
|
7251
8003
|
lazySet.add(key);
|
|
7252
8004
|
const lazyTables = [...lazySet];
|
|
7253
|
-
const hydratingTables = hydratingTablesFor({ sql:
|
|
8005
|
+
const hydratingTables = hydratingTablesFor({ sql: sql7, ...use ? { use } : {} });
|
|
7254
8006
|
const hydrated = hydratingTables.length > 0 ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table))).then(async () => {
|
|
7255
8007
|
if (!unsubscribed)
|
|
7256
8008
|
await subscription.refresh();
|
|
@@ -7298,6 +8050,44 @@ async function createSyncClient(options) {
|
|
|
7298
8050
|
}, exportOptions));
|
|
7299
8051
|
}
|
|
7300
8052
|
};
|
|
8053
|
+
client.mutations = createMutationsApi({
|
|
8054
|
+
registry: options.registry,
|
|
8055
|
+
subscribeLiveRows: client.subscribeLiveRows,
|
|
8056
|
+
query: (sql7, params) => pglite.query(sql7, params)
|
|
8057
|
+
});
|
|
8058
|
+
bootReportBuilder.setLocalReadReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
|
|
8059
|
+
resolveLocalReadReady();
|
|
8060
|
+
if (restoreBoot) {
|
|
8061
|
+
bootReportBuilder.setWriteReadyMs(performance.now() - bootReportBuilder.bootStartPerf);
|
|
8062
|
+
resolveWriteReady();
|
|
8063
|
+
}
|
|
8064
|
+
writeReady.catch(() => {
|
|
8065
|
+
return;
|
|
8066
|
+
});
|
|
8067
|
+
bootSettled.catch(() => {
|
|
8068
|
+
return;
|
|
8069
|
+
});
|
|
8070
|
+
ready.catch(() => {
|
|
8071
|
+
return;
|
|
8072
|
+
});
|
|
8073
|
+
runWriteAndSyncTail().then(() => {
|
|
8074
|
+
resolveBootSettled();
|
|
8075
|
+
pendingActivations = null;
|
|
8076
|
+
resolveSyncWired();
|
|
8077
|
+
}, (error) => {
|
|
8078
|
+
syncDebug("boot write/sync tail failed after localReadReady", { error });
|
|
8079
|
+
if (pendingActivations != null && pendingActivations.size > 0) {
|
|
8080
|
+
syncDebug("boot tail failure dropped buffered activations", { tables: [...pendingActivations] });
|
|
8081
|
+
}
|
|
8082
|
+
pendingActivations = null;
|
|
8083
|
+
status.phase = "degraded";
|
|
8084
|
+
status.lastError = error instanceof Error ? error.message : String(error);
|
|
8085
|
+
options.onStatusChange?.(status);
|
|
8086
|
+
rejectWriteReady(error);
|
|
8087
|
+
rejectReady(error);
|
|
8088
|
+
rejectBootSettled(error);
|
|
8089
|
+
rejectSyncWired(error);
|
|
8090
|
+
});
|
|
7301
8091
|
return client;
|
|
7302
8092
|
}
|
|
7303
8093
|
function allGroupSubscriptionKeys(registry) {
|
|
@@ -7317,7 +8107,7 @@ async function resetSubscriptionsIfRequested(pglite, keys) {
|
|
|
7317
8107
|
}
|
|
7318
8108
|
function createDrizzleDatabase(client, schema) {
|
|
7319
8109
|
const relations = defineRelations(schema);
|
|
7320
|
-
const createDatabase =
|
|
8110
|
+
const createDatabase = drizzle5;
|
|
7321
8111
|
return createDatabase({ client, relations });
|
|
7322
8112
|
}
|
|
7323
8113
|
function buildSchema(registry) {
|
|
@@ -7386,6 +8176,7 @@ export {
|
|
|
7386
8176
|
getOverlayTable,
|
|
7387
8177
|
getLocalMetaTable,
|
|
7388
8178
|
getJournalTable,
|
|
8179
|
+
getAllMutationsView,
|
|
7389
8180
|
generateLocalSchemaSql,
|
|
7390
8181
|
findReferencedSyncedKeysInSql,
|
|
7391
8182
|
findReferencedLazyKeysInSql,
|
|
@@ -7394,6 +8185,7 @@ export {
|
|
|
7394
8185
|
defineSyncWorker,
|
|
7395
8186
|
createWorkerTokenCache,
|
|
7396
8187
|
createSyncClient,
|
|
8188
|
+
createMutationsApi,
|
|
7397
8189
|
createLifecycleSlot,
|
|
7398
8190
|
createIntervalConvergenceTrigger,
|
|
7399
8191
|
createConvergenceDriver,
|
|
@@ -7404,6 +8196,7 @@ export {
|
|
|
7404
8196
|
buildLazyGuardIndex,
|
|
7405
8197
|
attachSyncClient,
|
|
7406
8198
|
assertLazyRefsActivated,
|
|
8199
|
+
WriteNotReadyError,
|
|
7407
8200
|
RestoreTargetExistsError,
|
|
7408
8201
|
NonPersistentStoreError,
|
|
7409
8202
|
LiveRowsMaterializer,
|
|
@@ -7412,8 +8205,9 @@ export {
|
|
|
7412
8205
|
InvalidStorePathError,
|
|
7413
8206
|
DataExportDrainError,
|
|
7414
8207
|
DEFAULT_DRAIN_TIMEOUT_MS,
|
|
8208
|
+
ClientDisposedError,
|
|
7415
8209
|
BRIDGE_PROTOCOL_VERSION,
|
|
7416
8210
|
BRIDGE_CHANNEL
|
|
7417
8211
|
};
|
|
7418
8212
|
|
|
7419
|
-
//# debugId=
|
|
8213
|
+
//# debugId=A2F9A60B406BFCC764756E2164756E21
|