From 6017091936ee0148c73c5ed1af77fa452fb4fce1 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Mon, 23 Nov 2026 11:53:37 -0800 Subject: [PATCH] refactor(mobile): remove the dead per-signer cache sweep (#9902) ## Summary The media cache and saved channel-directory sweeps kept, for each saved community, only the files of its current signer, and deleted the files of any other account under the same community id. That state came only from the same-relay credential replacement removed in #9896. Community ids are random, and every remaining path that rewrites a saved community's key keeps the same key (hosted reconnect refuses a different one). So no community can change signer anymore, and the per-signer cleanup is dead. This deletes it. The sweep now keeps whole community directories by id and deletes the directories of removed communities, as before. ## Changes - `MediaDiskCache.removeOrphans` takes the retained community ids and no longer sweeps signer subdirectories. - Delete `OpenChannelDirectoryStorage.removeOrphans`. Its only job was deleting other signers' files; a removed community's directory still goes with its community directory. - Delete the tests and assertions that covered signer replacement. ### Added lines - The new, shorter `MediaDiskCache.removeOrphans` body and doc comment. - The provider's retained set: community ids that have a signer, the same communities the old map kept. - Two doc comment rewordings that no longer mention replaced accounts. - The media cache test's removal check, rewritten for the new signature. ## Validation - Full mobile test suite, analyze, format and file-size checks pass. - No user-visible change, so no screenshots. --------- Signed-off-by: Tom Brow Co-authored-by: studio --- .../open_channel_directory_storage.dart | 36 +----------------- .../shared/community/community_provider.dart | 13 +++---- mobile/lib/shared/relay/media_disk_cache.dart | 37 ++++++------------- .../open_channel_directory_storage_test.dart | 35 ------------------ .../community/community_provider_test.dart | 5 --- .../shared/relay/media_disk_cache_test.dart | 10 ++--- 6 files changed, 22 insertions(+), 114 deletions(-) diff --git a/mobile/lib/shared/channels/open_channel_directory_storage.dart b/mobile/lib/shared/channels/open_channel_directory_storage.dart index 1bc1bc7724..da52275499 100644 --- a/mobile/lib/shared/channels/open_channel_directory_storage.dart +++ b/mobile/lib/shared/channels/open_channel_directory_storage.dart @@ -73,39 +73,6 @@ class OpenChannelDirectoryStorage { ), ); - /// Deletes every saved directory under [root] except each retained - /// community's file for its current signer (community id to signer), and - /// the pending copy a save of it may be writing. A - /// failed delete is retried on the next call. Removed communities lose their - /// whole directory to [MediaDiskCache.removeOrphans]. - static Future removeOrphans( - Directory root, - Map Function() retained, - ) async { - final communities = Directory(p.join(root.path, 'communities')); - if (!await communities.exists()) return; - Set keep() => { - for (final MapEntry(key: id, value: signer) in retained().entries) - if (signer != null) ...{ - fileFor(root, id, signer).path, - '${fileFor(root, id, signer).path}.pending', - }, - }; - await for (final community in communities.list(followLinks: false)) { - if (community is! Directory) continue; - final saved = Directory(p.join(community.path, 'channel-directory')); - if (!await saved.exists()) continue; - await for (final entry in saved.list(followLinks: false)) { - if (keep().contains(entry.path)) continue; - try { - await entry.delete(recursive: true); - } on FileSystemException catch (error) { - debugPrint('[OpenChannelDirectoryStorage] cleanup failed: $error'); - } - } - } - } - /// The saved directory, or null when there is none or it is unusable. Future read() async { final file = await _file; @@ -164,7 +131,8 @@ class OpenChannelDirectoryStorage { } /// Stops every later read and write, as when the community or account is - /// retired. The file itself is deleted by [removeOrphans]. + /// retired. The file is deleted with its community, by + /// [MediaDiskCache.removeOrphans]. void close() => _closed = true; Future _discard(File file) async { diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index 6c44720222..84c4148d67 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -20,7 +20,6 @@ import '../push/dev_push_lease.dart'; import '../push/push_bridge.dart'; import '../push/push_lease_revocation_outbox.dart'; import '../push/push_subscription.dart'; -import '../channels/open_channel_directory_storage.dart'; import '../relay/media_disk_cache.dart'; import '../relay/signed_event_relay.dart'; import '../relay/relay_provider.dart' show RelayConfig, pubkeyFromNsec; @@ -434,12 +433,11 @@ class CommunityListNotifier extends AsyncNotifier> { } /// Deletes the image caches and saved channel directories of communities no - /// longer in the list, and of accounts a community no longer signs in as. A - /// failure, or a write that lands after the delete, is swept on the next - /// launch. + /// longer in the list. A failure, or a write that lands after the delete, is + /// swept on the next launch. /// /// Sweeps run one at a time, each keeping what the community list holds - /// when it starts, so an older sweep can never delete a newer account's + /// when it starts, so an older sweep can never delete a newer community's /// cache. [fallback] stands in for the list while it is still loading. Future _removeOrphanMediaCaches({List? fallback}) => _mediaSweep = _mediaSweep.then((_) => _sweepMediaCaches(fallback)); @@ -454,17 +452,16 @@ class CommunityListNotifier extends AsyncNotifier> { state.isLoading ? fallback ?? state.value : state.value; var communities = current(); if (communities == null) return; - Map retained() { + Set retained() { // A list briefly unavailable mid-sweep keeps the last one seen. communities = current() ?? communities; return { for (final community in communities!) - community.id: _channelSnapshotPubkey(community)?.toLowerCase(), + if (_channelSnapshotPubkey(community) != null) community.id, }; } await MediaDiskCache.removeOrphans(root, retained); - await OpenChannelDirectoryStorage.removeOrphans(root, retained); } catch (error, stackTrace) { developer.log( 'Media cache deletion failed; the next launch will retry', diff --git a/mobile/lib/shared/relay/media_disk_cache.dart b/mobile/lib/shared/relay/media_disk_cache.dart index eabfba46e4..03759d3e34 100644 --- a/mobile/lib/shared/relay/media_disk_cache.dart +++ b/mobile/lib/shared/relay/media_disk_cache.dart @@ -22,8 +22,8 @@ typedef MediaDiskCacheHit = ({Uint8List bytes, bool isStale}); /// Built on `flutter_cache_manager`. It keeps the bytes each URL served, so a /// relay thumbnail and its original are separate entries. Each community and /// account has its own directory under the caches root (see -/// [mediaCacheRootProvider]), deleted with the community or account. Least recently used files are evicted once -/// the directory holds more than [maxBytes]. +/// [mediaCacheRootProvider]), deleted with its community. Least recently used +/// files are evicted once the directory holds more than [maxBytes]. /// /// Relay media URLs are content hashes and never go stale. Other URLs can /// change in place, so they are served from disk but refetched in the @@ -133,32 +133,19 @@ class MediaDiskCache { p.join(communityDirectory(root, communityId).path, 'media', signer), ); - /// Keeps only each retained community's cache for its current signer - /// (community id to signer pubkey) and deletes every other directory under - /// [root]: removed communities and replaced accounts, including writes - /// that landed after their removal. A failed delete is retried on the - /// next call. + /// Deletes every directory under [root] except the [retained] communities' + /// (by id), including writes that landed after their removal. A failed + /// delete is retried on the next call. /// - /// [retained] is read again before each delete, so a community or account - /// added while the sweep runs is kept. + /// [retained] is read again before each delete, so a community added while + /// the sweep runs is kept. static Future removeOrphans( Directory root, - Map Function() retained, - ) async { - Set keep() => { - for (final MapEntry(key: id, value: signer) in retained().entries) - if (signer != null) directoryFor(root, id, signer).path, - }; - final communities = Directory(p.join(root.path, 'communities')); - await _deleteExcept(communities, () { - return {for (final path in keep()) p.dirname(p.dirname(path))}; - }); - if (!await communities.exists()) return; - await for (final community in communities.list(followLinks: false)) { - if (community is! Directory) continue; - await _deleteExcept(Directory(p.join(community.path, 'media')), keep); - } - } + Set Function() retained, + ) => _deleteExcept( + Directory(p.join(root.path, 'communities')), + () => {for (final id in retained()) communityDirectory(root, id).path}, + ); /// Deletes the entries of [parent] whose paths are not in [keep]. static Future _deleteExcept( diff --git a/mobile/test/shared/channels/open_channel_directory_storage_test.dart b/mobile/test/shared/channels/open_channel_directory_storage_test.dart index e96ce24bbc..f2d1bfbc99 100644 --- a/mobile/test/shared/channels/open_channel_directory_storage_test.dart +++ b/mobile/test/shared/channels/open_channel_directory_storage_test.dart @@ -144,39 +144,4 @@ void main() { ); expect(await storage.read(), isNull); }); - - test( - 'cleanup keeps only each community\'s current account and its save', - () async { - Future save(String community, String signer) => - OpenChannelDirectoryStorage( - Future.value(fileFor(community, signer)), - ).write( - SavedOpenChannelDirectory( - metas: [_meta('a', 1)], - fullAt: 1, - readAt: 1, - ), - ); - await save('one', 'current'); - await save('one', 'signed-out'); - await save('two', 'current'); - // A save of the retained account in progress, and a stale one. - final pending = File('${fileFor('one', 'current').path}.pending') - ..writeAsStringSync(''); - final stalePending = File('${fileFor('one', 'signed-out').path}.pending') - ..writeAsStringSync(''); - - await OpenChannelDirectoryStorage.removeOrphans( - root, - () => {'one': 'current', 'two': null}, - ); - - expect(fileFor('one', 'current').existsSync(), isTrue); - expect(fileFor('one', 'signed-out').existsSync(), isFalse); - expect(fileFor('two', 'current').existsSync(), isFalse); - expect(pending.existsSync(), isTrue); - expect(stalePending.existsSync(), isFalse); - }, - ); } diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index 0702acd90b..a9f5aeb754 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -703,10 +703,6 @@ void main() { MediaDiskCache.communityDirectory(mediaRoot, 'restored'), ); final oldDirectory = await seedDirectory(community.id, oldKeys.public); - final retiredDirectory = await seedDirectory( - community.id, - nostr.Keys.generate().public, - ); container = createContainer( overrides: [ savedPrefsProvider.overrideWithValue(prefs), @@ -719,7 +715,6 @@ void main() { expect(await cache.write(restoredToken, snapshot), isFalse); expect(await eventuallyExists(orphanMedia), isFalse); expect(await oldMedia.exists(), isTrue); - expect(await eventuallyExists(retiredDirectory), isFalse); expect(await oldDirectory.exists(), isTrue); await communityStorage.saveActiveId(community.id); diff --git a/mobile/test/shared/relay/media_disk_cache_test.dart b/mobile/test/shared/relay/media_disk_cache_test.dart index 9e97f659ef..71826a71d4 100644 --- a/mobile/test/shared/relay/media_disk_cache_test.dart +++ b/mobile/test/shared/relay/media_disk_cache_test.dart @@ -260,15 +260,11 @@ void main() { replaceExternal = null; expect(fetched, _externalUrls.take(2)); - // A replaced account's directory goes, including writes that land after - // its delete; removing the community deletes its directory. + // Removing the community deletes its directory. expect(await directory.exists(), isTrue); - await MediaDiskCache.removeOrphans(root, () => {'community-1': 'signer-2'}); - expect(await directory.exists(), isFalse); - await directory.create(recursive: true); - await MediaDiskCache.removeOrphans(root, () => {'community-1': 'signer-1'}); + await MediaDiskCache.removeOrphans(root, () => {'community-1'}); expect(await directory.exists(), isTrue); - await MediaDiskCache.removeOrphans(root, () => {'community-2': 'signer-1'}); + await MediaDiskCache.removeOrphans(root, () => {'community-2'}); expect( await MediaDiskCache.communityDirectory(root, 'community-1').exists(), isFalse,