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:
+146
-57
@@ -636,7 +636,10 @@ async fn register_file(
|
|||||||
) -> Result<Json<RegisterFileResponse>, StatusCode> {
|
) -> Result<Json<RegisterFileResponse>, StatusCode> {
|
||||||
let worker_running = super::health::check_worker_alive(&state).await;
|
let worker_running = super::health::check_worker_alive(&state).await;
|
||||||
let worker_warning = if !worker_running {
|
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 {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@@ -1017,6 +1020,7 @@ struct UnregisterResponse {
|
|||||||
success: bool,
|
success: bool,
|
||||||
message: String,
|
message: String,
|
||||||
file_uuid: String,
|
file_uuid: String,
|
||||||
|
job_id: Option<String>,
|
||||||
deleted_face_detections: u64,
|
deleted_face_detections: u64,
|
||||||
deleted_processor_results: u64,
|
deleted_processor_results: u64,
|
||||||
deleted_chunks: u64,
|
deleted_chunks: u64,
|
||||||
@@ -1039,6 +1043,8 @@ struct UnregisterResponse {
|
|||||||
struct UnregisterRequest {
|
struct UnregisterRequest {
|
||||||
file_uuid: Option<String>,
|
file_uuid: Option<String>,
|
||||||
file_path: Option<String>,
|
file_path: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
async_mode: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn delete_output_files(uuid: &str) -> u64 {
|
fn delete_output_files(uuid: &str) -> u64 {
|
||||||
@@ -1094,10 +1100,7 @@ fn delete_output_files(uuid: &str) -> u64 {
|
|||||||
uuid
|
uuid
|
||||||
);
|
);
|
||||||
if deleted_count == 0 {
|
if deleted_count == 0 {
|
||||||
tracing::warn!(
|
tracing::warn!("[UNREGISTER] No output files found to delete for {}", uuid);
|
||||||
"[UNREGISTER] No output files found to delete for {}",
|
|
||||||
uuid
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
deleted_count
|
deleted_count
|
||||||
}
|
}
|
||||||
@@ -1111,8 +1114,50 @@ async fn unregister(
|
|||||||
None => return Err(StatusCode::BAD_REQUEST),
|
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 videos_table = schema::table_name("videos");
|
||||||
let processor_table = schema::table_name("processor_results");
|
let processor_table = schema::table_name("processor_results");
|
||||||
let chunks_table = schema::table_name("chunk");
|
let chunks_table = schema::table_name("chunk");
|
||||||
@@ -1296,19 +1341,31 @@ async fn unregister(
|
|||||||
|
|
||||||
// Delete PipelineProgress keys (all variants)
|
// Delete PipelineProgress keys (all variants)
|
||||||
let progress_patterns = [
|
let progress_patterns = [
|
||||||
format!("{}progress:{}:pipeline", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
|
format!(
|
||||||
format!("{}progress:{}:agent", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
|
"{}progress:{}:pipeline",
|
||||||
format!("{}progress:{}:tkg", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
|
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 {
|
if let Ok(mut conn) = redis.get_conn().await {
|
||||||
for key in &progress_patterns {
|
for key in &progress_patterns {
|
||||||
let _: Option<String> = redis::cmd("DEL")
|
let _: Option<String> =
|
||||||
.arg(key)
|
redis::cmd("DEL").arg(key).query_async(&mut conn).await.ok();
|
||||||
.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;
|
deleted += progress_patterns.len() as u64;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1342,6 +1399,7 @@ async fn unregister(
|
|||||||
success: true,
|
success: true,
|
||||||
message: format!("File {} unregistered successfully.", uuid),
|
message: format!("File {} unregistered successfully.", uuid),
|
||||||
file_uuid: uuid,
|
file_uuid: uuid,
|
||||||
|
job_id: None,
|
||||||
deleted_face_detections: deleted_faces as u64,
|
deleted_face_detections: deleted_faces as u64,
|
||||||
deleted_processor_results: deleted_processors as u64,
|
deleted_processor_results: deleted_processors as u64,
|
||||||
deleted_chunks: (deleted_chunks + deleted_parent_chunks + deleted_pre_chunks) as u64,
|
deleted_chunks: (deleted_chunks + deleted_parent_chunks + deleted_pre_chunks) as u64,
|
||||||
@@ -1686,9 +1744,15 @@ async fn sync_file_status(
|
|||||||
let pre_table = schema::table_name("pre_chunks");
|
let pre_table = schema::table_name("pre_chunks");
|
||||||
consistent = match *name {
|
consistent = match *name {
|
||||||
"asr" => {
|
"asr" => {
|
||||||
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
|
||||||
let is_no_audio = json_data.get("status").and_then(|s| s.as_str()) == Some("no_audio_track")
|
.get("segments")
|
||||||
|| json_data.get("status").and_then(|s| s.as_str()) == Some("silent_audio");
|
.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!(
|
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asr'", pre_table
|
"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
|
is_no_audio || (json_count as i64) == db_count
|
||||||
}
|
}
|
||||||
"asrx" => {
|
"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!(
|
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asrx'", pre_table
|
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asrx'", pre_table
|
||||||
))
|
))
|
||||||
@@ -1709,7 +1777,11 @@ async fn sync_file_status(
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
"cut" => {
|
"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!(
|
let db_count: i64 = sqlx::query_scalar(&format!(
|
||||||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'cut'", pre_table
|
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'cut'", pre_table
|
||||||
))
|
))
|
||||||
@@ -1753,10 +1825,13 @@ async fn sync_file_status(
|
|||||||
all_consistent = false;
|
all_consistent = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
processor_status.insert(name.to_string(), serde_json::json!({
|
processor_status.insert(
|
||||||
"json_exists": json_exists,
|
name.to_string(),
|
||||||
"consistent": consistent
|
serde_json::json!({
|
||||||
}));
|
"json_exists": json_exists,
|
||||||
|
"consistent": consistent
|
||||||
|
}),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果有錯誤,回傳錯誤
|
// 如果有錯誤,回傳錯誤
|
||||||
@@ -1771,33 +1846,39 @@ async fn sync_file_status(
|
|||||||
|
|
||||||
// 檢查 DB 進階狀態
|
// 檢查 DB 進階狀態
|
||||||
let has_sentence: bool = sqlx::query_scalar(&format!(
|
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)
|
.bind(&file_uuid)
|
||||||
.fetch_optional(state.db.pool())
|
.fetch_optional(state.db.pool())
|
||||||
.await
|
.await
|
||||||
.unwrap_or(None)
|
.unwrap_or(None)
|
||||||
.unwrap_or(0) > 0;
|
.unwrap_or(0)
|
||||||
|
> 0;
|
||||||
|
|
||||||
let has_tkg_nodes: bool = sqlx::query_scalar(&format!(
|
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)
|
.bind(&file_uuid)
|
||||||
.fetch_optional(state.db.pool())
|
.fetch_optional(state.db.pool())
|
||||||
.await
|
.await
|
||||||
.unwrap_or(None)
|
.unwrap_or(None)
|
||||||
.unwrap_or(0) > 0;
|
.unwrap_or(0)
|
||||||
|
> 0;
|
||||||
|
|
||||||
let has_tkg_edges: bool = sqlx::query_scalar(&format!(
|
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)
|
.bind(&file_uuid)
|
||||||
.fetch_optional(state.db.pool())
|
.fetch_optional(state.db.pool())
|
||||||
.await
|
.await
|
||||||
.unwrap_or(None)
|
.unwrap_or(None)
|
||||||
.unwrap_or(0) > 0;
|
.unwrap_or(0)
|
||||||
|
> 0;
|
||||||
|
|
||||||
// 查詢 processing_status phase
|
// 查詢 processing_status phase
|
||||||
let phase: String = sqlx::query_scalar(&format!(
|
let phase: String = sqlx::query_scalar(&format!(
|
||||||
"SELECT COALESCE(processing_status->>'phase', '') FROM {} WHERE file_uuid = $1",
|
"SELECT COALESCE(processing_status->>'phase', '') FROM {} WHERE file_uuid = $1",
|
||||||
videos_table
|
videos_table
|
||||||
@@ -1838,35 +1919,43 @@ async fn sync_file_status(
|
|||||||
|
|
||||||
// 查詢 monitor_jobs 取得 worker 狀態
|
// 查詢 monitor_jobs 取得 worker 狀態
|
||||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||||
let job: Option<(String, Option<String>, i32, i32, Vec<String>, Vec<String>, Option<chrono::NaiveDateTime>)> =
|
let job: Option<(
|
||||||
sqlx::query_as(&format!(
|
String,
|
||||||
"SELECT status, current_processor, progress_total, progress_current, \
|
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 \
|
completed_processors, failed_processors, updated_at \
|
||||||
FROM {} WHERE uuid = $1 ORDER BY created_at DESC LIMIT 1",
|
FROM {} WHERE uuid = $1 ORDER BY created_at DESC LIMIT 1",
|
||||||
monitor_jobs_table
|
monitor_jobs_table
|
||||||
))
|
))
|
||||||
.bind(&file_uuid)
|
.bind(&file_uuid)
|
||||||
.fetch_optional(state.db.pool())
|
.fetch_optional(state.db.pool())
|
||||||
.await
|
.await
|
||||||
.ok()
|
.ok()
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|
||||||
let worker_info = if let Some((status, current_proc, total, current, completed, failed, updated)) = job {
|
let worker_info =
|
||||||
serde_json::json!({
|
if let Some((status, current_proc, total, current, completed, failed, updated)) = job {
|
||||||
"has_job": true,
|
serde_json::json!({
|
||||||
"job_status": status,
|
"has_job": true,
|
||||||
"current_processor": current_proc,
|
"job_status": status,
|
||||||
"progress_total": total,
|
"current_processor": current_proc,
|
||||||
"progress_current": current,
|
"progress_total": total,
|
||||||
"completed_processors": completed,
|
"progress_current": current,
|
||||||
"failed_processors": failed,
|
"completed_processors": completed,
|
||||||
"updated_at": updated.map(|t| t.format("%Y-%m-%dT%H:%M:%S").to_string())
|
"failed_processors": failed,
|
||||||
})
|
"updated_at": updated.map(|t| t.format("%Y-%m-%dT%H:%M:%S").to_string())
|
||||||
} else {
|
})
|
||||||
serde_json::json!({
|
} else {
|
||||||
"has_job": false
|
serde_json::json!({
|
||||||
})
|
"has_job": false
|
||||||
};
|
})
|
||||||
|
};
|
||||||
|
|
||||||
Ok(Json(serde_json::json!({
|
Ok(Json(serde_json::json!({
|
||||||
"success": true,
|
"success": true,
|
||||||
|
|||||||
Reference in New Issue
Block a user