@pgxsinkit/client 0.1.48 → 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 +28 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +516 -50
- package/dist/index.js.map +9 -7
- 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 +9 -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 +29 -1
- package/src/index.ts +93 -16
- package/src/worker/attach-sync-client.ts +79 -10
- package/src/worker/define-sync-worker.ts +202 -49
- package/src/worker/live-query-fingerprint.ts +128 -0
- package/src/worker/live-query-manager.ts +591 -0
- package/src/worker/protocol.ts +11 -0
package/dist/index.js
CHANGED
|
@@ -5140,6 +5140,7 @@ async function createSyncEngine(pg, options) {
|
|
|
5140
5140
|
close
|
|
5141
5141
|
};
|
|
5142
5142
|
}
|
|
5143
|
+
|
|
5143
5144
|
// packages/client/src/worker/live-diff.ts
|
|
5144
5145
|
var KEY_SEP = String.fromCharCode(0);
|
|
5145
5146
|
function rowKey(row, pkColumns) {
|
|
@@ -5226,6 +5227,362 @@ class LiveRowsMaterializer {
|
|
|
5226
5227
|
}
|
|
5227
5228
|
}
|
|
5228
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
|
+
}
|
|
5229
5586
|
// packages/client/src/worker/protocol.ts
|
|
5230
5587
|
var BRIDGE_CHANNEL = "pgxsinkit-bridge";
|
|
5231
5588
|
var BRIDGE_PROTOCOL_VERSION = 1;
|
|
@@ -5267,6 +5624,8 @@ async function attachSyncClient(options) {
|
|
|
5267
5624
|
const initialPending = new Map;
|
|
5268
5625
|
const diffHandlers = new Map;
|
|
5269
5626
|
const hydratedPending = new Map;
|
|
5627
|
+
let detached = false;
|
|
5628
|
+
const detachError = () => new Error("[pgxsinkit] client detached \u2014 the tab released its worker attachment");
|
|
5270
5629
|
const status = { phase: "booting", isRunning: false };
|
|
5271
5630
|
let resolveReady;
|
|
5272
5631
|
const ready = new Promise((resolve) => {
|
|
@@ -5423,6 +5782,8 @@ async function attachSyncClient(options) {
|
|
|
5423
5782
|
port.addEventListener("message", listener);
|
|
5424
5783
|
port.start?.();
|
|
5425
5784
|
const rpc = (op, args) => {
|
|
5785
|
+
if (detached)
|
|
5786
|
+
return Promise.reject(detachError());
|
|
5426
5787
|
const id = newId("rpc");
|
|
5427
5788
|
return new Promise((resolve, reject) => {
|
|
5428
5789
|
rpcPending.set(id, { resolve, reject });
|
|
@@ -5435,6 +5796,41 @@ async function attachSyncClient(options) {
|
|
|
5435
5796
|
attachAckResolve = resolve;
|
|
5436
5797
|
attachAckReject = reject;
|
|
5437
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);
|
|
5438
5834
|
const initialToken = options.getToken ? await options.getToken() : null;
|
|
5439
5835
|
const memoryOverride = readTestStoreMarker(options) === "memory";
|
|
5440
5836
|
const restoreWire = options.restoreFrom ? {
|
|
@@ -5460,11 +5856,13 @@ async function attachSyncClient(options) {
|
|
|
5460
5856
|
try {
|
|
5461
5857
|
await attachAck;
|
|
5462
5858
|
} catch (error) {
|
|
5463
|
-
|
|
5859
|
+
detachFromWorker();
|
|
5464
5860
|
throw error;
|
|
5465
5861
|
}
|
|
5466
5862
|
status.isRunning = true;
|
|
5467
5863
|
const subscribeLiveRows = async (input, onRows) => {
|
|
5864
|
+
if (detached)
|
|
5865
|
+
throw detachError();
|
|
5468
5866
|
const queryId = newId("live");
|
|
5469
5867
|
const id = newId("sub");
|
|
5470
5868
|
const materializer = new LiveRowsMaterializer(input.pkColumns);
|
|
@@ -5481,7 +5879,8 @@ async function attachSyncClient(options) {
|
|
|
5481
5879
|
params: [...input.params],
|
|
5482
5880
|
...input.fields ? { fields: [...input.fields] } : {},
|
|
5483
5881
|
...input.pkColumns ? { pkColumns: [...input.pkColumns] } : {},
|
|
5484
|
-
...input.use ? { use: [...input.use] } : {}
|
|
5882
|
+
...input.use ? { use: [...input.use] } : {},
|
|
5883
|
+
...input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}
|
|
5485
5884
|
}, id);
|
|
5486
5885
|
});
|
|
5487
5886
|
} catch (error) {
|
|
@@ -5537,13 +5936,7 @@ async function attachSyncClient(options) {
|
|
|
5537
5936
|
await ready;
|
|
5538
5937
|
},
|
|
5539
5938
|
stop: async () => {
|
|
5540
|
-
|
|
5541
|
-
for (const queryId of diffHandlers.keys())
|
|
5542
|
-
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
5543
|
-
diffHandlers.clear();
|
|
5544
|
-
postBridgeMessage(port, codec, "detach", null);
|
|
5545
|
-
port.removeEventListener("message", listener);
|
|
5546
|
-
port.close?.();
|
|
5939
|
+
detachFromWorker();
|
|
5547
5940
|
},
|
|
5548
5941
|
destroy: notSupported("client.destroy"),
|
|
5549
5942
|
dropReadCache: notSupported("client.dropReadCache"),
|
|
@@ -5604,6 +5997,8 @@ async function attachSyncClient(options) {
|
|
|
5604
5997
|
return rpc("transaction", [{ mode, items: collected }]);
|
|
5605
5998
|
},
|
|
5606
5999
|
groupReady: async (table) => {
|
|
6000
|
+
if (detached)
|
|
6001
|
+
throw detachError();
|
|
5607
6002
|
const groupKey = groupKeyForTable(table);
|
|
5608
6003
|
if (groupKey == null || readyGroups.has(groupKey))
|
|
5609
6004
|
return;
|
|
@@ -5615,6 +6010,7 @@ async function attachSyncClient(options) {
|
|
|
5615
6010
|
},
|
|
5616
6011
|
subscribeLiveRows,
|
|
5617
6012
|
bootReport: () => rpc("bootReport", []),
|
|
6013
|
+
liveQueryDiagnostics: () => rpc("liveQueryDiagnostics", []),
|
|
5618
6014
|
exportStore: async (exportOptions) => {
|
|
5619
6015
|
const wire = await rpc("exportStore", [exportOptions]);
|
|
5620
6016
|
return {
|
|
@@ -5746,6 +6142,7 @@ function createWorkerTokenCache(options) {
|
|
|
5746
6142
|
|
|
5747
6143
|
// packages/client/src/worker/define-sync-worker.ts
|
|
5748
6144
|
function defineSyncWorker(options) {
|
|
6145
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
5749
6146
|
const codec = options.codec ?? identityCodec;
|
|
5750
6147
|
const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30000;
|
|
5751
6148
|
const convergenceIntervalMs = options.convergenceIntervalMs ?? 15000;
|
|
@@ -5753,6 +6150,24 @@ function defineSyncWorker(options) {
|
|
|
5753
6150
|
const workerTestMarker = readTestStoreMarker(options);
|
|
5754
6151
|
const ports = new Set;
|
|
5755
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
|
+
};
|
|
5756
6171
|
let provisioned = null;
|
|
5757
6172
|
let convergenceSuppressed = false;
|
|
5758
6173
|
let fireConvergence = null;
|
|
@@ -5930,6 +6345,8 @@ function defineSyncWorker(options) {
|
|
|
5930
6345
|
return active.rawExec(args[0], args[1]);
|
|
5931
6346
|
case "bootReport":
|
|
5932
6347
|
return active.bootReport();
|
|
6348
|
+
case "liveQueryDiagnostics":
|
|
6349
|
+
return liveManager?.snapshot() ?? [];
|
|
5933
6350
|
case "exportStore": {
|
|
5934
6351
|
const { file, report } = await active.exportStore(args[0]);
|
|
5935
6352
|
const buffer = await file.arrayBuffer();
|
|
@@ -5951,38 +6368,62 @@ function defineSyncWorker(options) {
|
|
|
5951
6368
|
}
|
|
5952
6369
|
}
|
|
5953
6370
|
};
|
|
5954
|
-
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) => {
|
|
5955
6389
|
const active = client ?? await bootPromise;
|
|
5956
6390
|
if (!active)
|
|
5957
6391
|
throw new Error("subscribe before attach");
|
|
5958
|
-
const { queryId, sql: sql5, params, pkColumns, use, fields } = payload;
|
|
6392
|
+
const { queryId, sql: sql5, params, pkColumns, use, fields, keepAliveMs } = payload;
|
|
5959
6393
|
const prepared = await active.prepareQuery({ sql: sql5, ...use ? { use } : {} });
|
|
5960
6394
|
const hydratingTables = active.hydratingTablesFor({ sql: sql5, ...use ? { use } : {} });
|
|
5961
|
-
const live = active.pglite.live;
|
|
5962
6395
|
const materialSql = wrapLiveQueryForMaterialization(sql5, fields);
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
},
|
|
5971
|
-
|
|
5972
|
-
|
|
5973
|
-
|
|
5974
|
-
|
|
5975
|
-
|
|
5976
|
-
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
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 });
|
|
5980
6421
|
if (hydratingTables.length > 0) {
|
|
5981
6422
|
Promise.all(hydratingTables.map((key) => active.groupReady(key))).then(async () => {
|
|
5982
|
-
if (!liveSubs.has(
|
|
6423
|
+
if (!liveSubs.has(subKey))
|
|
5983
6424
|
return;
|
|
5984
|
-
await
|
|
5985
|
-
if (!liveSubs.has(
|
|
6425
|
+
await subscription.refresh();
|
|
6426
|
+
if (!liveSubs.has(subKey))
|
|
5986
6427
|
return;
|
|
5987
6428
|
postBridgeMessage(port, codec, "live-hydrated", { queryId });
|
|
5988
6429
|
}).catch(() => {
|
|
@@ -6119,10 +6560,15 @@ function defineSyncWorker(options) {
|
|
|
6119
6560
|
}
|
|
6120
6561
|
case "unsubscribe": {
|
|
6121
6562
|
const { queryId } = payload;
|
|
6122
|
-
const
|
|
6563
|
+
const subKey = subKeyFor(port, queryId);
|
|
6564
|
+
const sub = liveSubs.get(subKey);
|
|
6123
6565
|
if (sub) {
|
|
6124
|
-
sub.unsubscribe();
|
|
6125
|
-
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;
|
|
6126
6572
|
}
|
|
6127
6573
|
break;
|
|
6128
6574
|
}
|
|
@@ -6137,12 +6583,16 @@ function defineSyncWorker(options) {
|
|
|
6137
6583
|
};
|
|
6138
6584
|
const detachPort = (port) => {
|
|
6139
6585
|
ports.delete(port);
|
|
6140
|
-
for (const [
|
|
6586
|
+
for (const [subKey, sub] of liveSubs) {
|
|
6141
6587
|
if (sub.port === port) {
|
|
6142
|
-
sub.unsubscribe();
|
|
6143
|
-
liveSubs.delete(
|
|
6588
|
+
sub.subscription.unsubscribe();
|
|
6589
|
+
liveSubs.delete(subKey);
|
|
6144
6590
|
}
|
|
6145
6591
|
}
|
|
6592
|
+
for (const pending of pendingSubscribes.values()) {
|
|
6593
|
+
if (pending.port === port)
|
|
6594
|
+
pending.cancelled = true;
|
|
6595
|
+
}
|
|
6146
6596
|
};
|
|
6147
6597
|
const connect = (port) => {
|
|
6148
6598
|
ports.add(port);
|
|
@@ -6163,9 +6613,12 @@ function defineSyncWorker(options) {
|
|
|
6163
6613
|
connect,
|
|
6164
6614
|
whenBooted,
|
|
6165
6615
|
close: async () => {
|
|
6166
|
-
|
|
6167
|
-
|
|
6616
|
+
closing = true;
|
|
6617
|
+
for (const pending of pendingSubscribes.values())
|
|
6618
|
+
pending.cancelled = true;
|
|
6619
|
+
await Promise.allSettled([...inFlightSubscribes]);
|
|
6168
6620
|
liveSubs.clear();
|
|
6621
|
+
await liveManager?.dispose();
|
|
6169
6622
|
ports.clear();
|
|
6170
6623
|
setSyncDebugSink(undefined);
|
|
6171
6624
|
const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
|
|
@@ -6223,6 +6676,7 @@ function replAdapter(client) {
|
|
|
6223
6676
|
};
|
|
6224
6677
|
}
|
|
6225
6678
|
async function createSyncClient(options) {
|
|
6679
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
6226
6680
|
const status = {
|
|
6227
6681
|
phase: "booting",
|
|
6228
6682
|
isRunning: false
|
|
@@ -6694,6 +7148,10 @@ async function createSyncClient(options) {
|
|
|
6694
7148
|
await prepareQuery({ sql: builder.toSQL().sql, ...use ? { use } : {} });
|
|
6695
7149
|
return builder;
|
|
6696
7150
|
};
|
|
7151
|
+
const liveManager = createLiveQueryManager({
|
|
7152
|
+
live: pglite.live,
|
|
7153
|
+
...options.liveQueries ? { policy: options.liveQueries } : {}
|
|
7154
|
+
});
|
|
6697
7155
|
const client = {
|
|
6698
7156
|
drizzle: drizzleDb,
|
|
6699
7157
|
pglite,
|
|
@@ -6719,6 +7177,7 @@ async function createSyncClient(options) {
|
|
|
6719
7177
|
status.isRunning = false;
|
|
6720
7178
|
options.onStatusChange?.(status);
|
|
6721
7179
|
await engine.close();
|
|
7180
|
+
await liveManager.dispose();
|
|
6722
7181
|
await pglite.close();
|
|
6723
7182
|
},
|
|
6724
7183
|
destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
|
|
@@ -6735,6 +7194,7 @@ async function createSyncClient(options) {
|
|
|
6735
7194
|
options.onStatusChange?.(status);
|
|
6736
7195
|
await pglite.exec(buildWipeLocalStoreSql(options.registry));
|
|
6737
7196
|
await engine.close();
|
|
7197
|
+
await liveManager.dispose();
|
|
6738
7198
|
await pglite.close();
|
|
6739
7199
|
}),
|
|
6740
7200
|
dropReadCache: () => lifecycleSlot.run("dropReadCache", async () => {
|
|
@@ -6773,13 +7233,18 @@ async function createSyncClient(options) {
|
|
|
6773
7233
|
transaction,
|
|
6774
7234
|
groupReady: groupReadyForTable,
|
|
6775
7235
|
hydratingTablesFor,
|
|
6776
|
-
subscribeLiveRows: async ({ sql: sql5, params, fields, use }, onRows) => {
|
|
7236
|
+
subscribeLiveRows: async ({ sql: sql5, params, fields, use, keepAliveMs }, onRows) => {
|
|
6777
7237
|
const materialSql = wrapLiveQueryForMaterialization(sql5, fields);
|
|
6778
|
-
const
|
|
6779
|
-
const
|
|
6780
|
-
|
|
6781
|
-
|
|
6782
|
-
|
|
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();
|
|
6783
7248
|
let unsubscribed = false;
|
|
6784
7249
|
const lazySet = new Set(use ?? []);
|
|
6785
7250
|
for (const key of findReferencedLazyKeysInSql(sql5, lazyGuardIndex))
|
|
@@ -6788,21 +7253,22 @@ async function createSyncClient(options) {
|
|
|
6788
7253
|
const hydratingTables = hydratingTablesFor({ sql: sql5, ...use ? { use } : {} });
|
|
6789
7254
|
const hydrated = hydratingTables.length > 0 ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table))).then(async () => {
|
|
6790
7255
|
if (!unsubscribed)
|
|
6791
|
-
await
|
|
7256
|
+
await subscription.refresh();
|
|
6792
7257
|
}).catch(() => {
|
|
6793
7258
|
return;
|
|
6794
7259
|
}) : undefined;
|
|
6795
7260
|
return {
|
|
6796
|
-
initialRows
|
|
7261
|
+
initialRows,
|
|
6797
7262
|
unsubscribe: () => {
|
|
6798
7263
|
unsubscribed = true;
|
|
6799
|
-
|
|
7264
|
+
subscription.unsubscribe();
|
|
6800
7265
|
},
|
|
6801
7266
|
...lazyTables.length > 0 ? { lazyTables } : {},
|
|
6802
7267
|
...hydrated ? { hydrated } : {}
|
|
6803
7268
|
};
|
|
6804
7269
|
},
|
|
6805
7270
|
bootReport: async () => finalizedBootReport,
|
|
7271
|
+
liveQueryDiagnostics: async () => liveManager.snapshot(),
|
|
6806
7272
|
exportStore: async (exportOptions) => {
|
|
6807
7273
|
await ready;
|
|
6808
7274
|
return lifecycleSlot.run("exportStore", () => performStoreExport({
|
|
@@ -6950,4 +7416,4 @@ export {
|
|
|
6950
7416
|
BRIDGE_CHANNEL
|
|
6951
7417
|
};
|
|
6952
7418
|
|
|
6953
|
-
//# debugId=
|
|
7419
|
+
//# debugId=C652F2B68A86222B64756E2164756E21
|