diff --git a/docs/administration.md b/docs/administration.md index 7f74742..5490bd4 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -134,6 +134,22 @@ federation content id even when federation is disabled, which requires **Settings → Agent → Storage directory** (`FURU_AGENT_STORAGE_DIR`); without it they wait as "no content id" and later passes try again. +When the user allows federated search and federation is enabled, entries still +without a match are looked up in the artist catalogues of peers. Only artist +names are sent: the server searches the network for each artist once, asks at +most 16 peers that offer it for their catalogues, four at a time, and spends at +most a minute per artist. Imports of the whole server search two artists at a +time, and one pass searches at most 500 artists for at most 30 minutes; the rest +stays unmatched until **Retry unmatched**. A failed search is repeated after 2, 4 +and 8 seconds before the artist is skipped. Catalogues that a peer refuses, that +exceed 4 MiB or that do not arrive in 8 seconds are counted as lost in the import +statistics. Cancelling an import stops its running searches. Without consent, or +with federation disabled, the import makes no network requests. + +Doubtful entries keep up to five candidates. The import page lets the owner pick +one; the choice is checked against the stored candidates and published like an +automatic match. + ## Federation Federation is optional. Independent Furumusic and Furumi players that use the diff --git a/docs/development.md b/docs/development.md index ddda461..4dfcd9b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -162,8 +162,17 @@ without a server restart once its lease expires, continuing the same Spotify API import after the user signs in again, and resolving a small library with federation disabled: local matches get content ids from `agent_storage_dir`, known federated tracks match without the network, and a federation stub that -panics proves no network access without consent. The database needs the -`pg_trgm` extension; the tests install it into `public`. +panics proves no network access without consent. Peer catalogues come from a +fake catalogue source: the tests cover matches through the original, folded and +split artist names, repeated failed searches, lost catalogues, the budget of a +pass, a stopped node, manual choices with tampered candidates, and cancellation +that leaves no catalogue request running. The database needs the `pg_trgm` +extension; the tests install it into `public`. + +`cargo test federation::client` checks bounded artist catalogue lookups without a +database: at most 16 owners and the given number of parallel requests, timeouts, +errors, oversized catalogues, and that dropping a lookup stops its search and +requests. The matcher's reference table (`src/library_import/matcher/tests.rs`) runs without a database and documents the matching rules case by case. diff --git a/src/federation/client.rs b/src/federation/client.rs index b4627f4..a8b9b5c 100644 --- a/src/federation/client.rs +++ b/src/federation/client.rs @@ -13,12 +13,18 @@ use sqlx::Row as _; use tokio::io::AsyncReadExt; use super::{Federation, now_iso}; +#[cfg(test)] +mod catalog_tests; mod local_catalog; #[cfg(test)] mod search_tests; use local_catalog::LocalCatalog; const MAX_CATALOG_BYTES: u64 = 4 * 1024 * 1024; +/// Time allowed for one peer's catalogue. +const CATALOG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8); +/// Peers asked for one artist's catalogue by a bounded lookup. +pub const MAX_CATALOG_OWNERS: usize = 16; #[derive(Debug, Clone, Serialize)] pub struct TrackKeyDto { @@ -176,32 +182,16 @@ impl Federation { tokio::spawn(async move { let result = async { let service = federation.service().await?; - let normalized = music_dht::normalize_name(&name); let outcome = service .search_network(&name) .await .map_err(|err| anyhow::anyhow!("federated artist search failed: {err}"))?; - // Deep links carry normalized names. Peers may require their - // original spelling (for example "AC/DC") in catalog requests. - let mut owners = HashMap::new(); - for item in &outcome.network_results { - if item.kind == ItemKind::Artist && item.normalized_name == normalized { - owners.insert(item.owner, item.name.clone()); - } else if let Some(display) = item - .artist_names - .iter() - .chain(&item.featured_artist_names) - .find(|artist| music_dht::normalize_name(artist) == normalized) - { - owners.entry(item.owner).or_insert_with(|| display.clone()); - } - } - for (owner, name) in owners { + for (owner, name) in catalog_owners(&outcome.network_results, &name) { let service = std::sync::Arc::clone(&service); let sender = sender.clone(); tokio::spawn(async move { let result = tokio::time::timeout( - std::time::Duration::from_secs(8), + CATALOG_TIMEOUT, fetch_artist_catalog(&service, owner, &name), ) .await @@ -221,6 +211,25 @@ impl Federation { receiver } + /// Catalogues of the peers offering `name`, with real limits: one task + /// searches the network, then asks at most [`MAX_CATALOG_OWNERS`] owners, + /// `max_parallel` at a time. Dropping the stream cancels the search and + /// every catalogue request. Fails at once when the node is not running. + /// [`Self::stream_artist_catalogs`] of the player is not limited this way. + pub async fn artist_catalogs_bounded( + &self, + name: &str, + max_parallel: usize, + ) -> Result { + let service = self.service().await?; + Ok(CatalogStream::spawn( + std::sync::Arc::new(DhtCatalogPeers(service)), + name.to_owned(), + max_parallel, + CATALOG_TIMEOUT, + )) + } + /// Performs one bounded DHT search and returns entity upserts. The HTTP /// layer streams each upsert independently; catalog fan-out can append /// events to the same contract without changing the browser model. @@ -478,6 +487,159 @@ async fn build_search_events( Ok(events) } +/// Owners whose search results credit `name`, with the spelling they use. +/// Deep links carry normalized names. Peers may require their original +/// spelling (for example "AC/DC") in catalog requests. +fn catalog_owners(items: &[LibraryItem], name: &str) -> HashMap { + let normalized = music_dht::normalize_name(name); + let mut owners = HashMap::new(); + for item in items { + if item.kind == ItemKind::Artist && item.normalized_name == normalized { + owners.insert(item.owner, item.name.clone()); + } else if let Some(display) = item + .artist_names + .iter() + .chain(&item.featured_artist_names) + .find(|artist| music_dht::normalize_name(artist) == normalized) + { + owners.entry(item.owner).or_insert_with(|| display.clone()); + } + } + owners +} + +/// Why a bounded catalogue lookup yielded no catalogue. +#[derive(Debug)] +pub enum CatalogError { + /// The network search for owners failed; no peer was asked. + Search(anyhow::Error), + /// One owner's catalogue was lost: unreachable, refused, too large or late. + Catalog(anyhow::Error), +} + +pub type CatalogResult = + std::result::Result<(String, music_dht::catalog::CatalogArtist), CatalogError>; + +/// Where catalogues come from: the DHT node, or a fake in tests. +#[async_trait::async_trait] +pub trait CatalogPeers: Send + Sync + 'static { + type Owner: std::fmt::Display + Send + 'static; + + /// Owners offering `name`, each with the spelling to ask for. + async fn owners(&self, name: &str) -> Result>; + + async fn catalog( + &self, + owner: Self::Owner, + name: String, + ) -> Result; +} + +/// Catalogues of one bounded lookup as they arrive. Dropping the stream +/// aborts its task; the task owns the request [`tokio::task::JoinSet`], so +/// the search and all catalogue requests stop with it. +pub struct CatalogStream { + receiver: tokio::sync::mpsc::UnboundedReceiver, + task: tokio::task::AbortHandle, +} + +impl CatalogStream { + /// Starts a lookup: at most [`MAX_CATALOG_OWNERS`] owners, `max_parallel` + /// requests at a time, each limited to `timeout`. + pub fn spawn( + peers: std::sync::Arc

