Files
momentry_core/src/api/cluster_agent.rs.bak2
T
Accusys 63fbbe1225 release: v1.3.1 - Pipeline Queue Integration, OCR Fix, Worker Compatibility
Major Changes:
- Pipeline Queue integration completed (internal.file + pipeline.commands)
- Fixed old job_worker database compatibility with new command_queue table
- Compiled Swift OCR binary (was missing, causing empty OCR results)
- Added deep scan functionality through re-scan API

Fixes:
- Changed CommandJob.id from i32 to i64 for database compatibility
- Added UUID generation in create_command (message_id field)
- Fixed claim_pending_commands to query queue_name = 'internal.file'
- Fixed field mappings: command_id → message_id, job_type → command_type
- Added support for 'processing' status in CommandJobStatus

Queue System:
- internal.file queue: for register/unregister/re-scan commands (job_worker)
- pipeline.commands queue: for vectorize/store_asrx/etc commands (pipeline_worker)

Documentation:
- Added comprehensive queue system documentation
- Created M4 workspace status reports
- Updated AGENTS.md with queue system details
2026-10-12 10:00:51 +08:00

607 lines
21 KiB
Plaintext

use axum::{
extract::{Path, State},
http::StatusCode,
routing::{get, post},
Extension, Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::LazyLock;
use std::time::Instant;
use tokio::sync::RwLock;
use super::middleware::UserAuth;
use super::types::AppState;
use crate::core::config::OUTPUT_DIR;
use crate::core::db::schema;
use crate::core::processor::{process_face_cluster, FaceClusterResult};
// ---------------------------------------------------------------------------
// In-memory job registry (one global, shared across requests)
// ---------------------------------------------------------------------------
static CLUSTER_JOB_REGISTRY: LazyLock<RwLock<HashMap<String, ClusterJobHandle>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
#[derive(Debug, Clone)]
pub enum ClusterJobStatus {
Running,
Completed,
Failed(String),
Cancelled,
}
impl serde::Serialize for ClusterJobStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(match self {
ClusterJobStatus::Running => "running",
ClusterJobStatus::Completed => "completed",
ClusterJobStatus::Failed(_) => "failed",
ClusterJobStatus::Cancelled => "cancelled",
})
}
}
#[derive(Debug)]
pub struct ClusterJobHandle {
pub file_uuid: String,
pub similarity_threshold: f64,
pub status: ClusterJobStatus,
pub progress: f64,
pub clusters: usize,
pub total_traces: usize,
pub created_at: Instant,
pub cancel_token: tokio_util::sync::CancellationToken,
}
// ---------------------------------------------------------------------------
// Request / Response types
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
pub struct ClusterAgentRequest {
pub confirm: Option<bool>,
pub similarity_threshold: Option<f64>,
}
#[derive(Debug, Serialize)]
pub struct ClusterAgentResponse {
success: bool,
job_id: String,
file_uuid: String,
status: String,
similarity_threshold: f64,
}
#[derive(Debug, Serialize)]
pub struct ClusterJobStatusResponse {
job_id: String,
file_uuid: String,
status: String,
progress: Option<f64>,
message: Option<String>,
clusters: usize,
total_traces: usize,
similarity_threshold: f64,
}
#[derive(Debug, Serialize)]
pub struct CancelJobResponse {
success: bool,
job_id: String,
status: String,
}
// ---------------------------------------------------------------------------
// Routes
// ---------------------------------------------------------------------------
pub fn cluster_agent_routes() -> Router<AppState> {
Router::new()
.route(
"/api/v1/file/:file_uuid/cluster-agent",
post(trigger_cluster_agent),
)
.route(
"/api/v1/cluster-job/:job_id",
get(get_cluster_job_status).delete(cancel_cluster_job),
)
}
// ---------------------------------------------------------------------------
// POST /api/v1/file/:file_uuid/cluster-agent (async, immediate 202)
// ---------------------------------------------------------------------------
pub async fn trigger_cluster_agent(
State(state): State<AppState>,
Extension(_auth): Extension<UserAuth>,
Path(file_uuid): Path<String>,
Json(req): Json<ClusterAgentRequest>,
) -> Result<Json<ClusterAgentResponse>, (StatusCode, Json<serde_json::Value>)> {
if !req.confirm.unwrap_or(false) {
return Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"success": false,
"error": "Confirmation required. Set 'confirm': true to proceed with reclustering. This will reset all trace names and re-cluster faces.",
"requires_confirmation": true
})),
));
}
// Validate similarity_threshold
let similarity_threshold = req.similarity_threshold.unwrap_or(0.65);
if !(0.5..=0.95).contains(&similarity_threshold) {
return Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "similarity_threshold must be between 0.5 and 0.95",
"provided": similarity_threshold
})),
));
}
// Check for existing running job for this file
let registry = CLUSTER_JOB_REGISTRY.read().await;
for (job_id, handle) in registry.iter() {
if handle.file_uuid == file_uuid && matches!(handle.status, ClusterJobStatus::Running) {
return Ok(Json(ClusterAgentResponse {
success: false,
job_id: job_id.clone(),
file_uuid,
status: "running".to_string(),
similarity_threshold: handle.similarity_threshold,
}));
}
}
drop(registry);
// Lookup video to get file_path + total_traces
let videos_table = schema::table_name("videos");
let row = sqlx::query(&format!(
"SELECT file_path, COALESCE(total_frames, 0) as total_frames, COALESCE(fps, 25.0) as fps, probe_json FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[ClusterAgent] DB error: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": e.to_string()})),
)
})?;
let (file_path, total_frames, fps) = match row {
Some(r) => {
use sqlx::Row;
let p: String = r.get("file_path");
let tf: i64 = r.get("total_frames");
let f: f64 = r.get("fps");
let mut frames = tf;
if frames <= 0 {
if let Ok(meta_val) = r.try_get::<serde_json::Value, _>("probe_json") {
if let Some(streams) = meta_val.get("streams").and_then(|v| v.as_array()) {
for s in streams {
if s.get("codec_type").and_then(|v| v.as_str()) == Some("video") {
if let Some(nb) = s.get("nb_frames").and_then(|v| v.as_str()) {
if let Ok(n) = nb.parse::<i64>() {
frames = n;
break;
}
}
}
}
}
}
}
(p, frames, f)
}
None => {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "File not found"})),
))
}
};
let total_traces = count_total_traces(&state, &file_uuid).await.unwrap_or(0);
let job_id = format!(
"cluster_{}_{}",
file_uuid,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
);
let output_path =
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
let cancel_token = tokio_util::sync::CancellationToken::new();
// Register job
let handle = ClusterJobHandle {
file_uuid: file_uuid.clone(),
similarity_threshold,
status: ClusterJobStatus::Running,
progress: 0.0,
clusters: 0,
total_traces,
created_at: Instant::now(),
cancel_token: cancel_token.clone(),
};
CLUSTER_JOB_REGISTRY
.write()
.await
.insert(job_id.clone(), handle);
// Reset trace names before re-clustering
let traced_path =
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid));
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(traces) = traced_data.get("traces") {
let trace_list = if traces.is_object() {
traces.as_object().map(|o| {
o.keys()
.filter_map(|k| k.parse::<i64>().ok())
.collect::<Vec<_>>()
})
} else if traces.is_array() {
traces.as_array().map(|a| {
a.iter()
.filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64()))
.collect()
})
} else {
None
};
if let Some(all_trace_ids) = trace_list {
let mut success_count = 0;
let mut error_count = 0;
for tid in &all_trace_ids {
let name = "Unassigned".to_string();
match schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
*tid as i32,
&name,
None,
)
.await
{
Ok(_) => success_count += 1,
Err(e) => {
error_count += 1;
tracing::error!(
"[ClusterAgent] Failed to upsert trace profile for trace {}: {}",
tid,
e
);
}
}
}
tracing::info!(
"[ClusterAgent] Reset {} trace names to default for {} (success: {}, errors: {})",
all_trace_ids.len(),
file_uuid,
success_count,
error_count
);
}
}
}
}
// Spawn background clustering task
let db_clone = state.db.clone();
let file_uuid_clone = file_uuid.clone();
let file_path_clone = file_path.clone();
let output_path_clone = output_path.clone();
let cancel_clone = cancel_token.clone();
let job_id_clone = job_id.clone();
tokio::spawn(async move {
// Build frames list
let frames = if total_frames > 0 {
let fps_val = if fps > 0.0 { fps } else { 30.0 };
Some(crate::core::processor::PythonExecutor::compute_8hz_frames(
total_frames,
fps_val,
))
} else {
None
};
// Run clustering with cancel support
let result = process_face_cluster(
&file_path_clone,
output_path_clone.to_str().unwrap(),
Some(&file_uuid_clone),
frames.as_deref(),
Some(similarity_threshold),
)
.await;
let mut registry = CLUSTER_JOB_REGISTRY.write().await;
let handle = match registry.get_mut(&job_id_clone) {
Some(h) => h,
None => return, // cancelled and cleaned up
};
match result {
Ok(cluster_result) => {
// Check if cancelled during run
if cancel_clone.is_cancelled() {
// Don't apply results if cancelled
let _ = registry.remove(&job_id_clone);
return;
}
// Update trace labels
let _ =
update_trace_labels_from_cluster(&db_clone, &file_uuid_clone, &cluster_result)
.await;
handle.status = ClusterJobStatus::Completed;
handle.progress = 1.0;
handle.clusters = cluster_result.clusters.len();
tracing::info!(
"[ClusterAgent] Completed for {}: {} clusters",
file_uuid_clone,
cluster_result.clusters.len()
);
}
Err(e) => {
if cancel_clone.is_cancelled() {
handle.status = ClusterJobStatus::Cancelled;
tracing::info!("[ClusterAgent] Cancelled for {}", file_uuid_clone);
} else {
handle.status = ClusterJobStatus::Failed(e.to_string());
tracing::error!("[ClusterAgent] Failed for {}: {}", file_uuid_clone, e);
}
}
}
// Clean up registry after a short delay so GET can still fetch final status
let job_id_for_cleanup = job_id_clone.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
CLUSTER_JOB_REGISTRY
.write()
.await
.remove(&job_id_for_cleanup);
});
});
// Return 202 immediately
Ok(Json(ClusterAgentResponse {
success: true,
job_id,
file_uuid,
status: "running".to_string(),
similarity_threshold,
}))
}
// ---------------------------------------------------------------------------
// GET /api/v1/cluster-job/:job_id
// ---------------------------------------------------------------------------
pub async fn get_cluster_job_status(
Path(job_id): Path<String>,
) -> Result<Json<ClusterJobStatusResponse>, (StatusCode, Json<serde_json::Value>)> {
let registry = CLUSTER_JOB_REGISTRY.read().await;
let handle = registry.get(&job_id).ok_or_else(|| {
(
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Job not found"})),
)
})?;
let (status_str, message) = match &handle.status {
ClusterJobStatus::Running => (
"running".to_string(),
Some("Clustering in progress".to_string()),
),
ClusterJobStatus::Completed => ("completed".to_string(), None),
ClusterJobStatus::Failed(msg) => ("failed".to_string(), Some(msg.clone())),
ClusterJobStatus::Cancelled => (
"cancelled".to_string(),
Some("Job was cancelled".to_string()),
),
};
Ok(Json(ClusterJobStatusResponse {
job_id,
file_uuid: handle.file_uuid.clone(),
status: status_str,
progress: if matches!(handle.status, ClusterJobStatus::Running) {
Some(handle.progress)
} else {
Some(if matches!(handle.status, ClusterJobStatus::Completed) {
1.0
} else {
handle.progress
})
},
message,
clusters: handle.clusters,
total_traces: handle.total_traces,
similarity_threshold: handle.similarity_threshold,
}))
}
// ---------------------------------------------------------------------------
// DELETE /api/v1/cluster-job/:job_id (cancel)
// ---------------------------------------------------------------------------
pub async fn cancel_cluster_job(
Path(job_id): Path<String>,
) -> Result<Json<CancelJobResponse>, (StatusCode, Json<serde_json::Value>)> {
let mut registry = CLUSTER_JOB_REGISTRY.write().await;
let handle = registry.get_mut(&job_id).ok_or_else(|| {
(
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Job not found or already finished"})),
)
})?;
if !matches!(handle.status, ClusterJobStatus::Running) {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Job not found or already finished"})),
));
}
// Trigger cancellation
handle.cancel_token.cancel();
handle.status = ClusterJobStatus::Cancelled;
Ok(Json(CancelJobResponse {
success: true,
job_id,
status: "cancelled".to_string(),
}))
}
// ---------------------------------------------------------------------------
// Helpers (reused from original implementation)
// ---------------------------------------------------------------------------
async fn update_trace_labels_from_cluster(
db: &crate::core::db::PostgresDb,
file_uuid: &str,
result: &FaceClusterResult,
) -> anyhow::Result<()> {
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("{}.face_traced.json", file_uuid));
let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new();
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(frames) = traced_data.get("frames").and_then(|v| v.as_object()) {
for (fnum_str, frame_data) in frames {
if let (Ok(fnum), Some(faces)) = (
fnum_str.parse::<u64>(),
frame_data.get("faces").and_then(|v| v.as_array()),
) {
for (idx, face) in faces.iter().enumerate() {
if let Some(tid) = face.get("trace_id").and_then(|v| v.as_i64()) {
frame_face_to_trace.insert((fnum, idx), tid);
}
}
}
}
}
}
}
let mut trace_to_cluster: HashMap<i64, String> = HashMap::new();
for frame_data in &result.frames {
for (idx, face) in frame_data.faces.iter().enumerate() {
if let Some(&tid) = frame_face_to_trace.get(&(frame_data.frame, idx)) {
trace_to_cluster.insert(tid, face.cluster_id.clone());
}
}
}
let tkg_table = schema::table_name("tkg_nodes");
for (trace_id, cluster_id) in &trace_to_cluster {
let external_id = format!("trace_{}", trace_id);
let label = cluster_id.clone();
let rows_updated = sqlx::query(&format!(
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3",
tkg_table
))
.bind(&label)
.bind(file_uuid)
.bind(&external_id)
.execute(db.pool())
.await?
.rows_affected();
if rows_updated == 0 {
sqlx::query(&format!(
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4)",
tkg_table
))
.bind(file_uuid)
.bind(&external_id)
.bind(&label)
.bind(serde_json::json!({"trace_id": trace_id}))
.execute(db.pool())
.await?;
}
let _ = schema::upsert_trace_profile(db.pool(), file_uuid, *trace_id as i32, &label, None)
.await;
}
if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) {
let mut updated_count = 0u64;
for tid in &all_trace_ids {
if !trace_to_cluster.contains_key(tid) {
let name = format!("Person_{}", tid);
let _ =
schema::upsert_trace_profile(db.pool(), file_uuid, *tid as i32, &name, None)
.await;
updated_count += 1;
}
}
if updated_count > 0 {
tracing::info!(
"[ClusterAgent] Updated {} unclustered trace names for {}",
updated_count,
file_uuid
);
}
}
tracing::info!(
"[ClusterAgent] Updated {} trace labels from clustering for {}",
trace_to_cluster.len(),
file_uuid
);
Ok(())
}
fn get_all_trace_ids(file_uuid: &str) -> Option<Vec<i64>> {
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("{}.face_traced.json", file_uuid));
let content = std::fs::read_to_string(&traced_path).ok()?;
let traced_data: serde_json::Value = serde_json::from_str(&content).ok()?;
let traces = traced_data.get("traces")?;
if let Some(obj) = traces.as_object() {
Some(obj.keys().filter_map(|k| k.parse::<i64>().ok()).collect())
} else if let Some(arr) = traces.as_array() {
Some(
arr.iter()
.filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64()))
.collect(),
)
} else {
None
}
}
async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result<usize> {
let tkg_table = schema::table_name("tkg_nodes");
let count: (i64,) = sqlx::query_as(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = 'face_track'",
tkg_table
))
.bind(file_uuid)
.fetch_one(state.db.pool())
.await?;
Ok(count.0 as usize)
}