Skip to content

Commit 6017091

Browse files
browstudio
andauthored
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 <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
1 parent 18e4b37 commit 6017091

6 files changed

Lines changed: 22 additions & 114 deletions

File tree

‎mobile/lib/shared/channels/open_channel_directory_storage.dart‎

Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -73,39 +73,6 @@ class OpenChannelDirectoryStorage {
7373
),
7474
);
7575

76-
/// Deletes every saved directory under [root] except each retained
77-
/// community's file for its current signer (community id to signer), and
78-
/// the pending copy a save of it may be writing. A
79-
/// failed delete is retried on the next call. Removed communities lose their
80-
/// whole directory to [MediaDiskCache.removeOrphans].
81-
static Future<void> removeOrphans(
82-
Directory root,
83-
Map<String, String?> Function() retained,
84-
) async {
85-
final communities = Directory(p.join(root.path, 'communities'));
86-
if (!await communities.exists()) return;
87-
Set<String> keep() => {
88-
for (final MapEntry(key: id, value: signer) in retained().entries)
89-
if (signer != null) ...{
90-
fileFor(root, id, signer).path,
91-
'${fileFor(root, id, signer).path}.pending',
92-
},
93-
};
94-
await for (final community in communities.list(followLinks: false)) {
95-
if (community is! Directory) continue;
96-
final saved = Directory(p.join(community.path, 'channel-directory'));
97-
if (!await saved.exists()) continue;
98-
await for (final entry in saved.list(followLinks: false)) {
99-
if (keep().contains(entry.path)) continue;
100-
try {
101-
await entry.delete(recursive: true);
102-
} on FileSystemException catch (error) {
103-
debugPrint('[OpenChannelDirectoryStorage] cleanup failed: $error');
104-
}
105-
}
106-
}
107-
}
108-
10976
/// The saved directory, or null when there is none or it is unusable.
11077
Future<SavedOpenChannelDirectory?> read() async {
11178
final file = await _file;
@@ -164,7 +131,8 @@ class OpenChannelDirectoryStorage {
164131
}
165132

166133
/// Stops every later read and write, as when the community or account is
167-
/// retired. The file itself is deleted by [removeOrphans].
134+
/// retired. The file is deleted with its community, by
135+
/// [MediaDiskCache.removeOrphans].
168136
void close() => _closed = true;
169137

170138
Future<void> _discard(File file) async {

‎mobile/lib/shared/community/community_provider.dart‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import '../push/dev_push_lease.dart';
2020
import '../push/push_bridge.dart';
2121
import '../push/push_lease_revocation_outbox.dart';
2222
import '../push/push_subscription.dart';
23-
import '../channels/open_channel_directory_storage.dart';
2423
import '../relay/media_disk_cache.dart';
2524
import '../relay/signed_event_relay.dart';
2625
import '../relay/relay_provider.dart' show RelayConfig, pubkeyFromNsec;
@@ -434,12 +433,11 @@ class CommunityListNotifier extends AsyncNotifier<List<Community>> {
434433
}
435434

436435
/// Deletes the image caches and saved channel directories of communities no
437-
/// longer in the list, and of accounts a community no longer signs in as. A
438-
/// failure, or a write that lands after the delete, is swept on the next
439-
/// launch.
436+
/// longer in the list. A failure, or a write that lands after the delete, is
437+
/// swept on the next launch.
440438
///
441439
/// Sweeps run one at a time, each keeping what the community list holds
442-
/// when it starts, so an older sweep can never delete a newer account's
440+
/// when it starts, so an older sweep can never delete a newer community's
443441
/// cache. [fallback] stands in for the list while it is still loading.
444442
Future<void> _removeOrphanMediaCaches({List<Community>? fallback}) =>
445443
_mediaSweep = _mediaSweep.then((_) => _sweepMediaCaches(fallback));
@@ -454,17 +452,16 @@ class CommunityListNotifier extends AsyncNotifier<List<Community>> {
454452
state.isLoading ? fallback ?? state.value : state.value;
455453
var communities = current();
456454
if (communities == null) return;
457-
Map<String, String?> retained() {
455+
Set<String> retained() {
458456
// A list briefly unavailable mid-sweep keeps the last one seen.
459457
communities = current() ?? communities;
460458
return {
461459
for (final community in communities!)
462-
community.id: _channelSnapshotPubkey(community)?.toLowerCase(),
460+
if (_channelSnapshotPubkey(community) != null) community.id,
463461
};
464462
}
465463

466464
await MediaDiskCache.removeOrphans(root, retained);
467-
await OpenChannelDirectoryStorage.removeOrphans(root, retained);
468465
} catch (error, stackTrace) {
469466
developer.log(
470467
'Media cache deletion failed; the next launch will retry',

‎mobile/lib/shared/relay/media_disk_cache.dart‎

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ typedef MediaDiskCacheHit = ({Uint8List bytes, bool isStale});
2222
/// Built on `flutter_cache_manager`. It keeps the bytes each URL served, so a
2323
/// relay thumbnail and its original are separate entries. Each community and
2424
/// account has its own directory under the caches root (see
25-
/// [mediaCacheRootProvider]), deleted with the community or account. Least recently used files are evicted once
26-
/// the directory holds more than [maxBytes].
25+
/// [mediaCacheRootProvider]), deleted with its community. Least recently used
26+
/// files are evicted once the directory holds more than [maxBytes].
2727
///
2828
/// Relay media URLs are content hashes and never go stale. Other URLs can
2929
/// change in place, so they are served from disk but refetched in the
@@ -133,32 +133,19 @@ class MediaDiskCache {
133133
p.join(communityDirectory(root, communityId).path, 'media', signer),
134134
);
135135

136-
/// Keeps only each retained community's cache for its current signer
137-
/// (community id to signer pubkey) and deletes every other directory under
138-
/// [root]: removed communities and replaced accounts, including writes
139-
/// that landed after their removal. A failed delete is retried on the
140-
/// next call.
136+
/// Deletes every directory under [root] except the [retained] communities'
137+
/// (by id), including writes that landed after their removal. A failed
138+
/// delete is retried on the next call.
141139
///
142-
/// [retained] is read again before each delete, so a community or account
143-
/// added while the sweep runs is kept.
140+
/// [retained] is read again before each delete, so a community added while
141+
/// the sweep runs is kept.
144142
static Future<void> removeOrphans(
145143
Directory root,
146-
Map<String, String?> Function() retained,
147-
) async {
148-
Set<String> keep() => {
149-
for (final MapEntry(key: id, value: signer) in retained().entries)
150-
if (signer != null) directoryFor(root, id, signer).path,
151-
};
152-
final communities = Directory(p.join(root.path, 'communities'));
153-
await _deleteExcept(communities, () {
154-
return {for (final path in keep()) p.dirname(p.dirname(path))};
155-
});
156-
if (!await communities.exists()) return;
157-
await for (final community in communities.list(followLinks: false)) {
158-
if (community is! Directory) continue;
159-
await _deleteExcept(Directory(p.join(community.path, 'media')), keep);
160-
}
161-
}
144+
Set<String> Function() retained,
145+
) => _deleteExcept(
146+
Directory(p.join(root.path, 'communities')),
147+
() => {for (final id in retained()) communityDirectory(root, id).path},
148+
);
162149

163150
/// Deletes the entries of [parent] whose paths are not in [keep].
164151
static Future<void> _deleteExcept(

‎mobile/test/shared/channels/open_channel_directory_storage_test.dart‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -144,39 +144,4 @@ void main() {
144144
);
145145
expect(await storage.read(), isNull);
146146
});
147-
148-
test(
149-
'cleanup keeps only each community\'s current account and its save',
150-
() async {
151-
Future<void> save(String community, String signer) =>
152-
OpenChannelDirectoryStorage(
153-
Future.value(fileFor(community, signer)),
154-
).write(
155-
SavedOpenChannelDirectory(
156-
metas: [_meta('a', 1)],
157-
fullAt: 1,
158-
readAt: 1,
159-
),
160-
);
161-
await save('one', 'current');
162-
await save('one', 'signed-out');
163-
await save('two', 'current');
164-
// A save of the retained account in progress, and a stale one.
165-
final pending = File('${fileFor('one', 'current').path}.pending')
166-
..writeAsStringSync('');
167-
final stalePending = File('${fileFor('one', 'signed-out').path}.pending')
168-
..writeAsStringSync('');
169-
170-
await OpenChannelDirectoryStorage.removeOrphans(
171-
root,
172-
() => {'one': 'current', 'two': null},
173-
);
174-
175-
expect(fileFor('one', 'current').existsSync(), isTrue);
176-
expect(fileFor('one', 'signed-out').existsSync(), isFalse);
177-
expect(fileFor('two', 'current').existsSync(), isFalse);
178-
expect(pending.existsSync(), isTrue);
179-
expect(stalePending.existsSync(), isFalse);
180-
},
181-
);
182147
}

‎mobile/test/shared/community/community_provider_test.dart‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -703,10 +703,6 @@ void main() {
703703
MediaDiskCache.communityDirectory(mediaRoot, 'restored'),
704704
);
705705
final oldDirectory = await seedDirectory(community.id, oldKeys.public);
706-
final retiredDirectory = await seedDirectory(
707-
community.id,
708-
nostr.Keys.generate().public,
709-
);
710706
container = createContainer(
711707
overrides: [
712708
savedPrefsProvider.overrideWithValue(prefs),
@@ -719,7 +715,6 @@ void main() {
719715
expect(await cache.write(restoredToken, snapshot), isFalse);
720716
expect(await eventuallyExists(orphanMedia), isFalse);
721717
expect(await oldMedia.exists(), isTrue);
722-
expect(await eventuallyExists(retiredDirectory), isFalse);
723718
expect(await oldDirectory.exists(), isTrue);
724719

725720
await communityStorage.saveActiveId(community.id);

‎mobile/test/shared/relay/media_disk_cache_test.dart‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -260,15 +260,11 @@ void main() {
260260
replaceExternal = null;
261261
expect(fetched, _externalUrls.take(2));
262262

263-
// A replaced account's directory goes, including writes that land after
264-
// its delete; removing the community deletes its directory.
263+
// Removing the community deletes its directory.
265264
expect(await directory.exists(), isTrue);
266-
await MediaDiskCache.removeOrphans(root, () => {'community-1': 'signer-2'});
267-
expect(await directory.exists(), isFalse);
268-
await directory.create(recursive: true);
269-
await MediaDiskCache.removeOrphans(root, () => {'community-1': 'signer-1'});
265+
await MediaDiskCache.removeOrphans(root, () => {'community-1'});
270266
expect(await directory.exists(), isTrue);
271-
await MediaDiskCache.removeOrphans(root, () => {'community-2': 'signer-1'});
267+
await MediaDiskCache.removeOrphans(root, () => {'community-2'});
272268
expect(
273269
await MediaDiskCache.communityDirectory(root, 'community-1').exists(),
274270
isFalse,

0 commit comments

Comments
 (0)