diff --git a/mobile/lib/shared/relay/media_disk_cache.dart b/mobile/lib/shared/relay/media_disk_cache.dart index 03759d3e34..1e52c25c45 100644 --- a/mobile/lib/shared/relay/media_disk_cache.dart +++ b/mobile/lib/shared/relay/media_disk_cache.dart @@ -9,6 +9,7 @@ import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; import '../community/community_provider.dart'; import 'relay_provider.dart' show pubkeyFromNsec; @@ -34,26 +35,65 @@ class MediaDiskCache { /// [directory] to resolve, so a load never skips the disk while it does. /// [now] is the clock staleness is judged by. /// - /// Tests can shrink the budgets and the delay after a write or first read - /// before eviction runs (10 s in `flutter_cache_manager`). + /// Tests can shrink the budgets, the delay after a write or first read + /// before eviction runs (10 s in `flutter_cache_manager`), and how long + /// requests wait for the directory or for a previous cache to close. MediaDiskCache.open( FutureOr directory, { @visibleForTesting DateTime Function() now = DateTime.now, @visibleForTesting int byteBudget = maxBytes, @visibleForTesting int fileBudget = maxFiles, @visibleForTesting Duration? evictionDelay, + @visibleForTesting int evictionsPerPass = maxEvictionsPerPass, + @visibleForTesting Duration openTimeout = _openTimeout, }) : _now = now { + CacheManager? openNow(Directory directory) { + if (isClosed) return null; + _path = directory.path; + final (manager, index) = _openManager( + directory, + byteBudget: byteBudget, + fileBudget: fileBudget, + evictionDelay: evictionDelay, + evictionsPerPass: evictionsPerPass, + ); + _index = index; + return manager; + } + _manager = Future.value(directory) // Images wait for the disk, so never wait on it for long. - .timeout(_openTimeout, onTimeout: () => null) - .then((directory) { + .timeout(openTimeout, onTimeout: () => null) + .then((directory) async { if (directory == null || isClosed) return null; - return _openManager( - directory, - byteBudget: byteBudget, - fileBudget: fileBudget, - evictionDelay: evictionDelay, + // A cache on this directory that is still closing, after a switch + // away and back, may hold saves its index has not recorded yet. + // Opening after it keeps this one's sweep from deleting them, and + // keeps its final flush from overwriting this one's index. + final previous = _closing[directory.path]; + if (previous == null) return openNow(directory); + var closed = true; + await previous.timeout( + openTimeout, + onTimeout: () { + closed = false; + }, ); + if (closed) return openNow(directory); + // Requests waiting now go without the disk. Later ones get it + // once the previous cache has closed. + unawaited( + previous + .then((_) { + if (isClosed) return; + final manager = openNow(directory); + if (manager != null) _manager = Future.value(manager); + }) + .catchError((Object error) { + debugPrint('[MediaDiskCache] open failed: $error'); + }), + ); + return null; }) .catchError((Object error) { debugPrint('[MediaDiskCache] open failed: $error'); @@ -61,32 +101,42 @@ class MediaDiskCache { }); } - static CacheManager _openManager( + static (CacheManager, MediaCacheIndex) _openManager( Directory directory, { required int byteBudget, required int fileBudget, required Duration? evictionDelay, + required int evictionsPerPass, }) { + final index = MediaCacheIndex( + File(p.join(directory.path, 'index.json')), + directory, + byteBudget, + evictionsPerPass: evictionsPerPass, + ); final manager = CacheManager( Config( directory.path, // Age never evicts: the byte budget below does. stalePeriod: _neverStale, maxNrOfCacheObjects: fileBudget, - repo: MediaCacheIndex( - File(p.join(directory.path, 'index.json')), - directory, - byteBudget, - ), + repo: index, fileSystem: _DirectoryFileSystem(directory), ), ); if (evictionDelay != null) { manager.store.cleanupRunMinInterval = evictionDelay; } - return manager; + // The package schedules a pass only on an index lookup, so a pass that + // stops at its limit looks up a key to schedule the next. + index.onMoreToEvict = () => unawaited( + manager.store.retrieveCacheData(_nextPassKey, ignoreMemCache: true), + ); + return (manager, index); } + static const _nextPassKey = 'media-disk-cache:next-eviction-pass'; + static const _openTimeout = Duration(seconds: 3); /// Most bytes one community's cache keeps on disk. @@ -96,16 +146,19 @@ class MediaDiskCache { /// avatars) cannot cost far more disk and index work than their bytes. static const maxFiles = 10000; - /// Larger images still show, from memory, but are never written to disk, - /// so one image cannot evict the rest of the cache. - static const maxFileBytes = 5 * 1024 * 1024; + /// Most files one eviction pass deletes. Each costs UI-isolate time, so a + /// large image saved into a cache full of small ones evicts them over + /// several passes rather than in one long pause. + static const maxEvictionsPerPass = 256; /// Age at which a non-relay image is refetched in the background. static const externalRefreshAge = Duration(days: 7); static const _neverStale = Duration(days: 365 * 100); - late final Future _manager; + /// Replaced once, when a previous cache on this directory outlasted the + /// open wait and has since closed. + late Future _manager; final DateTime Function() _now; final _closed = Completer(); @@ -166,6 +219,7 @@ class MediaDiskCache { /// Removes [url]'s saved bytes, for example when they no longer decode. /// Failures are logged; a later read finds the same bad bytes. Future remove(String url) async { + if (isClosed) return; try { await (await _manager)?.removeFile(url); } on Object catch (error) { @@ -176,6 +230,7 @@ class MediaDiskCache { /// Whether [url] has saved bytes, from the index alone, without reading /// them. Future contains(String url) async { + if (isClosed) return false; try { final manager = await _manager; return await manager?.getFileFromCache(url, ignoreMemCache: true) != null; @@ -190,7 +245,7 @@ class MediaDiskCache { final FileInfo? info; final Uint8List bytes; final manager = await _manager; - if (manager == null) return null; + if (manager == null || isClosed) return null; try { // Past the first lookup, the package serves a URL from memory without // marking it used, so a file read often would be evicted first. Going @@ -209,11 +264,24 @@ class MediaDiskCache { } /// Saves [bytes] for [url]. [immutable] bytes (relay media) are never - /// refetched; others are refetched after [externalRefreshAge]. Bytes over - /// [maxFileBytes] are not saved, and drop any older copy so it is not - /// shown in their place. Failures are logged, never thrown: a missing - /// entry only costs a later download. - Future write( + /// refetched; others are refetched after [externalRefreshAge]. Failures are + /// logged, never thrown: a missing entry only costs a later download. + Future write(String url, Uint8List bytes, {required bool immutable}) { + // Overlapping saves of one URL would each create a file, and the index + // tracks only the last, so the other would stay on disk past eviction. + // Each save waits for the one before it, then replaces its file. + final saved = (_writes[url] ?? Future.value()).then( + (_) => _write(url, bytes, immutable: immutable), + ); + _writes[url] = saved; + return saved.whenComplete(() { + if (identical(_writes[url], saved)) _writes.remove(url); + }); + } + + final _writes = >{}; + + Future _write( String url, Uint8List bytes, { required bool immutable, @@ -224,15 +292,27 @@ class MediaDiskCache { final manager = await _manager; if (manager == null || isClosed) return; try { - if (bytes.length > maxFileBytes) { - await manager.removeFile(url); - return; - } - await manager.putFile( - url, + final store = manager.store; + // Like `putFile`, keep the URL's path, but publish the bytes with a + // rename so a reader sees the old file or the new one, never a part. + final previous = await store.retrieveCacheData(url); + final saved = + (previous ?? + CacheObject( + url, + relativePath: '${const Uuid().v1()}.file', + validTill: _now(), + )) + .copyWith( + validTill: _now().add( + immutable ? _neverStale : externalRefreshAge, + ), + ); + await (store.fileSystem as _DirectoryFileSystem).replace( + saved.relativePath, bytes, - maxAge: immutable ? _neverStale : externalRefreshAge, ); + await store.putFile(saved); // Replacing a URL the package already holds in memory schedules no // eviction, so a refresh that grows the cache would leave it over // budget. An index lookup schedules it. @@ -242,19 +322,43 @@ class MediaDiskCache { } } - /// Stops writes, then flushes the index. + /// Stops writes, lets saves in progress finish, then flushes the index. Future dispose() { if (_closed.isCompleted) return _disposed; _closed.complete(); - return _disposed = _manager - .then((manager) => manager?.dispose()) + // The package leaves an eviction pass scheduled, which could run after + // another cache opened this directory and save a stale index over its. + _index?.retire(); + final disposed = _disposed = _manager + .then((manager) async { + await Future.wait(_writes.values.toList()); + await manager?.dispose(); + }) .catchError((Object error) { debugPrint('[MediaDiskCache] close failed: $error'); }); + final path = _path; + if (path != null) { + _closing[path] = disposed; + unawaited( + disposed.whenComplete(() { + if (identical(_closing[path], disposed)) _closing.remove(path); + }), + ); + } + return disposed; } Future _disposed = Future.value(); + /// The directory this cache opened, once it has. + String? _path; + + MediaCacheIndex? _index; + + /// Caches still closing, by directory. + static final _closing = >{}; + static void _logFailure(Object error) => debugPrint('[MediaDiskCache] write failed: $error'); } @@ -264,33 +368,125 @@ class MediaDiskCache { /// [_maxBytes], the least recently used are over capacity. @visibleForTesting class MediaCacheIndex extends JsonCacheInfoRepository { - MediaCacheIndex(super.file, this._directory, this._maxBytes) - : super.withFile(); + MediaCacheIndex( + super.file, + this._directory, + this._maxBytes, { + this.evictionsPerPass = MediaDiskCache.maxEvictionsPerPass, + }) : super.withFile(); final Directory _directory; final int _maxBytes; - /// Least recently used files past [capacity] files or past the byte - /// budget, whichever keeps fewer. + /// Most files [getObjectsOverCapacity] returns at once. + final int evictionsPerPass; + + /// Called when more files are over capacity than one pass returns. + void Function()? onMoreToEvict; + + bool _retired = false; + + /// Stops eviction for good, once its cache is disposed: a pass still + /// scheduled finds nothing to evict, and one in progress records nothing. + /// Saves still finishing are recorded. + void retire() => _retired = true; + + /// Set once closing starts. A later change, such as a read marking a file + /// used after the cache was disposed, would save this index over one a + /// newer cache wrote, so it is dropped. + bool _closed = false; + + /// Deletes files the index doesn't track, once, after it opens: a save + /// interrupted by a full disk or the app exiting, or one whose index entry + /// was not yet saved. Eviction sees only indexed files. The sweep runs in + /// the background, since listing a full directory would delay the first + /// image. + @override + Future open() async { + final opened = await super.open(); + _sweep ??= _deleteUntrackedFiles(); + return opened; + } + + Future? _sweep; + + /// Waits for the sweep, so a cache opening this directory next starts + /// after it. + @override + Future close() async { + await _sweep; + _closed = true; + return super.close(); + } + + /// How far a file's modification time may trail the clock, on file + /// systems that record it coarsely. + static const _mtimeSlack = Duration(seconds: 5); + + Future _deleteUntrackedFiles() async { + // A save that starts while this runs is newer, so it is kept. + final cutoff = DateTime.now().subtract(_mtimeSlack); + final Set tracked; + final List entries; + try { + if (!await _directory.exists()) return; + tracked = {for (final o in await getAllObjects()) o.relativePath}; + entries = await _directory.list().toList(); + } on FileSystemException catch (error) { + debugPrint('[MediaDiskCache] sweep failed: $error'); + return; + } + for (final entry in entries) { + final name = p.basename(entry.path); + if (entry is! File || + name.startsWith('index.json') || + tracked.contains(name)) { + continue; + } + try { + if ((await entry.lastModified()).isBefore(cutoff)) { + await entry.delete(); + } + } on FileSystemException { + // Renamed or deleted since the listing. + } + } + } + + /// The least recently used files past [capacity] files or past the byte + /// budget, whichever keeps fewer, at most [evictionsPerPass] of them. @override Future> getObjectsOverCapacity(int capacity) async { + if (_retired) return []; final newestFirst = await getAllObjects() ..sort((a, b) => b.touched!.compareTo(a.touched!)); var total = 0; var count = 0; - return [ + final over = [ for (final object in newestFirst) if ((total += object.length ?? 0) > _maxBytes || ++count > capacity) object, ]; + if (over.length <= evictionsPerPass) return over; + onMoreToEvict?.call(); + return over.sublist(over.length - evictionsPerPass); } + @override + Future deleteAll(Iterable ids) async => + _retired || _closed ? 0 : super.deleteAll(ids); + + @override + Future delete(int id) async => _closed ? 0 : super.delete(id); + /// `putFile` records no length, and replacing a file's bytes keeps the old /// one, so measure the file on every write. @override Future updateOrInsert(CacheObject cacheObject) async { + if (_closed) return cacheObject; final file = File(p.join(_directory.path, cacheObject.relativePath)); final length = await file.exists() ? await file.length() : 0; + if (_closed) return cacheObject; return super.updateOrInsert(cacheObject.copyWith(length: length)); } } @@ -308,6 +504,25 @@ class _DirectoryFileSystem implements FileSystem { await _directory.create(recursive: true); return _directory.childFile(name); } + + /// Writes [bytes] beside [name], then renames them over it, so readers + /// never see a partial file. A failed write leaves no file behind. + Future replace(String name, Uint8List bytes) async { + // A name of its own, so a sweep that found an earlier save's abandoned + // part cannot delete this one. + final part = await createFile('$name.${const Uuid().v4()}.part'); + try { + await part.writeAsBytes(bytes); + await part.rename(_directory.childFile(name).path); + } on Object { + try { + await part.delete(); + } on FileSystemException { + // Never created. + } + rethrow; + } + } } const _appGroupChannel = MethodChannel('buzz/app_group'); diff --git a/mobile/test/shared/relay/media_disk_cache_test.dart b/mobile/test/shared/relay/media_disk_cache_test.dart index 71826a71d4..f1a43e11cf 100644 --- a/mobile/test/shared/relay/media_disk_cache_test.dart +++ b/mobile/test/shared/relay/media_disk_cache_test.dart @@ -7,6 +7,7 @@ import 'package:buzz/shared/relay/media_auth.dart'; import 'package:buzz/shared/relay/media_disk_cache.dart'; import 'package:buzz/shared/relay/media_image.dart'; import 'package:flutter/painting.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart' as http_testing; @@ -23,7 +24,7 @@ const _hash = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const _relayUrl = '$_relayBase/media/$_hash.png'; const _thumbnailUrl = '$_relayBase/media/$_hash.thumb.jpg'; -const _hugeUrl = +const _largeUrl = '$_relayBase/media/' 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.png'; const _corruptUrl = @@ -57,24 +58,25 @@ void main() { 'ones are refetched', () async { final fetched = []; var online = true; - // While set, external images answer once it completes, with an image - // too large to save. + // While set, external images answer once it completes, with a large + // image. Completer? replaceExternal; // While set, external images answer with a body that never decodes. var malformedExternal = false; - // Trailing bytes after IEND still decode, so this is a 5 MiB+ image. - final hugeBytes = [..._pngBytes, ...Uint8List(MediaDiskCache.maxFileBytes)]; + // Trailing bytes after IEND still decode, so this is a 12 MiB image, the + // size of a full-resolution phone photo. + final largeBytes = [..._pngBytes, ...Uint8List(12 * 1024 * 1024)]; final client = http_testing.MockClient((request) async { final url = request.url.toString(); fetched.add(url); if (!online) throw const SocketException('offline'); - if (url == _hugeUrl) return http.Response.bytes(hugeBytes, 200); + if (url == _largeUrl) return http.Response.bytes(largeBytes, 200); if (malformedExternal && _externalUrls.contains(url)) { return http.Response('not an image', 200); } if (replaceExternal != null && _externalUrls.contains(url)) { await replaceExternal.future; - return http.Response.bytes(hugeBytes, 200); + return http.Response.bytes(largeBytes, 200); } if (request.url.toString() == _corruptUrl) { return http.Response('not an image', 200); @@ -122,34 +124,32 @@ void main() { ).resolve(ImageConfiguration.empty), ); - const saved = [_relayUrl, _thumbnailUrl, ..._externalUrls]; - const urls = [...saved, _hugeUrl]; + const saved = [_relayUrl, _thumbnailUrl, _largeUrl, ..._externalUrls]; - // First launch downloads everything and saves what fits. + // First launch downloads everything and saves what decodes. await launch((cache) async { - for (final url in urls) { + for (final url in saved) { expect(await show(cache, url), isNull, reason: url); } expect(await show(cache, _corruptUrl), isNotNull); expect(await show(cache, _truncatedUrl), isNotNull); await _settle(); }); - expect(fetched, [...urls, _corruptUrl, _truncatedUrl]); + expect(fetched, [...saved, _corruptUrl, _truncatedUrl]); // Offline relaunch: the original and its thumbnail are separate entries, - // both shown from disk. The oversized image and the bodies that failed - // to decode were never saved. + // both shown from disk, as is the large image. The bodies that failed to + // decode were never saved. fetched.clear(); online = false; await launch((cache) async { for (final url in saved) { expect(await show(cache, url), isNull, reason: url); } - expect(await show(cache, _hugeUrl), isNotNull); expect(await show(cache, _corruptUrl), isNotNull); expect(await show(cache, _truncatedUrl), isNotNull); }); - expect(fetched, [_hugeUrl, _corruptUrl, _truncatedUrl]); + expect(fetched, [_corruptUrl, _truncatedUrl]); // A week on, external images show from disk at once and refresh in the // background, two at a time. Relay media never goes stale. @@ -163,12 +163,13 @@ void main() { } await _settle(); expect(fetched, _externalUrls.take(2)); - // The third waits for a slot. The replacements are too large to save, - // so the old copies go rather than showing in their place. + // The third waits for a slot. The replacements are saved in place of + // the old copies. replacement.complete(); await _until(() async { for (final url in _externalUrls) { - if (await cache.read(url) != null) return false; + final hit = await cache.read(url); + if (hit?.bytes.length != largeBytes.length) return false; } return true; }); @@ -176,15 +177,6 @@ void main() { }); replaceExternal = null; - fetched.clear(); - online = false; - await launch((cache) async { - for (final url in _externalUrls) { - expect(await show(cache, url), isNotNull, reason: url); - } - }); - expect(fetched, _externalUrls); - // A saved copy that no longer decodes is dropped and fetched again. fetched.clear(); online = true; @@ -350,6 +342,266 @@ void main() { expect(await refresh.read('other'), isNull); expect((await refresh.read('refreshed'))?.bytes, hasLength(8)); await refresh.dispose(); + + // Overlapping saves of one URL, as when two sizes of one image decode + // at once, keep one file on disk. + final overlapping = await open('overlapping'); + await Future.wait([ + for (var i = 0; i < 2; i++) + overlapping.write('same', Uint8List(4), immutable: true), + ]); + final files = MediaDiskCache.directoryFor(root, 'overlapping', 's') + .listSync() + .where((entry) => !p.basename(entry.path).startsWith('index.json')); + expect(files, hasLength(1)); + await overlapping.dispose(); + + // One eviction pass returns at most its limit, oldest first, and asks + // for another pass. + final indexDirectory = MediaDiskCache.directoryFor(root, 'index', 's') + ..createSync(recursive: true); + final index = MediaCacheIndex( + File(p.join(indexDirectory.path, 'index.json')), + indexDirectory, + 0, + evictionsPerPass: 2, + ); + await index.open(); + final epoch = DateTime(2026); + for (var i = 0; i < 5; i++) { + await index.insert( + CacheObject( + 'url-$i', + relativePath: 'file-$i', + validTill: epoch, + length: 1, + touched: epoch.add(Duration(minutes: i)), + ), + setTouchedToNow: false, + ); + } + var morePasses = 0; + index.onMoreToEvict = () => morePasses++; + final firstPass = await index.getObjectsOverCapacity(100); + expect(firstPass.map((o) => o.url), ['url-1', 'url-0']); + expect(morePasses, 1); + // A retired index's pass in progress records no deletions. + final ids = [for (final o in await index.getAllObjects()) o.id!]; + index.retire(); + await index.deleteAll(ids); + expect(await index.getAllObjects(), hasLength(5)); + await index.close(); + + // Once closed, the index saves nothing more. A read that marks a file + // used, or an eviction pass that finishes late, would otherwise save + // it over the index a reopened cache wrote since. + final indexFile = File(p.join(indexDirectory.path, 'index.json')); + final reopenedIndex = MediaCacheIndex(indexFile, indexDirectory, 100); + await reopenedIndex.open(); + await reopenedIndex.insert( + CacheObject( + 'newer', + relativePath: 'file-newer', + validTill: epoch, + length: 1, + ), + ); + await reopenedIndex.close(); + final written = indexFile.readAsStringSync(); + await index.updateOrInsert( + CacheObject('late-read', relativePath: 'file-0', validTill: epoch), + ); + await index.deleteAll(ids); + await Future.delayed(const Duration(milliseconds: 50)); + expect(indexFile.readAsStringSync(), written); + + // So a large save into a cache full of small files evicts them over + // several passes, with no later reads to schedule them, until the + // directory is back in budget. + List filesIn(Directory directory) => [ + for (final entry in directory.listSync()) + if (!p.basename(entry.path).startsWith('index.json')) + p.basename(entry.path), + ]; + final passesDirectory = MediaDiskCache.directoryFor(root, 'passes', 's'); + final passes = MediaDiskCache.open( + passesDirectory, + byteBudget: 20, + evictionDelay: const Duration(milliseconds: 200), + evictionsPerPass: 2, + ); + for (var i = 0; i < 5; i++) { + await passes.write('small-$i', Uint8List(4), immutable: true); + await Future.delayed(const Duration(milliseconds: 5)); + } + await passes.write('large', Uint8List(16), immutable: true); + await _until(() async => filesIn(passesDirectory).length == 2); + expect(await passes.read('large'), isNotNull); + expect(await passes.read('small-4'), isNotNull); + await passes.dispose(); + + // Files the index doesn't track, such as a save cut short by a full + // disk or by the app exiting, are deleted on the next launch. + final sweptDirectory = MediaDiskCache.directoryFor(root, 'swept', 's'); + final first = MediaDiskCache.open(sweptDirectory); + await first.write('kept', Uint8List(4), immutable: true); + await first.dispose(); + final earlier = DateTime.now().subtract(const Duration(minutes: 1)); + for (final name in ['untracked.file', 'interrupted.file.part']) { + File(p.join(sweptDirectory.path, name)) + ..writeAsBytesSync(Uint8List(4)) + ..setLastModifiedSync(earlier); + } + // Closing waits for the sweep, so the next cache to open the directory + // starts after it. + final manyDirectory = MediaDiskCache.directoryFor(root, 'many', 's') + ..createSync(recursive: true); + for (var i = 0; i < 300; i++) { + File(p.join(manyDirectory.path, 'orphan-$i.file')) + ..writeAsBytesSync(Uint8List(1)) + ..setLastModifiedSync(earlier); + } + final manyIndex = MediaCacheIndex( + File(p.join(manyDirectory.path, 'index.json')), + manyDirectory, + 100, + ); + await manyIndex.open(); + await manyIndex.close(); + expect(filesIn(manyDirectory), isEmpty); + + // The sweep runs in the background, and a save made while it runs + // stays. + // A part written just now may belong to a save in progress, so it + // stays too. + final fresh = File(p.join(sweptDirectory.path, 'fresh.file.part')) + ..writeAsBytesSync(Uint8List(4)); + final relaunched = MediaDiskCache.open(sweptDirectory); + await relaunched.write('during', Uint8List(4), immutable: true); + expect(await relaunched.read('kept'), isNotNull); + await _until(() async => filesIn(sweptDirectory).length == 3); + expect(await relaunched.read('during'), isNotNull); + expect(fresh.existsSync(), isTrue); + await relaunched.dispose(); + + // A disposed cache's scheduled eviction pass, running after the + // community's cache was opened again, keeps the newer cache's saves. + final retiredDirectory = MediaDiskCache.directoryFor( + root, + 'retired', + 's', + ); + Future rows() async { + final index = File(p.join(retiredDirectory.path, 'index.json')); + return index.existsSync() + ? (jsonDecode(await index.readAsString()) as List).length + : 0; + } + + const passDelay = Duration(milliseconds: 300); + final retired = MediaDiskCache.open( + retiredDirectory, + byteBudget: 80, + evictionDelay: passDelay, + evictionsPerPass: 1, + ); + for (var i = 0; i < 6; i++) { + await retired.write('prior-$i', Uint8List(12), immutable: true); + await Future.delayed(const Duration(milliseconds: 5)); + } + // Two files over budget: the first pass evicts one and schedules + // another. + await retired.write('large', Uint8List(24), immutable: true); + await _until(() async => await rows() == 6); + // As the provider does, the old cache is disposed with a save and a + // read in progress, and not awaited before the reopen. + final inFlight = retired.write( + 'in-flight', + Uint8List(4), + immutable: true, + ); + final reading = retired.read('prior-3'); + await Future.delayed(Duration.zero); + final closing = retired.dispose(); + final reopened = MediaDiskCache.open(retiredDirectory, byteBudget: 80); + await reopened.write('newer', Uint8List(4), immutable: true); + await Future.wait([inFlight, reading, closing]); + await reopened.dispose(); + await Future.delayed(passDelay * 3); + final relaunchedAgain = MediaDiskCache.open( + retiredDirectory, + byteBudget: 80, + ); + expect(await relaunchedAgain.read('newer'), isNotNull); + expect(await relaunchedAgain.read('in-flight'), isNotNull); + // The old cache's next eviction would have taken it. + expect(await relaunchedAgain.read('prior-1'), isNotNull); + await relaunchedAgain.dispose(); + + // A cache reopened while the previous one is slow to close goes + // without the disk at first, then uses it once that close finishes. + final slowDirectory = MediaDiskCache.directoryFor(root, 'slow', 's'); + final saving = MediaDiskCache.open(slowDirectory); + await saving.write('saved', Uint8List(4), immutable: true); + await saving.dispose(); + final gated = _GatedDirectory(slowDirectory); + final slow = MediaDiskCache.open(gated); + // Opens the index, whose sweep then waits on the gate, and so does + // closing. + expect(await slow.read('saved'), isNotNull); + final slowSave = slow.write('slow-save', Uint8List(4), immutable: true); + await Future.delayed(Duration.zero); + final slowClosing = slow.dispose(); + const openTimeout = Duration(milliseconds: 100); + final waiting = MediaDiskCache.open( + slowDirectory, + openTimeout: openTimeout, + ); + expect(await waiting.read('saved'), isNull); + gated.release(); + await Future.wait([slowSave, slowClosing]); + await Future.delayed(Duration.zero); + expect(await waiting.read('saved'), isNotNull); + await waiting.write('after-close', Uint8List(4), immutable: true); + await waiting.dispose(); + final afterSlow = MediaDiskCache.open(slowDirectory); + expect(await afterSlow.read('after-close'), isNotNull); + expect(await afterSlow.read('slow-save'), isNotNull); + await afterSlow.dispose(); + + // Reads during refreshes see the old bytes or the new ones in full, + // never part of a file. + final refreshing = MediaDiskCache.open( + MediaDiskCache.directoryFor(root, 'refreshing', 's'), + ); + const sizes = [1024, 8 * 1024 * 1024]; + await refreshing.write('image', Uint8List(sizes[0]), immutable: false); + final lengths = {}; + Future refreshRepeatedly() async { + for (var i = 1; i <= 10; i++) { + await refreshing.write( + 'image', + Uint8List(sizes[i % 2]), + immutable: false, + ); + } + } + + // A bounded number of reads: each one marks the file used, and a + // reader that never stops keeps the index save, and so the refresh, + // from finishing. + Future readRepeatedly() async { + for (var i = 0; i < 20; i++) { + lengths.add((await refreshing.read('image'))?.bytes.length); + } + } + + await Future.wait([ + refreshRepeatedly(), + for (var i = 0; i < 3; i++) readRepeatedly(), + ]); + expect(lengths, everyElement(isIn(sizes))); + await refreshing.dispose(); }, ); @@ -500,3 +752,32 @@ Future _waitError(ImageStream stream) { stream.addListener(listener); return done.future; } + +/// [Directory] whose listing waits until [release], to hold a cache's +/// sweep, and so its close. +class _GatedDirectory implements Directory { + _GatedDirectory(this._inner); + + final Directory _inner; + final _gate = Completer(); + + void release() => _gate.complete(); + + @override + String get path => _inner.path; + + @override + Future exists() => _inner.exists(); + + @override + Stream list({ + bool recursive = false, + bool followLinks = true, + }) async* { + await _gate.future; + yield* _inner.list(recursive: recursive, followLinks: followLinks); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +}