Files
furumi-web/src/library_import/job.rs
T
sanapachandClaude Opus 5.5 097812a845 Store library imports and run them as a resumable background job
Add the library_import subsystem core: migration m_0065 with the import,
playlist, item, publication-receipt and attempt tables, the provider-neutral
import model, the adapter trait and the storage layer.

The library_import job claims imports under a two-minute lease that a
heartbeat renews, checks cancellation between phases and resumes an
interrupted import from its stored phase. Matching and publication phases
are placeholders for the following changes. At boot, imports of the previous
process are requeued; a sweeper starts a worker whenever an import waits
without one, so a worker that stops without a server restart is replaced
once its lease expires.

The /api/imports endpoints list the user's imports, show one import with
its playlists and paged entries, cancel it and delete its history while
keeping the created playlists. Every request is scoped to the owner.
GET /imports redirects to the player view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:05:42 +02:00

347 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `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<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<()> {
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<AppConfig>,
run_id: i64,
}
/// 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,
}
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<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 => 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<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"),
}
}
});
}