, + name: String, + max_parallel: usize, + timeout: std::time::Duration, + ) -> Self { + let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + let owners = match peers.owners(&name).await { + Ok(owners) => owners, + Err(err) => { + let _ = sender.send(Err(CatalogError::Search(err))); + return; + } + }; + let mut owners = owners.into_iter().take(MAX_CATALOG_OWNERS); + let mut requests = tokio::task::JoinSet::new(); + loop { + while requests.len() < max_parallel.max(1) { + let Some((owner, spelling)) = owners.next() else { + break; + }; + let peers = std::sync::Arc::clone(&peers); + requests.spawn(async move { + let label = owner.to_string(); + tokio::time::timeout(timeout, peers.catalog(owner, spelling)) + .await + .map_err(|_| anyhow::anyhow!("catalog request timed out")) + .and_then(|result| result) + .map(|artist| (label, artist)) + .map_err(CatalogError::Catalog) + }); + } + let Some(joined) = requests.join_next().await else { + return; + }; + let result = joined.unwrap_or_else(|err| { + Err(CatalogError::Catalog(anyhow::anyhow!( + "catalog request failed: {err}" + ))) + }); + if sender.send(result).is_err() { + return; + } + } + }); + Self { + receiver, + task: task.abort_handle(), + } + } + + /// The next catalogue or loss; `None` once every owner answered. + pub async fn next(&mut self) -> Option { + self.receiver.recv().await + } +} + +impl Drop for CatalogStream { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// The running DHT node as a catalogue source. +struct DhtCatalogPeers(std::sync::Arc); + +#[async_trait::async_trait] +impl CatalogPeers for DhtCatalogPeers { + type Owner = music_dht::EndpointId; + + async fn owners(&self, name: &str) -> Result> { + let outcome = self + .0 + .search_network(name) + .await + .map_err(|err| anyhow::anyhow!("federated artist search failed: {err}"))?; + let mut owners: Vec<_> = catalog_owners(&outcome.network_results, name) + .into_iter() + .collect(); + owners.sort_by_cached_key(|(owner, _)| owner.to_string()); + owners.truncate(MAX_CATALOG_OWNERS); + Ok(owners) + } + + async fn catalog( + &self, + owner: Self::Owner, + name: String, + ) -> Result { + fetch_artist_catalog(&self.0, owner, &name).await + } +} + async fn fetch_artist_catalog( service: &music_dht::MusicDhtService, owner: music_dht::EndpointId, @@ -495,10 +657,15 @@ async fn fetch_artist_catalog( request.push(b'\n'); stream.send.write_all(&request).await?; stream.send.finish()?; + read_catalog_response(stream.recv).await +} + +/// Reads a catalogue response of at most [`MAX_CATALOG_BYTES`]. +async fn read_catalog_response( + recv: impl tokio::io::AsyncRead + Unpin, +) -> Result { let mut payload = Vec::new(); - stream - .recv - .take(MAX_CATALOG_BYTES + 1) + recv.take(MAX_CATALOG_BYTES + 1) .read_to_end(&mut payload) .await?; anyhow::ensure!( diff --git a/src/federation/client/catalog_tests.rs b/src/federation/client/catalog_tests.rs new file mode 100644 index 0000000..2a86f67 --- /dev/null +++ b/src/federation/client/catalog_tests.rs @@ -0,0 +1,257 @@ +//! Limits and cancellation of bounded artist catalogue lookups, on a fake +//! catalogue source. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use music_dht::catalog::{CatalogArtist, CatalogResponse}; +use music_dht::{ItemId, SecretKey}; + +use super::*; + +/// Counts a running request until it is dropped, finished or aborted. +struct Live(Arc); + +impl Live { + fn start(counters: &Arc) -> Self { + let now = counters.live.fetch_add(1, Ordering::SeqCst) + 1; + counters.peak.fetch_max(now, Ordering::SeqCst); + counters.started.fetch_add(1, Ordering::SeqCst); + Self(Arc::clone(counters)) + } +} + +impl Drop for Live { + fn drop(&mut self) { + self.0.live.fetch_sub(1, Ordering::SeqCst); + } +} + +#[derive(Default)] +struct Counters { + live: AtomicUsize, + peak: AtomicUsize, + started: AtomicUsize, +} + +#[derive(Clone, Copy)] +enum Answer { + Catalog, + Fail, + Hang, + TooLarge, +} + +struct FakePeers { + owners: usize, + search_hangs: bool, + answer: fn(usize) -> Answer, + delay: Duration, + counters: Arc, +} + +impl FakePeers { + fn new(owners: usize, answer: fn(usize) -> Answer) -> Self { + Self { + owners, + search_hangs: false, + answer, + delay: Duration::from_millis(20), + counters: Arc::default(), + } + } +} + +#[async_trait::async_trait] +impl CatalogPeers for FakePeers { + type Owner = usize; + + async fn owners(&self, name: &str) -> Result> { + let _live = Live::start(&self.counters); + if self.search_hangs { + std::future::pending::<()>().await; + } + Ok((0..self.owners) + .map(|owner| (owner, name.to_owned())) + .collect()) + } + + async fn catalog(&self, owner: usize, name: String) -> Result { + let _live = Live::start(&self.counters); + tokio::time::sleep(self.delay).await; + match (self.answer)(owner) { + Answer::Catalog => Ok(CatalogArtist { + name, + ..Default::default() + }), + Answer::Fail => anyhow::bail!("peer refused catalog"), + Answer::Hang => std::future::pending().await, + Answer::TooLarge => { + let response = serde_json::to_vec(&CatalogResponse { + ok: true, + artist: Some(CatalogArtist { + name: "x".repeat(MAX_CATALOG_BYTES as usize), + ..Default::default() + }), + ..Default::default() + })?; + read_catalog_response(response.as_slice()).await + } + } + } +} + +async fn collect(mut stream: CatalogStream) -> (Vec, Vec) { + let (mut found, mut lost) = (Vec::new(), Vec::new()); + while let Some(result) = stream.next().await { + match result { + Ok((owner, _)) => found.push(owner), + Err(CatalogError::Catalog(err)) => lost.push(err.to_string()), + Err(CatalogError::Search(err)) => lost.push(format!("search: {err}")), + } + } + found.sort(); + (found, lost) +} + +async fn settle(counters: &Counters) { + for _ in 0..50 { + if counters.live.load(Ordering::SeqCst) == 0 { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +#[tokio::test] +async fn bounded_lookup_limits_owners_and_parallel_requests() { + let peers = Arc::new(FakePeers::new(20, |_| Answer::Catalog)); + let counters = Arc::clone(&peers.counters); + let stream = CatalogStream::spawn(peers, "Artist".into(), 4, Duration::from_secs(5)); + let (found, lost) = collect(stream).await; + assert_eq!(found.len(), MAX_CATALOG_OWNERS); + assert!(lost.is_empty()); + // The search plus at most four catalogue requests run at once. + assert!(counters.peak.load(Ordering::SeqCst) <= 4); + assert_eq!( + counters.started.load(Ordering::SeqCst), + 1 + MAX_CATALOG_OWNERS + ); +} + +#[tokio::test] +async fn bounded_lookup_reports_timeouts_errors_and_oversized_catalogues() { + let peers = Arc::new(FakePeers::new(4, |owner| match owner { + 0 => Answer::Catalog, + 1 => Answer::Fail, + 2 => Answer::Hang, + _ => Answer::TooLarge, + })); + let counters = Arc::clone(&peers.counters); + let stream = CatalogStream::spawn(peers, "Artist".into(), 4, Duration::from_millis(200)); + let (found, mut lost) = collect(stream).await; + lost.sort(); + assert_eq!(found, ["0"]); + assert_eq!( + lost, + [ + "catalog request timed out", + "catalog response is too large", + "peer refused catalog", + ] + ); + settle(&counters).await; + assert_eq!(counters.live.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn bounded_lookup_reports_a_failed_search() { + struct Offline; + + #[async_trait::async_trait] + impl CatalogPeers for Offline { + type Owner = usize; + + async fn owners(&self, _name: &str) -> Result> { + anyhow::bail!("no peers") + } + + async fn catalog(&self, _owner: usize, _name: String) -> Result { + unreachable!("no owners were found") + } + } + + let stream = CatalogStream::spawn( + Arc::new(Offline), + "Artist".into(), + 4, + Duration::from_secs(1), + ); + let (found, lost) = collect(stream).await; + assert!(found.is_empty()); + assert_eq!(lost, ["search: no peers"]); +} + +#[tokio::test] +async fn dropping_the_stream_stops_the_search_and_every_request() { + let mut searching = FakePeers::new(1, |_| Answer::Catalog); + searching.search_hangs = true; + let searching = Arc::new(searching); + let counters = Arc::clone(&searching.counters); + let stream = CatalogStream::spawn(searching, "Artist".into(), 4, Duration::from_secs(60)); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(counters.live.load(Ordering::SeqCst), 1); + drop(stream); + settle(&counters).await; + assert_eq!(counters.live.load(Ordering::SeqCst), 0); + + let fetching = Arc::new(FakePeers::new(10, |_| Answer::Hang)); + let counters = Arc::clone(&fetching.counters); + let mut stream = CatalogStream::spawn(fetching, "Artist".into(), 4, Duration::from_secs(60)); + let pending = tokio::time::timeout(Duration::from_millis(100), stream.next()).await; + assert!(pending.is_err(), "hanging peers answer nothing"); + assert_eq!(counters.live.load(Ordering::SeqCst), 4); + drop(stream); + settle(&counters).await; + assert_eq!(counters.live.load(Ordering::SeqCst), 0); + // No request was started after the drop. + assert_eq!(counters.started.load(Ordering::SeqCst), 1 + 4); +} + +fn item(kind: ItemKind, name: &str, artists: &[&str], owner_seed: u8) -> LibraryItem { + let owner = SecretKey::from_bytes(&[owner_seed; 32]).public(); + LibraryItem { + id: ItemId::derive(&owner, kind, name), + owner, + kind, + name: name.into(), + normalized_name: music_dht::normalize_name(name), + artist_names: artists.iter().map(|artist| (*artist).to_owned()).collect(), + featured_artist_names: Vec::new(), + release_title: None, + release_type: None, + year: None, + content_id: None, + track_number: None, + disc_number: None, + duration_seconds: None, + revision: 1, + deleted: false, + updated_at_ms: 1, + } +} + +#[test] +fn catalog_owners_keep_the_spelling_each_peer_uses() { + let items = [ + item(ItemKind::Artist, "AC/DC", &[], 1), + item(ItemKind::Track, "Thunderstruck", &["AC/DC"], 2), + item(ItemKind::Track, "Thunderstruck", &["AC-DC"], 3), + item(ItemKind::Track, "Other", &["Somebody"], 4), + ]; + let owners = catalog_owners(&items, "ac dc"); + let mut spellings: Vec<&str> = owners.values().map(String::as_str).collect(); + spellings.sort(); + assert_eq!(spellings, ["AC-DC", "AC/DC", "AC/DC"]); +} diff --git a/src/library_import/handlers.rs b/src/library_import/handlers.rs index 3066d7c..8a9e931 100644 --- a/src/library_import/handlers.rs +++ b/src/library_import/handlers.rs @@ -28,8 +28,8 @@ use super::model::{ use super::providers::spotify_api::{self, AuthState, AuthStateError, SpotifyClient}; use super::providers::{Connection, FetchError, TokenVault}; use super::store::{ - self, CancelOutcome, CreateImportError, DeleteOutcome, ItemFilter, NewImport, NewPlaylist, - ReauthOutcome, ReauthTarget, + self, CancelOutcome, ChooseOutcome, CreateImportError, DeleteOutcome, ItemFilter, NewImport, + NewPlaylist, ReauthOutcome, ReauthTarget, }; use crate::auth; use crate::config::AppConfig; @@ -93,7 +93,61 @@ struct ImportPath { } fn import_id(path: &ImportPath) -> Option { - path.id.parse::().ok().filter(|id| *id > 0) + positive_id(&path.id) +} + +fn positive_id(value: &str) -> Option { + value.parse::().ok().filter(|id| *id > 0) +} + +#[derive(Deserialize)] +struct ItemPath { + id: String, + item_id: String, +} + +/// `POST /api/imports/{id}/items/{item_id}/match`. +#[derive(Debug, Deserialize)] +struct MatchRequest { + /// Index into the entry's stored candidates. + candidate: usize, +} + +async fn choose(services: &Services, user_id: i64, path: &ItemPath, request: Request) -> Response { + let (Some(import_id), Some(item_id)) = (positive_id(&path.id), positive_id(&path.item_id)) + else { + return not_found(); + }; + let body: MatchRequest = match read_json(request).await { + Ok(body) => body, + Err(rejection) => return rejection.respond(), + }; + let pool = services.pool().await?; + match store::choose_candidate(&pool, user_id, import_id, item_id, body.candidate).await { + Ok(ChooseOutcome::Chosen { + queued, + publication, + }) => { + if queued { + services.start_worker().await; + } + ok(json!({ + "resolution_status": "matched", + "publication_status": publication, + })) + } + Ok(ChooseOutcome::NotFound) => error(StatusCode::NOT_FOUND, "entry not found"), + Ok(ChooseOutcome::NotAmbiguous) => error( + StatusCode::CONFLICT, + "the entry has no candidates to choose from", + ), + Ok(ChooseOutcome::InvalidCandidate) => error(StatusCode::BAD_REQUEST, "unknown candidate"), + Ok(ChooseOutcome::TrackGone) => error( + StatusCode::CONFLICT, + "the chosen track is no longer in the library", + ), + Err(error) => storage_error(&error), + } } #[derive(Default, Deserialize)] @@ -1109,6 +1163,22 @@ impl App for ImportApp { }, ) }; + let choose_route = { + let services = services.clone(); + post( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path, + request: Request| { + let services = services.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + choose(&services, user.id, &path, request).await + } + }, + ) + }; let cancel = post( move |auth_ctx: auth::AuthContext, session: Session, @@ -1158,6 +1228,11 @@ impl App for ImportApp { Route::with_handler_and_name("/{id}", detail, "library_import"), Route::with_handler_and_name("/{id}/items", items, "library_import_items"), Route::with_handler_and_name("/{id}/cancel", cancel, "library_import_cancel"), + Route::with_handler_and_name( + "/{id}/items/{item_id}/match", + choose_route, + "library_import_item_match", + ), ]) } } diff --git a/src/library_import/job.rs b/src/library_import/job.rs index 929ff7b..2c91c59 100644 --- a/src/library_import/job.rs +++ b/src/library_import/job.rs @@ -16,7 +16,10 @@ use sqlx::PgPool; use super::model::Phase; use super::model::ResolutionStatus; use super::providers::{FetchError, LibraryFetcher, ProviderFetchers, TokenVault}; -use super::resolver::{FederationAccess, NodeFederation, Resolver}; +use super::resolver::{ + FEDERATION_BUDGET, FEDERATION_UNAVAILABLE, FederationAccess, GroupOutcome, NetworkSearch, + NodeFederation, Resolver, +}; use super::store::{self, ClaimedImport, Control, FinishOutcome, NewItem, Resolution}; use crate::config::AppConfig; use crate::scheduler::{Job, JobContext, JobLog, SchedulerHandle}; @@ -292,7 +295,11 @@ impl Worker { return Ok(Some(stop)); } } - Phase::ResolveFederation => self.resolve_federation(import, log).await?, + Phase::ResolveFederation => { + if let Some(stop) = self.resolve_federation(import, heartbeat, log).await? { + return Ok(Some(stop)); + } + } Phase::Publish => self.publish(import, log).await?, } store::refresh_statistics(&mut *self.pool.acquire().await?, import.id).await?; @@ -373,10 +380,16 @@ impl Worker { Ok(None) } + /// Whether entries without a local match wait for the network stage. + fn searches_network(&self, import: &ClaimedImport) -> bool { + import.federated_search && self.config.federation_enabled + } + /// Matches pending entries against the local library and the federated /// tracks this server already knows (resolver stages 1–2), without the /// network. Decisions are written after each artist group; a group that - /// fails is marked failed and the import continues. + /// fails is marked failed and the import continues. When the network + /// stage follows, entries without a match stay pending with their reason. async fn resolve_local( &self, import: &ClaimedImport, @@ -394,6 +407,7 @@ impl Worker { self.config.agent_storage_dir.clone(), ) .await?; + let defer = self.searches_network(import); let mut counts = ResolveCounts::default(); if !prepared.invalid.is_empty() { if !self.store_resolutions(import, &prepared.invalid).await? { @@ -410,7 +424,11 @@ impl Worker { Control::Cancel => return Ok(Some(Stop::Cancelled)), Control::LeaseLost => return Ok(Some(Stop::LeaseLost)), } - let resolutions = match prepared.resolver.resolve_group(&self.pool, group).await { + let resolutions = match prepared + .resolver + .resolve_group(&self.pool, group, defer) + .await + { Ok(resolutions) => resolutions, Err(error) => { tracing::warn!( @@ -431,8 +449,14 @@ impl Worker { counts.add(&resolutions); } log.info(&format!( - "Library import {}: resolved {} entries locally ({} matched, {} ambiguous, {} unmatched, {} failed)", - import.id, counts.total, counts.matched, counts.ambiguous, counts.unmatched, counts.failed + "Library import {}: resolved {} entries locally ({} matched, {} ambiguous, {} unmatched, {} failed, {} left for the network)", + import.id, + counts.total, + counts.matched, + counts.ambiguous, + counts.unmatched, + counts.failed, + counts.deferred )); Ok(None) } @@ -462,26 +486,141 @@ impl Worker { } /// Searches artist catalogues on the network (resolver stage 3), only - /// with the user's consent and a running federation. Without consent the - /// federation is not even asked whether it runs. - async fn resolve_federation(&self, import: &ClaimedImport, log: &mut JobLog) -> Result<()> { + /// with the user's consent and enabled federation. Without consent the + /// federation is not even asked whether it runs. Entries that stages 1–2 + /// left pending are decided per artist group; cancellation and lease loss + /// stop a running group, which cancels its search and catalogue requests. + async fn resolve_federation( + &self, + import: &ClaimedImport, + heartbeat: &Heartbeat, + log: &mut JobLog, + ) -> Result> { if !import.federated_search { - return Ok(()); + // Entries wait for the network only with consent; after a change + // they keep their local reason. + return self.finish_deferred(import, None).await; } if !self.config.federation_enabled { log.info(&format!( "Library import {}: federation is disabled; network search skipped", import.id )); - return Ok(()); + return self.finish_deferred(import, None).await; } if !self.federation.is_running().await { log.info(&format!( "Library import {}: federation is not running; network search skipped", import.id )); + return self + .finish_deferred(import, Some(FEDERATION_UNAVAILABLE)) + .await; + } + let entries: Vec<_> = store::pending_entries(&self.pool, import.id) + .await? + .into_iter() + .filter(|entry| entry.note.is_some()) + .collect(); + if entries.is_empty() { + return Ok(None); + } + let mut prepared = Resolver::prepare( + &self.pool, + import.user_id, + entries, + self.config.agent_storage_dir.clone(), + ) + .await?; + if !prepared.invalid.is_empty() + && !self.store_resolutions(import, &prepared.invalid).await? + { + return Ok(Some(Stop::LeaseLost)); + } + let mut search = NetworkSearch::new(&mut prepared.resolver, &*self.federation); + let poll = search.limits().poll; + let (mut counts, mut catalogs, mut catalog_errors) = (ResolveCounts::default(), 0, 0); + let mut ending = None; + for group in &prepared.groups { + if heartbeat.lost() { + return Ok(Some(Stop::LeaseLost)); + } + match store::control(&self.pool, import.id, self.run_id).await? { + Control::Continue => {} + Control::Cancel => return Ok(Some(Stop::Cancelled)), + Control::LeaseLost => return Ok(Some(Stop::LeaseLost)), + } + if search.exhausted() { + ending = Some(FEDERATION_BUDGET); + break; + } + // Dropping the group future cancels its lookups. + let outcome = tokio::select! { + outcome = search.resolve_group(group) => outcome, + stop = self.watch(import, heartbeat, poll) => return Ok(Some(stop)), + }; + match outcome { + GroupOutcome::Resolved { + resolutions, + catalogs: received, + catalog_errors: lost, + } => { + if !store::add_catalog_errors(&self.pool, import.id, self.run_id, lost).await? + || !self.store_resolutions(import, &resolutions).await? + { + return Ok(Some(Stop::LeaseLost)); + } + counts.add(&resolutions); + catalogs += received; + catalog_errors += lost; + } + GroupOutcome::Unavailable => { + ending = Some(FEDERATION_UNAVAILABLE); + break; + } + } + } + let groups = search.groups(); + log.info(&format!( + "Library import {}: searched the network for {groups} artists ({catalogs} catalogues, {catalog_errors} lost); {} entries: {} matched, {} ambiguous, {} unmatched, {} failed", + import.id, counts.total, counts.matched, counts.ambiguous, counts.unmatched, counts.failed + )); + if let Some(note) = ending { + log.info(&format!( + "Library import {}: network search stopped ({note}); the remaining entries stay unmatched", + import.id + )); + return self.finish_deferred(import, Some(note)).await; + } + Ok(None) + } + + /// Entries still waiting for the network become unmatched. + async fn finish_deferred( + &self, + import: &ClaimedImport, + note: Option<&str>, + ) -> Result> { + Ok( + (!store::finish_deferred(&self.pool, import.id, self.run_id, note).await?) + .then_some(Stop::LeaseLost), + ) + } + + /// Resolves once the running group must stop: the lease is lost or the + /// user cancelled. A failed check is repeated at the next poll. + async fn watch(&self, import: &ClaimedImport, heartbeat: &Heartbeat, poll: Duration) -> Stop { + loop { + tokio::time::sleep(poll).await; + if heartbeat.lost() { + return Stop::LeaseLost; + } + match store::control(&self.pool, import.id, self.run_id).await { + Ok(Control::Continue) | Err(_) => {} + Ok(Control::Cancel) => return Stop::Cancelled, + Ok(Control::LeaseLost) => return Stop::LeaseLost, + } } - Ok(()) } /// Adds matched entries to the target playlists. @@ -498,6 +637,8 @@ struct ResolveCounts { ambiguous: usize, unmatched: usize, failed: usize, + /// Left pending for the network stage. + deferred: usize, } impl ResolveCounts { @@ -508,6 +649,7 @@ impl ResolveCounts { ResolutionStatus::Matched => self.matched += 1, ResolutionStatus::Ambiguous => self.ambiguous += 1, ResolutionStatus::Failed => self.failed += 1, + ResolutionStatus::Pending => self.deferred += 1, _ => self.unmatched += 1, } } diff --git a/src/library_import/model.rs b/src/library_import/model.rs index 030cca1..265dcc2 100644 --- a/src/library_import/model.rs +++ b/src/library_import/model.rs @@ -384,6 +384,8 @@ pub struct ImportStatistics { pub deferred_sync_limit: i64, pub paused: i64, pub publication_failed: i64, + /// Peer catalogues lost by the network search of the current or last attempt. + pub catalog_errors: i64, } impl ImportStatistics { diff --git a/src/library_import/resolver.rs b/src/library_import/resolver.rs index 420e45f..c41804d 100644 --- a/src/library_import/resolver.rs +++ b/src/library_import/resolver.rs @@ -1,12 +1,13 @@ -//! Resolver stages 1–2 (plan §6): the local library and the federated tracks -//! this server already knows. Neither stage touches the network. The network -//! (stage 3, artist catalogues of peers) is reached only through -//! [`FederationAccess`], so an import without consent provably makes no -//! network calls. +//! Resolver (plan §6). Stages 1–2 match against the local library and the +//! federated tracks this server already knows; neither touches the network. +//! Stage 3 ([`federated`]) searches artist catalogues of peers and reaches the +//! network only through [`FederationAccess`], so an import without consent +//! provably makes no network calls. //! //! Library SQL lives here; the import tables are written by `store.rs`. use std::collections::{BTreeSet, HashMap, HashSet}; +use std::time::Duration; use anyhow::Result; use music_dht::device_sync::SyncedFedTrack; @@ -20,12 +21,25 @@ use super::matcher::{ }; use super::model::{ItemMetadata, PublicationStatus, ResolutionStatus}; use super::store::{PendingEntry, Resolution}; +use crate::federation::client::CatalogStream; + +mod federated; +pub use federated::{FEDERATION_BUDGET, FEDERATION_UNAVAILABLE, GroupOutcome, NetworkSearch}; /// The network side of the resolver. #[async_trait::async_trait] pub trait FederationAccess: Send + Sync { /// Whether the federation node runs and can search the network. async fn is_running(&self) -> bool; + + /// Catalogues of the peers offering `name`, at most `max_parallel` + /// requests at a time. `None` when the node is not running. + async fn artist_catalogs(&self, name: &str, max_parallel: usize) -> Option; + + /// Limits of the network stage. + fn limits(&self) -> NetworkLimits { + NetworkLimits::default() + } } /// The process-wide federation node. @@ -36,6 +50,49 @@ impl FederationAccess for NodeFederation { async fn is_running(&self) -> bool { crate::federation::handle().is_running().await } + + async fn artist_catalogs(&self, name: &str, max_parallel: usize) -> Option { + crate::federation::handle() + .artist_catalogs_bounded(name, max_parallel) + .await + .ok() + } +} + +/// Limits of resolver stage 3 (plan §6). Together with the process-wide +/// limit of two artist groups, imports run at most two searches and eight +/// catalogue requests at a time. +#[derive(Debug, Clone)] +pub struct NetworkLimits { + /// Catalogue requests of one lookup running at once. + pub catalog_requests: usize, + /// Time for all lookups of one artist group, retries included. + pub group_timeout: Duration, + /// Waits before repeating a failed search; the group is skipped after the last. + pub backoff: Vec, + /// Artist groups searched per pass. + pub max_groups: usize, + /// Time for the network stage of one pass. + pub max_duration: Duration, + /// How often a running group checks for cancellation and lease loss. + pub poll: Duration, +} + +impl Default for NetworkLimits { + fn default() -> Self { + Self { + catalog_requests: 4, + group_timeout: Duration::from_secs(60), + backoff: vec![ + Duration::from_secs(2), + Duration::from_secs(4), + Duration::from_secs(8), + ], + max_groups: 500, + max_duration: Duration::from_secs(30 * 60), + poll: Duration::from_secs(1), + } + } } /// Up to this many artist names are looked up by name patterns. @@ -50,7 +107,10 @@ const FOLD_SQL: &str = "'[\\u0300-\\u036f]'"; /// A pending entry with its prepared source. pub struct Entry { pub id: i64, + raw: Source, source: PreparedSource, + /// Why stages 1–2 found nothing, for an entry waiting for the network. + note: Option, } /// Entries of one resolver pass, grouped by their main artist. @@ -106,13 +166,13 @@ impl Resolver { for entry in entries { match serde_json::from_value::(entry.metadata) { Ok(metadata) if !metadata.title.trim().is_empty() => { - parsed.push((entry.id, entry.artist_key, metadata)); + parsed.push((entry.id, entry.artist_key, entry.note, metadata)); } _ => invalid.push(Resolution::failed(entry.id, "invalid_metadata")), } } let mut names = BTreeSet::new(); - for (_, _, metadata) in &parsed { + for (_, _, _, metadata) in &parsed { let featured = matcher::parse_title(&metadata.title).featured; for raw in metadata.artists.iter().chain(&featured) { names.extend(matcher::artist_name_variants(raw)); @@ -173,16 +233,14 @@ impl Resolver { let mut groups: Vec> = Vec::new(); let mut current_key: Option> = None; - for (id, artist_key, metadata) in parsed { - let source = PreparedSource::new( - &Source { - title: metadata.title, - artists: metadata.artists, - album: metadata.album, - duration_ms: metadata.duration_ms, - }, - &known, - ); + for (id, artist_key, note, metadata) in parsed { + let raw = Source { + title: metadata.title, + artists: metadata.artists, + album: metadata.album, + duration_ms: metadata.duration_ms, + }; + let source = PreparedSource::new(&raw, &known); let same_group = current_key.as_ref() == Some(&artist_key) && groups.last().is_some_and(|group| group.len() < MAX_GROUP); if !same_group { @@ -192,7 +250,12 @@ impl Resolver { groups .last_mut() .expect("a group was just pushed") - .push(Entry { id, source }); + .push(Entry { + id, + raw, + source, + note, + }); } Ok(Prepared { resolver: Self { @@ -240,8 +303,15 @@ impl Resolver { } /// Decides every entry of a group: the local library first (stage 1), - /// then together with the known federated tracks (stage 2). - pub async fn resolve_group(&self, pool: &PgPool, group: &[Entry]) -> Result> { + /// then together with the known federated tracks (stage 2). With + /// `defer_unmatched` an entry without a match stays pending with its + /// reason for the network stage. + pub async fn resolve_group( + &self, + pool: &PgPool, + group: &[Entry], + defer_unmatched: bool, + ) -> Result> { let mut artist_ids = BTreeSet::new(); let mut by_title = Vec::new(); for entry in group { @@ -326,7 +396,14 @@ impl Resolver { }, Decision::Unmatched { reason } => Resolution { note: Some(reason.to_owned()), - ..Resolution::new(entry.id, ResolutionStatus::Unmatched) + ..Resolution::new( + entry.id, + if defer_unmatched { + ResolutionStatus::Pending + } else { + ResolutionStatus::Unmatched + }, + ) }, }); } @@ -381,16 +458,21 @@ impl Resolver { ..base } } - Chosen::Federated(track) => Resolution { - origin: Some(Origin::Federation.as_str()), - content_id: Some(track.fed.content_id.clone()), - fed: serde_json::to_value(&track.fed).ok(), - ..base - }, + Chosen::Federated(track) => federated_match(base, track), } } } +/// A match with a federated track: published by its content id and `SyncedFedTrack`. +fn federated_match(base: Resolution, track: &KnownTrack) -> Resolution { + Resolution { + origin: Some(Origin::Federation.as_str()), + content_id: Some(track.fed.content_id.clone()), + fed: serde_json::to_value(&track.fed).ok(), + ..base + } +} + /// The track behind a candidate index: local candidates come first. enum Chosen<'a> { Local(&'a LocalTrack), @@ -436,6 +518,66 @@ fn candidate_json(ranked: &Ranked, chosen: Chosen<'_>) -> Value { }) } +/// A candidate the user chose, read back from the stored `candidates` +/// (written by [`candidate_json`]). Stored data is checked again, so only a +/// verifiable content id and a servable federated source are accepted. +#[derive(Debug, Clone, PartialEq)] +pub struct ManualMatch { + pub origin: Origin, + pub score: Option, + pub content_id: Option, + pub track_id: Option, + pub fed: Option, +} + +impl ManualMatch { + pub fn from_candidate(candidate: &Value) -> Option { + let content_id = match candidate.get("content_id") { + None | Some(Value::Null) => None, + Some(value) => Some(music_dht::normalize_content_id(value.as_str()?)?), + }; + let score = candidate + .get("score") + .and_then(Value::as_f64) + .map(|score| score as f32); + match candidate.get("origin")?.as_str()? { + "local" => Some(Self { + origin: Origin::Local, + score, + content_id, + track_id: Some(candidate.get("track_id")?.as_i64()?), + fed: None, + }), + "federation" => { + let content_id = content_id?; + let fed: SyncedFedTrack = + serde_json::from_value(candidate.get("fed")?.clone()).ok()?; + let valid = music_dht::normalize_content_id(&fed.content_id).as_deref() + == Some(content_id.as_str()) + && !fed.title.trim().is_empty() + && usable_source(&fed.owner, &fed.item_id); + valid.then(|| Self { + origin: Origin::Federation, + score, + fed: serde_json::to_value(&fed).ok(), + content_id: Some(content_id), + track_id: None, + }) + } + _ => None, + } + } + + /// A local track without a content id waits for the publisher to hash it. + pub fn publication(&self) -> PublicationStatus { + if self.content_id.is_some() { + PublicationStatus::Pending + } else { + PublicationStatus::NoContentId + } + } +} + fn longest_token(key: &str) -> Option<&str> { key.split(' ') .filter(|token| !token.is_empty()) diff --git a/src/library_import/resolver/federated.rs b/src/library_import/resolver/federated.rs new file mode 100644 index 0000000..7484d11 --- /dev/null +++ b/src/library_import/resolver/federated.rs @@ -0,0 +1,650 @@ +//! Resolver stage 3 (plan §6): artist catalogues of federation peers. +//! +//! Only artist names leave the server. Each artist group is looked up by its +//! original name, then by its folded spelling, then by its collaboration +//! parts; whatever peers return becomes federated candidates for the group. +//! Groups run under a process-wide limit, a time limit per group and a budget +//! per pass. Dropping a running group cancels its search and all catalogue +//! requests. + +use std::collections::{HashMap, VecDeque}; +use std::sync::Arc; + +use music_dht::catalog::{CatalogArtist, CatalogTrack}; +use music_dht::device_sync::SyncedFedTrack; +use serde_json::Value; +use tokio::sync::Semaphore; +use tokio::time::Instant; + +use super::{ + Chosen, Entry, FederationAccess, KnownTrack, NetworkLimits, Resolver, candidate_json, + federated_match, usable_source, +}; +use crate::federation::client::CatalogError; +use crate::library_import::matcher::{ + self, Candidate, Decision, NameKey, Origin, PreparedCandidate, PreparedSource, +}; +use crate::library_import::model::{PublicationStatus, ResolutionStatus}; +use crate::library_import::store::Resolution; + +/// Artist groups searched at once by all imports of this process. +static GROUPS: Semaphore = Semaphore::const_new(2); +/// Lookups remembered during one pass. +const CACHE_NAMES: usize = 64; + +/// `resolution_note` when the federation node is off or stopped. +pub const FEDERATION_UNAVAILABLE: &str = "federation_unavailable"; +/// `resolution_note` of entries left over by the budget of a pass. +pub const FEDERATION_BUDGET: &str = "federation_budget"; +/// `resolution_note` of a group whose search kept failing; Resync retries it. +pub const FEDERATION_ERROR: &str = "federation_error"; + +/// The result of one artist group. +#[derive(Debug)] +pub enum GroupOutcome { + /// A decision for every entry of the group. + Resolved { + resolutions: Vec, + /// Catalogues received. + catalogs: u64, + /// Catalogues lost: unreachable, refused, too large or late. + catalog_errors: u64, + }, + /// The federation node is not running; the stage stops. + Unavailable, +} + +/// Federated tracks found for one name, unique by content id. +#[derive(Debug, Default)] +struct Found { + tracks: Vec<(SyncedFedTrack, Vec)>, + by_content: HashMap, + names: Vec, +} + +impl Found { + fn is_empty(&self) -> bool { + self.tracks.is_empty() + } + + /// Takes the tracks of a catalogue with a verifiable content id and a + /// source the network can serve. + fn add_catalog(&mut self, owner: &str, artist: &CatalogArtist) { + self.names.push(artist.name.clone()); + for release in &artist.releases { + for track in &release.tracks { + self.add_track(owner, &artist.name, track, &release.title, release.year); + } + } + for appearance in &artist.appears_on { + self.add_track( + owner, + &artist.name, + &appearance.track, + &appearance.release_title, + appearance.year, + ); + } + } + + fn add_track( + &mut self, + owner: &str, + artist: &str, + track: &CatalogTrack, + release: &str, + year: Option, + ) { + let Some(content_id) = track + .content_id + .as_deref() + .and_then(music_dht::normalize_content_id) + else { + return; + }; + if track.title.trim().is_empty() || !usable_source(owner, &track.item_id) { + return; + } + let artists = if track.artists.is_empty() { + vec![artist.to_owned()] + } else { + track.artists.clone() + }; + self.add( + SyncedFedTrack { + item_id: track.item_id.clone(), + owner: owner.to_owned(), + title: track.title.clone(), + artist_names: artists, + featured_artist_names: track.featured_artists.clone(), + year, + duration_seconds: track + .duration_seconds + .filter(|seconds| seconds.is_finite() && *seconds > 0.0) + .map(|seconds| seconds.round() as i64), + content_id, + release_title: Some(release.trim()) + .filter(|title| !title.is_empty()) + .map(str::to_owned), + track_number: track.track_number, + disc_number: track.disc_number, + }, + std::slice::from_ref(&owner.to_owned()), + ); + } + + /// Adds a track; another owner of a known content id counts, and the + /// first owner by id is kept as the source whatever order peers answer in. + fn add(&mut self, track: SyncedFedTrack, owners: &[String]) { + match self.by_content.get(&track.content_id) { + Some(&index) => { + let (source, known) = &mut self.tracks[index]; + for owner in owners { + if !known.contains(owner) { + known.push(owner.clone()); + } + } + known.sort(); + if track.owner < source.owner { + *source = track; + } + } + None => { + self.by_content + .insert(track.content_id.clone(), self.tracks.len()); + self.tracks.push((track, owners.to_vec())); + } + } + } + + fn merge(&mut self, other: &Found) { + self.names.extend(other.names.iter().cloned()); + for (track, owners) in &other.tracks { + self.add(track.clone(), owners); + } + } +} + +enum Lookup { + Found(Arc), + /// The group ran out of time; what arrived until then. + TimedOut(Found), + /// The search failed after every retry. + Failed, + Unavailable, +} + +#[derive(Default)] +struct Counts { + catalogs: u64, + catalog_errors: u64, +} + +/// Stage 3 of one resolver pass. +pub struct NetworkSearch<'a> { + resolver: &'a mut Resolver, + federation: &'a dyn FederationAccess, + limits: NetworkLimits, + cache: HashMap>, + cache_order: VecDeque, + groups: usize, + started: Instant, +} + +impl<'a> NetworkSearch<'a> { + pub fn new(resolver: &'a mut Resolver, federation: &'a dyn FederationAccess) -> Self { + Self { + resolver, + limits: federation.limits(), + federation, + cache: HashMap::new(), + cache_order: VecDeque::new(), + groups: 0, + started: Instant::now(), + } + } + + pub fn limits(&self) -> &NetworkLimits { + &self.limits + } + + /// Artist groups that asked the network. + pub fn groups(&self) -> usize { + self.groups + } + + /// Whether the pass used up its groups or its time. + pub fn exhausted(&self) -> bool { + self.groups >= self.limits.max_groups || self.started.elapsed() >= self.limits.max_duration + } + + /// Searches the catalogues of a group's artist and decides its entries. + /// Cancel-safe: dropping the future stops the search and its requests. + pub async fn resolve_group(&mut self, group: &[Entry]) -> GroupOutcome { + let Some(name) = group_artist(group) else { + return GroupOutcome::Resolved { + resolutions: self.decide(group, &Found::default()), + catalogs: 0, + catalog_errors: 0, + }; + }; + let _permit = GROUPS + .acquire() + .await + .expect("the semaphore is never closed"); + self.groups += 1; + let deadline = Instant::now() + self.limits.group_timeout; + let mut counts = Counts::default(); + let mut found = Found::default(); + let (mut failed, mut timed_out) = (false, false); + let mut queue = VecDeque::from([name.clone()]); + let mut step = 0; + 'search: loop { + while let Some(query) = queue.pop_front() { + match self.lookup(&query, deadline, &mut counts).await { + Lookup::Found(result) => found.merge(&result), + Lookup::TimedOut(result) => { + found.merge(&result); + timed_out = true; + break 'search; + } + Lookup::Failed => failed = true, + Lookup::Unavailable => return GroupOutcome::Unavailable, + } + } + if !found.is_empty() { + break; + } + step += 1; + match step { + 1 => queue.extend(latin_folded(&name)), + 2 => { + let parts = matcher::split_artists(&name, &self.resolver.known); + if parts.len() > 1 { + queue.extend(parts); + } + } + _ => break, + } + } + let resolutions = if found.is_empty() && (failed || timed_out) { + group + .iter() + .map(|entry| Resolution::failed(entry.id, FEDERATION_ERROR)) + .collect() + } else { + self.decide(group, &found) + }; + GroupOutcome::Resolved { + resolutions, + catalogs: counts.catalogs, + catalog_errors: counts.catalog_errors, + } + } + + /// One name: from the cache, or from the network with retries after a + /// failed search. Lost catalogues are counted, not retried. + async fn lookup(&mut self, name: &str, deadline: Instant, counts: &mut Counts) -> Lookup { + let key = NameKey::new(name).key; + if let Some(found) = self.cache.get(&key) { + return Lookup::Found(Arc::clone(found)); + } + let mut attempt = 0; + loop { + let Some(mut stream) = self + .federation + .artist_catalogs(name, self.limits.catalog_requests) + .await + else { + return Lookup::Unavailable; + }; + let mut found = Found::default(); + let mut search_failed = false; + loop { + match tokio::time::timeout_at(deadline, stream.next()).await { + // Dropping the stream cancels the requests still running. + Err(_) => { + counts.catalog_errors += 1; + return Lookup::TimedOut(found); + } + Ok(None) => break, + Ok(Some(Ok((owner, artist)))) => { + counts.catalogs += 1; + found.add_catalog(&owner, &artist); + } + // Errors describe the transport or the peer, never the artist name. + Ok(Some(Err(CatalogError::Catalog(error)))) => { + tracing::debug!(%error, "library import lost a peer catalogue"); + counts.catalog_errors += 1; + } + Ok(Some(Err(CatalogError::Search(error)))) => { + tracing::debug!(%error, "library import network search failed"); + search_failed = true; + } + } + } + if !search_failed { + let found = Arc::new(found); + self.remember(key, Arc::clone(&found)); + return Lookup::Found(found); + } + let Some(wait) = self.limits.backoff.get(attempt).copied() else { + return Lookup::Failed; + }; + attempt += 1; + if Instant::now() + wait >= deadline { + tokio::time::sleep_until(deadline).await; + return Lookup::Failed; + } + tokio::time::sleep(wait).await; + } + } + + fn remember(&mut self, key: String, found: Arc) { + if self.cache.len() >= CACHE_NAMES + && let Some(oldest) = self.cache_order.pop_front() + { + self.cache.remove(&oldest); + } + self.cache_order.push_back(key.clone()); + self.cache.insert(key, found); + } + + /// Decides the group's entries from the federated candidates found. + fn decide(&mut self, group: &[Entry], found: &Found) -> Vec { + let known = &mut self.resolver.known; + for name in &found.names { + known.insert(name); + } + for (track, _) in &found.tracks { + for name in track + .artist_names + .iter() + .chain(&track.featured_artist_names) + { + known.insert(name); + } + } + let known = &*known; + let tracks: Vec = found + .tracks + .iter() + .map(|(fed, owners)| { + let candidate = Candidate { + origin: Origin::Federation, + title: fed.title.clone(), + artists: fed.artist_names.clone(), + featured_artists: fed.featured_artist_names.clone(), + album: fed.release_title.clone(), + duration_seconds: fed.duration_seconds.map(|seconds| seconds as f64), + content_id: Some(fed.content_id.clone()), + owners: u32::try_from(owners.len()).unwrap_or(u32::MAX), + }; + let prepared = PreparedCandidate::new(&candidate, known); + KnownTrack { + fed: fed.clone(), + candidate, + prepared, + } + }) + .collect(); + let mut by_title: HashMap<&str, Vec> = HashMap::new(); + for (index, track) in tracks.iter().enumerate() { + let title = track.prepared.title_key(); + by_title.entry(title.key.as_str()).or_default().push(index); + if title.folded != title.key { + by_title + .entry(title.folded.as_str()) + .or_default() + .push(index); + } + } + group + .iter() + .map(|entry| { + // Catalogue names may split collaborations stages 1–2 kept whole. + let source = PreparedSource::new(&entry.raw, known); + let title = source.title_key(); + let mut indexes: Vec = [title.key.as_str(), title.folded.as_str()] + .iter() + .filter_map(|key| by_title.get(key)) + .flatten() + .copied() + .collect(); + indexes.sort_unstable(); + indexes.dedup(); + let candidates: Vec<&KnownTrack> = + indexes.iter().map(|index| &tracks[*index]).collect(); + let prepared: Vec<&PreparedCandidate> = + candidates.iter().map(|track| &track.prepared).collect(); + match matcher::decide(&source, &prepared) { + Decision::Matched(ranked) => federated_match( + Resolution { + score: Some(ranked.score), + publication: PublicationStatus::Pending, + ..Resolution::new(entry.id, ResolutionStatus::Matched) + }, + candidates[ranked.index], + ), + Decision::Ambiguous(ranked) => Resolution { + score: ranked.first().map(|best| best.score), + candidates: Some(Value::Array( + ranked + .iter() + .map(|ranked| { + candidate_json( + ranked, + Chosen::Federated(candidates[ranked.index]), + ) + }) + .collect(), + )), + ..Resolution::new(entry.id, ResolutionStatus::Ambiguous) + }, + Decision::Unmatched { reason } => Resolution { + note: Some(stronger_note(entry.note.as_deref(), reason).to_owned()), + ..Resolution::new(entry.id, ResolutionStatus::Unmatched) + }, + } + }) + .collect() + } +} + +/// The artist name a group is looked up by: the first credited artist as the +/// source spells it. +fn group_artist(group: &[Entry]) -> Option { + group + .iter() + .filter_map(|entry| entry.raw.artists.first()) + .map(|name| name.trim()) + .find(|name| !NameKey::new(name).is_empty()) + .map(str::to_owned) +} + +/// The name without the diacritics of Latin letters (Beyoncé → beyonce), if +/// it differs. Other scripts keep their marks: й is a letter of its own, and +/// peers spell it so. +fn latin_folded(name: &str) -> Option { + use unicode_normalization::UnicodeNormalization; + let key = NameKey::new(name).key; + let mut folded = String::with_capacity(key.len()); + let mut latin_base = false; + for c in key.nfd() { + if ('\u{300}'..='\u{36f}').contains(&c) { + if latin_base { + continue; + } + } else { + latin_base = c.is_ascii_alphabetic(); + } + folded.push(c); + } + let folded: String = folded.nfc().collect(); + (!folded.trim().is_empty() && folded != key).then_some(folded) +} + +/// The more specific of two reasons for an entry without a match. +fn stronger_note<'a>(local: Option<&'a str>, network: &'a str) -> &'a str { + fn rank(note: &str) -> u8 { + match note { + "duration_mismatch" => 2, + "version_mismatch" => 1, + _ => 0, + } + } + match local { + Some(local) if rank(local) > rank(network) => local, + _ => network, + } +} + +#[cfg(test)] +mod tests { + use music_dht::catalog::{CatalogAppearance, CatalogRelease}; + + use super::*; + + fn b3(digit: char) -> String { + format!("b3:{}", digit.to_string().repeat(64)) + } + + fn track(title: &str, content_id: Option, item_id: &str) -> CatalogTrack { + CatalogTrack { + title: title.into(), + duration_seconds: Some(200.4), + content_id, + item_id: item_id.into(), + ..Default::default() + } + } + + #[test] + fn catalogue_tracks_become_portable_federated_tracks() { + let artist = CatalogArtist { + name: "Кино".into(), + releases: vec![CatalogRelease { + title: "Группа крови".into(), + year: Some(1988), + tracks: vec![ + track("Группа крови", Some(b3('a')), "item-1"), + track("Без content id", None, "item-2"), + track("Свой трек веба", Some(b3('b')), "web:7"), + track(" ", Some(b3('c')), "item-3"), + ], + ..Default::default() + }], + appears_on: vec![CatalogAppearance { + release_title: "Сборник".into(), + year: Some(2000), + track: CatalogTrack { + artists: vec!["Другой".into()], + ..track("Группа крови", Some(b3('a')), "item-9") + }, + ..Default::default() + }], + }; + let mut found = Found::default(); + found.add_catalog("peer-1", &artist); + found.add_catalog("peer-2", &artist); + assert_eq!(found.tracks.len(), 1); + let (fed, owners) = &found.tracks[0]; + assert_eq!(owners, &["peer-1", "peer-2"]); + assert_eq!(fed.owner, "peer-1"); + assert_eq!(fed.item_id, "item-1"); + assert_eq!(fed.artist_names, ["Кино"]); + assert_eq!(fed.release_title.as_deref(), Some("Группа крови")); + assert_eq!(fed.year, Some(1988)); + assert_eq!(fed.duration_seconds, Some(200)); + assert_eq!(fed.content_id, b3('a')); + assert_eq!(found.names, ["Кино", "Кино"]); + } + + #[test] + fn only_latin_diacritics_are_folded_for_the_network() { + assert_eq!(latin_folded("Beyoncé").as_deref(), Some("beyonce")); + assert_eq!(latin_folded("Sigur Rós").as_deref(), Some("sigur ros")); + assert_eq!(latin_folded("Мумий Тролль"), None); + assert_eq!(latin_folded("Queen"), None); + } + + #[test] + fn stored_candidates_are_checked_before_a_manual_match() { + use super::super::ManualMatch; + + let fed = SyncedFedTrack { + item_id: "item-1".into(), + owner: "peer-1".into(), + title: "Группа крови".into(), + artist_names: vec!["Кино".into()], + featured_artist_names: Vec::new(), + year: None, + duration_seconds: Some(285), + content_id: b3('a'), + release_title: None, + track_number: None, + disc_number: None, + }; + let candidate = Candidate { + origin: Origin::Federation, + title: fed.title.clone(), + artists: fed.artist_names.clone(), + featured_artists: Vec::new(), + album: None, + duration_seconds: Some(285.0), + content_id: Some(fed.content_id.clone()), + owners: 1, + }; + let prepared = PreparedCandidate::new(&candidate, &Default::default()); + let track = KnownTrack { + fed, + candidate, + prepared, + }; + // Without a duration on the source side the candidate is only weak. + let source = PreparedSource::new( + &matcher::Source { + title: "Группа крови".into(), + artists: vec!["Кино".into()], + album: None, + duration_ms: None, + }, + &Default::default(), + ); + let Decision::Ambiguous(ranked) = matcher::decide(&source, &[&track.prepared]) else { + panic!("a weak candidate is left to the user"); + }; + let ranked = ranked[0]; + let stored = candidate_json(&ranked, Chosen::Federated(&track)); + let chosen = ManualMatch::from_candidate(&stored).unwrap(); + assert_eq!(chosen.origin, Origin::Federation); + assert_eq!(chosen.content_id, Some(b3('a'))); + assert_eq!(chosen.publication(), PublicationStatus::Pending); + + let mut web = stored.clone(); + web["fed"]["item_id"] = "web:7".into(); + let mut other = stored.clone(); + other["content_id"] = b3('b').into(); + let mut origin = stored.clone(); + origin["origin"] = "elsewhere".into(); + for invalid in [web, other, origin] { + assert_eq!(ManualMatch::from_candidate(&invalid), None); + } + let local = serde_json::json!({"origin": "local", "track_id": 3, "content_id": null}); + let chosen = ManualMatch::from_candidate(&local).unwrap(); + assert_eq!(chosen.publication(), PublicationStatus::NoContentId); + } + + #[test] + fn the_more_specific_reason_is_kept() { + assert_eq!( + stronger_note(Some("version_mismatch"), "not_found"), + "version_mismatch" + ); + assert_eq!( + stronger_note(Some("not_found"), "duration_mismatch"), + "duration_mismatch" + ); + assert_eq!(stronger_note(None, "not_found"), "not_found"); + } +} diff --git a/src/library_import/store.rs b/src/library_import/store.rs index 976dcbf..8d22540 100644 --- a/src/library_import/store.rs +++ b/src/library_import/store.rs @@ -15,6 +15,7 @@ use super::model::{ PlaylistLink, PlaylistView, PublicationStatus, ResolutionStatus, SourceType, }; use super::providers::FetchTarget; +use super::resolver::ManualMatch; /// Rows per `INSERT … SELECT FROM UNNEST` statement. const INSERT_CHUNK: usize = 1000; @@ -435,7 +436,7 @@ pub async fn open_attempt(pool: &PgPool, import_id: i64, run_id: i64) -> sqlx::R SELECT $1, CASE WHEN EXISTS(SELECT 1 FROM furumusic__library_import_attempt WHERE import_id = $1) THEN 'resync' ELSE 'initial' END, - 'running', statistics + 'running', statistics || jsonb_build_object('catalog_errors', 0) FROM furumusic__library_import WHERE id = $1 ON CONFLICT (import_id) WHERE finished_at IS NULL DO NOTHING", ) @@ -473,6 +474,27 @@ pub async fn refresh_statistics( row.get(3), ); } + // Lost catalogues are not entry states: the open attempt counts them. + let catalog_errors: Option = sqlx::query_scalar( + "SELECT (statistics->>'catalog_errors')::int8 FROM furumusic__library_import_attempt + WHERE import_id = $1 AND finished_at IS NULL", + ) + .bind(import_id) + .fetch_optional(&mut *conn) + .await? + .flatten(); + let catalog_errors = match catalog_errors { + Some(count) => Some(count), + None => sqlx::query_scalar( + "SELECT (statistics->>'catalog_errors')::int8 FROM furumusic__library_import + WHERE id = $1", + ) + .bind(import_id) + .fetch_optional(&mut *conn) + .await? + .flatten(), + }; + statistics.catalog_errors = catalog_errors.unwrap_or(0); let value = serde_json::to_value(&statistics).map_err(|error| sqlx::Error::Encode(Box::new(error)))?; sqlx::query("UPDATE furumusic__library_import SET statistics = $2 WHERE id = $1") @@ -491,6 +513,53 @@ pub async fn refresh_statistics( Ok(statistics) } +/// Counts peer catalogues the network search lost, on the open attempt and the import. +pub async fn add_catalog_errors( + pool: &PgPool, + import_id: i64, + run_id: i64, + count: u64, +) -> sqlx::Result { + if count == 0 { + return Ok(true); + } + let count = i64::try_from(count).unwrap_or(i64::MAX); + let mut tx = pool.begin().await?; + let owned: Option = sqlx::query_scalar( + "SELECT id FROM furumusic__library_import + WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR SHARE", + ) + .bind(import_id) + .bind(run_id) + .fetch_optional(&mut *tx) + .await?; + if owned.is_none() { + return Ok(false); + } + for table in [ + "furumusic__library_import_attempt", + "furumusic__library_import", + ] { + let filter = if table == "furumusic__library_import" { + "id = $1" + } else { + "import_id = $1 AND finished_at IS NULL" + }; + sqlx::query(&format!( + "UPDATE {table} + SET statistics = statistics || jsonb_build_object('catalog_errors', + COALESCE((statistics->>'catalog_errors')::int8, 0) + $2) + WHERE {filter}" + )) + .bind(import_id) + .bind(count) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(true) +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum FinishOutcome { Done(ImportStatistics), @@ -785,12 +854,14 @@ pub struct PendingEntry { pub id: i64, pub artist_key: Option, pub metadata: Value, + /// Set by stages 1–2 on an entry that waits for the network stage. + pub note: Option, } /// Pending entries of an import, grouped by their main artist. pub async fn pending_entries(pool: &PgPool, import_id: i64) -> sqlx::Result> { let rows = sqlx::query( - "SELECT i.id, i.artist_key, i.metadata + "SELECT i.id, i.artist_key, i.metadata, i.resolution_note FROM furumusic__library_import_item i JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id WHERE p.import_id = $1 AND i.resolution_status = 'pending' @@ -805,6 +876,7 @@ pub async fn pending_entries(pool: &PgPool, import_id: i64) -> sqlx::Result, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let owned: Option = sqlx::query_scalar( + "SELECT id FROM furumusic__library_import + WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR SHARE", + ) + .bind(import_id) + .bind(run_id) + .fetch_optional(&mut *tx) + .await?; + if owned.is_none() { + return Ok(false); + } + sqlx::query( + "UPDATE furumusic__library_import_item i + SET resolution_status = 'unmatched', + resolution_note = COALESCE($2, i.resolution_note), + publication_status = 'not_ready', last_attempt_at = now() + FROM furumusic__library_import_playlist p + WHERE p.id = i.import_playlist_id AND p.import_id = $1 + AND i.resolution_status = 'pending' AND i.resolution_note IS NOT NULL", + ) + .bind(import_id) + .bind(note) + .execute(&mut *tx) + .await?; + refresh_statistics(&mut tx, import_id).await?; + tx.commit().await?; + Ok(true) +} + // --------------------------------------------------------------------------- // Owner requests // --------------------------------------------------------------------------- @@ -1160,6 +1271,127 @@ pub async fn list_items( })) } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChooseOutcome { + /// The entry is matched manually. `queued` when the import waits for a + /// worker again; a running worker publishes it before it finishes. + Chosen { + queued: bool, + publication: PublicationStatus, + }, + NotFound, + /// The entry has no candidates to choose from. + NotAmbiguous, + /// No candidate with this index, or its stored data is not usable. + InvalidCandidate, + /// The chosen library track was removed or hidden meanwhile. + TrackGone, +} + +/// `POST …/items/{item_id}/match`: takes candidate `index` of an ambiguous +/// entry. Waits for a running publication batch, like cancellation. +pub async fn choose_candidate( + pool: &PgPool, + user_id: i64, + import_id: i64, + item_id: i64, + index: usize, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let status: Option = sqlx::query_scalar( + "SELECT status FROM furumusic__library_import WHERE id = $1 AND user_id = $2 FOR UPDATE", + ) + .bind(import_id) + .bind(user_id) + .fetch_optional(&mut *tx) + .await?; + let Some(status) = status else { + return Ok(ChooseOutcome::NotFound); + }; + let row = sqlx::query( + "SELECT i.resolution_status, i.candidates + FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE i.id = $1 AND p.import_id = $2 + FOR UPDATE OF i", + ) + .bind(item_id) + .bind(import_id) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = row else { + return Ok(ChooseOutcome::NotFound); + }; + let resolution: String = row.get(0); + if resolution != ResolutionStatus::Ambiguous.as_str() { + return Ok(ChooseOutcome::NotAmbiguous); + } + let candidates: Option = row.get(1); + let Some(chosen) = candidates + .as_ref() + .and_then(Value::as_array) + .and_then(|candidates| candidates.get(index)) + .and_then(ManualMatch::from_candidate) + else { + return Ok(ChooseOutcome::InvalidCandidate); + }; + if let Some(track_id) = chosen.track_id { + let visible: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM furumusic__track t + JOIN furumusic__release r ON r.id = t.release_id + WHERE t.id = $1 AND NOT t.is_hidden AND NOT r.is_hidden)", + ) + .bind(track_id) + .fetch_one(&mut *tx) + .await?; + if !visible { + return Ok(ChooseOutcome::TrackGone); + } + } + let publication = chosen.publication(); + sqlx::query( + "UPDATE furumusic__library_import_item + SET resolution_status = 'matched', resolution_note = NULL, + match_origin = $2, match_method = 'manual', match_score = $3, + matched_content_id = $4, matched_track_id = $5, matched_fed = $6, + publication_status = $7, last_attempt_at = now() + WHERE id = $1", + ) + .bind(item_id) + .bind(chosen.origin.as_str()) + .bind(chosen.score) + .bind(chosen.content_id.as_deref()) + .bind(chosen.track_id) + .bind(chosen.fed.as_ref()) + .bind(publication.as_str()) + .execute(&mut *tx) + .await?; + // A finished import is queued again; a waiting or running one publishes + // the entry before it finishes. + let queued = matches!( + status.parse::(), + Ok(ImportStatus::Done | ImportStatus::Cancelled | ImportStatus::Failed) + ); + sqlx::query( + "UPDATE furumusic__library_import + SET rerun_requested = true, + cancel_requested = CASE WHEN $2 THEN false ELSE cancel_requested END, + status = CASE WHEN $2 THEN 'queued' ELSE status END, + updated_at = now() + WHERE id = $1", + ) + .bind(import_id) + .bind(queued) + .execute(&mut *tx) + .await?; + refresh_statistics(&mut tx, import_id).await?; + tx.commit().await?; + Ok(ChooseOutcome::Chosen { + queued, + publication, + }) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CancelOutcome { /// The import had no worker and is cancelled now. diff --git a/src/library_import/tests.rs b/src/library_import/tests.rs index aa6818a..2e1cead 100644 --- a/src/library_import/tests.rs +++ b/src/library_import/tests.rs @@ -3,7 +3,11 @@ //! `FURU_LIBRARY_IMPORT_TEST_DATABASE_URL`. use std::collections::HashSet; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use music_dht::catalog::{CatalogArtist, CatalogRelease, CatalogTrack}; use serde_json::json; use sqlx::PgPool; @@ -12,6 +16,7 @@ use super::adapters::spotify_export::SpotifyExport; use super::adapters::{self, FileAdapter, InputFile}; use super::handlers::select_file_playlists; use super::job; +use super::matcher::NameKey; use super::model::{ self as import_model, ImportedLibrary, ImportedTrack, Phase, PlaylistKind, ResolutionStatus, SourceType, TrackKind, @@ -19,12 +24,13 @@ use super::model::{ use super::providers::{ AccessToken, Connection, FetchError, FetchTarget, LibraryFetcher, TOKEN_TTL, TokenVault, }; -use super::resolver::FederationAccess; +use super::resolver::{FederationAccess, NetworkLimits}; use super::store::{ - self, CancelOutcome, Control, CreateImportError, DeleteOutcome, FinishOutcome, ItemFilter, - NewImport, NewItem, NewPlaylist, ReauthOutcome, ReauthTarget, + self, CancelOutcome, ChooseOutcome, Control, CreateImportError, DeleteOutcome, FinishOutcome, + ItemFilter, NewImport, NewItem, NewPlaylist, ReauthOutcome, ReauthTarget, }; use crate::config::AppConfig; +use crate::federation::client::{CatalogPeers, CatalogStream}; use crate::scheduler::JobLog; /// Workers share a process-wide slot counter, so database tests run one at a time. @@ -231,6 +237,10 @@ impl FederationAccess for NoNetwork { async fn is_running(&self) -> bool { panic!("the resolver must not use the federation without consent"); } + + async fn artist_catalogs(&self, _name: &str, _max_parallel: usize) -> Option { + panic!("the resolver must not search the network without consent"); + } } async fn run_worker(pool: &PgPool, run_id: i64) -> String { @@ -1472,7 +1482,7 @@ async fn library_import_resolves_locally_without_the_network() { let output = log.output(); assert!( output - .contains("resolved 9 entries locally (5 matched, 1 ambiguous, 3 unmatched, 0 failed)"), + .contains("resolved 9 entries locally (5 matched, 1 ambiguous, 3 unmatched, 0 failed, 0 left for the network)"), "{output}" ); // The log carries ids and counters only. @@ -1677,3 +1687,608 @@ async fn library_import_resolves_locally_without_the_network() { fixture.drop().await; } + +// --------------------------------------------------------------------------- +// Resolver stage 3: artist catalogues of peers +// --------------------------------------------------------------------------- + +/// How a fake peer answers a catalogue request. +#[derive(Clone)] +enum Reply { + Catalog(CatalogArtist), + Fail, + Hang, +} + +/// Counts fake requests still running; dropped requests count down. +struct LiveRequest(Arc); + +impl LiveRequest { + fn start(live: &Arc) -> Self { + live.fetch_add(1, Ordering::SeqCst); + Self(Arc::clone(live)) + } +} + +impl Drop for LiveRequest { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + +/// Peers answering by artist name key. +struct FakePeers { + owners: Vec<(usize, Reply)>, + search_fails: bool, + live: Arc, +} + +#[async_trait::async_trait] +impl CatalogPeers for FakePeers { + type Owner = usize; + + async fn owners(&self, name: &str) -> anyhow::Result> { + anyhow::ensure!(!self.search_fails, "search failed"); + Ok(self + .owners + .iter() + .map(|(owner, _)| (*owner, name.to_owned())) + .collect()) + } + + async fn catalog(&self, owner: usize, _name: String) -> anyhow::Result { + let _live = LiveRequest::start(&self.live); + match &self.owners[owner].1 { + Reply::Catalog(artist) => Ok(artist.clone()), + Reply::Fail => anyhow::bail!("peer refused catalog"), + Reply::Hang => std::future::pending().await, + } + } +} + +/// A federation whose peers are configured per artist name key. +struct FakeNetwork { + running: bool, + peers: std::collections::HashMap>, + failing: HashSet, + catalog_timeout: Duration, + limits: NetworkLimits, + searches: Mutex>, + live: Arc, +} + +impl FakeNetwork { + fn new() -> Self { + Self { + running: true, + peers: Default::default(), + failing: HashSet::new(), + catalog_timeout: Duration::from_millis(300), + limits: NetworkLimits { + backoff: vec![Duration::from_millis(10), Duration::from_millis(20)], + poll: Duration::from_millis(20), + ..NetworkLimits::default() + }, + searches: Mutex::new(Vec::new()), + live: Arc::default(), + } + } + + fn peer(mut self, artist: &str, replies: Vec) -> Self { + self.peers.insert(NameKey::new(artist).key, replies); + self + } + + fn searches(&self) -> Vec { + self.searches.lock().unwrap().clone() + } +} + +#[async_trait::async_trait] +impl FederationAccess for FakeNetwork { + async fn is_running(&self) -> bool { + self.running + } + + async fn artist_catalogs(&self, name: &str, max_parallel: usize) -> Option { + assert!(self.running, "no lookups once the node is known to be off"); + assert_eq!(max_parallel, 4); + self.searches.lock().unwrap().push(name.to_owned()); + let key = NameKey::new(name).key; + let peers = FakePeers { + owners: self + .peers + .get(&key) + .cloned() + .unwrap_or_default() + .into_iter() + .enumerate() + .collect(), + search_fails: self.failing.contains(&key), + live: Arc::clone(&self.live), + }; + Some(CatalogStream::spawn( + Arc::new(peers), + name.to_owned(), + max_parallel, + self.catalog_timeout, + )) + } + + fn limits(&self) -> NetworkLimits { + self.limits.clone() + } +} + +/// A release title with its tracks: title, content id digit and duration. +type FakeRelease<'a> = (&'a str, &'a [(&'a str, char, Option)]); + +fn catalog(artist: &str, releases: &[FakeRelease<'_>]) -> Reply { + Reply::Catalog(CatalogArtist { + name: artist.into(), + releases: releases + .iter() + .map(|(title, tracks)| CatalogRelease { + title: (*title).into(), + tracks: tracks + .iter() + .map(|(track, digit, duration)| CatalogTrack { + title: (*track).into(), + duration_seconds: *duration, + content_id: Some(b3(*digit)), + item_id: format!("item-{digit}"), + ..Default::default() + }) + .collect(), + ..Default::default() + }) + .collect(), + ..Default::default() + }) +} + +async fn run_with(pool: &PgPool, run_id: i64, federation: Arc) -> String { + let config = AppConfig { + federation_enabled: true, + ..AppConfig::default() + }; + let mut log = JobLog::new(); + job::run_worker_with( + pool, + Arc::new(config), + run_id, + &mut log, + Arc::new(super::providers::ProviderFetchers), + federation, + ) + .await + .unwrap(); + log.output() +} + +async fn create_with_consent( + pool: &PgPool, + key: &str, + tracks: &[ImportedTrack], + consent: bool, +) -> i64 { + let mut new = new_import(1, "spotify", vec![playlist(key, key, tracks)]); + new.federated_search = consent; + store::create_import(pool, &new).await.unwrap() +} + +async fn item_ids(pool: &PgPool, import_id: i64) -> Vec { + sqlx::query_scalar( + "SELECT i.id FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 ORDER BY i.source_position", + ) + .bind(import_id) + .fetch_all(pool) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_searches_peer_catalogues_and_takes_manual_choices() { + let _serial = SERIAL.lock().await; + let fixture = Fixture::new().await; + let pool = &fixture.pool; + // A library artist without tracks makes the duet splittable. + sqlx::raw_sql( + "INSERT INTO furumusic__artist VALUES (10, 'Мумий Тролль', 'мумий тролль', false); + INSERT INTO furumusic__release VALUES (10, 'Local', 2000, false); + INSERT INTO furumusic__media_file VALUES (10, 'local.flac', 'sha-10'); + INSERT INTO furumusic__track VALUES (10, 'Local', 'local', 10, 1, 1, 100.0, 10, false);", + ) + .execute(pool) + .await + .unwrap(); + let mut network = FakeNetwork::new() + .peer( + "Земфира", + vec![ + catalog( + "Земфира", + &[ + ("Прости меня моя любовь", &[("Хочешь?", '1', Some(219.0))]), + ("Земфира", &[("Ариведерчи", '2', Some(230.0))]), + ], + ), + catalog( + "Земфира", + &[ + ("Прости меня моя любовь", &[("Хочешь?", '1', Some(219.0))]), + ("Best of", &[("Ариведерчи", '3', Some(250.0))]), + ], + ), + ], + ) + .peer( + "Slow Peer", + vec![ + catalog("Slow Peer", &[("Album", &[("Track", '4', Some(180.0))])]), + Reply::Hang, + Reply::Fail, + ], + ) + .peer( + "Beyonce", + vec![catalog( + "Beyonce", + &[("I Am... Sasha Fierce", &[("Halo", '5', Some(261.0))])], + )], + ) + .peer( + "Мумий Тролль", + vec![Reply::Catalog(CatalogArtist { + name: "Мумий Тролль".into(), + releases: vec![CatalogRelease { + title: "Точно ртуть алоэ".into(), + tracks: vec![CatalogTrack { + title: "Невеста?".into(), + artists: vec!["Мумий Тролль".into()], + featured_artists: vec!["Земфира".into()], + duration_seconds: Some(240.0), + content_id: Some(b3('6')), + item_id: "item-6".into(), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + })], + ); + network.failing.insert(NameKey::new("Broken Artist").key); + let network = Arc::new(network); + let tracks = [ + timed(0, "Хочешь?", "Земфира", Some("ПММЛ"), Some(219)), + timed(1, "Ариведерчи", "Земфира", None, None), + timed(2, "Несуществующая", "Земфира", None, Some(200)), + timed(3, "Song", "Broken Artist", None, Some(200)), + timed(4, "Track", "Slow Peer", Some("Album"), Some(180)), + timed(5, "Halo", "Beyoncé", None, Some(261)), + timed(6, "Невеста?", "Земфира & Мумий Тролль", None, Some(240)), + ]; + let import_id = create_with_consent(pool, "network", &tracks, true).await; + + let output = run_with(pool, 701, network.clone()).await; + assert!( + output.contains("7 entries locally (0 matched, 0 ambiguous, 0 unmatched, 0 failed, 7 left for the network)"), + "{output}" + ); + assert!( + output.contains("searched the network for 5 artists (5 catalogues, 2 lost); 7 entries: 4 matched, 1 ambiguous, 1 unmatched, 1 failed"), + "{output}" + ); + for private in ["Земфира", "Broken", "Halo", "Beyonc"] { + assert!(!output.contains(private), "{output}"); + } + assert_eq!(fixture.status(import_id).await, "done"); + + let searches = network.searches(); + // The folded spelling follows an unknown original one; a failed search is + // repeated after each backoff step; the duet asks for its parts, and + // the part looked up before comes from the cache. + for (name, count) in [ + ("Beyoncé", 1), + ("beyonce", 1), + ("Broken Artist", 3), + ("Slow Peer", 1), + ("Земфира", 1), + ("Земфира & Мумий Тролль", 1), + ("Мумий Тролль", 1), + ] { + assert_eq!( + searches.iter().filter(|search| *search == name).count(), + count, + "{name}: {searches:?}" + ); + } + assert_eq!(searches.len(), 9, "{searches:?}"); + + let s = |value: &str| Some(value.to_owned()); + let items = resolved_items(pool, import_id).await; + let federated = |digit: char| -> ItemRow { + ( + "matched".into(), + None, + s("federation"), + Some(b3(digit)), + None, + s("0"), + None, + "pending".into(), + ) + }; + let expected: Vec = vec![ + // Two peers offer it; the duration confirms it across albums. + federated('1'), + // Two recordings without a duration to compare: the user chooses. + ( + "ambiguous".into(), + None, + None, + None, + None, + None, + Some(2), + "not_ready".into(), + ), + ( + "unmatched".into(), + s("not_found"), + None, + None, + None, + None, + None, + "not_ready".into(), + ), + // The search kept failing: Resync retries it. + ( + "failed".into(), + s("federation_error"), + None, + None, + None, + None, + None, + "not_ready".into(), + ), + // One peer answered; a late and a refusing peer are counted as lost. + federated('4'), + federated('5'), + federated('6'), + ]; + assert_eq!(items, expected); + let fed: serde_json::Value = sqlx::query_scalar( + "SELECT i.matched_fed FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 AND i.source_position = 0", + ) + .bind(import_id) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!( + fed, + json!({"item_id": "item-1", "owner": "0", "title": "Хочешь?", + "artist_names": ["Земфира"], "featured_artist_names": [], "year": null, + "duration_seconds": 219, "content_id": b3('1'), + "release_title": "Прости меня моя любовь", "track_number": null, + "disc_number": null}) + ); + let statistics = store::get_import(pool, 1, import_id) + .await + .unwrap() + .unwrap() + .summary + .statistics; + assert_eq!(statistics["matched_federation"], 4); + assert_eq!(statistics["catalog_errors"], 2); + assert_eq!(statistics["pending"], 0); + // Dropped and finished lookups leave no request behind. + assert_eq!(network.live.load(Ordering::SeqCst), 0); + + // Manual choice of an ambiguous entry. + let ids = item_ids(pool, import_id).await; + let choose = |user_id: i64, item: i64, index: usize| async move { + store::choose_candidate(pool, user_id, import_id, item, index) + .await + .unwrap() + }; + assert_eq!(choose(2, ids[1], 0).await, ChooseOutcome::NotFound); + assert_eq!(choose(1, ids[0], 0).await, ChooseOutcome::NotAmbiguous); + assert_eq!(choose(1, ids[1], 2).await, ChooseOutcome::InvalidCandidate); + let candidates: serde_json::Value = + sqlx::query_scalar("SELECT candidates FROM furumusic__library_import_item WHERE id = $1") + .bind(ids[1]) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(candidates[1]["origin"], "federation"); + assert_eq!( + choose(1, ids[1], 1).await, + ChooseOutcome::Chosen { + queued: true, + publication: import_model::PublicationStatus::Pending + } + ); + assert_eq!(fixture.status(import_id).await, "queued"); + let chosen: (String, String, Option, String) = sqlx::query_as( + "SELECT match_method, match_origin, matched_content_id, publication_status + FROM furumusic__library_import_item WHERE id = $1", + ) + .bind(ids[1]) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!( + chosen, + ( + "manual".to_owned(), + "federation".to_owned(), + candidates[1]["content_id"].as_str().map(str::to_owned), + "pending".to_owned() + ) + ); + + // Stored candidates are checked again before they are taken. + let mut tampered = candidates.clone(); + tampered[0]["fed"]["owner"] = json!("WEB"); + tampered[1]["content_id"] = json!(b3('9')); + let local_gone = json!([{"origin": "local", "track_id": 404, "content_id": null}]); + for (item, value) in [(ids[2], tampered.clone()), (ids[3], local_gone.clone())] { + sqlx::query( + "UPDATE furumusic__library_import_item SET resolution_status = 'ambiguous', candidates = $2 WHERE id = $1", + ) + .bind(item) + .bind(&value) + .execute(pool) + .await + .unwrap(); + } + assert_eq!(choose(1, ids[2], 0).await, ChooseOutcome::InvalidCandidate); + assert_eq!(choose(1, ids[2], 1).await, ChooseOutcome::InvalidCandidate); + assert_eq!(choose(1, ids[3], 0).await, ChooseOutcome::TrackGone); + // A local candidate without a content id waits for the publisher to hash it. + sqlx::query("UPDATE furumusic__library_import_item SET candidates = $2 WHERE id = $1") + .bind(ids[3]) + .bind(json!([{"origin": "local", "track_id": 10, "content_id": null, "score": 0.5}])) + .execute(pool) + .await + .unwrap(); + assert_eq!( + choose(1, ids[3], 0).await, + ChooseOutcome::Chosen { + queued: false, + publication: import_model::PublicationStatus::NoContentId + } + ); + + // The queued import runs again without searching anything new. + let before = network.searches().len(); + run_with(pool, 702, network.clone()).await; + assert_eq!(fixture.status(import_id).await, "done"); + assert_eq!(network.searches().len(), before); + let items = resolved_items(pool, import_id).await; + assert_eq!(items[1].0, "matched"); + assert_eq!(items[3].7, "no_content_id"); + + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_network_search_needs_consent_a_running_node_and_budget() { + let _serial = SERIAL.lock().await; + let fixture = Fixture::new().await; + let pool = &fixture.pool; + let tracks = [ + timed(0, "Хочешь?", "Земфира", None, Some(219)), + timed(1, "Halo", "Beyonce", None, Some(261)), + ]; + + // Federation enabled, no consent: not a single call to the federation. + let without_consent = create_with_consent(pool, "no-consent", &tracks, false).await; + let output = run_with(pool, 711, Arc::new(NoNetwork)).await; + assert!(output.contains("0 left for the network"), "{output}"); + assert!(!output.contains("searched the network"), "{output}"); + assert_eq!(fixture.status(without_consent).await, "done"); + let items = resolved_items(pool, without_consent).await; + assert!( + items + .iter() + .all(|item| item.0 == "unmatched" && item.1.as_deref() == Some("not_found")) + ); + + // Consent, but the node is not running: no lookups. + let stopped = create_with_consent(pool, "stopped", &tracks, true).await; + let mut network = FakeNetwork::new(); + network.running = false; + let output = run_with(pool, 712, Arc::new(network)).await; + assert!(output.contains("federation is not running"), "{output}"); + let items = resolved_items(pool, stopped).await; + assert!( + items.iter().all( + |item| item.0 == "unmatched" && item.1.as_deref() == Some("federation_unavailable") + ) + ); + + // One artist group per pass: the other one is left over. + let budget = create_with_consent(pool, "budget", &tracks, true).await; + let mut network = FakeNetwork::new().peer( + "Beyonce", + vec![catalog( + "Beyonce", + &[("I Am... Sasha Fierce", &[("Halo", '5', Some(261.0))])], + )], + ); + network.limits.max_groups = 1; + let network = Arc::new(network); + let output = run_with(pool, 713, network.clone()).await; + assert!(output.contains("stopped (federation_budget)"), "{output}"); + assert_eq!(network.searches(), ["Beyonce"]); + let items = resolved_items(pool, budget).await; + assert_eq!( + (items[0].0.as_str(), items[0].1.as_deref()), + ("unmatched", Some("federation_budget")) + ); + assert_eq!( + (items[1].0.as_str(), items[1].3.clone()), + ("matched", Some(b3('5'))) + ); + + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_cancel_stops_a_running_network_search() { + let _serial = SERIAL.lock().await; + let fixture = Fixture::new().await; + let pool = fixture.pool.clone(); + let import_id = create_with_consent( + &pool, + "hanging", + &[timed(0, "Хочешь?", "Земфира", None, Some(219))], + true, + ) + .await; + let mut network = FakeNetwork::new().peer("Земфира", vec![Reply::Hang; 6]); + network.catalog_timeout = Duration::from_secs(600); + let network = Arc::new(network); + let worker = tokio::spawn({ + let pool = pool.clone(); + let network: Arc = network.clone(); + async move { run_with(&pool, 721, network).await } + }); + for _ in 0..250 { + if network.live.load(Ordering::SeqCst) == 4 { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + // Four catalogue requests at a time, out of six owners. + assert_eq!(network.live.load(Ordering::SeqCst), 4); + assert_eq!( + store::request_cancel(&pool, 1, import_id).await.unwrap(), + CancelOutcome::Requested + ); + let output = tokio::time::timeout(Duration::from_secs(5), worker) + .await + .expect("the worker stops within a few polls") + .unwrap(); + assert!(output.contains("cancelled"), "{output}"); + assert_eq!(fixture.status(import_id).await, "cancelled"); + for _ in 0..50 { + if network.live.load(Ordering::SeqCst) == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!(network.live.load(Ordering::SeqCst), 0); + fixture.drop().await; +}