@pgxsinkit/client 0.1.51 → 0.1.53
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/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +66 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +213 -55
- package/dist/index.js.map +15 -13
- package/dist/local-tables.d.ts +6 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +4 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +41 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +17 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +6 -2
- package/skills/operating/SKILL.md +28 -5
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/index.ts +175 -41
- package/src/local-tables.ts +7 -0
- package/src/sync/apply.ts +164 -26
- package/src/sync/index.ts +31 -7
- package/src/worker/attach-sync-client.ts +119 -20
- package/src/worker/define-sync-worker.ts +112 -2
- package/src/worker/live-query-manager.ts +6 -0
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +28 -0
package/dist/index.js
CHANGED
|
@@ -351,6 +351,21 @@ function createIntervalConvergenceTrigger(intervalMs) {
|
|
|
351
351
|
};
|
|
352
352
|
}
|
|
353
353
|
|
|
354
|
+
// packages/client/src/error-chain.ts
|
|
355
|
+
function describeErrorChain(error, maxDepth = 5) {
|
|
356
|
+
const parts = [];
|
|
357
|
+
let current = error;
|
|
358
|
+
for (let depth = 0;depth < maxDepth && current != null; depth += 1) {
|
|
359
|
+
const message = current instanceof Error ? current.message : typeof current === "string" ? current : JSON.stringify(current);
|
|
360
|
+
const code = typeof current === "object" && "code" in current ? current.code : undefined;
|
|
361
|
+
const detail = typeof current === "object" && "detail" in current ? current.detail : undefined;
|
|
362
|
+
const asText = (value) => typeof value === "string" ? value : JSON.stringify(value);
|
|
363
|
+
parts.push([message, code != null ? `[${asText(code)}]` : undefined, detail != null ? `(${asText(detail)})` : undefined].filter(Boolean).join(" "));
|
|
364
|
+
current = current instanceof Error ? current.cause : undefined;
|
|
365
|
+
}
|
|
366
|
+
return parts.join(" \u2190 caused by: ");
|
|
367
|
+
}
|
|
368
|
+
|
|
354
369
|
// packages/client/src/export-dump.ts
|
|
355
370
|
import { PGlite } from "@electric-sql/pglite";
|
|
356
371
|
|
|
@@ -496,7 +511,7 @@ async function runThrowawayCloneDump(pglite, startPerf, options = {}) {
|
|
|
496
511
|
const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
|
|
497
512
|
const cloneBootStartedAtMs = nowMs2() - startPerf;
|
|
498
513
|
const cloneBootStartPerf = nowMs2();
|
|
499
|
-
const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });
|
|
514
|
+
const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped, relaxedDurability: true });
|
|
500
515
|
const cloneBootMs = nowMs2() - cloneBootStartPerf;
|
|
501
516
|
let sqlBytes;
|
|
502
517
|
let pgDumpStartedAtMs;
|
|
@@ -956,6 +971,20 @@ function targetColumn(target, name) {
|
|
|
956
971
|
}
|
|
957
972
|
return column;
|
|
958
973
|
}
|
|
974
|
+
function hasGeneratedIdentityColumn(target, colNames) {
|
|
975
|
+
return colNames.some((name) => {
|
|
976
|
+
const column = target.columnByName[name];
|
|
977
|
+
return column?.generatedIdentity !== undefined && column.generatedIdentity.type !== "byDefault";
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
function insertInto(db, target, colNames) {
|
|
981
|
+
const builder = db.insert(target.table);
|
|
982
|
+
return hasGeneratedIdentityColumn(target, colNames) ? builder.overridingSystemValue() : builder;
|
|
983
|
+
}
|
|
984
|
+
function castTypeFor(column, tableSchema) {
|
|
985
|
+
const base = column.isEnum ? tableSchema ? `${quoteIdentifier2(tableSchema)}.${quoteIdentifier2(column.sqlType)}` : quoteIdentifier2(column.sqlType) : column.sqlType;
|
|
986
|
+
return `${base}${column.isArray ? "[]" : ""}`;
|
|
987
|
+
}
|
|
959
988
|
var MAX_INSERT_PARAMS = 32000;
|
|
960
989
|
var MAX_INSERT_BYTES = 50 * 1024 * 1024;
|
|
961
990
|
function renderInsert(db, target, colNames, rowCount) {
|
|
@@ -964,7 +993,7 @@ function renderInsert(db, target, colNames, rowCount) {
|
|
|
964
993
|
if (cached)
|
|
965
994
|
return cached;
|
|
966
995
|
const placeholderRows = Array.from({ length: rowCount }, (_, r) => Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name], sql.placeholder(`${r}_${ci}`)])));
|
|
967
|
-
const rendered = db
|
|
996
|
+
const rendered = insertInto(db, target, colNames).values(placeholderRows).toSQL();
|
|
968
997
|
const value = { sqlText: rendered.sql, params: rendered.params };
|
|
969
998
|
target.insertRenderCache.set(key, value);
|
|
970
999
|
return value;
|
|
@@ -1082,6 +1111,16 @@ async function applyInsertsToTable({ pg, target, messages, debug }) {
|
|
|
1082
1111
|
if (debug)
|
|
1083
1112
|
console.log(`Inserted ${messages.length} rows using INSERT`);
|
|
1084
1113
|
}
|
|
1114
|
+
function upsertConflictSpec(target, columns) {
|
|
1115
|
+
const pkSet = new Set(target.primaryKey);
|
|
1116
|
+
const nonPkColumns = columns.filter((column) => !pkSet.has(column));
|
|
1117
|
+
const conflictTarget = target.primaryKey.map((column) => targetColumn(target, column));
|
|
1118
|
+
const conflictSet = {};
|
|
1119
|
+
for (const column of nonPkColumns) {
|
|
1120
|
+
conflictSet[target.propertyKeyByName[column]] = sql`excluded.${sql.identifier(column)}`;
|
|
1121
|
+
}
|
|
1122
|
+
return { conflictTarget, conflictSet, nonPkColumns };
|
|
1123
|
+
}
|
|
1085
1124
|
async function applyUpsertsToTable({ pg, target, messages, debug }) {
|
|
1086
1125
|
const primaryKey = target.primaryKey;
|
|
1087
1126
|
if (primaryKey.length === 0)
|
|
@@ -1091,19 +1130,13 @@ async function applyUpsertsToTable({ pg, target, messages, debug }) {
|
|
|
1091
1130
|
if (!firstRow)
|
|
1092
1131
|
return;
|
|
1093
1132
|
const columns = Object.keys(firstRow);
|
|
1094
|
-
const
|
|
1095
|
-
const nonPkColumns = columns.filter((column) => !pkSet.has(column));
|
|
1096
|
-
const conflictTarget = primaryKey.map((column) => targetColumn(target, column));
|
|
1097
|
-
const conflictSet = {};
|
|
1098
|
-
for (const column of nonPkColumns) {
|
|
1099
|
-
conflictSet[target.propertyKeyByName[column]] = sql`excluded.${sql.identifier(column)}`;
|
|
1100
|
-
}
|
|
1133
|
+
const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
|
|
1101
1134
|
const perRow = columns.length;
|
|
1102
1135
|
const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));
|
|
1103
1136
|
const db = drizzleOverPg(pg);
|
|
1104
1137
|
for (let i = 0;i < data.length; i += rowsPerBatch) {
|
|
1105
1138
|
const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));
|
|
1106
|
-
const insert = db
|
|
1139
|
+
const insert = insertInto(db, target, columns).values(batch);
|
|
1107
1140
|
if (nonPkColumns.length > 0) {
|
|
1108
1141
|
await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet });
|
|
1109
1142
|
} else {
|
|
@@ -1115,11 +1148,22 @@ async function applyUpsertsToTable({ pg, target, messages, debug }) {
|
|
|
1115
1148
|
}
|
|
1116
1149
|
function jsonRecordsetColumns(target, firstRow) {
|
|
1117
1150
|
const present = (name) => Object.prototype.hasOwnProperty.call(firstRow, name);
|
|
1118
|
-
|
|
1151
|
+
const { schema } = getTableConfig2(target.table);
|
|
1152
|
+
return target.columnTypes.filter((column) => present(column.name)).map((column) => ({ name: column.name, castType: castTypeFor(column, schema) }));
|
|
1119
1153
|
}
|
|
1120
|
-
|
|
1154
|
+
function jsonConflictClause(target, columns) {
|
|
1155
|
+
const pkSet = new Set(target.primaryKey);
|
|
1156
|
+
const nonPkColumns = columns.map((column) => column.name).filter((name) => !pkSet.has(name));
|
|
1157
|
+
const conflictTarget = sql.join(target.primaryKey.map((name) => sql`${sql.identifier(name)}`), sql`, `);
|
|
1158
|
+
if (nonPkColumns.length === 0) {
|
|
1159
|
+
return sql`ON CONFLICT (${conflictTarget}) DO NOTHING`;
|
|
1160
|
+
}
|
|
1161
|
+
const setList = sql.join(nonPkColumns.map((name) => sql`${sql.identifier(name)} = excluded.${sql.identifier(name)}`), sql`, `);
|
|
1162
|
+
return sql`ON CONFLICT (${conflictTarget}) DO UPDATE SET ${setList}`;
|
|
1163
|
+
}
|
|
1164
|
+
async function applyMessagesToTableWithJsonImpl({ pg, target, messages, debug }, conflict) {
|
|
1121
1165
|
if (debug)
|
|
1122
|
-
console.log(
|
|
1166
|
+
console.log(`applying messages with json_to_recordset${conflict ? " (upsert)" : ""}`);
|
|
1123
1167
|
const data = messages.map((message) => message.value);
|
|
1124
1168
|
const firstRow = data[0];
|
|
1125
1169
|
if (!firstRow) {
|
|
@@ -1128,16 +1172,27 @@ async function applyMessagesToTableWithJson({ pg, target, messages, debug }) {
|
|
|
1128
1172
|
const columns = jsonRecordsetColumns(target, firstRow);
|
|
1129
1173
|
const targetTable = target.table;
|
|
1130
1174
|
const recordDef = columns.map((column) => `${quoteIdentifier2(column.name)} ${column.castType}`).join(", ");
|
|
1175
|
+
const conflictClause = conflict ? sql` ${conflict}` : sql``;
|
|
1131
1176
|
const db = drizzleOverPg(pg);
|
|
1132
1177
|
const max = 1e4;
|
|
1133
1178
|
for (let i = 0;i < data.length; i += max) {
|
|
1134
1179
|
const batch = data.slice(i, i + max);
|
|
1135
|
-
await db.execute(sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`);
|
|
1180
|
+
await db.execute(sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})${conflictClause}`);
|
|
1136
1181
|
}
|
|
1137
1182
|
if (debug) {
|
|
1138
|
-
console.log(
|
|
1183
|
+
console.log(`${conflict ? "Upserted" : "Inserted"} ${messages.length} rows using json_to_recordset`);
|
|
1139
1184
|
}
|
|
1140
1185
|
}
|
|
1186
|
+
async function applyMessagesToTableWithJson(options) {
|
|
1187
|
+
return applyMessagesToTableWithJsonImpl(options, undefined);
|
|
1188
|
+
}
|
|
1189
|
+
async function applyUpsertsToTableWithJson(options) {
|
|
1190
|
+
const firstRow = options.messages[0]?.value;
|
|
1191
|
+
if (!firstRow)
|
|
1192
|
+
return;
|
|
1193
|
+
const columns = jsonRecordsetColumns(options.target, firstRow);
|
|
1194
|
+
return applyMessagesToTableWithJsonImpl(options, jsonConflictClause(options.target, columns));
|
|
1195
|
+
}
|
|
1141
1196
|
function copyColumnUdts(target) {
|
|
1142
1197
|
const map = {};
|
|
1143
1198
|
for (const column of target.columnTypes) {
|
|
@@ -1175,12 +1230,13 @@ async function applyMessagesToTableWithCopy({ pg, target, messages, debug }) {
|
|
|
1175
1230
|
var JSON_RECORDSET_BATCH = 1e4;
|
|
1176
1231
|
function recordsetColumnCasts(target, columnNames) {
|
|
1177
1232
|
const byName = new Map(target.columnTypes.map((column) => [column.name, column]));
|
|
1233
|
+
const { schema } = getTableConfig2(target.table);
|
|
1178
1234
|
return columnNames.map((name) => {
|
|
1179
1235
|
const column = byName.get(name);
|
|
1180
1236
|
if (!column) {
|
|
1181
1237
|
throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);
|
|
1182
1238
|
}
|
|
1183
|
-
return { name, castType:
|
|
1239
|
+
return { name, castType: castTypeFor(column, schema) };
|
|
1184
1240
|
});
|
|
1185
1241
|
}
|
|
1186
1242
|
async function applyBulkDeletesToTable({ pg, target, messages, debug }) {
|
|
@@ -2270,6 +2326,7 @@ function resolveApplyTarget(registry, tableKey) {
|
|
|
2270
2326
|
columnByName,
|
|
2271
2327
|
propertyKeyByName,
|
|
2272
2328
|
primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
|
|
2329
|
+
applyMode: entry.applyMode,
|
|
2273
2330
|
columnTypes: deriveSyncColumnTypes(entry),
|
|
2274
2331
|
insertRenderCache: new Map
|
|
2275
2332
|
};
|
|
@@ -5208,12 +5265,22 @@ async function createSyncEngine(pg, options) {
|
|
|
5208
5265
|
}
|
|
5209
5266
|
messages = remainingMessages;
|
|
5210
5267
|
if (initialInserts.length > 0) {
|
|
5211
|
-
|
|
5212
|
-
|
|
5213
|
-
|
|
5214
|
-
|
|
5215
|
-
|
|
5216
|
-
|
|
5268
|
+
if (target.applyMode === "upsert") {
|
|
5269
|
+
const applyInitialUpserts = shapeMethod === "insert" ? applyUpsertsToTable : applyUpsertsToTableWithJson;
|
|
5270
|
+
await applyInitialUpserts({
|
|
5271
|
+
pg: tx,
|
|
5272
|
+
target,
|
|
5273
|
+
messages: initialInserts,
|
|
5274
|
+
debug
|
|
5275
|
+
});
|
|
5276
|
+
} else {
|
|
5277
|
+
await insertMethods[shapeMethod]({
|
|
5278
|
+
pg: tx,
|
|
5279
|
+
target,
|
|
5280
|
+
messages: initialInserts,
|
|
5281
|
+
debug
|
|
5282
|
+
});
|
|
5283
|
+
}
|
|
5217
5284
|
useInsert.set(shapeName, true);
|
|
5218
5285
|
}
|
|
5219
5286
|
}
|
|
@@ -5228,7 +5295,7 @@ async function createSyncEngine(pg, options) {
|
|
|
5228
5295
|
});
|
|
5229
5296
|
}
|
|
5230
5297
|
if (folded.inserts.length > 0) {
|
|
5231
|
-
if (snapshotModeAtPeek.get(shapeName)) {
|
|
5298
|
+
if (snapshotModeAtPeek.get(shapeName) || target.applyMode === "upsert") {
|
|
5232
5299
|
await applyUpsertsToTable({
|
|
5233
5300
|
pg: tx,
|
|
5234
5301
|
target,
|
|
@@ -5761,6 +5828,21 @@ function fingerprintLiveQuery(materialSql, params, pkColumns) {
|
|
|
5761
5828
|
return { key, digest: shortDigest(key) };
|
|
5762
5829
|
}
|
|
5763
5830
|
|
|
5831
|
+
// packages/client/src/worker/live-query-params-guard.ts
|
|
5832
|
+
function assertLiveQueryParamsSafe(sql7, params) {
|
|
5833
|
+
if (params.length === 0)
|
|
5834
|
+
return;
|
|
5835
|
+
const numbers = [];
|
|
5836
|
+
for (const match of sql7.matchAll(/\$(\d+)/g))
|
|
5837
|
+
numbers.push(Number(match[1]));
|
|
5838
|
+
const expected = params.length;
|
|
5839
|
+
const safe = numbers.length === expected && numbers.every((n, i) => n === i + 1);
|
|
5840
|
+
if (safe)
|
|
5841
|
+
return;
|
|
5842
|
+
const found = numbers.length === 0 ? "(none)" : numbers.map((n) => `$${n}`).join(", ");
|
|
5843
|
+
throw new Error(`[pgxsinkit] live query hits PGlite bug #1055 ` + `(https://github.com/electric-sql/pglite/issues/1055): its live-query param inlining binds $N ` + `placeholders SEQUENTIALLY (in textual order), not positionally, so anything but a strictly ` + `ascending $1..$n each used once silently mis-binds or throws. Found placeholders [${found}] for ` + `${expected} param${expected === 1 ? "" : "s"}, expected exactly [$1..$${expected}]. Renumber the ` + `placeholders to a strictly sequential $1..$${expected}, each used once \u2014 or pass the query as a ` + `Drizzle builder, which always compiles to that shape.`);
|
|
5844
|
+
}
|
|
5845
|
+
|
|
5764
5846
|
// packages/client/src/worker/live-query-manager.ts
|
|
5765
5847
|
var MAX_KEEP_ALIVE_MS = 2147483647;
|
|
5766
5848
|
function validateLiveQueryPolicy(policy) {
|
|
@@ -5948,6 +6030,7 @@ function createLiveQueryManager(deps) {
|
|
|
5948
6030
|
if (hint !== undefined && hint > MAX_KEEP_ALIVE_MS) {
|
|
5949
6031
|
throw new TypeError(`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`);
|
|
5950
6032
|
}
|
|
6033
|
+
assertLiveQueryParamsSafe(spec.materialSql, spec.params);
|
|
5951
6034
|
const keepAliveMs = hint ?? 0;
|
|
5952
6035
|
const scope = opts?.scope;
|
|
5953
6036
|
let markSetupDone;
|
|
@@ -6454,10 +6537,22 @@ async function attachSyncClient(options) {
|
|
|
6454
6537
|
...hydrated ? { hydrated } : {}
|
|
6455
6538
|
};
|
|
6456
6539
|
};
|
|
6457
|
-
const { drizzle: drizzle5, views } = buildRegistryReadHandles(options.registry);
|
|
6458
6540
|
const notSupported = (name) => () => {
|
|
6459
|
-
throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client (
|
|
6541
|
+
throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local PGlite. ` + `Direct store access (client.pglite) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` + `implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` + `(ensureSynced), and the write API ARE proxied to the worker.`);
|
|
6542
|
+
};
|
|
6543
|
+
const noBridgeTransaction = () => {
|
|
6544
|
+
throw new Error("[pgxsinkit] client.drizzle.transaction() is not available on a worker-attached client: a read " + "transaction needs a local PGlite the tab does not have. Use one-shot reads (client.query) instead.");
|
|
6460
6545
|
};
|
|
6546
|
+
const guardedQueryArgs = (sql7, params, rowMode, use) => {
|
|
6547
|
+
const options2 = rowMode ? { rowMode } : {};
|
|
6548
|
+
return use ? [sql7, params, options2, use] : [sql7, params, options2];
|
|
6549
|
+
};
|
|
6550
|
+
const makeBridgeExecutor = (use) => ({
|
|
6551
|
+
query: (sql7, params, options2) => rpc("guardedQuery", guardedQueryArgs(sql7, params, options2?.rowMode, use)),
|
|
6552
|
+
transaction: noBridgeTransaction
|
|
6553
|
+
});
|
|
6554
|
+
const { drizzle: drizzle5, views, drizzleFor } = buildRegistryReadHandles(options.registry, makeBridgeExecutor());
|
|
6555
|
+
const bridgeReadDrizzle = (use) => drizzleFor(makeBridgeExecutor(use));
|
|
6461
6556
|
const groupKeyForTable = (table) => {
|
|
6462
6557
|
const entry = options.registry[table];
|
|
6463
6558
|
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
@@ -6465,9 +6560,7 @@ async function attachSyncClient(options) {
|
|
|
6465
6560
|
const client = {
|
|
6466
6561
|
drizzle: drizzle5,
|
|
6467
6562
|
views,
|
|
6468
|
-
pglite:
|
|
6469
|
-
get: notSupported("client.pglite")
|
|
6470
|
-
}),
|
|
6563
|
+
pglite: undefined,
|
|
6471
6564
|
tables: Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
|
|
6472
6565
|
tableKey,
|
|
6473
6566
|
{
|
|
@@ -6498,6 +6591,7 @@ async function attachSyncClient(options) {
|
|
|
6498
6591
|
readMutationDetails: (table) => rpc("readMutationDetails", [table]),
|
|
6499
6592
|
rawQuery: (sql7, params, options2) => rpc("rawQuery", [sql7, params, options2]),
|
|
6500
6593
|
rawExec: (sql7, options2) => rpc("rawExec", [sql7, options2]),
|
|
6594
|
+
guardedRawQuery: (sql7, params, options2, use) => rpc("guardedQuery", guardedQueryArgs(sql7, params, options2?.rowMode, use)),
|
|
6501
6595
|
mutate: {
|
|
6502
6596
|
create: (table, input) => rpc("create", [table, input]),
|
|
6503
6597
|
update: (table, entityKey, patch) => rpc("update", [table, entityKey, patch]),
|
|
@@ -6512,12 +6606,20 @@ async function attachSyncClient(options) {
|
|
|
6512
6606
|
subscribeLiveRows,
|
|
6513
6607
|
query: (sql7, params) => rpc("rawQuery", [sql7, params])
|
|
6514
6608
|
}),
|
|
6515
|
-
query:
|
|
6516
|
-
queryRow:
|
|
6517
|
-
|
|
6518
|
-
|
|
6519
|
-
|
|
6520
|
-
|
|
6609
|
+
query: (build) => Promise.resolve(build(client)),
|
|
6610
|
+
queryRow: async (build) => {
|
|
6611
|
+
const rows = await build(client);
|
|
6612
|
+
return rows[0] ?? null;
|
|
6613
|
+
},
|
|
6614
|
+
queryRaw: ({ build, use }) => Promise.resolve(build({ ...client, drizzle: bridgeReadDrizzle(use) })),
|
|
6615
|
+
queryRawRow: async ({ build, use }) => {
|
|
6616
|
+
const rows = await build({ ...client, drizzle: bridgeReadDrizzle(use) });
|
|
6617
|
+
return rows[0] ?? null;
|
|
6618
|
+
},
|
|
6619
|
+
ensureSynced: (keys) => rpc("ensureSynced", [keys]),
|
|
6620
|
+
isSynced: () => {
|
|
6621
|
+
throw new Error("[pgxsinkit] client.isSynced is not available on a worker-attached client: it is a SYNCHRONOUS " + "activation-STARTED peek (in-process: isTableStarted), but the tab caches only per-group CATCH-UP " + "readiness (status.groups / groupReady) \u2014 an activated-but-not-caught-up group reads as not-ready \u2014 " + "so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " + "client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.");
|
|
6622
|
+
},
|
|
6521
6623
|
desync: (key) => rpc("desync", [key]),
|
|
6522
6624
|
discardEphemeral: (key) => rpc("discardEphemeral", [key]),
|
|
6523
6625
|
prepareQuery: async () => ({ lazyTables: [] }),
|
|
@@ -6595,6 +6697,11 @@ async function attachSyncClient(options) {
|
|
|
6595
6697
|
postBridgeMessage(port, codec, "set-online", { online });
|
|
6596
6698
|
}
|
|
6597
6699
|
};
|
|
6700
|
+
Object.defineProperty(client, "pglite", {
|
|
6701
|
+
get: notSupported("client.pglite"),
|
|
6702
|
+
enumerable: false,
|
|
6703
|
+
configurable: true
|
|
6704
|
+
});
|
|
6598
6705
|
return client;
|
|
6599
6706
|
}
|
|
6600
6707
|
function provisionSyncWorker(options) {
|
|
@@ -6643,6 +6750,9 @@ function rebuildError(error) {
|
|
|
6643
6750
|
}
|
|
6644
6751
|
return rebuilt;
|
|
6645
6752
|
}
|
|
6753
|
+
// packages/client/src/worker/define-sync-worker.ts
|
|
6754
|
+
import { types as types2 } from "@electric-sql/pglite";
|
|
6755
|
+
|
|
6646
6756
|
// packages/client/src/worker/token-cache.ts
|
|
6647
6757
|
function createWorkerTokenCache(options) {
|
|
6648
6758
|
const now2 = options.now ?? (() => Date.now());
|
|
@@ -6697,12 +6807,27 @@ function createWorkerTokenCache(options) {
|
|
|
6697
6807
|
}
|
|
6698
6808
|
|
|
6699
6809
|
// packages/client/src/worker/define-sync-worker.ts
|
|
6810
|
+
var identityParser = (value) => value;
|
|
6811
|
+
var DRIZZLE_PGLITE_IDENTITY_PARSERS = {
|
|
6812
|
+
[types2.TIMESTAMP]: identityParser,
|
|
6813
|
+
[types2.TIMESTAMPTZ]: identityParser,
|
|
6814
|
+
[types2.INTERVAL]: identityParser,
|
|
6815
|
+
[types2.DATE]: identityParser,
|
|
6816
|
+
1231: identityParser,
|
|
6817
|
+
1115: identityParser,
|
|
6818
|
+
1185: identityParser,
|
|
6819
|
+
1187: identityParser,
|
|
6820
|
+
1182: identityParser
|
|
6821
|
+
};
|
|
6700
6822
|
function defineSyncWorker(options) {
|
|
6701
6823
|
validateLiveQueryPolicy(options.liveQueries);
|
|
6702
6824
|
const codec = options.codec ?? identityCodec;
|
|
6703
6825
|
const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30000;
|
|
6704
6826
|
const convergenceIntervalMs = options.convergenceIntervalMs ?? 15000;
|
|
6705
|
-
const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath,
|
|
6827
|
+
const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath, {
|
|
6828
|
+
...backendOverride ? { backendOverride } : {},
|
|
6829
|
+
...options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}
|
|
6830
|
+
}));
|
|
6706
6831
|
const workerTestMarker = readTestStoreMarker(options);
|
|
6707
6832
|
const ports = new Set;
|
|
6708
6833
|
const liveSubs = new Map;
|
|
@@ -6851,6 +6976,9 @@ function defineSyncWorker(options) {
|
|
|
6851
6976
|
...provisionStamp ? { provisionStamp } : {},
|
|
6852
6977
|
...precreatedPglite ? { precreatedPglite } : {},
|
|
6853
6978
|
...options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {},
|
|
6979
|
+
...options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {},
|
|
6980
|
+
...options.prepareLocalDb ? { prepareLocalDb: options.prepareLocalDb } : {},
|
|
6981
|
+
...options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {},
|
|
6854
6982
|
...attach.config?.freshStore === true ? { freshStore: true } : {},
|
|
6855
6983
|
getAuthToken: getWorkerAuthToken,
|
|
6856
6984
|
autoSync: gatedTrigger,
|
|
@@ -6863,13 +6991,21 @@ function defineSyncWorker(options) {
|
|
|
6863
6991
|
onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
|
|
6864
6992
|
onReject: (details) => broadcastEvent({ kind: "reject", details }),
|
|
6865
6993
|
onSchemaChange: (event) => broadcastEvent({ kind: "schema-change", event }),
|
|
6866
|
-
onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error
|
|
6994
|
+
onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: describeErrorChain(error) }),
|
|
6867
6995
|
onBootReport: (report) => broadcastEvent({ kind: "boot-report", report })
|
|
6868
6996
|
});
|
|
6869
6997
|
return bootPromise;
|
|
6870
6998
|
};
|
|
6871
6999
|
const whenBooted = () => bootedPromise;
|
|
6872
7000
|
const dispatchRpc = async (active, op, args) => {
|
|
7001
|
+
const runGuardedQueryRpc = () => {
|
|
7002
|
+
const [sql7, params, options2, use] = args;
|
|
7003
|
+
const queryOptions = {
|
|
7004
|
+
...options2?.rowMode ? { rowMode: options2.rowMode } : {},
|
|
7005
|
+
parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS
|
|
7006
|
+
};
|
|
7007
|
+
return active.guardedRawQuery(sql7, params, queryOptions, use);
|
|
7008
|
+
};
|
|
6873
7009
|
switch (op) {
|
|
6874
7010
|
case "create":
|
|
6875
7011
|
return active.mutate.create(args[0], args[1]);
|
|
@@ -6913,6 +7049,8 @@ function defineSyncWorker(options) {
|
|
|
6913
7049
|
return active.desync(args[0]);
|
|
6914
7050
|
case "discardEphemeral":
|
|
6915
7051
|
return active.discardEphemeral(args[0]);
|
|
7052
|
+
case "ensureSynced":
|
|
7053
|
+
return active.ensureSynced(args[0]);
|
|
6916
7054
|
case "readMutationDetails":
|
|
6917
7055
|
return active.readMutationDetails(args[0]);
|
|
6918
7056
|
case "diagnostics":
|
|
@@ -6921,6 +7059,8 @@ function defineSyncWorker(options) {
|
|
|
6921
7059
|
return active.rawQuery(args[0], args[1], args[2]);
|
|
6922
7060
|
case "rawExec":
|
|
6923
7061
|
return active.rawExec(args[0], args[1]);
|
|
7062
|
+
case "guardedQuery":
|
|
7063
|
+
return runGuardedQueryRpc();
|
|
6924
7064
|
case "bootReport":
|
|
6925
7065
|
return active.bootReport();
|
|
6926
7066
|
case "liveQueryDiagnostics":
|
|
@@ -7260,13 +7400,15 @@ async function createClientPGlite(store, options) {
|
|
|
7260
7400
|
const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => {
|
|
7261
7401
|
return;
|
|
7262
7402
|
}) : undefined;
|
|
7403
|
+
const relaxedDurability = options?.relaxedDurability ?? true;
|
|
7263
7404
|
return await timeAsync("boot pglite.create", () => PGlite2.create(dataDir, {
|
|
7264
7405
|
...bootAssets ?? {},
|
|
7406
|
+
relaxedDurability,
|
|
7265
7407
|
...options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {},
|
|
7266
7408
|
extensions: {
|
|
7267
7409
|
live
|
|
7268
7410
|
}
|
|
7269
|
-
}), { dataDir: dataDirScheme });
|
|
7411
|
+
}), { dataDir: dataDirScheme, relaxedDurability });
|
|
7270
7412
|
}
|
|
7271
7413
|
function replAdapter(client) {
|
|
7272
7414
|
return {
|
|
@@ -7309,13 +7451,7 @@ async function createSyncClient(options) {
|
|
|
7309
7451
|
if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
|
|
7310
7452
|
throw new Error("createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` \u2014 restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).");
|
|
7311
7453
|
}
|
|
7312
|
-
|
|
7313
|
-
syncDebug("boot restore forces offline \u2014 ignoring the online sync option for this restore boot", {
|
|
7314
|
-
syncEnabled: options.syncEnabled === true,
|
|
7315
|
-
autoSync: options.autoSync != null
|
|
7316
|
-
});
|
|
7317
|
-
}
|
|
7318
|
-
const syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
|
|
7454
|
+
let syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
|
|
7319
7455
|
const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
|
|
7320
7456
|
const storeKind = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
|
|
7321
7457
|
const bootReportBuilder = createBootReportBuilder({
|
|
@@ -7338,6 +7474,7 @@ async function createSyncClient(options) {
|
|
|
7338
7474
|
const createClientOptions = {
|
|
7339
7475
|
...options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {},
|
|
7340
7476
|
...backendOverride ? { backendOverride } : {},
|
|
7477
|
+
...options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {},
|
|
7341
7478
|
...restoreBoot ? { restoreFrom: options.restoreFrom } : {}
|
|
7342
7479
|
};
|
|
7343
7480
|
const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
@@ -7427,7 +7564,7 @@ async function createSyncClient(options) {
|
|
|
7427
7564
|
onSyncError: (error) => {
|
|
7428
7565
|
status.phase = "degraded";
|
|
7429
7566
|
degradedReason = "commit";
|
|
7430
|
-
status.lastError = error
|
|
7567
|
+
status.lastError = describeErrorChain(error);
|
|
7431
7568
|
options.onStatusChange?.(status);
|
|
7432
7569
|
options.onSyncError?.(error);
|
|
7433
7570
|
},
|
|
@@ -7438,7 +7575,7 @@ async function createSyncClient(options) {
|
|
|
7438
7575
|
return;
|
|
7439
7576
|
status.phase = "degraded";
|
|
7440
7577
|
degradedReason = "stream";
|
|
7441
|
-
status.lastError = error
|
|
7578
|
+
status.lastError = describeErrorChain(error);
|
|
7442
7579
|
options.onStatusChange?.(status);
|
|
7443
7580
|
},
|
|
7444
7581
|
onSyncActivity: () => {
|
|
@@ -7525,6 +7662,13 @@ async function createSyncClient(options) {
|
|
|
7525
7662
|
};
|
|
7526
7663
|
if (restoreBoot) {
|
|
7527
7664
|
await runBootRecoveryStage();
|
|
7665
|
+
const recoveredQuarantined = (await mutationRuntime.readMutationStats()).quarantinedCount;
|
|
7666
|
+
if (recoveredQuarantined === 0 && options.syncEnabled !== false) {
|
|
7667
|
+
syncEnabled = options.syncEnabled ?? true;
|
|
7668
|
+
syncDebug("boot restore comes online \u2014 recovered journal was clean (nothing to quarantine)");
|
|
7669
|
+
} else if (recoveredQuarantined > 0) {
|
|
7670
|
+
syncDebug("boot restore stays offline \u2014 recovered journal mutations were quarantined; release/discard them and a subsequent normal boot brings sync online", { quarantinedCount: recoveredQuarantined, syncEnabledOption: options.syncEnabled ?? null });
|
|
7671
|
+
}
|
|
7528
7672
|
await runReconcileStage();
|
|
7529
7673
|
} else {
|
|
7530
7674
|
await runReconcileStage();
|
|
@@ -7604,7 +7748,7 @@ async function createSyncClient(options) {
|
|
|
7604
7748
|
}
|
|
7605
7749
|
resolveSyncWired();
|
|
7606
7750
|
};
|
|
7607
|
-
if (options.autoSync && !restoreBoot) {
|
|
7751
|
+
if (options.autoSync && (!restoreBoot || syncEnabled)) {
|
|
7608
7752
|
convergenceDriver = createConvergenceDriver({
|
|
7609
7753
|
client: {
|
|
7610
7754
|
flush: () => mutationRuntime.flush(),
|
|
@@ -7865,12 +8009,19 @@ async function createSyncClient(options) {
|
|
|
7865
8009
|
});
|
|
7866
8010
|
return { lazyTables };
|
|
7867
8011
|
};
|
|
7868
|
-
const
|
|
8012
|
+
const gateAndGuardRead = async (sql7, use) => {
|
|
7869
8013
|
await localReadReady;
|
|
8014
|
+
await prepareQuery({ sql: sql7, ...use ? { use } : {} });
|
|
8015
|
+
};
|
|
8016
|
+
const runGuardedQuery = async (build, use) => {
|
|
7870
8017
|
const builder = build(client);
|
|
7871
|
-
await
|
|
8018
|
+
await gateAndGuardRead(builder.toSQL().sql, use);
|
|
7872
8019
|
return builder;
|
|
7873
8020
|
};
|
|
8021
|
+
const guardedRawQuery = async (sql7, params, options2, use) => {
|
|
8022
|
+
await gateAndGuardRead(sql7, use);
|
|
8023
|
+
return pglite.query(sql7, params, options2);
|
|
8024
|
+
};
|
|
7874
8025
|
const liveManager = createLiveQueryManager({
|
|
7875
8026
|
live: pglite.live,
|
|
7876
8027
|
...options.liveQueries ? { policy: options.liveQueries } : {}
|
|
@@ -7966,6 +8117,7 @@ async function createSyncClient(options) {
|
|
|
7966
8117
|
mutations: undefined,
|
|
7967
8118
|
rawQuery: (sql7, params, options2) => pglite.query(sql7, params, options2),
|
|
7968
8119
|
rawExec: (sql7, options2) => pglite.exec(sql7, options2),
|
|
8120
|
+
guardedRawQuery,
|
|
7969
8121
|
query: (build) => runGuardedQuery(build),
|
|
7970
8122
|
queryRow: async (build) => {
|
|
7971
8123
|
const rows = await runGuardedQuery(build);
|
|
@@ -8081,7 +8233,7 @@ async function createSyncClient(options) {
|
|
|
8081
8233
|
}
|
|
8082
8234
|
pendingActivations = null;
|
|
8083
8235
|
status.phase = "degraded";
|
|
8084
|
-
status.lastError =
|
|
8236
|
+
status.lastError = describeErrorChain(error);
|
|
8085
8237
|
options.onStatusChange?.(status);
|
|
8086
8238
|
rejectWriteReady(error);
|
|
8087
8239
|
rejectReady(error);
|
|
@@ -8116,13 +8268,19 @@ function buildSchema(registry) {
|
|
|
8116
8268
|
function buildViews(registry) {
|
|
8117
8269
|
return Object.fromEntries(Object.entries(registry).flatMap(([key, entry]) => entry.view != null ? [[key, entry.view]] : []));
|
|
8118
8270
|
}
|
|
8119
|
-
function buildRegistryReadHandles(registry) {
|
|
8120
|
-
const
|
|
8271
|
+
function buildRegistryReadHandles(registry, client = {}) {
|
|
8272
|
+
const drizzleFor = buildRegistryDrizzleFactory(registry);
|
|
8121
8273
|
return {
|
|
8122
|
-
drizzle:
|
|
8123
|
-
views: buildViews(registry)
|
|
8274
|
+
drizzle: drizzleFor(client),
|
|
8275
|
+
views: buildViews(registry),
|
|
8276
|
+
drizzleFor
|
|
8124
8277
|
};
|
|
8125
8278
|
}
|
|
8279
|
+
function buildRegistryDrizzleFactory(registry) {
|
|
8280
|
+
const relations = defineRelations(buildSchema(registry));
|
|
8281
|
+
const createDatabase = drizzle5;
|
|
8282
|
+
return (client) => createDatabase({ client, relations });
|
|
8283
|
+
}
|
|
8126
8284
|
function buildSyncConfigFromRegistry(registry, electricUrl) {
|
|
8127
8285
|
return {
|
|
8128
8286
|
electricUrl,
|
|
@@ -8210,4 +8368,4 @@ export {
|
|
|
8210
8368
|
BRIDGE_CHANNEL
|
|
8211
8369
|
};
|
|
8212
8370
|
|
|
8213
|
-
//# debugId=
|
|
8371
|
+
//# debugId=AF8FCBA60459DB4564756E2164756E21
|