feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx
Consolidated snapshot (previously WIP in working tree). - core/pipeline_config: new module loading config/pipeline_flows.json as the source of truth for stage execution mode (parallel/blocking) and dependencies - worker/job_worker: dispatch Scene VLM to a background task when the stage is declared parallel, unblocking the worker poll loop; resolve processor dependencies from pipeline_flows.json (fallback to built-in) - config/pipeline_flows.json: asrx depends on [cut, asr] - scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold to 6h, skip jobs with recent processor activity - rust_asrx: Rust speaker diarization CLI + processor wiring - processor metadata helper; fast_face_clustering script; file_progress pipeline API; scan API; VAD updates
This commit is contained in:
@@ -22,6 +22,7 @@ pub fn admin_config_routes() -> Router<AppState> {
|
||||
put(update_vlm_prompt),
|
||||
)
|
||||
.route("/api/v1/admin/config/reload", post(reload_config))
|
||||
.route("/api/v1/admin/settings", get(get_settings))
|
||||
}
|
||||
|
||||
pub async fn get_config(State(state): State<AppState>) -> Result<Json<Value>, StatusCode> {
|
||||
@@ -88,3 +89,16 @@ pub async fn reload_config(State(state): State<AppState>) -> Result<Json<Value>,
|
||||
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
}
|
||||
}
|
||||
|
||||
// Settings endpoint - alias for /admin/config for frontend compatibility
|
||||
pub async fn get_settings(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
|
||||
let config = state.admin_config_manager.get_full_config().await;
|
||||
Ok(Json(serde_json::to_value(config).map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Failed to serialize config: {}", e),
|
||||
)
|
||||
})?))
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ async fn login(
|
||||
|
||||
let body = serde_json::json!({
|
||||
"success": true,
|
||||
"token": jwt_token.clone(),
|
||||
"jwt": jwt_token,
|
||||
"api_key": DEMO_USER_API_KEY.clone(),
|
||||
"user": {
|
||||
|
||||
@@ -0,0 +1,685 @@
|
||||
//! Phase-based pipeline progress API (V2).
|
||||
//!
|
||||
//! Exposes two endpoints consumed by the Studio frontend:
|
||||
//! GET /api/v1/pipeline/phases → phase config (from config/pipeline_flows.json)
|
||||
//! GET /api/v1/file/:file_uuid/progress → per-phase / per-processor progress
|
||||
//!
|
||||
//! Progress is computed from Redis per-processor status + PostgreSQL
|
||||
//! `processor_results`, then clamped with a per-file Redis high-water mark so a
|
||||
//! phase never moves backwards during a run. The high-water mark is cleared by
|
||||
//! the worker when a new job starts (see `job_worker.rs`).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::Json,
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::Row;
|
||||
|
||||
use super::types::AppState;
|
||||
use crate::core::config::REDIS_KEY_PREFIX;
|
||||
use crate::core::db::{schema, RedisClient};
|
||||
|
||||
// ── Config (config/pipeline_flows.json) ─────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct RawStage {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
progress_weight: f64,
|
||||
#[serde(default)]
|
||||
dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Default)]
|
||||
struct RawFlow {
|
||||
#[serde(default)]
|
||||
stages: Vec<RawStage>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct RawPhase {
|
||||
#[serde(default)]
|
||||
id: i64,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
name_en: Option<String>,
|
||||
#[serde(default)]
|
||||
progress_weight: f64,
|
||||
#[serde(default)]
|
||||
processors: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Default)]
|
||||
struct RawConfig {
|
||||
#[serde(default)]
|
||||
phases: Vec<RawPhase>,
|
||||
#[serde(default)]
|
||||
flows: HashMap<String, RawFlow>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ProcDef {
|
||||
name: String,
|
||||
weight: f64,
|
||||
depends_on: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PhaseDef {
|
||||
key: String,
|
||||
order: i64,
|
||||
weight: f64,
|
||||
processors: Vec<ProcDef>,
|
||||
}
|
||||
|
||||
fn load_config() -> &'static RawConfig {
|
||||
static CFG: OnceLock<RawConfig> = OnceLock::new();
|
||||
CFG.get_or_init(|| {
|
||||
let candidates = [
|
||||
crate::core::path_utils::config_dir().join("pipeline_flows.json"),
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config/pipeline_flows.json"),
|
||||
];
|
||||
for path in candidates {
|
||||
if let Ok(s) = std::fs::read_to_string(&path) {
|
||||
if let Ok(cfg) = serde_json::from_str::<RawConfig>(&s) {
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::warn!("file_progress: pipeline_flows.json not found, using empty phase config");
|
||||
RawConfig::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn phase_defs() -> &'static Vec<PhaseDef> {
|
||||
static DEFS: OnceLock<Vec<PhaseDef>> = OnceLock::new();
|
||||
DEFS.get_or_init(|| build_phase_defs(load_config()))
|
||||
}
|
||||
|
||||
fn build_phase_defs(cfg: &RawConfig) -> Vec<PhaseDef> {
|
||||
let mut stage_meta: HashMap<String, (f64, Vec<String>)> = HashMap::new();
|
||||
if let Some(flow) = cfg.flows.get("register") {
|
||||
for s in &flow.stages {
|
||||
stage_meta.insert(s.name.clone(), (s.progress_weight, s.dependencies.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
let mut defs: Vec<PhaseDef> = cfg
|
||||
.phases
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let processors: Vec<ProcDef> = p
|
||||
.processors
|
||||
.iter()
|
||||
.map(|name| {
|
||||
let (w, deps) = stage_meta.get(name).cloned().unwrap_or((0.0, Vec::new()));
|
||||
let weight = if w > 0.0 { w } else { 1.0 };
|
||||
ProcDef {
|
||||
name: name.clone(),
|
||||
weight,
|
||||
depends_on: deps,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
PhaseDef {
|
||||
key: p.name_en.clone().unwrap_or_else(|| p.name.clone()),
|
||||
order: if p.id != 0 { p.id } else { i as i64 + 1 },
|
||||
weight: if p.progress_weight > 0.0 {
|
||||
p.progress_weight
|
||||
} else {
|
||||
1.0
|
||||
},
|
||||
processors,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
defs.sort_by_key(|d| d.order);
|
||||
defs
|
||||
}
|
||||
|
||||
// ── Aggregation ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// Resolved input for phase aggregation (one entry per processor).
|
||||
#[derive(Debug, Clone)]
|
||||
struct PhaseAggInput {
|
||||
weight: f64,
|
||||
applicable: bool,
|
||||
status: String,
|
||||
progress: f64,
|
||||
}
|
||||
|
||||
/// Compute a phase's weighted progress (0..1) and status from its processors.
|
||||
/// Only applicable processors contribute to the denominator; once the file is
|
||||
/// completed the phase is forced to 1.0.
|
||||
fn aggregate_phase(procs: &[PhaseAggInput], file_completed: bool) -> (f64, String) {
|
||||
let mut total_weight = 0.0;
|
||||
let mut weighted = 0.0;
|
||||
let mut any_running = false;
|
||||
let mut any_failed = false;
|
||||
|
||||
for p in procs {
|
||||
match p.status.as_str() {
|
||||
"running" | "processing" => any_running = true,
|
||||
"failed" | "error" => any_failed = true,
|
||||
_ => {}
|
||||
}
|
||||
if p.applicable {
|
||||
total_weight += p.weight;
|
||||
weighted += p.weight * p.progress;
|
||||
}
|
||||
}
|
||||
|
||||
let progress = if file_completed {
|
||||
1.0
|
||||
} else if total_weight > 0.0 {
|
||||
(weighted / total_weight).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let status = if progress >= 1.0 {
|
||||
"completed"
|
||||
} else if any_failed {
|
||||
"failed"
|
||||
} else if any_running || progress > 0.0 {
|
||||
"running"
|
||||
} else {
|
||||
"pending"
|
||||
};
|
||||
|
||||
(progress, status.to_string())
|
||||
}
|
||||
|
||||
// ── Response types ──────────────────────────────────────────────────────────
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PhaseProcessorResponse {
|
||||
name: String,
|
||||
weight: f64,
|
||||
depends_on: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PhaseConfigResponse {
|
||||
name: String,
|
||||
weight: f64,
|
||||
processors: Vec<PhaseProcessorResponse>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PhasesResponse {
|
||||
phases: Vec<PhaseConfigResponse>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct ProcessorProgressDetail {
|
||||
name: String,
|
||||
status: String,
|
||||
progress: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PhaseProgressDetail {
|
||||
status: String,
|
||||
progress: f64,
|
||||
processors: HashMap<String, ProcessorProgressDetail>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct FileProgressResponse {
|
||||
file_uuid: String,
|
||||
overall_progress: f64,
|
||||
current_phase: Option<String>,
|
||||
phases: HashMap<String, PhaseProgressDetail>,
|
||||
}
|
||||
|
||||
// ── Routes ──────────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn file_progress_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/pipeline/phases", get(get_pipeline_phases))
|
||||
.route("/api/v1/file/:file_uuid/progress", get(get_file_progress))
|
||||
}
|
||||
|
||||
/// Static phase configuration for the frontend.
|
||||
async fn get_pipeline_phases() -> Json<PhasesResponse> {
|
||||
let phases = phase_defs()
|
||||
.iter()
|
||||
.map(|p| PhaseConfigResponse {
|
||||
name: p.key.clone(),
|
||||
weight: p.weight,
|
||||
processors: p
|
||||
.processors
|
||||
.iter()
|
||||
.map(|pr| PhaseProcessorResponse {
|
||||
name: pr.name.clone(),
|
||||
weight: pr.weight,
|
||||
depends_on: pr.depends_on.clone(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
Json(PhasesResponse { phases })
|
||||
}
|
||||
|
||||
/// Per-phase / per-processor progress for a file.
|
||||
async fn get_file_progress(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<FileProgressResponse>, StatusCode> {
|
||||
let defs = phase_defs();
|
||||
|
||||
// 1. Video status + processing status
|
||||
let videos_table = schema::table_name("videos");
|
||||
let video_row = sqlx::query(&format!(
|
||||
"SELECT COALESCE(status::text, '') AS status, \
|
||||
COALESCE(processing_status::text, '') AS ps \
|
||||
FROM {} WHERE file_uuid = $1",
|
||||
videos_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("file_progress video query failed: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let (video_status, status_phase, active_set) = match video_row {
|
||||
Some(r) => {
|
||||
let status: String = r.try_get("status").unwrap_or_default();
|
||||
let ps: String = r.try_get("ps").unwrap_or_default();
|
||||
let parsed = serde_json::from_str::<serde_json::Value>(&ps).ok();
|
||||
let phase = parsed
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("phase").and_then(|p| p.as_str()))
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let active: HashSet<String> = parsed
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("active_processors").and_then(|a| a.as_array()))
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|x| x.as_str())
|
||||
.map(|s| s.to_lowercase())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
(status, phase, active)
|
||||
}
|
||||
None => (String::new(), String::new(), HashSet::new()),
|
||||
};
|
||||
|
||||
let file_completed = video_status == "completed" || status_phase == "COMPLETED";
|
||||
|
||||
// 2. PostgreSQL processor_results (latest status per processor)
|
||||
let pr_table = schema::table_name("processor_results");
|
||||
let pr_rows = sqlx::query(&format!(
|
||||
"SELECT DISTINCT ON (processor) processor, status FROM {} \
|
||||
WHERE uuid = $1 ORDER BY processor, id DESC",
|
||||
pr_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut db_status: HashMap<String, String> = HashMap::new();
|
||||
for r in &pr_rows {
|
||||
let processor: String = r.try_get("processor").unwrap_or_default();
|
||||
let status: String = r.try_get("status").unwrap_or_default();
|
||||
db_status.insert(processor.to_lowercase(), status.to_lowercase());
|
||||
}
|
||||
|
||||
// 3. Redis per-processor realtime status
|
||||
let redis = RedisClient::new().ok();
|
||||
let prefix = REDIS_KEY_PREFIX.as_str();
|
||||
|
||||
let mut redis_status: HashMap<String, (String, f64)> = HashMap::new();
|
||||
if let Some(redis) = redis.as_ref() {
|
||||
if let Ok(mut conn) = redis.get_conn().await {
|
||||
for p in defs.iter().flat_map(|d| d.processors.iter()) {
|
||||
if redis_status.contains_key(&p.name) {
|
||||
continue;
|
||||
}
|
||||
let key = format!("{}job:{}:processor:{}", prefix, file_uuid, p.name);
|
||||
let fields: HashMap<String, String> = redis::cmd("HGETALL")
|
||||
.arg(&key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if fields.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let status = fields
|
||||
.get("status")
|
||||
.map(|s| s.to_lowercase())
|
||||
.unwrap_or_else(|| "pending".to_string());
|
||||
let current: f64 = fields
|
||||
.get("current")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(0.0);
|
||||
let total: f64 = fields
|
||||
.get("total")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(0.0);
|
||||
let progress = if status == "completed" || status == "skipped" {
|
||||
1.0
|
||||
} else if total > 0.0 {
|
||||
(current / total).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
redis_status.insert(p.name.clone(), (status, progress));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. TKG progress (Redis :tkg key)
|
||||
let mut tkg_status = ("pending".to_string(), 0.0_f64);
|
||||
if let Some(redis) = redis.as_ref() {
|
||||
if let Ok(mut conn) = redis.get_conn().await {
|
||||
let key = format!("{}progress:{}:tkg", prefix, file_uuid);
|
||||
let val: Option<String> = redis::cmd("GET")
|
||||
.arg(&key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.ok();
|
||||
if let Some(s) = val {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&s) {
|
||||
let phase = v.get("phase").and_then(|p| p.as_str()).unwrap_or("");
|
||||
let progress = v
|
||||
.get("overall_progress")
|
||||
.and_then(|p| p.as_f64())
|
||||
.unwrap_or(0.0)
|
||||
.clamp(0.0, 1.0);
|
||||
let status = if phase == "completed" {
|
||||
"completed"
|
||||
} else if phase == "failed" {
|
||||
"failed"
|
||||
} else if progress > 0.0 {
|
||||
"running"
|
||||
} else {
|
||||
"pending"
|
||||
};
|
||||
tkg_status = (status.to_string(), progress);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Assemble per-phase progress
|
||||
let mut phases_out: HashMap<String, PhaseProgressDetail> = HashMap::new();
|
||||
let mut ordered: Vec<(String, f64, String)> = Vec::new();
|
||||
|
||||
for def in defs.iter() {
|
||||
let mut procs_out: HashMap<String, ProcessorProgressDetail> = HashMap::new();
|
||||
let mut resolved: Vec<PhaseAggInput> = Vec::with_capacity(def.processors.len());
|
||||
|
||||
for p in def.processors.iter() {
|
||||
let is_tkg = p.name == "tkg";
|
||||
|
||||
let has_signal = if is_tkg {
|
||||
tkg_status.0 != "pending" || tkg_status.1 > 0.0
|
||||
} else {
|
||||
redis_status.contains_key(&p.name) || db_status.contains_key(&p.name)
|
||||
};
|
||||
|
||||
// A processor counts toward the phase only when it is part of this
|
||||
// job (active_processors) or has already produced a signal. This
|
||||
// avoids a phase reporting 100% while sibling processors are still
|
||||
// pending, and avoids stalling on processors that never run.
|
||||
let applicable = file_completed || has_signal || active_set.contains(&p.name);
|
||||
|
||||
let (mut status, mut progress) = if is_tkg {
|
||||
(tkg_status.0.clone(), tkg_status.1)
|
||||
} else if let Some((s, pr)) = redis_status.get(&p.name) {
|
||||
(s.clone(), *pr)
|
||||
} else if let Some(s) = db_status.get(&p.name) {
|
||||
let pr = if s == "completed" || s == "skipped" {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
(s.clone(), pr)
|
||||
} else {
|
||||
("pending".to_string(), 0.0_f64)
|
||||
};
|
||||
|
||||
if file_completed {
|
||||
status = "completed".to_string();
|
||||
progress = 1.0;
|
||||
}
|
||||
|
||||
resolved.push(PhaseAggInput {
|
||||
weight: p.weight,
|
||||
applicable,
|
||||
status: status.clone(),
|
||||
progress,
|
||||
});
|
||||
|
||||
let name = p.name.clone();
|
||||
procs_out.insert(
|
||||
name.clone(),
|
||||
ProcessorProgressDetail {
|
||||
name,
|
||||
status,
|
||||
progress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let (phase_progress, phase_status) = aggregate_phase(&resolved, file_completed);
|
||||
|
||||
phases_out.insert(
|
||||
def.key.clone(),
|
||||
PhaseProgressDetail {
|
||||
status: phase_status.clone(),
|
||||
progress: phase_progress,
|
||||
processors: procs_out,
|
||||
},
|
||||
);
|
||||
ordered.push((def.key.clone(), phase_progress, phase_status));
|
||||
}
|
||||
|
||||
// 6. Apply monotonic high-water mark (never regress within a run)
|
||||
if let Some(redis) = redis.as_ref() {
|
||||
if let Ok(mut conn) = redis.get_conn().await {
|
||||
let hwm_key = format!("{}progress:{}:phase_hwm", prefix, file_uuid);
|
||||
let stored: Option<String> = redis::cmd("GET")
|
||||
.arg(&hwm_key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
let mut hwm: HashMap<String, f64> = stored
|
||||
.and_then(|s| serde_json::from_str::<HashMap<String, f64>>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
for (key, phase) in phases_out.iter_mut() {
|
||||
let prev = hwm.get(key).copied().unwrap_or(0.0);
|
||||
if prev > phase.progress {
|
||||
phase.progress = prev;
|
||||
}
|
||||
if phase.progress >= 1.0 {
|
||||
phase.status = "completed".to_string();
|
||||
}
|
||||
hwm.insert(key.clone(), phase.progress);
|
||||
}
|
||||
|
||||
for entry in ordered.iter_mut() {
|
||||
if let Some(phase) = phases_out.get(&entry.0) {
|
||||
entry.1 = phase.progress;
|
||||
entry.2 = phase.status.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(json) = serde_json::to_string(&hwm) {
|
||||
let _: Result<(), _> = redis::cmd("SET")
|
||||
.arg(&hwm_key)
|
||||
.arg(&json)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Overall + current phase
|
||||
let overall = ordered
|
||||
.iter()
|
||||
.map(|(key, progress, _)| {
|
||||
let weight = defs
|
||||
.iter()
|
||||
.find(|d| d.key == *key)
|
||||
.map(|d| d.weight)
|
||||
.unwrap_or(0.0);
|
||||
weight * progress
|
||||
})
|
||||
.sum::<f64>()
|
||||
.clamp(0.0, 1.0);
|
||||
|
||||
let current_phase = ordered
|
||||
.iter()
|
||||
.find(|(_, progress, status)| *progress < 1.0 && status != "completed")
|
||||
.map(|(key, _, _)| key.clone());
|
||||
|
||||
Ok(Json(FileProgressResponse {
|
||||
file_uuid,
|
||||
overall_progress: overall,
|
||||
current_phase,
|
||||
phases: phases_out,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_config() -> RawConfig {
|
||||
let json = r#"{
|
||||
"phases": [
|
||||
{"id": 1, "name": "基础分析", "name_en": "Foundation", "progress_weight": 0.15, "processors": ["cut"]},
|
||||
{"id": 2, "name": "核心处理", "name_en": "Core Processing", "progress_weight": 0.60, "processors": ["asr", "face", "ocr"]}
|
||||
],
|
||||
"flows": {
|
||||
"register": {
|
||||
"stages": [
|
||||
{"name": "asr", "progress_weight": 0.35, "dependencies": []},
|
||||
{"name": "face", "progress_weight": 0.35, "dependencies": []},
|
||||
{"name": "ocr", "progress_weight": 0.30, "dependencies": []}
|
||||
]
|
||||
}
|
||||
}
|
||||
}"#;
|
||||
serde_json::from_str(json).expect("sample config parses")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_phases_sorted_with_weights() {
|
||||
let defs = build_phase_defs(&sample_config());
|
||||
assert_eq!(defs.len(), 2);
|
||||
assert_eq!(defs[0].key, "Foundation");
|
||||
assert_eq!(defs[1].key, "Core Processing");
|
||||
|
||||
let total: f64 = defs.iter().map(|d| d.weight).sum();
|
||||
assert!((total - 0.75).abs() < 1e-9, "weights sum, got {total}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_weights_default_when_missing() {
|
||||
let defs = build_phase_defs(&sample_config());
|
||||
let core = &defs[1];
|
||||
let asr = core.processors.iter().find(|p| p.name == "asr").unwrap();
|
||||
assert!((asr.weight - 0.35).abs() < 1e-9);
|
||||
|
||||
let foundation = &defs[0];
|
||||
assert_eq!(foundation.processors[0].name, "cut");
|
||||
// "cut" has no stage meta → default weight 1.0
|
||||
assert!((foundation.processors[0].weight - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
fn agg(weight: f64, applicable: bool, status: &str, progress: f64) -> PhaseAggInput {
|
||||
PhaseAggInput {
|
||||
weight,
|
||||
applicable,
|
||||
status: status.to_string(),
|
||||
progress,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase_progress_is_weighted_over_applicable() {
|
||||
// asr done (0.35), face half (0.35), ocr pending (0.30) — all applicable
|
||||
let procs = vec![
|
||||
agg(0.35, true, "completed", 1.0),
|
||||
agg(0.35, true, "running", 0.5),
|
||||
agg(0.30, true, "pending", 0.0),
|
||||
];
|
||||
let (progress, status) = aggregate_phase(&procs, false);
|
||||
assert!((progress - 0.525).abs() < 1e-9, "got {progress}");
|
||||
assert_eq!(status, "running");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_siblings_prevent_premature_completion() {
|
||||
// Only asr finished; face/ocr applicable but not started → not 100%
|
||||
let procs = vec![
|
||||
agg(0.35, true, "completed", 1.0),
|
||||
agg(0.35, true, "pending", 0.0),
|
||||
agg(0.30, true, "pending", 0.0),
|
||||
];
|
||||
let (progress, status) = aggregate_phase(&procs, false);
|
||||
assert!((progress - 0.35).abs() < 1e-9, "got {progress}");
|
||||
assert_eq!(status, "running");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_applicable_processors_are_ignored() {
|
||||
// asr done+applicable; face/ocr not applicable (never ran)
|
||||
let procs = vec![
|
||||
agg(0.35, true, "completed", 1.0),
|
||||
agg(0.35, false, "pending", 0.0),
|
||||
agg(0.30, false, "pending", 0.0),
|
||||
];
|
||||
let (progress, status) = aggregate_phase(&procs, false);
|
||||
assert!((progress - 1.0).abs() < 1e-9, "got {progress}");
|
||||
assert_eq!(status, "completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_applicable_processors_is_pending() {
|
||||
let procs = vec![
|
||||
agg(0.35, false, "pending", 0.0),
|
||||
agg(0.35, false, "pending", 0.0),
|
||||
];
|
||||
let (progress, status) = aggregate_phase(&procs, false);
|
||||
assert_eq!(progress, 0.0);
|
||||
assert_eq!(status, "pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_marks_phase_failed() {
|
||||
let procs = vec![
|
||||
agg(0.5, true, "completed", 1.0),
|
||||
agg(0.5, true, "failed", 0.0),
|
||||
];
|
||||
let (progress, status) = aggregate_phase(&procs, false);
|
||||
assert!((progress - 0.5).abs() < 1e-9, "got {progress}");
|
||||
assert_eq!(status, "failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_file_forces_full_progress() {
|
||||
let procs = vec![agg(0.35, true, "pending", 0.0)];
|
||||
let (progress, status) = aggregate_phase(&procs, true);
|
||||
assert_eq!(progress, 1.0);
|
||||
assert_eq!(status, "completed");
|
||||
}
|
||||
}
|
||||
+78
-34
@@ -121,6 +121,7 @@ async fn list_files(
|
||||
total_chunks: chunk_count,
|
||||
file_size: None,
|
||||
modified_time: None,
|
||||
thumbnail_url: None,
|
||||
}]
|
||||
} else {
|
||||
vec![]
|
||||
@@ -149,21 +150,7 @@ async fn list_files(
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("MarkBase API parse error: {}", e)))?;
|
||||
|
||||
let mut all_files: Vec<FileItem> = Vec::new();
|
||||
|
||||
// Convert MarkBase files to FileItem
|
||||
for mb_file in markbase_files {
|
||||
all_files.push(FileItem {
|
||||
file_uuid: mb_file.file_uuid.unwrap_or_default(),
|
||||
file_name: mb_file.name,
|
||||
file_path: mb_file.file_path.unwrap_or_default(),
|
||||
status: "unregistered".to_string(),
|
||||
is_registered: false,
|
||||
total_chunks: 0,
|
||||
file_size: Some(mb_file.size),
|
||||
modified_time: Some(mb_file.modified),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Get registered files from database
|
||||
let table = crate::core::db::schema::table_name("videos");
|
||||
let registered: Vec<(String, String, String, String, Option<i64>, Option<String>)> = sqlx::query_as(&format!(
|
||||
@@ -173,28 +160,73 @@ async fn list_files(
|
||||
.fetch_all(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
// Build registered map
|
||||
let registered_map: std::collections::HashMap<String, (String, String, String, Option<i64>, Option<String>)> = registered
|
||||
.into_iter()
|
||||
.map(|(uuid, name, path, status, size, mtime)| (path, (uuid, name, status, size, mtime)))
|
||||
.collect();
|
||||
|
||||
// Merge: update registration status for matching files
|
||||
for file in &mut all_files {
|
||||
if let Some((uuid, name, status, size, mtime)) = registered_map.get(&file.file_path) {
|
||||
file.file_uuid = uuid.clone();
|
||||
file.status = status.clone();
|
||||
file.is_registered = status != "pending";
|
||||
file.file_size = size.map(|s| s as u64);
|
||||
file.modified_time = mtime.clone();
|
||||
|
||||
// Build registered lookup maps by path and by name.
|
||||
// MarkBase only returns name/size/modified (no path), so name is the reliable key.
|
||||
let mut registered_by_path: std::collections::HashMap<String, (String, String, String, Option<i64>, Option<String>)> =
|
||||
std::collections::HashMap::new();
|
||||
let mut registered_by_name: std::collections::HashMap<String, (String, String, String, Option<i64>, Option<String>)> =
|
||||
std::collections::HashMap::new();
|
||||
for (uuid, name, path, status, size, mtime) in registered {
|
||||
registered_by_path.insert(
|
||||
path.clone(),
|
||||
(uuid.clone(), path.clone(), status.clone(), size, mtime.clone()),
|
||||
);
|
||||
registered_by_name.insert(name, (uuid, path, status, size, mtime));
|
||||
}
|
||||
|
||||
// Convert MarkBase files to FileItem, merging registration info by path or name
|
||||
for mb_file in markbase_files {
|
||||
// Skip hidden/system files
|
||||
let name_lower = mb_file.name.to_lowercase();
|
||||
if name_lower == ".ds_store" || name_lower.ends_with(".sqlite") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let name = mb_file.name;
|
||||
let mb_path = mb_file.file_path.clone().unwrap_or_default();
|
||||
let matched = if !mb_path.is_empty() {
|
||||
registered_by_path.get(&mb_path)
|
||||
} else {
|
||||
registered_by_name.get(&name)
|
||||
};
|
||||
if let Some((uuid, path, status, size, mtime)) = matched {
|
||||
all_files.push(FileItem {
|
||||
file_uuid: uuid.clone(),
|
||||
file_name: name,
|
||||
file_path: path.clone(),
|
||||
status: status.clone(),
|
||||
is_registered: status != "pending",
|
||||
total_chunks: 0,
|
||||
file_size: size.map(|s| s as u64),
|
||||
modified_time: mtime.clone(),
|
||||
thumbnail_url: None,
|
||||
});
|
||||
} else {
|
||||
// Not registered: synthesize a path so the client can still preview it
|
||||
let synth_path = std::env::var("MOMENTRY_SFTP_ROOT")
|
||||
.ok()
|
||||
.map(|root| format!("{}/{}", root.trim_end_matches('/'), name))
|
||||
.unwrap_or_default();
|
||||
all_files.push(FileItem {
|
||||
file_uuid: mb_file.file_uuid.unwrap_or_default(),
|
||||
file_name: name,
|
||||
file_path: synth_path,
|
||||
status: "unregistered".to_string(),
|
||||
is_registered: false,
|
||||
total_chunks: 0,
|
||||
file_size: Some(mb_file.size),
|
||||
modified_time: Some(mb_file.modified),
|
||||
thumbnail_url: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Add files that are in database but not in MarkBase (registered but moved/deleted)
|
||||
let all_paths: std::collections::HashSet<String> = all_files.iter().map(|f| f.file_path.clone()).collect();
|
||||
for (path, (uuid, name, status, size, mtime)) in ®istered_map {
|
||||
if !all_paths.contains(path) {
|
||||
let all_names: std::collections::HashSet<String> = all_files.iter().map(|f| f.file_name.clone()).collect();
|
||||
for (name, (uuid, path, status, size, mtime)) in ®istered_by_name {
|
||||
if !all_names.contains(name) && !all_paths.contains(path) {
|
||||
all_files.push(FileItem {
|
||||
file_uuid: uuid.clone(),
|
||||
file_name: name.clone(),
|
||||
@@ -204,10 +236,20 @@ async fn list_files(
|
||||
total_chunks: 0,
|
||||
file_size: size.map(|s| s as u64),
|
||||
modified_time: mtime.clone(),
|
||||
thumbnail_url: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Add thumbnail URLs for all video files
|
||||
for file in &mut all_files {
|
||||
let path_lower = file.file_path.to_lowercase();
|
||||
if path_lower.ends_with(".mp4") || path_lower.ends_with(".mov") || path_lower.ends_with(".avi") || path_lower.ends_with(".mkv") {
|
||||
file.thumbnail_url = Some(format!("/api/v1/file/thumbnail?path={}&frame=0", urlencoding::encode(&file.file_path)));
|
||||
}
|
||||
}
|
||||
|
||||
let total = all_files.len() as i64;
|
||||
|
||||
// Apply pagination
|
||||
@@ -287,6 +329,8 @@ pub struct FileItem {
|
||||
pub file_size: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub modified_time: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thumbnail_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
|
||||
+20
-4
@@ -6,6 +6,7 @@ use axum::{
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::core::auth::jwt;
|
||||
@@ -45,7 +46,9 @@ pub struct ApiState {
|
||||
/// handshake rate and the kernel starts RST-ing connections.
|
||||
static REQUEST_PERMITS: OnceLock<Arc<Semaphore>> = OnceLock::new();
|
||||
|
||||
const REQUEST_CONCURRENCY_DEFAULT: usize = 40;
|
||||
const REQUEST_CONCURRENCY_DEFAULT: usize = 256;
|
||||
/// How long a request waits for a free slot before being rejected with 429.
|
||||
const REQUEST_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
fn request_semaphore() -> &'static Arc<Semaphore> {
|
||||
REQUEST_PERMITS.get_or_init(|| {
|
||||
@@ -68,10 +71,23 @@ pub async fn concurrency_limit(request: Request, next: Next) -> Response {
|
||||
return next.run(request).await;
|
||||
}
|
||||
|
||||
let permit = match request_semaphore().clone().try_acquire_owned() {
|
||||
Ok(p) => p,
|
||||
let permit = match tokio::time::timeout(
|
||||
REQUEST_WAIT_TIMEOUT,
|
||||
request_semaphore().clone().acquire_owned(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(p)) => p,
|
||||
Ok(Err(_)) => {
|
||||
tracing::error!("[Concurrency] semaphore closed {} {}", request.method(), path);
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server busy: limiter unavailable",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!("[Concurrency] rejected {} {} (429)", request.method(), path);
|
||||
tracing::warn!("[Concurrency] wait timeout {} {} (429)", request.method(), path);
|
||||
return (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
[("retry-after", "1")],
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod checkin_api;
|
||||
pub mod cluster_agent;
|
||||
pub mod docs;
|
||||
pub mod face_filter;
|
||||
pub mod file_progress;
|
||||
pub mod files;
|
||||
pub mod health;
|
||||
pub mod identities;
|
||||
|
||||
@@ -854,10 +854,12 @@ async fn get_processor_counts(
|
||||
.map(|v| v as u32);
|
||||
}
|
||||
|
||||
segment_count = json
|
||||
.get("segments")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| arr.len() as u32);
|
||||
if proc_name != "scene" {
|
||||
segment_count = json
|
||||
.get("segments")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| arr.len() as u32);
|
||||
}
|
||||
chunk_count = json
|
||||
.get("child_chunks")
|
||||
.and_then(|v| v.as_array())
|
||||
|
||||
+113
@@ -1317,6 +1317,7 @@ pub fn scan_routes() -> Router<AppState> {
|
||||
get(get_ingestion_status),
|
||||
)
|
||||
.route("/api/v1/stats/file/:file_uuid", get(get_file_stats))
|
||||
.route("/api/v1/file/:file_uuid/scene-vlm-stats", get(get_scene_vlm_stats))
|
||||
.route(
|
||||
"/api/v1/stats/pipeline/:file_uuid",
|
||||
get(get_pipeline_progress_handler),
|
||||
@@ -1517,6 +1518,62 @@ async fn get_pipeline_progress_handler(
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
// Check scene_vlm progress from scenes.json
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
|
||||
if std::path::Path::new(&scenes_path).exists() {
|
||||
if let Ok(scenes_json) = std::fs::read_to_string(&scenes_path) {
|
||||
if let Ok(scenes_data) = serde_json::from_str::<serde_json::Value>(&scenes_json) {
|
||||
let total_scenes = scenes_data
|
||||
.get("total_scenes")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0) as i64;
|
||||
|
||||
let vlm_done = scenes_data
|
||||
.get("scenes")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter(|s| {
|
||||
let status = s.get("vlm_status").and_then(|v| v.as_str());
|
||||
status == Some("completed") || status == Some("done")
|
||||
})
|
||||
.count() as i64
|
||||
})
|
||||
.unwrap_or(0);
|
||||
|
||||
let scene_vlm_status = if total_scenes == 0 {
|
||||
"completed"
|
||||
} else if vlm_done == total_scenes {
|
||||
"completed"
|
||||
} else if vlm_done > 0 {
|
||||
"running"
|
||||
} else {
|
||||
"pending"
|
||||
};
|
||||
|
||||
let scene_vlm_progress = if total_scenes == 0 {
|
||||
1.0
|
||||
} else if vlm_done > 0 {
|
||||
vlm_done as f64 / total_scenes as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
pp.update_stage(
|
||||
"scene_vlm",
|
||||
scene_vlm_progress,
|
||||
scene_vlm_status,
|
||||
if total_scenes == 0 {
|
||||
Some("no scenes".to_string())
|
||||
} else {
|
||||
Some(format!("{}/{}", vlm_done, total_scenes))
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check face dedup from actual face_cluster.json content
|
||||
// Always check if processors_done, regardless of tkg_node_count (A-10 fix)
|
||||
if processors_done {
|
||||
@@ -1585,3 +1642,59 @@ async fn get_pipeline_progress_handler(
|
||||
|
||||
Ok(Json(pp))
|
||||
}
|
||||
|
||||
/// Quick scene VLM stats endpoint (fast, no Qdrant queries)
|
||||
async fn get_scene_vlm_stats(
|
||||
State(state): State<AppState>,
|
||||
Path(file_uuid): Path<String>,
|
||||
) -> Result<Json<SceneVlmStats>, StatusCode> {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
|
||||
|
||||
if !std::path::Path::new(&scenes_path).exists() {
|
||||
return Ok(Json(SceneVlmStats::default()));
|
||||
}
|
||||
|
||||
let scenes_json = std::fs::read_to_string(&scenes_path)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let scenes_data: serde_json::Value = serde_json::from_str(&scenes_json)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let total_scenes = scenes_data
|
||||
.get("total_scenes")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
|
||||
let status = scenes_data
|
||||
.get("status")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("pending")
|
||||
.to_string();
|
||||
|
||||
let scenes_array = scenes_data
|
||||
.get("scenes")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| arr.len() as i64)
|
||||
.unwrap_or(0);
|
||||
|
||||
let vlm_done = scenes_data
|
||||
.get("scenes")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter(|s| {
|
||||
let vlm_status = s.get("vlm_status").and_then(|v| v.as_str());
|
||||
vlm_status == Some("completed") || vlm_status == Some("done")
|
||||
})
|
||||
.count() as i64
|
||||
})
|
||||
.unwrap_or(0);
|
||||
|
||||
Ok(Json(SceneVlmStats {
|
||||
total_scenes: total_scenes.max(scenes_array),
|
||||
status,
|
||||
vlm_done,
|
||||
vlm_total: total_scenes.max(scenes_array),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use super::checkin_api;
|
||||
use super::cluster_agent;
|
||||
use super::docs;
|
||||
use super::face_filter;
|
||||
use super::file_progress;
|
||||
use super::files;
|
||||
use super::health;
|
||||
use super::health::{health, health_consistency, health_detailed, health_queue};
|
||||
@@ -138,6 +139,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.merge(agent_api::agent_routes())
|
||||
.merge(agent_search::agent_search_routes())
|
||||
.merge(processing::processing_routes())
|
||||
.merge(file_progress::file_progress_routes())
|
||||
.merge(media_api::bbox_routes())
|
||||
.merge(media_api::media_proxy_routes())
|
||||
.merge(media_api::pose_appearance_routes())
|
||||
|
||||
Reference in New Issue
Block a user