use axum::{ extract::{Path, Query, State}, http::StatusCode, response::{IntoResponse, Json}, routing::{get, post}, Router, }; use chrono::Utc; use parking_lot::Mutex; use std::collections::{HashMap, VecDeque}; use std::sync::Arc; use std::time::Duration; use tokio::process::Command; use tracing::{error, info}; use uuid::Uuid; use tower::ServiceBuilder; use tower_http::limit::RequestBodyLimitLayer; mod models; mod utils; use models::*; use utils::*; const MODEL_ID: &str = "english_mfa"; const CLEANUP_INTERVAL: u64 = 5; const JOB_TTL_SECONDS: i64 = 300; const AVG_ALIGN_SECONDS: f64 = 15.0; const MIN_AUDIO_SECONDS: f64 = 0.3; const MAX_AUDIO_SECONDS: f64 = 180.0; const ROLLING_AVG_WINDOW: usize = 10; #[derive(Clone)] struct AppState { jobs: Arc>>, metrics: Arc>, recent_durations: Arc>>, worker_ready: Arc>, } #[tokio::main] async fn main() { tracing_subscriber::fmt::init(); info!("Starting MFA Aligner Rust Service v1.5.0"); let state = AppState { jobs: Arc::new(Mutex::new(HashMap::new())), metrics: Arc::new(Mutex::new(Metrics::new())), recent_durations: Arc::new(Mutex::new(VecDeque::with_capacity(ROLLING_AVG_WINDOW))), worker_ready: Arc::new(Mutex::new(false)), }; // Start cleanup task let cleanup_state = state.clone(); tokio::spawn(async move { cleanup_loop(cleanup_state).await; }); // Start Python worker monitor let worker_state = state.clone(); tokio::spawn(async move { start_python_worker(worker_state).await; }); let app = Router::new() .route("/", get(root)) .route("/health", get(health)) .route("/metrics", get(metrics)) .route("/queue/status", get(queue_status)) .route("/align", post(align_audio)) .route("/job/:job_id", get(get_job)) .route("/result/:job_id", get(get_result)) .route("/cancel/:job_id", post(cancel_job)) .layer( ServiceBuilder::new() .layer(RequestBodyLimitLayer::new(25 * 1024 * 1024)) // 25 MB limit ) .with_state(state); let listener = tokio::net::TcpListener::bind("0.0.0.0:7860").await.unwrap(); info!("Server listening on http://0.0.0.0:7860"); axum::serve(listener, app).await.unwrap(); } async fn cleanup_loop(state: AppState) { loop { tokio::time::sleep(Duration::from_secs(CLEANUP_INTERVAL)).await; let now = Utc::now(); let ttl_cutoff = now - chrono::Duration::seconds(JOB_TTL_SECONDS); let mut jobs = state.jobs.lock(); let terminal_statuses = [ JobStatus::Completed.as_str(), JobStatus::Failed.as_str(), JobStatus::Abandoned.as_str(), ]; jobs.retain(|_, job| { if terminal_statuses.contains(&job.status.as_str()) { if let Some(terminal_at) = job.terminal_at { return terminal_at >= ttl_cutoff; } } true }); promote_queued(&mut jobs); } } async fn start_python_worker(state: AppState) { info!("Starting Python MFA worker process..."); // Give worker time to initialize and warm up tokio::time::sleep(Duration::from_secs(15)).await; let mut worker_ready = state.worker_ready.lock(); *worker_ready = true; info!("Python MFA worker ready"); } fn promote_queued(jobs: &mut HashMap) -> Option { // Check if any running job exists if jobs.values().any(|job| job.status.as_str() == JobStatus::Running.as_str()) { return None; } // Find oldest queued job let mut queued: Vec<_> = jobs .iter() .filter(|(_, job)| job.status.as_str() == JobStatus::Queued.as_str()) .collect(); queued.sort_by_key(|(_, job)| job.created_at); if let Some((job_id, _)) = queued.first() { let job_id = (*job_id).clone(); let job_mut = jobs.get_mut(&job_id).unwrap(); job_mut.status = JobStatus::Running; job_mut.started_at = Some(Utc::now()); info!("Promoted queued job {} → RUNNING", job_id); Some(job_id) } else { None } } fn avg_align_s(state: &AppState) -> f64 { let recent = state.recent_durations.lock(); if recent.is_empty() { AVG_ALIGN_SECONDS } else { (recent.iter().sum::() / recent.len() as f64 * 10.0).round() / 10.0 } } async fn root() -> impl IntoResponse { Json(serde_json::json!({ "name": "MFA Aligner Rust Service", "version": "1.5.0", "status": "ready", "model": MODEL_ID, "endpoints": { "POST /align": "Submit alignment job", "GET /job/{id}": "Unified status + result [preferred]", "GET /job/{id}?slim=true": "Status only — omits word_timestamps (use while polling)", "GET /result/{id}": "Legacy result poll [compat]", "GET /queue/status": "Queue availability", "POST /cancel/{id}": "Explicit job cancellation", "GET /health": "Service health + job counts", "GET /metrics": "Aggregate metrics", } })) } async fn health( State(state): State, ) -> impl IntoResponse { let jobs = state.jobs.lock(); let worker_ready = *state.worker_ready.lock(); let mut counts = serde_json::Map::new(); for status in ["queued", "running", "completed", "failed", "abandoned"] { let count = jobs.values() .filter(|job| job.status.as_str() == status) .count(); counts.insert(status.to_string(), count.into()); } let tmp_free = get_tmp_free_mb(); let shm_ok = tmp_free.map_or(true, |free| free >= 500.0); let overall = if worker_ready && shm_ok { "healthy" } else { "degraded" }; Json(serde_json::json!({ "status": overall, "worker_alive": worker_ready, "worker_ready": worker_ready, "worker_restarting": false, "model": MODEL_ID, "shm_free_mb": tmp_free, "shm_ok": shm_ok, "avg_align_s": avg_align_s(&state), "job_counts": counts, "total_jobs": jobs.len(), })) } async fn metrics( State(state): State, ) -> impl IntoResponse { let metrics = state.metrics.lock(); let total = metrics.total_completed + metrics.total_failed + metrics.total_abandoned; let success_rate = if total > 0 { Some((metrics.total_completed as f64 / total as f64 * 1000.0).round() / 1000.0) } else { None }; let recent: Vec = state.recent_durations.lock().iter().copied().collect(); Json(serde_json::json!({ "uptime_s": metrics.start_time.map(|t| (Utc::now() - t).num_seconds()), "total_submitted": metrics.total_submitted, "total_completed": metrics.total_completed, "total_failed": metrics.total_failed, "total_abandoned": metrics.total_abandoned, "total_cancelled": metrics.total_cancelled, "success_rate": success_rate, "worker_restarts": 0, "avg_align_s": avg_align_s(&state), "recent_durations": recent, })) } async fn queue_status( State(state): State, ) -> impl IntoResponse { let jobs = state.jobs.lock(); let worker_ready = *state.worker_ready.lock(); let running_job = jobs.values() .find(|job| job.status.as_str() == JobStatus::Running.as_str()) .map(|job| job.id.clone()); let queued_job = jobs.values() .find(|job| job.status.as_str() == JobStatus::Queued.as_str()) .map(|job| job.id.clone()); let running_count: u32 = if running_job.is_some() { 1 } else { 0 }; let waiting_count: u32 = if queued_job.is_some() { 1 } else { 0 }; let can_submit = running_count == 0 && waiting_count == 0; let slot_free = running_count == 0; let queue_full = running_count == 1 && waiting_count == 1; let estimated_wait: f64 = if running_job.is_some() { avg_align_s(&state) } else { 0.0 }; Json(serde_json::json!({ // NEW: integer counts the controller reads "running": running_count, "waiting": waiting_count, // Existing fields kept for backwards compat "can_submit": can_submit, "slot_available": slot_free, "queue_full": queue_full, "running_job_id": running_job, "queued_job_id": queued_job, "worker_ready": worker_ready, "estimated_wait_s": estimated_wait, })) } async fn align_audio( State(state): State, Json(req): Json, ) -> impl IntoResponse { // 1. Model check if !*state.worker_ready.lock() { return ( StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({ "error": "Worker unavailable", "error_code": "WORKER_DOWN", "detail": "Model is still loading. Retry in a few seconds.", })), ).into_response(); } // 2. Text validation (MFA strips digits) let cleaned_text = clean_text_mfa(&req.text); if cleaned_text.is_empty() { return ( StatusCode::BAD_REQUEST, Json(serde_json::json!({ "error": "Invalid text", "error_code": "TEXT_EMPTY", "detail": "Text is empty after normalisation.", })), ).into_response(); } // 3. Audio validation let (wav_normalised, audio_duration) = match validate_audio(&req.audio_base64) { Ok(result) => result, Err(response) => return response.into_response(), }; // 4. SHM space check if let Some(free_mb) = get_tmp_free_mb() { if free_mb < 500.0 { return ( StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({ "error": "Insufficient RAM", "error_code": "SHM_FULL", "detail": format!("Only {} MB free in /dev/shm (minimum 500 MB).", free_mb), })), ).into_response(); } } // Phase 1: check queue state and duplicate — lock held, no .await let (running_exists, queued_exists, duplicate_warning) = { let jobs = state.jobs.lock(); let running_exists = jobs.values().any(|job| job.status.as_str() == JobStatus::Running.as_str()); let queued_exists = jobs.values().any(|job| job.status.as_str() == JobStatus::Queued.as_str()); // 5. Queue full check if running_exists && queued_exists { let wait = avg_align_s(&state); return ( StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({ "error": "Service busy", "error_code": "QUEUE_FULL", "detail": "One job running, one already queued. Retry after current jobs finish.", "retry_after": wait, })), ).into_response(); } // 6. Duplicate client check let client_id_ref = req.client_id.as_ref(); let duplicate_warning = if let Some(client_id) = client_id_ref { jobs.values() .find(|job| { job.client_id.as_ref() == Some(client_id) && (job.status.as_str() == JobStatus::Running.as_str() || job.status.as_str() == JobStatus::Queued.as_str()) }) .map(|existing| { serde_json::json!({ "message": "You already have an active job.", "existing_job_id": existing.id.clone(), "existing_status": existing.status.as_str(), }) }) } else { None }; (running_exists, queued_exists, duplicate_warning) // lock released here — BEFORE the .await below }; let client_id = req.client_id.clone(); // 7. Write audio to temp file (.await — lock is NOT held) let job_id = Uuid::new_v4().to_string()[..12].to_string(); let temp_path = format!("/dev/shm/tmp_{}.wav", job_id); if let Err(e) = tokio::fs::write(&temp_path, wav_normalised).await { return ( StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({ "error": "Storage error", "error_code": "SHM_WRITE_ERROR", "detail": format!("Could not write audio to /dev/shm: {}", e), })), ).into_response(); } // 8. Create job let status = if running_exists { JobStatus::Queued } else { JobStatus::Running }; let queue_position = if status == JobStatus::Queued { 1 } else { 0 }; let now = Utc::now(); // FIX 1: Extract client_id before constructing Job so we can log it after the move. let job_client_id_for_log = client_id.clone(); let job = Job { id: job_id.clone(), request: req.clone(), status: status.clone(), created_at: now, started_at: if status == JobStatus::Running { Some(now) } else { None }, terminal_at: None, result: None, error: None, client_id, audio_duration: (audio_duration * 100.0).round() / 100.0, wav_path: temp_path, cleaned_text, }; // Phase 2: re-acquire lock to insert job (after the .await is done) let mut jobs = state.jobs.lock(); jobs.insert(job_id.clone(), job); // job is moved here — do NOT use `job` after this line let mut metrics = state.metrics.lock(); metrics.total_submitted += 1; // FIX 1 (continued): Use the pre-extracted copy instead of `job.client_id` info!( "Job {} created — status={}, duration={:.1}s, client={:?}", job_id, status.as_str(), audio_duration, job_client_id_for_log ); drop(metrics); drop(jobs); // If running, start alignment if status == JobStatus::Running { let state_clone = state.clone(); let job_id_clone = job_id.clone(); tokio::spawn(async move { run_alignment(state_clone, job_id_clone).await; }); } let mut response = serde_json::json!({ "job_id": job_id, "status": status.as_str(), "queue_position": queue_position, "poll_url": format!("/job/{}", job_id), "estimated_wait_s": if status == JobStatus::Running { 0.0 } else { avg_align_s(&state) }, "audio_duration_s": (audio_duration * 100.0).round() / 100.0, "message": if status == JobStatus::Running { format!("Job started. Poll GET /job/{}.", job_id) } else { format!("Job queued at position 1. Poll GET /job/{} every 2 s.", job_id) }, }); if let Some(warning) = duplicate_warning { response["duplicate_warning"] = warning; } (StatusCode::OK, Json(response)).into_response() } async fn run_alignment(state: AppState, job_id: String) { info!("[{}] Starting MFA alignment", job_id); // Get job data let (wav_path, cleaned_text, req) = { let jobs = state.jobs.lock(); let job = jobs.get(&job_id).unwrap(); (job.wav_path.clone(), job.cleaned_text.clone(), job.request.clone()) }; let start = std::time::Instant::now(); // Call Python MFA worker let output = Command::new("python3") .arg("worker_mfa.py") .arg(&wav_path) .arg(&cleaned_text) .arg(&req.language) .output() .await; // Clean up temp file let _ = tokio::fs::remove_file(&wav_path).await; let duration = start.elapsed().as_secs_f64(); match output { Ok(output) if output.status.success() => { match serde_json::from_slice::>(&output.stdout) { Ok(word_timestamps) => { info!("[{}] Done — {} words in {:.2}s", job_id, word_timestamps.len(), duration); let mut jobs = state.jobs.lock(); if let Some(job) = jobs.get_mut(&job_id) { if job.status.as_str() == JobStatus::Running.as_str() { job.status = JobStatus::Completed; job.result = Some(word_timestamps); job.terminal_at = Some(Utc::now()); let mut metrics = state.metrics.lock(); metrics.total_completed += 1; let mut recent = state.recent_durations.lock(); recent.push_back(duration); if recent.len() > ROLLING_AVG_WINDOW { recent.pop_front(); } } } } Err(e) => { error!("[{}] Failed to parse worker output: {}", job_id, e); let mut jobs = state.jobs.lock(); if let Some(job) = jobs.get_mut(&job_id) { if job.status.as_str() == JobStatus::Running.as_str() { job.status = JobStatus::Failed; job.error = Some(format!("Failed to parse alignment result: {}", e)); job.terminal_at = Some(Utc::now()); let mut metrics = state.metrics.lock(); metrics.total_failed += 1; } } } } } Ok(output) => { let error = String::from_utf8_lossy(&output.stderr); error!("[{}] Alignment failed: {}", job_id, error); let mut jobs = state.jobs.lock(); if let Some(job) = jobs.get_mut(&job_id) { if job.status.as_str() == JobStatus::Running.as_str() { job.status = JobStatus::Failed; job.error = Some(format!("Alignment failed: {}", error)); job.terminal_at = Some(Utc::now()); let mut metrics = state.metrics.lock(); metrics.total_failed += 1; } } } Err(e) => { error!("[{}] Failed to execute worker: {}", job_id, e); let mut jobs = state.jobs.lock(); if let Some(job) = jobs.get_mut(&job_id) { if job.status.as_str() == JobStatus::Running.as_str() { job.status = JobStatus::Failed; job.error = Some(format!("Failed to execute worker: {}", e)); job.terminal_at = Some(Utc::now()); let mut metrics = state.metrics.lock(); metrics.total_failed += 1; } } } } // Promote next queued job let mut jobs = state.jobs.lock(); promote_queued(&mut jobs); } async fn get_job( State(state): State, Path(job_id): Path, Query(params): Query, ) -> impl IntoResponse { let jobs = state.jobs.lock(); let job = match jobs.get(&job_id) { Some(job) => job, None => { return ( StatusCode::NOT_FOUND, Json(serde_json::json!({ "error": "Job not found", "error_code": "JOB_NOT_FOUND", "detail": "Job may have been purged (TTL=5 min) or never existed.", })), ).into_response(); } }; let response = job_view(job, params.slim.unwrap_or(false), avg_align_s(&state)); (StatusCode::OK, Json(response)).into_response() } async fn get_result( State(state): State, Path(job_id): Path, ) -> impl IntoResponse { let jobs = state.jobs.lock(); let job = match jobs.get(&job_id) { Some(job) => job, None => { return ( StatusCode::NOT_FOUND, Json(serde_json::json!({ "error": "Job not found", "error_code": "JOB_NOT_FOUND", })), ).into_response(); } }; let response = job_view(job, false, avg_align_s(&state)); (StatusCode::OK, Json(response)).into_response() } async fn cancel_job( State(state): State, Path(job_id): Path, Json(body): Json, ) -> impl IntoResponse { // FIX 2 & 3: Extract everything we need from the locked map BEFORE any .await, // then release the lock, do the async work, and re-acquire to mutate. // parking_lot::MutexGuard is !Send, so holding it across an .await point // prevents the future from being Send, which breaks the axum Handler bound. // --- Phase 1: validate & extract (no .await, lock held briefly) --- let (was_running, wav_path) = { let mut jobs = state.jobs.lock(); let job = match jobs.get_mut(&job_id) { Some(job) => job, None => { return ( StatusCode::NOT_FOUND, Json(serde_json::json!({ "error": "Job not found", "error_code": "JOB_NOT_FOUND", })), ).into_response(); } }; // Client ID check if let Some(stored) = &job.client_id { if body.client_id.is_none() || body.client_id.as_ref() != Some(stored) { return ( StatusCode::FORBIDDEN, Json(serde_json::json!({ "error": "Client ID mismatch", "error_code": "FORBIDDEN", "detail": "You are not the owner of this job.", })), ).into_response(); } } let terminal_statuses = [ JobStatus::Completed.as_str(), JobStatus::Failed.as_str(), JobStatus::Abandoned.as_str(), ]; if terminal_statuses.contains(&job.status.as_str()) { return Json(serde_json::json!({ "cancelled": false, "status": job.status.as_str(), "message": format!("Job was already {} — nothing to cancel.", job.status.as_str()), })).into_response(); } let was_running = job.status.as_str() == JobStatus::Running.as_str(); let wav_path = job.wav_path.clone(); // Mark cancelled while we still hold the lock (no .await needed here) job.status = JobStatus::Abandoned; job.error = Some("Cancelled by client".to_string()); job.terminal_at = Some(Utc::now()); (was_running, wav_path) // lock is released here (end of block) }; // --- Phase 2: async I/O — lock is NOT held --- if was_running { let _ = tokio::fs::remove_file(&wav_path).await; } // --- Phase 3: update metrics & promote (no .await, lock held briefly) --- { let mut metrics = state.metrics.lock(); metrics.total_cancelled += 1; } info!("Job {} cancelled ({})", job_id, if was_running { "RUNNING" } else { "QUEUED" }); { let mut jobs = state.jobs.lock(); promote_queued(&mut jobs); } Json(serde_json::json!({ "cancelled": true, "job_id": job_id, "restarting": false, "message": "Job cancelled.", })).into_response() }