feat: add status sync trigger and status query APIs
- Created PostgreSQL trigger to sync videos.status with monitor_jobs.status - Added GET /api/v1/jobs/:uuid/status endpoint - Added POST /api/v1/admin/sync-status endpoint for batch sync - Status mapping: paused→paused, pending→registered, running→processing, completed→completed, failed→failed - Migration file: 008_sync_video_status_trigger.sql
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
-- Migration 008: Status Sync Trigger
|
||||
-- Synchronizes videos.status with monitor_jobs.status
|
||||
-- Date: 2026-10-18
|
||||
-- Purpose: Ensure videos.status always reflects monitor_jobs.status (single source of truth)
|
||||
|
||||
-- ── Step 1: Create the trigger function ──
|
||||
|
||||
CREATE OR REPLACE FUNCTION sync_video_status()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Prevent recursive triggers
|
||||
IF pg_trigger_depth() > 1 THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Map monitor_jobs.status → videos.status
|
||||
CASE NEW.status
|
||||
WHEN 'paused' THEN
|
||||
UPDATE videos
|
||||
SET status = 'paused', updated_at = NOW()
|
||||
WHERE file_uuid = NEW.uuid;
|
||||
WHEN 'pending' THEN
|
||||
UPDATE videos
|
||||
SET status = 'registered', updated_at = NOW()
|
||||
WHERE file_uuid = NEW.uuid;
|
||||
WHEN 'running' THEN
|
||||
UPDATE videos
|
||||
SET status = 'processing', updated_at = NOW()
|
||||
WHERE file_uuid = NEW.uuid;
|
||||
WHEN 'completed' THEN
|
||||
UPDATE videos
|
||||
SET status = 'completed', updated_at = NOW()
|
||||
WHERE file_uuid = NEW.uuid;
|
||||
WHEN 'failed' THEN
|
||||
UPDATE videos
|
||||
SET status = 'failed', updated_at = NOW()
|
||||
WHERE file_uuid = NEW.uuid;
|
||||
-- For any other status, keep videos.status unchanged
|
||||
ELSE
|
||||
NULL;
|
||||
END CASE;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ── Step 2: Create the trigger ──
|
||||
|
||||
DROP TRIGGER IF EXISTS trigger_sync_video_status ON monitor_jobs;
|
||||
|
||||
CREATE TRIGGER trigger_sync_video_status
|
||||
AFTER UPDATE OF status ON monitor_jobs
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION sync_video_status();
|
||||
|
||||
-- ── Step 3: Fix existing inconsistent data ──
|
||||
|
||||
-- Synchronize videos.status with monitor_jobs.status for all existing records
|
||||
UPDATE videos v
|
||||
SET status = CASE mj.status
|
||||
WHEN 'paused' THEN 'paused'
|
||||
WHEN 'pending' THEN 'registered'
|
||||
WHEN 'running' THEN 'processing'
|
||||
WHEN 'completed' THEN 'completed'
|
||||
WHEN 'failed' THEN 'failed'
|
||||
ELSE v.status
|
||||
END,
|
||||
updated_at = NOW()
|
||||
FROM monitor_jobs mj
|
||||
WHERE v.file_uuid = mj.uuid
|
||||
AND v.status != CASE mj.status
|
||||
WHEN 'paused' THEN 'paused'
|
||||
WHEN 'pending' THEN 'registered'
|
||||
WHEN 'running' THEN 'processing'
|
||||
WHEN 'completed' THEN 'completed'
|
||||
WHEN 'failed' THEN 'failed'
|
||||
ELSE v.status
|
||||
END;
|
||||
|
||||
-- ── Step 4: Add index for performance ──
|
||||
|
||||
-- Index for faster lookups by uuid
|
||||
CREATE INDEX IF NOT EXISTS idx_monitor_jobs_uuid ON monitor_jobs(uuid);
|
||||
|
||||
-- ── Comments ──
|
||||
|
||||
COMMENT ON FUNCTION sync_video_status() IS 'Synchronizes videos.status with monitor_jobs.status after updates. Prevents recursive triggers.';
|
||||
COMMENT ON TRIGGER trigger_sync_video_status ON monitor_jobs IS 'After status update on monitor_jobs, sync videos.status accordingly.';
|
||||
@@ -18,6 +18,8 @@ pub fn job_management_routes() -> Router<AppState> {
|
||||
.route("/api/v1/jobs/:uuid/pause", post(pause_job))
|
||||
.route("/api/v1/jobs/:uuid/resume", post(resume_job))
|
||||
.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))
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -243,3 +245,120 @@ async fn list_paused_jobs(
|
||||
total,
|
||||
}))
|
||||
}
|
||||
|
||||
// ── New APIs for status synchronization ──
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct JobStatusResponse {
|
||||
pub uuid: String,
|
||||
pub monitor_status: String,
|
||||
pub video_status: String,
|
||||
pub is_consistent: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SyncStatusResponse {
|
||||
pub success: bool,
|
||||
pub mismatches_found: usize,
|
||||
pub mismatches_fixed: usize,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// GET /api/v1/jobs/:uuid/status
|
||||
/// Returns consistent status information from both monitor_jobs and videos tables.
|
||||
async fn get_job_status(
|
||||
State(state): State<AppState>,
|
||||
Path(uuid): Path<String>,
|
||||
) -> Result<Json<JobStatusResponse>, StatusCode> {
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
let videos_table = schema::table_name("videos");
|
||||
|
||||
// Get status from both tables
|
||||
let row: Option<(String, String)> = sqlx::query_as(&format!(
|
||||
"SELECT mj.status, v.status
|
||||
FROM {} mj
|
||||
LEFT JOIN {} v ON mj.uuid = v.file_uuid
|
||||
WHERE mj.uuid = $1",
|
||||
monitor_jobs_table, videos_table
|
||||
))
|
||||
.bind(&uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
match row {
|
||||
Some((mj_status, v_status)) => {
|
||||
let is_consistent = mj_status == v_status
|
||||
|| (mj_status == "paused" && v_status == "paused")
|
||||
|| (mj_status == "pending" && v_status == "registered")
|
||||
|| (mj_status == "running" && v_status == "processing");
|
||||
|
||||
Ok(Json(JobStatusResponse {
|
||||
uuid,
|
||||
monitor_status: mj_status,
|
||||
video_status: v_status,
|
||||
is_consistent,
|
||||
}))
|
||||
}
|
||||
None => Err(StatusCode::NOT_FOUND),
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/admin/sync-status
|
||||
/// Manually synchronize videos.status with monitor_jobs.status for all records.
|
||||
async fn sync_all_statuses(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<SyncStatusResponse>, StatusCode> {
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
let videos_table = schema::table_name("videos");
|
||||
|
||||
// Find mismatches
|
||||
let mismatches: Vec<(String, String, String)> = sqlx::query_as(&format!(
|
||||
"SELECT mj.uuid, mj.status as mj_status, v.status as v_status
|
||||
FROM {} mj
|
||||
JOIN {} v ON mj.uuid = v.file_uuid
|
||||
WHERE mj.status != v.status
|
||||
AND NOT (mj.status = 'paused' AND v.status = 'paused')
|
||||
AND NOT (mj.status = 'pending' AND v.status = 'registered')
|
||||
AND NOT (mj.status = 'running' AND v.status = 'processing')
|
||||
AND NOT (mj.status = 'completed' AND v.status = 'completed')
|
||||
AND NOT (mj.status = 'failed' AND v.status = 'failed')",
|
||||
monitor_jobs_table, videos_table
|
||||
))
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let mismatch_count = mismatches.len();
|
||||
|
||||
// Fix mismatches
|
||||
let mut fixed = 0;
|
||||
for (uuid, mj_status, _v_status) in mismatches {
|
||||
let video_status = match mj_status.as_str() {
|
||||
"paused" => "paused",
|
||||
"pending" => "registered",
|
||||
"running" => "processing",
|
||||
"completed" => "completed",
|
||||
"failed" => "failed",
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET status = $1, updated_at = NOW() WHERE file_uuid = $2",
|
||||
videos_table
|
||||
))
|
||||
.bind(video_status)
|
||||
.bind(&uuid)
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
fixed += 1;
|
||||
}
|
||||
|
||||
Ok(Json(SyncStatusResponse {
|
||||
success: true,
|
||||
mismatches_found: mismatch_count,
|
||||
mismatches_fixed: fixed,
|
||||
message: format!("Found {} mismatches, fixed {}", mismatch_count, fixed),
|
||||
}))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user