From 720f7a579ad7694dfe23001fd67b55cd725b90d0 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Thu, 5 Nov 2026 20:43:22 +0200 Subject: [PATCH 1/2] Dispose plugin downloads and abort only service-owned requests --- lib/plugins/bloc/plugin_system_bloc.dart | 46 +- .../services/plugin_download_service.dart | 147 ++++-- ...n_system_bloc_download_lifecycle_test.dart | 51 ++ .../plugin_system_bloc_remote_close_test.dart | 330 ++++++++++++ ...lugin_download_service_lifecycle_test.dart | 477 ++++++++++++++++++ 5 files changed, 995 insertions(+), 56 deletions(-) create mode 100644 test/plugins/bloc/plugin_system_bloc_download_lifecycle_test.dart create mode 100644 test/plugins/bloc/plugin_system_bloc_remote_close_test.dart create mode 100644 test/plugins/services/plugin_download_service_lifecycle_test.dart diff --git a/lib/plugins/bloc/plugin_system_bloc.dart b/lib/plugins/bloc/plugin_system_bloc.dart index 7eef69f579..8506e1ef46 100644 --- a/lib/plugins/bloc/plugin_system_bloc.dart +++ b/lib/plugins/bloc/plugin_system_bloc.dart @@ -1,5 +1,6 @@ import 'package:bloc_concurrency/bloc_concurrency.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:http/http.dart' as http; import 'package:otzaria/plugins/utils/plugin_safe_mode.dart'; import 'package:otzaria/plugins/bloc/plugin_system_event.dart'; import 'package:otzaria/plugins/bloc/plugin_system_state.dart'; @@ -64,6 +65,7 @@ class PluginSystemBloc extends Bloc { final bool _sharedDevWatcher; StreamSubscription? _devWatchSub; StreamSubscription? _readerStateSub; + Future? _closeFuture; /// החתימה מונעת קומפילציה ושאילתות חוזרות כשהמניפסט וההרשאות לא השתנו. String? _lastDeclarativeSyncSignature; @@ -85,6 +87,7 @@ class PluginSystemBloc extends Bloc { PluginSystemBloc({ required this.repository, PluginInstallerService? installerService, + // השירות מועבר לבעלות ה-BLoC ומשוחרר בסגירת החלון. PluginDownloadService? downloadService, PluginDevLoaderService? devLoader, PluginDevWatchService? devWatchService, @@ -154,18 +157,26 @@ class PluginSystemBloc extends Bloc { } @override - Future close() async { - PluginShortcutRegistry.instance.removeListener(_onPluginShortcutsChanged); - await _devWatchSub?.cancel(); - await _readerStateSub?.cancel(); - if (_sharedDevWatcher) { - PluginDevWatchService.release(); - } else { - devWatchService.dispose(); + // _close קוראת ל-super.close ב-finally, גם אם שחרור השירות נכשל. + // ignore: must_call_super + Future close() => _closeFuture ??= _close(); + + Future _close() async { + try { + _downloadService.dispose(); + } finally { + PluginShortcutRegistry.instance.removeListener(_onPluginShortcutsChanged); + await _devWatchSub?.cancel(); + await _readerStateSub?.cancel(); + if (_sharedDevWatcher) { + PluginDevWatchService.release(); + } else { + devWatchService.dispose(); + } + declarativeHost?.dispose(); + toolbarRegistry?.dispose(); + await super.close(); } - declarativeHost?.dispose(); - toolbarRegistry?.dispose(); - await super.close(); } Future _handleDevChange(PluginDevFsChange change) async { @@ -519,6 +530,7 @@ class PluginSystemBloc extends Bloc { InstallRemotePluginRequested event, Emitter emit, ) async { + if (_closeFuture != null || emit.isDone) return; String? archivePath; // אישור קבלה מיידי לאתר החנות — עוד לפני ההורדה ודיאלוג ההרשאות, @@ -533,17 +545,23 @@ class PluginSystemBloc extends Bloc { try { appVersion = appReleaseVersion(await PackageInfo.fromPlatform()); } catch (_) {} + if (_closeFuture != null || emit.isDone) return; archivePath = await _downloadService.downloadPluginArchive( Uri.parse(event.downloadUrl), appVersion: appVersion, storeOnly: event.storeOnly, ); + if (_closeFuture != null || emit.isDone) return; final prepareInfo = await _installerService.prepareInstall( archivePath, forceOverwrite: event.forceOverwrite, ); + if (_closeFuture != null || emit.isDone) { + await _installerService.cancelInstall(prepareInfo.tempDirPath); + return; + } emit( PluginSystemInstallRequiresPermissions( @@ -555,7 +573,10 @@ class PluginSystemBloc extends Bloc { isUserInitiated: event.isUserInitiated, ), ); + } on http.RequestAbortedException { + return; } on PluginOverwriteException catch (e) { + if (_closeFuture != null || emit.isDone) return; UiSnack.show(PluginMessages.pluginAlreadyInstalledSameVersion); debugPrint( 'Plugin overwrite required for "${e.pluginName}" version ${e.version}', @@ -567,6 +588,7 @@ class PluginSystemBloc extends Bloc { ); add(LoadPlugins()); } on PluginStoreIncompatibleException catch (e) { + if (_closeFuture != null || emit.isDone) return; // tryParse מבטיח שלפחות אחד הגבולות קיים, לכן maxAppVersion אינו null כאן. final String message; if (e.isAboveCeiling || e.minAppVersion.isEmpty) { @@ -588,6 +610,7 @@ class PluginSystemBloc extends Bloc { ); add(LoadPlugins()); } on PluginNewerVersionInstalledException catch (e) { + if (_closeFuture != null || emit.isDone) return; UiSnack.show( PluginMessages.newerVersionInstalled(e.pluginName, e.installedVersion), ); @@ -598,6 +621,7 @@ class PluginSystemBloc extends Bloc { ); add(LoadPlugins()); } catch (e) { + if (_closeFuture != null || emit.isDone) return; UiSnack.showError(PluginMessages.installRemotePluginError(e)); _reportInstallResult( event.reportContext, diff --git a/lib/plugins/services/plugin_download_service.dart b/lib/plugins/services/plugin_download_service.dart index 8483c72988..54ca9b08ce 100644 --- a/lib/plugins/services/plugin_download_service.dart +++ b/lib/plugins/services/plugin_download_service.dart @@ -10,15 +10,32 @@ import 'package:path/path.dart' as p; class PluginDownloadService { final http.Client _client; + final bool _ownsClient; + final _downloads = >{}; + late final FutureOr Function() _closer = dispose; + bool _disposed = false; /// משך מרבי ללא בייטים (גם בהמתנה לכותרות) לפני [TimeoutException]. final Duration _stallTimeout; + /// [client] מוזרק נשאר באחריות הקורא ואינו נסגר עם השירות. PluginDownloadService({ http.Client? client, this._stallTimeout = const Duration(seconds: 60), - }) : _client = client ?? http.Client() { - HttpClientRegistry.register(_client.close); + }) : _client = client ?? http.Client(), + _ownsClient = client == null { + if (_ownsClient) HttpClientRegistry.register(_closer); + } + + /// מבטל הורדות פעילות ומשחרר רק את ה-client שבבעלות השירות. + void dispose() { + if (_disposed) return; + _disposed = true; + if (_ownsClient) HttpClientRegistry.unregister(_closer); + for (final download in _downloads) { + if (!download.isCompleted) download.complete(); + } + if (_ownsClient) _client.close(); } /// מורידה את ארכיון התוסף. [appVersion] — גרסת האוצריא הנוכחית; כשהכתובת @@ -32,56 +49,81 @@ class PluginDownloadService { String? appVersion, bool storeOnly = false, }) async { - final resolvedUri = PluginStoreLinkParser.appendAppVersion( - downloadUri, - appVersion, - ); - var response = await _sendFollowingRedirects(resolvedUri, storeOnly); - - if (response.statusCode >= 400 && resolvedUri != downloadUri) { - final body = await utf8.decodeStream( - response.stream.timeout(_stallTimeout), + if (_disposed) throw StateError('PluginDownloadService is disposed'); + final abort = Completer(); + _downloads.add(abort); + http.StreamedResponse? response; + var responseConsumed = false; + try { + final resolvedUri = PluginStoreLinkParser.appendAppVersion( + downloadUri, + appVersion, ); - // לחנות אין גרסה תואמת — פרטי התאימות כבר בגוף התשובה, ואין טעם - // להוריד ארכיון שממילא ייפסל. - final incompatible = PluginStoreIncompatibleException.tryParse(body); - if (incompatible != null) { - throw incompatible; - } - // סירוב מסיבה אחרת (למשל שילוב פרמטרים שהשרת דוחה) — מנסים שוב - // בכתובת המקורית, כדי לא לשבור התקנה שעבדה לפני הוספת appVersion. - response = await _sendFollowingRedirects(downloadUri, storeOnly); - } + response = await _sendFollowingRedirects(resolvedUri, storeOnly, abort); + _checkActive(abort, downloadUri); - if (response.statusCode < 200 || response.statusCode >= 300) { - throw Exception( - 'שגיאה בהורדת התוסף (${response.statusCode})', - ); - } + if (response.statusCode >= 400 && resolvedUri != downloadUri) { + responseConsumed = true; + final body = await utf8.decodeStream( + response.stream.timeout(_stallTimeout), + ); + _checkActive(abort, downloadUri); + final incompatible = PluginStoreIncompatibleException.tryParse(body); + if (incompatible != null) throw incompatible; - final tempDir = await Directory.systemTemp.createTemp( - 'otzaria_plugin_download_', - ); - final archivePath = p.join( - tempDir.path, - '${_resolveFileStem(downloadUri)}.otzplugin', - ); - final targetFile = File(archivePath); - final sink = targetFile.openWrite(); + // סירוב שאינו אי-תאימות — מנסים את הכתובת המקורית ללא appVersion. + response = await _sendFollowingRedirects(downloadUri, storeOnly, abort); + responseConsumed = false; + _checkActive(abort, downloadUri); + } - try { - await sink.addStream(response.stream.timeout(_stallTimeout)); - await sink.flush(); - await sink.close(); - } catch (_) { + if (response.statusCode < 200 || response.statusCode >= 300) { + throw Exception('שגיאה בהורדת התוסף (${response.statusCode})'); + } + + final tempDir = await Directory.systemTemp.createTemp( + 'otzaria_plugin_download_', + ); + final archivePath = p.join( + tempDir.path, + '${_resolveFileStem(downloadUri)}.otzplugin', + ); + IOSink? sink; try { + _checkActive(abort, downloadUri); + sink = File(archivePath).openWrite(); + responseConsumed = true; + await sink.addStream(response.stream.timeout(_stallTimeout)); + await sink.flush(); await sink.close(); - } catch (_) {} - await _cleanupDirectory(tempDir); + sink = null; + _checkActive(abort, downloadUri); + } catch (_) { + try { + await sink?.close(); + } catch (_) {} + await _cleanupDirectory(tempDir); + rethrow; + } + + return archivePath; + } catch (error) { + if (abort.isCompleted && + (error is http.ClientException || error is SocketException)) { + throw http.RequestAbortedException(downloadUri); + } rethrow; + } finally { + if (!abort.isCompleted) abort.complete(); + _downloads.remove(abort); + if (response != null && !responseConsumed) { + await response.stream.listen(null).cancel(); + } } + } - return archivePath; + void _checkActive(Completer abort, Uri uri) { + if (abort.isCompleted) throw http.RequestAbortedException(uri); } Future cleanupDownloadedArchive(String archivePath) async { @@ -112,14 +154,29 @@ class PluginDownloadService { Future _sendFollowingRedirects( Uri uri, bool storeOnly, + Completer abort, ) async { var current = uri; for (var hop = 0; hop <= _maxRedirects; hop++) { + _checkActive(abort, current); if (storeOnly && !PluginStoreLinkParser.isStoreDownloadUri(current)) { throw Exception('הורדת תוסף מותרת רק מכתובת של חנות התוספים'); } - final request = http.Request('GET', current)..followRedirects = false; - final response = await _client.send(request).timeout(_stallTimeout); + final request = http.AbortableRequest( + 'GET', + current, + abortTrigger: abort.future, + )..followRedirects = false; + final response = await _client + .send(request) + .then((response) async { + if (abort.isCompleted) { + await response.stream.listen(null).cancel(); + throw http.RequestAbortedException(request.url); + } + return response; + }) + .timeout(_stallTimeout); final location = response.headers['location']; final isRedirect = response.statusCode >= 300 && diff --git a/test/plugins/bloc/plugin_system_bloc_download_lifecycle_test.dart b/test/plugins/bloc/plugin_system_bloc_download_lifecycle_test.dart new file mode 100644 index 0000000000..7d175ca558 --- /dev/null +++ b/test/plugins/bloc/plugin_system_bloc_download_lifecycle_test.dart @@ -0,0 +1,51 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:otzaria/core/http_client_registry.dart'; +import 'package:otzaria/plugins/bloc/plugin_system_bloc.dart'; +import 'package:otzaria/plugins/repository/plugin_registry_repository.dart'; + +class _FakeRepo implements PluginRegistryRepository { + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _RecordingClient extends MockClient { + _RecordingClient() : super((_) async => http.Response('archive', 200)); + + int closeCount = 0; + + @override + void close() { + closeCount++; + super.close(); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + '30 window lifetimes release their registered download clients', + () async { + final before = HttpClientRegistry.registeredCount; + final clients = <_RecordingClient>[]; + final countsAfterClose = []; + addTearDown(HttpClientRegistry.closeAll); + + for (var cycle = 0; cycle < 30; cycle++) { + final client = _RecordingClient(); + clients.add(client); + final bloc = http.runWithClient( + () => PluginSystemBloc(repository: _FakeRepo()), + () => client, + ); + await bloc.close(); + countsAfterClose.add(HttpClientRegistry.registeredCount); + } + + expect(countsAfterClose, List.filled(30, before)); + expect(clients.map((client) => client.closeCount), everyElement(1)); + }, + ); +} diff --git a/test/plugins/bloc/plugin_system_bloc_remote_close_test.dart b/test/plugins/bloc/plugin_system_bloc_remote_close_test.dart new file mode 100644 index 0000000000..34d2219f00 --- /dev/null +++ b/test/plugins/bloc/plugin_system_bloc_remote_close_test.dart @@ -0,0 +1,330 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:otzaria/core/http_client_registry.dart'; +import 'package:otzaria/plugins/bloc/plugin_system_bloc.dart'; +import 'package:otzaria/plugins/bloc/plugin_system_event.dart'; +import 'package:otzaria/plugins/bloc/plugin_system_state.dart'; +import 'package:otzaria/plugins/models/installed_plugin.dart'; +import 'package:otzaria/plugins/models/plugin_manifest.dart'; +import 'package:otzaria/plugins/repository/plugin_registry_repository.dart'; +import 'package:otzaria/plugins/services/plugin_download_service.dart'; +import 'package:otzaria/plugins/services/plugin_installer_service.dart'; +import 'package:otzaria/plugins/utils/plugin_safe_mode.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:path/path.dart' as path; + +class _FakeRepo implements PluginRegistryRepository { + int loads = 0; + + @override + Future> getAllPlugins() async { + loads++; + return []; + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _ControlledDownload extends PluginDownloadService { + _ControlledDownload({ + this.abortOnDispose = false, + this.failOnDispose = false, + }); + + final bool abortOnDispose; + final bool failOnDispose; + final started = Completer(); + final result = Completer(); + int disposals = 0; + + @override + Future downloadPluginArchive( + Uri downloadUri, { + String? appVersion, + bool storeOnly = false, + }) { + started.complete(); + return result.future; + } + + @override + void dispose() { + disposals++; + super.dispose(); + if (abortOnDispose && started.isCompleted && !result.isCompleted) { + result.completeError(http.RequestAbortedException()); + } + if (failOnDispose) throw StateError('dispose failed'); + } +} + +class _ControlledInstaller extends PluginInstallerService { + _ControlledInstaller() : super(repository: _FakeRepo()); + + final started = Completer(); + final result = Completer(); + final cancelled = []; + int prepares = 0; + + @override + Future prepareInstall( + String archivePath, { + bool forceOverwrite = false, + }) { + prepares++; + started.complete(); + return result.future; + } + + @override + Future cancelInstall(String tempDirPath) async { + cancelled.add(tempDirPath); + await super.cancelInstall(tempDirPath); + } +} + +class _ObservedBloc extends PluginSystemBloc { + _ObservedBloc({ + required super.repository, + required super.downloadService, + required super.installerService, + }); + + final handled = Completer(); + final errors = []; + + @override + void onError(Object error, StackTrace stackTrace) { + errors.add(error); + super.onError(error, stackTrace); + } + + @override + void onDone( + PluginSystemEvent event, [ + Object? error, + StackTrace? stackTrace, + ]) { + if (event is InstallRemotePluginRequested && !handled.isCompleted) { + handled.complete(); + } + super.onDone(event, error, stackTrace); + } +} + +PreparedInstall _prepared(Directory directory) => PreparedInstall( + PluginManifest.fromJson({ + 'id': 'test.plugin', + 'name': 'תוסף בדיקה', + 'version': '1.0.0', + 'entrypoint': 'index.html', + }), + directory.path, + false, +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _FakeRepo repository; + late _ControlledInstaller installer; + late Directory directory; + late int registryBefore; + + setUp(() async { + registryBefore = HttpClientRegistry.registeredCount; + repository = _FakeRepo(); + installer = _ControlledInstaller(); + directory = await Directory.systemTemp.createTemp('plugin_close_test_'); + PackageInfo.setMockInitialValues( + appName: 'Otzaria', + packageName: 'com.otzaria.app', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ); + }); + + tearDown(() async { + PluginSafeMode.resetForTesting(); + if (await directory.exists()) await directory.delete(recursive: true); + expect(HttpClientRegistry.registeredCount, registryBefore); + }); + + _ObservedBloc create(_ControlledDownload download) { + final bloc = _ObservedBloc( + repository: repository, + downloadService: download, + installerService: installer, + ); + addTearDown(bloc.close); + return bloc; + } + + void install(_ObservedBloc bloc) => bloc.add( + const InstallRemotePluginRequested('https://example.com/plugin.otzplugin'), + ); + + Future archive() async { + final archiveDirectory = await directory.createTemp('download_'); + final file = File(path.join(archiveDirectory.path, 'test.otzplugin')); + await file.writeAsString('archive'); + return file.path; + } + + test('close cancels the download without a stale error or reload', () async { + final download = _ControlledDownload(abortOnDispose: true); + final bloc = create(download); + install(bloc); + await download.started.future; + + await bloc.close(); + await bloc.handled.future; + await bloc.close(); + + expect(download.disposals, 1); + expect(installer.prepares, 0); + expect(repository.loads, 0); + expect(bloc.errors, isEmpty); + }); + + test('registry shutdown cancels a download before the bloc closes', () async { + final download = _ControlledDownload(abortOnDispose: true); + final bloc = create(download); + install(bloc); + await download.started.future; + + await HttpClientRegistry.closeAll(); + await bloc.handled.future; + + expect(bloc.isClosed, isFalse); + expect(installer.prepares, 0); + expect(repository.loads, 0); + expect(bloc.errors, isEmpty); + expect(HttpClientRegistry.registeredCount, registryBefore); + await bloc.close(); + }); + + test( + 'ordinary download failures still reset the live window state', + () async { + PluginSafeMode.active.value = true; + final download = _ControlledDownload(); + final bloc = create(download); + final reloaded = bloc.stream.firstWhere( + (state) => state is PluginSystemLoaded, + ); + install(bloc); + await download.started.future; + + download.result.completeError(http.ClientException('network failed')); + await bloc.handled.future; + await reloaded; + + expect(bloc.isClosed, isFalse); + expect(repository.loads, 1); + expect(installer.prepares, 0); + await bloc.close(); + }, + ); + + test( + 'late successful download is cleaned without starting installation', + () async { + final download = _ControlledDownload(); + final bloc = create(download); + final archivePath = await archive(); + install(bloc); + await download.started.future; + + await bloc.close(); + download.result.complete(archivePath); + await bloc.handled.future; + + expect(installer.prepares, 0); + expect(repository.loads, 0); + expect(bloc.errors, isEmpty); + expect(await File(archivePath).exists(), isFalse); + }, + ); + + test( + 'preparation finishing after close releases extracted and source files', + () async { + final download = _ControlledDownload(); + final bloc = create(download); + final archivePath = await archive(); + final extracted = await directory.createTemp('prepared_'); + download.result.complete(archivePath); + install(bloc); + await installer.started.future; + + await bloc.close(); + installer.result.complete(_prepared(extracted)); + await bloc.handled.future; + + expect(installer.cancelled, [extracted.path]); + expect(await extracted.exists(), isFalse); + expect(await File(archivePath).exists(), isFalse); + expect(repository.loads, 0); + expect(bloc.errors, isEmpty); + }, + ); + + test( + 'a live window still receives the prepared permission request', + () async { + final download = _ControlledDownload(); + final bloc = create(download); + final archivePath = await archive(); + final extracted = await directory.createTemp('prepared_'); + download.result.complete(archivePath); + installer.result.complete(_prepared(extracted)); + final state = bloc.stream.firstWhere( + (state) => state is PluginSystemInstallRequiresPermissions, + ); + + install(bloc); + final ready = await state as PluginSystemInstallRequiresPermissions; + await bloc.handled.future; + + expect(ready.tempDirPath, extracted.path); + expect(installer.cancelled, isEmpty); + expect(await extracted.exists(), isTrue); + expect(await File(archivePath).exists(), isFalse); + expect(bloc.errors, isEmpty); + await bloc.close(); + }, + ); + + test('closing immediately does not start an enqueued download', () async { + final download = _ControlledDownload(); + final bloc = create(download); + + install(bloc); + await bloc.close(); + await pumpEventQueue(); + + expect(download.started.isCompleted, isFalse); + expect(download.disposals, 1); + expect(installer.prepares, 0); + expect(repository.loads, 0); + }); + + test('download disposal failure still closes the bloc', () async { + final download = _ControlledDownload(failOnDispose: true); + final bloc = _ObservedBloc( + repository: repository, + downloadService: download, + installerService: installer, + ); + + await expectLater(bloc.close(), throwsStateError); + expect(bloc.isClosed, isTrue); + expect(download.disposals, 1); + }); +} diff --git a/test/plugins/services/plugin_download_service_lifecycle_test.dart b/test/plugins/services/plugin_download_service_lifecycle_test.dart new file mode 100644 index 0000000000..61879793d7 --- /dev/null +++ b/test/plugins/services/plugin_download_service_lifecycle_test.dart @@ -0,0 +1,477 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/io_client.dart'; +import 'package:http/testing.dart'; +import 'package:otzaria/core/http_client_registry.dart'; +import 'package:otzaria/plugins/services/plugin_download_service.dart'; + +class _RecordingClient extends MockClient { + _RecordingClient({this.throwOnClose = false}) + : super((_) async => http.Response('archive', 200)); + + final bool throwOnClose; + int closeCount = 0; + + @override + void close() { + closeCount++; + super.close(); + if (throwOnClose) throw StateError('close failed'); + } +} + +class _BodyObservingClient extends http.BaseClient { + _BodyObservingClient(this.onDownloadBody); + + final void Function() onDownloadBody; + final _inner = IOClient(); + + @override + Future send(http.BaseRequest request) async { + final response = await _inner.send(request); + return http.StreamedResponse( + response.stream.map((chunk) { + if (request.url.path != '/other') onDownloadBody(); + return chunk; + }), + response.statusCode, + headers: response.headers, + contentLength: response.contentLength, + ); + } + + @override + void close() => _inner.close(); +} + +class _FailingCleanupDirectory implements Directory { + _FailingCleanupDirectory(this.directory, this.failure); + + final Directory directory; + final FileSystemException failure; + + @override + String get path => directory.path; + + @override + Future exists() => directory.exists(); + + @override + Future createTemp([String? prefix]) async => + _FailingCleanupDirectory(await directory.createTemp(prefix), failure); + + @override + Future delete({bool recursive = false}) => Future.error(failure); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +Future _serve(void Function(HttpRequest) handle) async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen(handle); + addTearDown(() => server.close(force: true)); + return server; +} + +Uri _uri(HttpServer server, [String path = '/plugin.otzplugin']) => + Uri.parse('http://127.0.0.1:${server.port}$path'); + +int? _descriptorCount(String targetPrefix) { + if (!Platform.isLinux) return null; + final directory = Directory('/proc/self/fd'); + if (!directory.existsSync()) return null; + return directory.listSync(followLinks: false).whereType().where((link) { + try { + return link.targetSync().startsWith(targetPrefix); + } on FileSystemException { + return false; + } + }).length; +} + +void main() { + late Directory downloads; + late int registryBefore; + + setUp(() async { + registryBefore = HttpClientRegistry.registeredCount; + downloads = await Directory.systemTemp.createTemp('plugin_lifecycle_test_'); + }); + + tearDown(() async { + // Deleting an archive is not enough on Unix: a leaked IOSink can keep its + // native file descriptor alive even after the path has been removed. + final openFiles = _descriptorCount( + '${downloads.path}${Platform.pathSeparator}', + ); + if (openFiles != null) expect(openFiles, 0); + await downloads.delete(recursive: true); + expect(HttpClientRegistry.registeredCount, registryBefore); + }); + + Future inDownloads(Future Function() body) => IOOverrides.runZoned( + body, + getSystemTempDirectory: () => downloads, + ); + + test('owned client unregisters and closes exactly once', () async { + final client = _RecordingClient(); + final service = http.runWithClient(PluginDownloadService.new, () => client); + addTearDown(service.dispose); + + expect(HttpClientRegistry.registeredCount, registryBefore + 1); + service.dispose(); + service.dispose(); + + expect(HttpClientRegistry.registeredCount, registryBefore); + expect(client.closeCount, 1); + await expectLater( + service.downloadPluginArchive(Uri.parse('https://example.com/plugin')), + throwsStateError, + ); + }); + + test('injected client is neither registered nor closed', () async { + final client = _RecordingClient(); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + expect(HttpClientRegistry.registeredCount, registryBefore); + await HttpClientRegistry.closeAll(); + service.dispose(); + service.dispose(); + + expect(client.closeCount, 0); + expect( + (await client.get(Uri.parse('https://example.com/other'))).body, + 'archive', + ); + }); + + test( + 'registry shutdown retires the service and removes its callback', + () async { + final client = _RecordingClient(); + final service = http.runWithClient( + PluginDownloadService.new, + () => client, + ); + addTearDown(service.dispose); + + await HttpClientRegistry.closeAll(); + await HttpClientRegistry.closeAll(); + service.dispose(); + + expect(client.closeCount, 1); + expect(HttpClientRegistry.registeredCount, registryBefore); + await expectLater( + service.downloadPluginArchive(Uri.parse('https://example.com/plugin')), + throwsStateError, + ); + }, + ); + + test('a failing client close still unregisters the service', () { + final client = _RecordingClient(throwOnClose: true); + final service = http.runWithClient(PluginDownloadService.new, () => client); + + expect(service.dispose, throwsStateError); + expect(HttpClientRegistry.registeredCount, registryBefore); + service.dispose(); + expect(client.closeCount, 1); + }); + + test('each finished download releases its abort listeners', () async { + final signals = >[]; + final client = MockClient.streaming((request, _) async { + expect(request, isA()); + signals.add((request as http.AbortableRequest).abortTrigger!); + return http.StreamedResponse(Stream.value([1, 2, 3]), 200); + }); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + await inDownloads(() async { + for (var cycle = 0; cycle < 30; cycle++) { + final path = await service.downloadPluginArchive( + Uri.parse('https://example.com/plugin'), + ); + expect(await File(path).readAsBytes(), [1, 2, 3]); + await signals.last.timeout(const Duration(seconds: 2)); + await service.cleanupDownloadedArchive(path); + } + }); + + expect(signals, hasLength(30)); + expect(await downloads.list().isEmpty, isTrue); + }); + + test('HTTP rejection cancels an otherwise unconsumed body', () async { + final cancelled = Completer(); + final body = StreamController>(onCancel: cancelled.complete); + addTearDown(body.close); + final client = MockClient.streaming((_, _) async { + return http.StreamedResponse(body.stream, 500); + }); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + await expectLater( + service.downloadPluginArchive(Uri.parse('https://example.com/plugin')), + throwsException, + ); + await cancelled.future.timeout(const Duration(seconds: 2)); + expect(await downloads.list().isEmpty, isTrue); + }); + + test('a response arriving after the header timeout is cancelled', () async { + final response = Completer(); + final cancelled = Completer(); + final body = StreamController>(onCancel: cancelled.complete); + addTearDown(body.close); + final client = MockClient.streaming((_, _) => response.future); + addTearDown(client.close); + final service = PluginDownloadService( + client: client, + stallTimeout: const Duration(milliseconds: 20), + ); + addTearDown(service.dispose); + + await expectLater( + service.downloadPluginArchive(Uri.parse('https://example.com/plugin')), + throwsA(isA()), + ); + response.complete(http.StreamedResponse(body.stream, 200)); + await cancelled.future.timeout(const Duration(seconds: 2)); + }); + + test('file creation failure removes its temporary directory', () async { + final client = MockClient((_) async => http.Response('archive', 200)); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + await inDownloads(() async { + await expectLater( + service.downloadPluginArchive( + Uri.parse('https://example.com/${'a' * 400}'), + ), + throwsA(isA()), + ); + }); + expect(await downloads.list().isEmpty, isTrue); + }); + + test( + 'a body failure preserves its cause and removes the partial file', + () async { + final failure = StateError('body failed'); + final client = MockClient.streaming((_, _) async { + Stream> body() async* { + yield [1, 2, 3]; + throw failure; + } + + return http.StreamedResponse(body(), 200); + }); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + await inDownloads(() async { + await expectLater( + service.downloadPluginArchive( + Uri.parse('https://example.com/plugin'), + ), + throwsA(same(failure)), + ); + }); + expect(await downloads.list().isEmpty, isTrue); + }, + ); + + test( + 'disposal does not disguise a temporary-directory cleanup failure', + () async { + const failure = FileSystemException('cleanup denied'); + late final PluginDownloadService service; + final client = MockClient.streaming((_, _) async { + Stream> body() async* { + yield [1, 2, 3]; + service.dispose(); + throw http.ClientException('connection closed'); + } + + return http.StreamedResponse(body(), 200); + }); + addTearDown(client.close); + service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + await IOOverrides.runZoned( + () => expectLater( + service.downloadPluginArchive( + Uri.parse('https://example.com/plugin'), + ), + throwsA(same(failure)), + ), + getSystemTempDirectory: () => + _FailingCleanupDirectory(downloads, failure), + ); + expect(await downloads.list().isEmpty, isFalse); + }, + ); + + test('dispose aborts a real request waiting for response headers', () async { + final received = Completer(); + final server = await _serve((_) => received.complete()); + final service = PluginDownloadService(); + addTearDown(service.dispose); + + await inDownloads(() async { + final result = service.downloadPluginArchive(_uri(server)); + final aborted = expectLater( + result, + throwsA(isA()), + ); + await received.future.timeout(const Duration(seconds: 5)); + service.dispose(); + await aborted.timeout(const Duration(seconds: 5)); + }); + + expect(HttpClientRegistry.registeredCount, registryBefore); + expect(await downloads.list().isEmpty, isTrue); + }); + + test('dispose cancels only its download on a shared HTTP client', () async { + final downloadSent = Completer(); + final downloadRead = Completer(); + final otherReceived = Completer(); + final server = await _serve((request) async { + if (request.uri.path == '/other') { + otherReceived.complete(request); + return; + } + request.response.bufferOutput = false; + request.response.add(List.filled(8192, 1)); + await request.response.flush(); + downloadSent.complete(); + }); + final client = _BodyObservingClient(() { + if (!downloadRead.isCompleted) downloadRead.complete(); + }); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + + await inDownloads(() async { + final result = service.downloadPluginArchive(_uri(server)); + final aborted = expectLater( + result, + throwsA(isA()), + ); + final other = client.get(_uri(server, '/other')); + await downloadSent.future.timeout( + const Duration(seconds: 5), + onTimeout: () => + throw TimeoutException('server did not flush download'), + ); + await downloadRead.future.timeout( + const Duration(seconds: 5), + onTimeout: () => throw TimeoutException('client did not read download'), + ); + expect(await downloads.list().length, 1); + final otherRequest = await otherReceived.future.timeout( + const Duration(seconds: 5), + onTimeout: () => throw TimeoutException('other request not received'), + ); + service.dispose(); + await aborted.timeout( + const Duration(seconds: 5), + onTimeout: () => throw TimeoutException('download did not abort'), + ); + otherRequest.response.write('still connected'); + await otherRequest.response.close(); + expect((await other).body, 'still connected'); + }); + + expect(HttpClientRegistry.registeredCount, registryBefore); + expect(await downloads.list().isEmpty, isTrue); + }); + + test( + 'dispose aborts all concurrent downloads owned by the service', + () async { + final received = Completer(); + var requests = 0; + final server = await _serve((request) async { + request.response.add([1, 2, 3]); + await request.response.flush(); + if (++requests == 2) received.complete(); + }); + final service = PluginDownloadService(); + addTearDown(service.dispose); + + await inDownloads(() async { + final aborted = [ + for (var index = 0; index < 2; index++) + expectLater( + service.downloadPluginArchive(_uri(server, '/plugin-$index')), + throwsA(isA()), + ), + ]; + await received.future.timeout(const Duration(seconds: 5)); + service.dispose(); + await Future.wait(aborted).timeout(const Duration(seconds: 5)); + }); + + expect(HttpClientRegistry.registeredCount, registryBefore); + expect(await downloads.list().isEmpty, isTrue); + }, + ); + + test( + '30 real client lifetimes release sockets, callbacks and temp files', + () async { + final payload = List.filled(65536, 42); + final server = await _serve((request) { + request.response.add(payload); + unawaited(request.response.close()); + }); + + await inDownloads(() async { + Future cycle() async { + final service = PluginDownloadService(); + try { + final path = await service.downloadPluginArchive(_uri(server)); + expect(await File(path).readAsBytes(), payload); + await service.cleanupDownloadedArchive(path); + } finally { + service.dispose(); + } + } + + await cycle(); + await pumpEventQueue(); + final before = _descriptorCount('socket:'); + for (var index = 0; index < 30; index++) { + await cycle(); + expect(HttpClientRegistry.registeredCount, registryBefore); + } + await pumpEventQueue(); + if (before != null) { + expect(_descriptorCount('socket:'), lessThanOrEqualTo(before)); + } + }); + + expect(await downloads.list().isEmpty, isTrue); + }, + ); +} From 86de833dfefecae2fc953d346ad207a0e3bc7d4e Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Thu, 5 Nov 2026 21:28:38 +0200 Subject: [PATCH 2/2] fix(plugins): subscribe to download responses before async file setup --- .../services/plugin_download_service.dart | 66 +++++++-- ...lugin_download_service_lifecycle_test.dart | 126 ++++++++++++++++++ 2 files changed, 178 insertions(+), 14 deletions(-) diff --git a/lib/plugins/services/plugin_download_service.dart b/lib/plugins/services/plugin_download_service.dart index 54ca9b08ce..003dce655f 100644 --- a/lib/plugins/services/plugin_download_service.dart +++ b/lib/plugins/services/plugin_download_service.dart @@ -52,8 +52,7 @@ class PluginDownloadService { if (_disposed) throw StateError('PluginDownloadService is disposed'); final abort = Completer(); _downloads.add(abort); - http.StreamedResponse? response; - var responseConsumed = false; + _DownloadResponse? response; try { final resolvedUri = PluginStoreLinkParser.appendAppVersion( downloadUri, @@ -63,7 +62,6 @@ class PluginDownloadService { _checkActive(abort, downloadUri); if (response.statusCode >= 400 && resolvedUri != downloadUri) { - responseConsumed = true; final body = await utf8.decodeStream( response.stream.timeout(_stallTimeout), ); @@ -72,8 +70,8 @@ class PluginDownloadService { if (incompatible != null) throw incompatible; // סירוב שאינו אי-תאימות — מנסים את הכתובת המקורית ללא appVersion. + await response.cancel(); response = await _sendFollowingRedirects(downloadUri, storeOnly, abort); - responseConsumed = false; _checkActive(abort, downloadUri); } @@ -92,7 +90,6 @@ class PluginDownloadService { try { _checkActive(abort, downloadUri); sink = File(archivePath).openWrite(); - responseConsumed = true; await sink.addStream(response.stream.timeout(_stallTimeout)); await sink.flush(); await sink.close(); @@ -116,9 +113,7 @@ class PluginDownloadService { } finally { if (!abort.isCompleted) abort.complete(); _downloads.remove(abort); - if (response != null && !responseConsumed) { - await response.stream.listen(null).cancel(); - } + await response?.cancel(); } } @@ -151,7 +146,7 @@ class PluginDownloadService { /// שולחת GET ועוקבת אחרי הפניות **ידנית**. מעקב אוטומטי היה מאפשר /// ל-redirect מהחנות להוציא את ההורדה לשרת זר, ובכך לרוקן את הגידור /// שנעשה בנקודת הקריאה. - Future _sendFollowingRedirects( + Future<_DownloadResponse> _sendFollowingRedirects( Uri uri, bool storeOnly, Completer abort, @@ -169,12 +164,16 @@ class PluginDownloadService { )..followRedirects = false; final response = await _client .send(request) - .then((response) async { + .then<_DownloadResponse>((response) { + // רישום סינכרוני לפני החזרת התשובה: ביטול בזמן יצירת התיקייה + // חייב להגיע גם ל-body שעדיין לא התחיל להיכתב. + final body = _DownloadResponse(response); if (abort.isCompleted) { - await response.stream.listen(null).cancel(); - throw http.RequestAbortedException(request.url); + return body.cancel().then<_DownloadResponse>( + (_) => throw http.RequestAbortedException(request.url), + ); } - return response; + return body; }) .timeout(_stallTimeout); final location = response.headers['location']; @@ -183,7 +182,11 @@ class PluginDownloadService { response.statusCode < 400 && location != null; if (!isRedirect) return response; - await response.stream.timeout(_stallTimeout).drain(); + try { + await response.stream.timeout(_stallTimeout).drain(); + } finally { + await response.cancel(); + } current = current.resolve(location); } throw Exception('יותר מדי הפניות בהורדת התוסף'); @@ -204,6 +207,41 @@ class PluginDownloadService { } } +/// מחזיק subscription מיד עם קבלת הכותרות, לפני כל IO נוסף. IOClient אינו +/// מנתק body שטרם האזינו לו אם הביטול כבר הגיע; pause שומר על backpressure +/// עד שהצרכן מוכן, והביטול משחרר את החיבור גם בכשל ביצירת תיקייה או קובץ. +class _DownloadResponse { + _DownloadResponse(this._response) { + _subscription = _response.stream.listen( + _body.add, + onError: _body.addError, + onDone: _body.close, + )..pause(); + _body + ..onListen = _subscription.resume + ..onPause = _subscription.pause + ..onResume = _subscription.resume + ..onCancel = _subscription.cancel; + } + + final http.StreamedResponse _response; + final _body = StreamController>(sync: true); + late final StreamSubscription> _subscription; + + int get statusCode => _response.statusCode; + Map get headers => _response.headers; + Stream> get stream => _body.stream; + + Future cancel() async { + try { + await _subscription.cancel(); + } finally { + // בלי מאזין (למשל כש-mkdir נכשל), close ממתינה עד שיאזינו ל-stream. + unawaited(_body.close()); + } + } +} + /// לחנות אין גרסה של התוסף שתואמת לגרסת האוצריא המותקנת. נבנית מגוף תשובת /// ה-404 של החנות, שכולל את פרטי התאימות — כך שאין צורך להוריד ארכיון כדי /// לדעת מה להציג למשתמש. diff --git a/test/plugins/services/plugin_download_service_lifecycle_test.dart b/test/plugins/services/plugin_download_service_lifecycle_test.dart index 61879793d7..9c44ff67a3 100644 --- a/test/plugins/services/plugin_download_service_lifecycle_test.dart +++ b/test/plugins/services/plugin_download_service_lifecycle_test.dart @@ -70,6 +70,83 @@ class _FailingCleanupDirectory implements Directory { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } +class _DeferredTempDirectory implements Directory { + _DeferredTempDirectory(this.directory, {this.failure}); + + final Directory directory; + final FileSystemException? failure; + final creating = Completer(); + final release = Completer(); + + @override + Future createTemp([String? prefix]) async { + creating.complete(); + await release.future; + if (failure != null) throw failure!; + return directory.createTemp(prefix); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +Future<({Uri uri, Future disconnected})> _servePendingDownload() async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final peers = []; + final disconnected = Completer(); + addTearDown(() async { + for (final peer in peers) { + peer.destroy(); + } + await server.close(); + }); + server.listen((socket) { + peers.add(socket); + final request = StringBuffer(); + var replied = false; + var download = false; + void closed() { + if (download && !disconnected.isCompleted) disconnected.complete(); + socket.destroy(); + } + + Future respond() async { + try { + if (download) { + socket.write('HTTP/1.1 200 OK\r\nContent-Length: 100000\r\n\r\nx'); + await socket.flush(); + } else { + socket.write( + 'HTTP/1.1 200 OK\r\nContent-Length: 15\r\n' + 'Connection: close\r\n\r\nstill connected', + ); + await socket.flush(); + await socket.close(); + } + } on SocketException { + closed(); + } + } + + socket.listen( + (bytes) { + if (replied) return; + request.write(String.fromCharCodes(bytes)); + if (!request.toString().contains('\r\n\r\n')) return; + replied = true; + download = !request.toString().startsWith('GET /other '); + unawaited(respond()); + }, + onDone: closed, + onError: (Object _) => closed(), + ); + }); + return ( + uri: Uri.parse('http://127.0.0.1:${server.port}/plugin.otzplugin'), + disconnected: disconnected.future, + ); +} + Future _serve(void Function(HttpRequest) handle) async { final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); server.listen(handle); @@ -406,6 +483,55 @@ void main() { expect(await downloads.list().isEmpty, isTrue); }); + for (final failCreate in [false, true]) { + test( + failCreate + ? 'temporary directory creation failure closes an unread response' + : 'dispose before the file is ready closes only its response', + () async { + final failure = FileSystemException('cannot create directory'); + final deferred = _DeferredTempDirectory( + downloads, + failure: failCreate ? failure : null, + ); + final server = await _servePendingDownload(); + final client = IOClient(); + addTearDown(client.close); + final service = PluginDownloadService(client: client); + addTearDown(service.dispose); + final result = IOOverrides.runZoned( + () => service.downloadPluginArchive(server.uri), + getSystemTempDirectory: () => deferred, + ); + final failed = expectLater( + result, + throwsA( + failCreate ? same(failure) : isA(), + ), + ); + try { + await deferred.creating.future.timeout(const Duration(seconds: 5)); + if (failCreate) { + deferred.release.complete(); + } else { + service.dispose(); + } + // The peer must disconnect before the blocked mkdir is released, + // without closing the caller's client to free the connection. + await server.disconnected.timeout(const Duration(seconds: 5)); + final other = await client + .get(server.uri.resolve('/other')) + .timeout(const Duration(seconds: 5)); + expect(other.body, 'still connected'); + } finally { + if (!deferred.release.isCompleted) deferred.release.complete(); + await failed.timeout(const Duration(seconds: 5)); + } + expect(await downloads.list().isEmpty, isTrue); + }, + ); + } + test( 'dispose aborts all concurrent downloads owned by the service', () async {