feat: async unregister mode for large files

Add async_mode option to POST /api/v1/unregister:
- async_mode=false (default): synchronous, waits for completion
- async_mode=true: spawns background task, returns immediately with job_id

Response now includes job_id field (None for sync mode).

Used by Studio when unregistering large files that take >30s
(e.g., 83K faces, 20K tkg_nodes).
This commit is contained in:
Accusys
2026-07-31 18:30:27 +08:00
parent 4c8041974a
commit d6653f8240
+164 -75
View File
@@ -636,11 +636,14 @@ async fn register_file(
) -> Result<Json<RegisterFileResponse>, StatusCode> {
let worker_running = super::health::check_worker_alive(&state).await;
let worker_warning = if !worker_running {
Some("Worker is not running - file will be registered but not processed automatically".to_string())
Some(
"Worker is not running - file will be registered but not processed automatically"
.to_string(),
)
} else {
None
};
let file_path = req.file_path.clone();
let pattern = req.pattern;
@@ -783,7 +786,7 @@ async fn register_file(
let mut resp =
register_single_file(&state, &file_path, req.user_id, req.content_hash, req.force).await;
if worker_warning.is_some() {
resp.warning = worker_warning;
}
@@ -1017,6 +1020,7 @@ struct UnregisterResponse {
success: bool,
message: String,
file_uuid: String,
job_id: Option<String>,
deleted_face_detections: u64,
deleted_processor_results: u64,
deleted_chunks: u64,
@@ -1039,6 +1043,8 @@ struct UnregisterResponse {
struct UnregisterRequest {
file_uuid: Option<String>,
file_path: Option<String>,
#[serde(default)]
async_mode: bool,
}
fn delete_output_files(uuid: &str) -> u64 {
@@ -1094,10 +1100,7 @@ fn delete_output_files(uuid: &str) -> u64 {
uuid
);
if deleted_count == 0 {
tracing::warn!(
"[UNREGISTER] No output files found to delete for {}",
uuid
);
tracing::warn!("[UNREGISTER] No output files found to delete for {}", uuid);
}
deleted_count
}
@@ -1111,8 +1114,50 @@ async fn unregister(
None => return Err(StatusCode::BAD_REQUEST),
};
tracing::info!("[UNREGISTER] Unregistering file: {}", uuid);
tracing::info!("[UNREGISTER] Unregistering file: {} (async_mode={})", uuid, req.async_mode);
// Async mode: spawn background task and return immediately
if req.async_mode {
let job_id = format!("unregister_{}", uuid);
let state_clone = state.clone();
let uuid_clone = uuid.clone();
tokio::spawn(async move {
tracing::info!("[ASYNC_UNREGISTER] Starting background unregister for {}", uuid_clone);
match unregister_internal(&state_clone, &uuid_clone).await {
Ok(()) => {
tracing::info!("[ASYNC_UNREGISTER] Completed for {}", uuid_clone);
}
Err(e) => {
tracing::error!("[ASYNC_UNREGISTER] Failed for {}: {:?}", uuid_clone, e);
}
}
});
return Ok(Json(UnregisterResponse {
success: true,
message: format!("Unregister started in background for {}", uuid),
file_uuid: uuid,
job_id: Some(job_id),
deleted_face_detections: 0,
deleted_processor_results: 0,
deleted_chunks: 0,
deleted_tkg_nodes: 0,
deleted_qdrant_vectors: None,
deleted_qdrant_workspace: None,
deleted_redis_keys: None,
deleted_output_files: 0,
deleted_file_identities: 0,
deleted_speaker_detections: 0,
deleted_face_clusters: 0,
deleted_face_recognition_results: 0,
deleted_characters: 0,
deleted_chunks_rule1: 0,
deleted_processor_alerts: 0,
deleted_processor_versions: 0,
}));
}
// Synchronous mode (existing code follows)
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
let chunks_table = schema::table_name("chunk");
@@ -1296,19 +1341,31 @@ async fn unregister(
// Delete PipelineProgress keys (all variants)
let progress_patterns = [
format!("{}progress:{}:pipeline", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
format!("{}progress:{}:agent", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
format!("{}progress:{}:tkg", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
format!(
"{}progress:{}:pipeline",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
),
format!(
"{}progress:{}:agent",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
),
format!(
"{}progress:{}:tkg",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
),
];
if let Ok(mut conn) = redis.get_conn().await {
for key in &progress_patterns {
let _: Option<String> = redis::cmd("DEL")
.arg(key)
.query_async(&mut conn)
.await
.ok();
let _: Option<String> =
redis::cmd("DEL").arg(key).query_async(&mut conn).await.ok();
}
tracing::info!("[UNREGISTER] Deleted Redis PipelineProgress keys for {}", uuid);
tracing::info!(
"[UNREGISTER] Deleted Redis PipelineProgress keys for {}",
uuid
);
deleted += progress_patterns.len() as u64;
}
@@ -1342,6 +1399,7 @@ async fn unregister(
success: true,
message: format!("File {} unregistered successfully.", uuid),
file_uuid: uuid,
job_id: None,
deleted_face_detections: deleted_faces as u64,
deleted_processor_results: deleted_processors as u64,
deleted_chunks: (deleted_chunks + deleted_parent_chunks + deleted_pre_chunks) as u64,
@@ -1646,14 +1704,14 @@ async fn sync_file_status(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use crate::core::config::OUTPUT_DIR;
let output_dir = OUTPUT_DIR.as_str();
let videos_table = schema::table_name("videos");
let chunk_table = schema::table_name("chunk");
let tp_table = schema::table_name("trace_profiles");
let tkg_nodes_table = schema::table_name("tkg_nodes");
let tkg_edges_table = schema::table_name("tkg_edges");
// 檢查 processor JSON 是否存在
let processors = [
("asr", "asr.json"),
@@ -1664,20 +1722,20 @@ async fn sync_file_status(
("face", "face.json"),
("face_cluster", "face_cluster.json"),
];
let mut processor_status = serde_json::Map::new();
let mut errors = Vec::new();
let mut all_consistent = true;
let mut any_json_exists = false;
for (name, filename) in &processors {
let path = std::path::Path::new(output_dir).join(format!("{}.{}", file_uuid, filename));
let json_exists = path.exists();
let mut consistent = false;
if json_exists {
any_json_exists = true;
// 讀取 JSON 內容
match std::fs::read_to_string(&path) {
Ok(content) => {
@@ -1686,9 +1744,15 @@ async fn sync_file_status(
let pre_table = schema::table_name("pre_chunks");
consistent = match *name {
"asr" => {
let json_count = json_data.get("segments").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
let is_no_audio = json_data.get("status").and_then(|s| s.as_str()) == Some("no_audio_track")
|| json_data.get("status").and_then(|s| s.as_str()) == Some("silent_audio");
let json_count = json_data
.get("segments")
.and_then(|s| s.as_array())
.map(|a| a.len())
.unwrap_or(0);
let is_no_audio = json_data.get("status").and_then(|s| s.as_str())
== Some("no_audio_track")
|| json_data.get("status").and_then(|s| s.as_str())
== Some("silent_audio");
let db_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asr'", pre_table
))
@@ -1696,7 +1760,11 @@ async fn sync_file_status(
is_no_audio || (json_count as i64) == db_count
}
"asrx" => {
let json_count = json_data.get("segments").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
let json_count = json_data
.get("segments")
.and_then(|s| s.as_array())
.map(|a| a.len())
.unwrap_or(0);
let db_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asrx'", pre_table
))
@@ -1709,7 +1777,11 @@ async fn sync_file_status(
true
}
"cut" => {
let json_count = json_data.get("scenes").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
let json_count = json_data
.get("scenes")
.and_then(|s| s.as_array())
.map(|a| a.len())
.unwrap_or(0);
let db_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'cut'", pre_table
))
@@ -1747,18 +1819,21 @@ async fn sync_file_status(
}
}
}
// JSON not existing also counts as inconsistent
if !consistent {
all_consistent = false;
}
processor_status.insert(name.to_string(), serde_json::json!({
"json_exists": json_exists,
"consistent": consistent
}));
processor_status.insert(
name.to_string(),
serde_json::json!({
"json_exists": json_exists,
"consistent": consistent
}),
);
}
// 如果有錯誤,回傳錯誤
if !errors.is_empty() {
return Ok(Json(serde_json::json!({
@@ -1768,36 +1843,42 @@ async fn sync_file_status(
"errors": errors
})));
}
// 檢查 DB 進階狀態
let has_sentence: bool = sqlx::query_scalar(&format!(
"SELECT 1 FROM {} WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1", chunk_table
"SELECT 1 FROM {} WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1",
chunk_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0) > 0;
.unwrap_or(0)
> 0;
let has_tkg_nodes: bool = sqlx::query_scalar(&format!(
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1", tkg_nodes_table
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1",
tkg_nodes_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0) > 0;
.unwrap_or(0)
> 0;
let has_tkg_edges: bool = sqlx::query_scalar(&format!(
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1", tkg_edges_table
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1",
tkg_edges_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0) > 0;
// 查詢 processing_status phase
.unwrap_or(0)
> 0;
// 查詢 processing_status phase
let phase: String = sqlx::query_scalar(&format!(
"SELECT COALESCE(processing_status->>'phase', '') FROM {} WHERE file_uuid = $1",
videos_table
@@ -1835,39 +1916,47 @@ async fn sync_file_status(
tracing::error!("[SYNC_STATUS] Update failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
// 查詢 monitor_jobs 取得 worker 狀態
let monitor_jobs_table = schema::table_name("monitor_jobs");
let job: Option<(String, Option<String>, i32, i32, Vec<String>, Vec<String>, Option<chrono::NaiveDateTime>)> =
sqlx::query_as(&format!(
"SELECT status, current_processor, progress_total, progress_current, \
let job: Option<(
String,
Option<String>,
i32,
i32,
Vec<String>,
Vec<String>,
Option<chrono::NaiveDateTime>,
)> = sqlx::query_as(&format!(
"SELECT status, current_processor, progress_total, progress_current, \
completed_processors, failed_processors, updated_at \
FROM {} WHERE uuid = $1 ORDER BY created_at DESC LIMIT 1",
monitor_jobs_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten();
let worker_info = if let Some((status, current_proc, total, current, completed, failed, updated)) = job {
serde_json::json!({
"has_job": true,
"job_status": status,
"current_processor": current_proc,
"progress_total": total,
"progress_current": current,
"completed_processors": completed,
"failed_processors": failed,
"updated_at": updated.map(|t| t.format("%Y-%m-%dT%H:%M:%S").to_string())
})
} else {
serde_json::json!({
"has_job": false
})
};
monitor_jobs_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten();
let worker_info =
if let Some((status, current_proc, total, current, completed, failed, updated)) = job {
serde_json::json!({
"has_job": true,
"job_status": status,
"current_processor": current_proc,
"progress_total": total,
"progress_current": current,
"completed_processors": completed,
"failed_processors": failed,
"updated_at": updated.map(|t| t.format("%Y-%m-%dT%H:%M:%S").to_string())
})
} else {
serde_json::json!({
"has_job": false
})
};
Ok(Json(serde_json::json!({
"success": true,
"file_uuid": file_uuid,