forked from Furumi/furumi-web
Add the Spotify adapter to the library import. The data export path parses Playlist*.json and YourLibrary.json sent by the browser, tolerates missing and unexpected keys, keeps the source order and repeats, and stores episodes, audiobooks, local files and unreadable entries as unsupported instead of dropping them. The bundled export fixture is synthetic and must be joined by an anonymized real export before acceptance. POST /api/imports/preview lists the playlists of an upload and marks those already imported or similar to an earlier import; POST /api/imports stores the selected playlists with every entry in one transaction and starts the worker. Requests are JSON-only and limited to 32 MiB (413). Re-import is detected per source playlist: a repeat is refused with 409, and a changed playlist with the same title needs confirm_similar. The Spotify Web API is optional and enabled by an administrator's client ID (and redirect URI behind a proxy) in the settings. Sign-in uses PKCE with the state, verifier and waiting import kept in the session; access tokens stay only in an in-memory vault for at most 30 minutes. The worker fetches the selected playlists one by one, honors Retry-After and backs off on server errors. A missing or expired token parks the import as needs_reauth; signing in again with the same account continues the same import and skips the playlists already fetched. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
445 lines
16 KiB
Rust
445 lines
16 KiB
Rust
//! `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::providers::{FetchError, LibraryFetcher, ProviderFetchers, TokenVault};
|
||
use super::store::{self, ClaimedImport, Control, FinishOutcome, NewItem};
|
||
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<Self> {
|
||
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<AppConfig>,
|
||
run_id: i64,
|
||
log: &mut JobLog,
|
||
) -> Result<()> {
|
||
run_worker_with(pool, config, run_id, log, Arc::new(ProviderFetchers)).await
|
||
}
|
||
|
||
/// [`run_worker`] with the provider API client given by the caller.
|
||
pub async fn run_worker_with(
|
||
pool: &PgPool,
|
||
config: Arc<AppConfig>,
|
||
run_id: i64,
|
||
log: &mut JobLog,
|
||
fetcher: Arc<dyn LibraryFetcher>,
|
||
) -> 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,
|
||
fetcher,
|
||
};
|
||
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<AppConfig>,
|
||
run_id: i64,
|
||
fetcher: Arc<dyn LibraryFetcher>,
|
||
}
|
||
|
||
/// Renews the lease in the background while the worker owns an import.
|
||
struct Heartbeat {
|
||
task: tokio::task::JoinHandle<()>,
|
||
lost: Arc<AtomicBool>,
|
||
}
|
||
|
||
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,
|
||
/// The provider token is missing or expired; the user signs in again.
|
||
NeedsReauth,
|
||
}
|
||
|
||
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)) => {
|
||
TokenVault::shared().forget_import(import.id);
|
||
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::NeedsReauth)) => {
|
||
if store::wait_for_reauth(&self.pool, import.id, self.run_id).await? {
|
||
log.info(&format!(
|
||
"Library import {}: waiting for the user to sign in to {} again",
|
||
import.id, import.provider
|
||
));
|
||
}
|
||
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<Phase>,
|
||
heartbeat: &Heartbeat,
|
||
log: &mut JobLog,
|
||
) -> Result<Option<Stop>> {
|
||
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 => {
|
||
if let Some(stop) = self.fetch(import, heartbeat, log).await? {
|
||
return Ok(Some(stop));
|
||
}
|
||
}
|
||
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)
|
||
}
|
||
|
||
/// Fetches the entries of the selected playlists of an API import. Each
|
||
/// playlist is stored with its `fetched_at` in one transaction, so a
|
||
/// continued import skips the playlists it already has. The token is
|
||
/// dropped once everything is fetched.
|
||
async fn fetch(
|
||
&self,
|
||
import: &ClaimedImport,
|
||
heartbeat: &Heartbeat,
|
||
log: &mut JobLog,
|
||
) -> Result<Option<Stop>> {
|
||
let vault = TokenVault::shared();
|
||
let pending = store::playlists_to_fetch(&self.pool, import.id).await?;
|
||
if pending.is_empty() {
|
||
vault.forget_import(import.id);
|
||
return Ok(None);
|
||
}
|
||
let Some(token) = vault.import_token(import.id) else {
|
||
return Ok(Some(Stop::NeedsReauth));
|
||
};
|
||
let (mut fetched, mut refused, mut entries) = (0usize, 0usize, 0usize);
|
||
for playlist in &pending {
|
||
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)),
|
||
}
|
||
let tracks = match self
|
||
.fetcher
|
||
.fetch_playlist(&import.provider, &token, &playlist.target)
|
||
.await
|
||
{
|
||
Ok(tracks) => tracks,
|
||
Err(FetchError::Unauthorized) => {
|
||
vault.forget_import(import.id);
|
||
return Ok(Some(Stop::NeedsReauth));
|
||
}
|
||
// Development Mode refuses playlists of other owners, and a
|
||
// playlist may be gone; it stays in the import without entries.
|
||
Err(FetchError::Forbidden | FetchError::NotFound) => {
|
||
refused += 1;
|
||
Vec::new()
|
||
}
|
||
Err(error) => return Err(error.into()),
|
||
};
|
||
let items: Vec<NewItem> = tracks
|
||
.iter()
|
||
.map(|track| NewItem::from_track(track, super::model::artist_key(track)))
|
||
.collect();
|
||
if !store::store_fetched(
|
||
&self.pool,
|
||
import.id,
|
||
self.run_id,
|
||
playlist.playlist_id,
|
||
&items,
|
||
)
|
||
.await?
|
||
{
|
||
return Ok(Some(Stop::LeaseLost));
|
||
}
|
||
fetched += 1;
|
||
entries += items.len();
|
||
}
|
||
vault.forget_import(import.id);
|
||
log.info(&format!(
|
||
"Library import {}: fetched {fetched} playlists with {entries} entries ({refused} not readable)",
|
||
import.id
|
||
));
|
||
Ok(None)
|
||
}
|
||
|
||
/// 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<bool> {
|
||
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<AppConfig>,
|
||
scheduler: Arc<tokio::sync::OnceCell<Arc<SchedulerHandle>>>,
|
||
) {
|
||
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"),
|
||
}
|
||
}
|
||
});
|
||
}
|