perf: add batch offline cache command to replace sequential IPC loops

Add v2_cache_tracks_batch_for_offline command that inserts all tracks
in a single SQLite transaction and spawns download tasks in one IPC
call. Extract spawn_track_cache_download helper shared by both single
and batch commands.

Replace sequential for-of loops with batch calls in PlaylistDetailView
and +page.svelte (downloadAlbumById, handleDownloadAlbum,
handleReDownloadAlbum, reDownloadAlbumById). Single-track handlers
remain unchanged.

Reduces 75 IPC round-trips to 1 for bulk downloads.
This commit is contained in:
vicrodh committed 2026-02-17 10:59:02 -06:00
1 parent 343bfff357
commit 644571f82a
6 files changed
+284 -126

No files matched your search

+135 -45
View File
@@ -6364,52 +6364,19 @@ pub async fn v2_subscribe_playlist(
.map_err(|e| format!("Failed to fetch created playlist: {}", e))
}
#[tauri::command]
pub async fn v2_cache_track_for_offline(
/// 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(
track_id: u64,
title: String,
artist: String,
album: Option<String>,
album_id: Option<String>,
duration_secs: u64,
quality: String,
bit_depth: Option<u32>,
sample_rate: Option<f64>,
state: State<'_, AppState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::LibraryState>,
app_handle: tauri::AppHandle,
) -> Result<(), String> {
log::info!("Command: v2_cache_track_for_offline {} - {} by {}", track_id, title, artist);
let track_info = crate::offline_cache::TrackCacheInfo {
track_id,
title,
artist,
album,
album_id,
duration_secs,
quality,
bit_depth,
sample_rate,
};
let file_path = cache_state.track_file_path(track_id, "flac");
let file_path_str = file_path.to_string_lossy().to_string();
{
let guard = cache_state.db.lock().await;
let db = guard.as_ref().ok_or("No active session - please log in")?;
db.insert_track(&track_info, &file_path_str)?;
}
let client = state.client.clone();
let fetcher = cache_state.fetcher.clone();
let db = cache_state.db.clone();
let offline_root = cache_state.get_cache_path();
let library_db = library_state.db.clone();
let app = app_handle.clone();
let semaphore = cache_state.cache_semaphore.clone();
file_path: std::path::PathBuf,
client: std::sync::Arc<tokio::sync::RwLock<crate::api::QobuzClient>>,
fetcher: std::sync::Arc<crate::offline_cache::StreamFetcher>,
db: std::sync::Arc<tokio::sync::Mutex<Option<crate::offline_cache::OfflineCacheDb>>>,
offline_root: String,
library_db: std::sync::Arc<tokio::sync::Mutex<Option<qbz_library::LibraryDatabase>>>,
app: tauri::AppHandle,
semaphore: std::sync::Arc<tokio::sync::Semaphore>,
) {
tokio::spawn(async move {
let _permit = match semaphore.acquire_owned().await {
Ok(permit) => permit,
@@ -6567,6 +6534,129 @@ pub async fn v2_cache_track_for_offline(
}
}
});
}
#[tauri::command]
pub async fn v2_cache_track_for_offline(
track_id: u64,
title: String,
artist: String,
album: Option<String>,
album_id: Option<String>,
duration_secs: u64,
quality: String,
bit_depth: Option<u32>,
sample_rate: Option<f64>,
state: State<'_, AppState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::LibraryState>,
app_handle: tauri::AppHandle,
) -> Result<(), String> {
log::info!("Command: v2_cache_track_for_offline {} - {} by {}", track_id, title, artist);
let track_info = crate::offline_cache::TrackCacheInfo {
track_id,
title,
artist,
album,
album_id,
duration_secs,
quality,
bit_depth,
sample_rate,
};
let file_path = cache_state.track_file_path(track_id, "flac");
let file_path_str = file_path.to_string_lossy().to_string();
{
let guard = cache_state.db.lock().await;
let db = guard.as_ref().ok_or("No active session - please log in")?;
db.insert_track(&track_info, &file_path_str)?;
}
spawn_track_cache_download(
track_id,
file_path,
state.client.clone(),
cache_state.fetcher.clone(),
cache_state.db.clone(),
cache_state.get_cache_path(),
library_state.db.clone(),
app_handle.clone(),
cache_state.cache_semaphore.clone(),
);
Ok(())
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchTrackInfo {
pub id: u64,
pub title: String,
pub artist: String,
pub album: Option<String>,
pub album_id: Option<String>,
pub duration_secs: u64,
pub quality: String,
pub bit_depth: Option<u32>,
pub sample_rate: Option<f64>,
}
#[tauri::command]
pub async fn v2_cache_tracks_batch_for_offline(
tracks: Vec<BatchTrackInfo>,
state: State<'_, AppState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::LibraryState>,
app_handle: tauri::AppHandle,
) -> Result<(), String> {
log::info!("Command: v2_cache_tracks_batch_for_offline ({} tracks)", tracks.len());
// Build TrackCacheInfo + file_path pairs for batch insert
let mut batch: Vec<(crate::offline_cache::TrackCacheInfo, String)> = Vec::with_capacity(tracks.len());
for track in &tracks {
let file_path = cache_state.track_file_path(track.id, "flac");
let file_path_str = file_path.to_string_lossy().to_string();
batch.push((
crate::offline_cache::TrackCacheInfo {
track_id: track.id,
title: track.title.clone(),
artist: track.artist.clone(),
album: track.album.clone(),
album_id: track.album_id.clone(),
duration_secs: track.duration_secs,
quality: track.quality.clone(),
bit_depth: track.bit_depth,
sample_rate: track.sample_rate,
},
file_path_str,
));
}
// Single transactional batch insert
{
let guard = cache_state.db.lock().await;
let db = guard.as_ref().ok_or("No active session - please log in")?;
let refs: Vec<(&crate::offline_cache::TrackCacheInfo, String)> = batch.iter().map(|(info, path)| (info, path.clone())).collect();
db.insert_tracks_batch(&refs)?;
}
// Spawn download tasks for each track
for track in &tracks {
let file_path = cache_state.track_file_path(track.id, "flac");
spawn_track_cache_download(
track.id,
file_path,
state.client.clone(),
cache_state.fetcher.clone(),
cache_state.db.clone(),
cache_state.get_cache_path(),
library_state.db.clone(),
app_handle.clone(),
cache_state.cache_semaphore.clone(),
);
}
Ok(())
}
+1
View File
@@ -844,6 +844,7 @@ pub fn run() {
commands_v2::v2_show_track_notification,
commands_v2::v2_subscribe_playlist,
commands_v2::v2_cache_track_for_offline,
commands_v2::v2_cache_tracks_batch_for_offline,
commands_v2::v2_start_legacy_migration,
commands_v2::v2_library_scan,
commands_v2::v2_library_stop_scan,
+34
View File
@@ -91,6 +91,40 @@ impl OfflineCacheDb {
Ok(())
}
/// Insert multiple tracks in a single transaction (batch queuing)
pub fn insert_tracks_batch(&self, tracks: &[(&TrackCacheInfo, String)]) -> Result<(), String> {
let tx = self.conn.unchecked_transaction()
.map_err(|e| format!("Failed to begin transaction: {}", e))?;
{
let mut stmt = tx.prepare(
"INSERT OR REPLACE INTO cached_tracks
(track_id, title, artist, album, album_id, duration_secs, file_path, quality, bit_depth, sample_rate, status, progress_percent, created_at, last_accessed_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'queued', 0, datetime('now'), datetime('now'))"
).map_err(|e| format!("Failed to prepare batch insert: {}", e))?;
for (info, file_path) in tracks {
stmt.execute(params![
info.track_id as i64,
info.title,
info.artist,
info.album,
info.album_id,
info.duration_secs as i64,
file_path,
info.quality,
info.bit_depth.map(|v| v as i64),
info.sample_rate,
]).map_err(|e| format!("Failed to insert track {}: {}", info.track_id, e))?;
}
}
tx.commit()
.map_err(|e| format!("Failed to commit batch insert: {}", e))?;
Ok(())
}
/// Update track status
pub fn update_status(
&self,
@@ -11,7 +11,7 @@
import TrackRow from '../TrackRow.svelte';
import PlaylistSuggestions from '../PlaylistSuggestions.svelte';
import { extractAdaptiveArtists } from '$lib/services/playlistSuggestionsService';
import { type OfflineCacheStatus, cacheTrackForOffline, getOfflineCacheState } from '$lib/stores/offlineCacheState';
import { type OfflineCacheStatus, cacheTrackForOffline, cacheTracksForOfflineBatch, getOfflineCacheState } from '$lib/stores/offlineCacheState';
import {
subscribe as subscribeOffline,
getStatus as getOfflineStatus,
@@ -1937,22 +1937,20 @@
const playlistName = playlist?.name || '';
showToast(translate('playlist.preparingPlaylistOffline', { values: { count: tracksToCache.length, name: playlistName } }), 'info');
for (const track of tracksToCache) {
try {
await cacheTrackForOffline({
id: track.id,
title: track.title,
artist: track.artist || 'Unknown',
album: track.album,
albumId: track.albumId,
durationSecs: track.durationSeconds,
quality: '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
});
} catch (err) {
console.error(`Failed to queue offline cache for "${track.title}":`, err);
}
try {
await cacheTracksForOfflineBatch(tracksToCache.map(track => ({
id: track.id,
title: track.title,
artist: track.artist || 'Unknown',
album: track.album,
albumId: track.albumId,
durationSecs: track.durationSeconds,
quality: '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
})));
} catch (err) {
console.error('Failed to batch queue offline cache:', err);
}
}
</script>
+42
View File
@@ -196,6 +196,48 @@ export async function cacheTrackForOffline(track: {
}
}
// Cache multiple tracks for offline in a single batch IPC call
export async function cacheTracksForOfflineBatch(tracks: Array<{
id: number;
title: string;
artist: string;
album?: string;
albumId?: string;
durationSecs: number;
quality: string;
bitDepth?: number;
sampleRate?: number;
}>): Promise<void> {
if (tracks.length === 0) return;
// Mark all as queued immediately
for (const track of tracks) {
setOfflineCacheState(track.id, { status: 'queued', progress: 0 });
}
try {
await invoke('v2_cache_tracks_batch_for_offline', {
tracks: tracks.map(track => ({
id: track.id,
title: track.title,
artist: track.artist,
album: track.album,
albumId: track.albumId,
durationSecs: track.durationSecs,
quality: track.quality,
bitDepth: track.bitDepth,
sampleRate: track.sampleRate,
})),
});
} catch (err) {
console.error('Failed to batch cache tracks for offline:', err);
for (const track of tracks) {
setOfflineCacheState(track.id, { status: 'failed', progress: 0, error: String(err) });
}
throw err;
}
}
// Remove a track from offline cache
export async function removeCachedTrack(trackId: number): Promise<void> {
try {
+57 -64
View File
@@ -15,6 +15,7 @@
startOfflineCacheEventListeners,
stopOfflineCacheEventListeners,
cacheTrackForOffline,
cacheTracksForOfflineBatch,
removeCachedTrack,
getOfflineCacheState,
openAlbumFolder,
@@ -1125,22 +1126,20 @@
showToast($t('toast.preparingTracksOffline', { values: { count: tracksToDownload.length, album: album.title } }), 'info');
for (const track of tracksToDownload) {
try {
await cacheTrackForOffline({
id: track.id,
title: track.title,
artist: track.artist || album.artist || 'Unknown',
album: album.title,
albumId: album.id,
durationSecs: track.durationSeconds,
quality: track.quality || '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
});
} catch (err) {
console.error(`Failed to queue download for "${track.title}":`, err);
}
try {
await cacheTracksForOfflineBatch(tracksToDownload.map(track => ({
id: track.id,
title: track.title,
artist: track.artist || album.artist || 'Unknown',
album: album.title,
albumId: album.id,
durationSecs: track.durationSeconds,
quality: track.quality || '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
})));
} catch (err) {
console.error('Failed to batch queue downloads:', err);
}
}
@@ -2024,22 +2023,20 @@
showToast($t('toast.preparingTracksOffline', { values: { count: tracksToDownload.length, album: selectedAlbum.title } }), 'info');
for (const track of tracksToDownload) {
try {
await cacheTrackForOffline({
id: track.id,
title: track.title,
artist: track.artist || selectedAlbum.artist || 'Unknown',
album: selectedAlbum.title,
albumId: selectedAlbum.id,
durationSecs: track.durationSeconds,
quality: track.quality || '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
});
} catch (err) {
console.error(`Failed to queue "${track.title}" for offline:`, err);
}
try {
await cacheTracksForOfflineBatch(tracksToDownload.map(track => ({
id: track.id,
title: track.title,
artist: track.artist || selectedAlbum.artist || 'Unknown',
album: selectedAlbum.title,
albumId: selectedAlbum.id,
durationSecs: track.durationSeconds,
quality: track.quality || '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
})));
} catch (err) {
console.error('Failed to batch queue for offline:', err);
}
}
@@ -2059,22 +2056,20 @@
showToast($t('toast.refreshingAlbumOffline', { values: { album: selectedAlbum.title } }), 'info');
for (const track of selectedAlbum.tracks) {
try {
await cacheTrackForOffline({
id: track.id,
title: track.title,
artist: track.artist || selectedAlbum.artist || 'Unknown',
album: selectedAlbum.title,
albumId: selectedAlbum.id,
durationSecs: track.durationSeconds,
quality: track.quality || '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
});
} catch (err) {
console.error(`Failed to refresh "${track.title}" for offline:`, err);
}
try {
await cacheTracksForOfflineBatch(selectedAlbum.tracks.map(track => ({
id: track.id,
title: track.title,
artist: track.artist || selectedAlbum.artist || 'Unknown',
album: selectedAlbum.title,
albumId: selectedAlbum.id,
durationSecs: track.durationSeconds,
quality: track.quality || '-',
bitDepth: track.bitDepth,
sampleRate: track.samplingRate,
})));
} catch (err) {
console.error('Failed to batch refresh for offline:', err);
}
}
@@ -2097,22 +2092,20 @@
showToast($t('toast.refreshingAlbumOffline', { values: { album: album.title } }), 'info');
for (const track of album.tracks.items) {
try {
await cacheTrackForOffline({
id: track.id,
title: track.title,
artist: track.performer?.name || album.artist?.name || 'Unknown',
album: album.title,
albumId: album.id,
durationSecs: track.duration,
quality: track.hires_streamable ? 'Hi-Res' : '-',
bitDepth: track.maximum_bit_depth,
sampleRate: track.maximum_sampling_rate,
});
} catch (err) {
console.error(`Failed to refresh "${track.title}" for offline:`, err);
}
try {
await cacheTracksForOfflineBatch(album.tracks.items.map(track => ({
id: track.id,
title: track.title,
artist: track.performer?.name || album.artist?.name || 'Unknown',
album: album.title,
albumId: album.id,
durationSecs: track.duration,
quality: track.hires_streamable ? 'Hi-Res' : '-',
bitDepth: track.maximum_bit_depth,
sampleRate: track.maximum_sampling_rate,
})));
} catch (err) {
console.error('Failed to batch refresh for offline:', err);
}
} catch (err) {
console.error('Failed to load album:', err);