diff --git a/src/api/identity_api.rs b/src/api/identity_api.rs index 8d8309e8..09dbc2c7 100644 --- a/src/api/identity_api.rs +++ b/src/api/identity_api.rs @@ -129,6 +129,7 @@ async fn list_files( file_size: None, modified_time: None, thumbnail_url: None, + job_status: None, }] } else { vec![] @@ -223,6 +224,7 @@ async fn list_files( file_size, modified_time, thumbnail_url: None, + job_status: None, }); } else { // Not registered: use MarkBase file_path if available @@ -261,6 +263,7 @@ async fn list_files( file_size, modified_time, thumbnail_url: None, + job_status: None, }); } } @@ -289,6 +292,7 @@ async fn list_files( file_size, modified_time, thumbnail_url: None, + job_status: None, }); } } @@ -317,6 +321,7 @@ async fn list_files( modified_time: meta.and_then(|m| m.modified().ok()) .map(|t| chrono::DateTime::::from(t).to_rfc3339()), thumbnail_url: None, + job_status: None, }); } } @@ -362,11 +367,50 @@ async fn list_files( count_map = chunk_counts.into_iter().collect(); } + // Fetch job status counts for all files + let monitor_jobs_table = crate::core::db::schema::table_name("monitor_jobs"); + let mut job_status_map: std::collections::HashMap = std::collections::HashMap::new(); + + + if !uuids.is_empty() { + // Build query with proper bindings + let placeholders: Vec = (1..=uuids.len()).map(|i| format!("${}", i)).collect(); + let job_query = format!( + "SELECT uuid, status, COUNT(*) as cnt FROM {mj_t} WHERE uuid IN ({}) GROUP BY uuid, status", + placeholders.join(", "), + mj_t = monitor_jobs_table + ); + + let mut query = sqlx::query_as::<_, (String, String, i64)>(&job_query); + for uuid in &uuids { + query = query.bind(uuid); + } + + let job_counts: Vec<(String, String, i64)> = query + .fetch_all(state.db.pool()) + .await + .unwrap_or_default(); + + + // Group by uuid: {pending: N, running: N, completed: N} + let mut temp_map: std::collections::HashMap> = std::collections::HashMap::new(); + for (uuid, status, cnt) in job_counts { + let entry = temp_map.entry(uuid).or_default(); + entry.insert(status, serde_json::Value::Number(serde_json::Number::from(cnt))); + } + for (uuid, map) in temp_map { + job_status_map.insert(uuid, serde_json::Value::Object(map)); + } + } + let mut data = data; for item in &mut data { if let Some(cnt) = count_map.get(&item.file_uuid) { item.total_chunks = *cnt; } + if let Some(js) = job_status_map.get(&item.file_uuid) { + item.job_status = Some(js.clone()); + } } Ok(Json(FilesResponse { @@ -412,6 +456,9 @@ pub struct FileItem { pub modified_time: Option, #[serde(skip_serializing_if = "Option::is_none")] pub thumbnail_url: Option, + /// Job status summary: {pending: N, running: N, completed: N} + #[serde(skip_serializing_if = "Option::is_none")] + pub job_status: Option, } #[derive(Debug, Serialize)] diff --git a/src/api/job_management.rs b/src/api/job_management.rs index c0a20127..25a5ec1e 100644 --- a/src/api/job_management.rs +++ b/src/api/job_management.rs @@ -9,6 +9,7 @@ use axum::{ }; use serde::{Deserialize, Serialize}; use std::collections::HashSet; +use sqlx::Row; use super::types::AppState; use crate::core::db::schema; @@ -20,6 +21,10 @@ pub fn job_management_routes() -> Router { .route("/api/v1/jobs/paused", get(list_paused_jobs)) .route("/api/v1/jobs/:uuid/status", get(get_job_status)) .route("/api/v1/admin/sync-status", post(sync_all_statuses)) + .route("/api/v1/jobs/queue", get(list_queue_jobs)) + .route("/api/v1/jobs/:uuid/cancel", post(cancel_job)) + .route("/api/v1/jobs/:uuid/priority", post(set_job_priority)) + .route("/api/v1/jobs/queue/clear", post(clear_queue_jobs)) } #[derive(Debug, Serialize)] @@ -362,3 +367,331 @@ async fn sync_all_statuses( message: format!("Found {} mismatches, fixed {}", mismatch_count, fixed), })) } + +// ─── Queue Management: list, cancel, priority ───────────────────────────────── + +#[derive(Debug, Serialize)] +pub struct QueueJob { + pub job_id: i32, + pub uuid: String, + pub file_name: String, + pub status: String, + pub created_at: Option, + pub updated_at: Option, + /// Processor completion summary from processor_results + pub processors_total: i64, + pub processors_completed: i64, + pub processors_running: i64, + pub processors_pending: i64, + pub processors_failed: i64, +} + +#[derive(Debug, Serialize)] +pub struct QueueResponse { + pub jobs: Vec, + pub summary: serde_json::Value, +} + +/// GET /api/v1/jobs/queue +/// List all jobs in the queue with their processor status. +/// Query params: status (filter), limit (default 100) +async fn list_queue_jobs( + State(state): State, + axum::extract::Query(params): axum::extract::Query>, +) -> Result, (StatusCode, String)> { + let monitor_jobs_table = schema::table_name("monitor_jobs"); + let videos_table = schema::table_name("videos"); + let pr_table = schema::table_name("processor_results"); + + let status_filter = params.get("status").cloned().unwrap_or_default(); + let limit: i64 = params.get("limit").and_then(|v| v.parse().ok()).unwrap_or(100); + + let status_clause = if status_filter.is_empty() { + String::new() + } else { + format!("WHERE mj.status = '{}'", status_filter.replace('\'', "")) + }; + + let rows = sqlx::query(&format!( + "SELECT mj.id::text, mj.uuid, v.file_name, mj.status, + mj.created_at::text, COALESCE(mj.updated_at::text, ''), + COALESCE(pr.total, 0), COALESCE(pr.completed, 0), + COALESCE(pr.running, 0), COALESCE(pr.pending, 0), COALESCE(pr.failed, 0) + FROM {mj_t} mj + LEFT JOIN {v_t} v ON v.file_uuid = mj.uuid + LEFT JOIN ( + SELECT job_id, + COUNT(*) as total, + COUNT(*) FILTER (WHERE status = 'completed') as completed, + COUNT(*) FILTER (WHERE status = 'running') as running, + COUNT(*) FILTER (WHERE status = 'pending') as pending, + COUNT(*) FILTER (WHERE status = 'failed') as failed + FROM {pr_t} + GROUP BY job_id + ) pr ON pr.job_id = mj.id + {status_clause} + ORDER BY mj.created_at DESC + LIMIT $1", + mj_t = monitor_jobs_table, + v_t = videos_table, + pr_t = pr_table, + status_clause = status_clause, + )) + .bind(limit) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + tracing::error!("[Queue] query failed: {}", e); + (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()) + })?; + + let mut jobs = Vec::new(); + for row in rows { + jobs.push(QueueJob { + job_id: row.try_get::("id").unwrap_or_default().parse().unwrap_or(0), + uuid: row.try_get::("uuid").unwrap_or_default(), + file_name: row.try_get::("file_name").unwrap_or_else(|_| "(unknown)".to_string()), + status: row.try_get::("status").unwrap_or_default(), + created_at: row.try_get::("created_at").ok(), + updated_at: row.try_get::("updated_at").ok(), + processors_total: row.try_get::("total").unwrap_or(0), + processors_completed: row.try_get::("completed").unwrap_or(0), + processors_running: row.try_get::("running").unwrap_or(0), + processors_pending: row.try_get::("pending").unwrap_or(0), + processors_failed: row.try_get::("failed").unwrap_or(0), + }); + } + + // Summary counts + let summary_rows: Vec<(String, i64)> = sqlx::query_as(&format!( + "SELECT status, COUNT(*) FROM {mj_t} GROUP BY status", + mj_t = monitor_jobs_table + )) + .fetch_all(state.db.pool()) + .await + .unwrap_or_default(); + + let mut summary = serde_json::Map::new(); + for (status, count) in summary_rows { + summary.insert(status, serde_json::Value::Number(serde_json::Number::from(count))); + } + + Ok(Json(QueueResponse { + jobs, + summary: serde_json::Value::Object(summary), + })) +} + +/// POST /api/v1/jobs/:uuid/cancel +/// Cancel a pending/paused job: delete monitor_jobs + processor_results, reset video status. +async fn cancel_job( + State(state): State, + Path(uuid): Path, +) -> Result, (StatusCode, Json)> { + let monitor_jobs_table = schema::table_name("monitor_jobs"); + let pr_table = schema::table_name("processor_results"); + let videos_table = schema::table_name("videos"); + + // Check current status — only pending/paused/running jobs can be cancelled + let status: Option = sqlx::query_scalar(&format!( + "SELECT status FROM {mj_t} WHERE uuid = $1", + mj_t = monitor_jobs_table + )) + .bind(&uuid) + .fetch_optional(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })? + .flatten(); + + let status = match status { + Some(s) => s, + None => { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Job not found"})), + )) + } + }; + + if status == "completed" { + return Err(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "Cannot cancel a completed job"})), + )); + } + + // Delete processor_results + sqlx::query(&format!( + "DELETE FROM {pr_t} WHERE job_id IN (SELECT id FROM {mj_t} WHERE uuid = $1)", + pr_t = pr_table, + mj_t = monitor_jobs_table + )) + .bind(&uuid) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + // Delete monitor_jobs + sqlx::query(&format!( + "DELETE FROM {mj_t} WHERE uuid = $1", + mj_t = monitor_jobs_table + )) + .bind(&uuid) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + // Reset video status + sqlx::query(&format!( + "UPDATE {v_t} SET status = 'registered', updated_at = NOW() WHERE file_uuid = $1", + v_t = videos_table + )) + .bind(&uuid) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + tracing::info!("[Queue] Cancelled job for {} (was {})", uuid, status); + + Ok(Json(serde_json::json!({ + "success": true, + "message": format!("Job cancelled (was {})", status), + "uuid": uuid + }))) +} + +/// POST /api/v1/jobs/:uuid/priority +/// Move a pending job to the front of the queue (oldest created_at). +async fn set_job_priority( + State(state): State, + Path(uuid): Path, + axum::Json(body): axum::Json, +) -> Result, (StatusCode, Json)> { + let monitor_jobs_table = schema::table_name("monitor_jobs"); + + let action = body.get("action").and_then(|v| v.as_str()).unwrap_or("front"); + + let result = sqlx::query(&format!( + "UPDATE {mj_t} SET created_at = CASE WHEN $1 = 'front' THEN NOW() - INTERVAL '1 hour' ELSE NOW() END, updated_at = NOW() WHERE uuid = $2 AND status = 'pending'", + mj_t = monitor_jobs_table + )) + .bind(action) + .bind(&uuid) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + if result.rows_affected() == 0 { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Pending job not found"})), + )); + } + + tracing::info!("[Queue] Job {} priority set to {}", uuid, action); + + Ok(Json(serde_json::json!({ + "success": true, + "message": format!("Job priority: {}", action), + "uuid": uuid + }))) +} + +/// POST /api/v1/jobs/queue/clear +/// Bulk-clear queued jobs by status: delete monitor_jobs + processor_results, +/// reset video status to 'registered'. Body: { status: "pending" | "paused" | "all" } +async fn clear_queue_jobs( + State(state): State, + axum::Json(body): axum::Json, +) -> Result, (StatusCode, Json)> { + let monitor_jobs_table = schema::table_name("monitor_jobs"); + let pr_table = schema::table_name("processor_results"); + let videos_table = schema::table_name("videos"); + + let target = body.get("status").and_then(|v| v.as_str()).unwrap_or("pending"); + let status_clause = match target { + "pending" => "WHERE mj.status = 'pending'".to_string(), + "paused" => "WHERE mj.status = 'paused'".to_string(), + "all" => "WHERE mj.status != 'completed'".to_string(), + _ => { + return Err(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "status must be pending/paused/all"})), + )) + } + }; + + // Collect affected uuids first + let uuids: Vec = sqlx::query_scalar(&format!( + "SELECT mj.uuid FROM {mj_t} mj {sc}", + mj_t = monitor_jobs_table, + sc = status_clause + )) + .fetch_all(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + if uuids.is_empty() { + return Ok(Json(serde_json::json!({ + "success": true, "cleared": 0, "message": "No matching jobs" + }))); + } + + // Delete processor_results + sqlx::query(&format!( + "DELETE FROM {pr_t} WHERE job_id IN (SELECT id FROM {mj_t} WHERE uuid = ANY($1))", + pr_t = pr_table, + mj_t = monitor_jobs_table + )) + .bind(&uuids) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + // Delete monitor_jobs + sqlx::query(&format!( + "DELETE FROM {mj_t} WHERE uuid = ANY($1)", + mj_t = monitor_jobs_table + )) + .bind(&uuids) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + // Reset video status + sqlx::query(&format!( + "UPDATE {v_t} SET status = 'registered', updated_at = NOW() WHERE file_uuid = ANY($1) AND status NOT IN ('completed')", + v_t = videos_table + )) + .bind(&uuids) + .execute(state.db.pool()) + .await + .map_err(|e| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))) + })?; + + let cleared = uuids.len(); + tracing::info!("[Queue] Cleared {} {} jobs", cleared, target); + + Ok(Json(serde_json::json!({ + "success": true, + "cleared": cleared, + "message": format!("Cleared {} {} jobs", cleared, target) + }))) +}