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
+234
-2
@@ -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<i64> = 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<bool> {
|
||||
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<i64> = 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<String>,
|
||||
pub metadata: Value,
|
||||
/// Set by stages 1–2 on an entry that waits for the network stage.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
/// Pending entries of an import, grouped by their main artist.
|
||||
pub async fn pending_entries(pool: &PgPool, import_id: i64) -> sqlx::Result<Vec<PendingEntry>> {
|
||||
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<Vec<
|
||||
id: row.get(0),
|
||||
artist_key: row.get(1),
|
||||
metadata: row.get(2),
|
||||
note: row.get(3),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -921,6 +993,45 @@ pub async fn store_resolutions(
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Ends the wait of entries that stages 1–2 left pending for the network
|
||||
/// stage: they become unmatched with `note`, or keep their own reason without
|
||||
/// one. `false` when the worker no longer owns the import.
|
||||
pub async fn finish_deferred(
|
||||
pool: &PgPool,
|
||||
import_id: i64,
|
||||
run_id: i64,
|
||||
note: Option<&str>,
|
||||
) -> sqlx::Result<bool> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let owned: Option<i64> = 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<ChooseOutcome> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let status: Option<String> = 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<Value> = 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::<ImportStatus>(),
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user