@pgxsinkit/client 0.1.46 → 0.1.49
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/index.d.ts +61 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +647 -72
- package/dist/index.js.map +11 -9
- package/dist/lazy-guard.d.ts +20 -1
- package/dist/lazy-guard.d.ts.map +1 -1
- package/dist/mutation.d.ts +10 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-fingerprint.d.ts +14 -0
- package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts +130 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +21 -5
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +25 -4
- package/skills/operating/SKILL.md +29 -1
- package/src/index.ts +243 -35
- package/src/lazy-guard.ts +67 -25
- package/src/mutation.ts +30 -0
- package/src/worker/attach-sync-client.ts +90 -16
- package/src/worker/define-sync-worker.ts +214 -52
- package/src/worker/live-query-fingerprint.ts +128 -0
- package/src/worker/live-query-manager.ts +591 -0
- package/src/worker/protocol.ts +23 -4
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import { PGlite as PGlite2 } from "@electric-sql/pglite";
|
|
|
6
6
|
import { live } from "@electric-sql/pglite/live";
|
|
7
7
|
import { drizzle as drizzle4 } from "drizzle-orm/pglite";
|
|
8
8
|
import { defineRelations } from "drizzle-orm/relations";
|
|
9
|
-
import { fingerprintRegistry as fingerprintRegistry2, getSyncRegistrySchema as getSyncRegistrySchema4 } from "@pgxsinkit/contracts";
|
|
9
|
+
import { fingerprintRegistry as fingerprintRegistry2, getSyncRegistrySchema as getSyncRegistrySchema4, isClaimsDependentRowFilter } from "@pgxsinkit/contracts";
|
|
10
10
|
|
|
11
11
|
// packages/client/src/debug.ts
|
|
12
12
|
var isEnabled = () => globalThis.__pgxsinkitDebug === true;
|
|
@@ -621,28 +621,36 @@ async function performDataExport(deps, options = {}) {
|
|
|
621
621
|
|
|
622
622
|
// packages/client/src/lazy-guard.ts
|
|
623
623
|
import { getTableConfig, getViewConfig } from "drizzle-orm/pg-core";
|
|
624
|
+
function tokensForEntry(entry) {
|
|
625
|
+
const tokens = [];
|
|
626
|
+
if (entry.readProjection) {
|
|
627
|
+
const localTable = getTableConfig(entry.localTable);
|
|
628
|
+
tokens.push(quotedRef(localTable.name, localTable.schema));
|
|
629
|
+
} else {
|
|
630
|
+
const table = getTableConfig(entry.table);
|
|
631
|
+
tokens.push(quotedRef(table.name, table.schema));
|
|
632
|
+
if (entry.view != null) {
|
|
633
|
+
const view = getViewConfig(entry.view);
|
|
634
|
+
tokens.push(quotedRef(view.name, view.schema));
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return tokens;
|
|
638
|
+
}
|
|
624
639
|
function buildLazyGuardIndex(registry) {
|
|
625
640
|
const lazyKeys = new Set;
|
|
626
641
|
const lazyTokens = new Map;
|
|
642
|
+
const allKeys = new Set;
|
|
643
|
+
const allTokens = new Map;
|
|
627
644
|
for (const [key, entry] of Object.entries(registry)) {
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
tokens.push(quotedRef(localTable.name, localTable.schema));
|
|
635
|
-
} else {
|
|
636
|
-
const table = getTableConfig(entry.table);
|
|
637
|
-
tokens.push(quotedRef(table.name, table.schema));
|
|
638
|
-
if (entry.view != null) {
|
|
639
|
-
const view = getViewConfig(entry.view);
|
|
640
|
-
tokens.push(quotedRef(view.name, view.schema));
|
|
641
|
-
}
|
|
645
|
+
const tokens = tokensForEntry(entry);
|
|
646
|
+
allKeys.add(key);
|
|
647
|
+
allTokens.set(key, tokens);
|
|
648
|
+
if (entry.subscription === "lazy") {
|
|
649
|
+
lazyKeys.add(key);
|
|
650
|
+
lazyTokens.set(key, tokens);
|
|
642
651
|
}
|
|
643
|
-
lazyTokens.set(key, tokens);
|
|
644
652
|
}
|
|
645
|
-
return { lazyKeys, lazyTokens };
|
|
653
|
+
return { lazyKeys, lazyTokens, allKeys, allTokens };
|
|
646
654
|
}
|
|
647
655
|
function quotedRef(name, schema) {
|
|
648
656
|
return schema != null && schema.length > 0 ? `"${schema}"."${name}"` : `"${name}"`;
|
|
@@ -655,6 +663,14 @@ function findReferencedLazyKeysInSql(sql, index) {
|
|
|
655
663
|
}
|
|
656
664
|
return found;
|
|
657
665
|
}
|
|
666
|
+
function findReferencedSyncedKeysInSql(sql, index) {
|
|
667
|
+
const found = new Set;
|
|
668
|
+
for (const [key, tokens] of index.allTokens) {
|
|
669
|
+
if (tokens.some((token) => sqlReferencesToken(sql, token)))
|
|
670
|
+
found.add(key);
|
|
671
|
+
}
|
|
672
|
+
return found;
|
|
673
|
+
}
|
|
658
674
|
function sqlReferencesToken(sql, token) {
|
|
659
675
|
for (let from = 0;; ) {
|
|
660
676
|
const at = sql.indexOf(token, from);
|
|
@@ -2411,6 +2427,18 @@ function createMutationRuntime(options) {
|
|
|
2411
2427
|
const needsAuthClaims = items.some((item) => item.kind === "create" && getTableContext(item.table).managedAuthClaimCreateFields.length > 0);
|
|
2412
2428
|
const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;
|
|
2413
2429
|
const normalizedItems = items.map((item, index2) => normalizeBatchItem(item, index2, claims));
|
|
2430
|
+
const ordinaryTables = new Set;
|
|
2431
|
+
for (const item of normalizedItems) {
|
|
2432
|
+
if (item.kind === "update" && item.blind) {
|
|
2433
|
+
continue;
|
|
2434
|
+
}
|
|
2435
|
+
ordinaryTables.add(item.context.key);
|
|
2436
|
+
}
|
|
2437
|
+
if (ordinaryTables.size > 0 && options.onOrdinaryEnqueue) {
|
|
2438
|
+
try {
|
|
2439
|
+
options.onOrdinaryEnqueue([...ordinaryTables]);
|
|
2440
|
+
} catch {}
|
|
2441
|
+
}
|
|
2414
2442
|
const batchGroups = new Map;
|
|
2415
2443
|
for (const item of normalizedItems) {
|
|
2416
2444
|
const existing = batchGroups.get(item.context.key);
|
|
@@ -5112,6 +5140,7 @@ async function createSyncEngine(pg, options) {
|
|
|
5112
5140
|
close
|
|
5113
5141
|
};
|
|
5114
5142
|
}
|
|
5143
|
+
|
|
5115
5144
|
// packages/client/src/worker/live-diff.ts
|
|
5116
5145
|
var KEY_SEP = String.fromCharCode(0);
|
|
5117
5146
|
function rowKey(row, pkColumns) {
|
|
@@ -5198,6 +5227,362 @@ class LiveRowsMaterializer {
|
|
|
5198
5227
|
}
|
|
5199
5228
|
}
|
|
5200
5229
|
|
|
5230
|
+
// packages/client/src/worker/live-query-fingerprint.ts
|
|
5231
|
+
var opaqueCounter = 0;
|
|
5232
|
+
function opaqueToken() {
|
|
5233
|
+
return `${(opaqueCounter++).toString(36)}.${Math.random().toString(36).slice(2)}`;
|
|
5234
|
+
}
|
|
5235
|
+
function toHex(bytes) {
|
|
5236
|
+
let hex = "";
|
|
5237
|
+
for (const byte of bytes)
|
|
5238
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
5239
|
+
return hex;
|
|
5240
|
+
}
|
|
5241
|
+
function isPlainObject(value) {
|
|
5242
|
+
const proto = Object.getPrototypeOf(value);
|
|
5243
|
+
return proto === Object.prototype || proto === null;
|
|
5244
|
+
}
|
|
5245
|
+
function encodeValue(value) {
|
|
5246
|
+
if (value === null)
|
|
5247
|
+
return ["z"];
|
|
5248
|
+
if (value === undefined)
|
|
5249
|
+
return ["v"];
|
|
5250
|
+
switch (typeof value) {
|
|
5251
|
+
case "boolean":
|
|
5252
|
+
return ["b", value];
|
|
5253
|
+
case "number":
|
|
5254
|
+
return ["n", String(value)];
|
|
5255
|
+
case "bigint":
|
|
5256
|
+
return ["i", value.toString()];
|
|
5257
|
+
case "string":
|
|
5258
|
+
return ["s", value];
|
|
5259
|
+
case "object": {
|
|
5260
|
+
if (value instanceof Date)
|
|
5261
|
+
return ["d", value.getTime()];
|
|
5262
|
+
if (value instanceof Uint8Array)
|
|
5263
|
+
return ["x", toHex(value)];
|
|
5264
|
+
if (value instanceof ArrayBuffer)
|
|
5265
|
+
return ["x", toHex(new Uint8Array(value))];
|
|
5266
|
+
if (ArrayBuffer.isView(value)) {
|
|
5267
|
+
const view = value;
|
|
5268
|
+
return ["x", toHex(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))];
|
|
5269
|
+
}
|
|
5270
|
+
if (Array.isArray(value))
|
|
5271
|
+
return ["a", value.map(encodeValue)];
|
|
5272
|
+
if (isPlainObject(value)) {
|
|
5273
|
+
const record = value;
|
|
5274
|
+
const members = Object.keys(record).sort().map((k) => [k, encodeValue(record[k])]);
|
|
5275
|
+
return ["o", members];
|
|
5276
|
+
}
|
|
5277
|
+
return ["q", opaqueToken()];
|
|
5278
|
+
}
|
|
5279
|
+
default:
|
|
5280
|
+
return ["q", opaqueToken()];
|
|
5281
|
+
}
|
|
5282
|
+
}
|
|
5283
|
+
function shortDigest(key) {
|
|
5284
|
+
let hash = 2166136261;
|
|
5285
|
+
for (let i = 0;i < key.length; i++) {
|
|
5286
|
+
hash ^= key.charCodeAt(i);
|
|
5287
|
+
hash = Math.imul(hash, 16777619);
|
|
5288
|
+
}
|
|
5289
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
5290
|
+
}
|
|
5291
|
+
function fingerprintLiveQuery(materialSql, params, pkColumns) {
|
|
5292
|
+
const mode = pkColumns && pkColumns.length === 1 ? "inc" : "full";
|
|
5293
|
+
const key = JSON.stringify({
|
|
5294
|
+
sql: materialSql,
|
|
5295
|
+
params: params.map(encodeValue),
|
|
5296
|
+
pk: pkColumns ? [...pkColumns] : null,
|
|
5297
|
+
mode
|
|
5298
|
+
});
|
|
5299
|
+
return { key, digest: shortDigest(key) };
|
|
5300
|
+
}
|
|
5301
|
+
|
|
5302
|
+
// packages/client/src/worker/live-query-manager.ts
|
|
5303
|
+
var MAX_KEEP_ALIVE_MS = 2147483647;
|
|
5304
|
+
function validateLiveQueryPolicy(policy) {
|
|
5305
|
+
if (policy == null)
|
|
5306
|
+
return;
|
|
5307
|
+
const ms = (name, value) => {
|
|
5308
|
+
if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
|
|
5309
|
+
throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a finite number >= 0 (got ${value})`);
|
|
5310
|
+
}
|
|
5311
|
+
if (value !== undefined && value > MAX_KEEP_ALIVE_MS) {
|
|
5312
|
+
throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${value})`);
|
|
5313
|
+
}
|
|
5314
|
+
};
|
|
5315
|
+
const int = (name, value) => {
|
|
5316
|
+
if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
|
|
5317
|
+
throw new TypeError(`[pgxsinkit] liveQueries.${String(name)} must be a non-negative integer (got ${value})`);
|
|
5318
|
+
}
|
|
5319
|
+
};
|
|
5320
|
+
ms("defaultKeepAliveMs", policy.defaultKeepAliveMs);
|
|
5321
|
+
int("maxRetainedQueries", policy.maxRetainedQueries);
|
|
5322
|
+
int("maxRetainedRows", policy.maxRetainedRows);
|
|
5323
|
+
}
|
|
5324
|
+
function createLiveQueryManager(deps) {
|
|
5325
|
+
validateLiveQueryPolicy(deps.policy);
|
|
5326
|
+
const { live } = deps;
|
|
5327
|
+
const policy = {
|
|
5328
|
+
defaultKeepAliveMs: deps.policy?.defaultKeepAliveMs ?? 0,
|
|
5329
|
+
maxRetainedQueries: deps.policy?.maxRetainedQueries ?? 16,
|
|
5330
|
+
maxRetainedRows: deps.policy?.maxRetainedRows ?? 50000
|
|
5331
|
+
};
|
|
5332
|
+
const now2 = deps.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
5333
|
+
const setTimer = deps.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
|
|
5334
|
+
const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
|
|
5335
|
+
const pendingTeardowns = new Set;
|
|
5336
|
+
const entries = new Map;
|
|
5337
|
+
const retained = new Set;
|
|
5338
|
+
const setups = new Set;
|
|
5339
|
+
let dedupHits = 0;
|
|
5340
|
+
let disposed = false;
|
|
5341
|
+
const createEntry = (key, digest, spec) => {
|
|
5342
|
+
const entry = {
|
|
5343
|
+
key,
|
|
5344
|
+
digest,
|
|
5345
|
+
subscribers: new Map,
|
|
5346
|
+
torn: false,
|
|
5347
|
+
generationKeepAliveMs: 0,
|
|
5348
|
+
createdAt: now2(),
|
|
5349
|
+
dedupHits: 0,
|
|
5350
|
+
refreshCount: 0,
|
|
5351
|
+
refreshTotalMs: 0,
|
|
5352
|
+
refreshMaxMs: 0,
|
|
5353
|
+
teardownPending: false,
|
|
5354
|
+
setup: undefined
|
|
5355
|
+
};
|
|
5356
|
+
entry.setup = (async () => {
|
|
5357
|
+
const setupStartedAt = now2();
|
|
5358
|
+
const { materialSql, params, pkColumns } = spec;
|
|
5359
|
+
const registered = pkColumns && pkColumns.length === 1 ? await live.incrementalQuery(materialSql, params, pkColumns[0]) : await live.query(materialSql, params);
|
|
5360
|
+
const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
|
|
5361
|
+
const listener = (results) => {
|
|
5362
|
+
const diff = computeLiveDiff(state, results.rows);
|
|
5363
|
+
for (const record of entry.subscribers.values()) {
|
|
5364
|
+
try {
|
|
5365
|
+
record.subscriber.deliverDiff(diff);
|
|
5366
|
+
} catch {
|
|
5367
|
+
syncDebug("live-query subscriber-error", { digest: entry.digest });
|
|
5368
|
+
}
|
|
5369
|
+
}
|
|
5370
|
+
if (retained.has(entry))
|
|
5371
|
+
queueMicrotask(() => enforceBudgets());
|
|
5372
|
+
};
|
|
5373
|
+
registered.subscribe(listener);
|
|
5374
|
+
entry.registered = registered;
|
|
5375
|
+
entry.state = state;
|
|
5376
|
+
entry.listener = listener;
|
|
5377
|
+
entry.setupMs = now2() - setupStartedAt;
|
|
5378
|
+
syncDebug("live-query register", { digest, setupMs: Math.round(entry.setupMs) });
|
|
5379
|
+
})();
|
|
5380
|
+
entry.setup.catch(() => {
|
|
5381
|
+
if (entries.get(key) === entry)
|
|
5382
|
+
entries.delete(key);
|
|
5383
|
+
});
|
|
5384
|
+
return entry;
|
|
5385
|
+
};
|
|
5386
|
+
const tearDownEntry = (entry) => {
|
|
5387
|
+
if (entry.torn)
|
|
5388
|
+
return entry.teardown ?? Promise.resolve();
|
|
5389
|
+
entry.torn = true;
|
|
5390
|
+
entry.teardownPending = true;
|
|
5391
|
+
const teardown = (async () => {
|
|
5392
|
+
await entry.setup.catch(() => {});
|
|
5393
|
+
if (entry.registered && entry.listener)
|
|
5394
|
+
await entry.registered.unsubscribe(entry.listener);
|
|
5395
|
+
})().catch(() => {
|
|
5396
|
+
syncDebug("live-query teardown-failed", { digest: entry.digest });
|
|
5397
|
+
}).finally(() => {
|
|
5398
|
+
entry.teardownPending = false;
|
|
5399
|
+
if (entries.get(entry.key) === entry)
|
|
5400
|
+
entries.delete(entry.key);
|
|
5401
|
+
syncDebug("live-query teardown-complete", { digest: entry.digest });
|
|
5402
|
+
});
|
|
5403
|
+
entry.teardown = teardown;
|
|
5404
|
+
pendingTeardowns.add(teardown);
|
|
5405
|
+
teardown.finally(() => pendingTeardowns.delete(teardown));
|
|
5406
|
+
return teardown;
|
|
5407
|
+
};
|
|
5408
|
+
const cancelEviction = (entry) => {
|
|
5409
|
+
if (entry.evictionTimer !== undefined) {
|
|
5410
|
+
clearTimer(entry.evictionTimer);
|
|
5411
|
+
entry.evictionTimer = undefined;
|
|
5412
|
+
}
|
|
5413
|
+
retained.delete(entry);
|
|
5414
|
+
};
|
|
5415
|
+
const retainedRowTotal = () => {
|
|
5416
|
+
let total = 0;
|
|
5417
|
+
for (const entry of retained)
|
|
5418
|
+
total += entry.state?.previous.size ?? 0;
|
|
5419
|
+
return total;
|
|
5420
|
+
};
|
|
5421
|
+
const enforceBudgets = () => {
|
|
5422
|
+
if (disposed)
|
|
5423
|
+
return;
|
|
5424
|
+
while (retained.size > policy.maxRetainedQueries || retainedRowTotal() > policy.maxRetainedRows) {
|
|
5425
|
+
const reason = retained.size > policy.maxRetainedQueries ? "count-budget" : "row-budget";
|
|
5426
|
+
let victim;
|
|
5427
|
+
for (const entry of retained) {
|
|
5428
|
+
if (victim === undefined || (entry.lastUsedAt ?? 0) < (victim.lastUsedAt ?? 0))
|
|
5429
|
+
victim = entry;
|
|
5430
|
+
}
|
|
5431
|
+
if (victim === undefined)
|
|
5432
|
+
break;
|
|
5433
|
+
cancelEviction(victim);
|
|
5434
|
+
syncDebug("live-query evicted", { digest: victim.digest, reason });
|
|
5435
|
+
tearDownEntry(victim);
|
|
5436
|
+
}
|
|
5437
|
+
};
|
|
5438
|
+
const onEvictionTimer = (entry) => {
|
|
5439
|
+
entry.evictionTimer = undefined;
|
|
5440
|
+
if (entry.torn || !retained.has(entry) || entry.subscribers.size > 0)
|
|
5441
|
+
return;
|
|
5442
|
+
retained.delete(entry);
|
|
5443
|
+
syncDebug("live-query evicted", { digest: entry.digest, reason: "expiry" });
|
|
5444
|
+
tearDownEntry(entry);
|
|
5445
|
+
};
|
|
5446
|
+
const removeSubscriber = (entry, token) => {
|
|
5447
|
+
if (!entry.subscribers.has(token))
|
|
5448
|
+
return entry.teardown ?? Promise.resolve();
|
|
5449
|
+
entry.subscribers.delete(token);
|
|
5450
|
+
if (entry.subscribers.size > 0)
|
|
5451
|
+
return Promise.resolve();
|
|
5452
|
+
const effective = Math.max(policy.defaultKeepAliveMs, entry.generationKeepAliveMs);
|
|
5453
|
+
if (effective <= 0 || disposed || entry.torn)
|
|
5454
|
+
return tearDownEntry(entry);
|
|
5455
|
+
entry.lastUsedAt = now2();
|
|
5456
|
+
retained.add(entry);
|
|
5457
|
+
entry.evictionTimer = setTimer(() => onEvictionTimer(entry), effective);
|
|
5458
|
+
syncDebug("live-query retained", { digest: entry.digest, keepAliveMs: effective });
|
|
5459
|
+
enforceBudgets();
|
|
5460
|
+
return Promise.resolve();
|
|
5461
|
+
};
|
|
5462
|
+
const refreshEntry = (entry) => {
|
|
5463
|
+
if (entry.torn || !entry.registered)
|
|
5464
|
+
return Promise.resolve();
|
|
5465
|
+
if (entry.refreshInFlight === undefined) {
|
|
5466
|
+
const startedAt = now2();
|
|
5467
|
+
entry.refreshInFlight = entry.registered.refresh().finally(() => {
|
|
5468
|
+
const ms = now2() - startedAt;
|
|
5469
|
+
entry.refreshCount++;
|
|
5470
|
+
entry.refreshLastMs = ms;
|
|
5471
|
+
entry.refreshTotalMs += ms;
|
|
5472
|
+
if (ms > entry.refreshMaxMs)
|
|
5473
|
+
entry.refreshMaxMs = ms;
|
|
5474
|
+
delete entry.refreshInFlight;
|
|
5475
|
+
});
|
|
5476
|
+
}
|
|
5477
|
+
return entry.refreshInFlight;
|
|
5478
|
+
};
|
|
5479
|
+
const subscribe = async (spec, subscriber, opts) => {
|
|
5480
|
+
if (disposed)
|
|
5481
|
+
throw new Error("[pgxsinkit] live-query subscribe after dispose \u2014 the engine is closing");
|
|
5482
|
+
const hint = opts?.keepAliveMs;
|
|
5483
|
+
if (hint !== undefined && (!Number.isFinite(hint) || hint < 0)) {
|
|
5484
|
+
throw new TypeError(`[pgxsinkit] keepAliveMs must be a finite number >= 0 (got ${hint})`);
|
|
5485
|
+
}
|
|
5486
|
+
if (hint !== undefined && hint > MAX_KEEP_ALIVE_MS) {
|
|
5487
|
+
throw new TypeError(`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`);
|
|
5488
|
+
}
|
|
5489
|
+
const keepAliveMs = hint ?? 0;
|
|
5490
|
+
const scope = opts?.scope;
|
|
5491
|
+
let markSetupDone;
|
|
5492
|
+
const setupDone = new Promise((resolve) => {
|
|
5493
|
+
markSetupDone = resolve;
|
|
5494
|
+
});
|
|
5495
|
+
setups.add(setupDone);
|
|
5496
|
+
try {
|
|
5497
|
+
const { key, digest } = fingerprintLiveQuery(spec.materialSql, spec.params, spec.pkColumns);
|
|
5498
|
+
let entry = entries.get(key);
|
|
5499
|
+
while (entry && entry.torn) {
|
|
5500
|
+
await entry.teardown;
|
|
5501
|
+
entry = entries.get(key);
|
|
5502
|
+
}
|
|
5503
|
+
if (entry && retained.has(entry))
|
|
5504
|
+
cancelEviction(entry);
|
|
5505
|
+
const isDedupHit = entry != null;
|
|
5506
|
+
if (!entry) {
|
|
5507
|
+
entry = createEntry(key, digest, spec);
|
|
5508
|
+
entries.set(key, entry);
|
|
5509
|
+
}
|
|
5510
|
+
const joined = entry;
|
|
5511
|
+
if (isDedupHit) {
|
|
5512
|
+
dedupHits++;
|
|
5513
|
+
joined.dedupHits++;
|
|
5514
|
+
syncDebug("live-query dedup-hit", { digest: joined.digest, dedupHits });
|
|
5515
|
+
}
|
|
5516
|
+
await joined.setup;
|
|
5517
|
+
const firstOfGeneration = joined.subscribers.size === 0;
|
|
5518
|
+
joined.generationKeepAliveMs = firstOfGeneration ? keepAliveMs : Math.max(joined.generationKeepAliveMs, keepAliveMs);
|
|
5519
|
+
const token = Symbol("live-subscriber");
|
|
5520
|
+
const snapshot2 = [...joined.state.previous.values()];
|
|
5521
|
+
joined.subscribers.set(token, { subscriber, keepAliveMs, scope });
|
|
5522
|
+
try {
|
|
5523
|
+
subscriber.deliverInitial(snapshot2);
|
|
5524
|
+
} catch (error) {
|
|
5525
|
+
joined.subscribers.delete(token);
|
|
5526
|
+
if (joined.subscribers.size === 0)
|
|
5527
|
+
tearDownEntry(joined);
|
|
5528
|
+
throw error;
|
|
5529
|
+
}
|
|
5530
|
+
return {
|
|
5531
|
+
unsubscribe: () => removeSubscriber(joined, token),
|
|
5532
|
+
refresh: () => refreshEntry(joined)
|
|
5533
|
+
};
|
|
5534
|
+
} finally {
|
|
5535
|
+
setups.delete(setupDone);
|
|
5536
|
+
markSetupDone();
|
|
5537
|
+
}
|
|
5538
|
+
};
|
|
5539
|
+
const dispose = async () => {
|
|
5540
|
+
disposed = true;
|
|
5541
|
+
for (const entry of entries.values()) {
|
|
5542
|
+
if (entry.evictionTimer !== undefined) {
|
|
5543
|
+
clearTimer(entry.evictionTimer);
|
|
5544
|
+
entry.evictionTimer = undefined;
|
|
5545
|
+
}
|
|
5546
|
+
}
|
|
5547
|
+
retained.clear();
|
|
5548
|
+
while (setups.size > 0 || entries.size > 0 || pendingTeardowns.size > 0) {
|
|
5549
|
+
await Promise.allSettled([...setups]);
|
|
5550
|
+
for (const entry of entries.values())
|
|
5551
|
+
tearDownEntry(entry);
|
|
5552
|
+
await Promise.allSettled([...pendingTeardowns]);
|
|
5553
|
+
}
|
|
5554
|
+
};
|
|
5555
|
+
const snapshot = () => {
|
|
5556
|
+
const records = [];
|
|
5557
|
+
for (const entry of entries.values()) {
|
|
5558
|
+
const isRetained = retained.has(entry);
|
|
5559
|
+
const scopes = new Set;
|
|
5560
|
+
for (const { scope } of entry.subscribers.values())
|
|
5561
|
+
scopes.add(scope);
|
|
5562
|
+
records.push({
|
|
5563
|
+
digest: entry.digest,
|
|
5564
|
+
subscriberCount: entry.subscribers.size,
|
|
5565
|
+
scopeCount: scopes.size,
|
|
5566
|
+
rowCount: entry.state?.previous.size ?? 0,
|
|
5567
|
+
retained: isRetained,
|
|
5568
|
+
dedupHits: entry.dedupHits,
|
|
5569
|
+
createdAt: entry.createdAt,
|
|
5570
|
+
setupMs: entry.setupMs ?? null,
|
|
5571
|
+
refresh: {
|
|
5572
|
+
count: entry.refreshCount,
|
|
5573
|
+
lastMs: entry.refreshLastMs ?? null,
|
|
5574
|
+
totalMs: entry.refreshTotalMs,
|
|
5575
|
+
maxMs: entry.refreshMaxMs
|
|
5576
|
+
},
|
|
5577
|
+
lastUsedAt: entry.lastUsedAt ?? null,
|
|
5578
|
+
retainedSinceMs: isRetained && entry.lastUsedAt != null ? Math.max(0, now2() - entry.lastUsedAt) : null,
|
|
5579
|
+
teardownPending: entry.teardownPending
|
|
5580
|
+
});
|
|
5581
|
+
}
|
|
5582
|
+
return records;
|
|
5583
|
+
};
|
|
5584
|
+
return { subscribe, dispose, snapshot };
|
|
5585
|
+
}
|
|
5201
5586
|
// packages/client/src/worker/protocol.ts
|
|
5202
5587
|
var BRIDGE_CHANNEL = "pgxsinkit-bridge";
|
|
5203
5588
|
var BRIDGE_PROTOCOL_VERSION = 1;
|
|
@@ -5239,6 +5624,8 @@ async function attachSyncClient(options) {
|
|
|
5239
5624
|
const initialPending = new Map;
|
|
5240
5625
|
const diffHandlers = new Map;
|
|
5241
5626
|
const hydratedPending = new Map;
|
|
5627
|
+
let detached = false;
|
|
5628
|
+
const detachError = () => new Error("[pgxsinkit] client detached \u2014 the tab released its worker attachment");
|
|
5242
5629
|
const status = { phase: "booting", isRunning: false };
|
|
5243
5630
|
let resolveReady;
|
|
5244
5631
|
const ready = new Promise((resolve) => {
|
|
@@ -5395,6 +5782,8 @@ async function attachSyncClient(options) {
|
|
|
5395
5782
|
port.addEventListener("message", listener);
|
|
5396
5783
|
port.start?.();
|
|
5397
5784
|
const rpc = (op, args) => {
|
|
5785
|
+
if (detached)
|
|
5786
|
+
return Promise.reject(detachError());
|
|
5398
5787
|
const id = newId("rpc");
|
|
5399
5788
|
return new Promise((resolve, reject) => {
|
|
5400
5789
|
rpcPending.set(id, { resolve, reject });
|
|
@@ -5407,6 +5796,41 @@ async function attachSyncClient(options) {
|
|
|
5407
5796
|
attachAckResolve = resolve;
|
|
5408
5797
|
attachAckReject = reject;
|
|
5409
5798
|
});
|
|
5799
|
+
const detachFromWorker = () => {
|
|
5800
|
+
if (detached)
|
|
5801
|
+
return;
|
|
5802
|
+
detached = true;
|
|
5803
|
+
status.isRunning = false;
|
|
5804
|
+
for (const queryId of diffHandlers.keys())
|
|
5805
|
+
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
5806
|
+
diffHandlers.clear();
|
|
5807
|
+
postBridgeMessage(port, codec, "detach", null);
|
|
5808
|
+
attachAckReject?.(detachError());
|
|
5809
|
+
for (const pending of rpcPending.values())
|
|
5810
|
+
pending.reject(detachError());
|
|
5811
|
+
rpcPending.clear();
|
|
5812
|
+
for (const pending of initialPending.values())
|
|
5813
|
+
pending.reject(detachError());
|
|
5814
|
+
initialPending.clear();
|
|
5815
|
+
for (const resolve of hydratedPending.values())
|
|
5816
|
+
resolve();
|
|
5817
|
+
hydratedPending.clear();
|
|
5818
|
+
for (const waiters of groupWaiters.values())
|
|
5819
|
+
for (const resolve of waiters)
|
|
5820
|
+
resolve();
|
|
5821
|
+
groupWaiters.clear();
|
|
5822
|
+
if (pagehideListener)
|
|
5823
|
+
pageWindow?.removeEventListener("pagehide", pagehideListener);
|
|
5824
|
+
port.removeEventListener("message", listener);
|
|
5825
|
+
port.close?.();
|
|
5826
|
+
};
|
|
5827
|
+
const pageWindow = globalThis.window;
|
|
5828
|
+
const pagehideListener = pageWindow ? (event) => {
|
|
5829
|
+
if (!event.persisted)
|
|
5830
|
+
detachFromWorker();
|
|
5831
|
+
} : undefined;
|
|
5832
|
+
if (pagehideListener)
|
|
5833
|
+
pageWindow?.addEventListener("pagehide", pagehideListener);
|
|
5410
5834
|
const initialToken = options.getToken ? await options.getToken() : null;
|
|
5411
5835
|
const memoryOverride = readTestStoreMarker(options) === "memory";
|
|
5412
5836
|
const restoreWire = options.restoreFrom ? {
|
|
@@ -5432,11 +5856,13 @@ async function attachSyncClient(options) {
|
|
|
5432
5856
|
try {
|
|
5433
5857
|
await attachAck;
|
|
5434
5858
|
} catch (error) {
|
|
5435
|
-
|
|
5859
|
+
detachFromWorker();
|
|
5436
5860
|
throw error;
|
|
5437
5861
|
}
|
|
5438
5862
|
status.isRunning = true;
|
|
5439
5863
|
const subscribeLiveRows = async (input, onRows) => {
|
|
5864
|
+
if (detached)
|
|
5865
|
+
throw detachError();
|
|
5440
5866
|
const queryId = newId("live");
|
|
5441
5867
|
const id = newId("sub");
|
|
5442
5868
|
const materializer = new LiveRowsMaterializer(input.pkColumns);
|
|
@@ -5453,7 +5879,8 @@ async function attachSyncClient(options) {
|
|
|
5453
5879
|
params: [...input.params],
|
|
5454
5880
|
...input.fields ? { fields: [...input.fields] } : {},
|
|
5455
5881
|
...input.pkColumns ? { pkColumns: [...input.pkColumns] } : {},
|
|
5456
|
-
...input.use ? { use: [...input.use] } : {}
|
|
5882
|
+
...input.use ? { use: [...input.use] } : {},
|
|
5883
|
+
...input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}
|
|
5457
5884
|
}, id);
|
|
5458
5885
|
});
|
|
5459
5886
|
} catch (error) {
|
|
@@ -5462,7 +5889,7 @@ async function attachSyncClient(options) {
|
|
|
5462
5889
|
}
|
|
5463
5890
|
const initialRows = materializer.seed(initial.rows);
|
|
5464
5891
|
let hydrated;
|
|
5465
|
-
if (initial.
|
|
5892
|
+
if (initial.hydratingTables && initial.hydratingTables.length > 0) {
|
|
5466
5893
|
hydrated = new Promise((resolve) => {
|
|
5467
5894
|
hydratedPending.set(queryId, resolve);
|
|
5468
5895
|
});
|
|
@@ -5509,13 +5936,7 @@ async function attachSyncClient(options) {
|
|
|
5509
5936
|
await ready;
|
|
5510
5937
|
},
|
|
5511
5938
|
stop: async () => {
|
|
5512
|
-
|
|
5513
|
-
for (const queryId of diffHandlers.keys())
|
|
5514
|
-
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
5515
|
-
diffHandlers.clear();
|
|
5516
|
-
postBridgeMessage(port, codec, "detach", null);
|
|
5517
|
-
port.removeEventListener("message", listener);
|
|
5518
|
-
port.close?.();
|
|
5939
|
+
detachFromWorker();
|
|
5519
5940
|
},
|
|
5520
5941
|
destroy: notSupported("client.destroy"),
|
|
5521
5942
|
dropReadCache: notSupported("client.dropReadCache"),
|
|
@@ -5544,6 +5965,7 @@ async function attachSyncClient(options) {
|
|
|
5544
5965
|
desync: (key) => rpc("desync", [key]),
|
|
5545
5966
|
discardEphemeral: (key) => rpc("discardEphemeral", [key]),
|
|
5546
5967
|
prepareQuery: async () => ({ lazyTables: [] }),
|
|
5968
|
+
hydratingTablesFor: () => [],
|
|
5547
5969
|
transaction: async ({ mode }, run) => {
|
|
5548
5970
|
const collected = [];
|
|
5549
5971
|
const txTables = Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
|
|
@@ -5575,6 +5997,8 @@ async function attachSyncClient(options) {
|
|
|
5575
5997
|
return rpc("transaction", [{ mode, items: collected }]);
|
|
5576
5998
|
},
|
|
5577
5999
|
groupReady: async (table) => {
|
|
6000
|
+
if (detached)
|
|
6001
|
+
throw detachError();
|
|
5578
6002
|
const groupKey = groupKeyForTable(table);
|
|
5579
6003
|
if (groupKey == null || readyGroups.has(groupKey))
|
|
5580
6004
|
return;
|
|
@@ -5586,6 +6010,7 @@ async function attachSyncClient(options) {
|
|
|
5586
6010
|
},
|
|
5587
6011
|
subscribeLiveRows,
|
|
5588
6012
|
bootReport: () => rpc("bootReport", []),
|
|
6013
|
+
liveQueryDiagnostics: () => rpc("liveQueryDiagnostics", []),
|
|
5589
6014
|
exportStore: async (exportOptions) => {
|
|
5590
6015
|
const wire = await rpc("exportStore", [exportOptions]);
|
|
5591
6016
|
return {
|
|
@@ -5717,6 +6142,7 @@ function createWorkerTokenCache(options) {
|
|
|
5717
6142
|
|
|
5718
6143
|
// packages/client/src/worker/define-sync-worker.ts
|
|
5719
6144
|
function defineSyncWorker(options) {
|
|
6145
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
5720
6146
|
const codec = options.codec ?? identityCodec;
|
|
5721
6147
|
const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30000;
|
|
5722
6148
|
const convergenceIntervalMs = options.convergenceIntervalMs ?? 15000;
|
|
@@ -5724,6 +6150,24 @@ function defineSyncWorker(options) {
|
|
|
5724
6150
|
const workerTestMarker = readTestStoreMarker(options);
|
|
5725
6151
|
const ports = new Set;
|
|
5726
6152
|
const liveSubs = new Map;
|
|
6153
|
+
let liveManager = null;
|
|
6154
|
+
const ensureLiveManager = (active) => liveManager ??= createLiveQueryManager({
|
|
6155
|
+
live: active.pglite.live,
|
|
6156
|
+
...options.liveQueries ? { policy: options.liveQueries } : {}
|
|
6157
|
+
});
|
|
6158
|
+
const pendingSubscribes = new Map;
|
|
6159
|
+
let closing = false;
|
|
6160
|
+
const inFlightSubscribes = new Set;
|
|
6161
|
+
const portScopes = new WeakMap;
|
|
6162
|
+
let nextScopeId = 0;
|
|
6163
|
+
const scopeForPort = (port) => {
|
|
6164
|
+
let scope = portScopes.get(port);
|
|
6165
|
+
if (scope === undefined) {
|
|
6166
|
+
scope = `port-${nextScopeId++}`;
|
|
6167
|
+
portScopes.set(port, scope);
|
|
6168
|
+
}
|
|
6169
|
+
return scope;
|
|
6170
|
+
};
|
|
5727
6171
|
let provisioned = null;
|
|
5728
6172
|
let convergenceSuppressed = false;
|
|
5729
6173
|
let fireConvergence = null;
|
|
@@ -5901,6 +6345,8 @@ function defineSyncWorker(options) {
|
|
|
5901
6345
|
return active.rawExec(args[0], args[1]);
|
|
5902
6346
|
case "bootReport":
|
|
5903
6347
|
return active.bootReport();
|
|
6348
|
+
case "liveQueryDiagnostics":
|
|
6349
|
+
return liveManager?.snapshot() ?? [];
|
|
5904
6350
|
case "exportStore": {
|
|
5905
6351
|
const { file, report } = await active.exportStore(args[0]);
|
|
5906
6352
|
const buffer = await file.arrayBuffer();
|
|
@@ -5922,36 +6368,62 @@ function defineSyncWorker(options) {
|
|
|
5922
6368
|
}
|
|
5923
6369
|
}
|
|
5924
6370
|
};
|
|
5925
|
-
const
|
|
6371
|
+
const subKeyFor = (port, queryId) => `${scopeForPort(port)}:${queryId}`;
|
|
6372
|
+
const handleSubscribe = (port, id, payload) => {
|
|
6373
|
+
const pending = { port, cancelled: false };
|
|
6374
|
+
const subKey = subKeyFor(port, payload.queryId);
|
|
6375
|
+
pendingSubscribes.set(subKey, pending);
|
|
6376
|
+
let task;
|
|
6377
|
+
task = (async () => {
|
|
6378
|
+
try {
|
|
6379
|
+
await handleSubscribeInner(port, id, payload, pending, subKey);
|
|
6380
|
+
} finally {
|
|
6381
|
+
pendingSubscribes.delete(subKey);
|
|
6382
|
+
inFlightSubscribes.delete(task);
|
|
6383
|
+
}
|
|
6384
|
+
})();
|
|
6385
|
+
inFlightSubscribes.add(task);
|
|
6386
|
+
return task;
|
|
6387
|
+
};
|
|
6388
|
+
const handleSubscribeInner = async (port, id, payload, pending, subKey) => {
|
|
5926
6389
|
const active = client ?? await bootPromise;
|
|
5927
6390
|
if (!active)
|
|
5928
6391
|
throw new Error("subscribe before attach");
|
|
5929
|
-
const { queryId, sql: sql5, params, pkColumns, use, fields } = payload;
|
|
6392
|
+
const { queryId, sql: sql5, params, pkColumns, use, fields, keepAliveMs } = payload;
|
|
5930
6393
|
const prepared = await active.prepareQuery({ sql: sql5, ...use ? { use } : {} });
|
|
5931
|
-
const
|
|
6394
|
+
const hydratingTables = active.hydratingTablesFor({ sql: sql5, ...use ? { use } : {} });
|
|
5932
6395
|
const materialSql = wrapLiveQueryForMaterialization(sql5, fields);
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
|
|
5936
|
-
|
|
5937
|
-
|
|
5938
|
-
|
|
5939
|
-
}
|
|
5940
|
-
const
|
|
5941
|
-
|
|
5942
|
-
|
|
5943
|
-
|
|
5944
|
-
|
|
5945
|
-
|
|
5946
|
-
|
|
5947
|
-
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
6396
|
+
if (closing || pending.cancelled || !ports.has(port)) {
|
|
6397
|
+
postBridgeMessage(port, codec, "rpc-result", {
|
|
6398
|
+
ok: false,
|
|
6399
|
+
error: { message: "[pgxsinkit] subscribe cancelled \u2014 the worker is closing or the port detached" }
|
|
6400
|
+
}, id);
|
|
6401
|
+
return;
|
|
6402
|
+
}
|
|
6403
|
+
const subscription = await ensureLiveManager(active).subscribe({ materialSql, params, ...pkColumns ? { pkColumns } : {} }, {
|
|
6404
|
+
deliverInitial: (rows) => {
|
|
6405
|
+
postBridgeMessage(port, codec, "live-initial", {
|
|
6406
|
+
queryId,
|
|
6407
|
+
rows,
|
|
6408
|
+
...prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {},
|
|
6409
|
+
...hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}
|
|
6410
|
+
}, id);
|
|
6411
|
+
},
|
|
6412
|
+
deliverDiff: (diff) => {
|
|
6413
|
+
postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
|
|
6414
|
+
}
|
|
6415
|
+
}, { ...keepAliveMs != null ? { keepAliveMs } : {}, scope: scopeForPort(port) });
|
|
6416
|
+
if (closing || pending.cancelled || !ports.has(port)) {
|
|
6417
|
+
subscription.unsubscribe();
|
|
6418
|
+
return;
|
|
6419
|
+
}
|
|
6420
|
+
liveSubs.set(subKey, { port, subscription });
|
|
6421
|
+
if (hydratingTables.length > 0) {
|
|
6422
|
+
Promise.all(hydratingTables.map((key) => active.groupReady(key))).then(async () => {
|
|
6423
|
+
if (!liveSubs.has(subKey))
|
|
5952
6424
|
return;
|
|
5953
|
-
await
|
|
5954
|
-
if (!liveSubs.has(
|
|
6425
|
+
await subscription.refresh();
|
|
6426
|
+
if (!liveSubs.has(subKey))
|
|
5955
6427
|
return;
|
|
5956
6428
|
postBridgeMessage(port, codec, "live-hydrated", { queryId });
|
|
5957
6429
|
}).catch(() => {
|
|
@@ -6088,10 +6560,15 @@ function defineSyncWorker(options) {
|
|
|
6088
6560
|
}
|
|
6089
6561
|
case "unsubscribe": {
|
|
6090
6562
|
const { queryId } = payload;
|
|
6091
|
-
const
|
|
6563
|
+
const subKey = subKeyFor(port, queryId);
|
|
6564
|
+
const sub = liveSubs.get(subKey);
|
|
6092
6565
|
if (sub) {
|
|
6093
|
-
sub.unsubscribe();
|
|
6094
|
-
liveSubs.delete(
|
|
6566
|
+
sub.subscription.unsubscribe();
|
|
6567
|
+
liveSubs.delete(subKey);
|
|
6568
|
+
} else {
|
|
6569
|
+
const inFlight = pendingSubscribes.get(subKey);
|
|
6570
|
+
if (inFlight)
|
|
6571
|
+
inFlight.cancelled = true;
|
|
6095
6572
|
}
|
|
6096
6573
|
break;
|
|
6097
6574
|
}
|
|
@@ -6106,12 +6583,16 @@ function defineSyncWorker(options) {
|
|
|
6106
6583
|
};
|
|
6107
6584
|
const detachPort = (port) => {
|
|
6108
6585
|
ports.delete(port);
|
|
6109
|
-
for (const [
|
|
6586
|
+
for (const [subKey, sub] of liveSubs) {
|
|
6110
6587
|
if (sub.port === port) {
|
|
6111
|
-
sub.unsubscribe();
|
|
6112
|
-
liveSubs.delete(
|
|
6588
|
+
sub.subscription.unsubscribe();
|
|
6589
|
+
liveSubs.delete(subKey);
|
|
6113
6590
|
}
|
|
6114
6591
|
}
|
|
6592
|
+
for (const pending of pendingSubscribes.values()) {
|
|
6593
|
+
if (pending.port === port)
|
|
6594
|
+
pending.cancelled = true;
|
|
6595
|
+
}
|
|
6115
6596
|
};
|
|
6116
6597
|
const connect = (port) => {
|
|
6117
6598
|
ports.add(port);
|
|
@@ -6132,9 +6613,12 @@ function defineSyncWorker(options) {
|
|
|
6132
6613
|
connect,
|
|
6133
6614
|
whenBooted,
|
|
6134
6615
|
close: async () => {
|
|
6135
|
-
|
|
6136
|
-
|
|
6616
|
+
closing = true;
|
|
6617
|
+
for (const pending of pendingSubscribes.values())
|
|
6618
|
+
pending.cancelled = true;
|
|
6619
|
+
await Promise.allSettled([...inFlightSubscribes]);
|
|
6137
6620
|
liveSubs.clear();
|
|
6621
|
+
await liveManager?.dispose();
|
|
6138
6622
|
ports.clear();
|
|
6139
6623
|
setSyncDebugSink(undefined);
|
|
6140
6624
|
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
@@ -6192,6 +6676,7 @@ function replAdapter(client) {
|
|
|
6192
6676
|
};
|
|
6193
6677
|
}
|
|
6194
6678
|
async function createSyncClient(options) {
|
|
6679
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
6195
6680
|
const status = {
|
|
6196
6681
|
phase: "booting",
|
|
6197
6682
|
isRunning: false
|
|
@@ -6375,10 +6860,12 @@ async function createSyncClient(options) {
|
|
|
6375
6860
|
}
|
|
6376
6861
|
}
|
|
6377
6862
|
const writePathHeaders = options.requestHeaders || options.writeRequestHeaders ? { ...options.requestHeaders ?? {}, ...options.writeRequestHeaders ?? {} } : undefined;
|
|
6863
|
+
let activateOrdinaryWriteTables = null;
|
|
6378
6864
|
const mutationRuntime = createMutationRuntime({
|
|
6379
6865
|
db: pglite,
|
|
6380
6866
|
registry: options.registry,
|
|
6381
6867
|
writeUrl: options.writeUrl,
|
|
6868
|
+
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
6382
6869
|
...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
|
|
6383
6870
|
...writePathHeaders ? { requestHeaders: writePathHeaders } : {},
|
|
6384
6871
|
...options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {},
|
|
@@ -6455,6 +6942,50 @@ async function createSyncClient(options) {
|
|
|
6455
6942
|
requestConvergence();
|
|
6456
6943
|
}
|
|
6457
6944
|
};
|
|
6945
|
+
let groupClaimsInfoCache = null;
|
|
6946
|
+
const groupClaimsInfoFor = (activeSync) => {
|
|
6947
|
+
if (groupClaimsInfoCache != null)
|
|
6948
|
+
return groupClaimsInfoCache;
|
|
6949
|
+
const map = new Map;
|
|
6950
|
+
for (const key of Object.keys(options.registry)) {
|
|
6951
|
+
const groupKey = activeSync.groupKeyForTable(key);
|
|
6952
|
+
if (groupKey == null)
|
|
6953
|
+
continue;
|
|
6954
|
+
const entry = options.registry[key];
|
|
6955
|
+
const info = map.get(groupKey) ?? { claimsDependent: false, memberKeys: [] };
|
|
6956
|
+
info.memberKeys.push(key);
|
|
6957
|
+
if (isClaimsDependentRowFilter(entry.shape?.rowFilter))
|
|
6958
|
+
info.claimsDependent = true;
|
|
6959
|
+
map.set(groupKey, info);
|
|
6960
|
+
}
|
|
6961
|
+
groupClaimsInfoCache = map;
|
|
6962
|
+
return map;
|
|
6963
|
+
};
|
|
6964
|
+
const anonymousActivationWarned = new Set;
|
|
6965
|
+
const warnIfAnonymousClaimsDependentActivation = (activeSync, groupKey) => {
|
|
6966
|
+
if (anonymousActivationWarned.has(groupKey))
|
|
6967
|
+
return;
|
|
6968
|
+
const info = groupClaimsInfoFor(activeSync).get(groupKey);
|
|
6969
|
+
if (info == null || !info.claimsDependent)
|
|
6970
|
+
return;
|
|
6971
|
+
(async () => {
|
|
6972
|
+
try {
|
|
6973
|
+
const token = options.getAuthToken ? await options.getAuthToken() : undefined;
|
|
6974
|
+
if (token != null && token !== "")
|
|
6975
|
+
return;
|
|
6976
|
+
if (anonymousActivationWarned.has(groupKey))
|
|
6977
|
+
return;
|
|
6978
|
+
anonymousActivationWarned.add(groupKey);
|
|
6979
|
+
console.warn(`pgxsinkit: activating the lazy group [${info.memberKeys.join(", ")}] with no auth token \u2014 its ` + `row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first ` + `query on auth (e.g. the React hooks' \`ready\` option) so the group activates with real claims.`);
|
|
6980
|
+
syncDebug("anonymous activation of a claims-dependent lazy group", {
|
|
6981
|
+
groupKey,
|
|
6982
|
+
tables: info.memberKeys
|
|
6983
|
+
});
|
|
6984
|
+
} catch (error) {
|
|
6985
|
+
syncDebug("anonymous-activation auth probe failed", { groupKey, error });
|
|
6986
|
+
}
|
|
6987
|
+
})();
|
|
6988
|
+
};
|
|
6458
6989
|
const ensureSynced = async (keys) => {
|
|
6459
6990
|
const activeSync = sync;
|
|
6460
6991
|
if (activeSync == null || keys.length === 0)
|
|
@@ -6462,11 +6993,23 @@ async function createSyncClient(options) {
|
|
|
6462
6993
|
const groupKeys = new Set;
|
|
6463
6994
|
for (const key of keys) {
|
|
6464
6995
|
const groupKey = activeSync.groupKeyForTable(key);
|
|
6465
|
-
if (groupKey
|
|
6466
|
-
|
|
6996
|
+
if (groupKey == null)
|
|
6997
|
+
continue;
|
|
6998
|
+
if (!activeSync.isTableStarted(key)) {
|
|
6999
|
+
warnIfAnonymousClaimsDependentActivation(activeSync, groupKey);
|
|
7000
|
+
}
|
|
7001
|
+
groupKeys.add(groupKey);
|
|
6467
7002
|
}
|
|
6468
7003
|
await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
|
|
6469
7004
|
};
|
|
7005
|
+
activateOrdinaryWriteTables = (tables) => {
|
|
7006
|
+
const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table));
|
|
7007
|
+
if (lazyTables.length === 0)
|
|
7008
|
+
return;
|
|
7009
|
+
ensureSynced(lazyTables).catch((error) => {
|
|
7010
|
+
syncDebug("write-triggered lazy activation failed", { tables: lazyTables, error });
|
|
7011
|
+
});
|
|
7012
|
+
};
|
|
6470
7013
|
const groupReadyForTable = async (table) => {
|
|
6471
7014
|
const activeSync = sync;
|
|
6472
7015
|
if (activeSync == null)
|
|
@@ -6476,6 +7019,23 @@ async function createSyncClient(options) {
|
|
|
6476
7019
|
return;
|
|
6477
7020
|
await activeSync.groupReady(groupKey);
|
|
6478
7021
|
};
|
|
7022
|
+
const isGroupReadyForTable = (table) => {
|
|
7023
|
+
const activeSync = sync;
|
|
7024
|
+
if (activeSync == null)
|
|
7025
|
+
return true;
|
|
7026
|
+
const groupKey = activeSync.groupKeyForTable(table);
|
|
7027
|
+
if (groupKey == null)
|
|
7028
|
+
return true;
|
|
7029
|
+
return activeSync.isGroupReady(groupKey);
|
|
7030
|
+
};
|
|
7031
|
+
const hydratingTablesFor = (query) => {
|
|
7032
|
+
if (sync == null)
|
|
7033
|
+
return [];
|
|
7034
|
+
const referenced = new Set(query.use ?? []);
|
|
7035
|
+
for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex))
|
|
7036
|
+
referenced.add(key);
|
|
7037
|
+
return [...referenced].filter((table) => !isGroupReadyForTable(table));
|
|
7038
|
+
};
|
|
6479
7039
|
const isSynced = (key) => {
|
|
6480
7040
|
const activeSync = sync;
|
|
6481
7041
|
if (activeSync == null)
|
|
@@ -6588,6 +7148,10 @@ async function createSyncClient(options) {
|
|
|
6588
7148
|
await prepareQuery({ sql: builder.toSQL().sql, ...use ? { use } : {} });
|
|
6589
7149
|
return builder;
|
|
6590
7150
|
};
|
|
7151
|
+
const liveManager = createLiveQueryManager({
|
|
7152
|
+
live: pglite.live,
|
|
7153
|
+
...options.liveQueries ? { policy: options.liveQueries } : {}
|
|
7154
|
+
});
|
|
6591
7155
|
const client = {
|
|
6592
7156
|
drizzle: drizzleDb,
|
|
6593
7157
|
pglite,
|
|
@@ -6613,6 +7177,7 @@ async function createSyncClient(options) {
|
|
|
6613
7177
|
status.isRunning = false;
|
|
6614
7178
|
options.onStatusChange?.(status);
|
|
6615
7179
|
await engine.close();
|
|
7180
|
+
await liveManager.dispose();
|
|
6616
7181
|
await pglite.close();
|
|
6617
7182
|
},
|
|
6618
7183
|
destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
|
|
@@ -6629,6 +7194,7 @@ async function createSyncClient(options) {
|
|
|
6629
7194
|
options.onStatusChange?.(status);
|
|
6630
7195
|
await pglite.exec(buildWipeLocalStoreSql(options.registry));
|
|
6631
7196
|
await engine.close();
|
|
7197
|
+
await liveManager.dispose();
|
|
6632
7198
|
await pglite.close();
|
|
6633
7199
|
}),
|
|
6634
7200
|
dropReadCache: () => lifecycleSlot.run("dropReadCache", async () => {
|
|
@@ -6666,35 +7232,43 @@ async function createSyncClient(options) {
|
|
|
6666
7232
|
prepareQuery,
|
|
6667
7233
|
transaction,
|
|
6668
7234
|
groupReady: groupReadyForTable,
|
|
6669
|
-
|
|
7235
|
+
hydratingTablesFor,
|
|
7236
|
+
subscribeLiveRows: async ({ sql: sql5, params, fields, use, keepAliveMs }, onRows) => {
|
|
6670
7237
|
const materialSql = wrapLiveQueryForMaterialization(sql5, fields);
|
|
6671
|
-
const
|
|
6672
|
-
const
|
|
6673
|
-
|
|
6674
|
-
|
|
6675
|
-
|
|
7238
|
+
const materializer = new LiveRowsMaterializer(undefined);
|
|
7239
|
+
const subscription = await liveManager.subscribe({ materialSql, params }, {
|
|
7240
|
+
deliverInitial: (rows) => {
|
|
7241
|
+
materializer.seed(rows);
|
|
7242
|
+
},
|
|
7243
|
+
deliverDiff: (diff) => {
|
|
7244
|
+
onRows(materializer.apply(diff));
|
|
7245
|
+
}
|
|
7246
|
+
}, keepAliveMs != null ? { keepAliveMs } : undefined);
|
|
7247
|
+
const initialRows = materializer.current();
|
|
6676
7248
|
let unsubscribed = false;
|
|
6677
7249
|
const lazySet = new Set(use ?? []);
|
|
6678
7250
|
for (const key of findReferencedLazyKeysInSql(sql5, lazyGuardIndex))
|
|
6679
7251
|
lazySet.add(key);
|
|
6680
7252
|
const lazyTables = [...lazySet];
|
|
6681
|
-
const
|
|
7253
|
+
const hydratingTables = hydratingTablesFor({ sql: sql5, ...use ? { use } : {} });
|
|
7254
|
+
const hydrated = hydratingTables.length > 0 ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table))).then(async () => {
|
|
6682
7255
|
if (!unsubscribed)
|
|
6683
|
-
await
|
|
7256
|
+
await subscription.refresh();
|
|
6684
7257
|
}).catch(() => {
|
|
6685
7258
|
return;
|
|
6686
7259
|
}) : undefined;
|
|
6687
7260
|
return {
|
|
6688
|
-
initialRows
|
|
7261
|
+
initialRows,
|
|
6689
7262
|
unsubscribe: () => {
|
|
6690
7263
|
unsubscribed = true;
|
|
6691
|
-
|
|
7264
|
+
subscription.unsubscribe();
|
|
6692
7265
|
},
|
|
6693
7266
|
...lazyTables.length > 0 ? { lazyTables } : {},
|
|
6694
7267
|
...hydrated ? { hydrated } : {}
|
|
6695
7268
|
};
|
|
6696
7269
|
},
|
|
6697
7270
|
bootReport: async () => finalizedBootReport,
|
|
7271
|
+
liveQueryDiagnostics: async () => liveManager.snapshot(),
|
|
6698
7272
|
exportStore: async (exportOptions) => {
|
|
6699
7273
|
await ready;
|
|
6700
7274
|
return lifecycleSlot.run("exportStore", () => performStoreExport({
|
|
@@ -6813,6 +7387,7 @@ export {
|
|
|
6813
7387
|
getLocalMetaTable,
|
|
6814
7388
|
getJournalTable,
|
|
6815
7389
|
generateLocalSchemaSql,
|
|
7390
|
+
findReferencedSyncedKeysInSql,
|
|
6816
7391
|
findReferencedLazyKeysInSql,
|
|
6817
7392
|
encodeEnvelope,
|
|
6818
7393
|
deriveStoreId,
|
|
@@ -6841,4 +7416,4 @@ export {
|
|
|
6841
7416
|
BRIDGE_CHANNEL
|
|
6842
7417
|
};
|
|
6843
7418
|
|
|
6844
|
-
//# debugId=
|
|
7419
|
+
//# debugId=C652F2B68A86222B64756E2164756E21
|