fix(library): serialize native folder watcher lifecycle

This commit is contained in:
zarzet committed 2026-10-22 02:43:04 +07:00
1 parent 6406e0a561
commit eef2a18f16
2 files changed
+181 -24

No files matched your search

+58 -18
View File
@@ -33,13 +33,20 @@ class DesktopLibraryWatcher {
final Stream<String> _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<void> _registrationTail = Future<void>.value();
/// Watched root path to source ID.
Map<String, String> _roots = const {};
Map<String, String> _registeredRoots = const {};
final _pending = <String>{};
StreamSubscription<String>? _subscription;
Timer? _timer;
bool _flushing = false;
bool _disposed = false;
bool _nativeWatchRequested = false;
Future<void>? _disposing;
@visibleForTesting
Set<String> get pendingSourceIds => Set.unmodifiable(_pending);
@@ -48,25 +55,50 @@ class DesktopLibraryWatcher {
/// re-registered.
Future<void> updateSources(Iterable<LocalLibrarySource> 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<void> _queueRegistration(Future<void> Function() operation) {
final pending = _registrationTail.then((_) => operation());
_registrationTail = pending.then<void>(
(_) {},
onError: (Object _, StackTrace _) {},
);
return pending;
}
void _onChanged(String root) {
@@ -104,19 +136,27 @@ class DesktopLibraryWatcher {
}
}
Future<void> dispose() async {
Future<void> dispose() => _disposing ??= _dispose();
Future<void> _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;
}
}
+123 -6
View File
@@ -24,14 +24,19 @@ void main() {
late int unwatches;
var scanning = false;
DesktopLibraryWatcher watcher() => DesktopLibraryWatcher(
DesktopLibraryWatcher watcher({
Future<List<String>> Function(List<String>)? watch,
Future<void> 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<void>();
final release = Completer<void>();
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<void>.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<void>();
final release = Completer<void>();
final events = <String>[];
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<void>.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<void>.delayed(const Duration(milliseconds: 150));
expect(scans, ['a']);
});
}