mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-29 07:34:13 +01:00
perf(library): check song files in batches and remember the answers
Rows asked storage about one file at a time, and asked again each time a row came back after its listener had been dropped. Requests made in the same turn now go out together: document files 64 to a call, local files eight at a time. Up to 5000 answers are kept. A found file is checked again when its row returns after five minutes, so one deleted outside the app does not stay playable for the session. A CUE track is checked against its backing file, as the single check does.
This commit is contained in:
1 parent
5c6fa36291
commit
8af763e539
1 file changed
+166
-20
@@ -1,10 +1,12 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:mornye/utils/audio_format_utils.dart';
|
||||
import 'package:mornye/utils/audio_quality_badge_policy.dart';
|
||||
import 'package:mornye/services/downloaded_embedded_cover_resolver.dart';
|
||||
import 'package:mornye/services/library_database.dart';
|
||||
import 'package:mornye/services/platform_bridge.dart';
|
||||
import 'package:mornye/utils/file_access.dart';
|
||||
|
||||
bool queueLibraryCountsHaveContent(QueueLibraryCounts counts) =>
|
||||
@@ -128,6 +130,10 @@ typedef LibraryFilePathNormalizer = String Function(String? path);
|
||||
/// rebuilt (for example after returning from the Metadata screen).
|
||||
class LibraryFileAvailabilityCache {
|
||||
static const int _defaultMaxEntries = 500;
|
||||
static const int _maxResultEntries = 5000;
|
||||
static const int _safBatchSize = 64;
|
||||
static const int _maxConcurrentLocalProbes = 8;
|
||||
static const Duration _foundRecheckAfter = Duration(minutes: 5);
|
||||
static const List<Duration> _defaultRetryDelays = [
|
||||
Duration(milliseconds: 350),
|
||||
Duration(milliseconds: 700),
|
||||
@@ -140,12 +146,14 @@ class LibraryFileAvailabilityCache {
|
||||
final List<Duration> _retryDelays;
|
||||
final Duration _missingRecheckAfter;
|
||||
final int _maxEntries;
|
||||
final Map<String, bool> _cache = {};
|
||||
final LinkedHashMap<String, bool> _cache = LinkedHashMap<String, bool>();
|
||||
final Map<String, DateTime> _checkedAt = {};
|
||||
final Map<String, _LibraryFileAvailabilityNotifier> _notifiers = {};
|
||||
final Map<String, Timer> _retryTimers = {};
|
||||
final Map<String, int> _generations = {};
|
||||
final Set<String> _probingPaths = {};
|
||||
final Map<String, ({int generation, int attempt})> _pendingProbes = {};
|
||||
Timer? _flushTimer;
|
||||
final ValueNotifier<bool> _alwaysMissingNotifier = ValueNotifier(false);
|
||||
bool _disposed = false;
|
||||
|
||||
@@ -167,9 +175,9 @@ class LibraryFileAvailabilityCache {
|
||||
final path = _normalizePath(filePath);
|
||||
if (path.isEmpty || _disposed) return _alwaysMissingNotifier;
|
||||
|
||||
final cached = _cache[path];
|
||||
final existingNotifier = _notifiers[path];
|
||||
if (existingNotifier != null) {
|
||||
final cached = _cache[path];
|
||||
if (cached != null && existingNotifier.value != cached) {
|
||||
existingNotifier.value = cached;
|
||||
}
|
||||
@@ -184,9 +192,15 @@ class LibraryFileAvailabilityCache {
|
||||
}
|
||||
|
||||
_evictUnusedEntriesIfNeeded();
|
||||
final notifier = _LibraryFileAvailabilityNotifier(_cache[path] ?? true);
|
||||
final notifier = _LibraryFileAvailabilityNotifier(cached ?? true);
|
||||
_notifiers[path] = notifier;
|
||||
_beginProbe(path);
|
||||
if (cached == null) {
|
||||
_beginProbe(path);
|
||||
} else if (cached ? _foundIsStale(path) : _confirmedMissIsStale(path)) {
|
||||
_beginProbe(path, force: true);
|
||||
} else {
|
||||
_touchCachedResult(path, cached);
|
||||
}
|
||||
return notifier;
|
||||
}
|
||||
|
||||
@@ -207,27 +221,51 @@ class LibraryFileAvailabilityCache {
|
||||
|
||||
_generations[path] = (_generations[path] ?? 0) + 1;
|
||||
_retryTimers.remove(path)?.cancel();
|
||||
_pendingProbes.remove(path);
|
||||
_probingPaths.remove(path);
|
||||
_cache[path] = true;
|
||||
_checkedAt[path] = DateTime.now();
|
||||
_recordResult(path, true);
|
||||
final notifier = _notifiers[path];
|
||||
if (notifier != null && !notifier.value) {
|
||||
notifier.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
void _touchCachedResult(String path, bool exists) {
|
||||
_cache.remove(path);
|
||||
_cache[path] = exists;
|
||||
}
|
||||
|
||||
void _recordResult(String path, bool exists) {
|
||||
_touchCachedResult(path, exists);
|
||||
_checkedAt[path] = DateTime.now();
|
||||
while (_cache.length > _maxResultEntries) {
|
||||
final oldest = _cache.keys.first;
|
||||
_cache.remove(oldest);
|
||||
_checkedAt.remove(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
bool _confirmedMissIsStale(String path) {
|
||||
final checkedAt = _checkedAt[path];
|
||||
return checkedAt == null ||
|
||||
DateTime.now().difference(checkedAt) >= _missingRecheckAfter;
|
||||
}
|
||||
|
||||
/// A found file is checked again when its card returns after this long, so
|
||||
/// one deleted outside the app does not stay playable for the session.
|
||||
bool _foundIsStale(String path) {
|
||||
final checkedAt = _checkedAt[path];
|
||||
return checkedAt == null ||
|
||||
DateTime.now().difference(checkedAt) >= _foundRecheckAfter;
|
||||
}
|
||||
|
||||
void _beginProbe(String path, {bool force = false, bool optimistic = false}) {
|
||||
if (_disposed || (!force && _probingPaths.contains(path))) return;
|
||||
|
||||
final generation = (_generations[path] ?? 0) + 1;
|
||||
_generations[path] = generation;
|
||||
_retryTimers.remove(path)?.cancel();
|
||||
_pendingProbes.remove(path);
|
||||
_probingPaths.add(path);
|
||||
_cache.remove(path);
|
||||
_checkedAt.remove(path);
|
||||
@@ -235,18 +273,125 @@ class LibraryFileAvailabilityCache {
|
||||
final notifier = _notifiers[path];
|
||||
if (notifier != null && !notifier.value) notifier.value = true;
|
||||
}
|
||||
unawaited(_probe(path, generation: generation, attempt: 0));
|
||||
_enqueueProbe(path, generation: generation, attempt: 0);
|
||||
}
|
||||
|
||||
Future<void> _probe(
|
||||
void _enqueueProbe(
|
||||
String path, {
|
||||
required int generation,
|
||||
required int attempt,
|
||||
}) async {
|
||||
var exists = false;
|
||||
try {
|
||||
exists = await _pathExists(path);
|
||||
} catch (_) {}
|
||||
}) {
|
||||
if (_disposed || _generations[path] != generation) return;
|
||||
_pendingProbes[path] = (generation: generation, attempt: attempt);
|
||||
_flushTimer ??= Timer(Duration.zero, _flushPendingProbes);
|
||||
}
|
||||
|
||||
void _flushPendingProbes() {
|
||||
_flushTimer = null;
|
||||
if (_disposed || _pendingProbes.isEmpty) return;
|
||||
|
||||
final batch = Map<String, ({int generation, int attempt})>.of(
|
||||
_pendingProbes,
|
||||
);
|
||||
_pendingProbes.clear();
|
||||
|
||||
final canBatchSaf = identical(_pathExists, fileExists);
|
||||
final safEntries = <MapEntry<String, ({int generation, int attempt})>>[];
|
||||
final singleEntries = <MapEntry<String, ({int generation, int attempt})>>[];
|
||||
for (final entry in batch.entries) {
|
||||
if (_generations[entry.key] != entry.value.generation) continue;
|
||||
if (canBatchSaf && isContentUri(entry.key)) {
|
||||
safEntries.add(entry);
|
||||
} else {
|
||||
singleEntries.add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (safEntries.isNotEmpty) {
|
||||
unawaited(_probeSafBatch(safEntries));
|
||||
}
|
||||
if (singleEntries.isNotEmpty) {
|
||||
unawaited(_probeSingleBatch(singleEntries));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _probeSafBatch(
|
||||
List<MapEntry<String, ({int generation, int attempt})>> entries,
|
||||
) async {
|
||||
for (var i = 0; i < entries.length; i += _safBatchSize) {
|
||||
if (_disposed) return;
|
||||
final end = i + _safBatchSize > entries.length
|
||||
? entries.length
|
||||
: i + _safBatchSize;
|
||||
final chunk = entries.sublist(i, end);
|
||||
// A CUE track is checked against its backing file, as fileExists does.
|
||||
final uris = {
|
||||
for (final entry in chunk) stripCueTrackSuffix(entry.key),
|
||||
}.toList(growable: false);
|
||||
Map<String, bool?>? results;
|
||||
try {
|
||||
results = await PlatformBridge.safExistsBatch(uris);
|
||||
} catch (_) {}
|
||||
if (_disposed) return;
|
||||
|
||||
final fallback = <MapEntry<String, ({int generation, int attempt})>>[];
|
||||
for (final entry in chunk) {
|
||||
if (_generations[entry.key] != entry.value.generation) continue;
|
||||
final exists = results?[stripCueTrackSuffix(entry.key)];
|
||||
if (exists != null) {
|
||||
_handleProbeResult(
|
||||
entry.key,
|
||||
generation: entry.value.generation,
|
||||
attempt: entry.value.attempt,
|
||||
exists: exists,
|
||||
);
|
||||
} else {
|
||||
fallback.add(entry);
|
||||
}
|
||||
}
|
||||
if (fallback.isNotEmpty) {
|
||||
await _probeSingleBatch(fallback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _probeSingleBatch(
|
||||
List<MapEntry<String, ({int generation, int attempt})>> entries,
|
||||
) async {
|
||||
var cursor = 0;
|
||||
final workers = entries.length < _maxConcurrentLocalProbes
|
||||
? entries.length
|
||||
: _maxConcurrentLocalProbes;
|
||||
Future<void> worker() async {
|
||||
while (!_disposed) {
|
||||
if (cursor >= entries.length) return;
|
||||
final entry = entries[cursor++];
|
||||
final path = entry.key;
|
||||
final generation = entry.value.generation;
|
||||
if (_generations[path] != generation) continue;
|
||||
var exists = false;
|
||||
try {
|
||||
exists = await _pathExists(path);
|
||||
} catch (_) {}
|
||||
if (_disposed || _generations[path] != generation) continue;
|
||||
_handleProbeResult(
|
||||
path,
|
||||
generation: generation,
|
||||
attempt: entry.value.attempt,
|
||||
exists: exists,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await Future.wait([for (var i = 0; i < workers; i++) worker()]);
|
||||
}
|
||||
|
||||
void _handleProbeResult(
|
||||
String path, {
|
||||
required int generation,
|
||||
required int attempt,
|
||||
required bool exists,
|
||||
}) {
|
||||
if (_disposed || _generations[path] != generation) return;
|
||||
|
||||
if (exists) {
|
||||
@@ -258,14 +403,13 @@ class LibraryFileAvailabilityCache {
|
||||
_retryTimers[path] = Timer(_retryDelays[attempt], () {
|
||||
_retryTimers.remove(path);
|
||||
if (_disposed || _generations[path] != generation) return;
|
||||
unawaited(_probe(path, generation: generation, attempt: attempt + 1));
|
||||
_enqueueProbe(path, generation: generation, attempt: attempt + 1);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
_probingPaths.remove(path);
|
||||
_cache[path] = false;
|
||||
_checkedAt[path] = DateTime.now();
|
||||
_recordResult(path, false);
|
||||
final notifier = _notifiers[path];
|
||||
if (notifier != null && notifier.value) notifier.value = false;
|
||||
}
|
||||
@@ -280,15 +424,14 @@ class LibraryFileAvailabilityCache {
|
||||
}
|
||||
}
|
||||
if (evictionPath == null) return;
|
||||
_removeEntry(evictionPath);
|
||||
_removeNotifierOnly(evictionPath);
|
||||
}
|
||||
}
|
||||
|
||||
void _removeEntry(String path) {
|
||||
void _removeNotifierOnly(String path) {
|
||||
_retryTimers.remove(path)?.cancel();
|
||||
_pendingProbes.remove(path);
|
||||
_probingPaths.remove(path);
|
||||
_cache.remove(path);
|
||||
_checkedAt.remove(path);
|
||||
_generations.remove(path);
|
||||
_notifiers.remove(path)?.dispose();
|
||||
}
|
||||
@@ -296,6 +439,9 @@ class LibraryFileAvailabilityCache {
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_flushTimer?.cancel();
|
||||
_flushTimer = null;
|
||||
_pendingProbes.clear();
|
||||
for (final timer in _retryTimers.values) {
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user