forked from Furumi/furumi-web
Search peer artist catalogues for unmatched import entries
With the user's consent and federation enabled, entries that the local
library and known federated tracks do not match wait for resolver stage 3.
It looks up each artist group by its original name, its spelling without
Latin diacritics and, if those find nothing, its collaboration parts, and
decides the entries against the federated tracks of the catalogues.
The new artist_catalogs_bounded in the federation client asks at most 16
owners, a given number at a time, in a JoinSet owned by one task; dropping
the stream aborts the search and every catalogue request. The player's
stream_artist_catalogs keeps its behaviour and shares the owner parsing.
Imports search two groups at a time process-wide, give a group 60 s, retry
failed searches after 2/4/8 s, stop after 500 groups or 30 minutes per pass
and cancel running lookups on cancellation or lease loss. Lost catalogues
are counted in the statistics.
POST /api/imports/{id}/items/{item_id}/match takes a stored candidate of
an ambiguous entry for its owner after checking it again, and queues a
finished import so that the choice is published.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0a258a3e05
commit
f10e384650
11 files changed
+2378
-71
No files matched your search
+188
-21
@@ -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<CatalogStream> {
|
||||
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<music_dht::EndpointId, String> {
|
||||
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<Vec<(Self::Owner, String)>>;
|
||||
|
||||
async fn catalog(
|
||||
&self,
|
||||
owner: Self::Owner,
|
||||
name: String,
|
||||
) -> Result<music_dht::catalog::CatalogArtist>;
|
||||
}
|
||||
|
||||
/// 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<CatalogResult>,
|
||||
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<P: CatalogPeers>(
|
||||
peers: std::sync::Arc<P>,
|
||||
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<CatalogResult> {
|
||||
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<music_dht::MusicDhtService>);
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl CatalogPeers for DhtCatalogPeers {
|
||||
type Owner = music_dht::EndpointId;
|
||||
|
||||
async fn owners(&self, name: &str) -> Result<Vec<(Self::Owner, String)>> {
|
||||
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<music_dht::catalog::CatalogArtist> {
|
||||
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<music_dht::catalog::CatalogArtist> {
|
||||
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!(
|
||||
|
||||
Reference in new issue
Block a user