feat(playlist-import): concurrent matching with progress reporting

Replace sequential track matching with buffer_unordered(8) for 8
concurrent Qobuz API calls, reducing import time ~8x. Add real-time
progress events (import:progress, import:phase) emitted from Rust
backend and consumed by frontend via Tauri event listeners.

Frontend shows progress bar, matching status text, and current track
name during import. Individual search failures are now logged and
skipped instead of aborting the entire import.
This commit is contained in:
vicrodh committed 2026-02-09 17:53:04 -06:00
1 parent a46a422a04
commit 9fdd1dd0df
10 files changed
+264 -23

No files matched your search

@@ -20,6 +20,7 @@ pub async fn playlist_import_preview(
#[tauri::command]
pub async fn playlist_import_execute(
app: tauri::AppHandle,
url: String,
name_override: Option<String>,
is_public: Option<bool>,
@@ -33,6 +34,7 @@ pub async fn playlist_import_execute(
&client,
name_override.as_deref(),
is_public.unwrap_or(false),
&app,
)
.await
.map_err(|e| e.to_string())
+29 -3
View File
@@ -1,9 +1,11 @@
//! Orchestrates playlist import
use tauri::{AppHandle, Emitter};
use crate::api::QobuzClient;
use crate::playlist_import::errors::PlaylistImportError;
use crate::playlist_import::match_qobuz::match_tracks;
use crate::playlist_import::models::{ImportPlaylist, ImportSummary};
use crate::playlist_import::models::{ImportPlaylist, ImportProgress, ImportSummary};
use crate::playlist_import::providers::{detect_provider, fetch_playlist};
const ADD_CHUNK_SIZE: usize = 50;
@@ -20,9 +22,13 @@ pub async fn import_public_playlist(
client: &QobuzClient,
name_override: Option<&str>,
is_public: bool,
app: &AppHandle,
) -> Result<ImportSummary, PlaylistImportError> {
let playlist = preview_public_playlist(url).await?;
let matches = match_tracks(client, &playlist.tracks).await?;
// Phase: matching
let _ = app.emit("import:phase", serde_json::json!({ "phase": "matching" }));
let matches = match_tracks(client, &playlist.tracks, app).await?;
let mut matched_track_ids = Vec::new();
let mut seen = std::collections::HashSet::new();
@@ -41,6 +47,9 @@ pub async fn import_public_playlist(
let mut qobuz_playlist_id = None;
if !matched_track_ids.is_empty() {
// Phase: creating
let _ = app.emit("import:phase", serde_json::json!({ "phase": "creating" }));
let name = name_override.unwrap_or(&playlist.name);
let description = playlist
.description
@@ -54,11 +63,28 @@ pub async fn import_public_playlist(
qobuz_playlist_id = Some(created.id);
for chunk in matched_track_ids.chunks(ADD_CHUNK_SIZE) {
// Phase: adding
let _ = app.emit("import:phase", serde_json::json!({ "phase": "adding" }));
let chunks: Vec<&[u64]> = matched_track_ids.chunks(ADD_CHUNK_SIZE).collect();
let total_chunks = chunks.len() as u32;
for (i, chunk) in chunks.iter().enumerate() {
client
.add_tracks_to_playlist(created.id, chunk)
.await
.map_err(|e| PlaylistImportError::Qobuz(e.to_string()))?;
let _ = app.emit(
"import:progress",
ImportProgress {
phase: "adding".to_string(),
current: (i as u32) + 1,
total: total_chunks,
matched_so_far: matched_count,
current_track: None,
},
);
}
}
+92 -14
View File
@@ -1,39 +1,69 @@
//! Match imported tracks to Qobuz catalog
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use futures_util::stream::{self, StreamExt};
use tauri::{AppHandle, Emitter};
use crate::api::models::Track;
use crate::api::QobuzClient;
use crate::playlist_import::errors::PlaylistImportError;
use crate::playlist_import::models::{ImportTrack, TrackMatch};
use crate::playlist_import::models::{ImportProgress, ImportTrack, TrackMatch};
const SEARCH_LIMIT: u32 = 20;
const TITLE_WEIGHT: f32 = 0.6;
const ARTIST_WEIGHT: f32 = 0.3;
const ALBUM_WEIGHT: f32 = 0.1;
const MIN_SCORE: f32 = 0.65;
const CONCURRENCY: usize = 8;
pub async fn match_tracks(
client: &QobuzClient,
tracks: &[ImportTrack],
app: &AppHandle,
) -> Result<Vec<TrackMatch>, PlaylistImportError> {
let mut results = Vec::new();
let total = tracks.len() as u32;
let matched_counter = Arc::new(AtomicU32::new(0));
let completed_counter = Arc::new(AtomicU32::new(0));
for track in tracks {
// Pre-allocate results vector with None slots
let results: Arc<tokio::sync::Mutex<Vec<Option<TrackMatch>>>> =
Arc::new(tokio::sync::Mutex::new(vec![None; tracks.len()]));
let owned_tracks: Vec<(usize, ImportTrack)> = tracks.iter().enumerate().map(|(i, tr)| (i, tr.clone())).collect();
stream::iter(owned_tracks)
.map(|(idx, track)| {
let client = client.clone();
let app = app.clone();
let matched_counter = Arc::clone(&matched_counter);
let completed_counter = Arc::clone(&completed_counter);
let results = Arc::clone(&results);
async move {
let query = format!("{} {}", track.artist, track.title);
let search = client
let search_result = client
.search_tracks(&query, SEARCH_LIMIT, 0, None)
.await
.map_err(|e| PlaylistImportError::Qobuz(e.to_string()))?;
.await;
let (best, score) = select_best_match(track, &search.items);
let match_entry = match best {
Some(candidate) if score >= MIN_SCORE => TrackMatch {
let match_entry = match search_result {
Ok(search) => {
let (best, score) = select_best_match(&track, &search.items);
match best {
Some(candidate) if score >= MIN_SCORE => {
matched_counter.fetch_add(1, Ordering::Relaxed);
TrackMatch {
source: track.clone(),
qobuz_track_id: Some(candidate.id),
qobuz_title: Some(candidate.title.clone()),
qobuz_artist: candidate.performer.as_ref().map(|a| a.name.clone()),
qobuz_artist: candidate
.performer
.as_ref()
.map(|a| a.name.clone()),
score,
},
}
}
_ => TrackMatch {
source: track.clone(),
qobuz_track_id: None,
@@ -41,12 +71,60 @@ pub async fn match_tracks(
qobuz_artist: None,
score,
},
}
}
Err(e) => {
log::warn!(
"Search failed for '{}' - '{}': {}",
track.artist,
track.title,
e
);
TrackMatch {
source: track.clone(),
qobuz_track_id: None,
qobuz_title: None,
qobuz_artist: None,
score: 0.0,
}
}
};
results.push(match_entry);
// Store result at correct index
{
let mut res = results.lock().await;
res[idx] = Some(match_entry);
}
Ok(results)
let current = completed_counter.fetch_add(1, Ordering::Relaxed) + 1;
let matched = matched_counter.load(Ordering::Relaxed);
let current_track = Some(format!("{} - {}", track.artist, track.title));
let _ = app.emit(
"import:progress",
ImportProgress {
phase: "matching".to_string(),
current,
total,
matched_so_far: matched,
current_track,
},
);
}
})
.buffer_unordered(CONCURRENCY)
.collect::<Vec<()>>()
.await;
// Extract results in order
let locked = results.lock().await;
let ordered: Vec<TrackMatch> = locked
.iter()
.map(|slot| slot.clone().expect("All slots should be filled"))
.collect();
Ok(ordered)
}
fn select_best_match<'a>(track: &ImportTrack, candidates: &'a [Track]) -> (Option<&'a Track>, f32) {
+1 -1
View File
@@ -8,5 +8,5 @@ pub mod providers;
pub use errors::PlaylistImportError;
pub use importer::{import_public_playlist, preview_public_playlist};
pub use models::{ImportPlaylist, ImportProvider, ImportSummary, ImportTrack, TrackMatch};
pub use models::{ImportPlaylist, ImportProgress, ImportProvider, ImportSummary, ImportTrack, TrackMatch};
pub use providers::ProviderCredentials;
+9
View File
@@ -60,3 +60,12 @@ pub struct ImportSummary {
pub qobuz_playlist_id: Option<u64>,
pub matches: Vec<TrackMatch>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportProgress {
pub phase: String,
pub current: u32,
pub total: u32,
pub matched_so_far: u32,
pub current_track: Option<String>,
}
+107 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
import { X, CloudOff } from 'lucide-svelte';
import { showToast } from '$lib/stores/toastStore';
import { t } from '$lib/i18n';
@@ -57,6 +58,8 @@
let isOffline = $state(checkIsOffline());
let importCompleted = $state(false);
let lastImportedUrl = $state('');
let importProgress = $state<{ phase: string; current: number; total: number; matched_so_far: number; current_track: string | null } | null>(null);
let importPhase = $state<string | null>(null);
// Preview + customization state
let preview = $state<ImportPlaylist | null>(null);
@@ -106,6 +109,8 @@
logEntries = [];
importCompleted = false;
lastImportedUrl = '';
importProgress = null;
importPhase = null;
preview = null;
previewUrl = '';
customName = '';
@@ -187,9 +192,57 @@
loading = true;
error = null;
importProgress = null;
importPhase = null;
let unlistenProgress: UnlistenFn | null = null;
let unlistenPhase: UnlistenFn | null = null;
let lastLoggedPercent = -1;
try {
pushLog('Matching tracks in Qobuz\u2122...');
// Set up event listeners before invoking
unlistenProgress = await listen<{ phase: string; current: number; total: number; matched_so_far: number; current_track: string | null }>('import:progress', (event) => {
importProgress = event.payload;
if (event.payload.phase === 'matching' && event.payload.total > 0) {
const pct = Math.floor((event.payload.current / event.payload.total) * 100);
// Log at every 5% milestone
if (pct >= lastLoggedPercent + 5) {
lastLoggedPercent = pct;
pushLog(
$t('playlistImport.matchingTracks', {
values: {
current: event.payload.current.toLocaleString(),
total: event.payload.total.toLocaleString(),
matched: event.payload.matched_so_far.toLocaleString()
}
})
);
}
} else if (event.payload.phase === 'adding') {
pushLog(
$t('playlistImport.addingProgress', {
values: {
current: event.payload.current,
total: event.payload.total
}
})
);
}
});
unlistenPhase = await listen<{ phase: string }>('import:phase', (event) => {
importPhase = event.payload.phase;
if (event.payload.phase === 'matching') {
pushLog($t('playlistImport.matchingPhase'));
} else if (event.payload.phase === 'creating') {
pushLog($t('playlistImport.creatingPhase'), 'success');
} else if (event.payload.phase === 'adding') {
pushLog($t('playlistImport.addingPhase'));
}
});
const nameOverride = customName.trim() !== preview.name ? customName.trim() || null : null;
const result = await invoke<ImportSummary>('playlist_import_execute', {
url: previewUrl,
@@ -223,6 +276,8 @@
showToast($t('toast.playlistImportFailed'), 'error');
} finally {
loading = false;
unlistenProgress?.();
unlistenPhase?.();
}
}
@@ -352,6 +407,26 @@
<span class="spinner" aria-hidden="true"></span>
{/if}
</div>
{#if importProgress && importProgress.total > 0 && loading}
<div class="progress-bar-container">
<div
class="progress-bar-fill"
style="width: {Math.min(100, (importProgress.current / importProgress.total) * 100)}%"
></div>
</div>
<div class="progress-status">
{$t('playlistImport.matchingTracks', {
values: {
current: importProgress.current.toLocaleString(),
total: importProgress.total.toLocaleString(),
matched: importProgress.matched_so_far.toLocaleString()
}
})}
</div>
{#if importProgress.current_track}
<div class="progress-current-track">{importProgress.current_track}</div>
{/if}
{/if}
<ul class="progress-log">
{#each logEntries as entry}
<li class={`log-item ${entry.status}`}>{entry.message}</li>
@@ -605,6 +680,37 @@
margin-bottom: 10px;
}
.progress-bar-container {
width: 100%;
height: 6px;
background: var(--alpha-8);
border-radius: 3px;
overflow: hidden;
margin-bottom: 8px;
}
.progress-bar-fill {
height: 100%;
background: var(--accent-primary);
border-radius: 3px;
transition: width 200ms ease;
}
.progress-status {
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 4px;
}
.progress-current-track {
font-size: 11px;
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 10px;
}
.progress-log {
list-style: none;
padding: 0;
+6 -1
View File
@@ -1318,6 +1318,11 @@
"summary": "Zusammenfassung",
"playlistLabel": "Playlist: {name}",
"tracksMatched": "Titel zugeordnet: {matched} / {total}",
"skipped": "Übersprungen: {count}"
"skipped": "Übersprungen: {count}",
"matchingTracks": "Titel abgleichen: {current} / {total} ({matched} gefunden)",
"matchingPhase": "Qobuz-Katalog durchsuchen...",
"creatingPhase": "Playlist erstellen...",
"addingPhase": "Titel zur Playlist hinzufugen...",
"addingProgress": "Titel hinzufugen: {current} / {total}"
}
}
+6 -1
View File
@@ -1520,6 +1520,11 @@
"summary": "Summary",
"playlistLabel": "Playlist: {name}",
"tracksMatched": "Tracks matched: {matched} / {total}",
"skipped": "Skipped: {count}"
"skipped": "Skipped: {count}",
"matchingTracks": "Matching tracks: {current} / {total} ({matched} found)",
"matchingPhase": "Searching Qobuz catalog...",
"creatingPhase": "Creating playlist...",
"addingPhase": "Adding tracks to playlist...",
"addingProgress": "Adding tracks: {current} / {total}"
}
}
+6 -1
View File
@@ -1520,6 +1520,11 @@
"summary": "Resumen",
"playlistLabel": "Playlist: {name}",
"tracksMatched": "Tracks encontrados: {matched} / {total}",
"skipped": "Omitidos: {count}"
"skipped": "Omitidos: {count}",
"matchingTracks": "Buscando tracks: {current} / {total} ({matched} encontrados)",
"matchingPhase": "Buscando en el catalogo de Qobuz...",
"creatingPhase": "Creando playlist...",
"addingPhase": "Agregando tracks a la playlist...",
"addingProgress": "Agregando tracks: {current} / {total}"
}
}
+6 -1
View File
@@ -1318,6 +1318,11 @@
"summary": "Resume",
"playlistLabel": "Playlist : {name}",
"tracksMatched": "Titres trouves : {matched} / {total}",
"skipped": "Ignores : {count}"
"skipped": "Ignores : {count}",
"matchingTracks": "Recherche des titres : {current} / {total} ({matched} trouves)",
"matchingPhase": "Recherche dans le catalogue Qobuz...",
"creatingPhase": "Creation de la playlist...",
"addingPhase": "Ajout des titres a la playlist...",
"addingProgress": "Ajout des titres : {current} / {total}"
}
}