perf: batch download status checks on Home view

Replace 8+ sequential per-section IPC calls with a single batch
command. Backend reads all tracks once instead of N times.

- Add v2_check_albums_fully_cached_batch (single DB read, HashMap return)
- Remove per-section await tick() + loadAllAlbumDownloadStatuses() calls
- Single batch call at end of loadHome() after all data resolves
- Keep individual check for on-click refresh (single album)

cc
This commit is contained in:
victorrhgap committed 2026-03-24 15:58:24 -06:00
1 parent 3366c2e8d9
commit 1a5104150a
4 files changed
+85 -34

No files matched your search

+11
View File
@@ -11594,6 +11594,17 @@ pub async fn v2_check_album_fully_cached(
.map_err(RuntimeError::Internal)
}
#[tauri::command]
#[allow(non_snake_case)]
pub async fn v2_check_albums_fully_cached_batch(
albumIds: Vec<String>,
cache_state: State<'_, crate::offline_cache::OfflineCacheState>,
) -> Result<std::collections::HashMap<String, bool>, RuntimeError> {
crate::offline_cache::commands::check_albums_fully_cached_batch(albumIds, cache_state)
.await
.map_err(RuntimeError::Internal)
}
/// Shared helper: spawn the download task for a single track.
/// Used by both v2_cache_track_for_offline (single) and v2_cache_tracks_batch_for_offline (batch).
fn spawn_track_cache_download(
+1
View File
@@ -1564,6 +1564,7 @@ pub fn run() {
commands_v2::v2_discogs_search_artwork,
commands_v2::v2_discogs_download_artwork,
commands_v2::v2_check_album_fully_cached,
commands_v2::v2_check_albums_fully_cached_batch,
commands_v2::v2_purchases_get_all,
commands_v2::v2_purchases_get_ids,
commands_v2::v2_purchases_get_by_type,
+46
View File
@@ -771,6 +771,52 @@ pub async fn check_album_fully_cached(
Ok(true)
}
/// Batch check which albums are fully cached (all tracks ready).
/// Single DB read instead of N individual calls.
#[tauri::command]
pub async fn check_albums_fully_cached_batch(
album_ids: Vec<String>,
cache_state: State<'_, OfflineCacheState>,
) -> Result<std::collections::HashMap<String, bool>, String> {
use std::collections::HashMap;
if album_ids.is_empty() {
return Ok(HashMap::new());
}
let guard__ = cache_state.db.lock().await;
let db = guard__
.as_ref()
.ok_or("No active session - please log in")?;
let tracks = db.get_all_tracks()?;
// Group tracks by album_id
let mut album_tracks: HashMap<&str, (usize, usize)> = HashMap::new(); // (total, ready)
for track in &tracks {
if let Some(ref aid) = track.album_id {
let entry = album_tracks.entry(aid.as_str()).or_insert((0, 0));
entry.0 += 1;
if track.status == crate::offline_cache::OfflineCacheStatus::Ready {
entry.1 += 1;
}
}
}
let result: HashMap<String, bool> = album_ids
.into_iter()
.map(|id| {
let fully_cached = album_tracks
.get(id.as_str())
.map(|(total, ready)| *total > 0 && *total == *ready)
.unwrap_or(false);
(id, fully_cached)
})
.collect();
Ok(result)
}
/// Evict tracks if cache exceeds limit (LRU policy)
async fn evict_if_needed(cache_state: &OfflineCacheState, limit_bytes: u64) -> Result<(), String> {
let guard__ = cache_state.db.lock().await;
+27 -34
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onMount, tick } from 'svelte';
import { onMount } from 'svelte';
import { invoke } from '@tauri-apps/api/core';
import { resolveArtistImage } from '$lib/stores/customArtistImageStore';
import { Music, User, Loader2, ArrowRight, Home } from 'lucide-svelte';
@@ -299,29 +299,30 @@
let failedArtistImages = $state<Set<number>>(new Set());
// Download status tracking
// Download status tracking — single batch call via backend
let albumDownloadStatuses = $state<Map<string, boolean>>(new Map());
let downloadStatusTick = $state(0);
async function loadAlbumDownloadStatus(albumId: string) {
if (!checkAlbumFullyDownloaded) return false;
if (!checkAlbumFullyDownloaded) return;
try {
const isDownloaded = await checkAlbumFullyDownloaded(albumId);
albumDownloadStatuses.set(albumId, isDownloaded);
downloadStatusTick++;
return isDownloaded;
} catch {
return false;
}
} catch { /* ignore */ }
}
async function loadAllAlbumDownloadStatuses(albums: AlbumCardData[]) {
if (!checkAlbumFullyDownloaded || albums.length === 0) return;
const BATCH_SIZE = 6;
for (let i = 0; i < albums.length; i += BATCH_SIZE) {
const batch = albums.slice(i, i + BATCH_SIZE);
await Promise.all(batch.map(album => loadAlbumDownloadStatus(album.id)));
async function loadAllAlbumDownloadStatusesBatch(albums: AlbumCardData[]) {
if (albums.length === 0) return;
const albumIds = albums.map(a => a.id);
try {
const result = await invoke<Record<string, boolean>>('v2_check_albums_fully_cached_batch', { albumIds });
for (const [id, downloaded] of Object.entries(result)) {
albumDownloadStatuses.set(id, downloaded);
}
downloadStatusTick++;
} catch {
// Offline cache not available — ignore
}
}
@@ -342,7 +343,7 @@
...recentAlbums,
...favoriteAlbums
];
loadAllAlbumDownloadStatuses(allAlbums);
loadAllAlbumDownloadStatusesBatch(allAlbums);
}
});
@@ -400,7 +401,7 @@
...cached.qobuzissimes, ...cached.editorPicks,
...cached.recentAlbums, ...cached.favoriteAlbums
];
loadAllAlbumDownloadStatuses(allAlbums);
loadAllAlbumDownloadStatusesBatch(allAlbums);
}
onMount(() => {
@@ -747,8 +748,6 @@
if (c.new_releases?.data?.items) {
newReleases = c.new_releases.data.items.slice(0, homeLimits.featuredAlbums).map(discoverAlbumToCardData);
loadingNewReleases = false;
await tick();
loadAllAlbumDownloadStatuses(newReleases).catch(() => {});
} else {
loadingNewReleases = false;
}
@@ -756,8 +755,6 @@
if (c.press_awards?.data?.items) {
pressAwards = c.press_awards.data.items.slice(0, homeLimits.featuredAlbums).map(discoverAlbumToCardData);
loadingPressAwards = false;
await tick();
loadAllAlbumDownloadStatuses(pressAwards).catch(() => {});
} else {
loadingPressAwards = false;
}
@@ -765,8 +762,6 @@
if (c.most_streamed?.data?.items) {
mostStreamed = c.most_streamed.data.items.slice(0, homeLimits.featuredAlbums).map(discoverAlbumToCardData);
loadingMostStreamed = false;
await tick();
loadAllAlbumDownloadStatuses(mostStreamed).catch(() => {});
} else {
loadingMostStreamed = false;
}
@@ -774,8 +769,6 @@
if (c.qobuzissims?.data?.items) {
qobuzissimes = c.qobuzissims.data.items.slice(0, homeLimits.featuredAlbums).map(discoverAlbumToCardData);
loadingQobuzissimes = false;
await tick();
loadAllAlbumDownloadStatuses(qobuzissimes).catch(() => {});
} else {
loadingQobuzissimes = false;
}
@@ -783,8 +776,6 @@
if (c.album_of_the_week?.data?.items) {
editorPicks = c.album_of_the_week.data.items.slice(0, homeLimits.featuredAlbums).map(discoverAlbumToCardData);
loadingEditorPicks = false;
await tick();
loadAllAlbumDownloadStatuses(editorPicks).catch(() => {});
} else {
loadingEditorPicks = false;
}
@@ -856,11 +847,8 @@
const resolved = await mlPromise;
// Recently Played Albums (always fetch, visibility applied in template)
const filteredRecent = filterAlbumsByGenre(resolved.recentlyPlayedAlbums).slice(0, homeLimits.recentAlbums);
recentAlbums = filteredRecent;
recentAlbums = filterAlbumsByGenre(resolved.recentlyPlayedAlbums).slice(0, homeLimits.recentAlbums);
loadingRecentAlbums = false;
await tick();
loadAllAlbumDownloadStatuses(filteredRecent).catch(() => {});
// Continue Listening Tracks
continueTracks = resolved.continueListeningTracks;
@@ -871,11 +859,8 @@
loadingTopArtists = false;
// Favorite Albums
const filteredFavs = filterAlbumsByGenre(resolved.favoriteAlbums).slice(0, homeLimits.favoriteAlbums);
favoriteAlbums = filteredFavs;
favoriteAlbums = filterAlbumsByGenre(resolved.favoriteAlbums).slice(0, homeLimits.favoriteAlbums);
loadingFavoriteAlbums = false;
await tick();
loadAllAlbumDownloadStatuses(filteredFavs).catch(() => {});
} catch (err) {
console.error('Home resolved failed:', err);
@@ -888,6 +873,14 @@
// Ensure discover promise completes (errors already handled internally)
await discoverPromise;
// Single batch download status check for ALL albums at once
const allAlbums = [
...newReleases, ...pressAwards, ...mostStreamed,
...qobuzissimes, ...editorPicks,
...recentAlbums, ...favoriteAlbums
];
loadAllAlbumDownloadStatusesBatch(allAlbums).catch(() => {});
}
</script>