From 227d40db46c5175eab523f481cb8d9e86efaa69a Mon Sep 17 00:00:00 2001 From: Ben Milanko Date: Sat, 14 Nov 2026 07:29:12 +1100 Subject: [PATCH] feat: cancel downloads per caller without breaking FileService Adds an optional CancellationToken to getFileStream, getSingleFile, downloadFile and ImageCacheManager.getImageFile. - FileService.get and BaseCacheManager keep their signatures. The token reaches the file service as CancellationToken.current, a zone value set with runScoped; HttpFileService aborts its request on it, and a service that ignores it is abandoned with its late body released. flutter_cache_manager_firebase compiles and passes unchanged. - Callers of the same url share one download through SharedCancellation, which gives each its own stream; the download (and a shared resize) stops only once every caller has cancelled, and a caller without a token keeps it alive. - A cancelled or failed download deletes its partial file. Downloads go to a fresh path, so the previously cached file stays valid. - The sink is closed when the response stream errors. - Tests cover mid-stream cancellation, a stream error, two callers on one url in both orders, every caller cancelling, a queued request, an already-cancelled token, a service that ignores the token, and the token through getFileStream, getSingleFile, downloadFile and getImageFile with and without resizing. Co-Authored-By: Claude Opus 5.5 --- flutter_cache_manager/CHANGELOG.md | 8 + flutter_cache_manager/README.md | 8 + .../lib/src/cache_manager.dart | 31 +- .../cache_managers/image_cache_manager.dart | 92 +++- .../lib/src/web/file_service.dart | 97 +++- .../lib/src/web/shared_cancellation.dart | 69 +++ .../lib/src/web/web_helper.dart | 271 +++++++++-- flutter_cache_manager/pubspec.yaml | 2 +- .../test/cancellation_test.dart | 450 ++++++++++++++++++ .../test/http_file_fetcher_test.dart | 89 ++++ flutter_cache_manager/test/mock.mocks.dart | 191 ++++---- .../test/web_helper_test.dart | 39 ++ 12 files changed, 1189 insertions(+), 158 deletions(-) create mode 100644 flutter_cache_manager/lib/src/web/shared_cancellation.dart create mode 100644 flutter_cache_manager/test/cancellation_test.dart diff --git a/flutter_cache_manager/CHANGELOG.md b/flutter_cache_manager/CHANGELOG.md index f1d60241..e0a5f627 100644 --- a/flutter_cache_manager/CHANGELOG.md +++ b/flutter_cache_manager/CHANGELOG.md @@ -1,3 +1,11 @@ +## [3.6.0] - 2026-11-14 + +* Adds an optional `CancellationToken` to `getFileStream`, `getSingleFile`, `downloadFile` and `ImageCacheManager.getImageFile`. Cancelling ends that call with a `CancelledException`. +* Applies cancellation per caller: callers that request the same url share one download, which stops only once every caller has cancelled. A caller without a token keeps the download running. +* Deletes the partial file of a cancelled or failed download. The previously cached file stays valid. +* Keeps `FileService.get` and `BaseCacheManager` unchanged: `HttpFileService` aborts its request on cancellation, and a custom `FileService` can read the token through `CancellationToken.current`. +* Closes the download sink when the response stream errors. + ## [3.5.0] - 2026-11-04 * **DEPRECATION** Deprecates `supportedFileNames`: whether an image is resized is now decided by the image engine from the file's content instead of from the file extension derived from the `Content-Type` header of the response ([#475](https://github.com/Baseflow/flutter_cache_manager/pull/475)) diff --git a/flutter_cache_manager/README.md b/flutter_cache_manager/README.md index d0e2df3e..77ca1066 100644 --- a/flutter_cache_manager/README.md +++ b/flutter_cache_manager/README.md @@ -85,6 +85,7 @@ class CustomCacheManager { - [How are the cache files stored?](#how-are-the-cache-files-stored) - [When are the cached files updated?](#when-are-the-cached-files-updated) - [When are cached files removed?](#when-are-cached-files-removed) +- [How do I cancel a download?](#how-do-i-cancel-a-download) ### How are the cache files stored? @@ -113,6 +114,13 @@ The cache knows when files have been used latest. When cleaning the cache (which deletes files when there are too many, ordered by last use, and when files just haven't been used for longer than the stale period. +### How do I cancel a download? +Pass a `CancellationToken` to `getFileStream`, `getSingleFile`, `downloadFile` or `ImageCacheManager.getImageFile` +and call `cancel()` on it. Cancellation applies per caller: when several callers request the same url they share one +download, which only stops once every caller has cancelled, and a caller without a token keeps it running. A +cancelled download's partial file is deleted and the previously cached file stays valid. A custom `FileService` +can read the token through `CancellationToken.current` to abort its own request. + ## Breaking changes in v2 - There is no longer a need to extend on BaseCacheManager, you can directly call the constructor. The BaseCacheManager diff --git a/flutter_cache_manager/lib/src/cache_manager.dart b/flutter_cache_manager/lib/src/cache_manager.dart index b700e1c7..e031e1e1 100644 --- a/flutter_cache_manager/lib/src/cache_manager.dart +++ b/flutter_cache_manager/lib/src/cache_manager.dart @@ -65,18 +65,27 @@ class CacheManager implements BaseCacheManager { /// When a file is cached and up to date it is return directly, when the cached /// file is too old the file is downloaded and returned after download. /// When a cached file is not available the newly downloaded file is returned. + /// A cancelled [cancellationToken] ends this call with a [CancelledException] + /// (see [CancellationToken]). @override Future getSingleFile( String url, { String? key, Map? headers, + CancellationToken? cancellationToken, }) async { key ??= url; + cancellationToken ??= CancellationToken.current; final cacheFile = await getFileFromCache(key); if (cacheFile != null && cacheFile.validTill.isAfter(DateTime.now())) { return cacheFile.file; } - return (await downloadFile(url, key: key, authHeaders: headers)).file; + return (await downloadFile( + url, + key: key, + authHeaders: headers, + cancellationToken: cancellationToken, + )).file; } /// Get the file from the cache and/or online, depending on availability and age. @@ -89,11 +98,13 @@ class CacheManager implements BaseCacheManager { String url, { String? key, Map? headers, + CancellationToken? cancellationToken, }) { return getFileStream( url, key: key, withProgress: false, + cancellationToken: cancellationToken, ).where((r) => r is FileInfo).cast(); } @@ -114,10 +125,21 @@ class CacheManager implements BaseCacheManager { String? key, Map? headers, bool withProgress = false, + CancellationToken? cancellationToken, }) { key ??= url; + // Callers that only see BaseCacheManager (such as ImageCacheManager) pass + // their token through CancellationToken.runScoped. + cancellationToken ??= CancellationToken.current; final streamController = StreamController(); - _pushFileToStream(streamController, url, key, headers, withProgress); + _pushFileToStream( + streamController, + url, + key, + headers, + withProgress, + cancellationToken, + ); return streamController.stream; } @@ -127,6 +149,7 @@ class CacheManager implements BaseCacheManager { String? key, Map? headers, bool withProgress, + CancellationToken? cancellationToken, ) async { key ??= url; FileInfo? cacheFile; @@ -148,6 +171,7 @@ class CacheManager implements BaseCacheManager { url, key: key, authHeaders: headers, + cancellationToken: cancellationToken, )) { if (response is DownloadProgress && withProgress) { streamController.add(response); @@ -185,14 +209,17 @@ class CacheManager implements BaseCacheManager { String? key, Map? authHeaders, bool force = false, + CancellationToken? cancellationToken, }) async { key ??= url; + cancellationToken ??= CancellationToken.current; final fileResponse = await _webHelper .downloadFile( url, key: key, authHeaders: authHeaders, ignoreMemCache: force, + cancellationToken: cancellationToken, ) .firstWhere((r) => r is FileInfo); return fileResponse as FileInfo; diff --git a/flutter_cache_manager/lib/src/cache_managers/image_cache_manager.dart b/flutter_cache_manager/lib/src/cache_managers/image_cache_manager.dart index 858ad146..c019e797 100644 --- a/flutter_cache_manager/lib/src/cache_managers/image_cache_manager.dart +++ b/flutter_cache_manager/lib/src/cache_managers/image_cache_manager.dart @@ -6,6 +6,7 @@ import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'package:flutter_cache_manager/src/web/shared_cancellation.dart'; /// Formats that used to be recognized by the extension of the file. /// @@ -36,13 +37,15 @@ mixin ImageCacheManager on BaseCacheManager { bool withProgress = false, int? maxHeight, int? maxWidth, + CancellationToken? cancellationToken, }) async* { if (maxHeight == null && maxWidth == null) { - yield* getFileStream( + yield* _getFileStream( url, key: key, headers: headers, withProgress: withProgress, + cancellationToken: cancellationToken, ); return; } @@ -60,24 +63,72 @@ mixin ImageCacheManager on BaseCacheManager { } withProgress = false; } - var runningResize = _runningResizes[resizedKey]; - if (runningResize == null) { - runningResize = _fetchedResizedFile( + var running = _runningResizes[resizedKey]; + if (running == null) { + final cancellation = SharedCancellation(); + final created = _RunningResize( + _fetchedResizedFile( + url, + key, + resizedKey, + headers, + withProgress, + cancellationToken: cancellation.token, + maxWidth: maxWidth, + maxHeight: maxHeight, + ).asBroadcastStream(), + cancellation, + ); + cancellation.onAllCancelled = () { + if (identical(_runningResizes[resizedKey], created)) { + _runningResizes.remove(resizedKey); + } + }; + _runningResizes[resizedKey] = created; + running = created; + } + // Each caller cancels only its own view; the resize (and the download + // behind it) stops once every caller has cancelled. + try { + yield* running.cancellation.join(running.stream, cancellationToken); + } finally { + // A caller that cancelled leaves the resize to the others. + final cancelled = cancellationToken?.isCancelled ?? false; + if (!cancelled && identical(_runningResizes[resizedKey], running)) { + _runningResizes.remove(resizedKey); + } + } + } + + /// [getFileStream] with [cancellationToken] applied. [BaseCacheManager] + /// does not take a token, so it is passed as [CancellationToken.current], + /// which [CacheManager] picks up. + Stream _getFileStream( + String url, { + String? key, + Map? headers, + bool withProgress = false, + CancellationToken? cancellationToken, + }) { + if (cancellationToken == null) { + return getFileStream( url, - key, - resizedKey, - headers, - withProgress, - maxWidth: maxWidth, - maxHeight: maxHeight, - ).asBroadcastStream(); - _runningResizes[resizedKey] = runningResize; + key: key, + headers: headers, + withProgress: withProgress, + ); } - yield* runningResize; - _runningResizes.remove(resizedKey); + return cancellationToken.runScoped( + () => getFileStream( + url, + key: key, + headers: headers, + withProgress: withProgress, + ), + ); } - final Map> _runningResizes = {}; + final Map _runningResizes = {}; /// Keys whose original file is known not to be resizable: it is not an /// image the engine can decode, it is animated, or it already fits within @@ -97,12 +148,14 @@ mixin ImageCacheManager on BaseCacheManager { bool withProgress, { int? maxWidth, int? maxHeight, + CancellationToken? cancellationToken, }) async* { - await for (final response in getFileStream( + await for (final response in _getFileStream( url, key: originalKey, headers: headers, withProgress: withProgress, + cancellationToken: cancellationToken, )) { if (response is DownloadProgress) { yield response; @@ -296,3 +349,10 @@ void _logResizeWarning(File file, Object error) { CacheManagerLogLevel.warning, ); } + +class _RunningResize { + _RunningResize(this.stream, this.cancellation); + + final Stream stream; + final SharedCancellation cancellation; +} diff --git a/flutter_cache_manager/lib/src/web/file_service.dart b/flutter_cache_manager/lib/src/web/file_service.dart index 174f69a6..a6f9e21c 100644 --- a/flutter_cache_manager/lib/src/web/file_service.dart +++ b/flutter_cache_manager/lib/src/web/file_service.dart @@ -9,6 +9,73 @@ import 'package:http/http.dart' as http; ///Copyright (c) 2019 Rene Floor ///Released under MIT License. +/// Token that cancels a request made through a cache manager. +/// +/// Pass it to [CacheManager.getFileStream], [CacheManager.getSingleFile], +/// [CacheManager.downloadFile] or `ImageCacheManager.getImageFile`. +/// Cancellation applies to that caller only: the caller's stream ends with a +/// [CancelledException], and a download shared with other callers keeps +/// running until every caller has cancelled. +/// +/// While a download runs, the token that stops it is available to the +/// [FileService] as [CancellationToken.current], so a service can abort its +/// request without any change to [FileService.get]'s signature. +class CancellationToken { + bool _isCancelled = false; + Completer? _completer; + + static final Object _zoneKey = Object(); + + /// The token of the download the current [FileService.get] call belongs to, + /// or null when the request cannot be cancelled. + static CancellationToken? get current => + Zone.current[_zoneKey] as CancellationToken?; + + /// Runs [body] with this token as [current]. + R runScoped(R Function() body) => + runZoned(body, zoneValues: {_zoneKey: this}); + + /// Whether this token has been cancelled. + bool get isCancelled => _isCancelled; + + /// Cancel the request associated with this token. + void cancel() { + if (_isCancelled) return; + _isCancelled = true; + if (_completer != null && !_completer!.isCompleted) { + _completer!.complete(); + } + } + + /// A future that completes when this token is cancelled. + Future get whenCancelled { + if (_completer == null) { + _completer = Completer(); + if (_isCancelled) { + _completer!.complete(); + } + } + return _completer!.future; + } + + /// Throws a [CancelledException] when this token has been cancelled. + void throwIfCancelled() { + if (_isCancelled) throw CancelledException(); + } +} + +/// Exception thrown when a request is cancelled. +class CancelledException implements Exception { + /// Creates a new [CancelledException] with an optional message. + CancelledException([this.message = 'Request was cancelled']); + + /// The error message. + final String message; + + @override + String toString() => 'CancelledException: $message'; +} + /// Defines the interface for a file service. /// Most common file service will be an [HttpFileService], however one can /// also make something more specialized. For example you could fetch files @@ -16,6 +83,11 @@ import 'package:http/http.dart' as http; abstract class FileService { int concurrentFetches = 10; + /// Fetches [url], sending [headers] with the request. + /// + /// When the download is cancelled by all of its callers, + /// [CancellationToken.current] is cancelled; implementations may use it to + /// abort the request. Ignoring it is safe: the response is then discarded. Future get(String url, {Map? headers}); } @@ -32,13 +104,32 @@ class HttpFileService extends FileService { String url, { Map? headers, }) async { - final req = http.Request('GET', Uri.parse(url)); + final cancellationToken = CancellationToken.current; + if (cancellationToken?.isCancelled ?? false) { + throw CancelledException(); + } + + final http.BaseRequest req; + if (cancellationToken != null) { + req = http.AbortableRequest( + 'GET', + Uri.parse(url), + abortTrigger: cancellationToken.whenCancelled, + ); + } else { + req = http.Request('GET', Uri.parse(url)); + } + if (headers != null) { req.headers.addAll(headers); } - final httpResponse = await _httpClient.send(req); - return HttpGetResponse(httpResponse, req.url); + try { + final httpResponse = await _httpClient.send(req); + return HttpGetResponse(httpResponse, req.url); + } on http.RequestAbortedException { + throw CancelledException(); + } } } diff --git a/flutter_cache_manager/lib/src/web/shared_cancellation.dart b/flutter_cache_manager/lib/src/web/shared_cancellation.dart new file mode 100644 index 00000000..98918bb7 --- /dev/null +++ b/flutter_cache_manager/lib/src/web/shared_cancellation.dart @@ -0,0 +1,69 @@ +import 'dart:async'; + +import 'package:flutter_cache_manager/src/web/file_service.dart'; + +/// Tracks the callers that share one piece of work, such as a download, and +/// cancels [token] once every caller has cancelled. +/// +/// A caller that joins without a token cannot cancel, so it keeps the work +/// alive until the work completes on its own. +class SharedCancellation { + /// The token that stops the shared work. + final CancellationToken token = CancellationToken(); + + /// Called once, when the last caller cancels. + void Function()? onAllCancelled; + + int _callers = 0; + + /// Gives a caller its own view of [source]. + /// + /// When [callerToken] is cancelled, only this caller's stream ends, with a + /// [CancelledException]. The shared work is cancelled when no caller is + /// left. + Stream join(Stream source, CancellationToken? callerToken) { + _callers++; + if (callerToken == null) return source; + + StreamSubscription? subscription; + var finished = false; + final controller = StreamController(); + + void leave() { + _callers--; + if (_callers == 0 && !token.isCancelled) { + token.cancel(); + onAllCancelled?.call(); + } + } + + controller + ..onListen = () { + if (finished) return; + subscription = source.listen( + controller.add, + onError: controller.addError, + onDone: () { + finished = true; + controller.close(); + }, + ); + } + ..onPause = (() => subscription?.pause()) + ..onResume = (() => subscription?.resume()) + ..onCancel = () => subscription?.cancel(); + + callerToken.whenCancelled.then((_) { + if (finished) return; + finished = true; + final pending = subscription; + subscription = null; + pending?.cancel(); + controller.addError(CancelledException()); + controller.close(); + leave(); + }); + + return controller.stream; + } +} diff --git a/flutter_cache_manager/lib/src/web/web_helper.dart b/flutter_cache_manager/lib/src/web/web_helper.dart index 5fe120e3..46e39996 100644 --- a/flutter_cache_manager/lib/src/web/web_helper.dart +++ b/flutter_cache_manager/lib/src/web/web_helper.dart @@ -7,6 +7,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_cache_manager/src/cache_store.dart'; import 'package:flutter_cache_manager/src/web/queue_item.dart'; +import 'package:flutter_cache_manager/src/web/shared_cancellation.dart'; import 'package:rxdart/rxdart.dart'; import 'package:uuid/uuid.dart'; @@ -25,36 +26,69 @@ class WebHelper { final CacheStore _store; @visibleForTesting final FileService fileFetcher; - final Map> _memCache; - final Queue _queue = Queue(); + final Map _memCache; + final Queue<_QueuedDownload> _queue = Queue(); ///Download the file from the url + /// + /// Callers asking for the same [key] share one download. A caller that + /// passes a [cancellationToken] and cancels it gets a [CancelledException] + /// on its own stream; the download itself only stops once every caller + /// sharing it has cancelled. Stream downloadFile( String url, { String? key, Map? authHeaders, bool ignoreMemCache = false, + CancellationToken? cancellationToken, }) { - key ??= url; - var subject = _memCache[key]; - if (subject == null || ignoreMemCache) { - subject = BehaviorSubject(); - _memCache[key] = subject; - _downloadOrAddToQueue(url, key, authHeaders); + final cacheKey = key ?? url; + if (cancellationToken?.isCancelled ?? false) { + return Stream.error(CancelledException()); } - return subject.stream; + var download = _memCache[cacheKey]; + if (download == null || ignoreMemCache) { + final created = _Download(); + created.cancellation.onAllCancelled = () => _abandon(cacheKey, created); + _memCache[cacheKey] = created; + download = created; + _downloadOrAddToQueue(url, cacheKey, authHeaders, created); + } + return download.cancellation.join( + download.subject.stream, + cancellationToken, + ); } var concurrentCalls = 0; + /// Every caller of [download] has cancelled: stop sharing it, and drop it + /// from the queue if it has not started yet. A running download notices its + /// cancelled token itself. + void _abandon(String key, _Download download) { + if (identical(_memCache[key], download)) _memCache.remove(key); + final wasQueued = _queue.any((item) => identical(item.download, download)); + if (wasQueued) { + _queue.removeWhere((item) => identical(item.download, download)); + download.fail(CancelledException()); + } + } + Future _downloadOrAddToQueue( String url, String key, Map? authHeaders, + _Download download, ) async { + if (download.cancellation.token.isCancelled) { + _forget(key, download); + download.fail(CancelledException()); + return; + } + //Add to queue if there are too many calls. if (concurrentCalls >= fileFetcher.concurrentFetches) { - _queue.add(QueueItem(url, key, authHeaders)); + _queue.add(_QueuedDownload(QueueItem(url, key, authHeaders), download)); return; } cacheLogger.log( @@ -63,12 +97,13 @@ class WebHelper { ); concurrentCalls++; - final subject = _memCache[key]!; + final subject = download.subject; try { await for (final result in _updateFile( url, key, authHeaders: authHeaders, + cancellationToken: download.cancellation.token, )) { subject.add(result); } @@ -77,15 +112,24 @@ class WebHelper { } finally { concurrentCalls--; await subject.close(); - _memCache.remove(key); + _forget(key, download); _checkQueue(); } } + void _forget(String key, _Download download) { + if (identical(_memCache[key], download)) _memCache.remove(key); + } + void _checkQueue() { if (_queue.isEmpty) return; final next = _queue.removeFirst(); - _downloadOrAddToQueue(next.url, next.key, next.headers); + _downloadOrAddToQueue( + next.item.url, + next.item.key, + next.item.headers, + next.download, + ); } ///Download the file from the url @@ -93,8 +137,20 @@ class WebHelper { String url, String key, { Map? authHeaders, + CancellationToken? cancellationToken, }) async* { + // Check cancellation before any work + if (cancellationToken?.isCancelled ?? false) { + throw CancelledException(); + } + var cacheObject = await _store.retrieveCacheData(key); + + // Check cancellation after async work + if (cancellationToken?.isCancelled ?? false) { + throw CancelledException(); + } + cacheObject = cacheObject == null ? CacheObject( url, @@ -103,13 +159,24 @@ class WebHelper { relativePath: '${const Uuid().v1()}.file', ) : cacheObject.copyWith(url: url); - final response = await _download(cacheObject, authHeaders); - yield* _manageResponse(cacheObject, response); + final response = await _download( + cacheObject, + authHeaders, + cancellationToken, + ); + + // Check cancellation after download + if (cancellationToken?.isCancelled ?? false) { + throw CancelledException(); + } + + yield* _manageResponse(cacheObject, response, cancellationToken); } Future _download( CacheObject cacheObject, Map? authHeaders, + CancellationToken? cancellationToken, ) { final headers = {}; @@ -124,13 +191,60 @@ class WebHelper { headers.addAll(authHeaders); } - return fileFetcher.get(cacheObject.url, headers: headers); + if (cancellationToken == null) { + return fileFetcher.get(cacheObject.url, headers: headers); + } + final request = cancellationToken.runScoped( + () => fileFetcher.get(cacheObject.url, headers: headers), + ); + return _untilCancelled(request, cancellationToken); + } + + /// Completes with [request], or with a [CancelledException] as soon as + /// [token] is cancelled, for file services that do not abort on + /// [CancellationToken.current]. A response that arrives after cancelling is + /// discarded. + Future _untilCancelled( + Future request, + CancellationToken token, + ) { + final result = Completer(); + request.then( + (response) { + if (result.isCompleted) { + _discard(response); + } else { + result.complete(response); + } + }, + onError: (Object error, StackTrace stackTrace) { + if (!result.isCompleted) result.completeError(error, stackTrace); + }, + ); + token.whenCancelled.then((_) { + if (!result.isCompleted) result.completeError(CancelledException()); + }); + return result.future; + } + + void _discard(FileServiceResponse response) { + try { + response.content.listen(null, onError: (Object _) {}).cancel(); + } on Object { + // Nothing to release. + } } Stream _manageResponse( CacheObject cacheObject, FileServiceResponse response, + CancellationToken? cancellationToken, ) async* { + // Check cancellation at start + if (cancellationToken?.isCancelled ?? false) { + throw CancelledException(); + } + final hasNewFile = statusCodesNewFile.contains(response.statusCode); final keepOldFile = statusCodesFileNotChanged.contains(response.statusCode); if (!hasNewFile && !keepOldFile) { @@ -143,24 +257,30 @@ class WebHelper { final oldCacheObject = cacheObject; var newCacheObject = _setDataFromHeaders(cacheObject, response); - if (statusCodesNewFile.contains(response.statusCode)) { - var savedBytes = 0; - await for (final progress in _saveFile(newCacheObject, response)) { - savedBytes = progress; - yield DownloadProgress( - cacheObject.url, - response.contentLength, - progress, - ); + try { + if (hasNewFile) { + var savedBytes = 0; + await for (final progress in _saveFile( + newCacheObject, + response, + cancellationToken, + )) { + cancellationToken?.throwIfCancelled(); + savedBytes = progress; + yield DownloadProgress( + cacheObject.url, + response.contentLength, + progress, + ); + } + newCacheObject = newCacheObject.copyWith(length: savedBytes); } - newCacheObject = newCacheObject.copyWith(length: savedBytes); - } - try { + cancellationToken?.throwIfCancelled(); await _store.putFile(newCacheObject); - } catch (e) { - if (statusCodesNewFile.contains(response.statusCode)) { - await _removeOldFile(newCacheObject.relativePath); + } catch (_) { + if (hasNewFile) { + await _discardPartialFile(newCacheObject); } rethrow; } @@ -171,6 +291,9 @@ class WebHelper { final file = await _store.fileSystem.createFile( newCacheObject.relativePath, ); + if (cancellationToken?.isCancelled ?? false) { + throw CancelledException(); + } yield FileInfo( file, FileSource.Online, @@ -202,12 +325,17 @@ class WebHelper { ); } - Stream _saveFile(CacheObject cacheObject, FileServiceResponse response) { + Stream _saveFile( + CacheObject cacheObject, + FileServiceResponse response, + CancellationToken? cancellationToken, + ) { final receivedBytesResultController = StreamController(); _saveFileAndPostUpdates( receivedBytesResultController, cacheObject, response, + cancellationToken, ); return receivedBytesResultController.stream; } @@ -216,25 +344,65 @@ class WebHelper { StreamController receivedBytesResultController, CacheObject cacheObject, FileServiceResponse response, + CancellationToken? cancellationToken, ) async { - final file = await _store.fileSystem.createFile(cacheObject.relativePath); - + IOSink? sink; + StreamSubscription>? subscription; try { + final file = await _store.fileSystem.createFile(cacheObject.relativePath); + cancellationToken?.throwIfCancelled(); + final openSink = sink = file.openWrite(); + final done = Completer(); var receivedBytes = 0; - final sink = file.openWrite(); - await response.content - .map((s) { - receivedBytes += s.length; - receivedBytesResultController.add(receivedBytes); - return s; - }) - .pipe(sink); + subscription = response.content.listen( + (chunk) { + receivedBytes += chunk.length; + openSink.add(chunk); + receivedBytesResultController.add(receivedBytes); + }, + onError: (Object e, StackTrace stackTrace) { + if (!done.isCompleted) done.completeError(e, stackTrace); + }, + onDone: () { + if (!done.isCompleted) done.complete(); + }, + cancelOnError: true, + ); + cancellationToken?.whenCancelled.then((_) { + if (!done.isCompleted) done.completeError(CancelledException()); + }); + await done.future; + subscription = null; + await openSink.close(); } on Object catch (e, stacktrace) { + // Stop reading and release the sink, whatever went wrong. The partial + // file is removed by _manageResponse. + await subscription?.cancel(); + try { + await sink?.close(); + } on Object { + // The original error is the one to report. + } receivedBytesResultController.addError(e, stacktrace); } await receivedBytesResultController.close(); } + /// Removes the file of a download that did not complete. A new download + /// is always written to a new path, so the previously cached file (and its + /// cache info) stays valid and is left alone. + Future _discardPartialFile(CacheObject newCacheObject) async { + try { + await _removeOldFile(newCacheObject.relativePath); + } on Object catch (e) { + cacheLogger.log( + 'CacheManager: Failed to remove incomplete download ' + '${newCacheObject.relativePath}: $e', + CacheManagerLogLevel.warning, + ); + } + } + Future _removeOldFile(String? relativePath) async { if (relativePath == null) return; final file = await _store.fileSystem.createFile(relativePath); @@ -254,3 +422,22 @@ class HttpExceptionWithStatus extends HttpException { final int statusCode; } + +/// One download shared by every caller asking for the same key. +class _Download { + final BehaviorSubject subject = BehaviorSubject(); + final SharedCancellation cancellation = SharedCancellation(); + + void fail(Object error) { + if (subject.isClosed) return; + subject.addError(error); + subject.close(); + } +} + +class _QueuedDownload { + _QueuedDownload(this.item, this.download); + + final QueueItem item; + final _Download download; +} diff --git a/flutter_cache_manager/pubspec.yaml b/flutter_cache_manager/pubspec.yaml index 49ca35b2..4ddc627c 100644 --- a/flutter_cache_manager/pubspec.yaml +++ b/flutter_cache_manager/pubspec.yaml @@ -1,6 +1,6 @@ name: flutter_cache_manager description: Generic cache manager for flutter. Saves web files on the storages of the device and saves the cache info using sqflite. -version: 3.5.0 +version: 3.6.0 homepage: https://github.com/Baseflow/flutter_cache_manager topics: - cache diff --git a/flutter_cache_manager/test/cancellation_test.dart b/flutter_cache_manager/test/cancellation_test.dart new file mode 100644 index 00000000..a84af4af --- /dev/null +++ b/flutter_cache_manager/test/cancellation_test.dart @@ -0,0 +1,450 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:clock/clock.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'package:flutter_cache_manager/src/cache_store.dart'; +import 'package:flutter_cache_manager/src/web/web_helper.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; + +import 'helpers/mock_cache_info_repository.dart'; +import 'helpers/test_configuration.dart'; +import 'test_images.dart'; + +void main() { + late ControlledFileService fileService; + late MockCacheInfoRepository repo; + late TestFileSystem fileSystem; + late Config config; + + setUp(() { + fileService = ControlledFileService(); + repo = MockCacheInfoRepository(); + fileSystem = TestFileSystem(); + config = Config( + 'test', + fileSystem: fileSystem, + repo: repo, + fileService: fileService, + ); + }); + + Future> filesOnDisk() async { + final dir = await fileSystem.directoryFuture; + return dir.listSync().map((e) => e.basename).toList(); + } + + group('WebHelper', () { + test('mid-stream cancellation stops the response and removes the ' + 'partial file', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final webHelper = WebHelper(CacheStore(config), fileService); + final token = CancellationToken(); + + final events = webHelper + .downloadFile('https://a.test/image', cancellationToken: token) + .toList(); + final failure = expectLater(events, throwsA(isA())); + + await pumpEventQueue(); + response.controller.add([1, 2, 3]); + await pumpEventQueue(); + expect(await filesOnDisk(), hasLength(1)); + + token.cancel(); + await failure; + await pumpEventQueue(); + + expect(response.listenerCancelled, isTrue); + expect(fileService.tokens.single!.isCancelled, isTrue); + expect(await filesOnDisk(), isEmpty); + }); + + test('a failing response stream closes the download and removes the ' + 'partial file', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final webHelper = WebHelper(CacheStore(config), fileService); + + final failure = expectLater( + webHelper.downloadFile('https://a.test/image').toList(), + throwsA(isA()), + ); + await pumpEventQueue(); + response.controller.add([1, 2, 3]); + response.controller.addError(StateError('connection reset')); + await failure; + await pumpEventQueue(); + + expect(await filesOnDisk(), isEmpty); + verifyNever(repo.updateOrInsert(any)); + }); + + test('cancelling a refresh keeps the previously cached file and its ' + 'cache info', () async { + final existing = CacheObject( + 'https://a.test/image', + key: 'https://a.test/image', + relativePath: 'existing.jpg', + validTill: clock.now().subtract(const Duration(days: 1)), + id: 7, + ); + when(repo.get(any)).thenAnswer((_) async => existing); + final old = await fileSystem.createFile('existing.jpg'); + await old.writeAsBytes([9, 9, 9]); + + final response = StreamingResponse(fileExtension: '.jpg'); + fileService.handler = (_) async => response; + final webHelper = WebHelper(CacheStore(config), fileService); + final token = CancellationToken(); + + final failure = expectLater( + webHelper + .downloadFile('https://a.test/image', cancellationToken: token) + .toList(), + throwsA(isA()), + ); + await pumpEventQueue(); + response.controller.add([1]); + await pumpEventQueue(); + token.cancel(); + await failure; + await pumpEventQueue(); + + expect(await filesOnDisk(), ['existing.jpg']); + verifyNever(repo.deleteAll(any)); + verifyNever(repo.delete(any)); + }); + + test('one caller cancelling does not affect another caller of the same ' + 'url', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final webHelper = WebHelper(CacheStore(config), fileService); + final tokenA = CancellationToken(); + + final a = webHelper + .downloadFile('https://a.test/image', cancellationToken: tokenA) + .toList(); + final b = webHelper.downloadFile('https://a.test/image').toList(); + final aFails = expectLater(a, throwsA(isA())); + + await pumpEventQueue(); + tokenA.cancel(); + await aFails; + + response.controller.add([1, 2, 3]); + await response.controller.close(); + final bEvents = await b; + + expect(bEvents.whereType(), hasLength(1)); + expect(fileService.requests, hasLength(1)); + expect(fileService.tokens.single!.isCancelled, isFalse); + }); + + test('a caller without a token is not affected by, and does not ignore, ' + 'a later caller cancelling', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final webHelper = WebHelper(CacheStore(config), fileService); + final tokenB = CancellationToken(); + + final a = webHelper.downloadFile('https://a.test/image').toList(); + final b = webHelper + .downloadFile('https://a.test/image', cancellationToken: tokenB) + .toList(); + final bFails = expectLater(b, throwsA(isA())); + + await pumpEventQueue(); + tokenB.cancel(); + await bFails; + + response.controller.add([1, 2, 3]); + await response.controller.close(); + expect((await a).whereType(), hasLength(1)); + }); + + test('the shared download stops once every caller has cancelled', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final webHelper = WebHelper(CacheStore(config), fileService); + final tokenA = CancellationToken(); + final tokenB = CancellationToken(); + + final a = webHelper + .downloadFile('https://a.test/image', cancellationToken: tokenA) + .toList(); + final b = webHelper + .downloadFile('https://a.test/image', cancellationToken: tokenB) + .toList(); + final aFails = expectLater(a, throwsA(isA())); + final bFails = expectLater(b, throwsA(isA())); + await pumpEventQueue(); + + tokenA.cancel(); + await aFails; + expect(fileService.tokens.single!.isCancelled, isFalse); + + tokenB.cancel(); + await bFails; + await pumpEventQueue(); + expect(fileService.tokens.single!.isCancelled, isTrue); + expect(response.listenerCancelled, isTrue); + + // A new caller starts a fresh download instead of joining the dead one. + final next = StreamingResponse(); + fileService.handler = (_) async => next; + final c = webHelper.downloadFile('https://a.test/image').toList(); + await pumpEventQueue(); + next.controller.add([1]); + await next.controller.close(); + expect((await c).whereType(), hasLength(1)); + expect(fileService.requests, hasLength(2)); + }); + + test('cancelling a queued request removes it from the queue', () async { + fileService.concurrentFetches = 1; + final first = StreamingResponse(); + fileService.handler = (_) async => first; + final webHelper = WebHelper(CacheStore(config), fileService); + final token = CancellationToken(); + + final running = webHelper.downloadFile('https://a.test/first').toList(); + final queued = webHelper + .downloadFile('https://a.test/second', cancellationToken: token) + .toList(); + final queuedFails = expectLater( + queued, + throwsA(isA()), + ); + await pumpEventQueue(); + expect(fileService.requests, ['https://a.test/first']); + + token.cancel(); + await queuedFails; + + first.controller.add([1]); + await first.controller.close(); + await running; + await pumpEventQueue(); + expect(fileService.requests, ['https://a.test/first']); + }); + + test('an already cancelled token never starts a download', () async { + fileService.handler = (_) async => StreamingResponse(); + final webHelper = WebHelper(CacheStore(config), fileService); + final token = CancellationToken()..cancel(); + + await expectLater( + webHelper + .downloadFile('https://a.test/image', cancellationToken: token) + .toList(), + throwsA(isA()), + ); + expect(fileService.requests, isEmpty); + }); + + test( + 'a file service that ignores the token is abandoned on cancel', + () async { + final pending = Completer(); + fileService.handler = (_) => pending.future; + final webHelper = WebHelper(CacheStore(config), fileService); + final token = CancellationToken(); + + final failure = expectLater( + webHelper + .downloadFile('https://a.test/image', cancellationToken: token) + .toList(), + throwsA(isA()), + ); + await pumpEventQueue(); + token.cancel(); + await failure; + + // The late response is discarded: its body is never read into a file. + final late = StreamingResponse(); + pending.complete(late); + await pumpEventQueue(); + expect(late.listenerCancelled, isTrue); + expect(await filesOnDisk(), isEmpty); + }, + ); + }); + + group('CacheManager', () { + test('getFileStream passes the token to the download', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final cacheManager = TestImageCacheManager(config); + final token = CancellationToken(); + + final failure = expectLater( + cacheManager + .getFileStream('https://a.test/image', cancellationToken: token) + .toList(), + throwsA(isA()), + ); + await pumpEventQueue(); + expect(fileService.tokens.single, isNotNull); + + token.cancel(); + await failure; + expect(fileService.tokens.single!.isCancelled, isTrue); + }); + + test('getSingleFile with a cancelled token throws without ' + 'downloading', () async { + fileService.handler = (_) async => StreamingResponse(); + final cacheManager = TestImageCacheManager(config); + + await expectLater( + cacheManager.getSingleFile( + 'https://a.test/image', + cancellationToken: CancellationToken()..cancel(), + ), + throwsA(isA()), + ); + expect(fileService.requests, isEmpty); + }); + + test('downloadFile passes the token to the download', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final cacheManager = TestImageCacheManager(config); + final token = CancellationToken(); + + final failure = expectLater( + cacheManager.downloadFile( + 'https://a.test/image', + cancellationToken: token, + ), + throwsA(isA()), + ); + await pumpEventQueue(); + token.cancel(); + await failure; + expect(fileService.tokens.single!.isCancelled, isTrue); + }); + }); + + group('ImageCacheManager', () { + test('getImageFile without resizing passes the token through', () async { + final response = StreamingResponse(); + fileService.handler = (_) async => response; + final cacheManager = TestImageCacheManager(config); + final token = CancellationToken(); + + final failure = expectLater( + cacheManager + .getImageFile('https://a.test/image', cancellationToken: token) + .toList(), + throwsA(isA()), + ); + await pumpEventQueue(); + token.cancel(); + await failure; + expect(fileService.tokens.single!.isCancelled, isTrue); + }); + + test('a resize shared by two callers keeps running for the caller that ' + 'did not cancel', () async { + final response = StreamingResponse(fileExtension: '.png'); + fileService.handler = (_) async => response; + final cacheManager = TestImageCacheManager(config); + final token = CancellationToken(); + + final a = cacheManager + .getImageFile( + 'https://a.test/image', + maxWidth: 10, + cancellationToken: token, + ) + .toList(); + final b = cacheManager + .getImageFile('https://a.test/image', maxWidth: 10) + .toList(); + final aFails = expectLater(a, throwsA(isA())); + await pumpEventQueue(); + + token.cancel(); + await aFails; + expect(fileService.tokens.single!.isCancelled, isFalse); + + response.controller.add(base64Decode(imagePng120)); + await response.controller.close(); + expect((await b).whereType(), hasLength(1)); + }); + + test('a resize stops its download once its only caller cancels', () async { + final response = StreamingResponse(fileExtension: '.png'); + fileService.handler = (_) async => response; + final cacheManager = TestImageCacheManager(config); + final token = CancellationToken(); + + final failure = expectLater( + cacheManager + .getImageFile( + 'https://a.test/image', + maxWidth: 10, + cancellationToken: token, + ) + .toList(), + throwsA(isA()), + ); + await pumpEventQueue(); + token.cancel(); + await failure; + await pumpEventQueue(); + expect(fileService.tokens.single!.isCancelled, isTrue); + }); + }); +} + +class TestImageCacheManager extends CacheManager with ImageCacheManager { + TestImageCacheManager(super.config) : super.custom(); +} + +/// A file service whose responses the test controls. Records each request +/// and the [CancellationToken.current] it ran with. +class ControlledFileService extends FileService { + final requests = []; + final tokens = []; + late Future Function(String url) handler; + + @override + Future get(String url, {Map? headers}) { + requests.add(url); + tokens.add(CancellationToken.current); + return handler(url); + } +} + +class StreamingResponse implements FileServiceResponse { + StreamingResponse({this.fileExtension = '.bin'}) { + controller.onCancel = () => listenerCancelled = true; + } + + final controller = StreamController>(); + bool listenerCancelled = false; + + @override + Stream> get content => controller.stream; + + @override + int? get contentLength => null; + + @override + String? get eTag => null; + + @override + final String fileExtension; + + @override + int get statusCode => 200; + + @override + DateTime get validTill => clock.now().add(const Duration(days: 1)); +} diff --git a/flutter_cache_manager/test/http_file_fetcher_test.dart b/flutter_cache_manager/test/http_file_fetcher_test.dart index 93952247..3cd58755 100644 --- a/flutter_cache_manager/test/http_file_fetcher_test.dart +++ b/flutter_cache_manager/test/http_file_fetcher_test.dart @@ -398,4 +398,93 @@ void main() { }); }); }); + + group('Cancellation', () { + test('CancellationToken basic functionality', () { + final token = CancellationToken(); + expect(token.isCancelled, false); + + token.cancel(); + expect(token.isCancelled, true); + }); + + test('CancellationToken whenCancelled completes after cancel', () async { + final token = CancellationToken(); + final future = token.whenCancelled; + + token.cancel(); + await future; + expect(token.isCancelled, true); + }); + + test( + 'CancellationToken whenCancelled completes immediately if already cancelled', + () async { + final token = CancellationToken(); + token.cancel(); + + final future = token.whenCancelled; + await future; + expect(token.isCancelled, true); + }, + ); + + test( + 'HttpFileService throws CancelledException when token is cancelled before request', + () async { + final token = CancellationToken(); + token.cancel(); + + final client = MockClient((request) async { + return Response.bytes(Uint8List(16), 200); + }); + + final httpFileFetcher = HttpFileService(httpClient: client); + + expect( + () => token.runScoped(() => httpFileFetcher.get('test.com/image')), + throwsA(isA()), + ); + }, + ); + + test( + 'HttpFileService completes normally if cancelled after response received', + () async { + final token = CancellationToken(); + + final client = MockClient((request) async { + return Response.bytes(Uint8List(16), 200); + }); + + final httpFileFetcher = HttpFileService(httpClient: client); + + // Complete the request first + final response = await token.runScoped( + () => httpFileFetcher.get('http://test.com/image'), + ); + + // Cancelling after response is received has no effect + token.cancel(); + + expect(response.statusCode, 200); + }, + ); + + test('HttpFileService works normally without cancellation token', () async { + final client = MockClient((request) async { + return Response.bytes( + Uint8List(16), + 200, + headers: {'content-type': 'image/jpeg'}, + ); + }); + + final httpFileFetcher = HttpFileService(httpClient: client); + final response = await httpFileFetcher.get('test.com/image'); + + expect(response.statusCode, 200); + expect(response.contentLength, 16); + }); + }); } diff --git a/flutter_cache_manager/test/mock.mocks.dart b/flutter_cache_manager/test/mock.mocks.dart index a1496764..b414ad68 100644 --- a/flutter_cache_manager/test/mock.mocks.dart +++ b/flutter_cache_manager/test/mock.mocks.dart @@ -1,16 +1,16 @@ -// Mocks generated by Mockito 5.4.6 from annotations +// Mocks generated by Mockito from annotations // in flutter_cache_manager/test/mock.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i4; -import 'package:flutter_cache_manager/flutter_cache_manager.dart' as _i3; -import 'package:flutter_cache_manager/src/cache_store.dart' as _i5; -import 'package:flutter_cache_manager/src/storage/cache_object.dart' as _i2; -import 'package:flutter_cache_manager/src/web/web_helper.dart' as _i7; +import 'dart:async' as _i3; + +import 'package:flutter_cache_manager/flutter_cache_manager.dart' as _i2; +import 'package:flutter_cache_manager/src/cache_store.dart' as _i4; +import 'package:flutter_cache_manager/src/web/web_helper.dart' as _i6; import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i6; +import 'package:mockito/src/dummies.dart' as _i5; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -18,6 +18,7 @@ import 'package:mockito/src/dummies.dart' as _i6; // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: experimental_member_use // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: must_be_immutable @@ -37,7 +38,7 @@ class _FakeDuration_1 extends _i1.SmartFake implements Duration { : super(parent, parentInvocation); } -class _FakeFileSystem_2 extends _i1.SmartFake implements _i3.FileSystem { +class _FakeFileSystem_2 extends _i1.SmartFake implements _i2.FileSystem { _FakeFileSystem_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -48,12 +49,12 @@ class _FakeDateTime_3 extends _i1.SmartFake implements DateTime { } class _FakeFileServiceResponse_4 extends _i1.SmartFake - implements _i3.FileServiceResponse { + implements _i2.FileServiceResponse { _FakeFileServiceResponse_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFileService_5 extends _i1.SmartFake implements _i3.FileService { +class _FakeFileService_5 extends _i1.SmartFake implements _i2.FileService { _FakeFileService_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -62,37 +63,37 @@ class _FakeFileService_5 extends _i1.SmartFake implements _i3.FileService { /// /// See the documentation for Mockito's code generation for more information. class MockCacheInfoRepositoryBase extends _i1.Mock - implements _i3.CacheInfoRepository { + implements _i2.CacheInfoRepository { MockCacheInfoRepositoryBase() { _i1.throwOnMissingStub(this); } @override - _i4.Future exists() => + _i3.Future exists() => (super.noSuchMethod( Invocation.method(#exists, []), - returnValue: _i4.Future.value(false), + returnValue: _i3.Future.value(false), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future open() => + _i3.Future open() => (super.noSuchMethod( Invocation.method(#open, []), - returnValue: _i4.Future.value(false), + returnValue: _i3.Future.value(false), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future updateOrInsert(_i2.CacheObject? cacheObject) => + _i3.Future updateOrInsert(_i2.CacheObject? cacheObject) => (super.noSuchMethod( Invocation.method(#updateOrInsert, [cacheObject]), - returnValue: _i4.Future.value(), + returnValue: _i3.Future.value(), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future<_i2.CacheObject> insert( + _i3.Future<_i2.CacheObject> insert( _i2.CacheObject? cacheObject, { bool? setTouchedToNow = true, }) => @@ -102,7 +103,7 @@ class MockCacheInfoRepositoryBase extends _i1.Mock [cacheObject], {#setTouchedToNow: setTouchedToNow}, ), - returnValue: _i4.Future<_i2.CacheObject>.value( + returnValue: _i3.Future<_i2.CacheObject>.value( _FakeCacheObject_0( this, Invocation.method( @@ -113,34 +114,34 @@ class MockCacheInfoRepositoryBase extends _i1.Mock ), ), ) - as _i4.Future<_i2.CacheObject>); + as _i3.Future<_i2.CacheObject>); @override - _i4.Future<_i2.CacheObject?> get(String? key) => + _i3.Future<_i2.CacheObject?> get(String? key) => (super.noSuchMethod( Invocation.method(#get, [key]), - returnValue: _i4.Future<_i2.CacheObject?>.value(), + returnValue: _i3.Future<_i2.CacheObject?>.value(), ) - as _i4.Future<_i2.CacheObject?>); + as _i3.Future<_i2.CacheObject?>); @override - _i4.Future delete(int? id) => + _i3.Future delete(int? id) => (super.noSuchMethod( Invocation.method(#delete, [id]), - returnValue: _i4.Future.value(0), + returnValue: _i3.Future.value(0), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future deleteAll(Iterable? ids) => + _i3.Future deleteAll(Iterable? ids) => (super.noSuchMethod( Invocation.method(#deleteAll, [ids]), - returnValue: _i4.Future.value(0), + returnValue: _i3.Future.value(0), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future update( + _i3.Future update( _i2.CacheObject? cacheObject, { bool? setTouchedToNow = true, }) => @@ -150,62 +151,62 @@ class MockCacheInfoRepositoryBase extends _i1.Mock [cacheObject], {#setTouchedToNow: setTouchedToNow}, ), - returnValue: _i4.Future.value(0), + returnValue: _i3.Future.value(0), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future> getAllObjects() => + _i3.Future> getAllObjects() => (super.noSuchMethod( Invocation.method(#getAllObjects, []), - returnValue: _i4.Future>.value( + returnValue: _i3.Future>.value( <_i2.CacheObject>[], ), ) - as _i4.Future>); + as _i3.Future>); @override - _i4.Future> getObjectsOverCapacity(int? capacity) => + _i3.Future> getObjectsOverCapacity(int? capacity) => (super.noSuchMethod( Invocation.method(#getObjectsOverCapacity, [capacity]), - returnValue: _i4.Future>.value( + returnValue: _i3.Future>.value( <_i2.CacheObject>[], ), ) - as _i4.Future>); + as _i3.Future>); @override - _i4.Future> getOldObjects(Duration? maxAge) => + _i3.Future> getOldObjects(Duration? maxAge) => (super.noSuchMethod( Invocation.method(#getOldObjects, [maxAge]), - returnValue: _i4.Future>.value( + returnValue: _i3.Future>.value( <_i2.CacheObject>[], ), ) - as _i4.Future>); + as _i3.Future>); @override - _i4.Future close() => + _i3.Future close() => (super.noSuchMethod( Invocation.method(#close, []), - returnValue: _i4.Future.value(false), + returnValue: _i3.Future.value(false), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future deleteDataFile() => + _i3.Future deleteDataFile() => (super.noSuchMethod( Invocation.method(#deleteDataFile, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i4.Future); + as _i3.Future); } /// A class which mocks [CacheStore]. /// /// See the documentation for Mockito's code generation for more information. -class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { +class MockCacheStoreBase extends _i1.Mock implements _i4.CacheStore { MockCacheStoreBase() { _i1.throwOnMissingStub(this); } @@ -222,7 +223,7 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { as Duration); @override - _i3.FileSystem get fileSystem => + _i2.FileSystem get fileSystem => (super.noSuchMethod( Invocation.getter(#fileSystem), returnValue: _FakeFileSystem_2( @@ -230,13 +231,13 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { Invocation.getter(#fileSystem), ), ) - as _i3.FileSystem); + as _i2.FileSystem); @override String get storeKey => (super.noSuchMethod( Invocation.getter(#storeKey), - returnValue: _i6.dummyValue( + returnValue: _i5.dummyValue( this, Invocation.getter(#storeKey), ), @@ -261,7 +262,7 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { ); @override - set fileSystem(_i3.FileSystem? value) => super.noSuchMethod( + set fileSystem(_i2.FileSystem? value) => super.noSuchMethod( Invocation.setter(#fileSystem, value), returnValueForMissingStub: null, ); @@ -273,7 +274,7 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { ); @override - _i4.Future<_i3.FileInfo?> getFile( + _i3.Future<_i2.FileInfo?> getFile( String? key, { bool? ignoreMemCache = false, }) => @@ -283,21 +284,21 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { [key], {#ignoreMemCache: ignoreMemCache}, ), - returnValue: _i4.Future<_i3.FileInfo?>.value(), + returnValue: _i3.Future<_i2.FileInfo?>.value(), ) - as _i4.Future<_i3.FileInfo?>); + as _i3.Future<_i2.FileInfo?>); @override - _i4.Future putFile(_i2.CacheObject? cacheObject) => + _i3.Future putFile(_i2.CacheObject? cacheObject) => (super.noSuchMethod( Invocation.method(#putFile, [cacheObject]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future<_i2.CacheObject?> retrieveCacheData( + _i3.Future<_i2.CacheObject?> retrieveCacheData( String? key, { bool? ignoreMemCache = false, }) => @@ -307,26 +308,26 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { [key], {#ignoreMemCache: ignoreMemCache}, ), - returnValue: _i4.Future<_i2.CacheObject?>.value(), + returnValue: _i3.Future<_i2.CacheObject?>.value(), ) - as _i4.Future<_i2.CacheObject?>); + as _i3.Future<_i2.CacheObject?>); @override - _i4.Future<_i3.FileInfo?> getFileFromMemory(String? key) => + _i3.Future<_i2.FileInfo?> getFileFromMemory(String? key) => (super.noSuchMethod( Invocation.method(#getFileFromMemory, [key]), - returnValue: _i4.Future<_i3.FileInfo?>.value(), + returnValue: _i3.Future<_i2.FileInfo?>.value(), ) - as _i4.Future<_i3.FileInfo?>); + as _i3.Future<_i2.FileInfo?>); @override - _i4.Future emptyCache() => + _i3.Future emptyCache() => (super.noSuchMethod( Invocation.method(#emptyCache, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i4.Future); + as _i3.Future); @override void emptyMemoryCache() => super.noSuchMethod( @@ -335,13 +336,13 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { ); @override - _i4.Future removeCachedFile(_i2.CacheObject? cacheObject) => + _i3.Future removeCachedFile(_i2.CacheObject? cacheObject) => (super.noSuchMethod( Invocation.method(#removeCachedFile, [cacheObject]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i4.Future); + as _i3.Future); @override bool memoryCacheContainsKey(String? key) => @@ -352,27 +353,27 @@ class MockCacheStoreBase extends _i1.Mock implements _i5.CacheStore { as bool); @override - _i4.Future dispose() => + _i3.Future dispose() => (super.noSuchMethod( Invocation.method(#dispose, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i4.Future); + as _i3.Future); @override - _i4.Future getCacheSize() => + _i3.Future getCacheSize() => (super.noSuchMethod( Invocation.method(#getCacheSize, []), - returnValue: _i4.Future.value(0), + returnValue: _i3.Future.value(0), ) - as _i4.Future); + as _i3.Future); } /// A class which mocks [FileService]. /// /// See the documentation for Mockito's code generation for more information. -class MockFileServiceBase extends _i1.Mock implements _i3.FileService { +class MockFileServiceBase extends _i1.Mock implements _i2.FileService { MockFileServiceBase() { _i1.throwOnMissingStub(this); } @@ -389,32 +390,32 @@ class MockFileServiceBase extends _i1.Mock implements _i3.FileService { ); @override - _i4.Future<_i3.FileServiceResponse> get( + _i3.Future<_i2.FileServiceResponse> get( String? url, { Map? headers, }) => (super.noSuchMethod( Invocation.method(#get, [url], {#headers: headers}), - returnValue: _i4.Future<_i3.FileServiceResponse>.value( + returnValue: _i3.Future<_i2.FileServiceResponse>.value( _FakeFileServiceResponse_4( this, Invocation.method(#get, [url], {#headers: headers}), ), ), ) - as _i4.Future<_i3.FileServiceResponse>); + as _i3.Future<_i2.FileServiceResponse>); } /// A class which mocks [WebHelper]. /// /// See the documentation for Mockito's code generation for more information. -class MockWebHelper extends _i1.Mock implements _i7.WebHelper { +class MockWebHelper extends _i1.Mock implements _i6.WebHelper { MockWebHelper() { _i1.throwOnMissingStub(this); } @override - _i3.FileService get fileFetcher => + _i2.FileService get fileFetcher => (super.noSuchMethod( Invocation.getter(#fileFetcher), returnValue: _FakeFileService_5( @@ -422,7 +423,7 @@ class MockWebHelper extends _i1.Mock implements _i7.WebHelper { Invocation.getter(#fileFetcher), ), ) - as _i3.FileService); + as _i2.FileService); @override int get concurrentCalls => @@ -436,11 +437,12 @@ class MockWebHelper extends _i1.Mock implements _i7.WebHelper { ); @override - _i4.Stream<_i3.FileResponse> downloadFile( + _i3.Stream<_i2.FileResponse> downloadFile( String? url, { String? key, Map? authHeaders, bool? ignoreMemCache = false, + _i2.CancellationToken? cancellationToken, }) => (super.noSuchMethod( Invocation.method( @@ -450,9 +452,10 @@ class MockWebHelper extends _i1.Mock implements _i7.WebHelper { #key: key, #authHeaders: authHeaders, #ignoreMemCache: ignoreMemCache, + #cancellationToken: cancellationToken, }, ), - returnValue: _i4.Stream<_i3.FileResponse>.empty(), + returnValue: _i3.Stream<_i2.FileResponse>.empty(), ) - as _i4.Stream<_i3.FileResponse>); + as _i3.Stream<_i2.FileResponse>); } diff --git a/flutter_cache_manager/test/web_helper_test.dart b/flutter_cache_manager/test/web_helper_test.dart index 5761ccb7..0e1145ef 100644 --- a/flutter_cache_manager/test/web_helper_test.dart +++ b/flutter_cache_manager/test/web_helper_test.dart @@ -289,6 +289,45 @@ void main() { await download; }); + test('cancellation during persistence does not yield FileInfo', () async { + const imageUrl = 'baseflow.com/testimage'; + + final persisted = Completer(); + var config = createTestConfig(); + var store = _createStore(config); + when(store.putFile(any)).thenAnswer((_) => persisted.future); + + final fileService = MockFileService(); + when(fileService.get(imageUrl, headers: anyNamed('headers'))).thenAnswer(( + _, + ) { + return Future.value( + MockFileFetcherResponse( + Stream.value([0, 1, 2, 3, 4, 5]), + 6, + 'testv1', + '.jpg', + 200, + DateTime.now(), + ), + ); + }); + + final webHelper = WebHelper(store, fileService); + final token = CancellationToken(); + final download = webHelper + .downloadFile(imageUrl, cancellationToken: token) + .toList(); + final expectation = expectLater( + download, + throwsA(isA()), + ); + await pumpEventQueue(); + token.cancel(); + persisted.complete(); + await expectation; + }); + test( 'downloadFile cleans up downloaded file if store persist fails', () async {