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
This commit is contained in:
Accusys
2026-10-12 10:00:51 +08:00
parent 0a18e70639
commit 63fbbe1225
418 changed files with 44084 additions and 4280 deletions
+2 -2
View File
@@ -267,7 +267,7 @@ pub async fn trigger_cluster_agent(
let mut success_count = 0;
let mut error_count = 0;
for tid in &all_trace_ids {
let name = format!("Person_{}", tid);
let name = "Unassigned".to_string();
match schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
@@ -548,7 +548,7 @@ async fn update_trace_labels_from_cluster(
let mut updated_count = 0u64;
for tid in &all_trace_ids {
if !trace_to_cluster.contains_key(tid) {
let name = format!("Person_{}", tid);
let name = "Unassigned".to_string();
let _ =
schema::upsert_trace_profile(db.pool(), file_uuid, *tid as i32, &name, None)
.await;
+606
View File
@@ -0,0 +1,606 @@
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)
}
+18 -14
View File
@@ -8,13 +8,15 @@ async fn doc_redirect() -> axum::response::Redirect {
async fn wasm_doc_handler() -> Result<impl axum::response::IntoResponse, (StatusCode, &'static str)>
{
let base_str = std::env::var("MOMENTRY_DOCS_DIR")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string()))
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
});
let base_str = std::env::var("MOMENTRY_DOCS_DIR").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| {
p.parent()
.map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string())
})
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
});
let path = std::path::Path::new(&base_str).join("index.html");
match tokio::fs::read_to_string(path).await {
Ok(html) => Ok(([("content-type", "text/html; charset=utf-8")], html)),
@@ -28,13 +30,15 @@ async fn wasm_doc_file_handler(
if file.contains("..") || file.contains("//") {
return Err((StatusCode::NOT_FOUND, "Invalid path"));
}
let base_str = std::env::var("MOMENTRY_DOCS_DIR")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string()))
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
});
let base_str = std::env::var("MOMENTRY_DOCS_DIR").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| {
p.parent()
.map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string())
})
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
});
let base = std::path::Path::new(&base_str);
let path = base.join(&file);
if !path.exists() || !path.starts_with(base) {
+141 -40
View File
@@ -410,7 +410,9 @@ pub(crate) async fn register_single_file(
let temp_probe_json: serde_json::Value = if let Some(ref pre) = pre_data {
pre.get("probe_json").cloned().unwrap_or_default()
} else {
let scripts_dir = crate::core::path_utils::scripts_dir().to_string_lossy().to_string();
let scripts_dir = crate::core::path_utils::scripts_dir()
.to_string_lossy()
.to_string();
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
crate::core::probe::unified::unified_probe(&path, &scripts_dir, &python_path).await
@@ -493,7 +495,7 @@ pub(crate) async fn register_single_file(
}
let status = "registered";
let _ = sqlx::query(&format!(
let insert_result = match sqlx::query(&format!(
"INSERT INTO {} (file_uuid, file_path, file_name, file_type, duration, width, height, fps, total_frames, probe_json, status, content_hash, registration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NOW()) ON CONFLICT (file_uuid) DO UPDATE SET file_path = EXCLUDED.file_path, file_name = EXCLUDED.file_name, status = EXCLUDED.status, content_hash = EXCLUDED.content_hash, duration = EXCLUDED.duration, width = EXCLUDED.width, height = EXCLUDED.height, fps = EXCLUDED.fps, total_frames = EXCLUDED.total_frames, probe_json = EXCLUDED.probe_json",
videos_table
))
@@ -501,12 +503,110 @@ pub(crate) async fn register_single_file(
.bind(duration).bind(width as i32).bind(height as i32).bind(fps)
.bind(total_frames as i64)
.bind(&probe_json).bind(status).bind(&content_hash_val)
.execute(db.pool()).await;
.execute(db.pool()).await
{
Ok(result) => result,
Err(e) => {
tracing::error!("[REGISTER] Failed to insert/update video record for {}: {}", file_uuid, e);
return RegisterFileResponse {
success: false,
file_uuid: file_uuid.clone(),
file_name: final_name,
file_path: canonical_path,
file_type: final_file_type.clone(),
duration,
width,
height,
fps,
total_frames,
registration_time: None,
already_exists: false,
message: format!("Database error: {}", e),
warning: None,
command_id: None,
command_ids: None,
status: None,
};
}
};
tracing::info!(
"[REGISTER] Video {} status set to '{}', affected rows: {}",
file_uuid,
status,
insert_result.rows_affected()
);
// Verify status was written correctly
let verify_status: Option<String> = match sqlx::query_scalar(&format!(
"SELECT status FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(db.pool())
.await
{
Ok(s) => s,
Err(e) => {
tracing::error!("[REGISTER] Failed to verify status for {}: {}", file_uuid, e);
return RegisterFileResponse {
success: false,
file_uuid: file_uuid.clone(),
file_name: final_name,
file_path: canonical_path,
file_type: final_file_type.clone(),
duration,
width,
height,
fps,
total_frames,
registration_time: None,
already_exists: false,
message: format!("Status verification error: {}", e),
warning: None,
command_id: None,
command_ids: None,
status: None,
};
}
};
if verify_status.as_deref() != Some(status) {
tracing::error!(
"[REGISTER] Status verification failed for {}: expected '{}', got '{:?}'",
file_uuid,
status,
verify_status
);
return RegisterFileResponse {
success: false,
file_uuid: file_uuid.clone(),
file_name: final_name,
file_path: canonical_path,
file_type: final_file_type.clone(),
duration,
width,
height,
fps,
total_frames,
registration_time: None,
already_exists: false,
message: "Status verification failed".to_string(),
warning: None,
command_id: None,
command_ids: None,
status: None,
};
}
tracing::info!("[REGISTER] Status verified for {}: {}", file_uuid, status);
let mut cut_done = false;
if has_video && total_frames > 0 && fps > 0.0 {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let scripts_dir = crate::core::path_utils::scripts_dir().to_string_lossy().to_string();
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let scripts_dir = crate::core::path_utils::scripts_dir()
.to_string_lossy()
.to_string();
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
@@ -569,10 +669,8 @@ let output_dir = crate::core::config::OUTPUT_DIR.to_string();
.collect()
});
let audio_tracks_json = serde_json::to_value(&audio_tracks).ok();
let cut_path = std::path::Path::new(
&crate::core::config::OUTPUT_DIR.to_string(),
)
.join(format!("{}.cut.json", file_uuid));
let cut_path = std::path::Path::new(&crate::core::config::OUTPUT_DIR.to_string())
.join(format!("{}.cut.json", file_uuid));
let mut cut_count = 0i32;
let mut cut_max_duration = 0.0f64;
if let Ok(content) = std::fs::read_to_string(&cut_path) {
@@ -601,10 +699,8 @@ let output_dir = crate::core::config::OUTPUT_DIR.to_string();
.execute(db.pool()).await;
if let Some(json_val) = probe_json {
let probe_path = std::path::Path::new(
&crate::core::config::OUTPUT_DIR.to_string(),
)
.join(format!("{}.probe.json", file_uuid));
let probe_path = std::path::Path::new(&crate::core::config::OUTPUT_DIR.to_string())
.join(format!("{}.probe.json", file_uuid));
let json_str = serde_json::to_string_pretty(&json_val).unwrap_or_default();
let _ = std::fs::write(&probe_path, json_str);
}
@@ -656,9 +752,12 @@ async fn register_file(
status: None,
}));
}
tracing::info!("[REGISTER] Sync mode: calling rust_register for {}", req.file_path);
tracing::info!(
"[REGISTER] Sync mode: calling rust_register for {}",
req.file_path
);
// Resolve rust_register at runtime (see unregister for rationale).
let binary_path = std::env::var_os("MOMENTRY_RUST_REGISTER")
.map(std::path::PathBuf::from)
@@ -670,12 +769,12 @@ async fn register_file(
.filter(|p| p.is_file())
})
.unwrap_or_else(|| std::path::PathBuf::from("target/release/rust_register"));
let mut args = vec![req.file_path.clone()];
if req.force {
args.push("--force".to_string());
}
let output = std::process::Command::new(&binary_path)
.args(&args)
.output()
@@ -683,7 +782,7 @@ async fn register_file(
tracing::error!("[REGISTER] Failed to execute rust_register: {:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
let file_uuid = stdout
@@ -692,14 +791,14 @@ async fn register_file(
.and_then(|line| line.split(':').nth(1))
.map(|s| s.trim().to_string())
.unwrap_or_default();
let duration = stdout
.lines()
.find(|line| line.starts_with("[REGISTER] Duration:"))
.and_then(|line| line.split(':').nth(1))
.and_then(|s| s.trim().trim_end_matches('s').parse().ok())
.unwrap_or(0.0);
Ok(Json(RegisterFileResponse {
success: true,
file_uuid,
@@ -1180,9 +1279,7 @@ struct ReScanResponse {
fn delete_output_files(uuid: &str) -> u64 {
let mut deleted_count = 0u64;
// Check multiple output directories
let output_dirs = [
config::OUTPUT_DIR.to_string(),
];
let output_dirs = [config::OUTPUT_DIR.to_string()];
for output_dir in &output_dirs {
if let Ok(entries) = std::fs::read_dir(output_dir) {
@@ -1301,7 +1398,7 @@ async fn unregister(
"[UNREGISTER] Sync mode: calling rust_unregister for {}",
uuid
);
// Resolve rust_unregister at runtime.
// env!("CARGO_MANIFEST_DIR") is baked in at compile time and points at the
// build machine, so it never exists on a binary-only release host.
@@ -1317,7 +1414,7 @@ async fn unregister(
.filter(|p| p.is_file())
})
.unwrap_or_else(|| std::path::PathBuf::from("target/release/rust_unregister"));
let output = std::process::Command::new(&binary_path)
.args(["--uuid", &uuid])
.output()
@@ -1325,7 +1422,7 @@ async fn unregister(
tracing::error!("[UNREGISTER] Failed to execute rust_unregister: {:?}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
if output.status.success() {
Ok(Json(UnregisterResponse {
success: true,
@@ -1383,7 +1480,11 @@ async fn re_scan(
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[RE-SCAN] Failed to query file path for {}: {:?}", file_uuid, e);
tracing::error!(
"[RE-SCAN] Failed to query file path for {}: {:?}",
file_uuid,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
@@ -1395,10 +1496,10 @@ async fn re_scan(
}
};
// Step 2: Create register command with force=true
// Step 2: Create register command with force=true
// Note: force=true will automatically unregister existing file if needed
let auto_pipeline = req.auto_pipeline.unwrap_or(false);
let register_payload = serde_json::json!({
"force": true,
"auto_pipeline": auto_pipeline,
@@ -1413,7 +1514,14 @@ async fn re_scan(
let register_cmd = state
.db
.create_command("register", Some(&file_path), None, None, &register_payload, 1)
.create_command(
"register",
Some(&file_path),
None,
None,
&register_payload,
1,
)
.await
.map_err(|e| {
tracing::error!(
@@ -1436,18 +1544,11 @@ async fn re_scan(
// 3. Trigger auto-pipeline only if auto_pipeline=true (default: false)
let mode = if auto_pipeline { "auto" } else { "manual" };
tracing::info!(
"[RE-SCAN] Mode: {} (auto_pipeline={})",
mode,
auto_pipeline
);
tracing::info!("[RE-SCAN] Mode: {} (auto_pipeline={})", mode, auto_pipeline);
Ok(Json(ReScanResponse {
success: true,
message: format!(
"Re-scan queued: register={}",
register_cmd.command_id
),
message: format!("Re-scan queued: register={}", register_cmd.command_id),
file_uuid,
unregister_command_id: None,
register_command_id: Some(register_cmd.command_id),
+2 -1
View File
@@ -7,6 +7,7 @@ use super::types::AppState;
use crate::core::cache::MongoCache;
use crate::core::config;
use crate::core::db::{Database, PostgresDb, RedisClient};
use crate::core::db::qdrant_db::new_http_client;
use crate::worker::resources::SystemResources;
// Global State
@@ -505,7 +506,7 @@ async fn check_qdrant() -> ServiceStatus {
std::env::var("QDRANT_API_KEY").unwrap_or_else(|_| "Test3200Test3200Test3200".to_string());
let url = format!("{}/collections", base_url);
let client = reqwest::Client::new();
let client = new_http_client();
match client
.get(&url)
.header("api-key", api_key)
+36 -31
View File
@@ -1,10 +1,4 @@
use axum::{
extract::Path,
http::StatusCode,
response::Json,
routing::get,
Router,
};
use axum::{extract::Path, http::StatusCode, response::Json, routing::get, Router};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;
@@ -38,9 +32,9 @@ pub async fn list_user_folders(
})
.join(&username)
.join("files");
let mut folders = Vec::new();
if let Ok(mut entries) = fs::read_dir(&base_path).await {
while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(file_type) = entry.file_type().await {
@@ -54,7 +48,7 @@ pub async fn list_user_folders(
}
}
}
Ok(Json(folders))
}
@@ -62,42 +56,53 @@ pub async fn list_user_folders(
pub async fn list_user_files(
Path(username): Path<String>,
) -> Result<Json<Vec<FileInfo>>, StatusCode> {
let base_path = std::env::var("MOMENTRY_STUDIO_DATA_DIR")
// Use SFTPGo directory as data source
let base_path = std::env::var("MOMENTRY_SFTP_ROOT")
.map(PathBuf::from)
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/studio/data")))
.unwrap_or_else(|| PathBuf::from("var/studio/data"))
})
.join(&username)
.join("files");
PathBuf::from("/Users/accusys/momentry/var/sftpgo/data/demo")
});
let mut files = Vec::new();
if let Ok(mut entries) = fs::read_dir(&base_path).await {
while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(metadata) = entry.metadata().await {
let name = entry.file_name().to_string_lossy().to_string();
let is_dir = metadata.is_dir();
let size = if is_dir { 0 } else { metadata.len() };
let modified = metadata.modified()
let modified = metadata
.modified()
.ok()
.map(|t| format!("{:?}", t))
.and_then(|t| {
t.duration_since(std::time::UNIX_EPOCH)
.ok()
.map(|d| {
chrono::DateTime::from_timestamp(d.as_secs() as i64, 0)
.map(|dt| dt.to_rfc3339())
.unwrap_or_else(|| "Unknown".to_string())
})
})
.unwrap_or_else(|| "Unknown".to_string());
// Only include allowed file types
let ext = name.rsplit('.').next().unwrap_or("");
let allowed = ["mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp"];
files.push(FileInfo {
name,
r#type: if is_dir { "directory".to_string() } else { "file".to_string() },
size,
modified,
is_dir,
});
if !is_dir && allowed.contains(&ext.to_lowercase().as_str()) {
files.push(FileInfo {
name,
r#type: "file".to_string(),
size,
modified,
is_dir,
});
}
}
}
}
Ok(Json(files))
}
+83
View File
@@ -82,6 +82,7 @@ pub fn bbox_routes() -> Router<crate::api::types::AppState> {
get(stranger_video),
)
.route("/api/v1/file/:file_uuid/video", get(stream_video))
.route("/api/v1/file/thumbnail", get(thumbnail_by_path))
.route("/api/v1/file/:file_uuid/thumbnail", get(face_thumbnail))
.route(
"/api/v1/file/:file_uuid/chunk/:chunk_id/thumbnail",
@@ -908,6 +909,12 @@ struct ThumbQuery {
trace_id: Option<i32>,
}
#[derive(Debug, serde::Deserialize)]
struct ThumbnailByPathQuery {
path: Option<String>,
frame: Option<i64>,
}
async fn face_thumbnail_compat(
State(state): State<crate::api::types::AppState>,
Query(q): Query<ThumbQuery>,
@@ -916,6 +923,82 @@ async fn face_thumbnail_compat(
face_thumbnail(State(state), Path(file_uuid), Query(q)).await
}
/// Thumbnail by file path — for unregistered files (no UUID).
/// Frontend calls: GET /api/v1/file/thumbnail?path=<abs_path>&frame=<n>
async fn thumbnail_by_path(
Query(q): Query<ThumbnailByPathQuery>,
) -> Result<impl IntoResponse, StatusCode> {
let file_path = q.path.ok_or(StatusCode::BAD_REQUEST)?;
let frame = q.frame.unwrap_or(0);
// Path safety: must be absolute and within scan root
if !file_path.starts_with('/') {
tracing::warn!("[thumbnail_by_path] Non-absolute path rejected: {}", file_path);
return Err(StatusCode::BAD_REQUEST);
}
let scan_root = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "/tmp".to_string())
});
let canonical_root = std::fs::canonicalize(&scan_root).unwrap_or_else(|_| {
std::path::PathBuf::from(&scan_root)
});
let canonical_file = std::fs::canonicalize(&file_path).unwrap_or_else(|_| {
std::path::PathBuf::from(&file_path)
});
if !canonical_file.starts_with(&canonical_root) {
tracing::warn!(
"[thumbnail_by_path] Path outside scan root rejected: {} (root: {})",
file_path, scan_root
);
return Err(StatusCode::FORBIDDEN);
}
if !canonical_file.is_file() {
return Err(StatusCode::NOT_FOUND);
}
// Extract frame with ffmpeg
let select = format!("select=eq(n\\,{})", frame);
let output = ffmpeg_cmd()
.args([
"-i",
&file_path,
"-vf",
&select,
"-frames:v",
"1",
"-f",
"image2pipe",
"-vcodec",
"mjpeg",
"-",
])
.output()
.map_err(|e| {
tracing::warn!("[thumbnail_by_path] ffmpeg spawn failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
if !output.status.success() {
tracing::warn!("[thumbnail_by_path] ffmpeg failed for: {}", file_path);
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
crate::core::thumbnail::validator::validate_jpeg(&output.stdout).map_err(|e| {
tracing::warn!("[thumbnail_by_path] JPEG validation failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(image_response(output.stdout))
}
/// Direct access to trace key_face.jpg — bypasses ffmpeg, reads pre-cached file.
/// Used by Studio for fast face group thumbnail loading.
async fn trace_thumbnail(
+49 -2
View File
@@ -2,10 +2,11 @@ use axum::{
extract::{Request, State},
http::{header::HeaderMap, StatusCode},
middleware::Next,
response::Response,
response::{IntoResponse, Response},
};
use sha2::{Digest, Sha256};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use tokio::sync::Semaphore;
use crate::core::auth::jwt;
use crate::core::billing::set_request_context;
@@ -39,6 +40,52 @@ pub struct ApiState {
pub db: Arc<PostgresDb>,
}
/// Max in-flight API requests. A page load fans out to thousands of
/// stats/thumbnail calls; without a cap the accept loop falls behind the
/// handshake rate and the kernel starts RST-ing connections.
static REQUEST_PERMITS: OnceLock<Arc<Semaphore>> = OnceLock::new();
const REQUEST_CONCURRENCY_DEFAULT: usize = 40;
fn request_semaphore() -> &'static Arc<Semaphore> {
REQUEST_PERMITS.get_or_init(|| {
let n = std::env::var("MOMENTRY_MAX_CONCURRENT_REQUESTS")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|v| *v > 0)
.unwrap_or(REQUEST_CONCURRENCY_DEFAULT);
tracing::info!("API request concurrency limit: {}", n);
Arc::new(Semaphore::new(n))
})
}
/// Reject excess load with 429 + Retry-After instead of letting the process
/// wedge. Health endpoints bypass the limiter so probes always get through.
pub async fn concurrency_limit(request: Request, next: Next) -> Response {
let path = request.uri().path().to_string();
if path.starts_with("/api/v1/health") || path.starts_with("/static") {
return next.run(request).await;
}
let permit = match request_semaphore().clone().try_acquire_owned() {
Ok(p) => p,
Err(_) => {
tracing::warn!("[Concurrency] rejected {} {} (429)", request.method(), path);
return (
StatusCode::TOO_MANY_REQUESTS,
[("retry-after", "1")],
"server busy: too many concurrent requests",
)
.into_response();
}
};
let response = next.run(request).await;
drop(permit);
response
}
pub fn extract_cookies(headers: &HeaderMap) -> Vec<(String, String)> {
let cookie_header = match headers.get("cookie").and_then(|v| v.to_str().ok()) {
Some(c) => c,
+1 -1
View File
@@ -13,6 +13,7 @@ pub mod identities;
pub mod identity_api;
pub mod identity_binding;
pub mod llm_search;
pub mod markbase_compat;
pub mod media_api;
pub mod middleware;
pub mod pipeline;
@@ -21,7 +22,6 @@ pub mod profile;
pub mod scan;
pub mod search;
pub mod server;
pub mod markbase_compat;
pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
+209 -81
View File
@@ -1,130 +1,258 @@
use axum::extract::Path;
use axum::routing::post;
use axum::extract::{Path, State};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::core::config;
use crate::core::db::postgres_db::PostgresDb;
use crate::core::pipeline as pipeline_core;
use crate::core::command::pipeline::PipelineService;
use crate::core::command::queue::CommandQueue;
use crate::core::command::types::CommandStatus;
use crate::api::types::AppState;
/// 队列提交响应
#[derive(Debug, Serialize)]
pub struct QueueSubmitResponse {
pub success: bool,
pub command_id: String,
pub file_uuid: String,
pub status: String,
pub estimated_duration_sec: u64,
}
/// 命令状态响应
#[derive(Debug, Serialize)]
pub struct CommandStatusResponse {
pub command_id: String,
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_started_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_completed_at: Option<String>,
}
/// 进度更新请求
#[derive(Debug, Deserialize)]
pub struct ProgressUpdateRequest {
pub progress: u8,
pub message: String,
}
/// 提交 ASRX 存储命令
async fn handle_store_asrx(
Path(uuid): Path<String>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
let db = PostgresDb::new(&config::DATABASE_URL).await.map_err(|e| {
tracing::error!("DB error: {}", e);
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<QueueSubmitResponse>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let service = PipelineService::new(db);
let command_id = service.store_asrx(&file_uuid).await.map_err(|e| {
tracing::error!("Failed to queue store_asrx: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "DB connection failed"})),
Json(json!({"error": e.to_string()})),
)
})?;
pipeline_core::store_asrx_chunks(&db, &uuid)
.await
.map_err(|e| {
tracing::error!("store_asrx error: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(
json!({"success": true, "message": "ASRX chunks stored", "file_uuid": uuid}),
))
Ok(Json(QueueSubmitResponse {
success: true,
command_id,
file_uuid,
status: "queued".to_string(),
estimated_duration_sec: 5,
}))
}
/// 提交 Rule1 命令
async fn handle_rule1(
Path(uuid): Path<String>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
let db = PostgresDb::new(&config::DATABASE_URL).await.map_err(|e| {
tracing::error!("DB error: {}", e);
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<QueueSubmitResponse>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let service = PipelineService::new(db);
let command_id = service.execute_rule1(&file_uuid).await.map_err(|e| {
tracing::error!("Failed to queue rule1: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "DB connection failed"})),
Json(json!({"error": e.to_string()})),
)
})?;
let count = pipeline_core::execute_rule1(&db, &uuid)
.await
.map_err(|e| {
tracing::error!("rule1 error: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(
json!({"success": true, "message": format!("Rule 1 complete: {} chunks", count), "file_uuid": uuid, "chunks": count}),
))
Ok(Json(QueueSubmitResponse {
success: true,
command_id,
file_uuid,
status: "queued".to_string(),
estimated_duration_sec: 10,
}))
}
/// 提交向量化命令
async fn handle_vectorize(
Path(uuid): Path<String>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
pipeline_core::vectorize_chunks(&uuid).await.map_err(|e| {
tracing::error!("vectorize error: {}", e);
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<QueueSubmitResponse>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let service = PipelineService::new(db);
let command_id = service.vectorize_chunks(&file_uuid).await.map_err(|e| {
tracing::error!("Failed to queue vectorize: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(
json!({"success": true, "message": "Vectorization complete", "file_uuid": uuid}),
))
Ok(Json(QueueSubmitResponse {
success: true,
command_id,
file_uuid,
status: "queued".to_string(),
estimated_duration_sec: 120,
}))
}
/// 提交 Phase1 命令
async fn handle_phase1(
Path(uuid): Path<String>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
pipeline_core::run_phase1(&uuid).await.map_err(|e| {
tracing::error!("phase1 error: {}", e);
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<QueueSubmitResponse>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let service = PipelineService::new(db);
let command_id = service.phase1_pack(&file_uuid).await.map_err(|e| {
tracing::error!("Failed to queue phase1: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(
json!({"success": true, "message": "Phase 1 complete", "file_uuid": uuid}),
))
Ok(Json(QueueSubmitResponse {
success: true,
command_id,
file_uuid,
status: "queued".to_string(),
estimated_duration_sec: 10,
}))
}
/// 提交标记完成命令
async fn handle_complete(
Path(uuid): Path<String>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
let db = PostgresDb::new(&config::DATABASE_URL).await.map_err(|e| {
tracing::error!("DB error: {}", e);
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<QueueSubmitResponse>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let service = PipelineService::new(db);
let command_id = service.mark_complete(&file_uuid).await.map_err(|e| {
tracing::error!("Failed to queue complete: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "DB connection failed"})),
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(QueueSubmitResponse {
success: true,
command_id,
file_uuid,
status: "queued".to_string(),
estimated_duration_sec: 5,
}))
}
pipeline_core::mark_complete(&db, &uuid)
.await
.map_err(|e| {
tracing::error!("complete error: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
/// 提交完整 pipeline 流程
async fn handle_full_pipeline(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let service = PipelineService::new(db);
let command_ids = service.submit_full_pipeline(&file_uuid).await.map_err(|e| {
tracing::error!("Failed to queue full pipeline: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(json!({
"success": true,
"file_uuid": file_uuid,
"commands_queued": command_ids.len(),
"command_ids": command_ids,
"estimated_total_duration_sec": 150,
"status": "queued"
})))
}
Ok(Json(
json!({"success": true, "message": "Video marked as completed", "file_uuid": uuid}),
))
/// 查询命令状态
async fn handle_command_status(
State(state): State<AppState>,
Path(command_id): Path<String>,
) -> Result<Json<CommandStatusResponse>, (axum::http::StatusCode, Json<Value>)> {
let db = state.db.pool().clone();
let queue = CommandQueue::new(db).await.map_err(|e| {
tracing::error!("Failed to create queue: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "Queue initialization failed"})),
)
})?;
let message = queue.get_command_status(&command_id).await.map_err(|e| {
tracing::error!("Failed to get command status: {}", e);
(
axum::http::StatusCode::NOT_FOUND,
Json(json!({"error": "Command not found"})),
)
})?;
Ok(Json(CommandStatusResponse {
command_id: command_id.clone(),
status: match message.status {
CommandStatus::Pending => "pending",
CommandStatus::Processing => "processing",
CommandStatus::Completed => "completed",
CommandStatus::Failed => "failed",
}.to_string(),
last_error: message.last_error,
processing_started_at: message.processing_started_at.map(|t| t.to_rfc3339()),
processing_completed_at: message.processing_completed_at.map(|t| t.to_rfc3339()),
}))
}
/// 更新进度 (Worker 内部使用)
async fn handle_update_progress(
State(state): State<AppState>,
Path(command_id): Path<String>,
Json(req): Json<ProgressUpdateRequest>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
let _db = state.db.pool().clone();
Ok(Json(json!({
"success": true,
"command_id": command_id,
"progress": req.progress,
"message": req.message
})))
}
pub fn pipeline_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route(
"/api/v1/file/:file_uuid/store-asrx",
post(handle_store_asrx),
)
// 原有端点 (改为异步队列)
.route("/api/v1/file/:file_uuid/store-asrx", post(handle_store_asrx))
.route("/api/v1/file/:file_uuid/rule1", post(handle_rule1))
.route("/api/v1/file/:file_uuid/vectorize", post(handle_vectorize))
.route("/api/v1/file/:file_uuid/phase1", post(handle_phase1))
.route("/api/v1/file/:file_uuid/complete", post(handle_complete))
}
// 新端点
.route("/api/v1/file/:file_uuid/pipeline", post(handle_full_pipeline))
.route("/api/v1/pipeline/status/:command_id", get(handle_command_status))
.route("/api/v1/pipeline/progress/:command_id", post(handle_update_progress))
}
+3 -3
View File
@@ -344,7 +344,7 @@ async fn trigger_processing(
// If force=true, delete output files to force re-processing
if req.force {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let deleted_count = delete_output_files_for_uuid(&file_uuid, &output_dir);
tracing::info!(
"[TRIGGER] Force re-scan: deleted {} output files for {}",
@@ -467,7 +467,7 @@ async fn download_json(
State(state): State<AppState>,
Path((file_uuid, processor)): Path<(String, String)>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let path = std::path::Path::new(&output_dir).join(format!("{}.{}.json", file_uuid, processor));
let content = tokio::fs::read_to_string(&path)
.await
@@ -876,7 +876,7 @@ async fn get_processor_counts(
}
}
}
// Special handling for face_cluster: query trace_profiles if frame_count is None
if proc_name == "face_cluster" && frame_count.is_none() {
let tp_table = crate::core::db::schema::table_name("trace_profiles");
+93 -15
View File
@@ -26,6 +26,8 @@ struct FileStatsResponse {
processors: Vec<ProcessorStatus>,
// PostgreSQL counts
postgres: PostgresStats,
// ASRX stats
asrx: AsrxStats,
// Qdrant collection counts
qdrant: QdrantStats,
// TKG stats
@@ -56,6 +58,13 @@ struct PostgresStats {
file_identities: i64,
}
#[derive(Debug, Serialize, Default)]
struct AsrxStats {
status: Option<String>,
segment_count: i32,
language: Option<String>,
}
#[derive(Debug, Serialize)]
struct QdrantStats {
faces: i64,
@@ -241,14 +250,13 @@ async fn scan_files(
State(state): State<AppState>,
Query(params): Query<ScanFilesQuery>,
) -> Result<Json<ScanFilesResponse>, StatusCode> {
let demo_dir_str = std::env::var("MOMENTRY_SFTP_ROOT")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/sftpgo/data/demo".to_string())
});
let demo_dir_str = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/sftpgo/data/demo".to_string())
});
let demo_dir = std::path::Path::new(&demo_dir_str);
let allowed_extensions = vec![
@@ -431,8 +439,8 @@ struct RegisteredVideo {
async fn get_sftpgo_status(
State(state): State<AppState>,
) -> Result<Json<SftpgoStatusResponse>, StatusCode> {
let demo_dir = std::env::var("MOMENTRY_SFTP_ROOT")
.unwrap_or_else(|_| "var/sftpgo/data/demo".to_string());
let demo_dir =
std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| "var/sftpgo/data/demo".to_string());
let files_count: i64 = std::fs::read_dir(&demo_dir)
.map(|entries| entries.count() as i64)
@@ -816,6 +824,29 @@ async fn get_ingestion_status(
async fn get_file_stats(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<FileStatsResponse>, StatusCode> {
// Wrap entire handler in a 60-second timeout to prevent indefinite
// hangs from multiple scroll_all_points calls or slow DB queries.
// This is the last line of defense: each individual HTTP call has a
// 30s timeout (via new_http_client), but multiple calls + DB queries
// could still exceed reasonable response time.
match tokio::time::timeout(
std::time::Duration::from_secs(60),
get_file_stats_inner(state, file_uuid),
)
.await
{
Ok(result) => result,
Err(_) => {
tracing::error!("get_file_stats timed out after 60s");
Err(StatusCode::REQUEST_TIMEOUT)
}
}
}
async fn get_file_stats_inner(
state: AppState,
file_uuid: String,
) -> Result<Json<FileStatsResponse>, StatusCode> {
let pool = state.db.pool();
@@ -959,7 +990,48 @@ async fn get_file_stats(
.unwrap_or(0),
};
// 4. Get Qdrant stats
// 4. Get ASRX stats from processor_results
let pr_table = schema::table_name("processor_results");
let mj_table = schema::table_name("monitor_jobs");
#[derive(sqlx::FromRow)]
struct AsrxRow {
status: Option<String>,
segment_count: i32,
language: Option<String>,
}
let asrx_data_result = sqlx::query_as::<_, AsrxRow>(&format!(
"SELECT pr.asr_status AS status, COALESCE(pr.segment_count, 0) AS segment_count, pr.output_data->>'language' AS language \
FROM {pr_table} pr \
JOIN {mj_table} mj ON pr.job_id = mj.id \
WHERE mj.uuid = $1 AND pr.processor = 'asrx' \
LIMIT 1"
))
.bind(&file_uuid)
.fetch_optional(pool)
.await;
let asrx = match asrx_data_result {
Ok(Some(row)) => {
eprintln!("[ASRX-DEBUG] Found data: status={:?}, segment_count={}, language={:?}", row.status, row.segment_count, row.language);
AsrxStats {
status: row.status,
segment_count: row.segment_count,
language: row.language,
}
}
Ok(None) => {
eprintln!("[ASRX-DEBUG] No ASRX data found for uuid={}", file_uuid);
AsrxStats::default()
}
Err(e) => {
eprintln!("[ASRX-DEBUG] Query failed for uuid={}: {}", file_uuid, e);
AsrxStats::default()
}
};
// 5. Get Qdrant stats
use crate::core::db::qdrant_db::QdrantDb;
use serde_json::json;
@@ -1202,6 +1274,7 @@ async fn get_file_stats(
processing_completed_at,
processors,
postgres,
asrx,
qdrant: qdrant_stats,
tkg,
face_dedup,
@@ -1390,7 +1463,12 @@ async fn get_pipeline_progress_handler(
pp.update_stage("face_dedup", 1.0, "completed", Some("no faces".to_string()));
} else if tkg_edge_count == 0 {
// Faces detected but no relationships
pp.update_stage("face_dedup", 1.0, "completed", Some("no relationships".to_string()));
pp.update_stage(
"face_dedup",
1.0,
"completed",
Some("no relationships".to_string()),
);
}
}
@@ -1419,15 +1497,15 @@ async fn get_pipeline_progress_handler(
} else {
"running"
};
let vlm_progress = if vlm_total == 0 {
1.0 // Completed with 0 results
1.0 // Completed with 0 results
} else if vlm_done > 0 {
vlm_done as f64 / vlm_total as f64
} else {
0.0
};
pp.update_stage(
"vlm_summary",
vlm_progress,
+4 -1
View File
@@ -19,13 +19,13 @@ use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::files;
use super::markbase_compat;
use super::health;
use super::health::{health, health_consistency, health_detailed};
use super::identities;
use super::identity_api;
use super::identity_binding;
use super::llm_search;
use super::markbase_compat;
use super::media_api;
use super::middleware::unified_auth;
use super::pipeline;
@@ -183,6 +183,9 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
.merge(protected_routes)
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.layer(axum::middleware::from_fn(
super::middleware::concurrency_limit,
))
.with_state(state);
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap();
+6 -4
View File
@@ -2712,14 +2712,16 @@ fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize {
/// Read trace_profile.json for a given file_uuid and trace_id.
fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option<serde_json::Value> {
use std::path::PathBuf;
let profile_path: PathBuf = [
crate::core::config::OUTPUT_DIR.as_str(),
file_uuid,
&format!("trace_{}", trace_id),
"trace_profile.json"
].iter().collect();
"trace_profile.json",
]
.iter()
.collect();
if let Ok(content) = std::fs::read_to_string(&profile_path) {
if let Ok(profile) = serde_json::from_str::<serde_json::Value>(&content) {
return Some(profile);