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
+4 -1
View File
@@ -648,7 +648,10 @@ pub async fn get_server() -> ServerConfig {
pub fn get_paths_sync() -> PathsConfig {
PathsConfig {
output_dir: crate::core::config::OUTPUT_DIR.to_string(),
// Must NOT read config::OUTPUT_DIR here: this function *is* the
// initializer of that lazy static, so reading it re-enters
// once_cell::sync::Lazy::force and deadlocks the calling thread.
output_dir: default_output_dir(),
backup_dir: std::env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| {
std::env::current_exe()
+4 -2
View File
@@ -7,6 +7,8 @@ use chrono::{DateTime, Utc};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::core::db::qdrant_db::new_http_client;
/// Gitea token scope
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -122,14 +124,14 @@ impl GiteaClient {
std::env::var("GITEA_URL").unwrap_or_else(|_| "http://localhost:3001".to_string());
Ok(Self {
client: Client::new(),
client: new_http_client(),
base_url,
})
}
pub fn with_url(base_url: String) -> Self {
Self {
client: Client::new(),
client: new_http_client(),
base_url,
}
}
+4 -2
View File
@@ -7,6 +7,8 @@ use chrono::{DateTime, Utc};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::core::db::qdrant_db::new_http_client;
/// Request to create an n8n API key
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateN8nApiKeyRequest {
@@ -46,7 +48,7 @@ impl N8nClient {
.unwrap_or_else(|_| "https://n8n.momentry.ddns.net".to_string());
Ok(Self {
client: Client::new(),
client: new_http_client(),
base_url,
api_key,
})
@@ -54,7 +56,7 @@ impl N8nClient {
pub fn with_url(base_url: String, api_key: String) -> Self {
Self {
client: Client::new(),
client: new_http_client(),
base_url,
api_key,
}
+409
View File
@@ -0,0 +1,409 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
pub mod types;
pub use types::{
TokenUsage, ServiceType, UsageRecord, QuotaConfig, QuotaStatus,
RateConfig, BillingPeriod, UsageReport, DailyUsage, ModelUsage, AlertConfig,
};
use types::*;
use super::error::{CommandError, CommandResult};
use chrono::{DateTime, Utc};
use serde_json::json;
use sqlx::PgPool;
use tracing::{debug, error, info, warn};
/// Billing 服务
pub struct BillingService {
db: PgPool,
}
impl BillingService {
pub fn new(db: PgPool) -> Self {
Self { db }
}
/// 记录使用
pub async fn record_usage(&self, record: UsageRecord) -> CommandResult<String> {
let record_id = &record.record_id;
let now = record.timestamp;
sqlx::query!(
r#"
INSERT INTO billing_usage (
record_id, key_id, service, model,
input_tokens, output_tokens, total_tokens,
cost_usd, duration_ms,
request_id, queue_name, message_id,
status, timestamp
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
"#,
record_id,
record.key_id,
serde_json::to_string(&record.service)?,
record.model,
record.token_usage.input_tokens as i32,
record.token_usage.output_tokens as i32,
record.token_usage.total_tokens as i32,
record.cost_usd,
record.duration_ms,
record.request_id,
record.queue_name,
record.message_id,
record.status,
now,
)
.execute(&self.db)
.await?;
// 更新 quota
self.update_quota_usage(&record.key_id, record.token_usage.total_tokens as i64).await?;
info!(
record_id = %record_id,
key_id = %record.key_id,
service = ?record.service,
tokens = record.token_usage.total_tokens,
cost = record.cost_usd,
"Usage recorded"
);
Ok(record_id.clone())
}
/// 检查 quota
pub async fn check_quota(&self, key_id: &str, tokens_required: i64) -> CommandResult<QuotaStatus> {
let quota = self.get_quota_config(key_id).await?;
let now = Utc::now();
let used = sqlx::query!(
r#"
SELECT COALESCE(SUM(total_tokens), 0) as tokens_used,
COALESCE(SUM(cost_usd), 0) as cost_used
FROM billing_usage
WHERE key_id = $1
AND timestamp >= date_trunc('month', NOW())
"#,
key_id,
)
.fetch_one(&self.db)
.await?;
let tokens_used = used.tokens_used.unwrap_or(0);
let cost_used = used.cost_used.unwrap_or(0.0);
let tokens_remaining = (quota.monthly_token_limit - tokens_used).max(0);
let cost_remaining = (quota.monthly_cost_limit - cost_used).max(0.0);
let percentage_used = if quota.monthly_token_limit > 0 {
(tokens_used as f64 / quota.monthly_token_limit as f64) * 100.0
} else {
0.0
};
let is_exceeded = tokens_used + tokens_required > quota.monthly_token_limit;
if is_exceeded && !quota.allow_overage {
return Err(CommandError::QuotaExceeded {
limit: quota.monthly_token_limit,
used: tokens_used,
});
}
Ok(QuotaStatus {
key_id: key_id.to_string(),
period: now.format("%Y-%m").to_string(),
tokens_used,
tokens_remaining,
cost_used,
cost_remaining,
percentage_used,
is_exceeded,
reset_at: (now + chrono::Duration::days(30)).with_day0(1).unwrap(),
})
}
/// 获取 quota 配置
pub async fn get_quota_config(&self, key_id: &str) -> CommandResult<QuotaConfig> {
let config = sqlx::query!(
r#"
SELECT
key_id, monthly_token_limit, daily_token_limit, hourly_token_limit,
monthly_cost_limit, allow_overage, overage_rate
FROM billing_quotas
WHERE key_id = $1
"#,
key_id,
)
.fetch_optional(&self.db)
.await?;
match config {
Some(row) => Ok(QuotaConfig {
key_id: row.key_id,
monthly_token_limit: row.monthly_token_limit,
daily_token_limit: row.daily_token_limit,
hourly_token_limit: row.hourly_token_limit,
monthly_cost_limit: row.monthly_cost_limit,
allow_overage: row.allow_overage,
overage_rate: row.overage_rate,
}),
None => Ok(QuotaConfig {
key_id: key_id.to_string(),
monthly_token_limit: 1_000_000,
daily_token_limit: 100_000,
hourly_token_limit: 10_000,
monthly_cost_limit: 100.0,
allow_overage: false,
overage_rate: 0.0,
}),
}
}
/// 更新 quota 使用
async fn update_quota_usage(&self, key_id: &str, tokens: i64) -> CommandResult<()> {
sqlx::query!(
r#"
INSERT INTO billing_quotas (key_id, monthly_token_used, daily_token_used, hourly_token_used)
VALUES ($1, $2, $2, $2)
ON CONFLICT (key_id)
DO UPDATE SET
monthly_token_used = billing_quotas.monthly_token_used + $2,
daily_token_used = billing_quotas.daily_token_used + $2,
hourly_token_used = billing_quotas.hourly_token_used + $2,
updated_at = NOW()
"#,
key_id,
tokens,
)
.execute(&self.db)
.await?;
Ok(())
}
/// 获取费率
pub async fn get_rate(&self, service: &ServiceType, model: Option<&str>) -> CommandResult<RateConfig> {
let service_str = serde_json::to_string(service)?;
let now = Utc::now();
let rate = sqlx::query!(
r#"
SELECT
service, model, input_rate_per_1k, output_rate_per_1k,
effective_from, effective_to
FROM billing_rates
WHERE service = $1
AND (model = $2 OR ($2 IS NULL AND model IS NULL))
AND effective_from <= $3
AND (effective_to IS NULL OR effective_to >= $3)
ORDER BY effective_from DESC
LIMIT 1
"#,
service_str,
model,
now,
)
.fetch_optional(&self.db)
.await?;
match rate {
Some(row) => Ok(RateConfig {
service: serde_json::from_str(&row.service)?,
model: row.model,
input_rate_per_1k: row.input_rate_per_1k,
output_rate_per_1k: row.output_rate_per_1k,
effective_from: row.effective_from,
effective_to: row.effective_to,
}),
None => Ok(RateConfig {
service: service.clone(),
model: model.map(|s| s.to_string()),
input_rate_per_1k: 0.0,
output_rate_per_1k: 0.0,
effective_from: now,
effective_to: None,
}),
}
}
/// 计算成本
pub async fn calculate_cost(
&self,
service: &ServiceType,
model: Option<&str>,
usage: &TokenUsage,
) -> CommandResult<f64> {
let rate = self.get_rate(service, model).await?;
Ok(rate.calculate_cost(usage))
}
/// 获取账单周期
pub async fn get_billing_period(&self, key_id: &str, period: &str) -> CommandResult<BillingPeriod> {
let period_month = period.to_string();
let result = sqlx::query!(
r#"
SELECT
key_id, period_month, period_start, period_end,
total_tokens, total_cost, service_breakdown, model_breakdown,
request_count, error_count
FROM billing_periods
WHERE key_id = $1 AND period_month = $2
"#,
key_id,
period_month,
)
.fetch_optional(&self.db)
.await?;
match result {
Some(row) => Ok(BillingPeriod {
period_id: format!("{}-{}", key_id, period_month),
key_id: row.key_id,
period_month: row.period_month,
period_start: row.period_start,
period_end: row.period_end,
total_tokens: row.total_tokens,
total_cost: row.total_cost,
service_breakdown: row.service_breakdown,
model_breakdown: row.model_breakdown,
request_count: row.request_count,
error_count: row.error_count,
}),
None => Err(CommandError::NotFound(format!("Billing period {} for {}", period_month, key_id))),
}
}
/// 生成使用报告
pub async fn generate_report(&self, key_id: &str, period: &str) -> CommandResult<UsageReport> {
let usage_data = sqlx::query!(
r#"
SELECT
DATE(timestamp) as date,
SUM(total_tokens) as tokens,
SUM(cost_usd) as cost,
COUNT(*) as requests
FROM billing_usage
WHERE key_id = $1
AND timestamp >= date_trunc('month', $2::TIMESTAMPTZ)
AND timestamp < date_trunc('month', $2::TIMESTAMPTZ) + INTERVAL '1 month'
GROUP BY DATE(timestamp)
ORDER BY date
"#,
key_id,
period,
)
.fetch_all(&self.db)
.await?;
let daily_usage: Vec<DailyUsage> = usage_data
.into_iter()
.map(|row| DailyUsage {
date: row.date.map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default(),
tokens: row.tokens.unwrap_or(0),
cost: row.cost.unwrap_or(0.0),
requests: row.requests.unwrap_or(0),
})
.collect();
let total_tokens: i64 = daily_usage.iter().map(|d| d.tokens).sum();
let total_cost: f64 = daily_usage.iter().map(|d| d.cost).sum();
Ok(UsageReport {
key_id: key_id.to_string(),
period: period.to_string(),
daily_usage,
service_breakdown: json!({}),
top_models: vec![],
total_cost,
total_tokens,
})
}
/// 设置警报
pub async fn set_alert(&self, config: AlertConfig) -> CommandResult<()> {
sqlx::query!(
r#"
INSERT INTO billing_alerts (key_id, threshold_percentage, notify_email, notify_webhook, enabled)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (key_id)
DO UPDATE SET
threshold_percentage = $2,
notify_email = $3,
notify_webhook = $4,
enabled = $5
"#,
config.key_id,
config.threshold_percentage,
config.notify_email,
config.notify_webhook,
config.enabled,
)
.execute(&self.db)
.await?;
info!(
key_id = %config.key_id,
threshold = config.threshold_percentage,
"Billing alert configured"
);
Ok(())
}
/// 检查警报
pub async fn check_alerts(&self) -> CommandResult<Vec<QuotaStatus>> {
let alerts = sqlx::query!(
r#"
SELECT
ba.key_id,
ba.threshold_percentage,
bq.monthly_token_limit,
bq.monthly_token_used
FROM billing_alerts ba
JOIN billing_quotas bq ON ba.key_id = bq.key_id
WHERE ba.enabled = true
"#,
)
.fetch_all(&self.db)
.await?;
let mut exceeded = Vec::new();
for alert in alerts {
let percentage = if alert.monthly_token_limit > 0 {
(alert.monthly_token_used.unwrap_or(0) as f64 / alert.monthly_token_limit as f64) * 100.0
} else {
0.0
};
if percentage >= alert.threshold_percentage {
warn!(
key_id = %alert.key_id,
percentage = percentage,
threshold = alert.threshold_percentage,
"Quota threshold exceeded"
);
let quota_status = QuotaStatus {
key_id: alert.key_id,
period: Utc::now().format("%Y-%m").to_string(),
tokens_used: alert.monthly_token_used.unwrap_or(0),
tokens_remaining: alert.monthly_token_limit - alert.monthly_token_used.unwrap_or(0),
cost_used: 0.0,
cost_remaining: 0.0,
percentage_used: percentage,
is_exceeded: true,
reset_at: Utc::now(),
};
exceeded.push(quota_status);
}
}
Ok(exceeded)
}
}
+204
View File
@@ -0,0 +1,204 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use uuid::Uuid;
/// Token 使用
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenUsage {
pub input_tokens: u32,
pub output_tokens: u32,
pub total_tokens: u32,
}
/// 服务类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ServiceType {
VLM,
Chat,
Embedding,
Agent,
Search,
Queue,
}
/// 使用记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageRecord {
pub record_id: String,
pub key_id: String,
pub service: ServiceType,
pub model: Option<String>,
pub token_usage: TokenUsage,
pub cost_usd: f64,
pub duration_ms: i64,
pub request_id: Option<String>,
pub queue_name: Option<String>,
pub message_id: Option<String>,
pub status: String,
pub timestamp: DateTime<Utc>,
}
/// Quota 配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuotaConfig {
pub key_id: String,
pub monthly_token_limit: i64,
pub daily_token_limit: i64,
pub hourly_token_limit: i64,
pub monthly_cost_limit: f64,
pub allow_overage: bool,
pub overage_rate: f64,
}
/// Quota 状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuotaStatus {
pub key_id: String,
pub period: String,
pub tokens_used: i64,
pub tokens_remaining: i64,
pub cost_used: f64,
pub cost_remaining: f64,
pub percentage_used: f64,
pub is_exceeded: bool,
pub reset_at: DateTime<Utc>,
}
/// 费率配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateConfig {
pub service: ServiceType,
pub model: Option<String>,
pub input_rate_per_1k: f64,
pub output_rate_per_1k: f64,
pub effective_from: DateTime<Utc>,
pub effective_to: Option<DateTime<Utc>>,
}
/// 账单周期
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingPeriod {
pub period_id: String,
pub key_id: String,
pub period_month: String,
pub period_start: DateTime<Utc>,
pub period_end: DateTime<Utc>,
pub total_tokens: i64,
pub total_cost: f64,
pub service_breakdown: JsonValue,
pub model_breakdown: JsonValue,
pub request_count: i64,
pub error_count: i64,
}
/// 使用报告
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageReport {
pub key_id: String,
pub period: String,
pub daily_usage: Vec<DailyUsage>,
pub service_breakdown: JsonValue,
pub top_models: Vec<ModelUsage>,
pub total_cost: f64,
pub total_tokens: i64,
}
/// 每日使用
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DailyUsage {
pub date: String,
pub tokens: i64,
pub cost: f64,
pub requests: i64,
}
/// 模型使用
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelUsage {
pub model: String,
pub tokens: i64,
pub cost: f64,
pub percentage: f64,
}
/// 警报配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertConfig {
pub key_id: String,
pub threshold_percentage: f64,
pub notify_email: Option<String>,
pub notify_webhook: Option<String>,
pub enabled: bool,
}
impl TokenUsage {
pub fn new(input: u32, output: u32) -> Self {
Self {
input_tokens: input,
output_tokens: output,
total_tokens: input + output,
}
}
}
impl UsageRecord {
pub fn new(
key_id: String,
service: ServiceType,
token_usage: TokenUsage,
) -> Self {
Self {
record_id: uuid::Uuid::new_v4().to_string(),
key_id,
service,
model: None,
token_usage,
cost_usd: 0.0,
duration_ms: 0,
request_id: None,
queue_name: None,
message_id: None,
status: "success".to_string(),
timestamp: Utc::now(),
}
}
pub fn with_model(mut self, model: String) -> Self {
self.model = Some(model);
self
}
pub fn with_cost(mut self, cost: f64) -> Self {
self.cost_usd = cost;
self
}
pub fn with_duration(mut self, duration_ms: i64) -> Self {
self.duration_ms = duration_ms;
self
}
pub fn with_request(mut self, request_id: String) -> Self {
self.request_id = Some(request_id);
self
}
pub fn with_queue(mut self, queue_name: String, message_id: String) -> Self {
self.queue_name = Some(queue_name);
self.message_id = Some(message_id);
self
}
}
impl RateConfig {
pub fn calculate_cost(&self, usage: &TokenUsage) -> f64 {
let input_cost = (usage.input_tokens as f64 / 1000.0) * self.input_rate_per_1k;
let output_cost = (usage.output_tokens as f64 / 1000.0) * self.output_rate_per_1k;
input_cost + output_cost
}
}
+66
View File
@@ -0,0 +1,66 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum CommandError {
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),
#[error("Serialization error: {0}")]
Serialization(#[from] serde_json::Error),
#[error("Command not found: {0}")]
NotFound(String),
#[error("Invalid command type: {0}")]
InvalidCommandType(String),
#[error("Invalid queue type: {0}")]
InvalidQueueType(String),
#[error("Invalid status: {0}")]
InvalidStatus(String),
#[error("Invalid priority: {0}")]
InvalidPriority(i32),
#[error("Missing metadata: {0}")]
MissingMetadata(String),
#[error("Missing payload: {0}")]
MissingPayload(String),
#[error("Handler not found: {0}")]
HandlerNotFound(String),
#[error("Route not found for command type: {0}")]
RouteNotFound(String),
#[error("Billing error: {0}")]
Billing(String),
#[error("Quota exceeded: limit {limit}, used {used}")]
QuotaExceeded { limit: i64, used: i64 },
#[error("Command execution failed: {0}")]
ExecutionFailed(String),
#[error("Pipeline processing error: {0}")]
ProcessingError(String),
#[error("Command timeout after {0}ms")]
Timeout(i32),
#[error("Max retries exceeded: {0}")]
MaxRetriesExceeded(i32),
#[error("Consumer error: {0}")]
ConsumerError(String),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
pub type CommandResult<T> = Result<T, CommandError>;
+301
View File
@@ -0,0 +1,301 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
pub mod types;
pub use types::{
LogLevel, LogSource, LogEntry, LogError, LogAggregate,
LogSearchOptions, LogStats,
};
use types::*;
use super::error::{CommandError, CommandResult};
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use sqlx::PgPool;
use tracing::debug;
/// 日志服务
pub struct LogService {
db: PgPool,
min_level: LogLevel,
}
impl LogService {
pub fn new(db: PgPool, min_level: LogLevel) -> Self {
Self { db, min_level }
}
/// 写入日志
pub async fn write(&self, entry: LogEntry) -> CommandResult<String> {
if entry.level < self.min_level {
return Ok(entry.log_id.clone());
}
sqlx::query!(
r#"
INSERT INTO system_logs (
log_id, timestamp, level, source, component,
message, context, trace_id, span_id,
user_id, request_id, duration_ms,
error_type, error_message, stack_trace
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
"#,
entry.log_id,
entry.timestamp,
entry.level as i32,
serde_json::to_string(&entry.source)?,
entry.component,
entry.message,
entry.context,
entry.trace_id,
entry.span_id,
entry.user_id,
entry.request_id,
entry.duration_ms,
entry.error.as_ref().map(|e| e.error_type.clone()),
entry.error.as_ref().map(|e| e.error_message.clone()),
entry.error.as_ref().and_then(|e| e.stack_trace.clone()),
)
.execute(&self.db)
.await?;
debug!(
log_id = %entry.log_id,
level = ?entry.level,
component = %entry.component,
"Log entry written"
);
Ok(entry.log_id.clone())
}
/// 批量写入日志
pub async fn write_batch(&self, entries: Vec<LogEntry>) -> CommandResult<i64> {
let count = entries.len() as i64;
for entry in entries {
if entry.level >= self.min_level {
self.write(entry).await?;
}
}
Ok(count)
}
/// 搜索日志
pub async fn search(&self, options: LogSearchOptions) -> CommandResult<Vec<LogEntry>> {
let limit = options.limit.unwrap_or(100);
let offset = options.offset.unwrap_or(0);
let query = sqlx::query!(
r#"
SELECT
log_id, timestamp, level, source, component,
message, context, trace_id, span_id,
user_id, request_id, duration_ms,
error_type, error_message, stack_trace
FROM system_logs
WHERE ($1::TIMESTAMPTZ IS NULL OR timestamp >= $1)
AND ($2::TIMESTAMPTZ IS NULL OR timestamp <= $2)
AND ($3::INTEGER IS NULL OR level >= $3)
AND ($4::INTEGER IS NULL OR level <= $4)
AND ($5::TEXT[] IS NULL OR source = ANY($5))
AND ($6::TEXT[] IS NULL OR component = ANY($6))
AND ($7::TEXT IS NULL OR message ILIKE '%' || $7 || '%')
AND ($8::TEXT IS NULL OR trace_id = $8)
AND ($9::TEXT IS NULL OR user_id = $9)
ORDER BY timestamp DESC
LIMIT $10
OFFSET $11
"#,
options.start_time,
options.end_time,
options.level_min.map(|l| l as i32),
options.level_max.map(|l| l as i32),
options.sources.map(|s| s.iter().map(|src| serde_json::to_string(src).unwrap()).collect::<Vec<_>>()),
options.components,
options.message_contains,
options.trace_id,
options.user_id,
limit as i64,
offset as i64,
);
let rows = query.fetch_all(&self.db).await?;
let entries = rows
.into_iter()
.map(|row| self.row_to_entry(row))
.collect::<CommandResult<Vec<_>>>()?;
Ok(entries)
}
/// 获取日志统计
pub async fn get_stats(&self, start_time: DateTime<Utc>, end_time: DateTime<Utc>) -> CommandResult<LogStats> {
let stats = sqlx::query!(
r#"
SELECT
COUNT(*) as total_logs,
COUNT(*) FILTER (WHERE level = 0) as trace_count,
COUNT(*) FILTER (WHERE level = 1) as debug_count,
COUNT(*) FILTER (WHERE level = 2) as info_count,
COUNT(*) FILTER (WHERE level = 3) as warn_count,
COUNT(*) FILTER (WHERE level = 4) as error_count,
COUNT(*) FILTER (WHERE level = 5) as fatal_count
FROM system_logs
WHERE timestamp >= $1 AND timestamp <= $2
"#,
start_time,
end_time,
)
.fetch_one(&self.db)
.await?;
let total = stats.total_logs.unwrap_or(0);
let duration = (end_time - start_time).num_minutes() as f64;
let mut by_level = std::collections::HashMap::new();
by_level.insert("trace".to_string(), stats.trace_count.unwrap_or(0));
by_level.insert("debug".to_string(), stats.debug_count.unwrap_or(0));
by_level.insert("info".to_string(), stats.info_count.unwrap_or(0));
by_level.insert("warn".to_string(), stats.warn_count.unwrap_or(0));
by_level.insert("error".to_string(), stats.error_count.unwrap_or(0));
by_level.insert("fatal".to_string(), stats.fatal_count.unwrap_or(0));
let error_count = stats.error_count.unwrap_or(0) + stats.fatal_count.unwrap_or(0);
let error_rate = if total > 0 {
error_count as f64 / total as f64
} else {
0.0
};
Ok(LogStats {
total_logs: total,
by_level,
by_source: std::collections::HashMap::new(),
error_rate,
avg_per_minute: if duration > 0.0 { total as f64 / duration } else { 0.0 },
})
}
/// 聚合日志
pub async fn aggregate(
&self,
period: &str,
start_time: DateTime<Utc>,
end_time: DateTime<Utc>,
) -> CommandResult<Vec<LogAggregate>> {
let aggregates = sqlx::query!(
r#"
SELECT
level,
source,
component,
COUNT(*) as count,
MIN(timestamp) as first_occurrence,
MAX(timestamp) as last_occurrence,
ARRAY_AGG(message ORDER BY timestamp DESC LIMIT 5) as sample_messages
FROM system_logs
WHERE timestamp >= $1 AND timestamp <= $2
GROUP BY level, source, component
ORDER BY count DESC
"#,
start_time,
end_time,
)
.fetch_all(&self.db)
.await?;
let result = aggregates
.into_iter()
.map(|row| {
let level = match row.level.unwrap_or(2) {
0 => LogLevel::Trace,
1 => LogLevel::Debug,
2 => LogLevel::Info,
3 => LogLevel::Warn,
4 => LogLevel::Error,
5 => LogLevel::Fatal,
_ => LogLevel::Info,
};
let source: LogSource = serde_json::from_str(&row.source.unwrap_or_default())
.unwrap_or(LogSource::System);
LogAggregate {
period: period.to_string(),
level,
source,
component: row.component.unwrap_or_default(),
count: row.count.unwrap_or(0),
first_occurrence: row.first_occurrence.unwrap_or_else(Utc::now),
last_occurrence: row.last_occurrence.unwrap_or_else(Utc::now),
sample_messages: row.sample_messages.unwrap_or_default(),
}
})
.collect();
Ok(result)
}
/// 清理过期日志
pub async fn cleanup(&self, days_to_keep: i32) -> CommandResult<i64> {
let result = sqlx::query!(
r#"
DELETE FROM system_logs
WHERE timestamp < NOW() - ($1 || ' days')::INTERVAL
"#,
days_to_keep,
)
.execute(&self.db)
.await?;
debug!(
days = days_to_keep,
deleted = result.rows_affected(),
"Old logs cleaned up"
);
Ok(result.rows_affected() as i64)
}
fn row_to_entry(&self, row: sqlx::postgres::PgRow) -> CommandResult<LogEntry> {
let level = match row.get::<i32, _>("level") {
0 => LogLevel::Trace,
1 => LogLevel::Debug,
2 => LogLevel::Info,
3 => LogLevel::Warn,
4 => LogLevel::Error,
5 => LogLevel::Fatal,
_ => LogLevel::Info,
};
let source: LogSource = serde_json::from_str(&row.get::<String, _>("source"))?;
let error = row.get::<Option<String>, _>("error_type")
.map(|error_type| LogError {
error_type,
error_message: row.get("error_message").unwrap_or_default(),
stack_trace: row.get("stack_trace"),
});
Ok(LogEntry {
log_id: row.get("log_id"),
timestamp: row.get("timestamp"),
level,
source,
component: row.get("component"),
message: row.get("message"),
context: row.get("context"),
trace_id: row.get("trace_id"),
span_id: row.get("span_id"),
user_id: row.get("user_id"),
request_id: row.get("request_id"),
duration_ms: row.get("duration_ms"),
error,
})
}
}
+153
View File
@@ -0,0 +1,153 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use uuid::Uuid;
/// 日志级别
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum LogLevel {
Trace = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4,
Fatal = 5,
}
/// 日志来源
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LogSource {
System,
Api,
Worker,
Agent,
Queue,
Database,
External,
}
/// 日志条目
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
pub log_id: String,
pub timestamp: DateTime<Utc>,
pub level: LogLevel,
pub source: LogSource,
pub component: String,
pub message: String,
pub context: Option<JsonValue>,
pub trace_id: Option<String>,
pub span_id: Option<String>,
pub user_id: Option<String>,
pub request_id: Option<String>,
pub duration_ms: Option<i64>,
pub error: Option<LogError>,
}
/// 日志错误
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogError {
pub error_type: String,
pub error_message: String,
pub stack_trace: Option<String>,
}
/// 日志聚合
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogAggregate {
pub period: String,
pub level: LogLevel,
pub source: LogSource,
pub component: String,
pub count: i64,
pub first_occurrence: DateTime<Utc>,
pub last_occurrence: DateTime<Utc>,
pub sample_messages: Vec<String>,
}
/// 日志搜索选项
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LogSearchOptions {
pub start_time: Option<DateTime<Utc>>,
pub end_time: Option<DateTime<Utc>>,
pub level_min: Option<LogLevel>,
pub level_max: Option<LogLevel>,
pub sources: Option<Vec<LogSource>>,
pub components: Option<Vec<String>>,
pub message_contains: Option<String>,
pub trace_id: Option<String>,
pub user_id: Option<String>,
pub limit: Option<i32>,
pub offset: Option<i32>,
}
/// 日志统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogStats {
pub total_logs: i64,
pub by_level: std::collections::HashMap<String, i64>,
pub by_source: std::collections::HashMap<String, i64>,
pub error_rate: f64,
pub avg_per_minute: f64,
}
impl LogEntry {
pub fn new(
level: LogLevel,
source: LogSource,
component: String,
message: String,
) -> Self {
Self {
log_id: uuid::Uuid::new_v4().to_string(),
timestamp: Utc::now(),
level,
source,
component,
message,
context: None,
trace_id: None,
span_id: None,
user_id: None,
request_id: None,
duration_ms: None,
error: None,
}
}
pub fn with_context(mut self, context: JsonValue) -> Self {
self.context = Some(context);
self
}
pub fn with_trace(mut self, trace_id: String, span_id: String) -> Self {
self.trace_id = Some(trace_id);
self.span_id = Some(span_id);
self
}
pub fn with_user(mut self, user_id: String) -> Self {
self.user_id = Some(user_id);
self
}
pub fn with_request(mut self, request_id: String) -> Self {
self.request_id = Some(request_id);
self
}
pub fn with_duration(mut self, duration_ms: i64) -> Self {
self.duration_ms = Some(duration_ms);
self
}
pub fn with_error(mut self, error: LogError) -> Self {
self.error = Some(error);
self
}
}
+397
View File
@@ -0,0 +1,397 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
pub mod types;
pub use types::{
MessageType, MessageSource, Message, MessagePriority, MessageStatus,
DeliveryOptions, Subscription, MessageFilter, MessageStats,
};
use types::*;
use super::error::{CommandError, CommandResult};
use chrono::Utc;
use serde_json::json;
use sqlx::PgPool;
use tracing::{debug, error, info};
use uuid::Uuid;
/// 消息服务
pub struct Messenger {
db: PgPool,
}
impl Messenger {
pub fn new(db: PgPool) -> Self {
Self { db }
}
/// 发送消息
pub async fn send(
&self,
queue_name: &str,
message: Message,
options: DeliveryOptions,
) -> CommandResult<String> {
let message_id = &message.message_id;
let now = Utc::now();
let expires_at = message.expires_at.or_else(|| {
options.ttl_seconds.map(|secs| {
now + chrono::Duration::seconds(secs as i64)
})
});
let source_type = serde_json::to_value(&message.source)?;
let source_component = self.extract_component(&message.source);
let metadata = serde_json::to_value(&message.metadata)?;
sqlx::query!(
r#"
INSERT INTO message_queue (
message_id, queue_name, message_type,
source_type, source_component,
target, priority, payload, metadata,
persistent, retry_count, require_ack,
status, created_at, expires_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
"#,
message_id,
queue_name,
serde_json::to_string(&message.message_type)?,
source_type,
source_component,
message.target,
message.priority as i32,
message.payload,
metadata,
options.persistent,
options.retry_count.unwrap_or(3),
options.require_ack,
"pending",
now,
expires_at,
)
.execute(&self.db)
.await?;
info!(
message_id = %message_id,
queue = %queue_name,
type = ?message.message_type,
"Message sent successfully"
);
Ok(message_id.clone())
}
/// 接收消息
pub async fn receive(
&self,
queue_name: &str,
subscriber_id: &str,
max_messages: i32,
timeout_ms: i32,
) -> CommandResult<Vec<Message>> {
let messages = sqlx::query!(
r#"
UPDATE message_queue
SET status = 'delivered',
delivered_at = NOW(),
delivered_to = $1
WHERE message_id IN (
SELECT message_id
FROM message_queue
WHERE queue_name = $2
AND status = 'pending'
AND (expires_at IS NULL OR expires_at > NOW())
ORDER BY priority ASC, created_at ASC
LIMIT $3
FOR UPDATE SKIP LOCKED
)
RETURNING
message_id, queue_name, message_type,
source_type, source_component, target,
priority, payload, metadata,
status, created_at, expires_at
"#,
subscriber_id,
queue_name,
max_messages as i64,
)
.fetch_all(&self.db)
.await?;
let messages = messages
.into_iter()
.map(|row| self.row_to_message(row))
.collect::<CommandResult<Vec<_>>>()?;
debug!(
queue = %queue_name,
count = messages.len(),
subscriber = %subscriber_id,
"Messages received"
);
Ok(messages)
}
/// 确认消息
pub async fn acknowledge(&self, message_id: &str, subscriber_id: &str) -> CommandResult<()> {
let result = sqlx::query!(
r#"
UPDATE message_queue
SET status = 'acknowledged',
acknowledged_at = NOW(),
acknowledged_by = $2
WHERE message_id = $1
AND delivered_to = $2
AND status = 'delivered'
"#,
message_id,
subscriber_id,
)
.execute(&self.db)
.await?;
if result.rows_affected() == 0 {
return Err(CommandError::NotFound(format!(
"Message {} not found or not delivered to {}",
message_id, subscriber_id
)));
}
info!(
message_id = %message_id,
subscriber = %subscriber_id,
"Message acknowledged"
);
Ok(())
}
/// 标记消息已处理
pub async fn mark_processed(&self, message_id: &str) -> CommandResult<()> {
sqlx::query!(
r#"
UPDATE message_queue
SET status = 'processed',
processed_at = NOW()
WHERE message_id = $1
"#,
message_id,
)
.execute(&self.db)
.await?;
debug!(
message_id = %message_id,
"Message marked as processed"
);
Ok(())
}
/// 标记消息失败
pub async fn mark_failed(&self, message_id: &str, error: &str) -> CommandResult<()> {
sqlx::query!(
r#"
UPDATE message_queue
SET status = 'failed',
error_message = $2,
retry_count = retry_count + 1,
failed_at = NOW()
WHERE message_id = $1
"#,
message_id,
error,
)
.execute(&self.db)
.await?;
error!(
message_id = %message_id,
error = %error,
"Message marked as failed"
);
Ok(())
}
/// 订阅队列
pub async fn subscribe(
&self,
queue_name: &str,
subscriber_id: &str,
filter: Option<MessageFilter>,
) -> CommandResult<String> {
let subscription_id = Uuid::new_v4().to_string();
let now = Utc::now();
sqlx::query!(
r#"
INSERT INTO message_subscriptions (
subscription_id, queue_name, subscriber_id,
filter, active, created_at
)
VALUES ($1, $2, $3, $4, true, $5)
ON CONFLICT (queue_name, subscriber_id)
DO UPDATE SET active = true, filter = $4
RETURNING subscription_id
"#,
subscription_id,
queue_name,
subscriber_id,
filter.map(|f| serde_json::to_value(f)).transpose()?,
now,
)
.fetch_one(&self.db)
.await?;
info!(
subscription_id = %subscription_id,
queue = %queue_name,
subscriber = %subscriber_id,
"Subscription created"
);
Ok(subscription_id)
}
/// 取消订阅
pub async fn unsubscribe(&self, queue_name: &str, subscriber_id: &str) -> CommandResult<()> {
sqlx::query!(
r#"
UPDATE message_subscriptions
SET active = false
WHERE queue_name = $1 AND subscriber_id = $2
"#,
queue_name,
subscriber_id,
)
.execute(&self.db)
.await?;
info!(
queue = %queue_name,
subscriber = %subscriber_id,
"Subscription cancelled"
);
Ok(())
}
/// 获取消息统计
pub async fn get_stats(&self, queue_name: &str) -> CommandResult<MessageStats> {
let stats = sqlx::query!(
r#"
SELECT
COUNT(*) as total_messages,
COUNT(*) FILTER (WHERE status = 'pending') as pending_count,
COUNT(*) FILTER (WHERE status = 'delivered') as delivered_count,
COUNT(*) FILTER (WHERE status = 'processed') as processed_count,
COUNT(*) FILTER (WHERE status = 'failed') as failed_count,
AVG(EXTRACT(EPOCH FROM (processed_at - created_at)) * 1000) FILTER (WHERE status = 'processed') as avg_latency_ms::double precision
FROM message_queue
WHERE queue_name = $1
AND created_at > NOW() - INTERVAL '1 hour'
"#,
queue_name,
)
.fetch_one(&self.db)
.await?;
Ok(MessageStats {
queue_name: queue_name.to_string(),
total_messages: stats.total_messages.unwrap_or(0),
pending_count: stats.pending_count.unwrap_or(0),
delivered_count: stats.delivered_count.unwrap_or(0),
processed_count: stats.processed_count.unwrap_or(0),
failed_count: stats.failed_count.unwrap_or(0),
avg_latency_ms: stats.avg_latency_ms.unwrap_or(0.0),
throughput_per_minute: stats.processed_count.unwrap_or(0) as f64 / 60.0,
})
}
/// 广播消息
pub async fn broadcast(
&self,
queue_pattern: &str,
message: Message,
options: DeliveryOptions,
) -> CommandResult<Vec<String>> {
let subscriptions = sqlx::query!(
r#"
SELECT DISTINCT queue_name
FROM message_subscriptions
WHERE queue_name LIKE $1
AND active = true
"#,
queue_pattern,
)
.fetch_all(&self.db)
.await?;
let mut message_ids = Vec::new();
for sub in subscriptions {
let id = self.send(&sub.queue_name, message.clone(), options.clone()).await?;
message_ids.push(id);
}
info!(
pattern = %queue_pattern,
count = message_ids.len(),
"Message broadcasted"
);
Ok(message_ids)
}
fn row_to_message(&self, row: sqlx::postgres::PgRow) -> CommandResult<Message> {
let message_type: MessageType = match row.get::<String, _>("message_type").as_str() {
"command" => MessageType::Command,
"event" => MessageType::Event,
"status" => MessageType::Status,
"log" => MessageType::Log,
"error" => MessageType::Error,
"heartbeat" => MessageType::Heartbeat,
_ => MessageType::Event,
};
let source: MessageSource = serde_json::from_str(&row.get::<String, _>("source_type"))?;
let priority = match row.get::<i32, _>("priority") {
0 => MessagePriority::Critical,
1 => MessagePriority::High,
2 => MessagePriority::Normal,
3 => MessagePriority::Low,
_ => MessagePriority::Normal,
};
Ok(Message {
message_id: row.get("message_id"),
message_type,
source,
target: row.get("target"),
priority,
payload: row.get("payload"),
metadata: serde_json::from_value(row.get("metadata"))?,
created_at: row.get("created_at"),
expires_at: row.get("expires_at"),
})
}
/// 从 MessageSource 提取组件名称
fn extract_component(&self, source: &MessageSource) -> Option<String> {
match source {
MessageSource::System { component } => Some(component.clone()),
MessageSource::Api { endpoint, .. } => Some(format!("api:{}", endpoint)),
MessageSource::Worker { worker_type, .. } => Some(format!("worker:{}", worker_type)),
MessageSource::Agent { agent_type, .. } => Some(format!("agent:{}", agent_type)),
MessageSource::External { service_name, .. } => Some(service_name.clone()),
}
}
}
+173
View File
@@ -0,0 +1,173 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use uuid::Uuid;
/// 消息类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MessageType {
/// 命令消息
Command,
/// 事件消息
Event,
/// 状态消息
Status,
/// 日志消息
Log,
/// 错误消息
Error,
/// 心跳消息
Heartbeat,
}
/// 消息来源
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageSource {
/// 系统内部
System {
component: String,
},
/// API 请求
Api {
endpoint: String,
method: String,
},
/// Worker
Worker {
worker_id: String,
worker_type: String,
},
/// Agent
Agent {
agent_id: String,
agent_type: String,
},
/// 外部服务
External {
service_name: String,
webhook_id: Option<String>,
},
}
/// 消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub message_id: String,
pub message_type: MessageType,
pub source: MessageSource,
pub target: Option<String>,
pub priority: MessagePriority,
pub payload: JsonValue,
pub metadata: std::collections::HashMap<String, String>,
pub created_at: DateTime<Utc>,
pub expires_at: Option<DateTime<Utc>>,
}
/// 消息优先级
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum MessagePriority {
Critical = 0,
High = 1,
Normal = 2,
Low = 3,
}
/// 消息状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MessageStatus {
Pending,
Delivered,
Acknowledged,
Processed,
Failed,
Expired,
}
/// 消息投递选项
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DeliveryOptions {
pub persistent: bool,
pub ttl_seconds: Option<i32>,
pub retry_count: Option<i32>,
pub require_ack: bool,
}
/// 消息订阅
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subscription {
pub subscription_id: String,
pub subscriber_id: String,
pub queue_name: String,
pub filter: Option<MessageFilter>,
pub active: bool,
pub created_at: DateTime<Utc>,
}
/// 消息过滤器
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageFilter {
pub message_types: Option<Vec<MessageType>>,
pub sources: Option<Vec<String>>,
pub priority_min: Option<MessagePriority>,
pub metadata_filter: Option<JsonValue>,
}
/// 消息统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageStats {
pub queue_name: String,
pub total_messages: i64,
pub pending_count: i64,
pub delivered_count: i64,
pub processed_count: i64,
pub failed_count: i64,
pub avg_latency_ms: f64,
pub throughput_per_minute: f64,
}
impl Message {
pub fn new(
message_type: MessageType,
source: MessageSource,
payload: JsonValue,
) -> Self {
Self {
message_id: Uuid::new_v4().to_string(),
message_type,
source,
target: None,
priority: MessagePriority::Normal,
payload,
metadata: std::collections::HashMap::new(),
created_at: Utc::now(),
expires_at: None,
}
}
pub fn with_target(mut self, target: String) -> Self {
self.target = Some(target);
self
}
pub fn with_priority(mut self, priority: MessagePriority) -> Self {
self.priority = priority;
self
}
pub fn with_metadata(mut self, key: String, value: String) -> Self {
self.metadata.insert(key, value);
self
}
pub fn with_ttl(mut self, seconds: i32) -> Self {
self.expires_at = Some(Utc::now() + chrono::Duration::seconds(seconds as i64));
self
}
}
+50
View File
@@ -0,0 +1,50 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
// Core Command Queue
pub mod error;
pub mod router;
pub mod queue;
pub mod types;
// Extensions
// pub mod messenger; // TODO: Fix sqlx::query! issues
// pub mod log;
// pub mod billing;
// pub mod search;
pub mod pipeline;
// Re-export Command types
pub use error::{CommandError, CommandResult};
pub use types::{
CommandType, InternalCommandCategory, ExternalCommandCategory, AgentCommandCategory,
CommandPriority, Command, CommandMessage, CommandStatus, CommandResult as CommandResultType,
ProduceOptions, ConsumeOptions, BillingContext, AgentMessage, AgentMessageType, QueueRoute,
};
pub use router::CommandRouter;
pub use queue::CommandQueue;
// Re-export Messenger types (disabled due to sqlx issues)
// pub use messenger::{
// MessageType, MessageSource, Message, MessagePriority, MessageStatus,
// DeliveryOptions, Subscription, MessageFilter, MessageStats, Messenger,
// };
// Re-export Log types (disabled due to sqlx issues)
// pub use log::{
// LogLevel, LogSource, LogEntry, LogError, LogAggregate,
// LogSearchOptions, LogStats, LogService,
// };
// Re-export Billing types (disabled due to sqlx issues)
// pub use billing::{
// TokenUsage, ServiceType, UsageRecord, QuotaConfig, QuotaStatus,
// RateConfig, BillingPeriod, UsageReport, DailyUsage, ModelUsage, AlertConfig,
// BillingService,
// };
// Re-export Search types (disabled due to sqlx issues)
// pub use search::{
// SearchType, SearchRequest, SearchFilters, SearchOptions, DateRange,
// SearchResponse, SearchResult, Highlight, SearchMessenger,
// };
+248
View File
@@ -0,0 +1,248 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
pub mod types;
pub mod worker;
use types::*;
use crate::core::command::error::{CommandError, CommandResult};
use crate::core::command::queue::CommandQueue;
use crate::core::command::types::{Command, CommandType, InternalCommandCategory, ProduceOptions};
use serde_json::json;
use sqlx::PgPool;
use tracing::info;
pub use worker::PipelineWorker;
/// Pipeline 服务
pub struct PipelineService {
db: PgPool,
}
impl PipelineService {
pub fn new(db: PgPool) -> Self {
Self { db }
}
/// 获取队列实例
async fn get_queue(&self) -> CommandResult<CommandQueue> {
CommandQueue::new(self.db.clone()).await
}
/// 提交 ASRX 存储命令
pub async fn store_asrx(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineStoreASRX,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline StoreASRX command queued"
);
Ok(message_id)
}
/// 提交 Rule1 执行命令
pub async fn execute_rule1(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineExecuteRule1,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline ExecuteRule1 command queued"
);
Ok(message_id)
}
/// 提交向量化命令
pub async fn vectorize_chunks(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineVectorize,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline Vectorize command queued"
);
Ok(message_id)
}
/// 提交 Phase1 打包命令
pub async fn phase1_pack(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelinePhase1Pack,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline Phase1Pack command queued"
);
Ok(message_id)
}
/// 提交标记完成命令
pub async fn mark_complete(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineMarkComplete,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline MarkComplete command queued"
);
Ok(message_id)
}
/// 提交 Rule3 执行命令
pub async fn execute_rule3(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineExecuteRule3,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline ExecuteRule3 command queued"
);
Ok(message_id)
}
/// 提交重索引命令
pub async fn reindex_embeddings(&self, file_uuid: &str) -> CommandResult<String> {
let queue = self.get_queue().await?;
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineReindexEmbeddings,
},
json!({
"file_uuid": file_uuid,
}),
);
let message_id = queue.produce(
"pipeline.commands",
command,
ProduceOptions::default(),
).await?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Pipeline ReindexEmbeddings command queued"
);
Ok(message_id)
}
/// 提交完整 pipeline 流程(所有命令)
pub async fn submit_full_pipeline(&self, file_uuid: &str) -> CommandResult<Vec<String>> {
let mut command_ids = Vec::new();
info!(file_uuid = %file_uuid, "Submitting full pipeline");
command_ids.push(self.store_asrx(file_uuid).await?);
command_ids.push(self.execute_rule1(file_uuid).await?);
command_ids.push(self.vectorize_chunks(file_uuid).await?);
command_ids.push(self.phase1_pack(file_uuid).await?);
command_ids.push(self.mark_complete(file_uuid).await?);
info!(
file_uuid = %file_uuid,
count = command_ids.len(),
"Full pipeline submitted"
);
Ok(command_ids)
}
}
+105
View File
@@ -0,0 +1,105 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use serde::{Deserialize, Serialize};
/// Pipeline 命令类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PipelineCommandType {
StoreASRX,
ExecuteRule1,
VectorizeChunks,
Phase1Pack,
MarkComplete,
ExecuteRule3,
ReindexEmbeddings,
}
impl PipelineCommandType {
/// 获取预估执行时间(秒)
pub fn estimated_duration_secs(&self) -> u64 {
match self {
Self::StoreASRX => 5,
Self::ExecuteRule1 => 10,
Self::VectorizeChunks => 120, // 2 分钟
Self::Phase1Pack => 10,
Self::MarkComplete => 5,
Self::ExecuteRule3 => 30,
Self::ReindexEmbeddings => 120,
}
}
/// 是否支持进度报告
pub fn supports_progress(&self) -> bool {
matches!(self, Self::VectorizeChunks | Self::ReindexEmbeddings)
}
}
/// Pipeline 请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineRequest {
pub file_uuid: String,
pub command_type: PipelineCommandType,
#[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<PipelineOptions>,
}
/// Pipeline 选项
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PipelineOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub force: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub batch_size: Option<usize>,
}
/// Pipeline 响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineResponse {
pub command_id: String,
pub file_uuid: String,
pub command_type: PipelineCommandType,
pub status: PipelineStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub progress: Option<u8>, // 0-100
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
pub estimated_duration_secs: u64,
}
/// Pipeline 状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PipelineStatus {
Queued,
Processing,
Completed,
Failed,
}
/// Pipeline 进度更新
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineProgress {
pub command_id: String,
pub file_uuid: String,
pub progress: u8, // 0-100
pub message: String,
pub processed_count: usize,
pub total_count: usize,
}
impl PipelineRequest {
pub fn new(file_uuid: String, command_type: PipelineCommandType) -> Self {
Self {
file_uuid,
command_type,
options: None,
}
}
pub fn with_options(mut self, options: PipelineOptions) -> Self {
self.options = Some(options);
self
}
}
+268
View File
@@ -0,0 +1,268 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use super::types::*;
use crate::core::command::error::{CommandError, CommandResult};
use crate::core::command::queue::CommandQueue;
use crate::core::command::types::{CommandType, ConsumeOptions, InternalCommandCategory, CommandResult as CmdResult};
use crate::core::pipeline;
use crate::core::db::postgres_db::PostgresDb;
use crate::core::config;
use sqlx::PgPool;
use std::time::Instant;
use tracing::{debug, error, info, warn};
/// Pipeline Worker
pub struct PipelineWorker {
worker_id: String,
db: PgPool,
}
impl PipelineWorker {
pub fn new(db: PgPool) -> Self {
Self {
worker_id: uuid::Uuid::new_v4().to_string(),
db,
}
}
/// 启动 Worker
pub async fn start(&self) -> CommandResult<()> {
info!(worker_id = %self.worker_id, "Pipeline worker started");
loop {
match self.process_commands().await {
Ok(count) => {
if count > 0 {
debug!(count = count, "Processed pipeline commands");
}
}
Err(e) => {
error!(error = ?e, "Error processing pipeline commands");
// 短暂休眠后继续
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
}
// 每次循环后休眠一小段时间
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
/// 处理命令
async fn process_commands(&self) -> CommandResult<usize> {
let queue = CommandQueue::new(self.db.clone()).await?;
let messages = queue.consume(
"pipeline.commands",
ConsumeOptions {
consumer_group: "pipeline_workers".to_string(),
consumer_id: self.worker_id.clone(),
max_messages: 5,
timeout_ms: 5000,
auto_commit: false,
},
).await?;
let count = messages.len();
for message in messages {
let message_id = message.message_id.clone();
if let Err(e) = self.handle_command(&message, &self.db).await {
error!(
message_id = %message_id,
error = ?e,
"Pipeline command failed"
);
// 重新创建 queue 来标记失败
let queue2 = CommandQueue::new(self.db.clone()).await?;
if let Err(err) = queue2.fail(&message_id, &e.to_string()).await {
error!(error = ?err, "Failed to mark command as failed");
}
}
}
Ok(count)
}
/// 处理单个命令
async fn handle_command(&self, message: &crate::core::command::types::CommandMessage, db: &PgPool) -> CommandResult<()> {
let command = &message.command;
let message_id = &message.message_id;
// 提取 file_uuid
let file_uuid = command.payload.get("file_uuid")
.and_then(|v| v.as_str())
.ok_or_else(|| CommandError::MissingPayload("file_uuid".to_string()))?;
info!(
message_id = %message_id,
file_uuid = %file_uuid,
"Processing pipeline command"
);
let start = Instant::now();
// 根据命令类型执行操作
let result = match &command.command_type {
CommandType::Internal { category } => match category {
InternalCommandCategory::PipelineStoreASRX => {
self.execute_store_asrx(file_uuid, db).await
}
InternalCommandCategory::PipelineExecuteRule1 => {
self.execute_rule1(file_uuid, db).await
}
InternalCommandCategory::PipelineVectorize => {
self.execute_vectorize(file_uuid).await
}
InternalCommandCategory::PipelinePhase1Pack => {
self.execute_phase1(file_uuid).await
}
InternalCommandCategory::PipelineMarkComplete => {
self.execute_mark_complete(file_uuid, db).await
}
InternalCommandCategory::PipelineExecuteRule3 => {
self.execute_rule3(file_uuid, db).await
}
InternalCommandCategory::PipelineReindexEmbeddings => {
self.execute_reindex(file_uuid).await
}
_ => {
warn!(
message_id = %message_id,
command_type = ?category,
"Unknown pipeline command type"
);
Err(CommandError::InvalidCommandType(format!("{:?}", category)))
}
},
_ => {
warn!(
message_id = %message_id,
command_type = ?command.command_type,
"Non-internal command received in pipeline queue"
);
Err(CommandError::InvalidCommandType(format!("{:?}", command.command_type)))
}
};
let duration_ms = start.elapsed().as_millis() as i64;
// 记录结果
match &result {
Ok(_) => {
info!(
message_id = %message_id,
file_uuid = %file_uuid,
duration_ms = duration_ms,
"Pipeline command completed"
);
// 提交成功
let queue = CommandQueue::new(self.db.clone()).await?;
queue.commit(message_id, &CmdResult {
status: crate::core::command::types::CommandStatus::Completed,
result: Some(serde_json::json!({
"file_uuid": file_uuid,
"duration_ms": duration_ms,
})),
error: None,
duration_ms: Some(duration_ms),
tokens_used: None,
cost_usd: None,
}).await?;
}
Err(e) => {
error!(
message_id = %message_id,
file_uuid = %file_uuid,
duration_ms = duration_ms,
error = ?e,
"Pipeline command failed"
);
}
}
result
}
/// 执行 StoreASRX
async fn execute_store_asrx(&self, file_uuid: &str, db: &PgPool) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing StoreASRX");
let pg_db = PostgresDb::from_pool(db.clone());
pipeline::store_asrx_chunks(&pg_db, file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
/// 执行 Rule1
async fn execute_rule1(&self, file_uuid: &str, db: &PgPool) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing Rule1");
let pg_db = PostgresDb::from_pool(db.clone());
pipeline::execute_rule1(&pg_db, file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
/// 执行 Vectorize
async fn execute_vectorize(&self, file_uuid: &str) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing Vectorize");
pipeline::vectorize_chunks(file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
/// 执行 Phase1
async fn execute_phase1(&self, file_uuid: &str) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing Phase1");
pipeline::run_phase1(file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
/// 执行 MarkComplete
async fn execute_mark_complete(&self, file_uuid: &str, db: &PgPool) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing MarkComplete");
let pg_db = PostgresDb::from_pool(db.clone());
pipeline::mark_complete(&pg_db, file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
/// 执行 Rule3
async fn execute_rule3(&self, file_uuid: &str, db: &PgPool) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing Rule3");
let pg_db = PostgresDb::from_pool(db.clone());
pipeline::execute_rule3_moment(&pg_db, file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
/// 执行 Reindex
async fn execute_reindex(&self, file_uuid: &str) -> CommandResult<()> {
debug!(file_uuid = %file_uuid, "Executing ReindexEmbeddings");
pipeline::reindex_embeddings(file_uuid).await
.map_err(|e| CommandError::ProcessingError(e.to_string()))?;
Ok(())
}
}
+423
View File
@@ -0,0 +1,423 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use crate::core::command::error::{CommandError, CommandResult};
use crate::core::command::types::{
Command, CommandMessage, CommandStatus, ProduceOptions, ConsumeOptions,
BillingContext, QueueRoute,
};
use crate::core::command::router::CommandRouter;
use chrono::{DateTime, Utc};
use serde_json::{Value as JsonValue, json};
use sqlx::PgPool;
use std::sync::Arc;
use tracing::{debug, error, info, warn};
use uuid::Uuid;
/// 命令队列
pub struct CommandQueue {
db: PgPool,
router: CommandRouter,
}
impl CommandQueue {
pub async fn new(db: PgPool) -> CommandResult<Self> {
let mut router = CommandRouter::new();
router.load_from_db(&db).await?;
Ok(Self { db, router })
}
/// 生产消息
pub async fn produce(
&self,
queue_name: &str,
command: Command,
options: ProduceOptions,
) -> CommandResult<String> {
let message_id = Uuid::new_v4().to_string();
let now = Utc::now();
let route = self.router.route(&command.command_type)?;
let priority = options.priority.unwrap_or(command.priority as i32) as i16;
let queue_type = command.command_type.queue_type();
let command_category = Self::command_type_to_string(&command.command_type)?;
let command_type_str = Self::command_category_to_string(&command.command_type);
let billing_context_json = options.billing_context
.as_ref()
.map(|ctx| serde_json::to_value(ctx))
.transpose()?;
sqlx::query!(
r#"
INSERT INTO command_queue (
message_id, queue_name, queue_type,
command_type, command_category,
key, value, priority,
request_id, key_id, billing_context,
scheduled_at, max_retries,
created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
"#,
message_id,
queue_name,
queue_type,
command_type_str,
command_category,
command.metadata.get("key"),
serde_json::to_value(&command.payload)?,
priority,
options.billing_context.as_ref().map(|ctx| ctx.request_id.clone()),
options.billing_context.as_ref().map(|ctx| ctx.key_id.clone()),
billing_context_json,
options.scheduled_at,
options.max_retries.unwrap_or(3),
now,
)
.execute(&self.db)
.await?;
info!(
message_id = %message_id,
queue = %queue_name,
command_type = ?command_type_str,
"Command queued successfully"
);
Ok(message_id)
}
/// 消费消息
pub async fn consume(
&self,
queue_name: &str,
options: ConsumeOptions,
) -> CommandResult<Vec<CommandMessage>> {
let messages = sqlx::query_as!(
CommandMessageRow,
r#"
UPDATE command_queue
SET status = 'processing',
consumer_group = $1,
consumer_id = $2,
processing_started_at = NOW()
WHERE message_id IN (
SELECT message_id
FROM command_queue
WHERE queue_name = $3
AND status = 'pending'
AND (scheduled_at IS NULL OR scheduled_at <= NOW())
ORDER BY priority ASC, created_at ASC
LIMIT $4
FOR UPDATE SKIP LOCKED
)
RETURNING
message_id, queue_name, queue_type,
command_type, command_category, command_action,
key, value, priority,
request_id, key_id, billing_context, token_usage, cost_usd,
status, consumer_group, consumer_id,
retry_count, max_retries, last_error,
created_at, scheduled_at, processing_started_at, processing_completed_at
"#,
options.consumer_group,
options.consumer_id,
queue_name,
options.max_messages as i64,
)
.fetch_all(&self.db)
.await?;
let messages = messages
.into_iter()
.map(|row| self.row_to_message(row))
.collect::<CommandResult<Vec<_>>>()?;
debug!(
queue = %queue_name,
count = messages.len(),
"Consumed messages from queue"
);
Ok(messages)
}
/// 提交消息
pub async fn commit(&self, message_id: &str, result: &crate::core::command::types::CommandResult) -> CommandResult<()> {
let now = Utc::now();
sqlx::query!(
r#"
UPDATE command_queue
SET status = $2,
processing_completed_at = $3,
token_usage = $4,
cost_usd = $5
WHERE message_id = $1
"#,
message_id,
match result.status {
CommandStatus::Completed => "completed",
CommandStatus::Failed => "failed",
_ => "processing",
},
now,
result.tokens_used.map(|t| json!({"total_tokens": t})),
result.cost_usd,
)
.execute(&self.db)
.await?;
sqlx::query!(
r#"
INSERT INTO command_execution_log (
message_id, handler, action, status,
result, error_message,
duration_ms, tokens_used, cost_usd,
executed_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
"#,
message_id,
"default_handler",
"execute",
match result.status {
CommandStatus::Completed => "success",
CommandStatus::Failed => "error",
_ => "unknown",
},
result.result,
result.error,
result.duration_ms.map(|d| d as i32),
result.tokens_used,
result.cost_usd,
now,
)
.execute(&self.db)
.await?;
info!(
message_id = %message_id,
status = ?result.status,
"Message processed successfully"
);
Ok(())
}
/// 标记失败
pub async fn fail(&self, message_id: &str, error: &str) -> CommandResult<()> {
let now = Utc::now();
sqlx::query!(
r#"
UPDATE command_queue
SET status = 'failed',
processing_completed_at = $3,
last_error = $2,
retry_count = retry_count + 1
WHERE message_id = $1
"#,
message_id,
error,
now,
)
.execute(&self.db)
.await?;
warn!(
message_id = %message_id,
error = %error,
"Command marked as failed"
);
Ok(())
}
/// 获取命令状态
pub async fn get_command_status(&self, message_id: &str) -> CommandResult<CommandMessage> {
let row = sqlx::query_as!(
CommandMessageRow,
r#"
SELECT
message_id, queue_name, queue_type,
command_type, command_category, command_action,
key, value, priority,
request_id, key_id, billing_context, token_usage, cost_usd,
status, consumer_group, consumer_id,
retry_count, max_retries, last_error,
created_at, scheduled_at, processing_started_at, processing_completed_at
FROM command_queue
WHERE message_id = $1
"#,
message_id,
)
.fetch_optional(&self.db)
.await?
.ok_or_else(|| CommandError::NotFound(message_id.to_string()))?;
self.row_to_message(row)
}
/// 获取路由器
pub fn router(&self) -> &CommandRouter {
&self.router
}
fn command_type_to_string(ct: &crate::core::command::types::CommandType) -> CommandResult<String> {
use crate::core::command::types::{CommandType, InternalCommandCategory, ExternalCommandCategory, AgentCommandCategory};
match ct {
CommandType::Internal { category } => {
let cat = match category {
// 文件处理
InternalCommandCategory::FileProcessing => "file_processing",
InternalCommandCategory::VideoRegistration => "video_registration",
InternalCommandCategory::FileDeletion => "file_deletion",
// 数据处理
InternalCommandCategory::EmbeddingGeneration => "embedding_generation",
InternalCommandCategory::IndexRebuild => "index_rebuild",
InternalCommandCategory::CacheClear => "cache_clear",
// 系统管理
InternalCommandCategory::WorkerRestart => "worker_restart",
InternalCommandCategory::ServiceHealthCheck => "service_health_check",
InternalCommandCategory::ConfigurationUpdate => "configuration_update",
// 数据同步
InternalCommandCategory::DatabaseMigration => "database_migration",
InternalCommandCategory::VectorSync => "vector_sync",
InternalCommandCategory::IdentityMerging => "identity_merging",
// Pipeline 操作
InternalCommandCategory::PipelineStoreASRX => "pipeline_store_asrx",
InternalCommandCategory::PipelineExecuteRule1 => "pipeline_execute_rule1",
InternalCommandCategory::PipelineVectorize => "pipeline_vectorize",
InternalCommandCategory::PipelinePhase1Pack => "pipeline_phase1_pack",
InternalCommandCategory::PipelineMarkComplete => "pipeline_mark_complete",
InternalCommandCategory::PipelineExecuteRule3 => "pipeline_execute_rule3",
InternalCommandCategory::PipelineReindexEmbeddings => "pipeline_reindex_embeddings",
};
Ok(cat.to_string())
}
CommandType::External { category } => {
let cat = match category {
ExternalCommandCategory::ApiRequest => "api_request",
ExternalCommandCategory::UserCommand => "user_command",
ExternalCommandCategory::WebhookTrigger => "webhook_trigger",
ExternalCommandCategory::IntegrationSync => "integration_sync",
ExternalCommandCategory::ExternalApiCall => "external_api_call",
};
Ok(cat.to_string())
}
CommandType::Agent { category } => {
let cat = match category {
AgentCommandCategory::AgentTask => "agent_task",
AgentCommandCategory::AgentQuery => "agent_query",
AgentCommandCategory::AgentResponse => "agent_response",
AgentCommandCategory::AgentMessage => "agent_message",
AgentCommandCategory::AgentBroadcast => "agent_broadcast",
AgentCommandCategory::AgentSubscribe => "agent_subscribe",
};
Ok(cat.to_string())
}
}
}
fn command_category_to_string(ct: &crate::core::command::types::CommandType) -> Option<String> {
use crate::core::command::types::CommandType;
match ct {
CommandType::Internal { .. } => Some("internal".to_string()),
CommandType::External { .. } => Some("external".to_string()),
CommandType::Agent { .. } => Some("agent".to_string()),
}
}
fn row_to_message(&self, row: CommandMessageRow) -> CommandResult<CommandMessage> {
let command_type = CommandRouter::parse_command_type(&row.command_type, row.command_category.as_deref())?;
let billing_ctx: Option<BillingContext> = row.billing_context
.map(|v| serde_json::from_value(v))
.transpose()?;
let mut metadata = std::collections::HashMap::new();
if let Some(key) = row.key {
metadata.insert("key".to_string(), key);
}
if let Some(request_id) = row.request_id {
metadata.insert("request_id".to_string(), request_id);
}
if let Some(key_id) = row.key_id {
metadata.insert("key_id".to_string(), key_id);
}
if let Some(ctx) = &billing_ctx {
metadata.insert("billing_context".to_string(), serde_json::to_string(ctx)?);
}
let command = Command {
command_type,
payload: row.value,
priority: match row.priority.unwrap_or(2) {
0 => crate::core::command::types::CommandPriority::Critical,
1 => crate::core::command::types::CommandPriority::High,
2 => crate::core::command::types::CommandPriority::Normal,
3 => crate::core::command::types::CommandPriority::Low,
_ => crate::core::command::types::CommandPriority::Normal,
},
metadata,
};
let status = match row.status.unwrap_or_else(|| "pending".to_string()).as_str() {
"pending" => CommandStatus::Pending,
"processing" => CommandStatus::Processing,
"completed" => CommandStatus::Completed,
"failed" => CommandStatus::Failed,
_ => CommandStatus::Pending,
};
Ok(CommandMessage {
message_id: row.message_id,
queue_name: row.queue_name,
queue_type: row.queue_type,
command,
status,
scheduled_at: row.scheduled_at,
created_at: row.created_at.unwrap_or_else(Utc::now),
processing_started_at: row.processing_started_at,
processing_completed_at: row.processing_completed_at,
retry_count: row.retry_count,
last_error: row.last_error,
})
}
}
#[derive(Debug, sqlx::FromRow)]
struct CommandMessageRow {
message_id: String,
queue_name: String,
queue_type: String,
command_type: String,
command_category: Option<String>,
command_action: Option<String>,
key: Option<String>,
value: JsonValue,
priority: Option<i16>,
request_id: Option<String>,
key_id: Option<String>,
billing_context: Option<JsonValue>,
token_usage: Option<JsonValue>,
cost_usd: Option<f64>,
status: Option<String>,
consumer_group: Option<String>,
consumer_id: Option<String>,
retry_count: Option<i32>,
max_retries: Option<i32>,
last_error: Option<String>,
created_at: Option<DateTime<Utc>>,
scheduled_at: Option<DateTime<Utc>>,
processing_started_at: Option<DateTime<Utc>>,
processing_completed_at: Option<DateTime<Utc>>,
}
+165
View File
@@ -0,0 +1,165 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use crate::core::command::error::CommandError;
use crate::core::command::types::{CommandType, CommandPriority, QueueRoute};
use std::collections::HashMap;
/// 命令路由器
pub struct CommandRouter {
routes: HashMap<CommandType, QueueRoute>,
}
impl CommandRouter {
pub fn new() -> Self {
Self {
routes: HashMap::new(),
}
}
/// 从数据库加载路由规则
pub async fn load_from_db(&mut self, db: &sqlx::PgPool) -> Result<(), CommandError> {
let rows = sqlx::query!(
r#"
SELECT command_type, command_category, queue_name, handler, priority, billing_required
FROM queue_routes
WHERE active = true
"#
)
.fetch_all(db)
.await?;
for row in rows {
let command_type = Self::parse_command_type(&row.command_type, row.command_category.as_deref())?;
let priority = match row.priority.unwrap_or(2) {
0 => CommandPriority::Critical,
1 => CommandPriority::High,
2 => CommandPriority::Normal,
3 => CommandPriority::Low,
_ => CommandPriority::Normal,
};
let route = QueueRoute {
queue_name: row.queue_name,
handler: row.handler,
priority,
billing_required: row.billing_required.unwrap_or(true),
};
self.routes.insert(command_type, route);
}
Ok(())
}
/// 路由命令到对应队列
pub fn route(&self, command_type: &CommandType) -> Result<QueueRoute, CommandError> {
if let Some(route) = self.routes.get(command_type) {
return Ok(route.clone());
}
Err(CommandError::RouteNotFound(format!("{:?}", command_type)))
}
/// 注册路由
pub fn register_route(&mut self, command_type: CommandType, route: QueueRoute) {
self.routes.insert(command_type, route);
}
/// 解析命令类型
pub fn parse_command_type(type_str: &str, category: Option<&str>) -> Result<CommandType, CommandError> {
match type_str {
"internal" => {
let category = category
.ok_or_else(|| CommandError::InvalidCommandType("missing category".to_string()))?;
let cat = Self::parse_internal_category(category)?;
Ok(CommandType::Internal { category: cat })
}
"external" => {
let category = category
.ok_or_else(|| CommandError::InvalidCommandType("missing category".to_string()))?;
let cat = Self::parse_external_category(category)?;
Ok(CommandType::External { category: cat })
}
"agent" => {
let category = category
.ok_or_else(|| CommandError::InvalidCommandType("missing category".to_string()))?;
let cat = Self::parse_agent_category(category)?;
Ok(CommandType::Agent { category: cat })
}
_ => Err(CommandError::InvalidCommandType(type_str.to_string())),
}
}
fn parse_internal_category(s: &str) -> Result<crate::core::command::types::InternalCommandCategory, CommandError> {
use crate::core::command::types::InternalCommandCategory;
match s {
// 文件处理
"file_processing" => Ok(InternalCommandCategory::FileProcessing),
"video_registration" => Ok(InternalCommandCategory::VideoRegistration),
"file_deletion" => Ok(InternalCommandCategory::FileDeletion),
// 数据处理
"embedding_generation" => Ok(InternalCommandCategory::EmbeddingGeneration),
"index_rebuild" => Ok(InternalCommandCategory::IndexRebuild),
"cache_clear" => Ok(InternalCommandCategory::CacheClear),
// 系统管理
"worker_restart" => Ok(InternalCommandCategory::WorkerRestart),
"service_health_check" => Ok(InternalCommandCategory::ServiceHealthCheck),
"configuration_update" => Ok(InternalCommandCategory::ConfigurationUpdate),
// 数据同步
"database_migration" => Ok(InternalCommandCategory::DatabaseMigration),
"vector_sync" => Ok(InternalCommandCategory::VectorSync),
"identity_merging" => Ok(InternalCommandCategory::IdentityMerging),
// Pipeline 操作
"pipeline_store_asrx" => Ok(InternalCommandCategory::PipelineStoreASRX),
"pipeline_execute_rule1" => Ok(InternalCommandCategory::PipelineExecuteRule1),
"pipeline_vectorize" => Ok(InternalCommandCategory::PipelineVectorize),
"pipeline_phase1_pack" => Ok(InternalCommandCategory::PipelinePhase1Pack),
"pipeline_mark_complete" => Ok(InternalCommandCategory::PipelineMarkComplete),
"pipeline_execute_rule3" => Ok(InternalCommandCategory::PipelineExecuteRule3),
"pipeline_reindex_embeddings" => Ok(InternalCommandCategory::PipelineReindexEmbeddings),
_ => Err(CommandError::InvalidCommandType(s.to_string())),
}
}
fn parse_external_category(s: &str) -> Result<crate::core::command::types::ExternalCommandCategory, CommandError> {
use crate::core::command::types::ExternalCommandCategory;
match s {
"api_request" => Ok(ExternalCommandCategory::ApiRequest),
"user_command" => Ok(ExternalCommandCategory::UserCommand),
"webhook_trigger" => Ok(ExternalCommandCategory::WebhookTrigger),
"integration_sync" => Ok(ExternalCommandCategory::IntegrationSync),
"external_api_call" => Ok(ExternalCommandCategory::ExternalApiCall),
_ => Err(CommandError::InvalidCommandType(s.to_string())),
}
}
fn parse_agent_category(s: &str) -> Result<crate::core::command::types::AgentCommandCategory, CommandError> {
use crate::core::command::types::AgentCommandCategory;
match s {
"agent_task" => Ok(AgentCommandCategory::AgentTask),
"agent_query" => Ok(AgentCommandCategory::AgentQuery),
"agent_response" => Ok(AgentCommandCategory::AgentResponse),
"agent_message" => Ok(AgentCommandCategory::AgentMessage),
"agent_broadcast" => Ok(AgentCommandCategory::AgentBroadcast),
"agent_subscribe" => Ok(AgentCommandCategory::AgentSubscribe),
_ => Err(CommandError::InvalidCommandType(s.to_string())),
}
}
/// 获取所有路由
pub fn routes(&self) -> &HashMap<CommandType, QueueRoute> {
&self.routes
}
}
impl Default for CommandRouter {
fn default() -> Self {
Self::new()
}
}
+161
View File
@@ -0,0 +1,161 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
pub mod types;
pub use types::{
SearchType, SearchRequest, SearchFilters, SearchOptions, DateRange,
SearchResponse, SearchResult, Highlight,
};
use types::*;
use super::messenger::Messenger;
use super::error::{CommandError, CommandResult};
use super::messenger::types::{Message, MessageSource, MessagePriority, MessageType, DeliveryOptions};
use std::time::Instant;
use tracing::{debug, info};
/// Search Messenger 服务
pub struct SearchMessenger {
messenger: Messenger,
}
impl SearchMessenger {
pub fn new(db: sqlx::PgPool) -> Self {
Self {
messenger: Messenger::new(db),
}
}
/// 提交搜索请求
pub async fn search(
&self,
request: SearchRequest,
user_id: Option<String>,
api_key: Option<String>,
) -> CommandResult<String> {
let source = MessageSource::Api {
endpoint: "/api/v1/search".to_string(),
method: "POST".to_string(),
};
let message = Message::new(
MessageType::Command,
source,
serde_json::to_value(&request)?,
)
.with_priority(MessagePriority::High)
.with_metadata("search_type".to_string(), serde_json::to_string(&request.search_type)?);
let mut message = message;
if let Some(uid) = user_id {
message = message.with_metadata("user_id".to_string(), uid);
}
if let Some(key) = api_key {
message = message.with_metadata("api_key".to_string(), key);
}
let options = DeliveryOptions {
persistent: true,
ttl_seconds: Some(300),
require_ack: true,
..Default::default()
};
self.messenger.send("search.requests", message, options).await
}
/// 获取搜索结果
pub async fn get_result(&self, request_id: &str) -> CommandResult<Option<SearchResponse>> {
let messages = self.messenger.receive(
"search.results",
&format!("search_waiter_{}", request_id),
1,
30000,
).await?;
if let Some(message) = messages.first() {
let response: SearchResponse = serde_json::from_value(message.payload.clone())?;
self.messenger.acknowledge(&message.message_id, &format!("search_waiter_{}", request_id)).await?;
return Ok(Some(response));
}
Ok(None)
}
/// 执行搜索(同步)
pub async fn execute_search(
&self,
request: SearchRequest,
user_id: Option<String>,
api_key: Option<String>,
) -> CommandResult<SearchResponse> {
let start = Instant::now();
let request_id = self.search(request.clone(), user_id, api_key).await?;
let timeout = request.options.limit.unwrap_or(30) as u64 * 1000;
let deadline = Instant::now() + std::time::Duration::from_millis(timeout);
loop {
if Instant::now() > deadline {
return Err(CommandError::Timeout(timeout as i32));
}
if let Some(response) = self.get_result(&request_id).await? {
debug!(
request_id = %request_id,
took_ms = start.elapsed().as_millis(),
"Search completed"
);
return Ok(response);
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
/// 取消搜索
pub async fn cancel(&self, request_id: &str) -> CommandResult<()> {
let message = Message::new(
MessageType::Command,
MessageSource::System {
component: "search_service".to_string(),
},
serde_json::json!({
"action": "cancel",
"request_id": request_id,
}),
)
.with_priority(MessagePriority::High);
self.messenger.send(
"search.control",
message,
DeliveryOptions::default(),
).await?;
info!(request_id = %request_id, "Search cancelled");
Ok(())
}
/// 批量搜索
pub async fn batch_search(
&self,
requests: Vec<SearchRequest>,
user_id: Option<String>,
api_key: Option<String>,
) -> CommandResult<Vec<String>> {
let mut request_ids = Vec::new();
for request in requests {
let id = self.search(request, user_id.clone(), api_key.clone()).await?;
request_ids.push(id);
}
info!(count = request_ids.len(), "Batch search submitted");
Ok(request_ids)
}
}
+274
View File
@@ -0,0 +1,274 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
/// Search 类型(5 种)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SearchType {
/// 关键词搜索 - BM25 + FTS
Keyword,
/// 语义搜索 - Vector Embedding
Semantic,
/// 视觉搜索 - Image/VLM
Visual,
/// Agent 搜索 - LLM + RAG
Agent,
/// 人物搜索 - Face Identity
People,
}
impl SearchType {
pub fn description(&self) -> &'static str {
match self {
SearchType::Keyword => "Precise text matching using BM25 and FTS",
SearchType::Semantic => "Conceptual understanding using vector embeddings",
SearchType::Visual => "Visual content search using VLM and image analysis",
SearchType::Agent => "Complex reasoning search using LLM and RAG",
SearchType::People => "Person-focused search using face identity",
}
}
pub fn priority(&self) -> crate::core::command::messenger::types::MessagePriority {
match self {
SearchType::Keyword => crate::core::command::messenger::types::MessagePriority::High,
SearchType::Semantic => crate::core::command::messenger::types::MessagePriority::High,
SearchType::Visual => crate::core::command::messenger::types::MessagePriority::Normal,
SearchType::Agent => crate::core::command::messenger::types::MessagePriority::Normal,
SearchType::People => crate::core::command::messenger::types::MessagePriority::High,
}
}
}
/// Search 请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchRequest {
pub query: String,
pub search_type: SearchType,
#[serde(default)]
pub filters: SearchFilters,
#[serde(default)]
pub options: SearchOptions,
}
/// Search 过滤器
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchFilters {
#[serde(skip_serializing_if = "Option::is_none")]
pub file_uuids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub date_range: Option<DateRange>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub identities: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locations: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub custom: Option<JsonValue>,
}
/// Search 选项
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchOptions {
/// 限制数量(默认 5,More 操作时为 10)
#[serde(default = "default_search_limit")]
pub limit: i32,
/// 偏移量
#[serde(default)]
pub offset: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub include_metadata: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub include_thumbnails: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sort_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sort_order: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub highlight: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub explain: Option<bool>,
}
fn default_search_limit() -> i32 {
5 // 默认返回 top 5
}
/// 日期范围
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DateRange {
pub start: DateTime<Utc>,
pub end: DateTime<Utc>,
}
/// Search 响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResponse {
pub request_id: String,
pub query: String,
pub search_type: SearchType,
pub results: Vec<SearchResult>,
pub total_count: i64,
pub took_ms: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub facets: Option<JsonValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub suggestions: Option<Vec<String>>,
}
/// Search 结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
pub id: String,
pub score: f64,
pub file_uuid: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub timestamp: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub snippet: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub highlights: Option<Vec<Highlight>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<JsonValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail: Option<String>,
}
/// 高亮
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Highlight {
pub field: String,
pub fragments: Vec<String>,
}
/// 查询意图
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryIntent {
pub primary_type: SearchType,
pub search_types: Vec<SearchType>,
pub confidence: f64,
pub scores: SearchTypeScores,
pub entities: Vec<String>,
pub keywords: Vec<String>,
}
/// 搜索类型分数
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchTypeScores {
pub keyword: f64,
pub semantic: f64,
pub visual: f64,
pub agent: f64,
pub people: f64,
}
/// 搜索上下文
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchContext {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
#[serde(default)]
pub conversation_history: Vec<crate::core::command::messenger::types::Message>,
#[serde(default)]
pub filters: SearchFilters,
#[serde(default)]
pub options: SearchOptions,
}
/// 统一搜索响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedSearchResponse {
pub query: String,
pub intent: QueryIntent,
pub results: Vec<SearchResult>,
pub total_count: i64,
pub summary: String,
pub took_ms: i64,
}
/// Agent Search 请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSearchRequest {
pub query: String,
#[serde(default)]
pub offset: i32,
#[serde(default = "default_search_limit")]
pub limit: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<SearchContext>,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
}
/// More 请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MoreRequest {
pub session_id: String,
pub current_offset: i32,
#[serde(default = "more_limit")]
pub limit: i32,
}
fn more_limit() -> i32 {
10 // More 操作固定返回 10 个
}
/// Agent Search 响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSearchResponse {
pub query: String,
pub session_id: String,
pub intent: QueryIntent,
pub results: Vec<SearchResult>,
pub total_count: i64,
pub offset: i32,
pub returned_count: i32,
pub has_more: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_offset: Option<i32>,
pub summary: String,
pub took_ms: i64,
}
/// 搜索会话
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchSession {
pub session_id: String,
pub user_id: String,
pub query: String,
pub intent: QueryIntent,
pub total_count: i64,
pub created_at: chrono::DateTime<chrono::Utc>,
pub expires_at: chrono::DateTime<chrono::Utc>,
}
impl SearchRequest {
pub fn new(query: String, search_type: SearchType) -> Self {
Self {
query,
search_type,
filters: SearchFilters::default(),
options: SearchOptions::default(),
}
}
pub fn with_filters(mut self, filters: SearchFilters) -> Self {
self.filters = filters;
self
}
pub fn with_options(mut self, options: SearchOptions) -> Self {
self.options = options;
self
}
}
+314
View File
@@ -0,0 +1,314 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use super::error::CommandError;
/// 命令类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum CommandType {
Internal { category: InternalCommandCategory },
External { category: ExternalCommandCategory },
Agent { category: AgentCommandCategory },
}
/// 内部命令分类
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum InternalCommandCategory {
// 文件处理
FileProcessing,
VideoRegistration,
FileDeletion,
// 数据处理
EmbeddingGeneration,
IndexRebuild,
CacheClear,
// 系统管理
WorkerRestart,
ServiceHealthCheck,
ConfigurationUpdate,
// 数据同步
DatabaseMigration,
VectorSync,
IdentityMerging,
// Pipeline 操作
PipelineStoreASRX,
PipelineExecuteRule1,
PipelineVectorize,
PipelinePhase1Pack,
PipelineMarkComplete,
PipelineExecuteRule3,
PipelineReindexEmbeddings,
}
/// 外部命令分类
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ExternalCommandCategory {
ApiRequest,
UserCommand,
WebhookTrigger,
IntegrationSync,
ExternalApiCall,
}
/// Agent 沟通命令分类
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum AgentCommandCategory {
AgentTask,
AgentQuery,
AgentResponse,
AgentMessage,
AgentBroadcast,
AgentSubscribe,
}
/// 命令优先级
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum CommandPriority {
Critical = 0,
High = 1,
Normal = 2,
Low = 3,
}
impl Default for CommandPriority {
fn default() -> Self {
CommandPriority::Normal
}
}
impl CommandType {
pub fn default_priority(&self) -> CommandPriority {
match self {
CommandType::Agent { .. } => CommandPriority::Critical,
CommandType::External { category } => match category {
ExternalCommandCategory::ApiRequest => CommandPriority::High,
ExternalCommandCategory::UserCommand => CommandPriority::High,
ExternalCommandCategory::WebhookTrigger => CommandPriority::Normal,
ExternalCommandCategory::IntegrationSync => CommandPriority::Low,
ExternalCommandCategory::ExternalApiCall => CommandPriority::Normal,
},
CommandType::Internal { category } => match category {
// 文件处理
InternalCommandCategory::FileProcessing => CommandPriority::Normal,
InternalCommandCategory::VideoRegistration => CommandPriority::Normal,
InternalCommandCategory::FileDeletion => CommandPriority::Low,
// 数据处理
InternalCommandCategory::EmbeddingGeneration => CommandPriority::Normal,
InternalCommandCategory::IndexRebuild => CommandPriority::Low,
InternalCommandCategory::CacheClear => CommandPriority::Low,
// 系统管理
InternalCommandCategory::WorkerRestart => CommandPriority::High,
InternalCommandCategory::ServiceHealthCheck => CommandPriority::Normal,
InternalCommandCategory::ConfigurationUpdate => CommandPriority::High,
// 数据同步
InternalCommandCategory::DatabaseMigration => CommandPriority::Critical,
InternalCommandCategory::VectorSync => CommandPriority::Normal,
InternalCommandCategory::IdentityMerging => CommandPriority::Low,
// Pipeline 操作
InternalCommandCategory::PipelineStoreASRX => CommandPriority::High,
InternalCommandCategory::PipelineExecuteRule1 => CommandPriority::Normal,
InternalCommandCategory::PipelineVectorize => CommandPriority::Low, // 长时间任务
InternalCommandCategory::PipelinePhase1Pack => CommandPriority::Normal,
InternalCommandCategory::PipelineMarkComplete => CommandPriority::High,
InternalCommandCategory::PipelineExecuteRule3 => CommandPriority::Normal,
InternalCommandCategory::PipelineReindexEmbeddings => CommandPriority::Low,
},
}
}
pub fn queue_type(&self) -> &'static str {
match self {
CommandType::Internal { .. } => "internal",
CommandType::External { .. } => "external",
CommandType::Agent { .. } => "agent",
}
}
}
/// 命令
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Command {
pub command_type: CommandType,
pub payload: JsonValue,
#[serde(default)]
pub priority: CommandPriority,
#[serde(default)]
pub metadata: HashMap<String, String>,
}
impl Command {
pub fn new(command_type: CommandType, payload: JsonValue) -> Self {
let priority = command_type.default_priority();
Self {
command_type,
payload,
priority,
metadata: HashMap::new(),
}
}
pub fn with_priority(mut self, priority: CommandPriority) -> Self {
self.priority = priority;
self
}
pub fn with_metadata(mut self, key: String, value: String) -> Self {
self.metadata.insert(key, value);
self
}
}
/// 队列消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandMessage {
pub message_id: String,
pub queue_name: String,
pub queue_type: String,
pub command: Command,
pub status: CommandStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub scheduled_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_started_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_completed_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub retry_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_error: Option<String>,
}
/// 命令状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CommandStatus {
Pending,
Processing,
Completed,
Failed,
}
/// 命令结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandResult {
pub status: CommandStatus,
pub result: Option<JsonValue>,
pub error: Option<String>,
pub duration_ms: Option<i64>,
pub tokens_used: Option<i32>,
pub cost_usd: Option<f64>,
}
/// 生产选项
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProduceOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub priority: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scheduled_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_context: Option<BillingContext>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_retries: Option<i32>,
}
/// 消费选项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsumeOptions {
pub consumer_group: String,
pub consumer_id: String,
#[serde(default = "default_max_messages")]
pub max_messages: i32,
#[serde(default = "default_timeout_ms")]
pub timeout_ms: i32,
#[serde(default)]
pub auto_commit: bool,
}
fn default_max_messages() -> i32 { 10 }
fn default_timeout_ms() -> i32 { 5000 }
/// Billing 上下文
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingContext {
pub request_id: String,
pub key_id: String,
pub user_id: Option<String>,
pub quota_limit: i64,
pub quota_used: i64,
pub quota_remaining: i64,
}
/// Agent 消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentMessage {
pub from: String,
pub to: String,
pub message_type: AgentMessageType,
pub content: JsonValue,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentMessageType {
Task,
Query,
Response,
Broadcast,
}
impl AgentMessage {
pub fn from_command(command: Command) -> Result<Self, CommandError> {
let from = command.metadata.get("from_agent")
.ok_or(CommandError::MissingMetadata("from_agent".to_string()))?
.clone();
let to = command.metadata.get("to_agent")
.ok_or(CommandError::MissingMetadata("to_agent".to_string()))?
.clone();
let message_type = serde_json::from_value(
command.payload.get("message_type")
.ok_or(CommandError::MissingPayload("message_type".to_string()))?
.clone()
)?;
let content = command.payload.get("content")
.ok_or(CommandError::MissingPayload("content".to_string()))?
.clone();
Ok(Self {
from,
to,
message_type,
content,
})
}
}
/// 队列路由
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueRoute {
pub queue_name: String,
pub handler: String,
pub priority: CommandPriority,
pub billing_required: bool,
}
+11 -13
View File
@@ -8,9 +8,9 @@ use std::sync::RwLock;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutionMode {
Python, // Use Python scripts (default)
Cli, // Use Swift/Rust CLI tools
Hybrid, // Use CLI for performance-critical processors, Python for others
Python, // Use Python scripts (default)
Cli, // Use Swift/Rust CLI tools
Hybrid, // Use CLI for performance-critical processors, Python for others
}
pub static EXECUTION_MODE: Lazy<ExecutionMode> = Lazy::new(|| {
@@ -72,8 +72,7 @@ pub fn set_auto_pipeline_enabled(enabled: bool) {
}
pub static RUNTIME_PREFERRED_LANGUAGE: Lazy<RwLock<String>> = Lazy::new(|| {
let initial = env::var("MOMENTRY_PREFERRED_LANGUAGE")
.unwrap_or_else(|_| "zh-TW".to_string());
let initial = env::var("MOMENTRY_PREFERRED_LANGUAGE").unwrap_or_else(|_| "zh-TW".to_string());
RwLock::new(initial)
});
@@ -234,14 +233,13 @@ pub static MEDIA_BASE_URL: Lazy<String> = Lazy::new(|| {
});
pub static STORAGE_ROOT: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_STORAGE_ROOT")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/sftpgo/data".to_string())
})
env::var("MOMENTRY_STORAGE_ROOT").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/sftpgo/data".to_string())
})
});
pub static SERVE_BASE_URL: Lazy<String> = Lazy::new(|| {
+5 -4
View File
@@ -3,6 +3,7 @@ use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType};
use crate::core::db::qdrant_db::new_http_client;
pub struct MongoDb {
base_url: String,
@@ -66,7 +67,7 @@ impl Default for MongoDb {
impl MongoDb {
pub async fn store_chunk(&self, chunk: &Chunk) -> Result<()> {
let doc: ChunkDocument = chunk.clone().into();
let client = reqwest::Client::new();
let client = new_http_client();
let url = format!("{}/{}/chunks", self.base_url, self.database);
@@ -81,7 +82,7 @@ impl MongoDb {
}
pub async fn get_chunks_by_uuid(&self, uuid: &str) -> Result<Vec<Chunk>> {
let client = reqwest::Client::new();
let client = new_http_client();
let url = format!(
"{}/{}/chunks?filter={{\"uuid\":\"{}\"}}",
self.base_url, self.database, uuid
@@ -139,7 +140,7 @@ impl MongoDb {
}
pub async fn search_text(&self, query: &str) -> Result<Vec<Chunk>> {
let client = reqwest::Client::new();
let client = new_http_client();
let url = format!(
"{}/{}/chunks?filter={{\"$text\":{{\"$search\":\"{}\"}}}}",
self.base_url, self.database, query
@@ -197,7 +198,7 @@ impl MongoDb {
}
pub async fn get_all_chunks(&self) -> Result<Vec<Chunk>> {
let client = reqwest::Client::new();
let client = new_http_client();
let url = format!("{}/{}/chunks", self.base_url, self.database);
let response = client
+172 -30
View File
@@ -467,7 +467,7 @@ impl CommandJobStatus {
pub fn as_str(&self) -> &'static str {
match self {
CommandJobStatus::Pending => "pending",
CommandJobStatus::Running => "running",
CommandJobStatus::Running => "processing",
CommandJobStatus::Completed => "completed",
CommandJobStatus::Failed => "failed",
CommandJobStatus::Cancelled => "cancelled",
@@ -477,7 +477,7 @@ impl CommandJobStatus {
pub fn from_db_str(s: &str) -> Option<Self> {
match s {
"pending" => Some(CommandJobStatus::Pending),
"running" => Some(CommandJobStatus::Running),
"running" | "processing" => Some(CommandJobStatus::Running),
"completed" => Some(CommandJobStatus::Completed),
"failed" => Some(CommandJobStatus::Failed),
"cancelled" => Some(CommandJobStatus::Cancelled),
@@ -488,7 +488,7 @@ impl CommandJobStatus {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandJob {
pub id: i32,
pub id: i64,
pub command_id: String,
pub job_type: String,
pub file_path: Option<String>,
@@ -518,7 +518,7 @@ pub fn parse_command_job(row: sqlx::postgres::PgRow) -> CommandJob {
let status_str: String = row.get(7);
let status = CommandJobStatus::from_db_str(&status_str).unwrap_or(CommandJobStatus::Pending);
CommandJob {
id: row.get::<i32, _>(0),
id: row.get::<i64, _>(0),
command_id: row.get(1),
job_type: row.get(2),
file_path: row.get(3),
@@ -1079,9 +1079,20 @@ impl PostgresDb {
.await
.unwrap_or(0);
if applied_count >= 42 {
tracing::info!("Schema already fully applied ({} migrations), skipping migration files", applied_count);
tracing::info!("This indicates schema.sql was used for initial setup");
// Guard against re-scanning migration files on every boot. The expected
// count comes from the manifest embedded by build.rs, instead of a
// hardcoded number that drifted out of sync with the real files.
let bundled_count: i64 = env!("REQUIRED_MIGRATIONS")
.split(',')
.filter(|s| !s.is_empty())
.count() as i64;
if bundled_count > 0 && applied_count >= bundled_count {
tracing::info!(
"Schema already fully applied ({}/{} bundled migrations), skipping migration files",
applied_count,
bundled_count
);
return Ok(());
}
@@ -1745,7 +1756,23 @@ impl PostgresDb {
let checksum = format!("{:x}", md5::compute(&sql_content));
match sqlx::raw_sql(&sql_with_schema).execute(pool).await {
// Bound each migration so a lock-contended or hanging statement
// cannot stall server startup indefinitely.
let apply_result = match tokio::time::timeout(
std::time::Duration::from_secs(120),
sqlx::raw_sql(&sql_with_schema).execute(pool),
)
.await
{
Ok(res) => res,
Err(_) => {
tracing::error!("✗ Timed out after 120s applying {}", filename);
failed_count += 1;
continue;
}
};
match apply_result {
Ok(_) => {
let duration_ms = file_start.elapsed().as_millis() as i32;
@@ -1778,6 +1805,13 @@ impl PostgresDb {
skipped_count,
failed_count
);
if failed_count > 0 {
return Err(anyhow::anyhow!(
"{} migration file(s) failed to apply",
failed_count
));
}
}
tracing::info!("Database migrations completed.");
@@ -2360,26 +2394,69 @@ impl PostgresDb {
priority: i32,
) -> Result<CommandJob> {
let table = schema::table_name("command_queue");
let mut value = payload.clone();
if let Some(fp) = file_path {
value["file_path"] = serde_json::json!(fp);
}
if let Some(uuid) = file_uuid {
value["file_uuid"] = serde_json::json!(uuid);
}
if let Some(uid) = user_id {
value["user_id"] = serde_json::json!(uid);
}
let priority_i16 = priority as i16;
let message_id = uuid::Uuid::new_v4().to_string();
let row = sqlx::query(
&format!(
r#"
INSERT INTO {} (job_type, file_path, file_uuid, user_id, payload, priority, status)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, 'pending')
RETURNING id, command_id, job_type, file_path, file_uuid, user_id, payload, status, priority, error_count, last_error, retry_count, started_at::TEXT, completed_at::TEXT, updated_at::TEXT, created_at::TEXT
INSERT INTO {} (message_id, command_type, queue_name, queue_type, command_category, value, priority, status)
VALUES ($1, $2, 'internal.file', 'internal', $3, $4::jsonb, $5, 'pending')
RETURNING id, message_id, command_type, key, value, status, priority, retry_count, last_error, created_at::TEXT, processing_started_at::TEXT, processing_completed_at::TEXT
"#,
table
)
)
.bind(&message_id)
.bind(job_type)
.bind(file_path)
.bind(file_uuid)
.bind(user_id)
.bind(payload.to_string())
.bind(priority)
.bind(job_type)
.bind(value.to_string())
.bind(priority_i16)
.fetch_one(&self.pool)
.await?;
Ok(parse_command_job(row))
let message_id_out: String = row.get("message_id");
let command_type: String = row.get("command_type");
let value_out: serde_json::Value = row.get("value");
let status_str: String = row.get("status");
let status = CommandJobStatus::from_db_str(&status_str).unwrap_or(CommandJobStatus::Pending);
let priority_out: i32 = row.get::<i16, _>("priority") as i32;
let retry_count: i32 = row.get("retry_count");
let last_error: Option<String> = row.get("last_error");
let created_at: String = row.get("created_at");
let processing_started_at: Option<String> = row.get("processing_started_at");
let processing_completed_at: Option<String> = row.get("processing_completed_at");
Ok(CommandJob {
id: row.get("id"),
command_id: message_id_out,
job_type: command_type,
file_path: value_out.get("file_path").and_then(|v| v.as_str()).map(String::from),
file_uuid: value_out.get("file_uuid").and_then(|v| v.as_str()).map(String::from),
user_id: value_out.get("user_id").and_then(|v| v.as_i64()),
payload: value_out,
status,
priority: priority_out,
error_count: 0,
last_error,
retry_count,
started_at: processing_started_at,
completed_at: processing_completed_at,
updated_at: None,
created_at,
})
}
pub async fn claim_pending_commands(&self, limit: i32) -> Result<Vec<CommandJob>> {
@@ -2388,13 +2465,15 @@ impl PostgresDb {
&format!(
r#"
WITH claimed AS (
SELECT id FROM {} WHERE status = 'pending'
ORDER BY priority DESC, created_at ASC
FOR UPDATE SKIP LOCKED LIMIT $1
SELECT id FROM {}
WHERE status = 'pending'
AND queue_name = 'internal.file'
ORDER BY priority ASC, created_at ASC
FOR UPDATE SKIP LOCKED LIMIT $1
)
UPDATE {} cq SET status = 'running', started_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
UPDATE {} cq SET status = 'processing', processing_started_at = CURRENT_TIMESTAMP
FROM claimed WHERE cq.id = claimed.id
RETURNING cq.id, cq.command_id, cq.job_type, cq.file_path, cq.file_uuid, cq.user_id, cq.payload, cq.status, cq.priority, cq.error_count, cq.last_error, cq.retry_count, cq.started_at::TEXT, cq.completed_at::TEXT, cq.updated_at::TEXT, cq.created_at::TEXT
RETURNING cq.id, cq.message_id, cq.command_type, cq.key, cq.value, cq.status, cq.priority, cq.retry_count, cq.last_error, cq.created_at::TEXT, cq.processing_started_at::TEXT, cq.processing_completed_at::TEXT
"#,
table,
table
@@ -2404,7 +2483,39 @@ SELECT id FROM {} WHERE status = 'pending'
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(parse_command_job).collect())
Ok(rows.into_iter().map(|row| {
let message_id: String = row.get("message_id");
let command_type: String = row.get("command_type");
let key: Option<String> = row.get("key");
let value: serde_json::Value = row.get("value");
let status_str: String = row.get("status");
let status = CommandJobStatus::from_db_str(&status_str).unwrap_or(CommandJobStatus::Pending);
let priority: i32 = row.get::<i16, _>("priority") as i32;
let retry_count: i32 = row.get("retry_count");
let last_error: Option<String> = row.get("last_error");
let created_at: String = row.get("created_at");
let processing_started_at: Option<String> = row.get("processing_started_at");
let processing_completed_at: Option<String> = row.get("processing_completed_at");
CommandJob {
id: row.get("id"),
command_id: message_id,
job_type: command_type,
file_path: value.get("file_path").and_then(|v| v.as_str()).map(String::from),
file_uuid: value.get("file_uuid").and_then(|v| v.as_str()).map(String::from),
user_id: value.get("user_id").and_then(|v| v.as_i64()),
payload: value,
status,
priority,
error_count: 0,
last_error,
retry_count,
started_at: processing_started_at,
completed_at: processing_completed_at,
updated_at: None,
created_at,
}
}).collect())
}
pub async fn update_command_status(
@@ -2417,7 +2528,7 @@ SELECT id FROM {} WHERE status = 'pending'
let (status_clause, completed_clause, retry_clause, error_clause, has_error_bind) =
match status {
CommandJobStatus::Running => (
"status = $1, started_at = COALESCE(started_at, CURRENT_TIMESTAMP)",
"status = $1, processing_started_at = COALESCE(processing_started_at, CURRENT_TIMESTAMP)",
"",
"",
"",
@@ -2425,14 +2536,14 @@ SELECT id FROM {} WHERE status = 'pending'
),
CommandJobStatus::Completed => (
"status = $1",
", completed_at = CURRENT_TIMESTAMP",
", processing_completed_at = CURRENT_TIMESTAMP",
"",
", last_error = NULL",
false,
),
CommandJobStatus::Failed => (
"status = $1",
", completed_at = CURRENT_TIMESTAMP",
", processing_completed_at = CURRENT_TIMESTAMP",
", retry_count = retry_count + 1",
if error_message.is_some() {
", last_error = $3"
@@ -2445,7 +2556,7 @@ SELECT id FROM {} WHERE status = 'pending'
};
let sql = format!(
"UPDATE {} SET {}{}{}{}, updated_at = CURRENT_TIMESTAMP WHERE command_id = $2",
"UPDATE {} SET {}{}{}{} WHERE message_id = $2",
table, status_clause, completed_clause, retry_clause, error_clause
);
let mut query = sqlx::query(&sql).bind(status.as_str()).bind(command_id);
@@ -2462,8 +2573,8 @@ SELECT id FROM {} WHERE status = 'pending'
let row = sqlx::query(
&format!(
r#"
SELECT id, command_id, job_type, file_path, file_uuid, user_id, payload, status, priority, error_count, last_error, retry_count, started_at::TEXT, completed_at::TEXT, updated_at::TEXT, created_at::TEXT
FROM {} WHERE command_id = $1
SELECT id, message_id, command_type, key, value, status, priority, retry_count, last_error, created_at::TEXT, processing_started_at::TEXT, processing_completed_at::TEXT
FROM {} WHERE message_id = $1
"#,
table
)
@@ -2472,7 +2583,38 @@ SELECT id FROM {} WHERE status = 'pending'
.fetch_optional(&self.pool)
.await?;
Ok(row.map(parse_command_job))
Ok(row.map(|row| {
let message_id: String = row.get("message_id");
let command_type: String = row.get("command_type");
let value: serde_json::Value = row.get("value");
let status_str: String = row.get("status");
let status = CommandJobStatus::from_db_str(&status_str).unwrap_or(CommandJobStatus::Pending);
let priority: i32 = row.get::<i16, _>("priority") as i32;
let retry_count: i32 = row.get("retry_count");
let last_error: Option<String> = row.get("last_error");
let created_at: String = row.get("created_at");
let processing_started_at: Option<String> = row.get("processing_started_at");
let processing_completed_at: Option<String> = row.get("processing_completed_at");
CommandJob {
id: row.get("id"),
command_id: message_id,
job_type: command_type,
file_path: value.get("file_path").and_then(|v| v.as_str()).map(String::from),
file_uuid: value.get("file_uuid").and_then(|v| v.as_str()).map(String::from),
user_id: value.get("user_id").and_then(|v| v.as_i64()),
payload: value,
status,
priority,
error_count: 0,
last_error,
retry_count,
started_at: processing_started_at,
completed_at: processing_completed_at,
updated_at: None,
created_at,
}
}))
}
// ── Token Usage Billing Methods ──
+21 -1
View File
@@ -3,11 +3,31 @@ use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;
use super::{Database, SearchResult, VectorStore};
pub const SCENES_COLLECTION: &str = "_scenes";
/// Build an HTTP client with sensible timeouts to prevent indefinite hangs.
/// All external service calls should use this instead of Client::new().
pub fn new_http_client() -> Client {
Client::builder()
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(10))
.build()
.expect("Failed to create HTTP client")
}
/// Build an HTTP client with custom timeout (for services that need different limits).
pub fn new_http_client_with_timeout(secs: u64) -> Client {
Client::builder()
.timeout(Duration::from_secs(secs))
.connect_timeout(Duration::from_secs(10))
.build()
.expect("Failed to create HTTP client")
}
pub struct QdrantDb {
pub client: Client,
pub base_url: String,
@@ -43,7 +63,7 @@ impl QdrantDb {
);
Self {
client: Client::new(),
client: new_http_client(),
base_url,
api_key,
collection_name,
+641
View File
@@ -0,0 +1,641 @@
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
pub struct InitOptions {
pub skip_db: bool,
pub skip_deps: bool,
pub force: bool,
pub scan_dir: Option<PathBuf>,
pub quiet: bool,
}
impl Default for InitOptions {
fn default() -> Self {
Self {
skip_db: false,
skip_deps: false,
force: false,
scan_dir: None,
quiet: false,
}
}
}
fn log(opts: &InitOptions, msg: &str) {
if !opts.quiet {
println!("{}", msg);
}
}
fn step(opts: &InitOptions, msg: &str) {
if !opts.quiet {
println!(" {}", msg);
}
}
fn warn(opts: &InitOptions, msg: &str) {
if !opts.quiet {
println!(" ⚠️ {}", msg);
}
}
fn ok(opts: &InitOptions, msg: &str) {
if !opts.quiet {
println!(" ✅ {}", msg);
}
}
/// Main init entry point
pub async fn run(opts: InitOptions) -> Result<()> {
log(&opts, "🚀 momentry init v1.0.0");
log(&opts, "");
// Step 1: Resolve install root
let root = resolve_install_root()?;
log(&opts, &format!("📍 安裝根目錄: {}", root.display()));
log(&opts, "");
// Step 2: Fix config/.env
let env_map = fix_env_file(&root, &opts)?;
log(&opts, "");
// Step 3: Create directories
create_directories(&root, &opts)?;
log(&opts, "");
// Step 4: Validate JSON configs
validate_json_configs(&root, &opts)?;
log(&opts, "");
// Step 5: Dependency preflight
if !opts.skip_deps {
check_dependencies(&env_map, &opts).await;
log(&opts, "");
}
// Step 6: Database init
if !opts.skip_db {
init_database(&env_map, &opts).await;
log(&opts, "");
}
// Step 7: Verify scan
verify_scan(&root, &env_map, &opts);
log(&opts, "");
log(&opts, "🎉 初始化完成!");
log(&opts, " 啟動服務: ./scripts/start_all.sh");
Ok(())
}
fn resolve_install_root() -> Result<PathBuf> {
let exe = std::env::current_exe().context("cannot determine exe path")?;
exe.parent()
.and_then(|p| p.parent())
.map(|p| p.to_path_buf())
.context("cannot determine install root (expected <root>/bin/momentry)")
}
// ─── Step 2: .env ───────────────────────────────────────────────
/// Keys that MUST exist with absolute paths
fn required_env_keys(root: &Path) -> Vec<(String, String)> {
let r = root.display().to_string();
vec![
("MOMENTRY_ENV_FILE".into(), format!("{}/config/.env", r)),
("MOMENTRY_SFTP_ROOT".into(), format!("{}/var/sftpgo/data/demo", r)),
("MOMENTRY_STORAGE_ROOT".into(), format!("{}/var/sftpgo/data", r)),
("MOMENTRY_OUTPUT_DIR".into(), format!("{}/var/output", r)),
("MOMENTRY_DATA_DIR".into(), format!("{}/data", r)),
("MOMENTRY_PROCESSORS_DIR".into(), format!("{}/processors", r)),
("MOMENTRY_LOG_LEVEL".into(), "info".into()),
]
}
fn generate_api_key() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let t = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let pid = std::process::id();
let hash = format!("{:x}{}", t, pid);
let padded: String = hash.chars().chain(std::iter::repeat('0')).take(64).collect();
format!("muser_{}", padded)
}
fn fix_env_file(root: &Path, opts: &InitOptions) -> Result<std::collections::HashMap<String, String>> {
log(opts, "📝 config/.env:");
let env_path = root.join("config").join(".env");
let example_path = root.join("config").join(".env.example");
let mut env_map = std::collections::HashMap::new();
let source_path = if env_path.exists() {
env_path.clone()
} else if example_path.exists() {
example_path.clone()
} else {
warn(opts, "無 .env 和 .env.example,將生成最小配置");
PathBuf::new()
};
if !source_path.as_os_str().is_empty() {
let content = std::fs::read_to_string(&source_path)
.context("cannot read env file")?;
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((key, value)) = line.split_once('=') {
env_map.insert(key.trim().to_string(), value.trim().to_string());
}
}
}
if !env_path.exists() {
if example_path.exists() {
std::fs::copy(&example_path, &env_path)
.context("cannot create config/.env")?;
step(opts, "從 .env.example 創建 config/.env");
} else {
std::fs::create_dir_all(root.join("config"))
.context("cannot create config dir")?;
std::fs::write(&env_path, "")
.context("cannot create config/.env")?;
step(opts, "創建空白 config/.env");
}
}
let root_str = root.display().to_string();
let mut changed = false;
for (_k, v) in env_map.iter_mut() {
if v.contains("@ROOT@") {
*v = v.replace("@ROOT@", &root_str);
changed = true;
}
}
let mut added = Vec::new();
for (key, default_val) in required_env_keys(root) {
let needs_set = match env_map.get(&key) {
None => true,
Some(v) => {
v.is_empty()
|| v.contains("@ROOT@")
|| (key == "MOMENTRY_API_KEY" && (v.is_empty() || v.contains("your_key")))
}
};
if needs_set {
let val = if key == "MOMENTRY_API_KEY" && env_map.get(&key).map_or(true, |v| v.is_empty()) {
generate_api_key()
} else {
default_val
};
env_map.insert(key.clone(), val.clone());
added.push(format!("+ {}={}", key, val));
changed = true;
}
}
if env_map.get("FFMPEG_PATH").map_or(true, |v| v.is_empty()) {
if let Some(ffmpeg) = find_ffmpeg() {
env_map.insert("FFMPEG_PATH".into(), ffmpeg.display().to_string());
added.push(format!("+ FFMPEG_PATH={}", ffmpeg.display()));
changed = true;
}
}
if env_map.get("WHISPER_MODEL_PATH").map_or(true, |v| v.is_empty() || !Path::new(v).exists()) {
if let Some(model) = find_whisper_model(root) {
env_map.insert("WHISPER_MODEL_PATH".into(), model.display().to_string());
added.push(format!("+ WHISPER_MODEL_PATH={}", model.display()));
changed = true;
}
}
if changed && !opts.force {
let mut content = std::fs::read_to_string(&env_path).unwrap_or_default();
for line in &added {
let kv = line.trim_start_matches("+ ");
if !content.contains(&format!("\n{}", kv)) && !content.contains(&format!("^{}", kv)) {
if !content.ends_with('\n') {
content.push('\n');
}
content.push_str(kv);
content.push('\n');
}
}
let content = content.replace("@ROOT@", &root_str);
std::fs::write(&env_path, content).context("cannot write config/.env")?;
} else if changed && opts.force {
let mut content = String::new();
content.push_str("# Generated by momentry init\n");
let mut keys: Vec<_> = env_map.iter().collect();
keys.sort_by(|a, b| a.0.cmp(b.0));
for (k, v) in keys {
content.push_str(&format!("{}={}\n", k, v));
}
std::fs::write(&env_path, content).context("cannot write config/.env")?;
}
if added.is_empty() {
ok(opts, "config/.env 完整(無需修改)");
} else {
for line in &added {
step(opts, line);
}
}
Ok(env_map)
}
fn find_ffmpeg() -> Option<PathBuf> {
let candidates = [
"/opt/homebrew/bin/ffmpeg",
"/usr/local/bin/ffmpeg",
"/usr/bin/ffmpeg",
];
candidates.iter().map(PathBuf::from).find(|p| p.exists())
}
fn find_whisper_model(root: &Path) -> Option<PathBuf> {
let candidates = [
root.join("tools/models/small.pt"),
root.join("tools/models/whisper-small-mlx/small.pt"),
root.join("tools/models/base.pt"),
];
candidates.into_iter().find(|p| p.exists())
}
// ─── Step 3: Directories ────────────────────────────────────────
fn create_directories(root: &Path, opts: &InitOptions) -> Result<()> {
log(opts, "📁 建立目錄:");
let dirs = [
("var/sftpgo/data/demo", "掃描根 (files/scan)"),
("var/sftpgo/data", "存儲根"),
("var/output", "處理輸出"),
("var/backup", "備份"),
("logs", "日誌"),
("thumbnails", "縮圖"),
("data", "數據"),
];
for (dir, desc) in &dirs {
let path = root.join(dir);
if !path.exists() {
std::fs::create_dir_all(&path)
.with_context(|| format!("cannot create {}", path.display()))?;
step(opts, &format!("{} ({})", dir, desc));
} else {
ok(opts, &format!("{} (已存在)", dir));
}
}
Ok(())
}
// ─── Step 4: JSON configs ───────────────────────────────────────
fn validate_json_configs(root: &Path, opts: &InitOptions) -> Result<()> {
log(opts, "⚙️ 配置文件:");
let admin_path = root.join("config").join("admin_config.json");
if admin_path.exists() {
let content = std::fs::read_to_string(&admin_path)
.context("cannot read admin_config.json")?;
match serde_json::from_str::<serde_json::Value>(&content) {
Ok(_) => {
let is_stub = content.len() < 200;
if is_stub {
warn(opts, "admin_config.json 是最小 stub,建議替換完整配置");
} else {
ok(opts, "config/admin_config.json");
}
}
Err(e) => {
warn(opts, &format!("admin_config.json JSON 解析失敗: {}", e));
}
}
} else {
let default_config = serde_json::json!({
"filter_config": {
"face": { "min_confidence": 0.5, "min_size": 30 }
},
"llm_config": {
"chat": {
"model": "gemma-4-12b-it",
"timeout": 30,
"url": "http://localhost:8080/v1/chat/completions"
},
"summary": {
"model": "gemma-4-12b-it",
"timeout": 60,
"url": "http://localhost:8080/v1/chat/completions"
}
},
"processor_config": {}
});
std::fs::write(&admin_path, serde_json::to_string_pretty(&default_config)?)
.context("cannot write admin_config.json")?;
step(opts, "config/admin_config.json (生成默認配置)");
}
let tools_path = root.join("config").join("processor_tools_v3.json");
if tools_path.exists() {
ok(opts, "config/processor_tools_v3.json");
} else {
warn(opts, "config/processor_tools_v3.json 不存在 — 請從安裝包複製");
}
Ok(())
}
// ─── Step 5: Dependencies ───────────────────────────────────────
async fn check_dependencies(env: &std::collections::HashMap<String, String>, opts: &InitOptions) {
log(opts, "🔍 服務預檢:");
let db_url = env.get("DATABASE_URL").cloned()
.unwrap_or_else(|| "postgres://localhost:5432/momentry".into());
match check_tcp(&db_url).await {
Ok(_) => ok(opts, "PostgreSQL"),
Err(e) => warn(opts, &format!("PostgreSQL: {}", e)),
}
let redis_url = env.get("REDIS_URL").cloned()
.unwrap_or_else(|| "redis://localhost:6379".into());
match check_redis(&redis_url).await {
Ok(_) => ok(opts, "Redis"),
Err(e) => warn(opts, &format!("Redis: {}", e)),
}
let qdrant_url = env.get("QDRANT_URL").cloned()
.unwrap_or_else(|| "http://localhost:6333".into());
match check_http(&qdrant_url).await {
Ok(_) => ok(opts, "Qdrant"),
Err(e) => warn(opts, &format!("Qdrant: {}", e)),
}
let ffmpeg = env.get("FFMPEG_PATH").cloned()
.unwrap_or_else(|| "/opt/homebrew/bin".into());
let ffmpeg_bin = Path::new(&ffmpeg).join("ffmpeg");
if ffmpeg_bin.exists() || which_exists("ffmpeg") {
ok(opts, "FFmpeg");
} else {
warn(opts, "FFmpeg not found");
}
if let Some(model) = env.get("WHISPER_MODEL_PATH") {
if Path::new(model).exists() {
let size = std::fs::metadata(model).map(|m| m.len()).unwrap_or(0);
if size > 100_000_000 {
ok(opts, &format!("Whisper model ({}MB)", size / 1_000_000));
} else {
warn(opts, &format!("Whisper model too small ({} bytes)", size));
}
} else {
warn(opts, &format!("Whisper model not found: {}", model));
}
}
}
async fn check_tcp(url: &str) -> Result<()> {
let addr = url
.trim_start_matches("postgres://")
.trim_start_matches("postgresql://")
.split('/')
.next()
.unwrap_or("localhost:5432");
let addr = if addr.contains(':') {
addr.to_string()
} else {
format!("{}:5432", addr)
};
tokio::net::TcpStream::connect(&addr)
.await
.with_context(|| format!("cannot connect to {}", addr))?;
Ok(())
}
async fn check_redis(url: &str) -> Result<()> {
let addr = url
.trim_start_matches("redis://")
.split('@')
.last()
.unwrap_or("localhost:6379");
let addr = if addr.contains(':') {
addr.to_string()
} else {
format!("{}:6379", addr)
};
let mut stream = tokio::net::TcpStream::connect(&addr)
.await
.with_context(|| format!("cannot connect to {}", addr))?;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
stream.write_all(b"PING\r\n").await?;
let mut buf = [0u8; 16];
let n = stream.read(&mut buf).await?;
let resp = String::from_utf8_lossy(&buf[..n]);
if resp.contains("PONG") {
Ok(())
} else {
anyhow::bail!("unexpected response: {}", resp)
}
}
async fn check_http(url: &str) -> Result<()> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(5))
.build()?;
let resp = client.get(format!("{}/collections", url)).send().await?;
if resp.status().is_success() {
Ok(())
} else {
anyhow::bail!("HTTP {}", resp.status())
}
}
fn which_exists(cmd: &str) -> bool {
std::process::Command::new("which")
.arg(cmd)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
// ─── Step 6: Database ───────────────────────────────────────────
async fn init_database(env: &std::collections::HashMap<String, String>, opts: &InitOptions) {
log(opts, "🗄️ 數據庫:");
let db_url = match env.get("DATABASE_URL") {
Some(u) => u.clone(),
None => {
warn(opts, "DATABASE_URL 未設定,跳過");
return;
}
};
match try_init_db(&db_url, opts).await {
Ok(msg) => ok(opts, &msg),
Err(e) => {
warn(opts, &format!("DB 初始化失敗: {}", e));
step(opts, "可手動執行: psql -d momentry -f release/migrate_*.sql");
}
}
}
async fn try_init_db(db_url: &str, _opts: &InitOptions) -> Result<String> {
let db_name = db_url
.rsplit('/')
.next()
.unwrap_or("momentry")
.split('?')
.next()
.unwrap_or("momentry");
let output = std::process::Command::new("psql")
.args(["-d", db_name, "-c", "SELECT 1"])
.output()
.context("psql not found in PATH")?;
if !output.status.success() {
let user_output = std::process::Command::new("psql")
.args(["-d", "postgres", "-c", &format!("CREATE DATABASE {}", db_name)])
.output();
match user_output {
Ok(o) if o.status.success() => {
let retry = std::process::Command::new("psql")
.args(["-d", db_name, "-c", "SELECT 1"])
.output()?;
if !retry.status.success() {
anyhow::bail!("cannot connect to database {}", db_name);
}
}
_ => anyhow::bail!("cannot connect to database {}", db_name),
}
}
let _ = std::process::Command::new("psql")
.args(["-d", db_name, "-c", "CREATE SCHEMA IF NOT EXISTS public"])
.output();
let _ = std::process::Command::new("psql")
.args(["-d", db_name, "-c",
"CREATE TABLE IF NOT EXISTS schema_migrations (filename TEXT PRIMARY KEY, checksum TEXT, duration_ms INT, applied_at TIMESTAMPTZ DEFAULT now())"])
.output();
let exe = std::env::current_exe()?;
let install_root = exe.parent().and_then(|p| p.parent())
.context("cannot find install root")?;
let release_dir = install_root.join("release");
let mut applied = 0;
let mut skipped = 0;
if release_dir.exists() {
let mut migrations: Vec<_> = std::fs::read_dir(&release_dir)?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.extension().map_or(false, |ext| ext == "sql"))
.filter(|p| {
p.file_name()
.map_or(false, |n| n.to_string_lossy().starts_with("migrate_"))
})
.collect();
migrations.sort();
for mig_path in migrations {
let mig_name = mig_path.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let check = std::process::Command::new("psql")
.args(["-d", db_name, "-t", "-c",
&format!("SELECT COUNT(*) FROM schema_migrations WHERE filename='{}'", mig_name)])
.output();
let already = check.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().parse::<i64>().unwrap_or(0))
.unwrap_or(0) > 0;
if already {
skipped += 1;
continue;
}
let sql = std::fs::read_to_string(&mig_path)?;
let start = std::time::Instant::now();
let result = std::process::Command::new("psql")
.args(["-d", db_name, "-f", &mig_path.display().to_string()])
.output();
let duration = start.elapsed().as_millis() as i32;
match result {
Ok(o) if o.status.success() => {
let _ = std::process::Command::new("psql")
.args(["-d", db_name, "-c",
&format!("INSERT INTO schema_migrations (filename, duration_ms) VALUES ('{}', {}) ON CONFLICT (filename) DO UPDATE SET duration_ms=EXCLUDED.duration_ms", mig_name, duration)])
.output();
applied += 1;
}
Ok(o) => {
let stderr = String::from_utf8_lossy(&o.stderr);
let _ = stderr;
}
Err(_) => {}
}
}
}
Ok(format!("Schema public, migrations: {} applied, {} skipped", applied, skipped))
}
// ─── Step 7: Verify scan ────────────────────────────────────────
fn verify_scan(root: &Path, env: &std::collections::HashMap<String, String>, opts: &InitOptions) {
log(opts, "✅ 驗證:");
let scan_dir = env.get("MOMENTRY_SFTP_ROOT")
.map(PathBuf::from)
.unwrap_or_else(|| root.join("var/sftpgo/data/demo"));
if scan_dir.exists() {
let count = count_media_files(&scan_dir);
ok(opts, &format!("掃描根: {} ({} files)", scan_dir.display(), count));
if count > 0 {
ok(opts, "files/scan 可用");
} else {
warn(opts, "掃描目錄為空(上傳文件後 files/scan 將返回結果)");
}
} else {
warn(opts, &format!("掃描根不存在: {}", scan_dir.display()));
}
if let Some(api_key) = env.get("MOMENTRY_API_KEY") {
if !api_key.is_empty() {
log(opts, "");
log(opts, " 驗證命令:");
log(opts, &format!(
" curl -H \"X-API-Key: {}\" http://localhost:3002/api/v1/files/scan?page_size=5",
api_key
));
}
}
}
fn count_media_files(dir: &Path) -> usize {
const EXTS: &[&str] = &["mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp"];
let mut count = 0;
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
if entry.path().is_dir() {
count += count_media_files(&entry.path());
} else if let Some(ext) = entry.path().extension() {
if EXTS.contains(&ext.to_string_lossy().to_lowercase().as_str()) {
count += 1;
}
}
}
}
count
}
+4
View File
@@ -6,6 +6,7 @@ pub mod billing;
pub mod cache;
pub mod checkin;
pub mod chunk;
pub mod command;
pub mod config;
pub mod db;
pub mod embedding;
@@ -15,6 +16,7 @@ pub mod file_profile;
pub mod frame_cache;
pub mod health_agent;
pub mod identity;
pub mod init;
pub mod ingestion;
pub mod llm;
pub mod overlay;
@@ -25,6 +27,7 @@ pub mod probe;
pub mod processor;
pub mod progress;
pub mod proxy;
// pub mod replay; // TODO: Fix type mismatch errors
pub mod storage;
pub mod text;
pub mod thumbnail;
@@ -32,3 +35,4 @@ pub mod time;
pub mod tkg;
pub mod tmdb;
pub mod vision;
pub mod vlm;
+1 -1
View File
@@ -40,4 +40,4 @@ pub fn config_dir() -> PathBuf {
/// Get models directory.
pub fn models_dir() -> PathBuf {
resolve_asset_path("MOMENTRY_MODELS_DIR", "models")
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ pub struct FormatInfo {
pub fn probe_video(video_path: &str) -> Result<ProbeResult> {
// Use FFPROBE_PATH environment variable, fallback to "ffprobe"
let ffprobe_path = std::env::var("FFPROBE_PATH").unwrap_or_else(|_| "ffprobe".to_string());
let output = Command::new(&ffprobe_path)
.args([
"-v",
+61 -40
View File
@@ -66,74 +66,86 @@ pub async fn process_asr(
tracing::info!("[ASR] Starting ASR processing: {}", video_path);
let whisper_cli = std::path::Path::new("/opt/homebrew/bin/whisper");
if whisper_cli.exists() {
tracing::info!("[ASR] Using whisper CLI: {:?}", whisper_cli);
let output_dir = std::path::Path::new(output_path)
.parent()
.context("Invalid output path")?;
// Resolve whisper model directory
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let whisper_model_dir = models_dir.join("whisper-small-mlx");
let output = tokio::process::Command::new(whisper_cli)
.args(&[
video_path,
"--model", "small",
"--model_dir", whisper_model_dir.to_str().unwrap(),
"--output_dir", output_dir.to_str().unwrap(),
"--output_format", "json",
"--verbose", "False",
"--model",
"small",
"--model_dir",
whisper_model_dir.to_str().unwrap(),
"--output_dir",
output_dir.to_str().unwrap(),
"--output_format",
"json",
"--verbose",
"False",
])
.output()
.await
.context("Failed to execute whisper CLI")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[ASR] Whisper CLI failed: {}", stderr);
tracing::warn!("[ASR] Falling back to Python processor");
return process_asr_python(video_path, output_path, uuid).await;
}
let json_path = output_dir.join(
std::path::Path::new(video_path)
.file_stem()
.unwrap()
.to_str()
.unwrap()
).with_extension("json");
let json_path = output_dir
.join(
std::path::Path::new(video_path)
.file_stem()
.unwrap()
.to_str()
.unwrap(),
)
.with_extension("json");
if !json_path.exists() {
tracing::warn!("[ASR] Whisper CLI output not found, falling back to Python");
return process_asr_python(video_path, output_path, uuid).await;
}
let json_str = std::fs::read_to_string(&json_path)
.context("Failed to read whisper output")?;
let whisper_result: WhisperJsonOutput = serde_json::from_str(&json_str)
.context("Failed to parse whisper output")?;
let json_str =
std::fs::read_to_string(&json_path).context("Failed to read whisper output")?;
let whisper_result: WhisperJsonOutput =
serde_json::from_str(&json_str).context("Failed to parse whisper output")?;
std::fs::copy(&json_path, output_path)
.context("Failed to copy whisper output to target path")?;
let mut result = convert_whisper_to_asr(whisper_result);
result.compute_status();
tracing::info!(
"[ASR] Whisper result: status={}, {} segments, language: {:?}",
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.segment_count,
result.language
);
return Ok(result);
}
tracing::warn!("[ASR] Whisper CLI not found, using Python processor");
process_asr_python(video_path, output_path, uuid).await
}
@@ -166,7 +178,11 @@ async fn process_asr_python(
tracing::info!(
"[ASR] Python result: status={}, {} segments, language: {:?}",
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.segment_count,
result.language
);
@@ -190,17 +206,22 @@ struct WhisperSegment {
}
fn convert_whisper_to_asr(whisper: WhisperJsonOutput) -> AsrResult {
let segments: Vec<AsrSegment> = whisper.segments.into_iter().map(|s| {
AsrSegment {
let segments: Vec<AsrSegment> = whisper
.segments
.into_iter()
.map(|s| AsrSegment {
start_time: s.start,
end_time: s.end,
start_frame: None,
end_frame: None,
text: s.text.trim().to_string(),
confidence: s.avg_logprob.map(|p| (p.exp() * 100.0).min(100.0)).unwrap_or(0.0),
}
}).collect();
confidence: s
.avg_logprob
.map(|p| (p.exp() * 100.0).min(100.0))
.unwrap_or(0.0),
})
.collect();
AsrResult {
status: None,
language: whisper.language,
+1 -1
View File
@@ -70,7 +70,7 @@ pub async fn process_asrx(
uuid: Option<&str>,
) -> Result<AsrxResult> {
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
// Use Python processor (Swift ASRX disabled - requires GUI authorization)
tracing::info!("[ASRX] Using Python processor");
process_asrx_python(video_path, output_path, uuid).await
+18 -12
View File
@@ -1203,7 +1203,7 @@ impl PythonExecutor {
/// back to `target/debug/` (mirrors the swift_processors layout convention).
pub fn rust_binary_path(&self, bin_name: &str) -> Option<PathBuf> {
let cli_dir = crate::core::path_utils::cli_dir();
let base = PathBuf::from(cli_dir).join("rust").join("target");
for profile in ["release", "debug"] {
let p = base.join(profile).join(bin_name);
@@ -1417,29 +1417,35 @@ pub struct CliExecutor {
impl CliExecutor {
pub fn new() -> Result<Self> {
let cli_dir = crate::core::path_utils::cli_dir();
let cli_path = PathBuf::from(&cli_dir);
if !cli_path.exists() {
anyhow::bail!(
"CLI directory not found at {:?} (set MOMENTRY_CLI_DIR env var)",
cli_dir
);
}
Ok(Self {
cli_dir: cli_path,
})
Ok(Self { cli_dir: cli_path })
}
pub fn swift_cli_path(&self, name: &str) -> PathBuf {
self.cli_dir.join("swift").join(".build").join("release").join(name)
self.cli_dir
.join("swift")
.join(".build")
.join("release")
.join(name)
}
pub fn rust_cli_path(&self, name: &str) -> PathBuf {
self.cli_dir.join("rust").join("target").join("release").join(name)
self.cli_dir
.join("rust")
.join("target")
.join("release")
.join(name)
}
pub fn cli_dir(&self) -> &PathBuf {
&self.cli_dir
}
+148 -108
View File
@@ -11,7 +11,7 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
use std::path::PathBuf;
let rel = format!(".build/release/{}", bin);
let rel = rel.as_str();
// Priority: env override -> current_exe sibling -> dev fallback
if let Ok(dir) = std::env::var("MOMENTRY_SWIFT_PROCESSORS_DIR") {
let p = PathBuf::from(dir).join(rel);
@@ -19,7 +19,7 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
return p;
}
}
// Try sibling of current_exe
if let Ok(exe) = std::env::current_exe() {
if let Some(parent) = exe.parent() {
@@ -29,14 +29,13 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
}
}
}
// Dev fallback
crate::core::path_utils::scripts_dir()
.join("swift_processors")
.join(rel)
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FaceResult {
#[serde(default)]
@@ -63,12 +62,10 @@ impl FaceResult {
self.status = Some(FaceStatus::from_face_count(self.total_faces));
}
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
let json = serde_json::to_string_pretty(self)
.context("Failed to serialize FaceResult")?;
std::fs::write(path, json)
.context("Failed to write face.json")?;
let json = serde_json::to_string_pretty(self).context("Failed to serialize FaceResult")?;
std::fs::write(path, json).context("Failed to write face.json")?;
Ok(())
}
@@ -103,11 +100,13 @@ pub struct Face {
#[serde(default)]
pub height: i32,
pub confidence: f32,
#[serde(default)]
#[serde(default, rename = "captureQuality", alias = "capture_quality")]
pub capture_quality: Option<f32>,
pub embedding: Option<Vec<f32>>,
pub landmarks: Option<serde_json::Value>,
pub pose_angle: Option<serde_json::Value>,
#[serde(default)]
pub lips: Option<serde_json::Value>,
pub attributes: Option<FaceAttributes>,
#[serde(default)]
pub bbox: Option<BoundingBox>,
@@ -179,60 +178,61 @@ pub async fn process_face(
return Ok(result);
}
let executor = PythonExecutor::new()?;
let executor = PythonExecutor::new()?;
// Try config-driven tool selection first
if let Ok(Some(result)) = run_face_with_config(&executor, video_path, output_path, uuid).await {
tracing::info!(
"[FACE] Config-driven processing completed: {} faces",
result.total_faces
);
return Ok(result);
}
// Try config-driven tool selection first
if let Ok(Some(result)) = run_face_with_config(&executor, video_path, output_path, uuid).await {
tracing::info!(
"[FACE] Config-driven processing completed: {} faces",
result.total_faces
);
return Ok(result);
}
tracing::info!("[FACE] Config-driven selection failed, falling back to hard-coded logic");
tracing::info!("[FACE] Config-driven selection failed, falling back to hard-coded logic");
// Fallback to hard-coded logic
// Check for Swift face processor first
let swift_face_path = swift_processor_path("swift_face");
// Fallback to hard-coded logic
// Check for Swift face processor first
let swift_face_path = swift_processor_path("swift_face");
if swift_face_path.exists() {
tracing::info!("[FACE] Using Swift processor: {:?}", swift_face_path);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
let output = tokio::process::Command::new(swift_face_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_face")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[FACE] Swift processor failed: {}", stderr);
anyhow::bail!("Swift face processor failed");
}
// Generate embeddings with FaceNet CoreML
let facenet_path = swift_processor_path("facenet_embedding");
if facenet_path.exists() {
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
// Resolve model path
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let model_path = models_dir.join("facenet512.mlpackage");
if !model_path.exists() {
tracing::error!("[FACE] FaceNet model not found at {:?}", model_path);
tracing::error!("[FACE] Set MOMENTRY_MODELS_DIR environment variable or ensure models/facenet512.mlpackage exists");
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
}
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
video_path.to_string(),
@@ -241,12 +241,12 @@ let swift_face_path = swift_processor_path("swift_face");
"--model".to_string(),
model_path.to_string_lossy().to_string(),
];
let facenet_result = tokio::process::Command::new(facenet_path)
.args(&facenet_args)
.output()
.await;
match facenet_result {
Ok(output) if output.status.success() => {
// Replace original file with embedding-enhanced version
@@ -258,7 +258,10 @@ let swift_face_path = swift_processor_path("swift_face");
tracing::info!("[FACE] Embeddings generated successfully");
}
} else {
tracing::error!("[FACE] FaceNet output file not created: {}", facenet_output);
tracing::error!(
"[FACE] FaceNet output file not created: {}",
facenet_output
);
anyhow::bail!("FaceNet output file not created");
}
}
@@ -273,14 +276,19 @@ let swift_face_path = swift_processor_path("swift_face");
}
}
} else {
tracing::warn!("[FACE] FaceNet binary not found at {:?}, skipping embedding generation", facenet_path);
tracing::warn!(
"[FACE] FaceNet binary not found at {:?}, skipping embedding generation",
facenet_path
);
}
// Read the JSON (with embeddings from FaceNet)
let json_str = std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
let mut result: FaceResult = serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
let json_str =
std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
let mut result: FaceResult =
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
result.compute_status();
// Store embeddings to Qdrant and remove from JSON
if let Some(file_uuid) = uuid {
tracing::info!("[FACE] Storing embeddings to Qdrant for {}", file_uuid);
@@ -295,7 +303,7 @@ let swift_face_path = swift_processor_path("swift_face");
} else {
tracing::warn!("[FACE] No UUID provided, skipping Qdrant storage");
}
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
@@ -304,19 +312,23 @@ let swift_face_path = swift_processor_path("swift_face");
} else {
tracing::info!("[FACE] Face tracking completed successfully");
}
result.save_to_file(output_path)?;
tracing::info!(
"[FACE] Swift result: status={}, {} frames, {} total faces",
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
result
.status
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
result.frames.len(),
result.total_faces
);
return Ok(result);
}
// Fallback to Python processor
let script_path = executor.script_path("face_processor.py");
@@ -344,18 +356,18 @@ let swift_face_path = swift_processor_path("swift_face");
let mut result: FaceResult =
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
result.compute_status();
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
tracing::warn!("[FACE] Face tracking failed: {}", e);
} else {
tracing::info!("[FACE] Face tracking completed successfully");
}
result.save_to_file(output_path)?;
result.compute_status();
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
tracing::warn!("[FACE] Face tracking failed: {}", e);
} else {
tracing::info!("[FACE] Face tracking completed successfully");
}
result.save_to_file(output_path)?;
tracing::info!(
"[FACE] Result: status={}, {} frames, {} total faces",
@@ -378,21 +390,24 @@ async fn run_face_with_config(
uuid: Option<&str>,
) -> Result<Option<FaceResult>> {
use super::tool_selector::ToolSelector;
let selector = ToolSelector::new("face");
if let Some(tool) = selector.select_tool(executor).await? {
tracing::info!(
"[FACE] Using tool from config: {} (priority {})",
tool.name,
tool.parameters.get("priority").and_then(|v| v.as_u64()).unwrap_or(99)
tool.parameters
.get("priority")
.and_then(|v| v.as_u64())
.unwrap_or(99)
);
match tool.name.as_str() {
"swift" => {
let swift_path = &tool.path;
tracing::info!("[FACE] Using Swift processor from config: {:?}", swift_path);
let args = if !tool.args.is_empty() {
tracing::info!("[FACE] Using args from config: {:?}", tool.args);
tool.args
@@ -411,37 +426,37 @@ async fn run_face_with_config(
}
args
};
let output = tokio::process::Command::new(swift_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_face")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[FACE] Swift processor failed: {}", stderr);
anyhow::bail!("Swift face processor failed");
}
// Generate embeddings with FaceNet CoreML
let facenet_path = swift_processor_path("facenet_embedding");
if facenet_path.exists() {
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
video_path.to_string(),
output_path.to_string(),
facenet_output.clone(),
];
let facenet_result = tokio::process::Command::new(facenet_path)
.args(&facenet_args)
.output()
.await;
match facenet_result {
Ok(output) if output.status.success() => {
if std::path::Path::new(&facenet_output).exists() {
@@ -451,56 +466,71 @@ async fn run_face_with_config(
}
}
_ => {
tracing::warn!("[FACE] FaceNet embedding generation failed, using detections only");
tracing::warn!(
"[FACE] FaceNet embedding generation failed, using detections only"
);
}
}
}
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read Swift FACE output")?;
let mut result: FaceResult = serde_json::from_str(&json_str)
.context("Failed to parse Swift FACE output")?;
let mut result: FaceResult =
serde_json::from_str(&json_str).context("Failed to parse Swift FACE output")?;
result.compute_status();
result.save_to_file(output_path)?;
if let Some(uid) = uuid {
match store_face_embeddings_to_qdrant(uid, &mut result, output_path).await {
Ok(count) => tracing::info!("[FACE] Stored {} embeddings to Qdrant", count),
Err(e) => tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e),
Err(e) => {
tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e)
}
}
}
return Ok(Some(result));
}
"python" => {
let script_path = &tool.path;
tracing::info!("[FACE] Using Python processor from config: {:?}", script_path);
tracing::info!(
"[FACE] Using Python processor from config: {:?}",
script_path
);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
executor
.run("face_processor.py", &[video_path, output_path], uuid, "FACE", None)
.run(
"face_processor.py",
&[video_path, output_path],
uuid,
"FACE",
None,
)
.await
.context("Failed to run face_processor.py")?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read Python FACE output")?;
let mut result: FaceResult = serde_json::from_str(&json_str)
.context("Failed to parse Python FACE output")?;
result.compute_status();
result.save_to_file(output_path)?;
if let Some(uid) = uuid {
match store_face_embeddings_to_qdrant(uid, &mut result, output_path).await {
Ok(count) => tracing::info!("[FACE] Stored {} embeddings to Qdrant", count),
Err(e) => tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e),
Err(e) => {
tracing::warn!("[FACE] Failed to store embeddings to Qdrant: {}", e)
}
}
}
return Ok(Some(result));
}
_ => {
@@ -508,7 +538,7 @@ async fn run_face_with_config(
}
}
}
Ok(None)
}
@@ -538,6 +568,7 @@ mod tests {
embedding: Some(vec![0.1, 0.2, 0.3]),
landmarks: Some(serde_json::json!([[10.0, 20.0], [30.0, 40.0]])),
pose_angle: None,
lips: None,
attributes: Some(FaceAttributes {
age: Some(30),
gender: Some("male".to_string()),
@@ -640,6 +671,7 @@ mod tests {
embedding: None,
landmarks: None,
pose_angle: None,
lips: None,
attributes: None,
bbox: None,
pose: None,
@@ -661,6 +693,7 @@ mod tests {
embedding: Some(vec![0.1; 512]),
landmarks: None,
pose_angle: None,
lips: None,
attributes: Some(FaceAttributes {
age: Some(35),
gender: Some("male".to_string()),
@@ -687,24 +720,26 @@ pub async fn store_face_embeddings_to_qdrant(
use uuid::Uuid;
let qdrant = QdrantDb::new();
let mut points: Vec<(u64, Vec<f32>, serde_json::Value)> = Vec::new();
let fps = face_result.fps;
// Prepare points with embeddings
for frame in &face_result.frames {
let frame_num = frame.frame;
let timestamp_secs = frame_num as f64 / fps;
for (idx, face) in frame.faces.iter().enumerate() {
if let Some(embedding) = &face.embedding {
let point_id = Uuid::new_v4().as_u128() as u64;
// Generate face_id if not present (format: face_{frame}_{idx})
let face_id = face.face_id.as_deref()
let face_id = face
.face_id
.as_deref()
.map(|s| s.to_string())
.unwrap_or_else(|| format!("face_{}_{}", frame_num, idx));
let payload = serde_json::json!({
"file_uuid": file_uuid,
"frame": frame_num,
@@ -715,20 +750,21 @@ pub async fn store_face_embeddings_to_qdrant(
"y": face.y,
"width": face.width,
"height": face.height,
"capture_quality": face.capture_quality.unwrap_or(0.0),
"trace_id": -1i32, // Will be updated by face tracing
});
points.push((point_id, embedding.clone(), payload));
}
}
}
let total_points = points.len();
if total_points == 0 {
tracing::info!("[FACE] No embeddings to store for {}", file_uuid);
return Ok(0);
}
// Delete old points for this file
let filter = serde_json::json!({
"must": [{
@@ -736,13 +772,13 @@ pub async fn store_face_embeddings_to_qdrant(
"match": {"value": file_uuid}
}]
});
if let Err(e) = qdrant.delete_points_by_filter("_faces", filter).await {
tracing::warn!("[FACE] Failed to delete old points: {}", e);
} else {
tracing::info!("[FACE] Deleted old points for {}", file_uuid);
}
// Upsert new points in batches
let batch_size = 100;
for (i, chunk) in points.chunks(batch_size).enumerate() {
@@ -750,27 +786,31 @@ pub async fn store_face_embeddings_to_qdrant(
.iter()
.map(|(id, vec, payload)| (*id, vec.as_slice(), Some(payload.clone())))
.collect();
qdrant.upsert_vectors_batch("_faces", &batch_points).await
qdrant
.upsert_vectors_batch("_faces", &batch_points)
.await
.with_context(|| format!("Failed to upsert batch {}", i + 1))?;
}
tracing::info!("[FACE] Stored {} embeddings to Qdrant", total_points);
// Remove embeddings from in-memory result
for frame in &mut face_result.frames {
for face in &mut frame.faces {
face.embedding = None;
}
}
// Save cleaned JSON back
let json_str = serde_json::to_string_pretty(&face_result)
.context("Failed to serialize cleaned face result")?;
std::fs::write(output_path, &json_str)
.context("Failed to write cleaned face.json")?;
tracing::info!("[FACE] Removed embeddings from JSON, saved to {}", output_path);
std::fs::write(output_path, &json_str).context("Failed to write cleaned face.json")?;
tracing::info!(
"[FACE] Removed embeddings from JSON, saved to {}",
output_path
);
Ok(total_points)
}
+2 -1
View File
@@ -90,7 +90,8 @@ pub async fn process_face_cluster(
];
tracing::info!(
"[FACE_CLUSTER] Using threshold: similarity={:.2}, distance={:.4}",
threshold, distance
threshold,
distance
);
// Try Rust binary first (preferred), fallback to Python if unavailable
+62 -55
View File
@@ -96,7 +96,8 @@ fn calculate_embedding_similarity(emb1: &[f32], emb2: &[f32]) -> f64 {
return 0.0;
}
let dot: f64 = emb1.iter()
let dot: f64 = emb1
.iter()
.zip(emb2.iter())
.map(|(a, b)| (*a as f64) * (*b as f64))
.sum();
@@ -126,7 +127,7 @@ fn match_faces(
curr_frame: Option<u64>,
) -> Vec<i32> {
let mut trace_ids = vec![-1i32; current_faces.len()];
if previous_faces.is_empty() {
return trace_ids;
}
@@ -151,10 +152,10 @@ fn match_faces(
width: curr_face.width,
height: curr_face.height,
};
let mut best_prev_idx = -1i32;
let mut best_iou = 0.0;
for (prev_idx, prev_face) in previous_faces.iter().enumerate() {
if used_prev.contains(&prev_idx) {
continue;
@@ -165,14 +166,14 @@ fn match_faces(
width: prev_face.width,
height: prev_face.height,
};
let iou = calculate_bbox_iou(&curr_bbox, &prev_bbox);
if iou > best_iou {
best_iou = iou;
best_prev_idx = prev_idx as i32;
}
}
if best_prev_idx >= 0 && best_iou > 0.5 {
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
used_prev.insert(best_prev_idx as usize);
@@ -185,7 +186,7 @@ fn match_faces(
// Normal matching
let mut used_prev = HashSet::new();
for (curr_idx, curr_face) in current_faces.iter().enumerate() {
let curr_bbox = BoundingBox {
x: curr_face.x,
@@ -193,27 +194,29 @@ fn match_faces(
width: curr_face.width,
height: curr_face.height,
};
let mut best_prev_idx = -1i32;
let mut best_score = 0.0;
for (prev_idx, prev_face) in previous_faces.iter().enumerate() {
if used_prev.contains(&prev_idx) {
continue;
}
let prev_bbox = BoundingBox {
x: prev_face.x,
y: prev_face.y,
width: prev_face.width,
height: prev_face.height,
};
let iou = calculate_bbox_iou(&curr_bbox, &prev_bbox);
let distance = calculate_bbox_distance(&curr_bbox, &prev_bbox);
let similarity = if use_embedding {
if let (Some(curr_emb), Some(prev_emb)) = (&curr_face.embedding, &prev_face.embedding) {
if let (Some(curr_emb), Some(prev_emb)) =
(&curr_face.embedding, &prev_face.embedding)
{
calculate_embedding_similarity(curr_emb, prev_emb)
} else {
0.0
@@ -221,38 +224,38 @@ fn match_faces(
} else {
0.0
};
// Bbox size consistency check
let prev_area = (prev_bbox.width * prev_bbox.height) as f64;
let curr_area = (curr_bbox.width * curr_bbox.height) as f64;
let area_ratio = curr_area.max(prev_area) / curr_area.min(prev_area).max(1.0);
let mut score = 0.0;
// Reject if both embedding AND IoU disagree
if use_embedding && similarity < 0.5 && iou < 0.3 {
continue;
}
// Reject if bbox size changes too much
if area_ratio > 5.0 && similarity < 0.8 {
continue;
}
// Edge exit check
let prev_at_edge = prev_bbox.x < 50
let prev_at_edge = prev_bbox.x < 50
|| prev_bbox.x + prev_bbox.width > 1870
|| prev_bbox.y < 50
|| prev_bbox.y < 50
|| prev_bbox.y + prev_bbox.height > 1030;
let curr_at_edge = curr_bbox.x < 50
let curr_at_edge = curr_bbox.x < 50
|| curr_bbox.x + curr_bbox.width > 1870
|| curr_bbox.y < 50
|| curr_bbox.y < 50
|| curr_bbox.y + curr_bbox.height > 1030;
if prev_at_edge && !curr_at_edge && similarity < 0.8 {
continue;
}
// Calculate score
if iou > iou_threshold && similarity > similarity_threshold {
score = iou + similarity;
@@ -269,19 +272,19 @@ fn match_faces(
score = similarity + iou;
}
}
if score > best_score {
best_score = score;
best_prev_idx = prev_idx as i32;
}
}
if best_prev_idx >= 0 && best_score > 0.0 {
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
used_prev.insert(best_prev_idx as usize);
}
}
trace_ids
}
@@ -298,18 +301,18 @@ pub fn track_faces(
tracing::info!("No frames found in face.json");
return Ok(());
}
let fps = face_data.fps;
let frames_count = face_data.frames.len();
let mut next_trace_id: i32 = 0;
let mut traces: HashMap<i32, Vec<TracePoint>> = HashMap::new();
let mut prev_faces: Vec<Face> = Vec::new();
let mut prev_trace_ids: Vec<i32> = Vec::new();
let mut prev_frame_num: Option<u64> = None;
let mut prev_face_frame: Option<u64> = None;
tracing::info!(
"Tracking faces across {} frames (iou={}, similarity={}, distance={})",
frames_count,
@@ -317,7 +320,7 @@ pub fn track_faces(
similarity_threshold,
distance_threshold
);
for frame_idx in 0..face_data.frames.len() {
let frame_num = face_data.frames[frame_idx].frame;
let frame_gap = if let Some(prev) = prev_frame_num {
@@ -326,15 +329,15 @@ pub fn track_faces(
None
};
prev_frame_num = Some(frame_num);
let faces = &face_data.frames[frame_idx].faces.clone();
if faces.is_empty() {
prev_faces.clear();
prev_trace_ids.clear();
continue;
}
let matches = match_faces(
faces,
&prev_faces,
@@ -348,7 +351,7 @@ pub fn track_faces(
prev_face_frame,
Some(frame_num),
);
let mut trace_ids = Vec::new();
for (curr_idx, &trace_id) in matches.iter().enumerate() {
let trace_id = if trace_id >= 0 {
@@ -358,12 +361,12 @@ pub fn track_faces(
next_trace_id += 1;
new_id
};
// Set trace_id on the face
face_data.frames[frame_idx].faces[curr_idx].trace_id = Some(trace_id);
trace_ids.push(trace_id);
let face = &faces[curr_idx];
let trace_point = TracePoint {
frame: frame_num,
@@ -376,14 +379,17 @@ pub fn track_faces(
},
confidence: face.confidence,
};
traces.entry(trace_id).or_insert_with(Vec::new).push(trace_point);
traces
.entry(trace_id)
.or_insert_with(Vec::new)
.push(trace_point);
}
prev_faces = faces.clone();
prev_trace_ids = trace_ids;
prev_face_frame = Some(frame_num);
if frame_num % 100 == 0 {
tracing::info!(
"Frame {}: {} faces, {} active traces",
@@ -393,7 +399,7 @@ pub fn track_faces(
);
}
}
// Build trace statistics
let trace_stats: HashMap<String, TraceStats> = traces
.into_iter()
@@ -402,8 +408,9 @@ pub fn track_faces(
let start_frame = path.first().unwrap().frame;
let end_frame = path.last().unwrap().frame;
let duration_frames = end_frame - start_frame + 1;
let avg_confidence = path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64;
let avg_confidence =
path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64;
let stats = TraceStats {
trace_id,
start_frame,
@@ -414,11 +421,11 @@ pub fn track_faces(
avg_confidence,
path,
};
(trace_id.to_string(), stats)
})
.collect();
// Store traces in metadata
face_data.metadata = Some(serde_json::json!({
"traces": trace_stats,
@@ -427,9 +434,9 @@ pub fn track_faces(
"active_traces": trace_stats.len(),
}
}));
tracing::info!("✅ Tracking complete: {} traces", trace_stats.len());
Ok(())
}
@@ -451,7 +458,7 @@ mod tests {
width: 100,
height: 100,
};
let iou = calculate_bbox_iou(&bbox1, &bbox2);
assert!(iou > 0.0 && iou < 1.0);
}
@@ -470,7 +477,7 @@ mod tests {
width: 100,
height: 100,
};
let distance = calculate_bbox_distance(&bbox1, &bbox2);
assert!(distance > 0.0);
}
@@ -479,12 +486,12 @@ mod tests {
fn test_calculate_embedding_similarity() {
let emb1 = vec![1.0, 0.0, 0.0];
let emb2 = vec![1.0, 0.0, 0.0];
let similarity = calculate_embedding_similarity(&emb1, &emb2);
assert!((similarity - 1.0).abs() < 0.001);
let emb3 = vec![0.0, 1.0, 0.0];
let similarity2 = calculate_embedding_similarity(&emb1, &emb3);
assert!((similarity2 - 0.0).abs() < 0.001);
}
}
}
+1 -1
View File
@@ -195,5 +195,5 @@ pub use tkg::{
build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo,
RepresentativeFrameResult, TkgResult,
};
pub mod tool_selector;
pub mod processor_config_v3;
pub mod tool_selector;
+6 -6
View File
@@ -240,32 +240,32 @@ pub async fn process_ocr(
// Resolve Swift OCR processor path
let swift_ocr_path = crate::core::processor::face::swift_processor_path("swift_ocr");
if swift_ocr_path.exists() {
tracing::info!("[OCR] Using Swift processor: {:?}", swift_ocr_path);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
let output = tokio::process::Command::new(swift_ocr_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_ocr")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[OCR] Swift processor failed: {}", stderr);
anyhow::bail!("Swift OCR failed: {}", stderr);
}
tracing::info!("[OCR] Swift processor completed successfully");
} else {
tracing::warn!("[OCR] Swift binary not found, falling back to Python");
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("ocr_processor.py");
+128 -102
View File
@@ -158,26 +158,31 @@ pub async fn process_pose(
total_video_frames
);
let executor = PythonExecutor::new()?;
let executor = PythonExecutor::new()?;
// Try config-driven tool selection first
if let Ok(Some(result)) = run_pose_with_config(&executor, video_path, output_path, uuid, frames).await {
tracing::info!(
"[POSE] Config-driven interpolation completed: {} frames",
result.frames.len()
);
return Ok(result);
}
// Try config-driven tool selection first
if let Ok(Some(result)) =
run_pose_with_config(&executor, video_path, output_path, uuid, frames).await
{
tracing::info!(
"[POSE] Config-driven interpolation completed: {} frames",
result.frames.len()
);
return Ok(result);
}
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded interpolation logic");
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded interpolation logic");
// Fallback to hard-coded logic
// Check for MediaPipe Pose first (highest accuracy)
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
// Fallback to hard-coded logic
// Check for MediaPipe Pose first (highest accuracy)
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
if mediapipe_script.exists() {
tracing::info!("[POSE] Using MediaPipe Pose for interpolation (highest accuracy): {:?}", mediapipe_script);
tracing::info!(
"[POSE] Using MediaPipe Pose for interpolation (highest accuracy): {:?}",
mediapipe_script
);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
@@ -185,7 +190,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
}
args.push("--model-complexity".to_string());
args.push("2".to_string()); // Highest accuracy
executor
.run_with_frames(
"pose_processor_mediapipe.py",
@@ -197,7 +202,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
)
.await
.with_context(|| format!("Failed to run MediaPipe Pose"))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read MediaPipe POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
@@ -208,7 +213,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
);
return Ok(result);
}
tracing::info!("[POSE] MediaPipe Pose not found, trying other processors");
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
@@ -246,43 +251,46 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
}
// Swift processor path (preferred over Python)
let swift_pose_path = crate::core::path_utils::cli_dir()
.join("swift/.build/release/swift_pose");
tracing::info!("[POSE] Looking for Swift processor at: {:?}", swift_pose_path);
let swift_pose_path =
crate::core::path_utils::cli_dir().join("swift/.build/release/swift_pose");
tracing::info!(
"[POSE] Looking for Swift processor at: {:?}",
swift_pose_path
);
if swift_pose_path.exists() {
tracing::info!("[POSE] Using Swift processor: {:?}", swift_pose_path);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
let output = tokio::process::Command::new(swift_pose_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_pose")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[POSE] Swift processor failed: {}", stderr);
anyhow::bail!("Swift pose processor failed");
}
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read Swift POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse Swift POSE output")?;
let result: PoseResult =
serde_json::from_str(&json_str).context("Failed to parse Swift POSE output")?;
tracing::info!(
"[POSE] Swift processor completed: {} frames",
result.frames.len()
);
return Ok(result);
}
tracing::info!("[POSE] Swift processor not found, falling back to Python");
// Call Python pose_processor.py for interpolation
@@ -320,29 +328,34 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
}
}
let executor = PythonExecutor::new()?;
let executor = PythonExecutor::new()?;
tracing::info!("[POSE] Starting pose estimation: {}", video_path);
tracing::info!("[POSE] Starting pose estimation: {}", video_path);
// Try config-driven tool selection first
if let Ok(Some(result)) = run_pose_with_config(&executor, video_path, output_path, uuid, frames).await {
tracing::info!(
"[POSE] Config-driven processing completed: {} frames, {} total poses",
result.frames.len(),
result.frames.iter().map(|f| f.persons.len()).sum::<usize>()
);
return Ok(result);
}
// Try config-driven tool selection first
if let Ok(Some(result)) =
run_pose_with_config(&executor, video_path, output_path, uuid, frames).await
{
tracing::info!(
"[POSE] Config-driven processing completed: {} frames, {} total poses",
result.frames.len(),
result.frames.iter().map(|f| f.persons.len()).sum::<usize>()
);
return Ok(result);
}
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded logic");
tracing::info!("[POSE] Config-driven selection failed, falling back to hard-coded logic");
// Fallback to hard-coded logic
// Check for MediaPipe Pose first (highest accuracy)
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
// Fallback to hard-coded logic
// Check for MediaPipe Pose first (highest accuracy)
let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
if mediapipe_script.exists() {
tracing::info!("[POSE] Using MediaPipe Pose (highest accuracy): {:?}", mediapipe_script);
tracing::info!(
"[POSE] Using MediaPipe Pose (highest accuracy): {:?}",
mediapipe_script
);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
@@ -350,7 +363,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
}
args.push("--model-complexity".to_string());
args.push("2".to_string()); // Highest accuracy
executor
.run_with_frames(
"pose_processor_mediapipe.py",
@@ -362,11 +375,11 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
)
.await
.with_context(|| format!("Failed to run MediaPipe Pose"))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read MediaPipe POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse MediaPipe POSE output")?;
let json_str =
std::fs::read_to_string(output_path).context("Failed to read MediaPipe POSE output")?;
let result: PoseResult =
serde_json::from_str(&json_str).context("Failed to parse MediaPipe POSE output")?;
tracing::info!(
"[POSE] MediaPipe Pose completed: {} frames, {} total poses",
result.frames.len(),
@@ -374,7 +387,7 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
);
return Ok(result);
}
tracing::info!("[POSE] MediaPipe Pose not found, trying other processors");
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
@@ -394,11 +407,14 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse POSE output")?;
tracing::info!("[POSE] Rust processor completed: {} frames", result.frames.len());
let json_str =
std::fs::read_to_string(output_path).context("Failed to read POSE output")?;
let result: PoseResult =
serde_json::from_str(&json_str).context("Failed to parse POSE output")?;
tracing::info!(
"[POSE] Rust processor completed: {} frames",
result.frames.len()
);
return Ok(result);
}
tracing::warn!(
@@ -407,40 +423,46 @@ let mediapipe_script = executor.script_path("pose_processor_mediapipe.py");
}
// Swift processor path (Apple Vision - faster but lower accuracy)
let swift_pose_path = crate::core::path_utils::cli_dir()
.join("swift/.build/release/swift_pose");
tracing::info!("[POSE] Looking for Swift processor at: {:?}", swift_pose_path);
let swift_pose_path =
crate::core::path_utils::cli_dir().join("swift/.build/release/swift_pose");
tracing::info!(
"[POSE] Looking for Swift processor at: {:?}",
swift_pose_path
);
if swift_pose_path.exists() {
tracing::info!("[POSE] Using Swift processor: {:?}", swift_pose_path);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
let output = tokio::process::Command::new(swift_pose_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_pose")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[POSE] Swift processor failed: {}", stderr);
anyhow::bail!("Swift pose processor failed");
}
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read Swift POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse Swift POSE output")?;
tracing::info!("[POSE] Swift processor completed: {} frames", result.frames.len());
let json_str =
std::fs::read_to_string(output_path).context("Failed to read Swift POSE output")?;
let result: PoseResult =
serde_json::from_str(&json_str).context("Failed to parse Swift POSE output")?;
tracing::info!(
"[POSE] Swift processor completed: {} frames",
result.frames.len()
);
return Ok(result);
}
tracing::info!("[POSE] Swift processor not found, falling back to Python");
let script_path = executor.script_path("pose_processor.py");
@@ -484,25 +506,29 @@ async fn run_pose_with_config(
frames: Option<&[i64]>,
) -> Result<Option<PoseResult>> {
use super::tool_selector::ToolSelector;
let selector = ToolSelector::new("pose");
if let Some(tool) = selector.select_tool(executor).await? {
tracing::info!(
"[POSE] Using tool from config: {} (priority {})",
tool.name,
tool.parameters.get("priority").and_then(|v| v.as_u64()).unwrap_or(99)
tool.parameters
.get("priority")
.and_then(|v| v.as_u64())
.unwrap_or(99)
);
match tool.name.as_str() {
"mediapipe" => {
let model_complexity = tool.parameters
let model_complexity = tool
.parameters
.get("model_complexity")
.and_then(|v| v.as_u64())
.unwrap_or(2) as u8;
tracing::info!("[POSE] MediaPipe model_complexity={}", model_complexity);
executor
.run_with_frames(
"pose_processor_mediapipe.py",
@@ -514,18 +540,18 @@ async fn run_pose_with_config(
)
.await
.with_context(|| "Failed to run MediaPipe Pose")?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read MediaPipe POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse MediaPipe POSE output")?;
return Ok(Some(result));
}
"swift" => {
let swift_path = &tool.path;
tracing::info!("[POSE] Using Swift processor from config: {:?}", swift_path);
let args = if !tool.args.is_empty() {
tracing::info!("[POSE] Using args from config: {:?}", tool.args);
tool.args.clone()
@@ -537,39 +563,39 @@ async fn run_pose_with_config(
}
args
};
let output = tokio::process::Command::new(swift_path)
.args(&args)
.output()
.await
.context("Failed to execute swift_pose")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[POSE] Swift processor failed: {}", stderr);
anyhow::bail!("Swift pose processor failed");
}
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read Swift POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse Swift POSE output")?;
let result: PoseResult =
serde_json::from_str(&json_str).context("Failed to parse Swift POSE output")?;
return Ok(Some(result));
}
"rust" => {
let rust_path = &tool.path;
tracing::info!("[POSE] Using Rust processor from config: {:?}", rust_path);
if !tool.args.is_empty() {
tracing::info!("[POSE] Using args from config: {:?}", tool.args);
let output = tokio::process::Command::new(rust_path)
.args(&tool.args)
.output()
.await
.context("Failed to execute rust_pose")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[POSE] Rust processor failed: {}", stderr);
@@ -589,12 +615,12 @@ async fn run_pose_with_config(
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_path))?;
}
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse POSE output")?;
let json_str =
std::fs::read_to_string(output_path).context("Failed to read POSE output")?;
let result: PoseResult =
serde_json::from_str(&json_str).context("Failed to parse POSE output")?;
return Ok(Some(result));
}
_ => {
@@ -602,7 +628,7 @@ async fn run_pose_with_config(
}
}
}
Ok(None)
}
+38 -29
View File
@@ -50,83 +50,90 @@ pub struct ProcessorConfigManager {
impl ProcessorConfigManager {
pub async fn load() -> Result<Self> {
let config_path = std::path::Path::new("config/processor_tools_v3.json");
if !config_path.exists() {
anyhow::bail!("Config file not found: {:?}", config_path);
}
let content = tokio::fs::read_to_string(config_path)
.await
.context("Failed to read config file")?;
let full_config: serde_json::Value = serde_json::from_str(&content)
.context("Failed to parse config JSON")?;
let full_config: serde_json::Value =
serde_json::from_str(&content).context("Failed to parse config JSON")?;
let processor_config = full_config
.get("processor_config")
.context("Missing processor_config in config")?
.clone();
let config: HashMap<String, ProcessorConfigV3> = serde_json::from_value(processor_config)
.context("Failed to parse processor configs")?;
let config: HashMap<String, ProcessorConfigV3> =
serde_json::from_value(processor_config)
.context("Failed to parse processor configs")?;
info!("[ConfigV3] Loaded {} processor configs", config.len());
Ok(Self { config })
}
pub fn get_processor(&self, name: &str) -> Option<&ProcessorConfigV3> {
self.config.get(name)
}
pub fn get_implementation(&self, processor: &str, tool: &str) -> Option<&Implementation> {
self.config.get(processor)?.implementations.iter()
self.config
.get(processor)?
.implementations
.iter()
.find(|i| i.tool == tool)
}
pub fn get_default_implementation(&self, processor: &str) -> Option<&Implementation> {
let proc_config = self.config.get(processor)?;
let default_tool = &proc_config.default.tool;
proc_config.implementations.iter()
proc_config
.implementations
.iter()
.find(|i| i.tool == *default_tool && i.enabled)
}
pub fn resolve_command(
&self,
processor: &str,
tool: &str,
variables: &HashMap<String, String>,
) -> Result<Option<(PathBuf, Vec<String>)>> {
let implementation = self.get_implementation(processor, tool)
let implementation = self
.get_implementation(processor, tool)
.context(format!("Implementation not found: {}/{}", processor, tool))?;
if !implementation.enabled {
return Ok(None);
}
let executable = Self::resolve_variables(&implementation.command.executable, variables);
let executable_path = PathBuf::from(&executable);
if !executable_path.exists() {
info!("[ConfigV3] Executable not found: {:?}", executable_path);
return Ok(None);
}
let mut args = Vec::new();
for arg in &implementation.command.args {
let resolved = Self::resolve_variables(arg, variables);
args.push(resolved);
}
info!(
"[ConfigV3] Resolved command: {:?} {:?}",
executable_path, args
);
Ok(Some((executable_path, args)))
}
fn resolve_variables(template: &str, variables: &HashMap<String, String>) -> String {
let mut result = template.to_string();
for (key, value) in variables {
@@ -135,14 +142,16 @@ impl ProcessorConfigManager {
}
result
}
pub fn get_all_processors(&self) -> Vec<String> {
self.config.keys().cloned().collect()
}
pub fn get_implementations_by_priority(&self, processor: &str) -> Vec<&Implementation> {
if let Some(proc_config) = self.config.get(processor) {
let mut implementations: Vec<_> = proc_config.implementations.iter()
let mut implementations: Vec<_> = proc_config
.implementations
.iter()
.filter(|i| i.enabled)
.collect();
implementations.sort_by_key(|i| i.priority);
+1 -1
View File
@@ -68,7 +68,7 @@ pub async fn process_scene_classification(
// Resolve scene classification model path
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let coreml_path = models_dir.join("resnet18_places365.mlpackage");
let mut args = vec![video_path, output_path];
if coreml_path.exists() {
args.push("--model");
+4 -4
View File
@@ -1231,7 +1231,7 @@ async fn build_face_track_nodes_from_qdrant(
// Use trace_N as primary external_id (consistent with cluster_agent)
let external_id = format!("trace_{}", tid);
let label = format!("Face Trace {}", tid);
let label = String::new();
// Compute average pose for this trace
let mut yaw_sum = 0.0f64;
@@ -3551,7 +3551,7 @@ async fn build_face_body_edges(
.get("frame")
.and_then(|v| v.as_i64())
.unwrap_or(0);
if let Some(persons) = frame_entry.get("persons").and_then(|v| v.as_array()) {
for (idx, person) in persons.iter().enumerate() {
if let Some(bbox) = person.get("bbox") {
@@ -3559,7 +3559,7 @@ async fn build_face_body_edges(
let y = bbox.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
let w = bbox.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0);
let h = bbox.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0);
if w > 0.0 && h > 0.0 {
frame_poses
.entry(frame_num)
@@ -3590,7 +3590,7 @@ async fn build_face_body_edges(
let body_center_y = py + ph / 2.0;
let distance = ((face_center_x - body_center_x).powi(2)
+ (face_center_y - body_center_y).powi(2))
.sqrt();
.sqrt();
if distance < best_distance {
best_distance = distance;
+140 -61
View File
@@ -16,20 +16,32 @@ impl ToolSelector {
}
}
pub async fn select_tool(&self, executor: &super::PythonExecutor) -> Result<Option<SelectedTool>> {
pub async fn select_tool(
&self,
executor: &super::PythonExecutor,
) -> Result<Option<SelectedTool>> {
match self.select_tool_v3().await {
Ok(Some(tool)) => {
info!("[{}] Selected tool via V3: {}", self.processor_name, tool.name);
info!(
"[{}] Selected tool via V3: {}",
self.processor_name, tool.name
);
return Ok(Some(tool));
}
Ok(None) => {
info!("[{}] No tool found via V3, falling back to V2", self.processor_name);
info!(
"[{}] No tool found via V3, falling back to V2",
self.processor_name
);
}
Err(e) => {
info!("[{}] V3 config failed: {}, falling back to V2", self.processor_name, e);
info!(
"[{}] V3 config failed: {}, falling back to V2",
self.processor_name, e
);
}
}
let config = admin_config::get_processor_config(&self.processor_name)
.await
.context("Failed to get processor config")?;
@@ -64,10 +76,7 @@ impl ToolSelector {
if let Some(default) = config.default_tool {
if let Some(tool_path) = self.find_tool(&default, executor) {
info!(
"[{}] Using default tool: {}",
self.processor_name, default
);
info!("[{}] Using default tool: {}", self.processor_name, default);
return Ok(Some(SelectedTool {
name: default.clone(),
path: tool_path,
@@ -81,30 +90,30 @@ impl ToolSelector {
info!("[{}] No available tool found", self.processor_name);
Ok(None)
}
pub async fn select_tool_v3(&self) -> Result<Option<SelectedTool>> {
let manager = processor_config_v3::get_config_manager().await?;
let implementations = manager.get_implementations_by_priority(&self.processor_name);
if implementations.is_empty() {
return Ok(None);
}
let variables = self.build_variables();
for impl_ in implementations {
if !impl_.enabled {
continue;
}
match manager.resolve_command(&self.processor_name, &impl_.tool, &variables) {
Ok(Some((executable, args))) => {
info!(
"[ToolSelector V3] Selected: {} (priority {}, timeout {}s)",
impl_.tool, impl_.priority, impl_.timeout
);
return Ok(Some(SelectedTool {
name: impl_.tool.clone(),
path: executable,
@@ -114,7 +123,10 @@ impl ToolSelector {
}));
}
Ok(None) => {
info!("[ToolSelector V3] Tool {} not available, trying next", impl_.tool);
info!(
"[ToolSelector V3] Tool {} not available, trying next",
impl_.tool
);
continue;
}
Err(e) => {
@@ -123,43 +135,48 @@ impl ToolSelector {
}
}
}
Ok(None)
}
fn build_variables(&self) -> HashMap<String, String> {
let mut vars = HashMap::new();
if let Ok(output_dir) = std::env::var("MOMENTRY_OUTPUT_DIR") {
vars.insert("output_dir".to_string(), output_dir);
} else {
// Resolve output_dir from environment or config
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
vars.insert("output_dir".to_string(), output_dir);
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
vars.insert("output_dir".to_string(), output_dir);
}
vars
}
fn swift_binary_path(executor: &super::PythonExecutor, bin_name: &str) -> PathBuf {
if let Ok(dir) = std::env::var("MOMENTRY_SWIFT_BIN_DIR") {
let p = PathBuf::from(dir).join(bin_name);
if p.exists() { return p; }
if p.exists() {
return p;
}
}
// Try sibling of current_exe
if let Ok(exe) = std::env::current_exe() {
if let Some(parent) = exe.parent() {
let p = parent.join("tools/cli/swift/.build/release").join(bin_name);
if p.exists() { return p; }
if p.exists() {
return p;
}
}
}
// Fallback to scripts dir
let scripts = executor.script_path("");
let base = scripts.parent().map(|p| p.to_path_buf()).unwrap_or_else(|| {
crate::core::path_utils::scripts_dir()
});
let base = scripts
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| crate::core::path_utils::scripts_dir());
base.join("swift_processors/.build/release").join(bin_name)
}
@@ -168,46 +185,78 @@ impl ToolSelector {
// POSE processor tools
("pose", "mediapipe") => {
let script = executor.script_path("pose_processor_mediapipe.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
("pose", "rust") => executor.rust_binary_path("rust_pose"),
("pose", "swift") => {
let swift_path = Self::swift_binary_path(executor, "swift_pose");
if swift_path.exists() { Some(swift_path) } else { None }
if swift_path.exists() {
Some(swift_path)
} else {
None
}
}
("pose", "yolov8") => {
let script = executor.script_path("pose_processor_mps.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
("pose", "python") => {
let script = executor.script_path("pose_processor.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
// FACE processor tools
("face", "swift") => {
let swift_path = Self::swift_binary_path(executor, "swift_face");
if swift_path.exists() { Some(swift_path) } else { None }
if swift_path.exists() {
Some(swift_path)
} else {
None
}
}
("face", "python") => {
let script = executor.script_path("face_processor.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
// ASR processor tools
("asr", "whisper") => {
let whisper_cli = std::path::Path::new("/opt/homebrew/bin/whisper");
if whisper_cli.exists() { Some(whisper_cli.to_path_buf()) } else { None }
if whisper_cli.exists() {
Some(whisper_cli.to_path_buf())
} else {
None
}
}
("asr", "rust") => {
// Future: Rust ASR implementation
executor.rust_binary_path("rust_asr")
}
// ASRX processor tools
("asrx", "swift") => {
let swift_path = Self::swift_binary_path(executor, "asrx_swift");
if swift_path.exists() { Some(swift_path) } else { None }
if swift_path.exists() {
Some(swift_path)
} else {
None
}
}
("asrx", "rust") => {
// Future: Rust ASRX implementation
@@ -215,61 +264,87 @@ impl ToolSelector {
}
("asrx", "python") => {
let script = executor.script_path("asrx_processor.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
// OCR processor tools
("ocr", "swift") => {
let swift_path = Self::swift_binary_path(executor, "swift_ocr");
if swift_path.exists() { Some(swift_path) } else { None }
if swift_path.exists() {
Some(swift_path)
} else {
None
}
}
("ocr", "python") => {
let script = executor.script_path("ocr_processor.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
// Face trace tools
("face_trace", "python") => {
let script = executor.script_path("store_traced_faces.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
("face_trace", "rust") => {
executor.rust_binary_path("rust_store_traced_faces")
}
("face_trace", "rust") => executor.rust_binary_path("rust_store_traced_faces"),
// Face deduplicate tools
("face_deduplicate", "python") => {
let script = executor.script_path("face_deduplicate.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
("face_deduplicate", "rust") => {
// Future: Rust face deduplicate implementation
executor.rust_binary_path("rust_face_deduplicate")
}
// Scene VLM summary tools
("scene_vlm_summary", "python") => {
let script = executor.script_path("scene_vlm_summary.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
// TKG (Temporal Knowledge Graph) tools
("tkg", "python") => {
let script = executor.script_path("store_traced_faces.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
("tkg", "rust") => {
// Future: Rust TKG implementation
executor.rust_binary_path("rust_tkg")
}
// VLM Summary tools (Rust native implementation)
("vlm_summary", "rust") => {
// VLM Summary is implemented in Rust, no external binary needed
// Return a placeholder path to indicate availability
Some(std::path::PathBuf::from("rust_vlm_summary"))
}
// CUT (Scene detection) tools
("cut", "rust") => {
// CUT is implemented in Rust using ffmpeg
@@ -278,9 +353,13 @@ impl ToolSelector {
}
("cut", "python") => {
let script = executor.script_path("cut_processor.py");
if script.exists() { Some(script) } else { None }
if script.exists() {
Some(script)
} else {
None
}
}
_ => None,
}
}
@@ -304,4 +383,4 @@ impl Default for SelectedTool {
timeout: 3600,
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ReplayError {
#[error("Session not found: {0}")]
SessionNotFound(String),
#[error("Command not found: {0}")]
CommandNotFound(i64),
#[error("Invalid replay type: {0}")]
InvalidReplayType(String),
#[error("Invalid status: {0}")]
InvalidStatus(String),
#[error("Session already running: {0}")]
SessionAlreadyRunning(String),
#[error("Session not running: {0}")]
SessionNotRunning(String),
#[error("No commands to replay")]
NoCommandsToReplay,
#[error("Database error: {0}")]
DatabaseError(#[from] sqlx::Error),
#[error("Worker error: {0}")]
WorkerError(String),
}
+16
View File
@@ -0,0 +1,16 @@
pub mod error;
pub mod store;
pub mod types;
pub use error::ReplayError;
pub use store::ReplayStore;
pub use types::{
CreateReplaySessionRequest, ReplayCommand, ReplayProgress, ReplaySession, ReplayStatus,
ReplayType,
};
use sqlx::PgPool;
pub fn init(db: PgPool) -> ReplayStore {
ReplayStore::new(db)
}
+441
View File
@@ -0,0 +1,441 @@
use crate::core::replay::error::ReplayError;
use crate::core::replay::types::{
CreateReplaySessionRequest, ReplayCommand, ReplaySession, ReplayStatus, ReplayType,
};
use sqlx::PgPool;
use chrono::Utc;
pub struct ReplayStore {
db: PgPool,
}
impl ReplayStore {
pub fn new(db: PgPool) -> Self {
Self { db }
}
/// 创建 Replay Session
pub async fn create_session(
&self,
req: CreateReplaySessionRequest,
user_id: Option<i64>,
) -> Result<ReplaySession, ReplayError> {
let config = req.config.unwrap_or(serde_json::json!({
"concurrency": 5,
"delay_ms": 100,
"stop_on_error": false,
"compare_results": true,
"timeout_secs": 300
}));
let row = sqlx::query!(
r#"
INSERT INTO replay_sessions (session_name, replay_type, source_filter, config, user_id)
VALUES ($1, $2, $3, $4, $5)
RETURNING
id, session_id, session_name, replay_type, source_filter, config, status,
total_commands, processed_commands, succeeded_commands, failed_commands, skipped_commands,
comparison_results, started_at, completed_at, duration_secs, error_message,
created_at, updated_at, user_id
"#,
req.session_name,
req.replay_type.as_str(),
req.source_filter.to_string(),
config.to_string(),
user_id,
)
.fetch_one(&self.db)
.await?;
Ok(ReplaySession {
id: row.id,
session_id: row.session_id,
session_name: row.session_name,
replay_type: ReplayType::from_str(&row.replay_type).unwrap(),
source_filter: serde_json::from_str(&row.source_filter).unwrap_or_default(),
config: serde_json::from_str(&row.config).unwrap_or_default(),
status: ReplayStatus::from_str(&row.status).unwrap(),
total_commands: row.total_commands,
processed_commands: row.processed_commands,
succeeded_commands: row.succeeded_commands,
failed_commands: row.failed_commands,
skipped_commands: row.skipped_commands,
comparison_results: serde_json::from_str(&row.comparison_results).unwrap_or_default(),
started_at: row.started_at,
completed_at: row.completed_at,
duration_secs: row.duration_secs,
error_message: row.error_message,
created_at: row.created_at,
updated_at: row.updated_at,
user_id: row.user_id,
})
}
/// 获取 Session
pub async fn get_session(&self, session_id: &str) -> Result<Option<ReplaySession>, ReplayError> {
let row = sqlx::query!(
r#"
SELECT
id, session_id, session_name, replay_type, source_filter, config, status,
total_commands, processed_commands, succeeded_commands, failed_commands, skipped_commands,
comparison_results, started_at, completed_at, duration_secs, error_message,
created_at, updated_at, user_id
FROM replay_sessions
WHERE session_id = $1
"#,
session_id,
)
.fetch_optional(&self.db)
.await?;
match row {
Some(row) => Ok(Some(ReplaySession {
id: row.id,
session_id: row.session_id,
session_name: row.session_name,
replay_type: ReplayType::from_str(&row.replay_type).unwrap(),
source_filter: serde_json::from_str(&row.source_filter).unwrap_or_default(),
config: serde_json::from_str(&row.config).unwrap_or_default(),
status: ReplayStatus::from_str(&row.status).unwrap(),
total_commands: row.total_commands,
processed_commands: row.processed_commands,
succeeded_commands: row.succeeded_commands,
failed_commands: row.failed_commands,
skipped_commands: row.skipped_commands,
comparison_results: serde_json::from_str(&row.comparison_results).unwrap_or_default(),
started_at: row.started_at,
completed_at: row.completed_at,
duration_secs: row.duration_secs,
error_message: row.error_message,
created_at: row.created_at,
updated_at: row.updated_at,
user_id: row.user_id,
})),
None => Ok(None),
}
}
/// 更新 Session 状态
pub async fn update_session_status(
&self,
session_id: &str,
status: ReplayStatus,
error_message: Option<&str>,
) -> Result<(), ReplayError> {
let now = Utc::now();
match status {
ReplayStatus::Running => {
sqlx::query!(
r#"
UPDATE replay_sessions
SET status = $2, started_at = $3
WHERE session_id = $1
"#,
session_id,
status.as_str(),
now,
)
.execute(&self.db)
.await?;
}
ReplayStatus::Completed | ReplayStatus::Failed | ReplayStatus::Cancelled => {
// 计算持续时间
let session = self.get_session(session_id).await?.ok_or_else(|| {
ReplayError::SessionNotFound(session_id.to_string())
})?;
let duration_secs = session.started_at.map(|start| {
(now - start).num_seconds() as f64
});
sqlx::query!(
r#"
UPDATE replay_sessions
SET status = $2, completed_at = $3, duration_secs = $4, error_message = $5
WHERE session_id = $1
"#,
session_id,
status.as_str(),
now,
duration_secs,
error_message,
)
.execute(&self.db)
.await?;
}
_ => {
sqlx::query!(
r#"
UPDATE replay_sessions
SET status = $2
WHERE session_id = $1
"#,
session_id,
status.as_str(),
)
.execute(&self.db)
.await?;
}
}
Ok(())
}
/// 更新 Session 统计
pub async fn update_session_stats(
&self,
session_id: &str,
processed: i32,
succeeded: i32,
failed: i32,
skipped: i32,
) -> Result<(), ReplayError> {
sqlx::query!(
r#"
UPDATE replay_sessions
SET
processed_commands = $2,
succeeded_commands = $3,
failed_commands = $4,
skipped_commands = $5
WHERE session_id = $1
"#,
session_id,
processed,
succeeded,
failed,
skipped,
)
.execute(&self.db)
.await?;
Ok(())
}
/// 创建 Replay Command
pub async fn create_replay_command(
&self,
session_id: &str,
original_command_id: &str,
original_job_type: &str,
original_file_path: Option<&str>,
original_file_uuid: Option<&str>,
original_payload: Option<serde_json::Value>,
) -> Result<ReplayCommand, ReplayError> {
let row = sqlx::query!(
r#"
INSERT INTO replay_commands
(session_id, original_command_id, original_job_type, original_file_path,
original_file_uuid, original_payload, status)
VALUES ($1, $2, $3, $4, $5, $6, 'pending')
RETURNING
id, session_id, original_command_id, replay_command_id, status,
original_job_type, original_file_path, original_file_uuid, original_payload,
original_result, replay_result, comparison_status, differences,
original_duration_secs, replay_duration_secs, error_message, retry_count,
started_at, completed_at, created_at
"#,
session_id,
original_command_id,
original_job_type,
original_file_path,
original_file_uuid,
original_payload.map(|p| p.to_string()),
)
.fetch_one(&self.db)
.await?;
Ok(ReplayCommand {
id: row.id,
session_id: row.session_id,
original_command_id: row.original_command_id,
replay_command_id: row.replay_command_id,
status: row.status,
original_job_type: row.original_job_type,
original_file_path: row.original_file_path,
original_file_uuid: row.original_file_uuid,
original_payload: row.original_payload.and_then(|s| serde_json::from_str(&s).ok()),
original_result: row.original_result.and_then(|s| serde_json::from_str(&s).ok()),
replay_result: row.replay_result.and_then(|s| serde_json::from_str(&s).ok()),
comparison_status: row.comparison_status,
differences: row.differences.and_then(|s| serde_json::from_str(&s).ok()),
original_duration_secs: row.original_duration_secs,
replay_duration_secs: row.replay_duration_secs,
error_message: row.error_message,
retry_count: row.retry_count,
started_at: row.started_at,
completed_at: row.completed_at,
created_at: row.created_at,
})
}
/// 获取待处理的 Replay Commands
pub async fn get_pending_commands(
&self,
session_id: &str,
limit: i32,
) -> Result<Vec<ReplayCommand>, ReplayError> {
let rows = sqlx::query!(
r#"
SELECT
id, session_id, original_command_id, replay_command_id, status,
original_job_type, original_file_path, original_file_uuid, original_payload,
original_result, replay_result, comparison_status, differences,
original_duration_secs, replay_duration_secs, error_message, retry_count,
started_at, completed_at, created_at
FROM replay_commands
WHERE session_id = $1 AND status = 'pending'
ORDER BY id ASC
LIMIT $2
FOR UPDATE SKIP LOCKED
"#,
session_id,
limit,
)
.fetch_all(&self.db)
.await?;
Ok(rows
.into_iter()
.map(|row| ReplayCommand {
id: row.id,
session_id: row.session_id,
original_command_id: row.original_command_id,
replay_command_id: row.replay_command_id,
status: row.status,
original_job_type: row.original_job_type,
original_file_path: row.original_file_path,
original_file_uuid: row.original_file_uuid,
original_payload: row.original_payload.and_then(|s| serde_json::from_str(&s).ok()),
original_result: row.original_result.and_then(|s| serde_json::from_str(&s).ok()),
replay_result: row.replay_result.and_then(|s| serde_json::from_str(&s).ok()),
comparison_status: row.comparison_status,
differences: row.differences.and_then(|s| serde_json::from_str(&s).ok()),
original_duration_secs: row.original_duration_secs,
replay_duration_secs: row.replay_duration_secs,
error_message: row.error_message,
retry_count: row.retry_count,
started_at: row.started_at,
completed_at: row.completed_at,
created_at: row.created_at,
})
.collect())
}
/// 更新 Replay Command 状态
pub async fn update_command_status(
&self,
command_id: i64,
status: &str,
replay_command_id: Option<&str>,
replay_result: Option<serde_json::Value>,
comparison_status: Option<&str>,
differences: Option<serde_json::Value>,
error_message: Option<&str>,
) -> Result<(), ReplayError> {
let now = Utc::now();
sqlx::query!(
r#"
UPDATE replay_commands
SET
status = $2,
replay_command_id = COALESCE($3, replay_command_id),
replay_result = COALESCE($4, replay_result),
comparison_status = COALESCE($5, comparison_status),
differences = COALESCE($6, differences),
error_message = COALESCE($7, error_message),
completed_at = $8
WHERE id = $1
"#,
command_id,
status,
replay_command_id,
replay_result.map(|r| r.to_string()),
comparison_status,
differences.map(|d| d.to_string()),
error_message,
now,
)
.execute(&self.db)
.await?;
Ok(())
}
/// 列出 Sessions
pub async fn list_sessions(
&self,
status: Option<&str>,
limit: i32,
offset: i32,
) -> Result<Vec<ReplaySession>, ReplayError> {
let rows = match status {
Some(s) => {
sqlx::query!(
r#"
SELECT
id, session_id, session_name, replay_type, source_filter, config, status,
total_commands, processed_commands, succeeded_commands, failed_commands, skipped_commands,
comparison_results, started_at, completed_at, duration_secs, error_message,
created_at, updated_at, user_id
FROM replay_sessions
WHERE status = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
"#,
s,
limit,
offset,
)
.fetch_all(&self.db)
.await?
}
None => {
sqlx::query!(
r#"
SELECT
id, session_id, session_name, replay_type, source_filter, config, status,
total_commands, processed_commands, succeeded_commands, failed_commands, skipped_commands,
comparison_results, started_at, completed_at, duration_secs, error_message,
created_at, updated_at, user_id
FROM replay_sessions
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
"#,
limit,
offset,
)
.fetch_all(&self.db)
.await?
}
};
Ok(rows
.into_iter()
.map(|row| ReplaySession {
id: row.id,
session_id: row.session_id,
session_name: row.session_name,
replay_type: ReplayType::from_str(&row.replay_type).unwrap(),
source_filter: serde_json::from_str(&row.source_filter).unwrap_or_default(),
config: serde_json::from_str(&row.config).unwrap_or_default(),
status: ReplayStatus::from_str(&row.status).unwrap(),
total_commands: row.total_commands,
processed_commands: row.processed_commands,
succeeded_commands: row.succeeded_commands,
failed_commands: row.failed_commands,
skipped_commands: row.skipped_commands,
comparison_results: serde_json::from_str(&row.comparison_results).unwrap_or_default(),
started_at: row.started_at,
completed_at: row.completed_at,
duration_secs: row.duration_secs,
error_message: row.error_message,
created_at: row.created_at,
updated_at: row.updated_at,
user_id: row.user_id,
})
.collect())
}
}
+180
View File
@@ -0,0 +1,180 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
/// Replay 类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReplayType {
/// 重放成功命令(验证幂等性)
Success,
/// 重放失败命令(测试容错)
Failed,
/// 批量重放(压力测试)
Batch,
/// 场景回放(测试特定场景)
Scenario,
}
impl ReplayType {
pub fn as_str(&self) -> &'static str {
match self {
ReplayType::Success => "success",
ReplayType::Failed => "failed",
ReplayType::Batch => "batch",
ReplayType::Scenario => "scenario",
}
}
pub fn from_str(s: &str) -> Option<Self> {
match s {
"success" => Some(ReplayType::Success),
"failed" => Some(ReplayType::Failed),
"batch" => Some(ReplayType::Batch),
"scenario" => Some(ReplayType::Scenario),
_ => None,
}
}
}
/// Replay Session 状态
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReplayStatus {
Pending,
Running,
Paused,
Completed,
Failed,
Cancelled,
}
impl ReplayStatus {
pub fn as_str(&self) -> &'static str {
match self {
ReplayStatus::Pending => "pending",
ReplayStatus::Running => "running",
ReplayStatus::Paused => "paused",
ReplayStatus::Completed => "completed",
ReplayStatus::Failed => "failed",
ReplayStatus::Cancelled => "cancelled",
}
}
pub fn from_str(s: &str) -> Option<Self> {
match s {
"pending" => Some(ReplayStatus::Pending),
"running" => Some(ReplayStatus::Running),
"paused" => Some(ReplayStatus::Paused),
"completed" => Some(ReplayStatus::Completed),
"failed" => Some(ReplayStatus::Failed),
"cancelled" => Some(ReplayStatus::Cancelled),
_ => None,
}
}
}
/// Replay Session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplaySession {
pub id: i64,
pub session_id: String,
pub session_name: Option<String>,
pub replay_type: ReplayType,
pub source_filter: JsonValue,
pub config: JsonValue,
pub status: ReplayStatus,
pub total_commands: i32,
pub processed_commands: i32,
pub succeeded_commands: i32,
pub failed_commands: i32,
pub skipped_commands: i32,
pub comparison_results: JsonValue,
pub started_at: Option<DateTime<Utc>>,
pub completed_at: Option<DateTime<Utc>>,
pub duration_secs: Option<f64>,
pub error_message: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub user_id: Option<i64>,
}
/// 创建 Replay Session 请求
#[derive(Debug, Clone, Deserialize)]
pub struct CreateReplaySessionRequest {
pub session_name: Option<String>,
pub replay_type: ReplayType,
pub source_filter: JsonValue,
pub config: Option<JsonValue>,
}
/// Replay Session 进度
#[derive(Debug, Clone, Serialize)]
pub struct ReplayProgress {
pub session_id: String,
pub status: ReplayStatus,
pub progress: ReplayProgressInfo,
pub performance: Option<ReplayPerformance>,
pub comparison: Option<ReplayComparison>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ReplayProgressInfo {
pub total: i32,
pub processed: i32,
pub succeeded: i32,
pub failed: i32,
pub percentage: f64,
}
#[derive(Debug, Clone, Serialize)]
pub struct ReplayPerformance {
pub started_at: DateTime<Utc>,
pub elapsed_secs: f64,
pub avg_command_time_secs: f64,
}
#[derive(Debug, Clone, Serialize)]
pub struct ReplayComparison {
pub match_count: i32,
pub mismatch_count: i32,
pub error_count: i32,
pub match_rate: f64,
}
/// Replay Command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplayCommand {
pub id: i64,
pub session_id: String,
pub original_command_id: String,
pub replay_command_id: Option<String>,
pub status: String,
pub original_job_type: Option<String>,
pub original_file_path: Option<String>,
pub original_file_uuid: Option<String>,
pub original_payload: Option<JsonValue>,
pub original_result: Option<JsonValue>,
pub replay_result: Option<JsonValue>,
pub comparison_status: Option<String>,
pub differences: Option<JsonValue>,
pub original_duration_secs: Option<f64>,
pub replay_duration_secs: Option<f64>,
pub error_message: Option<String>,
pub retry_count: i32,
pub started_at: Option<DateTime<Utc>>,
pub completed_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
+1 -2
View File
@@ -23,8 +23,7 @@ impl ThumbnailExtractor {
}
pub fn extract(&self, video_path: &str, uuid: &str) -> Result<ThumbnailResult> {
let script_path = crate::core::path_utils::scripts_dir()
.join("thumbnail_extractor.py");
let script_path = crate::core::path_utils::scripts_dir().join("thumbnail_extractor.py");
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
+4 -2
View File
@@ -7,7 +7,8 @@ pub const JPEG_EOI_MARKER: [u8; 2] = [0xFF, 0xD9];
/// 驗證 file_uuid:schema 為 varchar(32) 的 simple 格式 UUID
pub fn is_valid_file_uuid(s: &str) -> bool {
s.len() == 32
&& s.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
&& s.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
}
/// 驗證 chunk_id:區塊快取檔名
@@ -15,7 +16,8 @@ pub fn is_valid_file_uuid(s: &str) -> bool {
pub fn is_valid_chunk_id(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 128
&& s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}
/// Validate JPEG magic bytes
+5 -2
View File
@@ -4,6 +4,7 @@ use tracing::{info, warn};
use crate::core::config;
use crate::core::db::PostgresDb;
use crate::core::db::qdrant_db::new_http_client;
#[derive(Debug, Deserialize)]
struct TmdbSearchResult {
@@ -299,7 +300,9 @@ pub async fn create_identities_from_data(
// Step 4: Trigger background embedding extraction
if identities_created > 0 {
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());
let schema = crate::core::config::DATABASE_SCHEMA.clone();
@@ -385,7 +388,7 @@ pub async fn probe_movie(
info!("[TMDB] Searching for movie: {}", movie_name);
let client = reqwest::Client::new();
let client = new_http_client();
// Step 1: Search movie
let search_url = format!(
+3 -2
View File
@@ -20,8 +20,9 @@ pub struct QwenVLManager {
impl QwenVLManager {
pub fn new() -> Self {
let models_dir = crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
Self {
port: 8086,
model_path: models_dir.join("Qwen3VL-8B-Instruct-Q8_0.gguf"),
+110
View File
@@ -0,0 +1,110 @@
use crate::core::vlm::error::VLMError;
use base64::{engine::general_purpose, Engine as _};
use reqwest::Client;
use std::fs;
use std::time::Duration;
/// VLM 客户端(调用 llama.cpp API)
pub struct VLMClient {
http_client: Client,
base_url: String,
model: String,
}
impl VLMClient {
/// 创建新的 VLM 客户端
pub fn new() -> Self {
Self {
http_client: Client::builder()
.timeout(Duration::from_secs(120))
.build()
.expect("Failed to create HTTP client"),
base_url: std::env::var("MOMENTRY_LLM_VISION_URL")
.unwrap_or_else(|_| "http://127.0.0.1:8080/v1/chat/completions".to_string()),
model: std::env::var("MOMENTRY_LLM_VISION_MODEL")
.unwrap_or_else(|_| "gemma-4-12b-it".to_string()),
}
}
/// 生成文本描述
pub async fn generate(
&self,
image_path: &str,
prompt: &str,
max_tokens: usize,
) -> Result<String, VLMError> {
// 1. 读取图片并 Base64 编码
let image_data = fs::read(image_path)
.map_err(|e| VLMError::ImageReadFailed(image_path.to_string(), e))?;
let image_base64 = general_purpose::STANDARD.encode(&image_data);
// 2. 构建请求
let request = serde_json::json!({
"model": self.model,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": format!("data:image/jpeg;base64,{}", image_base64)
}
}
]
}
],
"max_tokens": max_tokens,
"temperature": 0.1
});
// 3. 调用 API
let response = self
.http_client
.post(&self.base_url)
.json(&request)
.send()
.await?;
// 4. 检查响应状态
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(VLMError::WorkerError(format!("HTTP {} - {}", status, body)));
}
// 5. 解析响应
let json: serde_json::Value = response.json().await?;
let text = json["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| VLMError::InvalidResponse)?
.to_string();
Ok(text)
}
/// 测试连接
pub async fn test_connection(&self) -> Result<bool, VLMError> {
let response = self
.http_client
.get(&self.base_url.replace("/v1/chat/completions", "/health"))
.send()
.await;
match response {
Ok(resp) => Ok(resp.status().is_success()),
Err(_) => Ok(false),
}
}
}
impl Default for VLMClient {
fn default() -> Self {
Self::new()
}
}
+228
View File
@@ -0,0 +1,228 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use crate::core::vlm::error::VLMError;
use crate::core::vlm::types::{VLMMessage, VLMRequestType, VLMStatus};
use sqlx::PgPool;
/// VLM Consumer(消费者)
pub struct VLMConsumer {
db: PgPool,
consumer_id: String,
max_batch_size: usize,
}
impl VLMConsumer {
/// 创建新的 Consumer
pub fn new(db: PgPool, consumer_id: String, max_batch_size: usize) -> Self {
Self {
db,
consumer_id,
max_batch_size,
}
}
/// 拉取消息(类似 Kafka Consumer.poll())
pub async fn poll(&mut self) -> Result<Vec<VLMMessage>, VLMError> {
// 1. 查询待处理消息(按优先级、创建时间排序)
let rows = sqlx::query!(
r#"
SELECT
id as offset,
request_type,
priority,
payload
FROM vlm_requests
WHERE status = 'pending'
ORDER BY priority ASC, created_at ASC
LIMIT $1
FOR UPDATE SKIP LOCKED
"#,
self.max_batch_size as i64,
)
.fetch_all(&self.db)
.await?;
// 2. 转换为 VLMMessage
let mut messages = Vec::with_capacity(rows.len());
for row in rows {
let request_type = VLMRequestType::from_str(&row.request_type)
.ok_or_else(|| VLMError::InvalidRequestType(row.request_type.clone()))?;
messages.push(VLMMessage {
offset: row.offset,
request_type,
priority: row.priority.unwrap_or(1),
payload: row.payload,
});
}
// 3. 标记为 processing
if !messages.is_empty() {
let ids: Vec<i64> = messages.iter().map(|m| m.offset).collect();
sqlx::query!(
r#"
UPDATE vlm_requests
SET status = 'processing', started_at = NOW()
WHERE id = ANY($1)
"#,
&ids,
)
.execute(&self.db)
.await?;
// 4. 更新 Consumer offset
let offset = messages.last().unwrap().offset;
self.update_offset(offset).await?;
}
Ok(messages)
}
/// 标记消息完成
pub async fn complete(
&mut self,
offset: i64,
result: String,
processing_time_ms: u64,
) -> Result<(), VLMError> {
sqlx::query!(
r#"
UPDATE vlm_requests
SET
status = 'completed',
result = $1,
processing_time_ms = $2,
completed_at = NOW()
WHERE id = $3
"#,
result,
processing_time_ms as i64,
offset,
)
.execute(&self.db)
.await?;
// 更新统计
self.update_stats(1, 1, 0).await?;
Ok(())
}
/// 标记消息失败
pub async fn fail(
&mut self,
offset: i64,
error: String,
max_retries: u32,
) -> Result<(), VLMError> {
// 1. 获取当前消息
let message = sqlx::query!(
r#"
SELECT id, request_type, payload, retry_count, priority
FROM vlm_requests
WHERE id = $1
"#,
offset,
)
.fetch_one(&self.db)
.await?;
// 2. 检查重试次数
if message.retry_count.unwrap_or(0) < max_retries as i32 {
// 重试:增加 retry_count,重置为 pending
sqlx::query!(
r#"
UPDATE vlm_requests
SET
status = 'pending',
retry_count = retry_count + 1,
error = $1
WHERE id = $2
"#,
error,
offset,
)
.execute(&self.db)
.await?;
} else {
// 发送到死信队列
sqlx::query!(
r#"
INSERT INTO vlm_dlq (original_id, original_request_type, original_priority, original_payload, error, retry_count)
VALUES ($1, $2, $3, $4, $5, $6)
"#,
message.id,
message.request_type,
message.priority,
message.payload,
error,
message.retry_count,
)
.execute(&self.db)
.await?;
// 标记原消息为 failed
sqlx::query!(
r#"
UPDATE vlm_requests
SET status = 'failed', error = $1, completed_at = NOW()
WHERE id = $2
"#,
error,
offset,
)
.execute(&self.db)
.await?;
}
// 更新统计
self.update_stats(1, 0, 1).await?;
Ok(())
}
/// 更新 Consumer offset
async fn update_offset(&mut self, offset: i64) -> Result<(), VLMError> {
sqlx::query!(
r#"
UPDATE vlm_consumer_offsets
SET current_offset = $1, last_poll_at = NOW()
WHERE consumer_id = $2
"#,
offset,
self.consumer_id,
)
.execute(&self.db)
.await?;
Ok(())
}
/// 更新统计信息
async fn update_stats(
&mut self,
total: i64,
succeeded: i64,
failed: i64,
) -> Result<(), VLMError> {
sqlx::query!(
r#"
UPDATE vlm_consumer_offsets
SET
total_processed = total_processed + $1,
total_succeeded = total_succeeded + $2,
total_failed = total_failed + $3
WHERE consumer_id = $4
"#,
total,
succeeded,
failed,
self.consumer_id,
)
.execute(&self.db)
.await?;
Ok(())
}
}
+58
View File
@@ -0,0 +1,58 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum VLMError {
#[error("Queue is full")]
QueueFull,
#[error("Request not found: {0}")]
RequestNotFound(i64),
#[error("Invalid payload: {0}")]
InvalidPayload(String),
#[error("Invalid request type: {0}")]
InvalidRequestType(String),
#[error("Invalid status: {0}")]
InvalidStatus(String),
#[error("Failed to read image '{0}': {1}")]
ImageReadFailed(String, #[source] std::io::Error),
#[error("Request failed: {0}")]
RequestFailed(#[from] reqwest::Error),
#[error("Failed to parse response: {0}")]
ParseFailed(#[source] serde_json::Error),
#[error("Invalid response format")]
InvalidResponse,
#[error("Timeout after {0} seconds")]
Timeout(u64),
#[error("Database error: {0}")]
DatabaseError(#[from] sqlx::Error),
#[error("Worker error: {0}")]
WorkerError(String),
#[error("Channel closed")]
ChannelClosed,
#[error("Retry limit exceeded")]
RetryLimitExceeded,
}
impl VLMError {
/// 是否可重试
pub fn is_retryable(&self) -> bool {
match self {
VLMError::Timeout(_) => true,
VLMError::RequestFailed(_) => true,
VLMError::DatabaseError(_) => true,
_ => false,
}
}
}
+85
View File
@@ -0,0 +1,85 @@
pub mod client;
pub mod consumer;
pub mod error;
pub mod producer;
pub mod types;
pub mod worker;
pub use client::VLMClient;
pub use consumer::VLMConsumer;
pub use error::VLMError;
pub use producer::VLMProducer;
pub use types::{
VLMMessage, VLMQueueStatus, VLMRequest, VLMRequestType, VLMResult, VLMStats, VLMStatus,
};
pub use worker::{start_workers, VLMWorker};
use sqlx::PgPool;
use std::sync::Arc;
use once_cell::sync::OnceCell;
/// Global VLM Producer instance
static VLM_PRODUCER: OnceCell<Arc<VLMProducer>> = OnceCell::new();
/// Initialize global VLM Producer
pub fn init_producer(db: PgPool) {
let producer = Arc::new(VLMProducer::new(db));
let _ = VLM_PRODUCER.set(producer);
}
/// Get global VLM Producer
pub fn get_producer() -> Option<Arc<VLMProducer>> {
VLM_PRODUCER.get().cloned()
}
/// 初始化 VLM 队列系统
pub async fn init(db: PgPool) -> Result<(), error::VLMError> {
// 1. 创建表(如果不存在)
create_tables_if_not_exists(&db).await?;
// 2. 启动 Workers
let num_workers = std::env::var("MOMENTRY_VLM_MAX_CONCURRENT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(3);
worker::start_workers(db, num_workers, 2).await;
Ok(())
}
/// 创建表(如果不存在)
async fn create_tables_if_not_exists(db: &PgPool) -> Result<(), error::VLMError> {
// 检查表是否存在
let table_exists: bool = sqlx::query_scalar(
r#"
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_name = 'vlm_requests'
)
"#,
)
.fetch_one(db)
.await?;
if !table_exists {
// 读取迁移文件并执行
tracing::info!("Creating VLM queue tables...");
// 这里简化处理,实际应该使用 sqlx-cli 运行迁移
// 暂时使用硬编码 SQL(从迁移文件提取)
let sql = include_str!("../../../migrations/20261011_vlm_queue.sql");
// 分割 SQL 语句并逐个执行
for statement in sql.split(';') {
let statement = statement.trim();
if !statement.is_empty() {
sqlx::query(statement).execute(db).await?;
}
}
tracing::info!("VLM queue tables created successfully");
}
Ok(())
}
+174
View File
@@ -0,0 +1,174 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use crate::core::vlm::error::VLMError;
use crate::core::vlm::types::{VLMRequest, VLMRequestType};
use sqlx::PgPool;
use serde_json::Value as JsonValue;
/// VLM Producer(生产者)
pub struct VLMProducer {
db: PgPool,
}
impl VLMProducer {
/// 创建新的 Producer
pub fn new(db: PgPool) -> Self {
Self { db }
}
/// 追加单条消息到队列(类似 Kafka Producer.send())
pub async fn append(&self, request: VLMRequest) -> Result<i64, VLMError> {
// 1. 写入消息(追加写入,PostgreSQL 自动分配 Offset)
let result = sqlx::query!(
r#"
INSERT INTO vlm_requests (request_type, priority, payload, status)
VALUES ($1, $2, $3, 'pending')
RETURNING id
"#,
request.request_type.as_str(),
request.priority,
request.payload,
)
.fetch_one(&self.db)
.await?;
// 2. 返回 Offset(id)
Ok(result.id)
}
/// 批量追加消息(优化性能)
pub async fn append_batch(
&self,
requests: Vec<VLMRequest>,
) -> Result<Vec<i64>, VLMError> {
let mut offsets = Vec::with_capacity(requests.len());
// 使用事务批量插入
let mut tx = self.db.begin().await?;
for request in requests {
let result = sqlx::query!(
r#"
INSERT INTO vlm_requests (request_type, priority, payload, status)
VALUES ($1, $2, $3, 'pending')
RETURNING id
"#,
request.request_type.as_str(),
request.priority,
request.payload,
)
.fetch_one(&mut *tx)
.await?;
offsets.push(result.id);
}
tx.commit().await?;
Ok(offsets)
}
/// 便捷方法:提交 Agent VLM 请求(高优先级)
pub async fn submit_agent_vlm(
&self,
image_path: String,
prompt: String,
max_tokens: usize,
) -> Result<i64, VLMError> {
let request = VLMRequest::agent_vlm(image_path, prompt, max_tokens);
self.append(request).await
}
/// 便捷方法:提交 Scene VLM 请求
pub async fn submit_scene_vlm(
&self,
image_path: String,
prompt: String,
max_tokens: usize,
file_uuid: String,
scene_index: usize,
) -> Result<i64, VLMError> {
let request = VLMRequest::scene_vlm(image_path, prompt, max_tokens, file_uuid, scene_index);
self.append(request).await
}
/// 便捷方法:提交 Face VLM 请求
pub async fn submit_face_vlm(
&self,
image_path: String,
prompt: String,
max_tokens: usize,
) -> Result<i64, VLMError> {
let request = VLMRequest::face_vlm(image_path, prompt, max_tokens);
self.append(request).await
}
/// 等待结果(轮询数据库)
pub async fn wait_for_result(
&self,
offset: i64,
timeout_secs: u64,
) -> Result<String, VLMError> {
let start = std::time::Instant::now();
let poll_interval = std::time::Duration::from_millis(500);
loop {
// 查询结果
let row = sqlx::query!(
r#"
SELECT status, result, error
FROM vlm_requests
WHERE id = $1
"#,
offset,
)
.fetch_optional(&self.db)
.await?;
match row {
Some(row) => {
let status = crate::core::vlm::types::VLMStatus::from_str(&row.status)
.ok_or_else(|| VLMError::InvalidStatus(row.status.clone()))?;
match status {
crate::core::vlm::types::VLMStatus::Completed => {
return Ok(row.result.unwrap_or_default());
}
crate::core::vlm::types::VLMStatus::Failed => {
return Err(VLMError::WorkerError(
row.error.unwrap_or_else(|| "Unknown error".to_string()),
));
}
crate::core::vlm::types::VLMStatus::Timeout => {
return Err(VLMError::Timeout(timeout_secs));
}
_ => {
// Pending or Processing, continue polling
}
}
}
None => {
return Err(VLMError::RequestNotFound(offset));
}
}
// 检查超时
if start.elapsed().as_secs() >= timeout_secs {
return Err(VLMError::Timeout(timeout_secs));
}
// 等待下次轮询
tokio::time::sleep(poll_interval).await;
}
}
/// 提交并等待结果
pub async fn submit_and_wait(
&self,
request: VLMRequest,
timeout_secs: u64,
) -> Result<String, VLMError> {
let offset = self.append(request).await?;
self.wait_for_result(offset, timeout_secs).await
}
}
+253
View File
@@ -0,0 +1,253 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
/// VLM 请求类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VLMRequestType {
/// Agent 调用 VLM(高优先级,P0)
AgentVLMDetection,
/// Scene VLM(普通优先级,P1)
SceneVLM,
/// Face Track VLM(普通优先级,P1)
FaceVLM,
}
impl VLMRequestType {
/// 获取优先级(数值越小优先级越高)
pub fn priority(&self) -> i32 {
match self {
VLMRequestType::AgentVLMDetection => 0, // 最高优先级
VLMRequestType::SceneVLM => 1,
VLMRequestType::FaceVLM => 1,
}
}
/// 转换为字符串
pub fn as_str(&self) -> &'static str {
match self {
VLMRequestType::AgentVLMDetection => "agent_vlm",
VLMRequestType::SceneVLM => "scene_vlm",
VLMRequestType::FaceVLM => "face_vlm",
}
}
/// 从字符串解析
pub fn from_str(s: &str) -> Option<Self> {
match s {
"agent_vlm" => Some(VLMRequestType::AgentVLMDetection),
"scene_vlm" => Some(VLMRequestType::SceneVLM),
"face_vlm" => Some(VLMRequestType::FaceVLM),
_ => None,
}
}
}
/// VLM 请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VLMRequest {
/// 请求唯一 ID
pub id: i64,
/// 请求类型
pub request_type: VLMRequestType,
/// 优先级(0 = 最高)
pub priority: i32,
/// 消息内容
pub payload: JsonValue,
/// 创建时间
pub created_at: DateTime<Utc>,
}
impl VLMRequest {
/// 创建新请求
pub fn new(request_type: VLMRequestType, payload: JsonValue) -> Self {
Self {
id: 0, // 将由数据库分配
request_type,
priority: request_type.priority(),
payload,
created_at: Utc::now(),
}
}
/// 创建 Agent VLM 请求(高优先级)
pub fn agent_vlm(image_path: String, prompt: String, max_tokens: usize) -> Self {
Self::new(
VLMRequestType::AgentVLMDetection,
serde_json::json!({
"image_path": image_path,
"prompt": prompt,
"max_tokens": max_tokens,
}),
)
}
/// 创建 Scene VLM 请求
pub fn scene_vlm(
image_path: String,
prompt: String,
max_tokens: usize,
file_uuid: String,
scene_index: usize,
) -> Self {
Self::new(
VLMRequestType::SceneVLM,
serde_json::json!({
"image_path": image_path,
"prompt": prompt,
"max_tokens": max_tokens,
"file_uuid": file_uuid,
"scene_index": scene_index,
}),
)
}
/// 创建 Face VLM 请求
pub fn face_vlm(image_path: String, prompt: String, max_tokens: usize) -> Self {
Self::new(
VLMRequestType::FaceVLM,
serde_json::json!({
"image_path": image_path,
"prompt": prompt,
"max_tokens": max_tokens,
}),
)
}
}
/// VLM 状态
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VLMStatus {
/// 等待中
Pending,
/// 处理中
Processing,
/// 已完成
Completed,
/// 失败
Failed,
/// 超时
Timeout,
}
impl VLMStatus {
/// 转换为字符串
pub fn as_str(&self) -> &'static str {
match self {
VLMStatus::Pending => "pending",
VLMStatus::Processing => "processing",
VLMStatus::Completed => "completed",
VLMStatus::Failed => "failed",
VLMStatus::Timeout => "timeout",
}
}
/// 从字符串解析
pub fn from_str(s: &str) -> Option<Self> {
match s {
"pending" => Some(VLMStatus::Pending),
"processing" => Some(VLMStatus::Processing),
"completed" => Some(VLMStatus::Completed),
"failed" => Some(VLMStatus::Failed),
"timeout" => Some(VLMStatus::Timeout),
_ => None,
}
}
}
/// VLM 结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VLMResult {
/// 请求 ID
pub request_id: i64,
/// 状态
pub status: VLMStatus,
/// 生成的文本(成功时)
pub text: Option<String>,
/// 错误信息(失败时)
pub error: Option<String>,
/// 处理时间(毫秒)
pub processing_time_ms: u64,
/// 完成时间
pub completed_at: DateTime<Utc>,
}
/// VLM 队列状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VLMQueueStatus {
/// 高优先级队列长度
pub high_priority_count: usize,
/// 普通优先级队列长度
pub normal_priority_count: usize,
/// 当前正在处理的请求
pub current_request: Option<VLMRequest>,
/// 当前并发数
pub current_concurrent: usize,
/// 最大并发数
pub max_concurrent: usize,
/// 是否健康
pub is_healthy: bool,
/// 平均处理时间(毫秒)
pub avg_processing_time_ms: f64,
/// 最后更新时间
pub last_updated: DateTime<Utc>,
}
/// VLM 消息(用于 Consumer 拉取)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VLMMessage {
/// Offset
pub offset: i64,
/// 请求类型
pub request_type: VLMRequestType,
/// 优先级
pub priority: i32,
/// 消息内容
pub payload: JsonValue,
}
/// VLM 队列统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VLMStats {
/// 请求类型
pub request_type: String,
/// 状态
pub status: String,
/// 数量
pub count: i64,
/// 平均处理时间(毫秒)
pub avg_processing_time_ms: Option<f64>,
/// 最小处理时间(毫秒)
pub min_processing_time_ms: Option<i64>,
/// 最大处理时间(毫秒)
pub max_processing_time_ms: Option<i64>,
}
+169
View File
@@ -0,0 +1,169 @@
// MarkBase Queue Protocol - Independent Implementation
// This is NOT compatible with Apache Kafka protocol or API.
use crate::core::vlm::client::VLMClient;
use crate::core::vlm::consumer::VLMConsumer;
use crate::core::vlm::error::VLMError;
use crate::core::vlm::types::VLMMessage;
use sqlx::PgPool;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::time::Duration;
use tracing::{debug, error, info, warn};
/// VLM Worker
pub struct VLMWorker {
consumer_id: String,
consumer: VLMConsumer,
client: VLMClient,
max_retries: u32,
running: Arc<AtomicBool>,
}
impl VLMWorker {
/// 创建新的 Worker
pub fn new(db: PgPool, consumer_id: String, max_retries: u32) -> Self {
Self {
consumer_id: consumer_id.clone(),
consumer: VLMConsumer::new(db, consumer_id, 1), // 每次处理 1 条消息
client: VLMClient::new(),
max_retries,
running: Arc::new(AtomicBool::new(false)),
}
}
/// 启动 Worker
pub async fn start(&mut self) {
self.running.store(true, Ordering::SeqCst);
info!("VLM Worker {} started", self.consumer_id);
while self.running.load(Ordering::SeqCst) {
// 1. 主动拉取消息(回压控制)
match self.consumer.poll().await {
Ok(messages) if !messages.is_empty() => {
debug!(
"Worker {} received {} messages",
self.consumer_id,
messages.len()
);
// 2. 处理每条消息
for message in messages {
if !self.running.load(Ordering::SeqCst) {
break;
}
if let Err(e) = self.process_message(message).await {
error!(
"Worker {} failed to process message: {}",
self.consumer_id, e
);
}
}
}
Ok(_) => {
// 队列为空,休眠一段时间
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(e) => {
error!("Worker {} poll error: {}", self.consumer_id, e);
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
}
info!("VLM Worker {} stopped", self.consumer_id);
}
/// 处理单条消息
async fn process_message(&mut self, message: VLMMessage) -> Result<(), VLMError> {
let start = std::time::Instant::now();
// 1. 解析 payload
let image_path = message.payload["image_path"]
.as_str()
.ok_or_else(|| VLMError::InvalidPayload("missing image_path".to_string()))?
.to_string();
let prompt = message.payload["prompt"]
.as_str()
.ok_or_else(|| VLMError::InvalidPayload("missing prompt".to_string()))?
.to_string();
let max_tokens = message.payload["max_tokens"]
.as_u64()
.unwrap_or(800) as usize;
debug!(
"Worker {} processing message {}: {}",
self.consumer_id,
message.offset,
message.request_type.as_str()
);
// 2. 调用 VLM API
let result = self.client.generate(&image_path, &prompt, max_tokens).await;
let processing_time_ms = start.elapsed().as_millis() as u64;
// 3. 处理结果
match result {
Ok(text) => {
// 成功
self.consumer
.complete(message.offset, text, processing_time_ms)
.await?;
debug!(
"Worker {} completed message {} in {}ms",
self.consumer_id,
message.offset,
processing_time_ms
);
}
Err(e) => {
// 失败
warn!(
"Worker {} failed message {}: {}",
self.consumer_id,
message.offset,
e
);
self.consumer
.fail(message.offset, e.to_string(), self.max_retries)
.await?;
}
}
Ok(())
}
/// 停止 Worker
pub fn stop(&self) {
self.running.store(false, Ordering::SeqCst);
}
}
/// 启动多个 Worker
pub async fn start_workers(db: PgPool, num_workers: usize, max_retries: u32) -> Vec<Arc<AtomicBool>> {
let mut handles = Vec::new();
let running_flags = Vec::new();
for i in 0..num_workers {
let db_clone = db.clone();
let consumer_id = format!("worker_{}", i);
let max_retries_clone = max_retries;
let handle = tokio::spawn(async move {
let mut worker = VLMWorker::new(db_clone, consumer_id, max_retries_clone);
worker.start().await;
});
handles.push(handle);
}
// 不等待完成,让 Worker 在后台运行
info!("Started {} VLM workers", num_workers);
running_flags
}