Skip to content

Commit 0d7d5ee

Browse files
wesbillmanCarl
andcommitted
fix(desktop): stop destroyed read state managers
Prevent delayed relay fetches and other post-destroy entry points from mutating or persisting stale manager state. Cover replacement-manager local state against an in-flight initialization resolving after teardown. Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz> Signed-off-by: Wes <[email protected]>
1 parent cb1b0c0 commit 0d7d5ee

2 files changed

Lines changed: 57 additions & 4 deletions

File tree

‎desktop/src/features/channels/readState/readStateManager.test.mjs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,54 @@ test("publish flushes pending local state first", async () => {
268268
}
269269
});
270270

271+
test("destroyed manager cannot persist after an in-flight fetch resolves", async () => {
272+
const storage = makeLocalStorage();
273+
globalThis.window.localStorage = storage;
274+
const { timers, restore } = withFakeTimers();
275+
const pubkey = "6".repeat(64);
276+
let resolveFetch;
277+
const fetchPending = new Promise((resolve) => {
278+
resolveFetch = resolve;
279+
});
280+
const staleManager = new ReadStateManager(pubkey, {
281+
...makeFakeRelay(),
282+
fetchEvents: () => fetchPending,
283+
});
284+
285+
try {
286+
const initialization = staleManager.initialize();
287+
staleManager.seedContextRead("channel-1", 100);
288+
staleManager.destroy();
289+
290+
const replacementManager = new ReadStateManager(pubkey, makeFakeRelay());
291+
replacementManager.seedContextRead("channel-1", 200);
292+
timers.advanceBy(1_000);
293+
const writesAfterReplacement = storage.writes.length;
294+
295+
resolveFetch([]);
296+
await initialization;
297+
timers.runAll();
298+
299+
assert.equal(
300+
storage.writes.length,
301+
writesAfterReplacement,
302+
"the stale manager must not schedule persistence after destruction",
303+
);
304+
const contexts = JSON.parse(
305+
storage.getItem(`buzz.channel-read-state.v2:${pubkey}`),
306+
);
307+
assert.equal(
308+
contexts["channel-1"],
309+
new Date(200_000).toISOString(),
310+
"the stale manager must not overwrite the replacement manager",
311+
);
312+
replacementManager.destroy();
313+
} finally {
314+
staleManager.destroy();
315+
restore();
316+
}
317+
});
318+
271319
test("resolveEffectiveTimestamp returns own value when context has no parent", () => {
272320
const effectiveState = new Map([[channelKey, 200]]);
273321
const result = resolveEffectiveTimestamp({

‎desktop/src/features/channels/readState/readStateManager.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ export class ReadStateManager {
381381
unixTimestamp: number,
382382
options: { publishable: boolean },
383383
): void {
384+
if (this.destroyed) return;
384385
const current = this.effectiveState.get(contextId) ?? 0;
385386
if (unixTimestamp <= current) {
386387
if (!options.publishable || this.publishableContextIds.has(contextId)) {
@@ -486,6 +487,7 @@ export class ReadStateManager {
486487
}
487488

488489
private async mergeEvents(events: RelayEvent[]): Promise<void> {
490+
if (this.destroyed) return;
489491
// Collect all own blobs (keyed by slot d-tag) to union them all.
490492
// NIP-RS: multiple own-slot blobs must be max-merged, not winner-takes-all.
491493
const ownBlobsBySlot = new Map<
@@ -495,6 +497,7 @@ export class ReadStateManager {
495497

496498
for (const event of events) {
497499
const parsed = await parseReadStateEvent(event, this.pubkey);
500+
if (this.destroyed) return;
498501
if (!parsed) continue;
499502

500503
this.maxFetchedCreatedAt = Math.max(
@@ -531,6 +534,7 @@ export class ReadStateManager {
531534
// d-tag coordinate. If so, rotate our slotId to avoid clobbering.
532535
for (const event of events) {
533536
const parsed = await parseReadStateEvent(event, this.pubkey);
537+
if (this.destroyed) return;
534538
if (!parsed || parsed.dTag !== `read-state:${this.slotId}`) continue;
535539
if (parsed.blob.client_id !== this.clientId) {
536540
this.slotId = generateHex(16);
@@ -583,14 +587,13 @@ export class ReadStateManager {
583587
}
584588

585589
private async handleIncomingEvent(event: RelayEvent): Promise<void> {
586-
if (event.pubkey !== this.pubkey) return;
587-
if (this.destroyed) return;
590+
if (this.destroyed || event.pubkey !== this.pubkey) return;
588591
console.debug(
589592
`[ReadStateManager] incoming event=${event.id.substring(0, 8)}… created_at=${event.created_at}`,
590593
);
591594

592595
const parsed = await parseReadStateEvent(event, this.pubkey);
593-
if (!parsed) return;
596+
if (!parsed || this.destroyed) return;
594597

595598
this.maxFetchedCreatedAt = Math.max(
596599
this.maxFetchedCreatedAt,
@@ -633,6 +636,7 @@ export class ReadStateManager {
633636
}
634637

635638
private schedulePublish(): void {
639+
if (this.destroyed) return;
636640
if (this.debounceTimer !== null) {
637641
window.clearTimeout(this.debounceTimer);
638642
}
@@ -645,6 +649,7 @@ export class ReadStateManager {
645649
private async publish(): Promise<void> {
646650
console.debug(`[ReadStateManager] publish starting slotId=${this.slotId}`);
647651
await this.fetchOwnBlobBeforePublish();
652+
if (this.destroyed) return;
648653
this.flushLocalState();
649654

650655
// Build blob from contexts this client is allowed to publish.
@@ -943,7 +948,7 @@ export class ReadStateManager {
943948
}
944949

945950
private persistLocalState(): void {
946-
if (this.localPersistTimer !== null) return;
951+
if (this.destroyed || this.localPersistTimer !== null) return;
947952

948953
this.localPersistTimer = window.setTimeout(() => {
949954
this.localPersistTimer = null;

0 commit comments

Comments
 (0)