From b0f4eced84ab5f717414b9fcb8cb494dba55175b Mon Sep 17 00:00:00 2001 From: Akash Kumar <116457960+akashchamp@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:46:23 +0530 Subject: [PATCH] fix(web): report cached file read and decode failures on HttpGet A failure while reading or decoding a cached file was never delivered to the image stream. Report it, evict the image, remove the broken cache entry and close the streams. Also close the streams when every decode finished before the download completed. --- cached_network_image_web/CHANGELOG.md | 7 + .../lib/cached_network_image_web.dart | 112 ++++-- cached_network_image_web/pubspec.yaml | 2 +- .../test/cached_network_image_web_test.dart | 363 ++++++++++++++++++ 4 files changed, 449 insertions(+), 35 deletions(-) diff --git a/cached_network_image_web/CHANGELOG.md b/cached_network_image_web/CHANGELOG.md index e5a41d3e..336b950e 100644 --- a/cached_network_image_web/CHANGELOG.md +++ b/cached_network_image_web/CHANGELOG.md @@ -1,3 +1,10 @@ +## [2.0.4] - 2026-10-23 + +* Report a failure to read or decode a cached file on the `HttpGet` render method to the image stream, evict the image and the broken cache entry, and close the streams, instead of leaving the image loading forever +* A stale cached file that fails to decode is only a failure if no fresh file follows, and a failure after a frame was shown keeps that frame +* Close the streams after a download error too +* Only the web loader removes the broken cache entry; the IO loader is unchanged + ## [2.0.3] - 2026-09-29 * Bump `flutter_cache_manager` to `^3.4.5`, `material_ui` to `^1.3.0` and `web` to `^1.1.1` diff --git a/cached_network_image_web/lib/cached_network_image_web.dart b/cached_network_image_web/lib/cached_network_image_web.dart index 182637f0..f4636164 100644 --- a/cached_network_image_web/lib/cached_network_image_web.dart +++ b/cached_network_image_web/lib/cached_network_image_web.dart @@ -15,8 +15,6 @@ import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'src/create_image_codec_from_url_stub.dart' if (dart.library.ui_web) 'src/create_image_codec_from_url_web.dart'; -enum _State { open, waitingForData, closing } - /// ImageLoader class to load images on the web platform. class ImageLoader implements platform.ImageLoader { @Deprecated('Use loadImageAsync instead') @@ -121,7 +119,74 @@ class ImageLoader implements platform.ImageLoader { Map? headers, VoidCallback evictImage, ) { - var streamController = StreamController(); + final streamController = StreamController(); + + var downloadDone = false; + var pendingDecodes = 0; + var finished = false; + var settling = false; + var decoded = false; + (Object, StackTrace)? decodeFailure; + (Object, StackTrace)? downloadFailure; + + void finish() { + if (finished) return; + finished = true; + streamController.close(); + chunkEvents.close(); + } + + void fail(Object e, StackTrace st) { + if (finished) return; + scheduleMicrotask(() { + evictImage(); + }); + streamController.addError(e, st); + finish(); + } + + // Runs once the download is over and every decode has finished, so a + // stale file that fails to decode is only fatal when no fresh file came. + Future settle() async { + final failure = downloadFailure ?? (decoded ? null : decodeFailure); + if (decodeFailure != null && !decoded) { + try { + // Drop the broken entry so the next attempt downloads it again. + await cacheManager.removeFile(cacheKey ?? url); + } on Object catch (_) { + // Keep the original error visible. + } + } + if (failure == null) { + finish(); + } else { + fail(failure.$1, failure.$2); + } + } + + void closeIfComplete() { + if (settling || !downloadDone || pendingDecodes > 0) return; + settling = true; + unawaited(settle()); + } + + Future decodeFile(FileInfo info) async { + try { + final bytes = await info.file.readAsBytes(); + final codec = await decode(bytes); + if (finished) { + codec.dispose(); + } else { + decoded = true; + streamController.add(codec); + } + } on Object catch (e, st) { + decodeFailure = (e, st); + } finally { + pendingDecodes--; + closeIfComplete(); + } + } try { final stream = cacheManager.getFileStream( @@ -131,8 +196,6 @@ class ImageLoader implements platform.ImageLoader { key: cacheKey, ); - var state = _State.open; - stream.listen( (event) { if (event is DownloadProgress) { @@ -144,42 +207,23 @@ class ImageLoader implements platform.ImageLoader { ); } if (event is FileInfo) { - if (state == _State.open) { - state = _State.waitingForData; - } - - event.file.readAsBytes().then((value) => decode(value)).then(( - data, - ) { - streamController.add(data); - if (state == _State.closing) { - streamController.close(); - chunkEvents.close(); - } - }); + pendingDecodes++; + unawaited(decodeFile(event)); } }, - onError: (e, st) { - scheduleMicrotask(() { - evictImage(); - }); - streamController.addError(e, st); + onError: (Object e, StackTrace st) { + downloadFailure = (e, st); + downloadDone = true; + closeIfComplete(); }, - onDone: () async { - if (state == _State.open) { - streamController.close(); - chunkEvents.close(); - } else if (state == _State.waitingForData) { - state = _State.closing; - } + onDone: () { + downloadDone = true; + closeIfComplete(); }, cancelOnError: true, ); } on Object catch (e, st) { - scheduleMicrotask(() { - evictImage(); - }); - streamController.addError(e, st); + fail(e, st); } return streamController.stream; diff --git a/cached_network_image_web/pubspec.yaml b/cached_network_image_web/pubspec.yaml index 4928f1fe..8c77eb10 100644 --- a/cached_network_image_web/pubspec.yaml +++ b/cached_network_image_web/pubspec.yaml @@ -1,6 +1,6 @@ name: cached_network_image_web description: Web implementation of CachedNetworkImage -version: 2.0.3 +version: 2.0.4 homepage: https://github.com/Baseflow/flutter_cached_network_image environment: diff --git a/cached_network_image_web/test/cached_network_image_web_test.dart b/cached_network_image_web/test/cached_network_image_web_test.dart index 00f4e219..e9c01e7e 100644 --- a/cached_network_image_web/test/cached_network_image_web_test.dart +++ b/cached_network_image_web/test/cached_network_image_web_test.dart @@ -9,6 +9,7 @@ import 'package:cached_network_image_platform_interface' hide ImageLoader; import 'package:cached_network_image_web/cached_network_image_web.dart'; import 'package:file/file.dart'; +import 'package:file/memory.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -30,6 +31,368 @@ void main() { ); expect(stream, isNotNull); }); + + group('HttpGet with cached files', () { + const url = 'https://example.com/image.webp'; + // The decoder tells files apart by their length: `stale` is the cached + // copy, `fresh` the one that is downloaded afterwards. + const stale = 3; + const fresh = 4; + + late _StreamingCacheManager cacheManager; + late List uncaught; + late List streamErrors; + late List codecs; + late Map> decodes; + late Completer streamDone; + late Completer chunkEventsDone; + late int evicted; + + // Lets every pending microtask run, e.g. a decode that was just completed. + Future flush() => Future.delayed(Duration.zero); + + Completer decodeOf(int length) => + decodes.putIfAbsent(length, Completer.new); + + void decodeSucceeds(int length) => decodeOf(length).complete(_FakeCodec()); + + void decodeFails(int length) => + decodeOf(length).completeError(StateError('invalid image $length')); + + FileInfo fileInfo(int length) { + final file = MemoryFileSystem().file('/image-$length.webp') + ..writeAsBytesSync(List.filled(length, 1)); + return FileInfo( + file, + FileSource.Online, + DateTime.now().add(const Duration(days: 1)), + url, + ); + } + + /// Emits a file and lets its decode start. + Future emit(int length) async { + cacheManager.events.add(fileInfo(length)); + await flush(); + } + + /// Ends the download and waits until both streams are closed. + Future finish() async { + await cacheManager.events.close(); + await Future.wait([ + streamDone.future, + chunkEventsDone.future, + ]).timeout(const Duration(seconds: 5)); + } + + void load({ + String? cacheKey, + bool failRemove = false, + Completer? removeGate, + bool throwOnGet = false, + }) { + uncaught = []; + streamErrors = []; + codecs = []; + decodes = {}; + streamDone = Completer(); + chunkEventsDone = Completer(); + evicted = 0; + cacheManager = _StreamingCacheManager( + failRemove: failRemove, + removeGate: removeGate, + throwOnGet: throwOnGet, + ); + runZonedGuarded(() { + final chunkEvents = StreamController(); + chunkEvents.stream.listen((_) {}, onDone: chunkEventsDone.complete); + ImageLoader() + .loadImageAsync( + url, + cacheKey, + chunkEvents, + (buffer, {getTargetSize}) { + final length = buffer.length; + buffer.dispose(); + return decodeOf(length).future; + }, + cacheManager, + null, + null, + null, + ImageRenderMethodForWeb.HttpGet, + () => evicted++, + ) + .listen( + codecs.add, + onError: streamErrors.add, + onDone: streamDone.complete, + ); + }, (e, _) => uncaught.add(e)); + } + + test('reports a decode failure to the stream and cleans up', () async { + load(cacheKey: 'custom-key'); + await emit(stale); + decodeFails(stale); + await finish(); + + expect(uncaught, isEmpty); + expect(streamErrors, hasLength(1)); + expect(streamErrors.single, isA()); + expect(codecs, isEmpty); + expect(evicted, 1); + expect(cacheManager.removedKeys, ['custom-key']); + }); + + test('removes the broken file under the url when no key is set', () async { + load(); + await emit(stale); + decodeFails(stale); + await finish(); + + expect(cacheManager.removedKeys, [url]); + }); + + test( + 'still reports the decode failure if removing the file fails', + () async { + load(failRemove: true); + await emit(stale); + decodeFails(stale); + await finish(); + + expect(uncaught, isEmpty); + expect(streamErrors.single, isA()); + expect(evicted, 1); + }, + ); + + test('evicts the image only after the broken file is removed', () async { + final removeGate = Completer(); + load(removeGate: removeGate); + await emit(stale); + decodeFails(stale); + await cacheManager.events.close(); + await flush(); + + expect(cacheManager.removedKeys, [url]); + expect(evicted, 0); + expect(streamErrors, isEmpty); + + removeGate.complete(); + await finish(); + + expect(evicted, 1); + expect(streamErrors, hasLength(1)); + }); + + test('closes the streams once the file is decoded', () async { + load(); + await emit(stale); + decodeSucceeds(stale); + await finish(); + + expect(uncaught, isEmpty); + expect(streamErrors, isEmpty); + expect(codecs, hasLength(1)); + expect(evicted, 0); + expect(cacheManager.removedKeys, isEmpty); + }); + + test('reports an error thrown while the download starts', () async { + load(throwOnGet: true); + await Future.wait([ + streamDone.future, + chunkEventsDone.future, + ]).timeout(const Duration(seconds: 5)); + + expect(uncaught, isEmpty); + expect(streamErrors.single, isA()); + expect(evicted, 1); + }); + + test('shows the fresh file when the stale one fails to decode', () async { + load(); + await emit(stale); + decodeFails(stale); + await flush(); + + // The download is still running, so nothing may be removed yet. + expect(cacheManager.removedKeys, isEmpty); + expect(streamErrors, isEmpty); + expect(evicted, 0); + + await emit(fresh); + decodeSucceeds(fresh); + await finish(); + + expect(uncaught, isEmpty); + expect(streamErrors, isEmpty); + expect(codecs, hasLength(1)); + expect(evicted, 0); + expect(cacheManager.removedKeys, isEmpty); + }); + + test( + 'reports the failure when the stale and fresh files both fail', + () async { + load(); + await emit(stale); + decodeFails(stale); + await emit(fresh); + decodeFails(fresh); + await flush(); + + expect(cacheManager.removedKeys, isEmpty); + + await finish(); + + expect(uncaught, isEmpty); + expect(codecs, isEmpty); + expect(streamErrors, hasLength(1)); + expect((streamErrors.single as StateError).message, contains('$fresh')); + expect(evicted, 1); + expect(cacheManager.removedKeys, [url]); + }, + ); + + test('keeps the image when a later file fails to decode', () async { + load(); + await emit(stale); + decodeSucceeds(stale); + await emit(fresh); + decodeFails(fresh); + await finish(); + + expect(uncaught, isEmpty); + expect(codecs, hasLength(1)); + expect(streamErrors, isEmpty); + expect(evicted, 0); + expect(cacheManager.removedKeys, isEmpty); + }); + + test( + 'keeps the image when the stale file fails after the fresh one decoded', + () async { + load(); + await emit(stale); + await emit(fresh); + decodeSucceeds(fresh); + await flush(); + decodeFails(stale); + await finish(); + + expect(uncaught, isEmpty); + expect(codecs, hasLength(1)); + expect(streamErrors, isEmpty); + expect(evicted, 0); + expect(cacheManager.removedKeys, isEmpty); + }, + ); + + test( + 'closes the streams after a download error following a frame', + () async { + load(); + await emit(stale); + decodeSucceeds(stale); + await flush(); + cacheManager.events.addError(StateError('download failed')); + await Future.wait([ + streamDone.future, + chunkEventsDone.future, + ]).timeout(const Duration(seconds: 5)); + + expect(uncaught, isEmpty); + expect(codecs, hasLength(1)); + expect(streamErrors.single, isA()); + expect(evicted, 1); + expect(cacheManager.removedKeys, isEmpty); + }, + ); + + test( + 'waits for a pending decode before reporting a download error', + () async { + load(); + await emit(stale); + cacheManager.events.addError(StateError('download failed')); + await flush(); + + expect(streamDone.isCompleted, isFalse); + expect(streamErrors, isEmpty); + + decodeSucceeds(stale); + await Future.wait([ + streamDone.future, + chunkEventsDone.future, + ]).timeout(const Duration(seconds: 5)); + + expect(uncaught, isEmpty); + expect(codecs, hasLength(1)); + expect(streamErrors, hasLength(1)); + expect(cacheManager.removedKeys, isEmpty); + }, + ); + + test('removes the broken file when the download fails too', () async { + load(); + await emit(stale); + decodeFails(stale); + cacheManager.events.addError(StateError('download failed')); + await Future.wait([ + streamDone.future, + chunkEventsDone.future, + ]).timeout(const Duration(seconds: 5)); + + expect(uncaught, isEmpty); + expect(codecs, isEmpty); + expect(streamErrors, hasLength(1)); + expect((streamErrors.single as StateError).message, 'download failed'); + expect(cacheManager.removedKeys, [url]); + }); + }); +} + +class _FakeCodec implements ui.Codec { + @override + void dispose() {} + + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _StreamingCacheManager extends MockCacheManager { + _StreamingCacheManager({ + this.failRemove = false, + this.removeGate, + this.throwOnGet = false, + }); + + final bool failRemove; + final Completer? removeGate; + final bool throwOnGet; + final events = StreamController(); + final removedKeys = []; + + @override + Stream getFileStream( + String url, { + String? key, + Map? headers, + bool withProgress = false, + }) { + if (throwOnGet) throw StateError('cannot start the download'); + return events.stream; + } + + @override + Future removeFile(String key) async { + removedKeys.add(key); + await removeGate?.future; + if (failRemove) throw StateError('remove failed'); + } } Future decoder(