From eef2a18f16add2aedd379aad2d431ab286c7a4ce Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:43:04 +0700 Subject: [PATCH] fix(library): serialize native folder watcher lifecycle --- lib/services/desktop_library_watcher.dart | 76 ++++++++++--- test/desktop_library_watcher_test.dart | 129 +++++++++++++++++++++- 2 files changed, 181 insertions(+), 24 deletions(-) diff --git a/lib/services/desktop_library_watcher.dart b/lib/services/desktop_library_watcher.dart index 7b466f141..f928d5c4c 100644 --- a/lib/services/desktop_library_watcher.dart +++ b/lib/services/desktop_library_watcher.dart @@ -33,13 +33,20 @@ class DesktopLibraryWatcher { final Stream _changes; final Duration debounce; + // Native folder watching belongs to the process, including across a rapid + // disable/enable cycle that replaces this Dart watcher before dispose ends. + static Future _registrationTail = Future.value(); + /// Watched root path to source ID. Map _roots = const {}; + Map _registeredRoots = const {}; final _pending = {}; StreamSubscription? _subscription; Timer? _timer; bool _flushing = false; bool _disposed = false; + bool _nativeWatchRequested = false; + Future? _disposing; @visibleForTesting Set get pendingSourceIds => Set.unmodifiable(_pending); @@ -48,25 +55,50 @@ class DesktopLibraryWatcher { /// re-registered. Future updateSources(Iterable sources) async { if (_disposed) return; - _subscription ??= _changes.listen(_onChanged); + _subscription ??= _changes.listen( + _onChanged, + onError: (Object error) => + _log.w('Library folder change stream failed: $error'), + ); final roots = { for (final source in sources) if (source.enabled && source.available && source.path.isNotEmpty) source.path: source.id, }; - if (mapEquals(roots, _roots)) return; _roots = roots; _pending.removeWhere((id) => !roots.containsValue(id)); - try { - if (roots.isEmpty) { - await _unwatch(); - } else { - final watched = await _watch(roots.keys.toList(growable: false)); - _log.d('Watching ${watched.length} of ${roots.length} library folders'); + await _queueRegistration(() async { + if (_disposed || + !mapEquals(roots, _roots) || + (mapEquals(roots, _registeredRoots) && + (roots.isNotEmpty || !_nativeWatchRequested))) { + return; } - } catch (error) { - _log.w('Could not watch library folders: $error'); - } + try { + if (roots.isEmpty) { + await _unwatch(); + _nativeWatchRequested = false; + } else { + _nativeWatchRequested = true; + final watched = await _watch(roots.keys.toList(growable: false)); + _log.d( + 'Watching ${watched.length} of ${roots.length} library folders', + ); + } + _registeredRoots = roots; + } catch (error) { + _log.w('Could not watch library folders: $error'); + } + }); + } + + static Future _queueRegistration(Future Function() operation) { + final pending = _registrationTail.then((_) => operation()); + _registrationTail = pending.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + return pending; } void _onChanged(String root) { @@ -104,19 +136,27 @@ class DesktopLibraryWatcher { } } - Future dispose() async { + Future dispose() => _disposing ??= _dispose(); + + Future _dispose() async { _disposed = true; _timer?.cancel(); - await _subscription?.cancel(); - _subscription = null; - _pending.clear(); - if (_roots.isNotEmpty) { - _roots = const {}; + // Queue cleanup before awaiting the stream so a replacement watcher can + // register only after this instance's pending native work has stopped. + final stopped = _queueRegistration(() async { + if (!_nativeWatchRequested) return; try { await _unwatch(); } catch (_) { // Shutting down; the backend drops its watcher with the process. } - } + _nativeWatchRequested = false; + _registeredRoots = const {}; + }); + await _subscription?.cancel(); + _subscription = null; + _pending.clear(); + _roots = const {}; + await stopped; } } diff --git a/test/desktop_library_watcher_test.dart b/test/desktop_library_watcher_test.dart index f912790cf..60c7cb1d2 100644 --- a/test/desktop_library_watcher_test.dart +++ b/test/desktop_library_watcher_test.dart @@ -24,14 +24,19 @@ void main() { late int unwatches; var scanning = false; - DesktopLibraryWatcher watcher() => DesktopLibraryWatcher( + DesktopLibraryWatcher watcher({ + Future> Function(List)? watch, + Future Function()? unwatch, + }) => DesktopLibraryWatcher( scanSource: (id) async => scans.add(id), isScanning: () => scanning, - watch: (paths) async { - watched.add(paths); - return paths; - }, - unwatch: () async => unwatches++, + watch: + watch ?? + (paths) async { + watched.add(paths); + return paths; + }, + unwatch: unwatch ?? () async => unwatches++, changes: changes.stream, debounce: const Duration(milliseconds: 60), ); @@ -108,4 +113,116 @@ void main() { expect(scans, isEmpty); expect(unwatches, 1); }); + + test('a failed registration can retry an unchanged source set', () async { + var attempts = 0; + final subject = watcher( + watch: (paths) async { + if (++attempts == 1) throw StateError('temporarily unavailable'); + watched.add(paths); + return paths; + }, + ); + addTearDown(subject.dispose); + await subject.updateSources([_source('a', '/music/a')]); + await subject.updateSources([_source('a', '/music/a')]); + expect(attempts, 2); + expect(watched, [ + ['/music/a'], + ]); + }); + + test('registration changes stay ordered and skip superseded roots', () async { + final started = Completer(); + final release = Completer(); + final subject = watcher( + watch: (paths) async { + watched.add(paths); + if (paths.single == '/music/a') { + started.complete(); + await release.future; + } + return paths; + }, + ); + addTearDown(subject.dispose); + addTearDown(() { + if (!release.isCompleted) release.complete(); + }); + final first = subject.updateSources([_source('a', '/music/a')]); + await started.future; + final superseded = subject.updateSources([_source('b', '/music/b')]); + final latest = subject.updateSources([_source('c', '/music/c')]); + await Future.delayed(Duration.zero); + expect(watched, [ + ['/music/a'], + ]); + release.complete(); + await Future.wait([first, superseded, latest]); + expect(watched, [ + ['/music/a'], + ['/music/c'], + ]); + }); + + test( + 'replacement registration waits for the disposed native watch', + () async { + final started = Completer(); + final release = Completer(); + final events = []; + final previous = watcher( + watch: (paths) async { + events.add('old watch'); + started.complete(); + await release.future; + return paths; + }, + unwatch: () async => events.add('old stop'), + ); + final registration = previous.updateSources([_source('a', '/music/a')]); + await started.future; + final disposed = previous.dispose(); + final replacement = watcher( + watch: (paths) async { + events.add('new watch'); + return paths; + }, + ); + addTearDown(replacement.dispose); + addTearDown(() { + if (!release.isCompleted) release.complete(); + }); + final replaced = replacement.updateSources([_source('b', '/music/b')]); + await Future.delayed(Duration.zero); + expect(events, ['old watch']); + release.complete(); + await Future.wait([registration, disposed, replaced]); + expect(events, ['old watch', 'old stop', 'new watch']); + await previous.dispose(); + expect(events, ['old watch', 'old stop', 'new watch']); + }, + ); + + test('empty sources stop a partially failed registration', () async { + final subject = watcher( + watch: (_) async => throw StateError('registration failed'), + ); + addTearDown(subject.dispose); + await subject.updateSources([_source('a', '/music/a')]); + await subject.updateSources(const []); + expect(unwatches, 1); + await subject.dispose(); + expect(unwatches, 1); + }); + + test('an event stream error does not abort later rescans', () async { + final subject = watcher(); + addTearDown(subject.dispose); + await subject.updateSources([_source('a', '/music/a')]); + changes.addError(StateError('temporary stream error')); + changes.add('/music/a'); + await Future.delayed(const Duration(milliseconds: 150)); + expect(scans, ['a']); + }); }