diff --git a/docs/development.md b/docs/development.md index 146567e..ae71e64 100644 --- a/docs/development.md +++ b/docs/development.md @@ -146,3 +146,15 @@ migrated instance with the import agent disabled at `FURU_TEST_URL` (default `furumi-import-playlist-test-pg` with database `furumi_import_test`, and Playwright and Chrome configured as above. It uses a local torrent preview fixture and simulated imported tracks, without downloading external torrents. + +## Library import tests + +```bash +cargo test library_import +# Disposable PostgreSQL with ICU support; each test creates and drops a unique schema. +FURU_LIBRARY_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test library_import -- --include-ignored +``` + +The database tests cover per-user isolation, repeated source playlists, exclusive +claims, lease ownership, cancellation, history deletion that keeps target playlists, +and resumption after a worker stops without a server restart once its lease expires. diff --git a/src/admin/mod.rs b/src/admin/mod.rs index 6c24bfa..c91e553 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -951,6 +951,9 @@ impl App for AdminApp { all.extend(cot::db::migrations::wrap_migrations( crate::youtube::db_migrations::MIGRATIONS, )); + all.extend(cot::db::migrations::wrap_migrations( + crate::library_import::db_migrations::MIGRATIONS, + )); all } } diff --git a/src/library_import/adapters/mod.rs b/src/library_import/adapters/mod.rs new file mode 100644 index 0000000..52960a9 --- /dev/null +++ b/src/library_import/adapters/mod.rs @@ -0,0 +1,68 @@ +//! File adapters convert exported provider data into [`ImportedLibrary`]. +//! +//! Adapters are pure: they receive file names and bytes and never touch the +//! database or the network. + +use std::fmt; + +use super::model::{ImportedLibrary, ProviderInfo, SourceType}; + +/// One uploaded file. Raw files are parsed in memory and never stored. +#[derive(Debug, Clone)] +pub struct InputFile { + pub name: String, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AdapterError { + /// None of the files belongs to this provider's export. + NoSupportedFiles, + /// A recognised file could not be parsed. The message never contains file contents. + Invalid { file: String, reason: String }, +} + +impl fmt::Display for AdapterError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoSupportedFiles => f.write_str("no supported files in the upload"), + Self::Invalid { file, reason } => write!(f, "{file}: {reason}"), + } + } +} + +impl std::error::Error for AdapterError {} + +pub trait FileAdapter: Send + Sync { + /// Provider id stored in `furumusic__library_import.provider`. + fn provider(&self) -> &'static str; + /// Name shown in the import wizard. + fn display_name(&self) -> &'static str; + /// Whether a file name belongs to this provider's export. + fn accepts(&self, file_name: &str) -> bool; + fn parse(&self, files: &[InputFile]) -> Result; +} + +/// File adapters available on this instance. +pub fn file_adapters() -> &'static [&'static dyn FileAdapter] { + &[] +} + +pub fn file_adapter(provider: &str) -> Option<&'static dyn FileAdapter> { + file_adapters() + .iter() + .copied() + .find(|adapter| adapter.provider() == provider) +} + +/// Providers with a file import path. API methods are added by provider integrations. +pub fn file_providers() -> Vec { + file_adapters() + .iter() + .map(|adapter| ProviderInfo { + id: adapter.provider(), + name: adapter.display_name(), + methods: vec![SourceType::File], + }) + .collect() +} diff --git a/src/library_import/handlers.rs b/src/library_import/handlers.rs new file mode 100644 index 0000000..ba32282 --- /dev/null +++ b/src/library_import/handlers.rs @@ -0,0 +1,357 @@ +//! HTTP API under `/api/imports`. Every request is scoped to the signed-in +//! user; another user's import answers 404. + +use std::sync::Arc; + +use cot::db::Database; +use cot::http::StatusCode; +use cot::json::Json; +use cot::request::extractors::{Path, UrlQuery}; +use cot::response::IntoResponse; +use cot::router::method::{get, post}; +use cot::router::{Route, Router}; +use cot::session::Session; +use cot::{App, Body}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use sqlx::PgPool; +use tokio::sync::OnceCell; + +use super::adapters; +use super::model::{ItemCursor, ProviderInfo}; +use super::store::{self, CancelOutcome, DeleteOutcome, ItemFilter}; +use crate::auth; +use crate::config::AppConfig; + +type Response = cot::Result; + +fn error(status: StatusCode, message: &str) -> Response { + Ok(cot::http::Response::builder() + .status(status) + .header("Content-Type", "application/json") + .header("Cache-Control", "private, no-store") + .body(Body::fixed(json!({ "error": message }).to_string())) + .expect("valid response")) +} + +fn ok(value: T) -> Response { + let mut response = Json(value).into_response()?; + response + .headers_mut() + .insert("Cache-Control", "private, no-store".parse().unwrap()); + Ok(response) +} + +fn not_found() -> Response { + error(StatusCode::NOT_FOUND, "import not found") +} + +/// Storage errors are logged without request data; the response stays generic. +fn storage_error(failure: &sqlx::Error) -> Response { + tracing::warn!(error = %failure, "library import storage operation failed"); + error( + StatusCode::INTERNAL_SERVER_ERROR, + "Import storage operation failed; try again", + ) +} + +#[derive(Deserialize)] +struct ImportPath { + id: String, +} + +fn import_id(path: &ImportPath) -> Option { + path.id.parse::().ok().filter(|id| *id > 0) +} + +#[derive(Default, Deserialize)] +struct ItemsQuery { + status: Option, + publication: Option, + playlist: Option, + q: Option, + after: Option, + limit: Option, +} + +impl ItemsQuery { + fn filter(self) -> Result { + let blank = |value: Option| value.filter(|value| !value.trim().is_empty()); + let resolution = blank(self.status) + .map(|value| value.parse()) + .transpose() + .map_err(|_| "unknown entry status")?; + let publication = blank(self.publication) + .map(|value| value.parse()) + .transpose() + .map_err(|_| "unknown publication status")?; + let after = blank(self.after) + .map(|value| ItemCursor::parse(&value).ok_or("invalid page cursor")) + .transpose()?; + let query = blank(self.q); + if query.as_ref().is_some_and(|query| query.len() > 200) { + return Err("search is limited to 200 characters"); + } + Ok(ItemFilter { + resolution, + publication, + playlist: self.playlist, + query, + after, + limit: self.limit, + }) + } +} + +#[derive(Serialize)] +struct Providers { + providers: Vec, + /// Whether federated search can be offered in the wizard. + federated_search_available: bool, +} + +fn providers(config: &AppConfig) -> Providers { + Providers { + providers: adapters::file_providers(), + federated_search_available: config.federation_enabled, + } +} + +#[derive(Clone)] +struct Services { + pool: Arc>, + config: Arc, +} + +impl Services { + async fn pool(&self) -> cot::Result { + self.pool + .get_or_try_init(|| async { + sqlx::postgres::PgPoolOptions::new() + .max_connections(5) + .connect(&self.config.database_url) + .await + }) + .await + .cloned() + .map_err(|err| cot::Error::internal(err.to_string())) + } +} + +pub struct ImportApp { + config: Arc, +} + +impl ImportApp { + pub fn new(config: Arc) -> Self { + Self { config } + } +} + +macro_rules! require_user { + ($auth:expr, $session:expr, $db:expr) => { + match auth::get_request_user(&$auth, &$session, &$db).await { + Some(user) => user, + None => return error(StatusCode::UNAUTHORIZED, "not authenticated"), + } + }; +} + +impl App for ImportApp { + fn name(&self) -> &'static str { + "library_import" + } + + fn router(&self) -> Router { + let services = Services { + pool: Arc::new(OnceCell::new()), + config: Arc::clone(&self.config), + }; + let list = { + let services = services.clone(); + get( + move |auth_ctx: auth::AuthContext, session: Session, db: Database| { + let services = services.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + match store::list_imports(&services.pool().await?, user.id).await { + Ok(imports) => ok(json!({ "imports": imports })), + Err(error) => storage_error(&error), + } + } + }, + ) + }; + let provider_list = get( + move |auth_ctx: auth::AuthContext, session: Session, db: Database| async move { + require_user!(auth_ctx, session, db); + let (config, _) = AppConfig::load_with_db(&db).await; + ok(providers(&config)) + }, + ); + let detail = { + let read = services.clone(); + let remove = services.clone(); + get( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path| { + let services = read.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + let Some(id) = import_id(&path) else { + return not_found(); + }; + match store::get_import(&services.pool().await?, user.id, id).await { + Ok(Some(detail)) => ok(detail), + Ok(None) => not_found(), + Err(error) => storage_error(&error), + } + } + }, + ) + .delete( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path| { + let services = remove.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + let Some(id) = import_id(&path) else { + return not_found(); + }; + match store::delete_import(&services.pool().await?, user.id, id).await { + Ok(DeleteOutcome::Deleted) => ok(json!({ "ok": true })), + Ok(DeleteOutcome::Active) => error( + StatusCode::CONFLICT, + "the import is still running; cancel it first", + ), + Ok(DeleteOutcome::NotFound) => not_found(), + Err(error) => storage_error(&error), + } + } + }, + ) + }; + let items = { + let services = services.clone(); + get( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path, + UrlQuery(query): UrlQuery| { + let services = services.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + let Some(id) = import_id(&path) else { + return not_found(); + }; + let filter = match query.filter() { + Ok(filter) => filter, + Err(message) => return error(StatusCode::BAD_REQUEST, message), + }; + match store::list_items(&services.pool().await?, user.id, id, &filter).await + { + Ok(Some(page)) => ok(page), + Ok(None) => not_found(), + Err(error) => storage_error(&error), + } + } + }, + ) + }; + let cancel = post( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path| { + let services = services.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + let Some(id) = import_id(&path) else { + return not_found(); + }; + match store::request_cancel(&services.pool().await?, user.id, id).await { + Ok(CancelOutcome::Cancelled) => ok(json!({ "status": "cancelled" })), + Ok(CancelOutcome::Requested) => ok(json!({ "status": "cancelling" })), + Ok(CancelOutcome::NotActive) => { + error(StatusCode::CONFLICT, "the import has already finished") + } + Ok(CancelOutcome::NotFound) => not_found(), + Err(error) => storage_error(&error), + } + } + }, + ); + // Static paths come before `/{id}`. + Router::with_urls([ + Route::with_handler_and_name("", list, "library_imports"), + Route::with_handler_and_name("/providers", provider_list, "library_import_providers"), + 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"), + ]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn query(pairs: &[(&str, &str)]) -> ItemsQuery { + let mut query = ItemsQuery::default(); + for (key, value) in pairs { + let value = Some((*value).to_owned()); + match *key { + "status" => query.status = value, + "publication" => query.publication = value, + "after" => query.after = value, + "q" => query.q = value, + _ => unreachable!(), + } + } + query + } + + #[test] + fn item_filters_are_validated() { + let filter = query(&[("status", "ambiguous"), ("after", "1.20"), ("q", " ")]) + .filter() + .unwrap(); + assert_eq!( + filter.resolution, + Some(crate::library_import::model::ResolutionStatus::Ambiguous) + ); + assert_eq!( + filter.after, + Some(ItemCursor { + ordinal: 1, + position: 20 + }) + ); + assert!(filter.query.is_none()); + assert!(query(&[("status", "published")]).filter().is_err()); + assert!( + query(&[("publication", "deferred_sync_limit")]) + .filter() + .is_ok() + ); + assert!(query(&[("after", "x")]).filter().is_err()); + assert!(query(&[("q", &"a".repeat(201))]).filter().is_err()); + } + + #[test] + fn import_ids_must_be_positive_integers() { + for (value, expected) in [("12", Some(12)), ("0", None), ("-3", None), ("x", None)] { + assert_eq!( + import_id(&ImportPath { + id: value.to_owned() + }), + expected + ); + } + } +} diff --git a/src/library_import/job.rs b/src/library_import/job.rs new file mode 100644 index 0000000..cf071b4 --- /dev/null +++ b/src/library_import/job.rs @@ -0,0 +1,346 @@ +//! `library_import` background job: claims imports stored in PostgreSQL and +//! runs their phases under a renewable lease. +//! +//! Work is durable: the phase and every entry state live in PostgreSQL, so an +//! interrupted import resumes from its stored phase. A worker that dies +//! without a server restart stops renewing its lease; the sweeper notices the +//! expired lease and starts a new worker, which takes the import over. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use anyhow::Result; +use sqlx::PgPool; + +use super::model::Phase; +use super::store::{self, ClaimedImport, Control, FinishOutcome}; +use crate::config::AppConfig; +use crate::scheduler::{Job, JobContext, JobLog, SchedulerHandle}; + +pub const JOB_NAME: &str = "library_import"; +/// Lease length. Renewed every [`HEARTBEAT`], so a live worker never loses it. +pub const LEASE: Duration = Duration::from_secs(120); +const HEARTBEAT: Duration = Duration::from_secs(30); +/// How often the sweeper looks for imports without a live worker. +const SWEEP_INTERVAL: Duration = Duration::from_secs(30); +/// Workers per process. More triggers return at once; queued imports are +/// taken by running workers or by the next sweep. +const MAX_WORKERS: usize = 2; + +static ACTIVE_WORKERS: AtomicUsize = AtomicUsize::new(0); + +/// A worker slot, released on return and on panic. +struct WorkerSlot; + +impl WorkerSlot { + fn acquire() -> Option { + let slot = Self; + // Dropping the slot gives the increment back when the limit is reached. + (ACTIVE_WORKERS.fetch_add(1, Ordering::AcqRel) < MAX_WORKERS).then_some(slot) + } +} + +impl Drop for WorkerSlot { + fn drop(&mut self) { + ACTIVE_WORKERS.fetch_sub(1, Ordering::AcqRel); + } +} + +pub struct LibraryImportJob; + +#[async_trait::async_trait] +impl Job for LibraryImportJob { + fn name(&self) -> &'static str { + JOB_NAME + } + + fn description(&self) -> &'static str { + "Match imported music libraries and publish them as playlists" + } + + fn default_cron(&self) -> &'static str { + "" + } + + async fn run(&self, ctx: &JobContext, log: &mut JobLog) -> Result<()> { + run_worker(&ctx.pool, Arc::clone(&ctx.config), ctx.run_id, log).await + } +} + +/// Processes claimable imports until none is left. +pub async fn run_worker( + pool: &PgPool, + config: Arc, + run_id: i64, + log: &mut JobLog, +) -> Result<()> { + let Some(_slot) = WorkerSlot::acquire() else { + log.info("Library import workers are busy; queued imports will be taken by them"); + return Ok(()); + }; + let worker = Worker { + pool: pool.clone(), + config, + run_id, + }; + let mut processed = 0usize; + while let Some(import) = store::claim_next(pool, run_id, LEASE).await? { + processed += 1; + log.info(&format!( + "Library import {}: claimed (phase {})", + import.id, + import.phase.map_or("start", Phase::as_str) + )); + worker.process(&import, log).await?; + } + if processed == 0 { + log.info("No library imports waiting"); + } + Ok(()) +} + +struct Worker { + pool: PgPool, + config: Arc, + run_id: i64, +} + +/// Renews the lease in the background while the worker owns an import. +struct Heartbeat { + task: tokio::task::JoinHandle<()>, + lost: Arc, +} + +impl Heartbeat { + fn start(pool: PgPool, import_id: i64, run_id: i64) -> Self { + let lost = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&lost); + let task = tokio::spawn(async move { + let mut interval = tokio::time::interval(HEARTBEAT); + interval.tick().await; + loop { + interval.tick().await; + match store::renew_lease(&pool, import_id, run_id, LEASE).await { + Ok(true) => {} + Ok(false) => { + flag.store(true, Ordering::Release); + return; + } + // A temporary database error is retried; the lease covers several beats. + Err(error) => { + tracing::warn!(import_id, %error, "library import lease renewal failed") + } + } + } + }); + Self { task, lost } + } + + fn lost(&self) -> bool { + self.lost.load(Ordering::Acquire) + } +} + +impl Drop for Heartbeat { + fn drop(&mut self) { + self.task.abort(); + } +} + +enum Stop { + Cancelled, + LeaseLost, +} + +impl Worker { + async fn process(&self, import: &ClaimedImport, log: &mut JobLog) -> Result<()> { + let heartbeat = Heartbeat::start(self.pool.clone(), import.id, self.run_id); + if !store::open_attempt(&self.pool, import.id, self.run_id).await? { + log.warn(&format!( + "Library import {}: lease lost before start", + import.id + )); + return Ok(()); + } + let mut resume_from = import.phase; + loop { + match self.run_phases(import, resume_from, &heartbeat, log).await { + Ok(None) => {} + Ok(Some(Stop::Cancelled)) => { + if store::cancel_by_worker(&self.pool, import.id, self.run_id).await? { + log.info(&format!("Library import {}: cancelled", import.id)); + } + return Ok(()); + } + Ok(Some(Stop::LeaseLost)) => { + log.warn(&format!( + "Library import {}: lease lost; another worker continues", + import.id + )); + return Ok(()); + } + Err(error) => { + tracing::warn!(import_id = import.id, %error, "library import phase failed"); + if store::fail( + &self.pool, + import.id, + self.run_id, + "Import processing failed; retry unmatched to continue", + ) + .await? + { + log.error(&format!("Library import {}: failed", import.id)); + } + return Ok(()); + } + } + match store::finish(&self.pool, import.id, self.run_id).await? { + FinishOutcome::Done(statistics) => { + log.info(&format!( + "Library import {}: done ({} entries, {} matched, {} published)", + import.id, + statistics.total, + statistics.matched(), + statistics.published + )); + return Ok(()); + } + FinishOutcome::Rerun => { + log.info(&format!( + "Library import {}: changed; running again", + import.id + )); + resume_from = None; + } + FinishOutcome::LeaseLost => { + log.warn(&format!("Library import {}: lease lost", import.id)); + return Ok(()); + } + } + } + } + + /// Runs the phases left after `resume_from`. Cancellation and lease loss + /// are checked before every phase; later stages check them inside phases too. + async fn run_phases( + &self, + import: &ClaimedImport, + resume_from: Option, + heartbeat: &Heartbeat, + log: &mut JobLog, + ) -> Result> { + for &phase in Phase::remaining(import.source_type, resume_from) { + 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 !store::set_phase(&self.pool, import.id, self.run_id, phase).await? { + return Ok(Some(Stop::LeaseLost)); + } + match phase { + Phase::Fetching => self.fetch(import, log).await?, + Phase::ResolveLocal => self.resolve_local(import, log).await?, + Phase::ResolveFederation => self.resolve_federation(import, log).await?, + Phase::Publish => self.publish(import, log).await?, + } + store::refresh_statistics(&mut *self.pool.acquire().await?, import.id).await?; + } + Ok(None) + } + + /// API imports fetch the selected playlists here (provider integrations). + async fn fetch(&self, _import: &ClaimedImport, _log: &mut JobLog) -> Result<()> { + Ok(()) + } + + /// Matches pending entries against the local library (resolver stage 1–2). + async fn resolve_local(&self, _import: &ClaimedImport, _log: &mut JobLog) -> Result<()> { + Ok(()) + } + + /// Searches artist catalogues on the network, only with the user's consent + /// and a running federation. + async fn resolve_federation(&self, import: &ClaimedImport, log: &mut JobLog) -> Result<()> { + if import.federated_search && !self.config.federation_enabled { + log.info(&format!( + "Library import {}: federation is disabled; network search skipped", + import.id + )); + } + Ok(()) + } + + /// Adds matched entries to the target playlists. + async fn publish(&self, _import: &ClaimedImport, _log: &mut JobLog) -> Result<()> { + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Boot hook and sweeper +// --------------------------------------------------------------------------- + +/// Whether the sweeper should start a worker: an import waits for one (queued, +/// or running under an expired lease) and this process has a free worker slot. +pub async fn needs_worker(pool: &PgPool) -> sqlx::Result { + if ACTIVE_WORKERS.load(Ordering::Acquire) >= MAX_WORKERS { + return Ok(false); + } + store::has_claimable(pool).await +} + +/// Requeues imports of the previous process, then starts a worker whenever an +/// import waits without one. Runs for the lifetime of the server. +pub fn spawn_boot( + config: Arc, + scheduler: Arc>>, +) { + if config.database_url.is_empty() { + return; + } + tokio::spawn(async move { + // The scheduler marks runs of the previous process failed before it is published. + let handle = loop { + if let Some(handle) = scheduler.get() { + break Arc::clone(handle); + } + tokio::time::sleep(Duration::from_secs(1)).await; + }; + let pool = match sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_lazy(&config.database_url) + { + Ok(pool) => pool, + Err(error) => { + tracing::error!(%error, "library import sweeper could not configure its pool"); + return; + } + }; + match store::requeue_orphaned(&pool).await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "requeued interrupted library imports"), + Err(error) => tracing::warn!(%error, "failed to requeue interrupted library imports"), + } + let mut interval = tokio::time::interval(SWEEP_INTERVAL); + loop { + interval.tick().await; + match needs_worker(&pool).await { + Ok(true) => { + if let Err(error) = Arc::clone(&handle) + .trigger_job_now_background(JOB_NAME) + .await + { + tracing::warn!(%error, "failed to start a library import worker"); + } + } + Ok(false) => {} + Err(error) => tracing::warn!(%error, "library import sweep failed"), + } + } + }); +} diff --git a/src/library_import/mod.rs b/src/library_import/mod.rs new file mode 100644 index 0000000..631e665 --- /dev/null +++ b/src/library_import/mod.rs @@ -0,0 +1,55 @@ +//! Music library import: provider exports are stored as durable imports, +//! matched against the library and the federation, and published as ordinary +//! private playlists. +//! +//! The subsystem owns the `furumusic__library_import*` tables. It touches the +//! rest of Furumi only when publishing: target playlists, their tracks and the +//! existing Device Sync operations. + +// Imports are created by the provider integrations and processed by the +// resolver and publisher; until those are wired in, parts of the model and +// the creation path are used by the tests only. +#[allow(dead_code)] +pub mod adapters; +mod handlers; +pub mod job; +#[allow(dead_code)] +pub mod model; +#[allow(dead_code)] +pub mod store; + +#[cfg(test)] +mod tests; + +pub use handlers::ImportApp; +pub use job::LibraryImportJob; + +pub mod db_migrations { + use cot::db::migrations::{self, Operation, SyncDynMigration}; + + #[cot::db::migrations::migration_op] + async fn create_library_import(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> { + for statement in include_str!("schema.sql").split(';') { + if !statement.trim().is_empty() { + ctx.db.raw(statement).await?; + } + } + Ok(()) + } + + #[derive(Debug, Copy, Clone)] + pub struct M0065CreateLibraryImport; + impl migrations::Migration for M0065CreateLibraryImport { + const APP_NAME: &'static str = "furumusic"; + const MIGRATION_NAME: &'static str = "m_0065_create_library_import"; + const DEPENDENCIES: &'static [migrations::MigrationDependency] = + &[migrations::MigrationDependency::migration( + "furumusic", + "m_0064_review_dismissals", + )]; + const OPERATIONS: &'static [Operation] = + &[Operation::custom(create_library_import).build()]; + } + + pub const MIGRATIONS: &[&SyncDynMigration] = &[&M0065CreateLibraryImport]; +} diff --git a/src/library_import/model.rs b/src/library_import/model.rs new file mode 100644 index 0000000..6a073a1 --- /dev/null +++ b/src/library_import/model.rs @@ -0,0 +1,539 @@ +//! Provider-neutral import model, statuses and API views. +//! +//! This module is pure: it does not depend on the database, the web framework +//! or the async runtime. + +use std::fmt; +use std::str::FromStr; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// A provider library converted by an adapter. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ImportedLibrary { + pub provider: String, + pub account_ref: Option, + pub playlists: Vec, + pub favorites: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ImportedPlaylist { + pub kind: PlaylistKind, + pub source_id: Option, + pub title: String, + pub description: Option, + pub tracks: Vec, +} + +/// One source entry. Entries without usable metadata are kept as unsupported; +/// order and repeats come from the source. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ImportedTrack { + pub kind: TrackKind, + pub source_id: Option, + pub position: u32, + pub title: String, + pub artists: Vec, + pub album: Option, + pub duration_ms: Option, + pub isrc: Option, + pub version_hint: Option, +} + +impl ImportedTrack { + /// The initial resolution of a stored entry and the reason it cannot be matched. + pub fn initial_resolution(&self) -> (ResolutionStatus, Option<&'static str>) { + match self.kind { + TrackKind::Track if self.title.trim().is_empty() => { + (ResolutionStatus::Unsupported, Some("missing_title")) + } + TrackKind::Track => (ResolutionStatus::Pending, None), + TrackKind::Episode => (ResolutionStatus::Unsupported, Some("episode")), + TrackKind::LocalFile => (ResolutionStatus::Unsupported, Some("local_file")), + TrackKind::Unknown => (ResolutionStatus::Unsupported, Some("unknown_kind")), + } + } + + /// Metadata stored in `furumusic__library_import_item.metadata`. Source ids + /// and positions have their own columns. + pub fn metadata(&self) -> ItemMetadata { + ItemMetadata { + kind: self.kind, + title: self.title.clone(), + artists: self.artists.clone(), + album: self.album.clone(), + duration_ms: self.duration_ms, + isrc: self.isrc.clone(), + version_hint: self.version_hint.clone(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ItemMetadata { + pub kind: TrackKind, + #[serde(default)] + pub title: String, + #[serde(default)] + pub artists: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub album: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub isrc: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version_hint: Option, +} + +macro_rules! text_enum { + ($(#[$meta:meta])* $name:ident { $($(#[$variant_meta:meta])* $variant:ident => $text:literal),+ $(,)? }) => { + $(#[$meta])* + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] + pub enum $name { + $($(#[$variant_meta])* #[serde(rename = $text)] $variant),+ + } + + impl $name { + pub const ALL: &'static [Self] = &[$(Self::$variant),+]; + + pub fn as_str(self) -> &'static str { + match self { + $(Self::$variant => $text),+ + } + } + } + + impl FromStr for $name { + type Err = UnknownValue; + + fn from_str(value: &str) -> Result { + match value { + $($text => Ok(Self::$variant),)+ + _ => Err(UnknownValue), + } + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } + } + }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UnknownValue; + +impl fmt::Display for UnknownValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("unknown value") + } +} + +text_enum!( + #[derive(Default)] + TrackKind { + #[default] + Track => "track", + Episode => "episode", + LocalFile => "local_file", + Unknown => "unknown", +}); + +text_enum!( + #[derive(Default)] + PlaylistKind { + #[default] + Playlist => "playlist", + Favorites => "favorites", +}); + +text_enum!(SourceType { + File => "file", + Api => "api", +}); + +text_enum!( + /// Lifecycle of an import as a whole. + ImportStatus { + Queued => "queued", + Running => "running", + Done => "done", + Cancelled => "cancelled", + Failed => "failed", + NeedsReauth => "needs_reauth", + } +); + +impl ImportStatus { + /// A worker owns or will own the import; history cannot be deleted. + pub fn is_active(self) -> bool { + matches!(self, Self::Queued | Self::Running) + } +} + +text_enum!( + /// Durable worker phases. A resumed import continues from the stored phase. + Phase { + Fetching => "fetching", + ResolveLocal => "resolve_local", + ResolveFederation => "resolve_federation", + Publish => "publish", + } +); + +impl Phase { + /// Phases for a source type. Only API imports fetch entries in the worker. + pub fn sequence(source_type: SourceType) -> &'static [Phase] { + match source_type { + SourceType::Api => &[ + Phase::Fetching, + Phase::ResolveLocal, + Phase::ResolveFederation, + Phase::Publish, + ], + SourceType::File => &[ + Phase::ResolveLocal, + Phase::ResolveFederation, + Phase::Publish, + ], + } + } + + /// Phases left to run, starting at the stored phase when it belongs to the sequence. + pub fn remaining(source_type: SourceType, stored: Option) -> &'static [Phase] { + let sequence = Self::sequence(source_type); + let start = stored + .and_then(|phase| sequence.iter().position(|candidate| *candidate == phase)) + .unwrap_or(0); + &sequence[start..] + } +} + +text_enum!(ResolutionStatus { + Pending => "pending", + Matched => "matched", + Ambiguous => "ambiguous", + Unmatched => "unmatched", + Unsupported => "unsupported", + Failed => "failed", +}); + +text_enum!(PublicationStatus { + NotReady => "not_ready", + Pending => "pending", + Published => "published", + Duplicate => "duplicate", + AlreadyPresent => "already_present", + NoContentId => "no_content_id", + DeferredSyncLimit => "deferred_sync_limit", + Paused => "paused", + Failed => "failed", +}); + +text_enum!(AttemptKind { + Initial => "initial", + Resync => "resync", + Publish => "publish", +}); + +text_enum!(AttemptStatus { + Running => "running", + Done => "done", + Cancelled => "cancelled", + Failed => "failed", +}); + +/// Counters cached on the import and its attempts. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ImportStatistics { + pub total: i64, + pub pending: i64, + pub matched_local: i64, + pub matched_federation: i64, + pub ambiguous: i64, + pub unmatched: i64, + pub unsupported: i64, + pub failed: i64, + pub published: i64, + pub publication_pending: i64, + pub duplicate: i64, + pub already_present: i64, + pub no_content_id: i64, + pub deferred_sync_limit: i64, + pub paused: i64, + pub publication_failed: i64, +} + +impl ImportStatistics { + /// Adds `count` entries with the given resolution, origin and publication state. + pub fn add( + &mut self, + resolution: Option, + origin: Option<&str>, + publication: Option, + count: i64, + ) { + self.total += count; + match resolution { + Some(ResolutionStatus::Pending) | None => self.pending += count, + Some(ResolutionStatus::Matched) if origin == Some("federation") => { + self.matched_federation += count + } + Some(ResolutionStatus::Matched) => self.matched_local += count, + Some(ResolutionStatus::Ambiguous) => self.ambiguous += count, + Some(ResolutionStatus::Unmatched) => self.unmatched += count, + Some(ResolutionStatus::Unsupported) => self.unsupported += count, + Some(ResolutionStatus::Failed) => self.failed += count, + } + match publication { + Some(PublicationStatus::Published) => self.published += count, + Some(PublicationStatus::Pending) => self.publication_pending += count, + Some(PublicationStatus::Duplicate) => self.duplicate += count, + Some(PublicationStatus::AlreadyPresent) => self.already_present += count, + Some(PublicationStatus::NoContentId) => self.no_content_id += count, + Some(PublicationStatus::DeferredSyncLimit) => self.deferred_sync_limit += count, + Some(PublicationStatus::Paused) => self.paused += count, + Some(PublicationStatus::Failed) => self.publication_failed += count, + Some(PublicationStatus::NotReady) | None => {} + } + } + + pub fn matched(&self) -> i64 { + self.matched_local + self.matched_federation + } +} + +/// A source offered by `GET /api/imports/providers`. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProviderInfo { + pub id: &'static str, + pub name: &'static str, + pub methods: Vec, +} + +/// One import in the history list. +#[derive(Debug, Clone, Serialize)] +pub struct ImportSummary { + pub id: i64, + pub provider: String, + pub source_type: String, + pub status: String, + pub phase: Option, + pub federated_search: bool, + pub cancel_requested: bool, + pub statistics: Value, + pub error: Option, + pub created_at: DateTime, + pub updated_at: DateTime, + pub last_resync_at: Option>, + pub playlists: Vec, +} + +/// A target playlist link shown in the history list. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PlaylistLink { + pub id: i64, + pub title: String, + pub target_playlist_id: Option, + pub target_deleted: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ImportDetail { + #[serde(flatten)] + pub summary: ImportSummary, + pub source_playlists: Vec, + pub attempt: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PlaylistView { + pub id: i64, + pub kind: String, + pub ordinal: i32, + pub title: String, + pub description: Option, + pub target_playlist_id: Option, + pub target_created_at: Option>, + pub target_deleted: bool, + pub publication_paused: bool, + pub total: i64, + pub matched: i64, + pub published: i64, +} + +#[derive(Debug, Clone, Serialize)] +pub struct AttemptView { + pub id: i64, + pub kind: String, + pub status: String, + pub started_at: DateTime, + pub finished_at: Option>, + pub statistics: Value, + pub error: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ItemView { + pub id: i64, + pub playlist_id: i64, + pub position: i32, + pub metadata: Value, + pub resolution_status: String, + pub resolution_note: Option, + pub match_origin: Option, + pub match_method: Option, + pub match_score: Option, + pub matched_content_id: Option, + pub matched_track_id: Option, + pub candidates: Option, + pub publication_status: String, + pub attempt_count: i32, + pub last_attempt_at: Option>, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ItemsPage { + pub items: Vec, + /// Cursor for the next page: `.`. + pub next: Option, +} + +/// Position of an item in the import order, used as a pagination cursor. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ItemCursor { + pub ordinal: i32, + pub position: i32, +} + +impl ItemCursor { + pub fn encode(self) -> String { + format!("{}.{}", self.ordinal, self.position) + } + + pub fn parse(value: &str) -> Option { + let (ordinal, position) = value.split_once('.')?; + let ordinal = ordinal.parse().ok()?; + let position = position.parse().ok()?; + (ordinal >= 0 && position >= 0).then_some(Self { ordinal, position }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn statuses_round_trip_through_text() { + for status in ImportStatus::ALL { + assert_eq!(status.as_str().parse::(), Ok(*status)); + } + for status in PublicationStatus::ALL { + assert_eq!(status.as_str().parse::(), Ok(*status)); + } + assert_eq!( + serde_json::to_value(ResolutionStatus::Unsupported).unwrap(), + "unsupported" + ); + assert!("publishing".parse::().is_err()); + } + + #[test] + fn phases_resume_from_the_stored_phase() { + assert_eq!( + Phase::remaining(SourceType::File, None), + &[ + Phase::ResolveLocal, + Phase::ResolveFederation, + Phase::Publish + ] + ); + assert_eq!( + Phase::remaining(SourceType::Api, Some(Phase::Publish)), + &[Phase::Publish] + ); + // A file import never fetches; an unexpected stored phase restarts the sequence. + assert_eq!( + Phase::remaining(SourceType::File, Some(Phase::Fetching)), + Phase::sequence(SourceType::File) + ); + } + + #[test] + fn entries_without_usable_metadata_are_kept_as_unsupported() { + let track = ImportedTrack { + title: "Song".into(), + ..ImportedTrack::default() + }; + assert_eq!( + track.initial_resolution(), + (ResolutionStatus::Pending, None) + ); + let untitled = ImportedTrack { + title: " ".into(), + ..track.clone() + }; + assert_eq!( + untitled.initial_resolution().0, + ResolutionStatus::Unsupported + ); + let episode = ImportedTrack { + kind: TrackKind::Episode, + ..track.clone() + }; + assert_eq!( + episode.initial_resolution(), + (ResolutionStatus::Unsupported, Some("episode")) + ); + let metadata = serde_json::to_value(track.metadata()).unwrap(); + assert_eq!(metadata["kind"], "track"); + assert!(metadata.get("source_id").is_none()); + } + + #[test] + fn statistics_split_matches_by_origin() { + let mut stats = ImportStatistics::default(); + stats.add( + Some(ResolutionStatus::Matched), + Some("federation"), + Some(PublicationStatus::Published), + 3, + ); + stats.add( + Some(ResolutionStatus::Matched), + Some("local"), + Some(PublicationStatus::Duplicate), + 2, + ); + stats.add( + Some(ResolutionStatus::Unmatched), + None, + Some(PublicationStatus::NotReady), + 5, + ); + assert_eq!(stats.total, 10); + assert_eq!(stats.matched(), 5); + assert_eq!(stats.published, 3); + assert_eq!(stats.duplicate, 2); + assert_eq!(stats.unmatched, 5); + } + + #[test] + fn item_cursor_rejects_malformed_values() { + let cursor = ItemCursor { + ordinal: 2, + position: 41, + }; + assert_eq!(ItemCursor::parse(&cursor.encode()), Some(cursor)); + for value in ["", "1", "a.b", "-1.0", "1.-2", "1.2.3"] { + assert_eq!(ItemCursor::parse(value), None, "{value}"); + } + } +} diff --git a/src/library_import/schema.sql b/src/library_import/schema.sql new file mode 100644 index 0000000..e628cf8 --- /dev/null +++ b/src/library_import/schema.sql @@ -0,0 +1,100 @@ +-- Library import keeps the full source list, matching decisions and publication receipts. +-- None of these tables take part in Device Sync. +CREATE TABLE IF NOT EXISTS furumusic__library_import ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES furumusic__user(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + source_type TEXT NOT NULL, + source_account_ref TEXT, + federated_search BOOLEAN NOT NULL DEFAULT false, + status TEXT NOT NULL, + phase TEXT, + cancel_requested BOOLEAN NOT NULL DEFAULT false, + rerun_requested BOOLEAN NOT NULL DEFAULT false, + lease_owner BIGINT, + lease_until TIMESTAMPTZ, + statistics JSONB NOT NULL DEFAULT '{}', + error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_resync_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_library_import_user + ON furumusic__library_import(user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_library_import_active + ON furumusic__library_import(status) WHERE status IN ('queued', 'running'); + +CREATE TABLE IF NOT EXISTS furumusic__library_import_playlist ( + id BIGSERIAL PRIMARY KEY, + import_id BIGINT NOT NULL REFERENCES furumusic__library_import(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + ordinal INTEGER NOT NULL, + source_playlist_id TEXT, + source_key TEXT NOT NULL, + source_title TEXT NOT NULL, + source_description TEXT, + target_playlist_id BIGINT REFERENCES furumusic__playlist(id) ON DELETE SET NULL, + -- A NULL target with a creation time means the user deleted the target playlist. + target_created_at TIMESTAMPTZ, + publication_paused BOOLEAN NOT NULL DEFAULT false, + fetched_at TIMESTAMPTZ, + UNIQUE (import_id, source_key) +); +CREATE INDEX IF NOT EXISTS idx_library_import_playlist_key + ON furumusic__library_import_playlist(source_key); + +CREATE TABLE IF NOT EXISTS furumusic__library_import_item ( + id BIGSERIAL PRIMARY KEY, + import_playlist_id BIGINT NOT NULL + REFERENCES furumusic__library_import_playlist(id) ON DELETE CASCADE, + source_track_id TEXT, + source_position INTEGER NOT NULL, + metadata JSONB NOT NULL, + artist_key TEXT, + resolution_status TEXT NOT NULL DEFAULT 'pending', + resolution_note TEXT, + match_origin TEXT, + match_method TEXT, + match_score REAL, + matched_content_id TEXT, + matched_track_id BIGINT, + matched_fed JSONB, + candidates JSONB, + publication_status TEXT NOT NULL DEFAULT 'not_ready', + last_attempt_at TIMESTAMPTZ, + attempt_count INTEGER NOT NULL DEFAULT 0, + UNIQUE (import_playlist_id, source_position) +); +CREATE INDEX IF NOT EXISTS idx_library_import_item_resolution + ON furumusic__library_import_item(import_playlist_id, resolution_status); +CREATE INDEX IF NOT EXISTS idx_library_import_item_publication + ON furumusic__library_import_item(import_playlist_id, publication_status, source_position); +CREATE INDEX IF NOT EXISTS idx_library_import_item_artist + ON furumusic__library_import_item(import_playlist_id, artist_key); + +-- A receipt survives track and playlist deletion, so removed tracks are never added again. +CREATE TABLE IF NOT EXISTS furumusic__library_import_publication ( + target_playlist_id BIGINT NOT NULL, + content_id TEXT NOT NULL, + import_playlist_id BIGINT NOT NULL + REFERENCES furumusic__library_import_playlist(id) ON DELETE CASCADE, + item_id BIGINT NOT NULL REFERENCES furumusic__library_import_item(id) ON DELETE CASCADE, + state TEXT NOT NULL, + position BIGINT NOT NULL, + op_id TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (target_playlist_id, content_id) +); + +CREATE TABLE IF NOT EXISTS furumusic__library_import_attempt ( + id BIGSERIAL PRIMARY KEY, + import_id BIGINT NOT NULL REFERENCES furumusic__library_import(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + status TEXT NOT NULL, + started_at TIMESTAMPTZ NOT NULL DEFAULT now(), + finished_at TIMESTAMPTZ, + statistics JSONB NOT NULL DEFAULT '{}', + error TEXT +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_library_import_attempt_active + ON furumusic__library_import_attempt(import_id) WHERE finished_at IS NULL diff --git a/src/library_import/store.rs b/src/library_import/store.rs new file mode 100644 index 0000000..54cce9c --- /dev/null +++ b/src/library_import/store.rs @@ -0,0 +1,887 @@ +//! All SQL for `furumusic__library_import*`. +//! +//! Requests on behalf of a user always filter by `user_id`. Worker writes are +//! conditional on `lease_owner = run_id`, so a worker that lost its lease can +//! no longer change the import. + +use std::time::Duration; + +use serde_json::Value; +use sqlx::{PgConnection, PgPool, Row}; + +use super::model::{ + AttemptView, ImportDetail, ImportStatistics, ImportStatus, ImportSummary, ImportedTrack, + ItemCursor, ItemView, ItemsPage, Phase, PlaylistKind, PlaylistLink, PlaylistView, + PublicationStatus, ResolutionStatus, SourceType, +}; + +/// Rows per `INSERT … SELECT FROM UNNEST` statement. +const INSERT_CHUNK: usize = 1000; +const HISTORY_LIMIT: i64 = 200; +pub const MAX_ITEMS_PAGE: i64 = 200; +const DEFAULT_ITEMS_PAGE: i64 = 50; + +// --------------------------------------------------------------------------- +// Creation +// --------------------------------------------------------------------------- + +pub struct NewImport { + pub user_id: i64, + pub provider: String, + pub source_type: SourceType, + pub source_account_ref: Option, + pub federated_search: bool, + pub playlists: Vec, +} + +pub struct NewPlaylist { + pub kind: PlaylistKind, + pub source_playlist_id: Option, + pub source_key: String, + pub title: String, + pub description: Option, + pub items: Vec, +} + +pub struct NewItem { + pub source_track_id: Option, + pub source_position: i32, + pub metadata: Value, + pub artist_key: Option, + pub resolution_status: ResolutionStatus, + pub resolution_note: Option, +} + +impl NewItem { + /// An entry with its initial resolution; unusable entries are stored as unsupported. + pub fn from_track(track: &ImportedTrack, artist_key: Option) -> Self { + let (resolution_status, note) = track.initial_resolution(); + Self { + source_track_id: track.source_id.clone(), + source_position: i32::try_from(track.position).unwrap_or(i32::MAX), + metadata: serde_json::to_value(track.metadata()).unwrap_or(Value::Null), + artist_key, + resolution_status, + resolution_note: note.map(str::to_owned), + } + } +} + +/// A source playlist this user already imported from the same provider. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct ImportConflict { + pub source_key: String, + pub import_id: i64, +} + +#[derive(Debug)] +pub enum CreateImportError { + AlreadyImported(Vec), + Database(sqlx::Error), +} + +impl From for CreateImportError { + fn from(error: sqlx::Error) -> Self { + Self::Database(error) + } +} + +/// Stores an import with all its playlists and entries in one transaction and +/// queues it. Nothing is left behind when any statement fails. +pub async fn create_import(pool: &PgPool, new: &NewImport) -> Result { + let mut tx = pool.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended('library-import:' || $1, 0))") + .bind(new.user_id) + .execute(&mut *tx) + .await?; + let keys: Vec<&str> = new + .playlists + .iter() + .map(|playlist| playlist.source_key.as_str()) + .collect(); + let conflicts = imported_source_keys(&mut tx, new.user_id, &new.provider, &keys).await?; + if !conflicts.is_empty() { + return Err(CreateImportError::AlreadyImported(conflicts)); + } + let import_id: i64 = sqlx::query_scalar( + "INSERT INTO furumusic__library_import + (user_id, provider, source_type, source_account_ref, federated_search, status) + VALUES ($1, $2, $3, $4, $5, 'queued') RETURNING id", + ) + .bind(new.user_id) + .bind(&new.provider) + .bind(new.source_type.as_str()) + .bind(&new.source_account_ref) + .bind(new.federated_search) + .fetch_one(&mut *tx) + .await?; + for (ordinal, playlist) in new.playlists.iter().enumerate() { + let playlist_id: i64 = sqlx::query_scalar( + "INSERT INTO furumusic__library_import_playlist + (import_id, kind, ordinal, source_playlist_id, source_key, source_title, source_description) + VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id", + ) + .bind(import_id) + .bind(playlist.kind.as_str()) + .bind(i32::try_from(ordinal).unwrap_or(i32::MAX)) + .bind(&playlist.source_playlist_id) + .bind(&playlist.source_key) + .bind(&playlist.title) + .bind(&playlist.description) + .fetch_one(&mut *tx) + .await?; + insert_items(&mut tx, playlist_id, &playlist.items).await?; + } + refresh_statistics(&mut tx, import_id).await?; + tx.commit().await?; + Ok(import_id) +} + +/// Source keys of `keys` that this user already imported from `provider`. +pub async fn imported_source_keys( + conn: &mut PgConnection, + user_id: i64, + provider: &str, + keys: &[&str], +) -> sqlx::Result> { + let rows = sqlx::query( + "SELECT DISTINCT ON (p.source_key) p.source_key, i.id + FROM furumusic__library_import_playlist p + JOIN furumusic__library_import i ON i.id = p.import_id + WHERE i.user_id = $1 AND i.provider = $2 AND p.source_key = ANY($3) + ORDER BY p.source_key, i.id", + ) + .bind(user_id) + .bind(provider) + .bind(keys) + .fetch_all(conn) + .await?; + Ok(rows + .into_iter() + .map(|row| ImportConflict { + source_key: row.get(0), + import_id: row.get(1), + }) + .collect()) +} + +async fn insert_items( + conn: &mut PgConnection, + playlist_id: i64, + items: &[NewItem], +) -> sqlx::Result<()> { + for chunk in items.chunks(INSERT_CHUNK) { + let source_ids: Vec> = chunk + .iter() + .map(|item| item.source_track_id.as_deref()) + .collect(); + let positions: Vec = chunk.iter().map(|item| item.source_position).collect(); + let metadata: Vec<&Value> = chunk.iter().map(|item| &item.metadata).collect(); + let artist_keys: Vec> = chunk + .iter() + .map(|item| item.artist_key.as_deref()) + .collect(); + let statuses: Vec<&str> = chunk + .iter() + .map(|item| item.resolution_status.as_str()) + .collect(); + let notes: Vec> = chunk + .iter() + .map(|item| item.resolution_note.as_deref()) + .collect(); + sqlx::query( + "INSERT INTO furumusic__library_import_item + (import_playlist_id, source_track_id, source_position, metadata, artist_key, + resolution_status, resolution_note) + SELECT $1, source_track_id, source_position, metadata, artist_key, status, note + FROM UNNEST($2::text[], $3::int4[], $4::jsonb[], $5::text[], $6::text[], $7::text[]) + AS entry(source_track_id, source_position, metadata, artist_key, status, note)", + ) + .bind(playlist_id) + .bind(&source_ids) + .bind(&positions) + .bind(&metadata) + .bind(&artist_keys) + .bind(&statuses) + .bind(¬es) + .execute(&mut *conn) + .await?; + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Worker: claim, lease and completion +// --------------------------------------------------------------------------- + +/// Condition for an import that a worker may take: queued, or running under an expired lease. +const CLAIMABLE: &str = + "(status = 'queued' OR (status = 'running' AND (lease_until IS NULL OR lease_until < now())))"; + +#[derive(Debug, Clone)] +pub struct ClaimedImport { + pub id: i64, + pub user_id: i64, + pub provider: String, + pub source_type: SourceType, + pub phase: Option, + pub federated_search: bool, +} + +/// Returns imports of a previous process to the queue at boot, without waiting +/// for their leases to expire. The scheduler has already marked that process's +/// job runs failed, so only leases of job runs started by this process survive. +pub async fn requeue_orphaned(pool: &PgPool) -> sqlx::Result { + Ok(sqlx::query( + "UPDATE furumusic__library_import i + SET status = 'queued', lease_owner = NULL, lease_until = NULL, updated_at = now() + WHERE i.status = 'running' + AND NOT EXISTS (SELECT 1 FROM furumusic__job_run r + WHERE r.id = i.lease_owner AND r.status = 'running')", + ) + .execute(pool) + .await? + .rows_affected()) +} + +/// Whether some import waits for a worker, including one left by a crashed worker. +pub async fn has_claimable(pool: &PgPool) -> sqlx::Result { + sqlx::query_scalar(&format!( + "SELECT EXISTS(SELECT 1 FROM furumusic__library_import WHERE status IN ('queued', 'running') AND {CLAIMABLE})" + )) + .fetch_one(pool) + .await +} + +/// Takes the oldest claimable import under a lease owned by `run_id`. +pub async fn claim_next( + pool: &PgPool, + run_id: i64, + lease: Duration, +) -> sqlx::Result> { + let row = sqlx::query(&format!( + "UPDATE furumusic__library_import + SET status = 'running', lease_owner = $1, + lease_until = now() + make_interval(secs => $2), + rerun_requested = false, error = NULL, updated_at = now() + WHERE id = (SELECT id FROM furumusic__library_import + WHERE status IN ('queued', 'running') AND {CLAIMABLE} + ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED) + AND {CLAIMABLE} + RETURNING id, user_id, provider, source_type, phase, federated_search" + )) + .bind(run_id) + .bind(lease.as_secs_f64()) + .fetch_optional(pool) + .await?; + row.map(|row| claimed_from_row(&row)).transpose() +} + +fn claimed_from_row(row: &sqlx::postgres::PgRow) -> sqlx::Result { + let source_type: String = row.get("source_type"); + let phase: Option = row.get("phase"); + Ok(ClaimedImport { + id: row.get("id"), + user_id: row.get("user_id"), + provider: row.get("provider"), + source_type: source_type + .parse() + .map_err(|_| sqlx::Error::Decode("unknown library import source type".into()))?, + phase: phase.and_then(|phase| phase.parse().ok()), + federated_search: row.get("federated_search"), + }) +} + +/// Extends the lease. `false` means another worker owns the import now. +pub async fn renew_lease( + pool: &PgPool, + import_id: i64, + run_id: i64, + lease: Duration, +) -> sqlx::Result { + Ok(sqlx::query( + "UPDATE furumusic__library_import + SET lease_until = now() + make_interval(secs => $3) + WHERE id = $1 AND lease_owner = $2 AND status = 'running'", + ) + .bind(import_id) + .bind(run_id) + .bind(lease.as_secs_f64()) + .execute(pool) + .await? + .rows_affected() + == 1) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Control { + Continue, + Cancel, + LeaseLost, +} + +/// Checked between phases, groups and batches. +pub async fn control(pool: &PgPool, import_id: i64, run_id: i64) -> sqlx::Result { + let cancel: Option = sqlx::query_scalar( + "SELECT cancel_requested FROM furumusic__library_import + WHERE id = $1 AND lease_owner = $2 AND status = 'running'", + ) + .bind(import_id) + .bind(run_id) + .fetch_optional(pool) + .await?; + Ok(match cancel { + None => Control::LeaseLost, + Some(true) => Control::Cancel, + Some(false) => Control::Continue, + }) +} + +pub async fn set_phase( + pool: &PgPool, + import_id: i64, + run_id: i64, + phase: Phase, +) -> sqlx::Result { + Ok(sqlx::query( + "UPDATE furumusic__library_import SET phase = $3, updated_at = now() + WHERE id = $1 AND lease_owner = $2 AND status = 'running'", + ) + .bind(import_id) + .bind(run_id) + .bind(phase.as_str()) + .execute(pool) + .await? + .rows_affected() + == 1) +} + +/// Opens the import's attempt unless one is still open: after a crash the +/// worker continues the interrupted attempt. Returns `false` without a lease. +pub async fn open_attempt(pool: &PgPool, import_id: i64, run_id: i64) -> 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( + "INSERT INTO furumusic__library_import_attempt (import_id, kind, status, statistics) + SELECT $1, + CASE WHEN EXISTS(SELECT 1 FROM furumusic__library_import_attempt WHERE import_id = $1) + THEN 'resync' ELSE 'initial' END, + 'running', statistics + FROM furumusic__library_import WHERE id = $1 + ON CONFLICT (import_id) WHERE finished_at IS NULL DO NOTHING", + ) + .bind(import_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(true) +} + +/// Recounts entry states and caches them on the import and its open attempt. +pub async fn refresh_statistics( + conn: &mut PgConnection, + import_id: i64, +) -> sqlx::Result { + let rows = sqlx::query( + "SELECT i.resolution_status, i.match_origin, i.publication_status, count(*) + FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 + GROUP BY 1, 2, 3", + ) + .bind(import_id) + .fetch_all(&mut *conn) + .await?; + let mut statistics = ImportStatistics::default(); + for row in rows { + let resolution: String = row.get(0); + let origin: Option = row.get(1); + let publication: String = row.get(2); + statistics.add( + resolution.parse::().ok(), + origin.as_deref(), + publication.parse::().ok(), + row.get(3), + ); + } + 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") + .bind(import_id) + .bind(&value) + .execute(&mut *conn) + .await?; + sqlx::query( + "UPDATE furumusic__library_import_attempt SET statistics = $2 + WHERE import_id = $1 AND finished_at IS NULL", + ) + .bind(import_id) + .bind(&value) + .execute(&mut *conn) + .await?; + Ok(statistics) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FinishOutcome { + Done(ImportStatistics), + /// A change arrived during the run; the phases run again under the same lease. + Rerun, + LeaseLost, +} + +/// Completes the import unless a rerun was requested meanwhile. +pub async fn finish(pool: &PgPool, import_id: i64, run_id: i64) -> sqlx::Result { + let mut tx = pool.begin().await?; + let row: Option = sqlx::query_scalar( + "SELECT rerun_requested FROM furumusic__library_import + WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR UPDATE", + ) + .bind(import_id) + .bind(run_id) + .fetch_optional(&mut *tx) + .await?; + let outcome = match row { + None => FinishOutcome::LeaseLost, + Some(true) => { + sqlx::query( + "UPDATE furumusic__library_import + SET rerun_requested = false, phase = NULL, updated_at = now() WHERE id = $1", + ) + .bind(import_id) + .execute(&mut *tx) + .await?; + FinishOutcome::Rerun + } + Some(false) => { + let statistics = refresh_statistics(&mut tx, import_id).await?; + sqlx::query( + "UPDATE furumusic__library_import + SET status = 'done', phase = NULL, lease_owner = NULL, lease_until = NULL, + cancel_requested = false, error = NULL, updated_at = now() + WHERE id = $1", + ) + .bind(import_id) + .execute(&mut *tx) + .await?; + close_attempt(&mut tx, import_id, "done", None).await?; + FinishOutcome::Done(statistics) + } + }; + tx.commit().await?; + Ok(outcome) +} + +/// Stops the import after `…/cancel`. Published tracks stay in their playlists. +pub async fn cancel_by_worker(pool: &PgPool, import_id: i64, run_id: i64) -> sqlx::Result { + end_by_worker(pool, import_id, run_id, ImportStatus::Cancelled, None).await +} + +/// Marks the import failed. `message` is shown to the user and must not contain source metadata. +pub async fn fail(pool: &PgPool, import_id: i64, run_id: i64, message: &str) -> sqlx::Result { + end_by_worker(pool, import_id, run_id, ImportStatus::Failed, Some(message)).await +} + +async fn end_by_worker( + pool: &PgPool, + import_id: i64, + run_id: i64, + status: ImportStatus, + error: Option<&str>, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let ended = sqlx::query( + "UPDATE furumusic__library_import + SET status = $3, error = $4, phase = NULL, lease_owner = NULL, lease_until = NULL, + cancel_requested = false, updated_at = now() + WHERE id = $1 AND lease_owner = $2 AND status = 'running'", + ) + .bind(import_id) + .bind(run_id) + .bind(status.as_str()) + .bind(error) + .execute(&mut *tx) + .await? + .rows_affected() + == 1; + if ended { + refresh_statistics(&mut tx, import_id).await?; + close_attempt(&mut tx, import_id, status.as_str(), error).await?; + } + tx.commit().await?; + Ok(ended) +} + +async fn close_attempt( + conn: &mut PgConnection, + import_id: i64, + status: &str, + error: Option<&str>, +) -> sqlx::Result<()> { + sqlx::query( + "UPDATE furumusic__library_import_attempt + SET status = $2, error = $3, finished_at = now(), + statistics = (SELECT statistics FROM furumusic__library_import WHERE id = $1) + WHERE import_id = $1 AND finished_at IS NULL", + ) + .bind(import_id) + .bind(status) + .bind(error) + .execute(conn) + .await?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Owner requests +// --------------------------------------------------------------------------- + +const SUMMARY_COLUMNS: &str = "i.id, i.provider, i.source_type, i.status, i.phase, i.federated_search, + i.cancel_requested, i.statistics, i.error, i.created_at, i.updated_at, i.last_resync_at, + COALESCE((SELECT jsonb_agg(jsonb_build_object( + 'id', p.id, 'title', p.source_title, 'target_playlist_id', p.target_playlist_id, + 'target_deleted', p.target_playlist_id IS NULL AND p.target_created_at IS NOT NULL) + ORDER BY p.ordinal) + FROM furumusic__library_import_playlist p WHERE p.import_id = i.id), '[]') AS playlists"; + +fn summary_from_row(row: &sqlx::postgres::PgRow) -> sqlx::Result { + let playlists: Value = row.get("playlists"); + Ok(ImportSummary { + id: row.get("id"), + provider: row.get("provider"), + source_type: row.get("source_type"), + status: row.get("status"), + phase: row.get("phase"), + federated_search: row.get("federated_search"), + cancel_requested: row.get("cancel_requested"), + statistics: row.get("statistics"), + error: row.get("error"), + created_at: row.get("created_at"), + updated_at: row.get("updated_at"), + last_resync_at: row.get("last_resync_at"), + playlists: serde_json::from_value::>(playlists) + .map_err(|error| sqlx::Error::Decode(Box::new(error)))?, + }) +} + +/// The user's import history, newest first. +pub async fn list_imports(pool: &PgPool, user_id: i64) -> sqlx::Result> { + let rows = sqlx::query(&format!( + "SELECT {SUMMARY_COLUMNS} FROM furumusic__library_import i + WHERE i.user_id = $1 ORDER BY i.created_at DESC, i.id DESC LIMIT $2" + )) + .bind(user_id) + .bind(HISTORY_LIMIT) + .fetch_all(pool) + .await?; + rows.iter().map(summary_from_row).collect() +} + +pub async fn get_import( + pool: &PgPool, + user_id: i64, + import_id: i64, +) -> sqlx::Result> { + let Some(row) = sqlx::query(&format!( + "SELECT {SUMMARY_COLUMNS} FROM furumusic__library_import i WHERE i.id = $1 AND i.user_id = $2" + )) + .bind(import_id) + .bind(user_id) + .fetch_optional(pool) + .await? + else { + return Ok(None); + }; + let summary = summary_from_row(&row)?; + let source_playlists = sqlx::query( + "SELECT p.id, p.kind, p.ordinal, p.source_title, p.source_description, p.target_playlist_id, + p.target_created_at, p.publication_paused, + count(i.id) AS total, + count(i.id) FILTER (WHERE i.resolution_status = 'matched') AS matched, + count(i.id) FILTER (WHERE i.publication_status = 'published') AS published + FROM furumusic__library_import_playlist p + LEFT JOIN furumusic__library_import_item i ON i.import_playlist_id = p.id + WHERE p.import_id = $1 + GROUP BY p.id ORDER BY p.ordinal", + ) + .bind(import_id) + .fetch_all(pool) + .await? + .iter() + .map(|row| { + let target: Option = row.get("target_playlist_id"); + let created: Option> = row.get("target_created_at"); + PlaylistView { + id: row.get("id"), + kind: row.get("kind"), + ordinal: row.get("ordinal"), + title: row.get("source_title"), + description: row.get("source_description"), + target_playlist_id: target, + target_created_at: created, + target_deleted: target.is_none() && created.is_some(), + publication_paused: row.get("publication_paused"), + total: row.get("total"), + matched: row.get("matched"), + published: row.get("published"), + } + }) + .collect(); + let attempt = sqlx::query( + "SELECT id, kind, status, started_at, finished_at, statistics, error + FROM furumusic__library_import_attempt WHERE import_id = $1 + ORDER BY id DESC LIMIT 1", + ) + .bind(import_id) + .fetch_optional(pool) + .await? + .map(|row| AttemptView { + id: row.get("id"), + kind: row.get("kind"), + status: row.get("status"), + started_at: row.get("started_at"), + finished_at: row.get("finished_at"), + statistics: row.get("statistics"), + error: row.get("error"), + }); + Ok(Some(ImportDetail { + summary, + source_playlists, + attempt, + })) +} + +#[derive(Debug, Clone, Default)] +pub struct ItemFilter { + pub resolution: Option, + pub publication: Option, + pub playlist: Option, + pub query: Option, + pub after: Option, + pub limit: Option, +} + +/// Escaped `ILIKE` patterns, one per word; every word must match. +fn search_terms(query: &str) -> Vec { + query + .split_whitespace() + .take(20) + .map(|word| { + format!( + "%{}%", + word.replace('\\', "\\\\") + .replace('%', "\\%") + .replace('_', "\\_") + ) + }) + .collect() +} + +/// Entries of one import in source order. `None` when the import is not the user's. +pub async fn list_items( + pool: &PgPool, + user_id: i64, + import_id: i64, + filter: &ItemFilter, +) -> sqlx::Result> { + let owned: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM furumusic__library_import WHERE id = $1 AND user_id = $2)", + ) + .bind(import_id) + .bind(user_id) + .fetch_one(pool) + .await?; + if !owned { + return Ok(None); + } + let limit = filter + .limit + .unwrap_or(DEFAULT_ITEMS_PAGE) + .clamp(1, MAX_ITEMS_PAGE); + let terms = filter + .query + .as_deref() + .map(search_terms) + .unwrap_or_default(); + let rows = sqlx::query( + "SELECT i.id, i.import_playlist_id, i.source_position, i.metadata, i.resolution_status, + i.resolution_note, i.match_origin, i.match_method, i.match_score, + i.matched_content_id, i.matched_track_id, i.candidates, i.publication_status, + i.attempt_count, i.last_attempt_at, p.ordinal + 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 ($2::text IS NULL OR i.resolution_status = $2) + AND ($3::text IS NULL OR i.publication_status = $3) + AND ($4::bigint IS NULL OR i.import_playlist_id = $4) + AND ($5::int IS NULL OR (p.ordinal, i.source_position) > ($5, $6)) + AND NOT EXISTS ( + SELECT 1 FROM unnest($7::text[]) AS term + WHERE concat_ws(' ', i.metadata->>'title', i.metadata->>'album', + (SELECT string_agg(artist, ' ') + FROM jsonb_array_elements_text(COALESCE(i.metadata->'artists', '[]')) AS artist)) + COLLATE furumusic_unicode NOT ILIKE term) + ORDER BY p.ordinal, i.source_position + LIMIT $8", + ) + .bind(import_id) + .bind(filter.resolution.map(|status| status.as_str())) + .bind(filter.publication.map(|status| status.as_str())) + .bind(filter.playlist) + .bind(filter.after.map(|cursor| cursor.ordinal)) + .bind(filter.after.map_or(0, |cursor| cursor.position)) + .bind(&terms) + .bind(limit + 1) + .fetch_all(pool) + .await?; + let more = rows.len() as i64 > limit; + let mut next = None; + let mut items = Vec::with_capacity(rows.len().min(limit as usize)); + for row in rows.iter().take(limit as usize) { + let position: i32 = row.get("source_position"); + next = Some(ItemCursor { + ordinal: row.get("ordinal"), + position, + }); + items.push(ItemView { + id: row.get("id"), + playlist_id: row.get("import_playlist_id"), + position, + metadata: row.get("metadata"), + resolution_status: row.get("resolution_status"), + resolution_note: row.get("resolution_note"), + match_origin: row.get("match_origin"), + match_method: row.get("match_method"), + match_score: row.get("match_score"), + matched_content_id: row.get("matched_content_id"), + matched_track_id: row.get("matched_track_id"), + candidates: row.get("candidates"), + publication_status: row.get("publication_status"), + attempt_count: row.get("attempt_count"), + last_attempt_at: row.get("last_attempt_at"), + }); + } + Ok(Some(ItemsPage { + items, + next: if more { + next.map(ItemCursor::encode) + } else { + None + }, + })) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CancelOutcome { + /// The import had no worker and is cancelled now. + Cancelled, + /// The worker stops at the next checkpoint. + Requested, + /// The import has already finished. + NotActive, + NotFound, +} + +pub async fn request_cancel( + pool: &PgPool, + user_id: i64, + import_id: i64, +) -> 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 outcome = match status.as_deref().map(str::parse::) { + None => CancelOutcome::NotFound, + Some(Ok(ImportStatus::Queued | ImportStatus::NeedsReauth)) => { + sqlx::query( + "UPDATE furumusic__library_import + SET status = 'cancelled', phase = NULL, lease_owner = NULL, lease_until = NULL, + cancel_requested = false, rerun_requested = false, updated_at = now() + WHERE id = $1", + ) + .bind(import_id) + .execute(&mut *tx) + .await?; + close_attempt(&mut tx, import_id, "cancelled", None).await?; + CancelOutcome::Cancelled + } + Some(Ok(ImportStatus::Running)) => { + sqlx::query( + "UPDATE furumusic__library_import + SET cancel_requested = true, updated_at = now() WHERE id = $1", + ) + .bind(import_id) + .execute(&mut *tx) + .await?; + CancelOutcome::Requested + } + Some(_) => CancelOutcome::NotActive, + }; + tx.commit().await?; + Ok(outcome) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeleteOutcome { + Deleted, + Active, + NotFound, +} + +/// Deletes the import history. Target playlists are ordinary playlists and stay. +pub async fn delete_import( + pool: &PgPool, + user_id: i64, + import_id: i64, +) -> 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 outcome = match status.as_deref().map(str::parse::) { + None => DeleteOutcome::NotFound, + Some(Ok(status)) if status.is_active() => DeleteOutcome::Active, + Some(_) => { + sqlx::query("DELETE FROM furumusic__library_import WHERE id = $1") + .bind(import_id) + .execute(&mut *tx) + .await?; + DeleteOutcome::Deleted + } + }; + tx.commit().await?; + Ok(outcome) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn search_terms_escape_like_wildcards() { + assert_eq!( + search_terms(" 100% a_b\\c "), + vec!["%100\\%%".to_owned(), "%a\\_b\\\\c%".to_owned()] + ); + assert!(search_terms(" ").is_empty()); + } +} diff --git a/src/library_import/tests.rs b/src/library_import/tests.rs new file mode 100644 index 0000000..8dd6ed8 --- /dev/null +++ b/src/library_import/tests.rs @@ -0,0 +1,707 @@ +//! PostgreSQL tests for import storage and the worker lifecycle. Each test +//! creates and drops a unique schema in the disposable database from +//! `FURU_LIBRARY_IMPORT_TEST_DATABASE_URL`. + +use std::sync::Arc; + +use sqlx::PgPool; + +use super::job; +use super::model::{ImportedTrack, Phase, PlaylistKind, ResolutionStatus, SourceType, TrackKind}; +use super::store::{ + self, CancelOutcome, Control, CreateImportError, DeleteOutcome, FinishOutcome, ItemFilter, + NewImport, NewItem, NewPlaylist, +}; +use crate::config::AppConfig; +use crate::scheduler::JobLog; + +/// Workers share a process-wide slot counter, so database tests run one at a time. +static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +struct Fixture { + admin: PgPool, + pool: PgPool, + schema: String, +} + +impl Fixture { + async fn new() -> Self { + let url = std::env::var("FURU_LIBRARY_IMPORT_TEST_DATABASE_URL") + .expect("disposable database URL"); + let admin = PgPool::connect(&url).await.unwrap(); + let schema = format!("library_import_test_{}", uuid::Uuid::new_v4().simple()); + sqlx::query(&format!("CREATE SCHEMA {schema}")) + .execute(&admin) + .await + .unwrap(); + let search_path = format!("SET search_path TO {schema}"); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(8) + .after_connect(move |connection, _| { + let query = search_path.clone(); + Box::pin(async move { + sqlx::query(&query).execute(connection).await?; + Ok(()) + }) + }) + .connect(&url) + .await + .unwrap(); + sqlx::raw_sql( + "CREATE COLLATION furumusic_unicode (provider=icu, locale='und', deterministic=true); + CREATE TABLE furumusic__user(id BIGINT PRIMARY KEY); + CREATE TABLE furumusic__playlist(id BIGSERIAL PRIMARY KEY, owner_id BIGINT NOT NULL, title TEXT NOT NULL); + CREATE TABLE furumusic__job_run(id BIGINT PRIMARY KEY, status TEXT NOT NULL); + INSERT INTO furumusic__user VALUES (1), (2);", + ) + .execute(&pool) + .await + .unwrap(); + // The migration must be repeatable after a partial upgrade. + for _ in 0..2 { + for statement in include_str!("schema.sql") + .split(';') + .filter(|statement| !statement.trim().is_empty()) + { + sqlx::query(statement).execute(&pool).await.unwrap(); + } + } + Self { + admin, + pool, + schema, + } + } + + async fn drop(self) { + self.pool.close().await; + sqlx::query(&format!("DROP SCHEMA {} CASCADE", self.schema)) + .execute(&self.admin) + .await + .unwrap(); + self.admin.close().await; + } + + async fn scalar(&self, sql: &str, id: i64) -> T + where + T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type + Send + Unpin, + { + sqlx::query_scalar(sql) + .bind(id) + .fetch_one(&self.pool) + .await + .unwrap() + } + + async fn status(&self, import_id: i64) -> String { + self.scalar( + "SELECT status FROM furumusic__library_import WHERE id = $1", + import_id, + ) + .await + } + + async fn create(&self, user_id: i64, provider: &str, playlists: Vec) -> i64 { + store::create_import(&self.pool, &new_import(user_id, provider, playlists)) + .await + .unwrap() + } +} + +fn track(position: u32, title: &str, artist: &str, album: &str) -> ImportedTrack { + ImportedTrack { + kind: TrackKind::Track, + source_id: Some(format!("spotify:track:{position}")), + position, + title: title.into(), + artists: vec![artist.into()], + album: Some(album.into()), + ..ImportedTrack::default() + } +} + +fn playlist(key: &str, title: &str, tracks: &[ImportedTrack]) -> NewPlaylist { + NewPlaylist { + kind: PlaylistKind::Playlist, + source_playlist_id: None, + source_key: key.into(), + title: title.into(), + description: None, + items: tracks + .iter() + .map(|track| NewItem::from_track(track, track.artists.first().cloned())) + .collect(), + } +} + +fn new_import(user_id: i64, provider: &str, playlists: Vec) -> NewImport { + NewImport { + user_id, + provider: provider.into(), + source_type: SourceType::File, + source_account_ref: None, + federated_search: false, + playlists, + } +} + +fn mixed_playlist(key: &str) -> NewPlaylist { + let mut episode = track(2, "Podcast episode", "Host", "Show"); + episode.kind = TrackKind::Episode; + playlist( + key, + "Road trip", + &[ + track( + 0, + "Звезда по имени Солнце", + "Кино", + "Звезда по имени Солнце", + ), + track(1, "Song 100%", "Artist", "Album"), + episode, + // Repeats are kept as separate entries. + track( + 3, + "Звезда по имени Солнце", + "Кино", + "Звезда по имени Солнце", + ), + ], + ) +} + +async fn run_worker(pool: &PgPool, run_id: i64) -> String { + let mut log = JobLog::new(); + job::run_worker(pool, Arc::new(AppConfig::default()), run_id, &mut log) + .await + .unwrap(); + log.output() +} + +async fn expire_lease(pool: &PgPool, import_id: i64) { + sqlx::query( + "UPDATE furumusic__library_import SET lease_until = now() - interval '1 second' WHERE id = $1", + ) + .bind(import_id) + .execute(pool) + .await + .unwrap(); +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_storage_is_isolated_per_user() { + let _serial = SERIAL.lock().await; + let db = Fixture::new().await; + let id = db + .create( + 1, + "spotify", + vec![mixed_playlist("a"), playlist("b", "Empty", &[])], + ) + .await; + let pool = &db.pool; + + let detail = store::get_import(pool, 1, id).await.unwrap().unwrap(); + assert_eq!(detail.summary.status, "queued"); + assert_eq!(detail.summary.statistics["total"], 4); + assert_eq!(detail.summary.statistics["pending"], 3); + assert_eq!(detail.summary.statistics["unsupported"], 1); + assert_eq!(detail.source_playlists.len(), 2); + assert_eq!(detail.source_playlists[0].total, 4); + assert_eq!(detail.source_playlists[1].total, 0); + assert!(detail.attempt.is_none()); + assert_eq!(store::list_imports(pool, 1).await.unwrap().len(), 1); + + // Another user sees nothing and cannot change anything. + assert!(store::list_imports(pool, 2).await.unwrap().is_empty()); + assert!(store::get_import(pool, 2, id).await.unwrap().is_none()); + assert!( + store::list_items(pool, 2, id, &ItemFilter::default()) + .await + .unwrap() + .is_none() + ); + assert_eq!( + store::request_cancel(pool, 2, id).await.unwrap(), + CancelOutcome::NotFound + ); + assert_eq!( + store::delete_import(pool, 2, id).await.unwrap(), + DeleteOutcome::NotFound + ); + assert_eq!(db.status(id).await, "queued"); + + // Entries keep source order and repeats; pages continue after the cursor. + let first = store::list_items( + pool, + 1, + id, + &ItemFilter { + limit: Some(3), + ..ItemFilter::default() + }, + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + first.items.iter().map(|i| i.position).collect::>(), + [0, 1, 2] + ); + assert_eq!(first.items[2].resolution_status, "unsupported"); + assert_eq!(first.items[2].resolution_note.as_deref(), Some("episode")); + assert!(first.items[0].metadata.get("source_id").is_none()); + let rest = store::list_items( + pool, + 1, + id, + &ItemFilter { + after: first + .next + .as_deref() + .and_then(super::model::ItemCursor::parse), + ..ItemFilter::default() + }, + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + rest.items.iter().map(|i| i.position).collect::>(), + [3] + ); + assert!(rest.next.is_none()); + + // Status filter and case-insensitive Unicode search over title, artists and album. + let search = |query: &str, resolution: Option| { + let filter = ItemFilter { + query: Some(query.into()), + resolution, + ..ItemFilter::default() + }; + async move { + store::list_items(pool, 1, id, &filter) + .await + .unwrap() + .unwrap() + .items + .len() + } + }; + assert_eq!(search("кино звезда", None).await, 2); + assert_eq!(search("100%", None).await, 1); + assert_eq!(search("10_", None).await, 0); + assert_eq!(search("host", Some(ResolutionStatus::Unsupported)).await, 1); + assert_eq!(search("host", Some(ResolutionStatus::Pending)).await, 0); + db.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_rejects_repeated_source_playlists() { + let _serial = SERIAL.lock().await; + let db = Fixture::new().await; + let pool = &db.pool; + let first = db.create(1, "spotify", vec![mixed_playlist("a")]).await; + + match store::create_import( + pool, + &new_import( + 1, + "spotify", + vec![playlist("new", "New", &[]), mixed_playlist("a")], + ), + ) + .await + { + Err(CreateImportError::AlreadyImported(conflicts)) => { + assert_eq!(conflicts.len(), 1); + assert_eq!(conflicts[0].source_key, "a"); + assert_eq!(conflicts[0].import_id, first); + } + other => panic!("expected a conflict, got {other:?}"), + } + // Other users and providers are independent. + db.create(2, "spotify", vec![mixed_playlist("a")]).await; + db.create(1, "csv", vec![mixed_playlist("a")]).await; + + // A failing statement leaves no partial import behind. + let before: i64 = db + .scalar( + "SELECT count(*) FROM furumusic__library_import_item WHERE $1 = $1", + 0, + ) + .await; + assert!(matches!( + store::create_import( + pool, + &new_import(1, "spotify", vec![mixed_playlist("x"), mixed_playlist("x")]), + ) + .await, + Err(CreateImportError::Database(_)) + )); + let after: i64 = db + .scalar( + "SELECT count(*) FROM furumusic__library_import_item WHERE $1 = $1", + 0, + ) + .await; + assert_eq!(before, after); + assert_eq!(store::list_imports(pool, 1).await.unwrap().len(), 2); + + // Deleting the history lifts the protection. + sqlx::query("UPDATE furumusic__library_import SET status = 'done' WHERE id = $1") + .bind(first) + .execute(pool) + .await + .unwrap(); + assert_eq!( + store::delete_import(pool, 1, first).await.unwrap(), + DeleteOutcome::Deleted + ); + db.create(1, "spotify", vec![mixed_playlist("a")]).await; + db.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_claim_is_exclusive_and_leases_belong_to_one_run() { + let _serial = SERIAL.lock().await; + let db = Fixture::new().await; + let pool = &db.pool; + let id = db.create(1, "spotify", vec![mixed_playlist("a")]).await; + + // Two workers race for one import: exactly one wins. + let (left, right) = tokio::join!( + store::claim_next(pool, 101, job::LEASE), + store::claim_next(pool, 102, job::LEASE) + ); + let winners: Vec<_> = [left.unwrap(), right.unwrap()] + .into_iter() + .flatten() + .collect(); + assert_eq!(winners.len(), 1); + assert_eq!(winners[0].id, id); + let (owner, other) = if store::renew_lease(pool, id, 101, job::LEASE).await.unwrap() { + (101, 102) + } else { + (102, 101) + }; + // A live lease is not taken again, and a foreign run cannot renew or write. + assert!( + store::claim_next(pool, 103, job::LEASE) + .await + .unwrap() + .is_none() + ); + assert!(!job::needs_worker(pool).await.unwrap()); + assert!( + !store::renew_lease(pool, id, other, job::LEASE) + .await + .unwrap() + ); + assert!( + !store::set_phase(pool, id, other, Phase::Publish) + .await + .unwrap() + ); + assert_eq!( + store::control(pool, id, other).await.unwrap(), + Control::LeaseLost + ); + assert_eq!( + store::finish(pool, id, other).await.unwrap(), + FinishOutcome::LeaseLost + ); + assert!(!store::open_attempt(pool, id, other).await.unwrap()); + assert_eq!( + store::control(pool, id, owner).await.unwrap(), + Control::Continue + ); + + // A change during the run repeats the phases under the same lease. + sqlx::query("UPDATE furumusic__library_import SET rerun_requested = true, phase = 'publish' WHERE id = $1") + .bind(id) + .execute(pool) + .await + .unwrap(); + assert_eq!( + store::finish(pool, id, owner).await.unwrap(), + FinishOutcome::Rerun + ); + assert_eq!(db.status(id).await, "running"); + let phase: Option = db + .scalar( + "SELECT phase FROM furumusic__library_import WHERE id = $1", + id, + ) + .await; + assert!(phase.is_none()); + assert!(matches!( + store::finish(pool, id, owner).await.unwrap(), + FinishOutcome::Done(_) + )); + assert_eq!(db.status(id).await, "done"); + assert!( + !store::renew_lease(pool, id, owner, job::LEASE) + .await + .unwrap() + ); + db.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_resumes_after_worker_crash_without_restart() { + let _serial = SERIAL.lock().await; + let db = Fixture::new().await; + let pool = &db.pool; + let id = db.create(1, "spotify", vec![mixed_playlist("a")]).await; + + // A worker claims the import, starts an attempt and dies in the middle of a phase. + let crashed = 201; + let claimed = store::claim_next(pool, crashed, job::LEASE) + .await + .unwrap() + .unwrap(); + assert_eq!(claimed.id, id); + assert!(store::open_attempt(pool, id, crashed).await.unwrap()); + assert!( + store::set_phase(pool, id, crashed, Phase::ResolveFederation) + .await + .unwrap() + ); + + // While the lease is valid, the sweeper leaves the import alone and a new worker skips it. + assert!(!job::needs_worker(pool).await.unwrap()); + assert!( + run_worker(pool, 202) + .await + .contains("No library imports waiting") + ); + assert_eq!(db.status(id).await, "running"); + + // Once the lease expires, the sweeper asks for a worker and the worker + // continues the same attempt from the stored phase. + expire_lease(pool, id).await; + assert!(job::needs_worker(pool).await.unwrap()); + let log = run_worker(pool, 203).await; + assert!(log.contains("claimed (phase resolve_federation)"), "{log}"); + assert!(log.contains("done"), "{log}"); + assert_eq!(db.status(id).await, "done"); + let attempts: Vec<(String, String, bool)> = sqlx::query_as( + "SELECT kind, status, finished_at IS NOT NULL FROM furumusic__library_import_attempt WHERE import_id = $1", + ) + .bind(id) + .fetch_all(pool) + .await + .unwrap(); + assert_eq!(attempts, [("initial".into(), "done".into(), true)]); + let attempt_total: i64 = db + .scalar( + "SELECT (statistics->>'total')::bigint FROM furumusic__library_import_attempt WHERE import_id = $1", + id, + ) + .await; + assert_eq!(attempt_total, 4); + assert!(!job::needs_worker(pool).await.unwrap()); + + // The crashed run cannot write after the takeover. + assert!( + !store::renew_lease(pool, id, crashed, job::LEASE) + .await + .unwrap() + ); + assert!(!store::fail(pool, id, crashed, "late").await.unwrap()); + assert_eq!(db.status(id).await, "done"); + + // A restart requeues imports whose job run did not survive, but not live ones. + let orphan = db.create(1, "spotify", vec![mixed_playlist("b")]).await; + let live = db.create(1, "spotify", vec![mixed_playlist("c")]).await; + sqlx::query("INSERT INTO furumusic__job_run VALUES (301, 'failed'), (302, 'running')") + .execute(pool) + .await + .unwrap(); + for (import, run) in [(orphan, 301), (live, 302)] { + sqlx::query( + "UPDATE furumusic__library_import SET status = 'running', lease_owner = $2, + lease_until = now() + interval '1 minute' WHERE id = $1", + ) + .bind(import) + .bind(run) + .execute(pool) + .await + .unwrap(); + } + assert_eq!(store::requeue_orphaned(pool).await.unwrap(), 1); + assert_eq!(db.status(orphan).await, "queued"); + assert_eq!(db.status(live).await, "running"); + db.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_cancel_and_delete_keep_playlists() { + let _serial = SERIAL.lock().await; + let db = Fixture::new().await; + let pool = &db.pool; + + // Queued imports are cancelled at once. + let queued = db.create(1, "spotify", vec![mixed_playlist("q")]).await; + assert_eq!( + store::request_cancel(pool, 1, queued).await.unwrap(), + CancelOutcome::Cancelled + ); + assert_eq!(db.status(queued).await, "cancelled"); + assert_eq!( + store::request_cancel(pool, 1, queued).await.unwrap(), + CancelOutcome::NotActive + ); + + // A running import is cancelled by its worker at the next checkpoint. + let running = db.create(1, "spotify", vec![mixed_playlist("r")]).await; + store::claim_next(pool, 401, job::LEASE) + .await + .unwrap() + .unwrap(); + assert!(store::open_attempt(pool, running, 401).await.unwrap()); + assert_eq!( + store::request_cancel(pool, 1, running).await.unwrap(), + CancelOutcome::Requested + ); + assert_eq!( + store::delete_import(pool, 1, running).await.unwrap(), + DeleteOutcome::Active + ); + expire_lease(pool, running).await; + let log = run_worker(pool, 402).await; + assert!(log.contains("cancelled"), "{log}"); + assert_eq!(db.status(running).await, "cancelled"); + let attempt: String = db + .scalar( + "SELECT status FROM furumusic__library_import_attempt WHERE import_id = $1", + running, + ) + .await; + assert_eq!(attempt, "cancelled"); + + // Deleting the history removes every import row and keeps the target playlist. + let done = db.create(1, "spotify", vec![mixed_playlist("d")]).await; + run_worker(pool, 403).await; + assert_eq!(db.status(done).await, "done"); + let target: i64 = sqlx::query_scalar( + "INSERT INTO furumusic__playlist (owner_id, title) VALUES (1, 'Road trip') RETURNING id", + ) + .fetch_one(pool) + .await + .unwrap(); + sqlx::query( + "UPDATE furumusic__library_import_playlist SET target_playlist_id = $2, target_created_at = now() + WHERE import_id = $1", + ) + .bind(done) + .bind(target) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO furumusic__library_import_publication + (target_playlist_id, content_id, import_playlist_id, item_id, state, position) + SELECT $2, 'content', i.import_playlist_id, i.id, 'published', 0 + 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.id LIMIT 1", + ) + .bind(done) + .bind(target) + .execute(pool) + .await + .unwrap(); + let links = store::list_imports(pool, 1) + .await + .unwrap() + .into_iter() + .find(|import| import.id == done) + .unwrap() + .playlists; + assert_eq!(links[0].target_playlist_id, Some(target)); + assert!(!links[0].target_deleted); + assert_eq!( + store::delete_import(pool, 1, done).await.unwrap(), + DeleteOutcome::Deleted + ); + assert!(store::get_import(pool, 1, done).await.unwrap().is_none()); + for table in [ + "furumusic__library_import_playlist", + "furumusic__library_import_item", + "furumusic__library_import_publication", + ] { + let count: i64 = sqlx::query_scalar(&format!("SELECT count(*) FROM {table}")) + .fetch_one(pool) + .await + .unwrap(); + // Only the two cancelled imports remain: 4 entries each, no receipts. + let expected = match table { + "furumusic__library_import_playlist" => 2, + "furumusic__library_import_item" => 8, + _ => 0, + }; + assert_eq!(count, expected, "{table}"); + } + let attempts: i64 = db + .scalar( + "SELECT count(*) FROM furumusic__library_import_attempt WHERE import_id = $1", + done, + ) + .await; + assert_eq!(attempts, 0); + let kept: i64 = db + .scalar( + "SELECT count(*) FROM furumusic__playlist WHERE id = $1", + target, + ) + .await; + assert_eq!(kept, 1); + + // Deleting a target playlist keeps the import and marks the playlist as deleted. + let other = db.create(1, "spotify", vec![mixed_playlist("e")]).await; + let target: i64 = sqlx::query_scalar( + "INSERT INTO furumusic__playlist (owner_id, title) VALUES (1, 'Other') RETURNING id", + ) + .fetch_one(pool) + .await + .unwrap(); + sqlx::query( + "UPDATE furumusic__library_import_playlist SET target_playlist_id = $2, target_created_at = now() + WHERE import_id = $1", + ) + .bind(other) + .bind(target) + .execute(pool) + .await + .unwrap(); + sqlx::query("DELETE FROM furumusic__playlist WHERE id = $1") + .bind(target) + .execute(pool) + .await + .unwrap(); + let detail = store::get_import(pool, 1, other).await.unwrap().unwrap(); + assert!(detail.source_playlists[0].target_deleted); + assert!(detail.summary.playlists[0].target_deleted); + + // Removing the user removes the import history too. + sqlx::query("DELETE FROM furumusic__user WHERE id = 1") + .execute(pool) + .await + .unwrap(); + let remaining: i64 = db + .scalar( + "SELECT count(*) FROM furumusic__library_import WHERE user_id = $1", + 1, + ) + .await; + assert_eq!(remaining, 0); + db.drop().await; +} diff --git a/src/main.rs b/src/main.rs index a228c43..b65a501 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ mod import_playlists; mod jobs; mod lastfm; mod library_cleanup; +mod library_import; mod local_uploads; mod lyrics; mod media_paths; @@ -69,6 +70,7 @@ fn build_registry() -> Arc { registry.register(jobs::lastfm_popularity::LastfmPopularityJob); registry.register(jobs::lastfm_scrobble::LastfmScrobbleJob); registry.register(podcasts::PodcastRefreshJob); + registry.register(library_import::LibraryImportJob); Arc::new(registry) } @@ -301,6 +303,11 @@ impl App for FuruApp { get(|| async { Ok::<_, cot::Error>(auth::redirect("/admin/")) }), "admin_redirect", ), + Route::with_handler_and_name( + "/imports", + get(|| async { Ok::<_, cot::Error>(auth::redirect("/#imports")) }), + "imports_redirect", + ), Route::with_handler_and_name( "/swagger", get(|| async { Ok::<_, cot::Error>(auth::redirect("/swagger/")) }), @@ -588,6 +595,12 @@ impl Project for FuruProject { similarity::handle().boot(&similarity_config).await; }); + // Resume interrupted imports and restart workers whose lease expired. + library_import::job::spawn_boot( + Arc::clone(&self.app_config), + Arc::clone(&self.scheduler_handle), + ); + let lyrics_config = Arc::clone(&self.app_config); tokio::spawn(async move { lyrics::search::handle().boot(&lyrics_config).await; @@ -614,6 +627,10 @@ impl Project for FuruProject { podcasts::PodcastApp::new(Arc::clone(&self.app_config)), "/api/podcasts", ); + apps.register_with_views( + library_import::ImportApp::new(Arc::clone(&self.app_config)), + "/api/imports", + ); apps.register_with_views( player::PlayerApp::new( Arc::clone(&self.app_config),