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:
@@ -0,0 +1,487 @@
|
||||
# Agent Search 统一智能搜尋介面设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 正式命名
|
||||
|
||||
---
|
||||
|
||||
## 🎯 命名规范
|
||||
|
||||
### 顶层统一介面
|
||||
|
||||
**名称**: **Agent Search** (统一智能搜尋介面)
|
||||
|
||||
**定位**:
|
||||
- 顶层统一入口
|
||||
- 智能路由
|
||||
- 用户无需选择搜索类型
|
||||
- 系统自动选择最佳搜索方式
|
||||
|
||||
---
|
||||
|
||||
### 底层搜索类型(保持不变)
|
||||
|
||||
Agent Search 内部调用以下 5 种搜索类型:
|
||||
|
||||
| 类型 | 技术 | 特点 | 用例 |
|
||||
|------|------|------|------|
|
||||
| **Keyword** | BM25 + FTS | 精确匹配,快速 | "interview with Obama" |
|
||||
| **Semantic** | Vector Embedding | 语义理解,模糊匹配 | "people discussing politics" |
|
||||
| **Visual** | VLM + CLIP | 视觉内容,场景描述 | "sunset beach" |
|
||||
| **Agent** | LLM + RAG | 复杂查询,推理 | "compare Obama and Biden on healthcare" |
|
||||
| **People** | Face Identity | 人物识别,身份关联 | "videos with Barack Obama" |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构层次
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Agent Search (统一介面) │
|
||||
│ ├─ Query Analyzer (智能路由) │
|
||||
│ ├─ Strategy Selector (策略选择) │
|
||||
│ ├─ Result Merger (结果合并) │
|
||||
│ └─ Summary Generator (摘要生成) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
├─────────┬─────────┬─────────┬─────────┐
|
||||
▼ ▼ ▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Keyword │ │Semantic│ │ Visual │ │ Agent │ │ People │
|
||||
│ Search │ │ Search │ │ Search │ │ Search │ │ Search │
|
||||
└────────┘ └────────┘ └────────┘ └────────┘ └────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💬 Agent Search Service
|
||||
|
||||
### 核心功能
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::messenger::types::{Message, MessageSource, MessagePriority, MessageType, DeliveryOptions};
|
||||
use crate::core::llm::LLMClient;
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Agent Search 服务(统一智能搜尋介面)
|
||||
pub struct AgentSearchService {
|
||||
messenger: Messenger,
|
||||
llm_client: LLMClient,
|
||||
query_analyzer: QueryAnalyzer,
|
||||
}
|
||||
|
||||
impl AgentSearchService {
|
||||
pub fn new(db: sqlx::PgPool, llm_client: LLMClient) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db),
|
||||
llm_client: llm_client.clone(),
|
||||
query_analyzer: QueryAnalyzer::new(llm_client),
|
||||
}
|
||||
}
|
||||
|
||||
/// Agent Search 入口(智能路由)
|
||||
pub async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
// 1. 分析查询意图
|
||||
let intent = self.query_analyzer.analyze(query, context.clone()).await?;
|
||||
|
||||
debug!(
|
||||
query = %query,
|
||||
intent = ?intent.search_types,
|
||||
confidence = intent.confidence,
|
||||
"Query intent analyzed"
|
||||
);
|
||||
|
||||
// 2. 根据意图选择搜索策略
|
||||
let strategy = self.select_strategy(&intent);
|
||||
|
||||
// 3. 执行搜索(可能并行多个类型)
|
||||
let results = self.execute_strategy(&strategy, query, context.clone()).await?;
|
||||
|
||||
// 4. 合并结果
|
||||
let response = self.merge_results(results, query, intent).await?;
|
||||
|
||||
info!(
|
||||
query = %query,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
total_results = response.total_count,
|
||||
"Agent Search completed"
|
||||
);
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// 选择搜索策略
|
||||
fn select_strategy(&self, intent: &QueryIntent) -> SearchStrategy {
|
||||
// 实现细节...
|
||||
match intent.primary_type {
|
||||
SearchType::Keyword if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Keyword)
|
||||
}
|
||||
SearchType::Semantic if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Semantic)
|
||||
}
|
||||
SearchType::Visual if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Visual)
|
||||
}
|
||||
SearchType::People if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::People)
|
||||
}
|
||||
SearchType::Agent if intent.confidence > 0.7 => {
|
||||
SearchStrategy::Single(SearchType::Agent)
|
||||
}
|
||||
_ => {
|
||||
// 混合策略
|
||||
let mut types = Vec::new();
|
||||
if intent.scores.keyword > 0.3 {
|
||||
types.push((SearchType::Keyword, intent.scores.keyword));
|
||||
}
|
||||
if intent.scores.semantic > 0.3 {
|
||||
types.push((SearchType::Semantic, intent.scores.semantic));
|
||||
}
|
||||
if intent.scores.visual > 0.3 {
|
||||
types.push((SearchType::Visual, intent.scores.visual));
|
||||
}
|
||||
if intent.scores.people > 0.3 {
|
||||
types.push((SearchType::People, intent.scores.people));
|
||||
}
|
||||
if types.is_empty() {
|
||||
types.push((SearchType::Agent, 1.0));
|
||||
}
|
||||
SearchStrategy::Hybrid(types)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行搜索策略
|
||||
async fn execute_strategy(
|
||||
&self,
|
||||
strategy: &SearchStrategy,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<Vec<SearchResponse>> {
|
||||
// 实现细节...
|
||||
match strategy {
|
||||
SearchStrategy::Single(search_type) => {
|
||||
let response = self.execute_single_search(search_type, query, context).await?;
|
||||
Ok(vec![response])
|
||||
}
|
||||
SearchStrategy::Hybrid(types) => {
|
||||
// 并行执行多个搜索
|
||||
let mut handles = Vec::new();
|
||||
for (search_type, weight) in types {
|
||||
let handle = self.execute_single_search(search_type, query, context.clone());
|
||||
handles.push((search_type.clone(), weight, handle));
|
||||
}
|
||||
|
||||
// 收集结果
|
||||
let mut results = Vec::new();
|
||||
for (search_type, _weight, handle) in handles {
|
||||
match handle.await {
|
||||
Ok(response) => {
|
||||
results.push(response);
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(search_type = ?search_type, error = ?e, "Search failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行单一类型搜索
|
||||
async fn execute_single_search(
|
||||
&self,
|
||||
search_type: &SearchType,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let request = SearchRequest::new(query.to_string(), search_type.clone())
|
||||
.with_filters(context.clone().map(|c| c.filters).unwrap_or_default())
|
||||
.with_options(context.clone().map(|c| c.options).unwrap_or_default());
|
||||
|
||||
// 发送到对应的搜索队列
|
||||
let queue_name = format!("search.{}", serde_json::to_string(search_type)?.to_lowercase());
|
||||
let request_id = self.messenger.send_search_request(&request).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.messenger.get_search_result(&request_id).await? {
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 合并搜索结果
|
||||
async fn merge_results(
|
||||
&self,
|
||||
results: Vec<SearchResponse>,
|
||||
query: &str,
|
||||
intent: QueryIntent,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
let mut all_results = Vec::new();
|
||||
let mut seen_ids = std::collections::HashSet::new();
|
||||
|
||||
// 收集所有结果
|
||||
for response in results {
|
||||
for result in response.results {
|
||||
if !seen_ids.contains(&result.id) {
|
||||
seen_ids.insert(result.id.clone());
|
||||
all_results.push(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重新评分和排序
|
||||
for result in &mut all_results {
|
||||
result.score = result.score * (0.5 + 0.5 * intent.confidence);
|
||||
}
|
||||
all_results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
|
||||
|
||||
// 生成摘要
|
||||
let summary = self.generate_summary(query, &all_results).await?;
|
||||
|
||||
Ok(AgentSearchResponse {
|
||||
query: query.to_string(),
|
||||
intent,
|
||||
results: all_results,
|
||||
total_count: all_results.len() as i64,
|
||||
summary,
|
||||
took_ms: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// 生成摘要
|
||||
async fn generate_summary(&self, query: &str, results: &[SearchResult]) -> CommandResult<String> {
|
||||
if results.is_empty() {
|
||||
return Ok("No results found.".to_string());
|
||||
}
|
||||
|
||||
let prompt = format!(
|
||||
"Summarize search results for query '{}' in 2-3 sentences. Found {} results.",
|
||||
query,
|
||||
results.len()
|
||||
);
|
||||
|
||||
self.llm_client.chat(&prompt).await
|
||||
}
|
||||
|
||||
/// 对话式搜索
|
||||
pub async fn conversational_search(
|
||||
&self,
|
||||
conversation_id: &str,
|
||||
query: &str,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
// 获取对话历史
|
||||
let history = self.get_conversation_history(conversation_id).await?;
|
||||
|
||||
let context = SearchContext {
|
||||
conversation_id: Some(conversation_id.to_string()),
|
||||
conversation_history: history,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = self.search(query, Some(context)).await?;
|
||||
|
||||
// 更新对话历史
|
||||
self.update_conversation(conversation_id, query, &response).await?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn get_conversation_history(&self, _conversation_id: &str) -> CommandResult<Vec<Message>> {
|
||||
// TODO: 从数据库获取
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn update_conversation(
|
||||
&self,
|
||||
_conversation_id: &str,
|
||||
_query: &str,
|
||||
_response: &AgentSearchResponse,
|
||||
) -> CommandResult<()> {
|
||||
// TODO: 更新到数据库
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 API 端点
|
||||
|
||||
```rust
|
||||
// POST /api/v1/agent/search
|
||||
pub async fn agent_search(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<AgentSearchRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
let context = SearchContext {
|
||||
user_id: Some(auth.user_id),
|
||||
..request.context.unwrap_or_default()
|
||||
};
|
||||
|
||||
let response = agent_search_service.search(&request.query, Some(context)).await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
// POST /api/v1/agent/search/conversation
|
||||
pub async fn agent_search_conversation(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<ConversationSearchRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
let response = agent_search_service
|
||||
.conversational_search(&request.conversation_id, &request.query)
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据模型
|
||||
|
||||
```rust
|
||||
/// Agent Search 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchRequest {
|
||||
pub query: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context: Option<SearchContext>,
|
||||
}
|
||||
|
||||
/// Agent Search 响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchResponse {
|
||||
pub query: String,
|
||||
pub intent: QueryIntent,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub summary: String,
|
||||
pub took_ms: i64,
|
||||
}
|
||||
|
||||
/// 查询意图
|
||||
#[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,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 用户介面
|
||||
|
||||
### 统一搜索框
|
||||
|
||||
```html
|
||||
<div class="agent-search">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Ask anything about your videos..."
|
||||
class="search-input"
|
||||
/>
|
||||
<div class="search-hints">
|
||||
<p>Try:</p>
|
||||
<span class="hint">"interview with Obama"</span>
|
||||
<span class="hint">"people discussing politics"</span>
|
||||
<span class="hint">"sunset at beach"</span>
|
||||
<span class="hint">"compare Obama and Biden on healthcare"</span>
|
||||
<span class="hint">"videos with Barack Obama"</span>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### 搜索结果
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"intent": {
|
||||
"primary_type": "people",
|
||||
"confidence": 0.85,
|
||||
"search_types": ["people", "keyword", "semantic"]
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"id": "video_123",
|
||||
"score": 0.96,
|
||||
"snippet": "Obama delivers speech on healthcare reform...",
|
||||
"thumbnail": "https://..."
|
||||
}
|
||||
],
|
||||
"total_count": 15,
|
||||
"summary": "Found 15 videos featuring Barack Obama discussing healthcare...",
|
||||
"took_ms": 250
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 核心实现(3 天)
|
||||
|
||||
- [ ] 实现 AgentSearchService
|
||||
- [ ] 实现 QueryAnalyzer
|
||||
- [ ] 实现 5 种底层搜索 Worker
|
||||
- [ ] 单元测试
|
||||
|
||||
### Phase 2: 集成(2 天)
|
||||
|
||||
- [ ] 集成到 Studio UI
|
||||
- [ ] 实现 API 端点
|
||||
- [ ] 对话历史管理
|
||||
|
||||
### Phase 3: 优化(2 天)
|
||||
|
||||
- [ ] 性能优化
|
||||
- [ ] 智能路由优化
|
||||
- [ ] 用户体验改进
|
||||
|
||||
---
|
||||
|
||||
**Agent Search 正式命名完成!统一智能搜尋介面,用户无需选择类型。**
|
||||
@@ -0,0 +1,799 @@
|
||||
# Agent Search 分页与 More 按钮设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 设计规范
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
**默认返回**: Top 5 结果
|
||||
**More 按钮**: 每次增加 10 个结果
|
||||
**翻页机制**: 避免缺漏,逐步展示
|
||||
|
||||
---
|
||||
|
||||
## 📊 分页规则
|
||||
|
||||
### 1. 初始查询
|
||||
|
||||
```
|
||||
First Query:
|
||||
- offset: 0
|
||||
- limit: 5
|
||||
- 返回: Top 5 结果
|
||||
- has_more: true/false
|
||||
```
|
||||
|
||||
### 2. More 操作
|
||||
|
||||
```
|
||||
Click "More":
|
||||
- offset: 5
|
||||
- limit: 10
|
||||
- 返回: 第 6-15 条结果
|
||||
- has_more: true/false
|
||||
```
|
||||
|
||||
### 3. 再次 More
|
||||
|
||||
```
|
||||
Click "More" Again:
|
||||
- offset: 15
|
||||
- limit: 10
|
||||
- 返回: 第 16-25 条结果
|
||||
- has_more: true/false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💬 API 设计
|
||||
|
||||
### 请求模型
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Agent Search 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchRequest {
|
||||
/// 搜索查询
|
||||
pub query: String,
|
||||
|
||||
/// 偏移量
|
||||
#[serde(default)]
|
||||
pub offset: i32,
|
||||
|
||||
/// 限制数量
|
||||
/// - 首次查询: 5(默认)
|
||||
/// - More 操作: 10
|
||||
#[serde(default = "default_limit")]
|
||||
pub limit: i32,
|
||||
|
||||
/// 搜索上下文
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context: Option<SearchContext>,
|
||||
|
||||
/// 会话 ID(用于保持分页状态)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub session_id: Option<String>,
|
||||
}
|
||||
|
||||
fn default_limit() -> i32 {
|
||||
5
|
||||
}
|
||||
|
||||
/// Search 上下文
|
||||
#[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 filters: SearchFilters,
|
||||
}
|
||||
|
||||
/// More 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MoreRequest {
|
||||
/// 会话 ID
|
||||
pub session_id: String,
|
||||
|
||||
/// 当前偏移量
|
||||
pub current_offset: i32,
|
||||
|
||||
/// 返回数量(固定 10)
|
||||
#[serde(default = "more_limit")]
|
||||
pub limit: i32,
|
||||
}
|
||||
|
||||
fn more_limit() -> i32 {
|
||||
10
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 响应模型
|
||||
|
||||
```rust
|
||||
/// Agent Search 响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentSearchResponse {
|
||||
/// 搜索查询
|
||||
pub query: String,
|
||||
|
||||
/// 会话 ID(用于分页)
|
||||
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,
|
||||
|
||||
/// 下一页偏移量
|
||||
pub next_offset: Option<i32>,
|
||||
|
||||
/// 摘要
|
||||
pub summary: String,
|
||||
|
||||
/// 耗时(毫秒)
|
||||
pub took_ms: i64,
|
||||
}
|
||||
|
||||
/// 搜索结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchResult {
|
||||
/// 结果 ID
|
||||
pub id: String,
|
||||
|
||||
/// 分数
|
||||
pub score: f64,
|
||||
|
||||
/// 文件 UUID
|
||||
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<serde_json::Value>,
|
||||
|
||||
/// 缩略图
|
||||
#[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 confidence: f64,
|
||||
pub search_types: Vec<SearchType>,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 工作流程
|
||||
|
||||
### 流程 1: 初始搜索
|
||||
|
||||
```
|
||||
用户: "Obama healthcare speech"
|
||||
↓
|
||||
POST /api/v1/agent/search
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"offset": 0,
|
||||
"limit": 5
|
||||
}
|
||||
↓
|
||||
AgentSearchService.search()
|
||||
↓
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"results": [
|
||||
{"id": "video_1", "score": 0.96, ...},
|
||||
{"id": "video_2", "score": 0.92, ...},
|
||||
{"id": "video_3", "score": 0.88, ...},
|
||||
{"id": "video_4", "score": 0.85, ...},
|
||||
{"id": "video_5", "score": 0.82, ...}
|
||||
],
|
||||
"total_count": 25,
|
||||
"offset": 0,
|
||||
"returned_count": 5,
|
||||
"has_more": true,
|
||||
"next_offset": 5,
|
||||
"summary": "Found 25 videos..."
|
||||
}
|
||||
↓
|
||||
UI 显示:
|
||||
- Top 5 结果
|
||||
- "More" 按钮(因为有 has_more: true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 2: 点击 More
|
||||
|
||||
```
|
||||
用户: 点击 "More"
|
||||
↓
|
||||
POST /api/v1/agent/search/more
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"current_offset": 5,
|
||||
"limit": 10
|
||||
}
|
||||
↓
|
||||
AgentSearchService.more()
|
||||
↓
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"results": [
|
||||
{"id": "video_6", "score": 0.79, ...},
|
||||
{"id": "video_7", "score": 0.76, ...},
|
||||
...
|
||||
{"id": "video_15", "score": 0.65, ...}
|
||||
],
|
||||
"total_count": 25,
|
||||
"offset": 5,
|
||||
"returned_count": 10,
|
||||
"has_more": true,
|
||||
"next_offset": 15,
|
||||
"summary": null // More 操作不生成新摘要
|
||||
}
|
||||
↓
|
||||
UI 显示:
|
||||
- 追加 10 个结果(现在显示 15 个)
|
||||
- "More" 按钮继续显示(因为 has_more: true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 3: 再次 More
|
||||
|
||||
```
|
||||
用户: 再次点击 "More"
|
||||
↓
|
||||
POST /api/v1/agent/search/more
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"current_offset": 15,
|
||||
"limit": 10
|
||||
}
|
||||
↓
|
||||
{
|
||||
"session_id": "sess_abc123",
|
||||
"results": [
|
||||
{"id": "video_16", "score": 0.62, ...},
|
||||
...
|
||||
{"id": "video_25", "score": 0.45, ...}
|
||||
],
|
||||
"total_count": 25,
|
||||
"offset": 15,
|
||||
"returned_count": 10,
|
||||
"has_more": false, // 没有更多了
|
||||
"next_offset": null,
|
||||
"summary": null
|
||||
}
|
||||
↓
|
||||
UI 显示:
|
||||
- 追加 10 个结果(现在显示 25 个)
|
||||
- "More" 按钮消失(因为 has_more: false)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 UI 设计
|
||||
|
||||
### 搜索结果界面
|
||||
|
||||
```html
|
||||
<div class="search-results">
|
||||
<!-- 摘要 -->
|
||||
<div class="summary">
|
||||
Found 25 videos featuring Barack Obama discussing healthcare...
|
||||
</div>
|
||||
|
||||
<!-- 结果列表 -->
|
||||
<div class="results-list">
|
||||
<!-- Top 5 -->
|
||||
<div class="result-item" data-id="video_1">
|
||||
<img src="thumbnail.jpg" />
|
||||
<div class="result-info">
|
||||
<h3>Obama Healthcare Speech 2010</h3>
|
||||
<p class="snippet">Obama delivers speech on healthcare reform...</p>
|
||||
<span class="score">Score: 0.96</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ... 其他 4 个结果 ... -->
|
||||
</div>
|
||||
|
||||
<!-- More 按钮 -->
|
||||
<button class="more-button" data-session="sess_abc123" data-offset="5">
|
||||
More Results (20 remaining)
|
||||
</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
### More 按钮 UI
|
||||
|
||||
```css
|
||||
.more-button {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
margin-top: 16px;
|
||||
background: #f0f0f0;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.more-button:hover {
|
||||
background: #e0e0e0;
|
||||
border-color: #bbb;
|
||||
}
|
||||
|
||||
.more-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.more-button.loading {
|
||||
background: url('spinner.gif') no-repeat center;
|
||||
color: transparent;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 端点
|
||||
|
||||
### POST /api/v1/agent/search
|
||||
|
||||
```rust
|
||||
pub async fn agent_search(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<AgentSearchRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
// 验证分页参数
|
||||
if request.offset < 0 {
|
||||
return Err(APIError::BadRequest("offset must be >= 0".to_string()));
|
||||
}
|
||||
|
||||
if request.limit < 1 || request.limit > 100 {
|
||||
return Err(APIError::BadRequest("limit must be between 1 and 100".to_string()));
|
||||
}
|
||||
|
||||
let context = SearchContext {
|
||||
user_id: Some(auth.user_id),
|
||||
..request.context.unwrap_or_default()
|
||||
};
|
||||
|
||||
let response = agent_search_service
|
||||
.search(&request.query, request.offset, request.limit, Some(context))
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/agent/search/more
|
||||
|
||||
```rust
|
||||
pub async fn agent_search_more(
|
||||
Extension(agent_search_service): Extension<Arc<AgentSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<MoreRequest>,
|
||||
) -> Result<Json<AgentSearchResponse>, APIError> {
|
||||
// 验证会话
|
||||
let session = agent_search_service
|
||||
.get_session(&request.session_id)
|
||||
.await?
|
||||
.ok_or_else(|| APIError::NotFound("Session not found".to_string()))?;
|
||||
|
||||
// 验证用户
|
||||
if session.user_id != auth.user_id {
|
||||
return Err(APIError::Forbidden("Access denied".to_string()));
|
||||
}
|
||||
|
||||
// 获取更多结果
|
||||
let response = agent_search_service
|
||||
.more(&request.session_id, request.current_offset, request.limit)
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💾 Session 管理
|
||||
|
||||
### 会话存储
|
||||
|
||||
```rust
|
||||
/// 搜索会话
|
||||
#[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: DateTime<Utc>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl AgentSearchService {
|
||||
/// 创建会话
|
||||
async fn create_session(
|
||||
&self,
|
||||
user_id: &str,
|
||||
query: &str,
|
||||
intent: QueryIntent,
|
||||
total_count: i64,
|
||||
) -> CommandResult<String> {
|
||||
let session_id = uuid::Uuid::new_v4().to_string();
|
||||
let now = Utc::now();
|
||||
|
||||
let session = SearchSession {
|
||||
session_id: session_id.clone(),
|
||||
user_id: user_id.to_string(),
|
||||
query: query.to_string(),
|
||||
intent,
|
||||
total_count,
|
||||
created_at: now,
|
||||
expires_at: now + chrono::Duration::hours(1), // 1小时过期
|
||||
};
|
||||
|
||||
// 存储到 Redis
|
||||
let key = format!("search_session:{}", session_id);
|
||||
let value = serde_json::to_string(&session)?;
|
||||
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO search_sessions (
|
||||
session_id, user_id, query, intent,
|
||||
total_count, created_at, expires_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
"#,
|
||||
session.session_id,
|
||||
session.user_id,
|
||||
session.query,
|
||||
serde_json::to_value(&session.intent)?,
|
||||
session.total_count,
|
||||
session.created_at,
|
||||
session.expires_at,
|
||||
)
|
||||
.execute(&self.db)
|
||||
.await?;
|
||||
|
||||
Ok(session_id)
|
||||
}
|
||||
|
||||
/// 获取会话
|
||||
pub async fn get_session(&self, session_id: &str) -> CommandResult<Option<SearchSession>> {
|
||||
let session = sqlx::query_as!(
|
||||
SearchSession,
|
||||
r#"
|
||||
SELECT session_id, user_id, query, intent as "intent: QueryIntent",
|
||||
total_count, created_at, expires_at
|
||||
FROM search_sessions
|
||||
WHERE session_id = $1 AND expires_at > NOW()
|
||||
"#,
|
||||
session_id,
|
||||
)
|
||||
.fetch_optional(&self.db)
|
||||
.await?;
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// More 操作
|
||||
pub async fn more(
|
||||
&self,
|
||||
session_id: &str,
|
||||
offset: i32,
|
||||
limit: i32,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
let session = self.get_session(session_id)
|
||||
.await?
|
||||
.ok_or_else(|| CommandError::NotFound("Session not found or expired".to_string()))?;
|
||||
|
||||
// 使用会话中的查询和意图
|
||||
let results = self.execute_search_with_offset(
|
||||
&session.query,
|
||||
&session.intent,
|
||||
offset,
|
||||
limit,
|
||||
).await?;
|
||||
|
||||
let has_more = (offset + limit) < session.total_count as i32;
|
||||
|
||||
Ok(AgentSearchResponse {
|
||||
query: session.query,
|
||||
session_id: session_id.to_string(),
|
||||
intent: session.intent,
|
||||
results,
|
||||
total_count: session.total_count,
|
||||
offset,
|
||||
returned_count: limit,
|
||||
has_more,
|
||||
next_offset: if has_more { Some(offset + limit) } else { None },
|
||||
summary: String::new(), // More 操作不生成摘要
|
||||
took_ms: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据库表
|
||||
|
||||
```sql
|
||||
-- 搜索会话表
|
||||
CREATE TABLE IF NOT EXISTS search_sessions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
session_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
query TEXT NOT NULL,
|
||||
intent JSONB NOT NULL,
|
||||
total_count BIGINT NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
|
||||
-- 索引
|
||||
INDEX idx_session_id (session_id),
|
||||
INDEX idx_user_id (user_id, created_at),
|
||||
INDEX idx_expires (expires_at)
|
||||
);
|
||||
|
||||
-- 定期清理过期会话
|
||||
CREATE OR REPLACE PROCEDURE cleanup_expired_search_sessions()
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
DELETE FROM search_sessions WHERE expires_at < NOW();
|
||||
RAISE NOTICE 'Cleaned up expired search sessions';
|
||||
END;
|
||||
$$;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 实现要点
|
||||
|
||||
### 1. 分页逻辑
|
||||
|
||||
```rust
|
||||
impl AgentSearchService {
|
||||
pub async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
offset: i32,
|
||||
limit: i32,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<AgentSearchResponse> {
|
||||
// 1. 分析查询意图
|
||||
let intent = self.query_analyzer.analyze(query, context.clone()).await?;
|
||||
|
||||
// 2. 执行搜索(获取总数)
|
||||
let (results, total_count) = self.execute_search(
|
||||
query,
|
||||
&intent,
|
||||
offset,
|
||||
limit,
|
||||
).await?;
|
||||
|
||||
// 3. 创建会话
|
||||
let user_id = context.as_ref().and_then(|c| c.user_id.clone()).unwrap_or_default();
|
||||
let session_id = self.create_session(&user_id, query, intent.clone(), total_count).await?;
|
||||
|
||||
// 4. 生成摘要(仅首次)
|
||||
let summary = if offset == 0 {
|
||||
self.generate_summary(query, &results).await?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// 5. 构建响应
|
||||
let has_more = (offset + limit) < total_count as i32;
|
||||
|
||||
Ok(AgentSearchResponse {
|
||||
query: query.to_string(),
|
||||
session_id,
|
||||
intent,
|
||||
results,
|
||||
total_count,
|
||||
offset,
|
||||
returned_count: results.len() as i32,
|
||||
has_more,
|
||||
next_offset: if has_more { Some(offset + limit) } else { None },
|
||||
summary,
|
||||
took_ms: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. UI 交互
|
||||
|
||||
```javascript
|
||||
// 初始搜索
|
||||
async function search(query) {
|
||||
const response = await fetch('/api/v1/agent/search', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
query: query,
|
||||
offset: 0,
|
||||
limit: 5
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// 显示结果
|
||||
displayResults(data.results);
|
||||
|
||||
// 显示摘要
|
||||
displaySummary(data.summary);
|
||||
|
||||
// 显示 More 按钮
|
||||
if (data.has_more) {
|
||||
showMoreButton(data.session_id, data.next_offset, data.total_count - data.returned_count);
|
||||
}
|
||||
}
|
||||
|
||||
// More 操作
|
||||
async function loadMore(sessionId, nextOffset) {
|
||||
const moreButton = document.querySelector('.more-button');
|
||||
moreButton.classList.add('loading');
|
||||
moreButton.disabled = true;
|
||||
|
||||
const response = await fetch('/api/v1/agent/search/more', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
session_id: sessionId,
|
||||
current_offset: nextOffset,
|
||||
limit: 10
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// 追加结果
|
||||
appendResults(data.results);
|
||||
|
||||
// 更新 More 按钮
|
||||
if (data.has_more) {
|
||||
updateMoreButton(data.session_id, data.next_offset, data.total_count - (data.offset + data.returned_count));
|
||||
} else {
|
||||
hideMoreButton();
|
||||
}
|
||||
|
||||
moreButton.classList.remove('loading');
|
||||
moreButton.disabled = false;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📈 性能优化
|
||||
|
||||
### 1. 会话缓存
|
||||
|
||||
```rust
|
||||
// 使用 Redis 缓存会话
|
||||
impl AgentSearchService {
|
||||
async fn cache_session(&self, session: &SearchSession) -> CommandResult<()> {
|
||||
let key = format!("search_session:{}", session.session_id);
|
||||
let value = serde_json::to_string(session)?;
|
||||
|
||||
// 存储到 Redis,设置 1 小时过期
|
||||
self.redis.set_ex(&key, &value, 3600).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_cached_session(&self, session_id: &str) -> CommandResult<Option<SearchSession>> {
|
||||
let key = format!("search_session:{}", session_id);
|
||||
|
||||
if let Some(value) = self.redis.get(&key).await? {
|
||||
let session: SearchSession = serde_json::from_str(&value)?;
|
||||
return Ok(Some(session));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 结果缓存
|
||||
|
||||
```rust
|
||||
// 缓存搜索结果(避免重复计算)
|
||||
impl AgentSearchService {
|
||||
async fn cache_results(
|
||||
&self,
|
||||
session_id: &str,
|
||||
offset: i32,
|
||||
limit: i32,
|
||||
results: &[SearchResult],
|
||||
) -> CommandResult<()> {
|
||||
let key = format!("search_results:{}:{}:{}", session_id, offset, offset + limit);
|
||||
let value = serde_json::to_string(results)?;
|
||||
|
||||
// 缓存 30 分钟
|
||||
self.redis.set_ex(&key, &value, 1800).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 设计总结
|
||||
|
||||
**默认返回**: Top 5 结果
|
||||
**More 操作**: 每次增加 10 个
|
||||
**会话管理**: 1 小时过期
|
||||
**UI 显示**: More 按钮 + 剩余数量
|
||||
**性能优化**: Redis 缓存会话和结果
|
||||
|
||||
**分页设计完成!用户可逐步浏览所有结果,避免信息过载。**
|
||||
@@ -0,0 +1,340 @@
|
||||
# Momentry 文件处理流程 - 产出导向设计
|
||||
|
||||
**日期**: 2026-10-10
|
||||
**版本**: V2.0 (产出导向)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计原则
|
||||
|
||||
1. **产出导向**: 每个阶段都有明确的产品
|
||||
2. **可查看性**: 每个产品都有对应的功能或文件
|
||||
3. **过程透明**: 不够直观的当作过程,不单独列出
|
||||
|
||||
---
|
||||
|
||||
## 📦 阶段与产出
|
||||
|
||||
### 阶段 1: 媒体分析 (Processors)
|
||||
|
||||
**产出**: `{file_uuid}.workspace.sqlite`
|
||||
|
||||
| 数据表 | 内容 | 用途 |
|
||||
|--------|------|------|
|
||||
| `pre_chunks` | 原始文本块 | ASR 原始输出 |
|
||||
| `face_detections` | 人脸检测 | 每帧人脸位置 |
|
||||
| `speaker_detections` | 说话人检测 | 说话人片段 |
|
||||
| `processor_results` | 处理结果 | 各处理器输出 |
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.workspace.sqlite`
|
||||
- 🔍 工具: SQLite Browser / `sqlite3` 命令
|
||||
- 🌐 API: 无(内部文件)
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (所有后续阶段的基础)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 2: 文本块 (Chunks)
|
||||
|
||||
**产出**: PostgreSQL `chunks` 表
|
||||
|
||||
| 字段 | 内容 | 用途 |
|
||||
|------|------|------|
|
||||
| `file_uuid` | 文件ID | 文件关联 |
|
||||
| `chunk_id` | 块ID | 唯一标识 |
|
||||
| `text_content` | 文本内容 | 关键词搜索 |
|
||||
| `start_time` | 开始时间 | 时间定位 |
|
||||
| `end_time` | 结束时间 | 时间定位 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/chunks?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: `GET /api/v1/search?keyword={keyword}`
|
||||
- 📊 状态: `keyword_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (支持关键词搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 3: 人脸轨迹 (Face Tracks)
|
||||
|
||||
**产出**: `{file_uuid}.faces.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"tracks": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"face_count": 150,
|
||||
"confidence": 0.95,
|
||||
"frames": [100, 101, 102, ...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.faces.json`
|
||||
- 🌐 API: `GET /api/v1/faces/tracks?file_uuid={file_uuid}`
|
||||
- 🖼️ 可视化: Face Track Viewer (规划中)
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸追踪数据)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 4: 身份识别 (Identities)
|
||||
|
||||
**产出**: PostgreSQL `identities` 表
|
||||
|
||||
| 字段 | 内容 | 用途 |
|
||||
|------|------|------|
|
||||
| `identity_uuid` | 身份ID | 全局唯一标识 |
|
||||
| `name` | 姓名 | 人物名称 |
|
||||
| `face_count` | 人脸数 | 统计信息 |
|
||||
| `file_count` | 文件数 | 出现范围 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/identities`
|
||||
- 🔍 搜索: `GET /api/v1/search?person={name}`
|
||||
- 📊 状态: `face_mgmt_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (支持人脸管理)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 5: 知识图谱 (TKG)
|
||||
|
||||
**产出**: PostgreSQL `tkg_nodes` + `tkg_edges` 表
|
||||
|
||||
**节点表**:
|
||||
| 节点类型 | 内容 | 用途 |
|
||||
|----------|------|------|
|
||||
| `face_track` | 人脸轨迹节点 | 轨迹关联 |
|
||||
| `speaker` | 说话人节点 | 说话人关联 |
|
||||
| `character` | 角色节点 | 角色关联 |
|
||||
| `chunk` | 文本块节点 | 内容关联 |
|
||||
|
||||
**边表**:
|
||||
| 边类型 | 内容 | 用途 |
|
||||
|--------|------|------|
|
||||
| `same_identity` | 同一身份 | 人脸绑定 |
|
||||
| `same_speaker` | 同一说话人 | 说话人绑定 |
|
||||
| `speaks_in` | 在某段说话 | 时间关联 |
|
||||
| `appears_in` | 出现在某段 | 时间关联 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/tkg/nodes?file_uuid={file_uuid}`
|
||||
- 🔍 查询: Agent 自然语言查询
|
||||
- 📊 状态: `agent_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (支持复杂查询)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 6: 向量索引 (Vectors)
|
||||
|
||||
**产出**: Qdrant Collections
|
||||
|
||||
| Collection | 内容 | 用途 |
|
||||
|------------|------|------|
|
||||
| `_chunks` | 文本向量 | 语义搜索 |
|
||||
| `_faces` | 人脸向量 | 人脸搜索 |
|
||||
| `_scenes` | 场景向量 | 场景搜索 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `POST /api/v1/search/semantic`
|
||||
- 🔍 搜索: 自然语言搜索
|
||||
- 📊 状态: `semantic_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (支持语义搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 7: 人脸描述 (Face VLM)
|
||||
|
||||
**产出**: `{file_uuid}.face_vlm.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"tracks": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"description": "中年男性,戴眼镜,穿蓝色衬衫...",
|
||||
"confidence": 0.92
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/faces/tracks/{trace_id}`
|
||||
- 🔍 搜索: 通过描述搜索人物
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸外观描述)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 8: 场景描述 (Scene VLM)
|
||||
|
||||
**产出**: `{file_uuid}.scene_vlm.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"scenes": [
|
||||
{
|
||||
"scene_id": 1,
|
||||
"start_time": 0.0,
|
||||
"end_time": 10.5,
|
||||
"description": "室内办公室场景,有两个人在对话..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.scene_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/scenes?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过描述搜索场景
|
||||
|
||||
**重要性**: ⭐⭐⭐ (场景描述)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 9: 时刻块 (Moment Chunks)
|
||||
|
||||
**产出**: PostgreSQL `moment_chunks` 表
|
||||
|
||||
| 字段 | 内容 | 用途 |
|
||||
|------|------|------|
|
||||
| `moment_id` | 时刻ID | 唯一标识 |
|
||||
| `start_time` | 开始时间 | 时间定位 |
|
||||
| `end_time` | 结束时间 | 时间定位 |
|
||||
| `summary` | 摘要 | 内容概览 |
|
||||
| `keywords` | 关键词 | 快速理解 |
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/moments?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过关键词搜索时刻
|
||||
- 📊 Timeline: 时刻时间线
|
||||
|
||||
**重要性**: ⭐⭐ (时刻概览)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 完整流程
|
||||
|
||||
```
|
||||
视频文件注册
|
||||
↓
|
||||
[阶段 1] 媒体分析
|
||||
→ 产出: {file_uuid}.workspace.sqlite
|
||||
↓
|
||||
[阶段 2] 文本块
|
||||
→ 产出: PostgreSQL chunks 表
|
||||
→ 状态: keyword_ready
|
||||
↓
|
||||
[阶段 3] 人脸轨迹
|
||||
→ 产出: {file_uuid}.faces.json
|
||||
↓
|
||||
[阶段 4] 身份识别
|
||||
→ 产出: PostgreSQL identities 表
|
||||
→ 状态: face_mgmt_ready
|
||||
↓
|
||||
[阶段 5] 知识图谱
|
||||
→ 产出: PostgreSQL tkg_nodes + tkg_edges
|
||||
→ 状态: agent_ready
|
||||
↓
|
||||
[阶段 6] 向量索引
|
||||
→ 产出: Qdrant collections
|
||||
→ 状态: semantic_ready
|
||||
↓
|
||||
[阶段 7] 人脸描述
|
||||
→ 产出: {file_uuid}.face_vlm.json
|
||||
↓
|
||||
[阶段 8] 场景描述
|
||||
→ 产出: {file_uuid}.scene_vlm.json
|
||||
↓
|
||||
[阶段 9] 时刻块
|
||||
→ 产出: PostgreSQL moment_chunks
|
||||
↓
|
||||
✅ 完成
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 文件状态映射
|
||||
|
||||
| 状态 | 含义 | 对应阶段 |
|
||||
|------|------|----------|
|
||||
| `pending` | 等待处理 | 初始状态 |
|
||||
| `scanning` | 正在扫描 | 阶段 1-9 |
|
||||
| `keyword_ready` | 支持关键词搜索 | 阶段 2+ |
|
||||
| `semantic_ready` | 支持语义搜索 | 阶段 6+ |
|
||||
| `face_mgmt_ready` | 支持人脸管理 | 阶段 4+ |
|
||||
| `agent_ready` | 支持Agent查询 | 阶段 5+ |
|
||||
| `completed` | 完全完成 | 所有阶段 |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 产出查看方式总结
|
||||
|
||||
| 产出类型 | 文件位置 | API 端点 | 可视化 |
|
||||
|----------|----------|----------|--------|
|
||||
| **workspace.sqlite** | `~/momentry/output/` | 无 | SQLite Browser |
|
||||
| **文本块** | 数据库 | `/api/v1/chunks` | 搜索结果 |
|
||||
| **人脸轨迹** | `.faces.json` | `/api/v1/faces/tracks` | 规划中 |
|
||||
| **身份** | 数据库 | `/api/v1/identities` | Identity Cards |
|
||||
| **知识图谱** | 数据库 | `/api/v1/tkg/nodes` | Graph Viewer |
|
||||
| **向量索引** | Qdrant | `/api/v1/search/semantic` | 搜索结果 |
|
||||
| **人脸描述** | `.face_vlm.json` | `/api/v1/faces/tracks/{id}` | 详情页 |
|
||||
| **场景描述** | `.scene_vlm.json` | `/api/v1/scenes` | 场景列表 |
|
||||
| **时刻块** | 数据库 | `/api/v1/moments` | Timeline |
|
||||
|
||||
---
|
||||
|
||||
## 💡 设计优势
|
||||
|
||||
### 相比原流程
|
||||
|
||||
| 改进点 | 原流程 | 新流程 |
|
||||
|--------|--------|--------|
|
||||
| **产出导向** | 过程导向 | ✅ 产出导向 |
|
||||
| **可查看性** | 抽象概念 | ✅ 具体文件/数据 |
|
||||
| **用户理解** | 需要技术背景 | ✅ 直观易懂 |
|
||||
| **功能映射** | 模糊 | ✅ 明确 |
|
||||
|
||||
### 用户体验
|
||||
|
||||
- ✅ 每个阶段都有明确的产品
|
||||
- ✅ 每个产品都有查看方式
|
||||
- ✅ 过程透明,不过度展示
|
||||
- ✅ 状态清晰,进度可追踪
|
||||
|
||||
---
|
||||
|
||||
## 📝 实施建议
|
||||
|
||||
### 优先级排序
|
||||
|
||||
**P0 - 核心产出**:
|
||||
1. 媒体分析 (workspace.sqlite)
|
||||
2. 文本块 (chunks)
|
||||
3. 身份识别 (identities)
|
||||
4. 知识图谱 (tkg)
|
||||
|
||||
**P1 - 增强产出**:
|
||||
5. 向量索引 (vectors)
|
||||
6. 人脸轨迹 (faces.json)
|
||||
|
||||
**P2 - 可选产出**:
|
||||
7. 人脸描述 (face_vlm.json)
|
||||
8. 场景描述 (scene_vlm.json)
|
||||
9. 时刻块 (moment_chunks)
|
||||
|
||||
---
|
||||
|
||||
**设计完成,等待实施。**
|
||||
@@ -0,0 +1,502 @@
|
||||
# Momentry 文件处理流程 - V3 (JSON 产出关联版)
|
||||
|
||||
**日期**: 2026-10-10
|
||||
**版本**: V3.0
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计原则
|
||||
|
||||
1. **每个阶段都有明确的 JSON 文件产出**
|
||||
2. **每个 JSON 文件都可查看**
|
||||
3. **数据库产出作为辅助**
|
||||
|
||||
---
|
||||
|
||||
## 📦 阶段与产出
|
||||
|
||||
### 阶段 1: 媒体分析 (Media Analysis)
|
||||
|
||||
**主要产出**: `{file_uuid}.workspace.sqlite`
|
||||
|
||||
**JSON 产出** (7个):
|
||||
|
||||
| 文件名 | 内容 | 大小 | 用途 |
|
||||
|--------|------|------|------|
|
||||
| `{file_uuid}.probe.json` | 视频元数据 | ~1KB | 视频信息 |
|
||||
| `{file_uuid}.asr.json` | ASR 结果 | ~10KB | 语音识别 |
|
||||
| `{file_uuid}.face.json` | 人脸检测 | ~50KB | 人脸位置 |
|
||||
| `{file_uuid}.ocr.json` | OCR 结果 | ~5KB | 文字识别 |
|
||||
| `{file_uuid}.cut.json` | 场景分割 | ~1KB | 场景边界 |
|
||||
| `{file_uuid}.asrx.json` | 说话人识别 | ~2KB | 说话人片段 |
|
||||
| `{file_uuid}.scenes.json` | 场景检测 | ~3KB | 场景信息 |
|
||||
|
||||
**示例: {file_uuid}.asr.json**:
|
||||
```json
|
||||
{
|
||||
"language": "en",
|
||||
"text": "Hello world...",
|
||||
"segments": [
|
||||
{
|
||||
"start": 0.0,
|
||||
"end": 2.5,
|
||||
"text": "Hello world"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.*.json`
|
||||
- 🔧 工具: `jq` 命令 / JSON Viewer
|
||||
- 🌐 API: 无(原始数据)
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (基础数据)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 2: 文本块 (Text Chunks)
|
||||
|
||||
**主要产出**: PostgreSQL `chunks` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- chunks 表
|
||||
CREATE TABLE chunks (
|
||||
file_uuid TEXT,
|
||||
chunk_id TEXT,
|
||||
text_content TEXT,
|
||||
start_time REAL,
|
||||
end_time REAL
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/chunks?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: `GET /api/v1/search?keyword={keyword}`
|
||||
- 📊 状态: `keyword_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (关键词搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 3: 人脸追踪 (Face Tracing)
|
||||
|
||||
**主要产出**: `{file_uuid}.face_traced.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"status": "has_faces",
|
||||
"frame_count": 150,
|
||||
"fps": 29.97,
|
||||
"frames": {
|
||||
"92": {
|
||||
"frame_number": 92,
|
||||
"time_seconds": 3.07,
|
||||
"faces": [
|
||||
{
|
||||
"x": 313,
|
||||
"y": 468,
|
||||
"width": 53,
|
||||
"height": 53,
|
||||
"confidence": 0.6,
|
||||
"captureQuality": 0.1,
|
||||
"trace_id": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"face_count": 50,
|
||||
"frames": [92, 93, 94, ...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_traced.json`
|
||||
- 🌐 API: `GET /api/v1/faces/tracks?file_uuid={file_uuid}`
|
||||
- 🖼️ 可视化: Face Track Viewer
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (人脸追踪)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 4: 人脸聚类 (Face Clustering)
|
||||
|
||||
**主要产出**: `{file_uuid}.face_cluster.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"status": "has_faces",
|
||||
"file_uuid": "abc123...",
|
||||
"clusters": [
|
||||
{
|
||||
"cluster_id": 0,
|
||||
"face_count": 150,
|
||||
"representative_frame": 100,
|
||||
"frames": [92, 93, 94, ...]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_cluster.json`
|
||||
- 🌐 API: `GET /api/v1/faces/clusters?file_uuid={file_uuid}`
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸聚类)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 5: 身份识别 (Identities)
|
||||
|
||||
**主要产出**: PostgreSQL `identities` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- identities 表
|
||||
CREATE TABLE identities (
|
||||
identity_uuid TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
face_count INTEGER,
|
||||
file_count INTEGER,
|
||||
created_at TIMESTAMP
|
||||
);
|
||||
|
||||
-- identity_bindings 表
|
||||
CREATE TABLE identity_bindings (
|
||||
file_uuid TEXT,
|
||||
trace_id INTEGER,
|
||||
identity_uuid TEXT,
|
||||
confidence REAL
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/identities`
|
||||
- 🔍 搜索: `GET /api/v1/search?person={name}`
|
||||
- 📊 状态: `face_mgmt_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (人脸管理)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 6: 知识图谱 (Knowledge Graph)
|
||||
|
||||
**主要产出**: PostgreSQL `tkg_*` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- tkg_nodes 表
|
||||
CREATE TABLE tkg_nodes (
|
||||
node_id TEXT PRIMARY KEY,
|
||||
node_type TEXT,
|
||||
file_uuid TEXT,
|
||||
properties JSONB
|
||||
);
|
||||
|
||||
-- tkg_edges 表
|
||||
CREATE TABLE tkg_edges (
|
||||
edge_id TEXT PRIMARY KEY,
|
||||
source_node TEXT,
|
||||
target_node TEXT,
|
||||
edge_type TEXT,
|
||||
properties JSONB
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/tkg/nodes?file_uuid={file_uuid}`
|
||||
- 🔍 查询: Agent 自然语言查询
|
||||
- 📊 状态: `agent_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐⭐ (复杂查询)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 7: 向量索引 (Vector Index)
|
||||
|
||||
**主要产出**: Qdrant Collections
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**向量产出**:
|
||||
- `_chunks` collection (文本向量)
|
||||
- `_faces` collection (人脸向量)
|
||||
- `_scenes` collection (场景向量)
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `POST /api/v1/search/semantic`
|
||||
- 🔍 搜索: 自然语言搜索
|
||||
- 📊 状态: `semantic_ready`
|
||||
|
||||
**重要性**: ⭐⭐⭐⭐ (语义搜索)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 8: 人脸描述 (Face Description)
|
||||
|
||||
**主要产出**: `{file_uuid}.face_vlm.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"traces": [
|
||||
{
|
||||
"trace_id": 1,
|
||||
"description": "中年男性,戴眼镜,穿蓝色衬衫",
|
||||
"confidence": 0.92,
|
||||
"frame": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.face_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/faces/traces/{trace_id}`
|
||||
- 🔍 搜索: 通过描述搜索人物
|
||||
|
||||
**重要性**: ⭐⭐⭐ (人脸外观)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 9: 场景描述 (Scene Description)
|
||||
|
||||
**主要产出**: `{file_uuid}.scene_vlm.json`
|
||||
|
||||
**JSON 结构**:
|
||||
```json
|
||||
{
|
||||
"file_uuid": "abc123...",
|
||||
"scenes": [
|
||||
{
|
||||
"scene_id": 1,
|
||||
"start_time": 0.0,
|
||||
"end_time": 10.5,
|
||||
"description": "室内办公室场景,有两个人在对话",
|
||||
"key_frame": 150
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 📄 文件: `~/momentry/output/{file_uuid}.scene_vlm.json`
|
||||
- 🌐 API: `GET /api/v1/scenes?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过描述搜索场景
|
||||
|
||||
**重要性**: ⭐⭐⭐ (场景理解)
|
||||
|
||||
---
|
||||
|
||||
### 阶段 10: 时刻块 (Moment Chunks)
|
||||
|
||||
**主要产出**: PostgreSQL `moment_chunks` 表
|
||||
|
||||
**JSON 产出**: 无
|
||||
|
||||
**数据库产出**:
|
||||
```sql
|
||||
-- moment_chunks 表
|
||||
CREATE TABLE moment_chunks (
|
||||
moment_id TEXT PRIMARY KEY,
|
||||
file_uuid TEXT,
|
||||
start_time REAL,
|
||||
end_time REAL,
|
||||
summary TEXT,
|
||||
keywords TEXT[]
|
||||
);
|
||||
```
|
||||
|
||||
**可查看方式**:
|
||||
- 🌐 API: `GET /api/v1/moments?file_uuid={file_uuid}`
|
||||
- 🔍 搜索: 通过关键词搜索时刻
|
||||
- 📊 Timeline: 时刻时间线
|
||||
|
||||
**重要性**: ⭐⭐ (时刻概览)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 完整流程图
|
||||
|
||||
```
|
||||
视频文件注册
|
||||
↓
|
||||
[阶段 1] 媒体分析
|
||||
→ 产出: {file_uuid}.workspace.sqlite
|
||||
→ JSON: probe.json, asr.json, face.json, ocr.json,
|
||||
cut.json, asrx.json, scenes.json
|
||||
↓
|
||||
[阶段 2] 文本块
|
||||
→ 产出: PostgreSQL chunks 表
|
||||
→ 状态: keyword_ready
|
||||
↓
|
||||
[阶段 3] 人脸追踪
|
||||
→ 产出: {file_uuid}.face_traced.json
|
||||
↓
|
||||
[阶段 4] 人脸聚类
|
||||
→ 产出: {file_uuid}.face_cluster.json
|
||||
↓
|
||||
[阶段 5] 身份识别
|
||||
→ 产出: PostgreSQL identities 表
|
||||
→ 状态: face_mgmt_ready
|
||||
↓
|
||||
[阶段 6] 知识图谱
|
||||
→ 产出: PostgreSQL tkg_* 表
|
||||
→ 状态: agent_ready
|
||||
↓
|
||||
[阶段 7] 向量索引
|
||||
→ 产出: Qdrant collections
|
||||
→ 状态: semantic_ready
|
||||
↓
|
||||
[阶段 8] 人脸描述
|
||||
→ 产出: {file_uuid}.face_vlm.json
|
||||
↓
|
||||
[阶段 9] 场景描述
|
||||
→ 产出: {file_uuid}.scene_vlm.json
|
||||
↓
|
||||
[阶段 10] 时刻块
|
||||
→ 产出: PostgreSQL moment_chunks
|
||||
↓
|
||||
✅ 完成
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 产出统计
|
||||
|
||||
### JSON 文件产出
|
||||
|
||||
| 阶段 | JSON 文件 | 数量 |
|
||||
|------|-----------|------|
|
||||
| 阶段 1 | probe, asr, face, ocr, cut, asrx, scenes | 7 |
|
||||
| 阶段 3 | face_traced | 1 |
|
||||
| 阶段 4 | face_cluster | 1 |
|
||||
| 阶段 8 | face_vlm | 1 |
|
||||
| 阶段 9 | scene_vlm | 1 |
|
||||
| **总计** | **10 个 JSON 文件** | **11** |
|
||||
|
||||
### 数据库产出
|
||||
|
||||
| 阶段 | 表/Collection | 数量 |
|
||||
|------|---------------|------|
|
||||
| 阶段 2 | chunks | 1 |
|
||||
| 阶段 5 | identities, identity_bindings | 2 |
|
||||
| 阶段 6 | tkg_nodes, tkg_edges | 2 |
|
||||
| 阶段 7 | _chunks, _faces, _scenes | 3 |
|
||||
| 阶段 10 | moment_chunks | 1 |
|
||||
| **总计** | **9 个数据库表/Collection** | **9** |
|
||||
|
||||
### SQLite 产出
|
||||
|
||||
| 阶段 | 文件 | 数量 |
|
||||
|------|------|------|
|
||||
| 阶段 1 | workspace.sqlite | 1 |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 JSON 文件查看方式
|
||||
|
||||
### 方式 1: 命令行
|
||||
|
||||
```bash
|
||||
# 查看 ASR 结果
|
||||
jq '.' ~/momentry/output/{file_uuid}.asr.json
|
||||
|
||||
# 查看 Face Traced 结果
|
||||
jq '.traces' ~/momentry/output/{file_uuid}.face_traced.json
|
||||
|
||||
# 查看 Face Cluster 结果
|
||||
jq '.clusters' ~/momentry/output/{file_uuid}.face_cluster.json
|
||||
```
|
||||
|
||||
### 方式 2: JSON Viewer
|
||||
|
||||
- 使用 VS Code 的 JSON Viewer
|
||||
- 使用在线 JSON Viewer
|
||||
|
||||
### 方式 3: API
|
||||
|
||||
```bash
|
||||
# 获取人脸轨迹
|
||||
GET /api/v1/faces/tracks?file_uuid={file_uuid}
|
||||
|
||||
# 获取人脸聚类
|
||||
GET /api/v1/faces/clusters?file_uuid={file_uuid}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 文件命名规则
|
||||
|
||||
### 格式
|
||||
|
||||
```
|
||||
{file_uuid}.{type}.json
|
||||
```
|
||||
|
||||
### 类型列表
|
||||
|
||||
| 类型 | 说明 |
|
||||
|------|------|
|
||||
| `probe` | 视频元数据 |
|
||||
| `asr` | ASR 结果 |
|
||||
| `face` | 人脸检测 |
|
||||
| `ocr` | OCR 结果 |
|
||||
| `cut` | 场景分割 |
|
||||
| `asrx` | 说话人识别 |
|
||||
| `scenes` | 场景检测 |
|
||||
| `face_traced` | 人脸追踪 |
|
||||
| `face_cluster` | 人脸聚类 |
|
||||
| `face_vlm` | 人脸描述 |
|
||||
| `scene_vlm` | 场景描述 |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 场景 1: 查看视频基本信息
|
||||
|
||||
```bash
|
||||
# 查看 probe.json
|
||||
jq '.duration, .width, .height' {file_uuid}.probe.json
|
||||
```
|
||||
|
||||
### 场景 2: 查看语音内容
|
||||
|
||||
```bash
|
||||
# 查看 ASR 结果
|
||||
jq '.text' {file_uuid}.asr.json
|
||||
```
|
||||
|
||||
### 场景 3: 查看人脸追踪
|
||||
|
||||
```bash
|
||||
# 查看人脸轨迹
|
||||
jq '.traces[] | {trace_id, face_count}' {file_uuid}.face_traced.json
|
||||
```
|
||||
|
||||
### 场景 4: 查看人脸外观
|
||||
|
||||
```bash
|
||||
# 查看人脸描述
|
||||
jq '.traces[] | {trace_id, description}' {file_uuid}.face_vlm.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**设计完成,每个阶段都有明确的 JSON 产出。**
|
||||
@@ -0,0 +1,654 @@
|
||||
# MarkBase Queue 与 Billing 集成设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**目标**: 队列系统完全兼容 MarkBase Billing 机制
|
||||
|
||||
---
|
||||
|
||||
## 🎯 集成目标
|
||||
|
||||
| 目标 | 说明 | 优先级 |
|
||||
|------|------|:------:|
|
||||
| **准确计费** | 每个队列消息准确记录 token 消耗 | 🔴 P0 |
|
||||
| **Quota 限制** | 根据用户 quota 限制队列处理 | 🔴 P0 |
|
||||
| **成本追踪** | 追踪每个请求的成本 | 🟡 P1 |
|
||||
| **实时监控** | 实时监控 token 使用情况 | 🟡 P1 |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 集成架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ MarkBase Queue Service │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Queue Manager │ │ Billing Manager │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ - 消息队列管理 │ │ - Token 追踪 │ │
|
||||
│ │ - 优先级调度 │ │ - Quota 检查 │ │
|
||||
│ │ - 并发控制 │ │ - 成本计算 │ │
|
||||
│ └──────────────────┘ └──────────────────┘ │
|
||||
│ │ │ │
|
||||
│ └───────────┬───────────┘ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ Billing-Aware Queue Processing │ │
|
||||
│ │ ├─ Pre-Processing: 检查 quota │ │
|
||||
│ │ ├─ Processing: 追踪 token 使用 │ │
|
||||
│ │ └─ Post-Processing: 记录成本 │ │
|
||||
│ └──────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ MarkBase Billing Service │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ PostgreSQL Tables: │
|
||||
│ ├─ billing_periods (计费周期汇总) │
|
||||
│ ├─ token_usage_log (token 使用明细) │
|
||||
│ ├─ user_quotas (用户 quota 配置) │
|
||||
│ └─ service_rates (服务费率配置) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据模型扩展
|
||||
|
||||
### 1. 队列消息与 Billing 关联
|
||||
|
||||
```sql
|
||||
-- 扩展 vlm_requests 表
|
||||
ALTER TABLE vlm_requests ADD COLUMN IF NOT EXISTS
|
||||
request_id VARCHAR(36), -- 关联 billing request_id
|
||||
key_id VARCHAR(36), -- API key ID
|
||||
billing_context JSONB, -- Billing 上下文
|
||||
token_usage JSONB, -- Token 使用记录
|
||||
cost_usd DECIMAL(10, 6); -- 成本(美元)
|
||||
|
||||
-- token_usage 格式
|
||||
{
|
||||
"input_tokens": 500,
|
||||
"output_tokens": 300,
|
||||
"total_tokens": 800,
|
||||
"model": "gemma-4-12b-it",
|
||||
"service": "vlm"
|
||||
}
|
||||
|
||||
-- billing_context 格式
|
||||
{
|
||||
"user_id": "user_123",
|
||||
"api_key": "muser_abc123",
|
||||
"quota_limit": 100000,
|
||||
"quota_used": 50000,
|
||||
"quota_remaining": 50000
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Billing 周期表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS billing_periods (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key_id VARCHAR(36) NOT NULL,
|
||||
period_month VARCHAR(7) NOT NULL, -- YYYY-MM
|
||||
period_start TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
period_end TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
|
||||
-- Token 统计
|
||||
total_input_tokens BIGINT DEFAULT 0,
|
||||
total_output_tokens BIGINT DEFAULT 0,
|
||||
total_tokens BIGINT DEFAULT 0,
|
||||
|
||||
-- 请求统计
|
||||
request_count BIGINT DEFAULT 0,
|
||||
error_count BIGINT DEFAULT 0,
|
||||
|
||||
-- 成本
|
||||
total_cost_usd DECIMAL(10, 2) DEFAULT 0.00,
|
||||
|
||||
-- 明细
|
||||
service_breakdown JSONB DEFAULT '{}',
|
||||
model_breakdown JSONB DEFAULT '{}',
|
||||
|
||||
-- 性能指标
|
||||
avg_duration_ms INTEGER,
|
||||
total_duration_ms BIGINT,
|
||||
|
||||
-- 索引
|
||||
UNIQUE(key_id, period_month)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_billing_periods_key ON billing_periods(key_id, period_month);
|
||||
CREATE INDEX idx_billing_periods_month ON billing_periods(period_month);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Token 使用日志表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS token_usage_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
-- 关联信息
|
||||
request_id VARCHAR(36) NOT NULL,
|
||||
key_id VARCHAR(36),
|
||||
queue_name VARCHAR(255),
|
||||
message_id VARCHAR(36),
|
||||
|
||||
-- 服务信息
|
||||
service VARCHAR(50) NOT NULL, -- 'vlm', 'chat', 'embedding'
|
||||
model VARCHAR(100),
|
||||
endpoint VARCHAR(255),
|
||||
|
||||
-- Token 使用
|
||||
input_tokens INTEGER NOT NULL,
|
||||
output_tokens INTEGER NOT NULL,
|
||||
total_tokens INTEGER NOT NULL,
|
||||
|
||||
-- 成本
|
||||
cost_usd DECIMAL(10, 6),
|
||||
|
||||
-- 性能
|
||||
duration_ms INTEGER,
|
||||
|
||||
-- 状态
|
||||
status_code INTEGER,
|
||||
error_message TEXT,
|
||||
|
||||
-- 时间戳
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
-- 索引
|
||||
FOREIGN KEY (request_id) REFERENCES vlm_requests(request_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_token_usage_log_key ON token_usage_log(key_id, created_at);
|
||||
CREATE INDEX idx_token_usage_log_service ON token_usage_log(service, created_at);
|
||||
CREATE INDEX idx_token_usage_log_request ON token_usage_log(request_id);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 用户 Quota 表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS user_quotas (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
user_id VARCHAR(36),
|
||||
|
||||
-- Quota 配置
|
||||
monthly_token_limit BIGINT DEFAULT 1000000, -- 每月 token 上限
|
||||
daily_token_limit BIGINT DEFAULT 50000, -- 每日 token 上限
|
||||
|
||||
-- 当前使用
|
||||
current_month_tokens BIGINT DEFAULT 0,
|
||||
current_day_tokens BIGINT DEFAULT 0,
|
||||
|
||||
-- 重置时间
|
||||
last_month_reset TIMESTAMP WITH TIME ZONE,
|
||||
last_day_reset TIMESTAMP WITH TIME ZONE,
|
||||
|
||||
-- 配额策略
|
||||
quota_policy VARCHAR(20) DEFAULT 'soft', -- 'hard' | 'soft'
|
||||
|
||||
-- 超额处理
|
||||
allow_overage BOOLEAN DEFAULT false,
|
||||
overage_rate DECIMAL(5, 2) DEFAULT 0.0, -- 超额单价
|
||||
|
||||
-- 索引
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_quotas_key ON user_quotas(key_id);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 服务费率表
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS service_rates (
|
||||
id SERIAL PRIMARY KEY,
|
||||
service VARCHAR(50) NOT NULL,
|
||||
model VARCHAR(100),
|
||||
|
||||
-- 价格(每 1000 tokens)
|
||||
input_rate_usd DECIMAL(10, 6) DEFAULT 0.0, -- 输入 token 单价
|
||||
output_rate_usd DECIMAL(10, 6) DEFAULT 0.0, -- 输出 token 单价
|
||||
|
||||
-- 生效时间
|
||||
effective_from TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
effective_to TIMESTAMP WITH TIME ZONE,
|
||||
|
||||
-- 索引
|
||||
UNIQUE(service, model, effective_from)
|
||||
);
|
||||
|
||||
-- 插入默认费率
|
||||
INSERT INTO service_rates (service, model, input_rate_usd, output_rate_usd) VALUES
|
||||
('vlm', 'gemma-4-12b-it', 0.0001, 0.0002),
|
||||
('chat', 'gemma-4-12b-it', 0.00005, 0.0001),
|
||||
('embedding', 'embeddinggemma-300m', 0.00001, 0.0);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 处理流程
|
||||
|
||||
### 流程 1: 消息入队前
|
||||
|
||||
```rust
|
||||
// 1. 检查用户 quota
|
||||
async fn check_quota(&self, key_id: &str) -> Result<bool, BillingError> {
|
||||
let quota = self.db.get_user_quota(key_id).await?;
|
||||
|
||||
// 检查月度 quota
|
||||
if quota.current_month_tokens >= quota.monthly_token_limit {
|
||||
if !quota.allow_overage {
|
||||
return Err(BillingError::QuotaExceeded {
|
||||
limit: quota.monthly_token_limit,
|
||||
used: quota.current_month_tokens,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 检查每日 quota
|
||||
if quota.current_day_tokens >= quota.daily_token_limit {
|
||||
if !quota.allow_overage {
|
||||
return Err(BillingError::DailyQuotaExceeded {
|
||||
limit: quota.daily_token_limit,
|
||||
used: quota.current_day_tokens,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// 2. 创建 billing 上下文
|
||||
async fn create_billing_context(&self, key_id: &str) -> Result<BillingContext, BillingError> {
|
||||
let quota = self.db.get_user_quota(key_id).await?;
|
||||
|
||||
Ok(BillingContext {
|
||||
request_id: Uuid::new_v4().to_string(),
|
||||
key_id: key_id.to_string(),
|
||||
user_id: quota.user_id,
|
||||
quota_limit: quota.monthly_token_limit,
|
||||
quota_used: quota.current_month_tokens,
|
||||
quota_remaining: quota.monthly_token_limit - quota.current_month_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 提交消息(带 billing 上下文)
|
||||
async fn enqueue_with_billing(
|
||||
&self,
|
||||
queue: &str,
|
||||
message: Message,
|
||||
billing_ctx: BillingContext,
|
||||
) -> Result<MessageId, QueueError> {
|
||||
// 将 billing 上下文附加到消息
|
||||
let mut message = message;
|
||||
message.metadata.insert(
|
||||
"billing_context".to_string(),
|
||||
serde_json::to_string(&billing_ctx)?,
|
||||
);
|
||||
|
||||
self.enqueue(queue, message).await
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 2: 消息处理中
|
||||
|
||||
```rust
|
||||
// 1. 开始处理
|
||||
async fn start_processing(&mut self, message: &Message) -> Result<(), BillingError> {
|
||||
let billing_ctx = message.metadata.get("billing_context")
|
||||
.ok_or(BillingError::MissingBillingContext)?;
|
||||
|
||||
let ctx: BillingContext = serde_json::from_str(billing_ctx)?;
|
||||
|
||||
// 更新请求状态为 processing
|
||||
self.db.update_request_status(
|
||||
&ctx.request_id,
|
||||
"processing",
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 2. 处理并追踪 token
|
||||
async fn process_with_tracking(
|
||||
&mut self,
|
||||
message: &Message,
|
||||
) -> Result<ProcessResult, BillingError> {
|
||||
let billing_ctx = self.get_billing_context(message)?;
|
||||
|
||||
// 开始计时
|
||||
let start = Instant::now();
|
||||
|
||||
// 调用服务(VLM/Chat/Embedding)
|
||||
let result = self.call_service(message).await?;
|
||||
|
||||
// 计算 token 使用
|
||||
let token_usage = TokenUsage {
|
||||
input_tokens: result.input_tokens,
|
||||
output_tokens: result.output_tokens,
|
||||
total_tokens: result.input_tokens + result.output_tokens,
|
||||
};
|
||||
|
||||
// 计算成本
|
||||
let cost = self.calculate_cost(&token_usage, &result.model).await?;
|
||||
|
||||
// 更新 quota
|
||||
self.update_quota(&billing_ctx.key_id, &token_usage).await?;
|
||||
|
||||
// 记录到日志
|
||||
self.log_token_usage(LogTokenUsage {
|
||||
request_id: billing_ctx.request_id.clone(),
|
||||
key_id: billing_ctx.key_id.clone(),
|
||||
service: result.service.clone(),
|
||||
model: Some(result.model.clone()),
|
||||
endpoint: None,
|
||||
input_tokens: token_usage.input_tokens,
|
||||
output_tokens: token_usage.output_tokens,
|
||||
total_tokens: token_usage.total_tokens,
|
||||
duration_ms: Some(start.elapsed().as_millis() as i32),
|
||||
status_code: Some(200),
|
||||
error_message: None,
|
||||
}).await?;
|
||||
|
||||
Ok(ProcessResult {
|
||||
result: result.output,
|
||||
token_usage,
|
||||
cost_usd: cost,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 3: 消息处理完成
|
||||
|
||||
```rust
|
||||
// 1. 记录成本
|
||||
async fn record_cost(
|
||||
&self,
|
||||
request_id: &str,
|
||||
cost_usd: f64,
|
||||
token_usage: TokenUsage,
|
||||
) -> Result<(), BillingError> {
|
||||
// 更新 billing_periods
|
||||
self.db.upsert_billing_period(
|
||||
key_id,
|
||||
period_month,
|
||||
token_usage,
|
||||
cost_usd,
|
||||
).await?;
|
||||
|
||||
// 更新消息记录
|
||||
self.db.update_message_billing(
|
||||
request_id,
|
||||
token_usage,
|
||||
cost_usd,
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 2. 更新 quota
|
||||
async fn update_quota(
|
||||
&self,
|
||||
key_id: &str,
|
||||
token_usage: &TokenUsage,
|
||||
) -> Result<(), BillingError> {
|
||||
self.db.increment_quota_usage(
|
||||
key_id,
|
||||
token_usage.total_tokens,
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💰 成本计算
|
||||
|
||||
### 费率配置
|
||||
|
||||
```rust
|
||||
pub struct ServiceRate {
|
||||
pub service: String,
|
||||
pub model: String,
|
||||
pub input_rate_usd: f64, // 每 1000 tokens
|
||||
pub output_rate_usd: f64, // 每 1000 tokens
|
||||
}
|
||||
|
||||
impl ServiceRate {
|
||||
pub fn calculate_cost(&self, usage: &TokenUsage) -> f64 {
|
||||
let input_cost = (usage.input_tokens as f64 / 1000.0) * self.input_rate_usd;
|
||||
let output_cost = (usage.output_tokens as f64 / 1000.0) * self.output_rate_usd;
|
||||
input_cost + output_cost
|
||||
}
|
||||
}
|
||||
|
||||
// 示例
|
||||
let vlm_rate = ServiceRate {
|
||||
service: "vlm".to_string(),
|
||||
model: "gemma-4-12b-it".to_string(),
|
||||
input_rate_usd: 0.0001,
|
||||
output_rate_usd: 0.0002,
|
||||
};
|
||||
|
||||
let usage = TokenUsage {
|
||||
input_tokens: 500,
|
||||
output_tokens: 300,
|
||||
total_tokens: 800,
|
||||
};
|
||||
|
||||
let cost = vlm_rate.calculate_cost(&usage);
|
||||
// cost = (500/1000 * 0.0001) + (300/1000 * 0.0002) = 0.00011 USD
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 集成
|
||||
|
||||
### 1. Billing API 扩展
|
||||
|
||||
```rust
|
||||
// GET /api/v1/billing/usage
|
||||
pub async fn get_usage(
|
||||
key_id: Option<String>,
|
||||
period: String,
|
||||
) -> Result<UsageResponse, BillingError> {
|
||||
let periods = db.get_billing_periods(key_id, &period).await?;
|
||||
|
||||
Ok(UsageResponse {
|
||||
key_id,
|
||||
period,
|
||||
tokens: TokenStats {
|
||||
input: periods.total_input_tokens,
|
||||
output: periods.total_output_tokens,
|
||||
total: periods.total_tokens,
|
||||
},
|
||||
services: periods.service_breakdown,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/billing/quota
|
||||
pub async fn get_quota(key_id: String) -> Result<QuotaResponse, BillingError> {
|
||||
let quota = db.get_user_quota(&key_id).await?;
|
||||
|
||||
Ok(QuotaResponse {
|
||||
key_id: quota.key_id,
|
||||
monthly_limit: quota.monthly_token_limit,
|
||||
daily_limit: quota.daily_token_limit,
|
||||
current_month_used: quota.current_month_tokens,
|
||||
current_day_used: quota.current_day_tokens,
|
||||
quota_remaining: quota.monthly_token_limit - quota.current_month_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/billing/history
|
||||
pub async fn get_history(
|
||||
key_id: String,
|
||||
limit: i32,
|
||||
) -> Result<HistoryResponse, BillingError> {
|
||||
let periods = db.get_billing_history(&key_id, limit).await?;
|
||||
|
||||
Ok(HistoryResponse {
|
||||
periods: periods.into_iter().map(|p| PeriodSummary {
|
||||
period: p.period_month,
|
||||
total_tokens: p.total_tokens,
|
||||
request_count: p.request_count,
|
||||
}).collect(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Queue API 扩展
|
||||
|
||||
```rust
|
||||
// POST /api/v1/queues/{name}/messages (with billing)
|
||||
pub async fn produce_message(
|
||||
queue_name: String,
|
||||
request: ProduceRequest,
|
||||
auth: UserAuth,
|
||||
) -> Result<ProduceResponse, QueueError> {
|
||||
// 1. 检查 quota
|
||||
billing.check_quota(&auth.key_id).await?;
|
||||
|
||||
// 2. 创建 billing 上下文
|
||||
let billing_ctx = billing.create_billing_context(&auth.key_id).await?;
|
||||
|
||||
// 3. 提交消息
|
||||
let message = Message {
|
||||
key: request.key,
|
||||
value: request.value,
|
||||
priority: request.priority,
|
||||
metadata: {
|
||||
let mut m = request.metadata;
|
||||
m.insert("billing_context", serde_json::to_string(&billing_ctx)?);
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
let response = queue.enqueue(&queue_name, message).await?;
|
||||
|
||||
Ok(ProduceResponse {
|
||||
message_id: response.message_id,
|
||||
offset: response.offset,
|
||||
timestamp: response.timestamp,
|
||||
quota_remaining: billing_ctx.quota_remaining,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 监控与告警
|
||||
|
||||
### 1. 监控指标
|
||||
|
||||
```rust
|
||||
// Prometheus 指标
|
||||
lazy_static! {
|
||||
static ref TOKENS_USED_TOTAL: Counter = register_counter!(
|
||||
"billing_tokens_used_total",
|
||||
"Total tokens used",
|
||||
vec!["service", "model"]
|
||||
).unwrap();
|
||||
|
||||
static ref QUOTA_USAGE_RATIO: Gauge = register_gauge!(
|
||||
"billing_quota_usage_ratio",
|
||||
"Quota usage ratio",
|
||||
vec!["key_id"]
|
||||
).unwrap();
|
||||
|
||||
static ref COST_TOTAL: Counter = register_counter!(
|
||||
"billing_cost_total_usd",
|
||||
"Total cost in USD",
|
||||
vec!["service"]
|
||||
).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 告警规则
|
||||
|
||||
```yaml
|
||||
# Prometheus AlertManager 规则
|
||||
groups:
|
||||
- name: billing
|
||||
rules:
|
||||
- alert: QuotaNearLimit
|
||||
expr: billing_quota_usage_ratio > 0.9
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Quota near limit for {{ $labels.key_id }}"
|
||||
description: "Usage at {{ $value }}%"
|
||||
|
||||
- alert: QuotaExceeded
|
||||
expr: billing_quota_usage_ratio >= 1.0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Quota exceeded for {{ $labels.key_id }}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 数据库扩展(1 天)
|
||||
|
||||
- [ ] 创建 billing 相关表
|
||||
- [ ] 扩展 vlm_requests 表
|
||||
- [ ] 创建索引
|
||||
|
||||
### Phase 2: Billing 集成(2 天)
|
||||
|
||||
- [ ] 实现 BillingManager
|
||||
- [ ] 实现 quota 检查
|
||||
- [ ] 实现成本计算
|
||||
|
||||
### Phase 3: 队列集成(2 天)
|
||||
|
||||
- [ ] 修改 produce API
|
||||
- [ ] 修改 consume 流程
|
||||
- [ ] 添加 billing 追踪
|
||||
|
||||
### Phase 4: 监控与测试(1 天)
|
||||
|
||||
- [ ] 添加监控指标
|
||||
- [ ] 配置告警规则
|
||||
- [ ] 集成测试
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- Billing API 文档: `docs_v1.0/API_WORKSPACE/modules/billing_api.md`
|
||||
- Quota 管理指南: `docs_v1.0/GUIDES/quota_management.md`
|
||||
- 成本计算规则: `docs_v1.0/OPERATIONS/cost_calculation.md`
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,819 @@
|
||||
# MarkBase 统一命令队列架构设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**目标**: 所有命令通过 MarkBase Queue 统一处理
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
| 目标 | 说明 | 优先级 |
|
||||
|------|------|:------:|
|
||||
| **统一入口** | 所有命令通过统一队列入口 | 🔴 P0 |
|
||||
| **解耦通信** | 系统组件通过队列异步通信 | 🔴 P0 |
|
||||
| **可追溯性** | 所有命令可追踪、审计 | 🔴 P0 |
|
||||
| **Billing 集成** | 每个命令关联 Billing | 🔴 P0 |
|
||||
| **优先级调度** | 按优先级处理命令 | 🟡 P1 |
|
||||
|
||||
---
|
||||
|
||||
## 📊 命令分类体系
|
||||
|
||||
### 1. 命令类型定义
|
||||
|
||||
```rust
|
||||
/// 命令类型
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CommandType {
|
||||
// ========== 内部命令 ==========
|
||||
Internal {
|
||||
category: InternalCommandCategory,
|
||||
},
|
||||
|
||||
// ========== 外部命令 ==========
|
||||
External {
|
||||
category: ExternalCommandCategory,
|
||||
},
|
||||
|
||||
// ========== Agent 沟通命令 ==========
|
||||
Agent {
|
||||
category: AgentCommandCategory,
|
||||
},
|
||||
}
|
||||
|
||||
/// 内部命令分类
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InternalCommandCategory {
|
||||
// 文件处理
|
||||
FileProcessing,
|
||||
VideoRegistration,
|
||||
FileDeletion,
|
||||
|
||||
// 数据处理
|
||||
EmbeddingGeneration,
|
||||
IndexRebuild,
|
||||
CacheClear,
|
||||
|
||||
// 系统管理
|
||||
WorkerRestart,
|
||||
ServiceHealthCheck,
|
||||
ConfigurationUpdate,
|
||||
|
||||
// 数据同步
|
||||
DatabaseMigration,
|
||||
VectorSync,
|
||||
IdentityMerging,
|
||||
}
|
||||
|
||||
/// 外部命令分类
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ExternalCommandCategory {
|
||||
// API 命令
|
||||
ApiRequest,
|
||||
UserCommand,
|
||||
|
||||
// Webhook
|
||||
WebhookTrigger,
|
||||
|
||||
// 第三方集成
|
||||
IntegrationSync,
|
||||
ExternalApiCall,
|
||||
}
|
||||
|
||||
/// Agent 沟通命令分类
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AgentCommandCategory {
|
||||
// Agent 协作
|
||||
AgentTask,
|
||||
AgentQuery,
|
||||
AgentResponse,
|
||||
|
||||
// Agent 沟通
|
||||
AgentMessage,
|
||||
AgentBroadcast,
|
||||
AgentSubscribe,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 命令优先级
|
||||
|
||||
```rust
|
||||
/// 命令优先级
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CommandPriority {
|
||||
/// P0: 最高优先级(Agent 即时响应)
|
||||
Critical = 0,
|
||||
|
||||
/// P1: 高优先级(API 用户请求)
|
||||
High = 1,
|
||||
|
||||
/// P2: 中优先级(内部处理任务)
|
||||
Normal = 2,
|
||||
|
||||
/// P3: 低优先级(后台任务)
|
||||
Low = 3,
|
||||
}
|
||||
|
||||
impl CommandType {
|
||||
/// 获取默认优先级
|
||||
pub fn default_priority(&self) -> CommandPriority {
|
||||
match self {
|
||||
// Agent 命令最高优先级
|
||||
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,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 队列架构设计
|
||||
|
||||
### 1. 整体架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ MarkBase Queue Service │
|
||||
├─────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Command Router (命令路由器) │ │
|
||||
│ │ ├─ 分类命令类型 │ │
|
||||
│ │ ├─ 分配优先级 │ │
|
||||
│ │ ├─ 路由到对应队列 │ │
|
||||
│ │ └─ 记录命令日志 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Queue Manager (队列管理器) │ │
|
||||
│ │ │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │ Internal │ │ External │ │ Agent │ │ System │ │ │
|
||||
│ │ │ Queue │ │ Queue │ │ Queue │ │ Queue │ │ │
|
||||
│ │ │ (P2-P3) │ │ (P0-P1) │ │ (P0) │ │ (P0-P3) │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Command Dispatcher (命令分发器) │ │
|
||||
│ │ ├─ 分发到对应处理器 │ │
|
||||
│ │ ├─ 执行命令 │ │
|
||||
│ │ ├─ 追踪执行状态 │ │
|
||||
│ │ └─ 记录执行结果 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Command Handlers │
|
||||
├─────────────────────────────────────────────────────────────────────┤
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ File │ │ Video │ │ Agent │ │ API │ │
|
||||
│ │ Handler │ │ Handler │ │ Handler │ │ Handler │ │
|
||||
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 队列定义
|
||||
|
||||
```sql
|
||||
-- 命令队列表
|
||||
CREATE TABLE IF NOT EXISTS command_queue (
|
||||
-- 消息 ID
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
message_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
|
||||
-- 队列信息
|
||||
queue_name VARCHAR(255) NOT NULL,
|
||||
queue_type VARCHAR(50) NOT NULL, -- 'internal' | 'external' | 'agent' | 'system'
|
||||
|
||||
-- 命令信息
|
||||
command_type VARCHAR(100) NOT NULL,
|
||||
command_category VARCHAR(100),
|
||||
command_action VARCHAR(100),
|
||||
|
||||
-- 消息内容
|
||||
key VARCHAR(255),
|
||||
value JSONB NOT NULL,
|
||||
|
||||
-- 优先级
|
||||
priority SMALLINT DEFAULT 2, -- 0=Critical, 1=High, 2=Normal, 3=Low
|
||||
|
||||
-- Billing 信息
|
||||
request_id VARCHAR(36),
|
||||
key_id VARCHAR(36),
|
||||
billing_context JSONB,
|
||||
token_usage JSONB,
|
||||
cost_usd DECIMAL(10, 6),
|
||||
|
||||
-- 状态管理
|
||||
status VARCHAR(20) DEFAULT 'pending', -- 'pending' | 'processing' | 'completed' | 'failed'
|
||||
consumer_group VARCHAR(255),
|
||||
consumer_id VARCHAR(255),
|
||||
|
||||
-- 重试机制
|
||||
retry_count INTEGER DEFAULT 0,
|
||||
max_retries INTEGER DEFAULT 3,
|
||||
last_error TEXT,
|
||||
|
||||
-- 时间戳
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
scheduled_at TIMESTAMP WITH TIME ZONE,
|
||||
processing_started_at TIMESTAMP WITH TIME ZONE,
|
||||
processing_completed_at TIMESTAMP WITH TIME ZONE,
|
||||
|
||||
-- 索引
|
||||
INDEX idx_queue_name (queue_name, priority, created_at),
|
||||
INDEX idx_status (status, created_at),
|
||||
INDEX idx_consumer (consumer_group, consumer_id),
|
||||
INDEX idx_command_type (command_type, created_at),
|
||||
INDEX idx_billing (request_id, key_id)
|
||||
);
|
||||
|
||||
-- 命令执行日志
|
||||
CREATE TABLE IF NOT EXISTS command_execution_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
message_id VARCHAR(36) NOT NULL,
|
||||
|
||||
-- 执行信息
|
||||
handler VARCHAR(255),
|
||||
action VARCHAR(255),
|
||||
|
||||
-- 执行结果
|
||||
status VARCHAR(20), -- 'success' | 'error' | 'timeout'
|
||||
result JSONB,
|
||||
error_message TEXT,
|
||||
|
||||
-- 性能指标
|
||||
duration_ms INTEGER,
|
||||
tokens_used INTEGER,
|
||||
cost_usd DECIMAL(10, 6),
|
||||
|
||||
-- 时间戳
|
||||
executed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
FOREIGN KEY (message_id) REFERENCES command_queue(message_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_execution_log_message ON command_execution_log(message_id, executed_at);
|
||||
CREATE INDEX idx_execution_log_status ON command_execution_log(status, executed_at);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 命令流程设计
|
||||
|
||||
### 流程 1: 内部命令流程
|
||||
|
||||
```rust
|
||||
// 示例:视频注册命令
|
||||
async fn register_video_internal(
|
||||
file_path: &str,
|
||||
options: RegisterOptions,
|
||||
) -> Result<CommandId, CommandError> {
|
||||
// 1. 创建命令
|
||||
let command = Command {
|
||||
command_type: CommandType::Internal {
|
||||
category: InternalCommandCategory::VideoRegistration,
|
||||
},
|
||||
payload: json!({
|
||||
"file_path": file_path,
|
||||
"options": options,
|
||||
}),
|
||||
priority: CommandPriority::Normal,
|
||||
metadata: {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("source", "internal");
|
||||
m.insert("triggered_by", "system");
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 2. 提交到队列
|
||||
let message_id = command_queue.produce(
|
||||
"internal.commands",
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(command.priority as i32),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 3. 返回命令 ID
|
||||
Ok(CommandId(message_id))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 2: 外部命令流程
|
||||
|
||||
```rust
|
||||
// 示例:API 用户命令
|
||||
async fn handle_api_command(
|
||||
api_key: &str,
|
||||
command_request: CommandRequest,
|
||||
) -> Result<CommandResponse, CommandError> {
|
||||
// 1. 验证 API Key
|
||||
let user = auth.verify_api_key(api_key).await?;
|
||||
|
||||
// 2. 检查 Billing Quota
|
||||
billing.check_quota(&user.key_id).await?;
|
||||
|
||||
// 3. 创建 billing 上下文
|
||||
let billing_ctx = billing.create_billing_context(&user.key_id).await?;
|
||||
|
||||
// 4. 创建命令
|
||||
let command = Command {
|
||||
command_type: CommandType::External {
|
||||
category: ExternalCommandCategory::ApiRequest,
|
||||
},
|
||||
payload: command_request.payload,
|
||||
priority: CommandPriority::High,
|
||||
metadata: {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("billing_context", serde_json::to_string(&billing_ctx)?);
|
||||
m.insert("api_key", api_key.to_string());
|
||||
m.insert("user_id", user.user_id.to_string());
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 5. 提交到队列
|
||||
let message_id = command_queue.produce(
|
||||
"external.commands",
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(command.priority as i32),
|
||||
billing_context: Some(billing_ctx.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 6. 返回响应
|
||||
Ok(CommandResponse {
|
||||
command_id: message_id.clone(),
|
||||
status: "queued".to_string(),
|
||||
billing: BillingInfo {
|
||||
quota_remaining: billing_ctx.quota_remaining,
|
||||
},
|
||||
message: "Command queued successfully".to_string(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 流程 3: Agent 沟通流程
|
||||
|
||||
```rust
|
||||
// 示例:Agent 间消息传递
|
||||
async fn send_agent_message(
|
||||
from_agent: &str,
|
||||
to_agent: &str,
|
||||
message_type: AgentMessageType,
|
||||
content: JsonValue,
|
||||
) -> Result<CommandId, CommandError> {
|
||||
// 1. 创建命令
|
||||
let command = Command {
|
||||
command_type: CommandType::Agent {
|
||||
category: AgentCommandCategory::AgentMessage,
|
||||
},
|
||||
payload: json!({
|
||||
"from": from_agent,
|
||||
"to": to_agent,
|
||||
"message_type": message_type,
|
||||
"content": content,
|
||||
}),
|
||||
priority: CommandPriority::Critical, // Agent 消息最高优先级
|
||||
metadata: {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("source", "agent");
|
||||
m.insert("from_agent", from_agent.to_string());
|
||||
m.insert("to_agent", to_agent.to_string());
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 2. 提交到 Agent 队列
|
||||
let message_id = command_queue.produce(
|
||||
&format!("agent.{}", to_agent),
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(CommandPriority::Critical as i32),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 3. 通知目标 Agent
|
||||
notify_agent(to_agent, &message_id).await?;
|
||||
|
||||
Ok(CommandId(message_id))
|
||||
}
|
||||
|
||||
// Agent 订阅队列
|
||||
async fn subscribe_agent_queue(
|
||||
agent_id: &str,
|
||||
handler: impl Fn(AgentMessage) -> Future<Output = Result<(), AgentError>> + Send + Sync + 'static,
|
||||
) -> Result<(), CommandError> {
|
||||
// 订阅专属队列
|
||||
command_queue.consume(
|
||||
&format!("agent.{}", agent_id),
|
||||
ConsumeOptions {
|
||||
consumer_group: format!("agent_{}", agent_id),
|
||||
consumer_id: format!("agent_{}_worker", agent_id),
|
||||
..Default::default()
|
||||
},
|
||||
|message| async {
|
||||
// 解析命令
|
||||
let command: Command = serde_json::from_str(&message.value)?;
|
||||
|
||||
// 提取 Agent 消息
|
||||
let agent_message = AgentMessage::from_command(command)?;
|
||||
|
||||
// 调用 handler
|
||||
handler(agent_message).await?;
|
||||
|
||||
// 提交 offset
|
||||
message.commit().await?;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
).await
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔀 命令路由设计
|
||||
|
||||
### 1. 路由规则
|
||||
|
||||
```rust
|
||||
pub struct CommandRouter {
|
||||
routes: HashMap<CommandType, QueueRoute>,
|
||||
}
|
||||
|
||||
/// 队列路由规则
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QueueRoute {
|
||||
pub queue_name: String,
|
||||
pub handler: String,
|
||||
pub priority: CommandPriority,
|
||||
pub billing_required: bool,
|
||||
}
|
||||
|
||||
impl CommandRouter {
|
||||
/// 根据命令类型路由到对应队列
|
||||
pub fn route(&self, command: &Command) -> Result<QueueRoute, RouterError> {
|
||||
// 查找路由规则
|
||||
if let Some(route) = self.routes.get(&command.command_type) {
|
||||
return Ok(route.clone());
|
||||
}
|
||||
|
||||
// 默认路由
|
||||
Ok(QueueRoute {
|
||||
queue_name: "default".to_string(),
|
||||
handler: "default_handler".to_string(),
|
||||
priority: command.command_type.default_priority(),
|
||||
billing_required: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// 注册路由
|
||||
pub fn register_route(&mut self, command_type: CommandType, route: QueueRoute) {
|
||||
self.routes.insert(command_type, route);
|
||||
}
|
||||
}
|
||||
|
||||
// 路由配置示例
|
||||
fn setup_router() -> CommandRouter {
|
||||
let mut router = CommandRouter::new();
|
||||
|
||||
// 内部命令路由
|
||||
router.register_route(
|
||||
CommandType::Internal { category: InternalCommandCategory::VideoRegistration },
|
||||
QueueRoute {
|
||||
queue_name: "internal.video".to_string(),
|
||||
handler: "video_registration_handler".to_string(),
|
||||
priority: CommandPriority::Normal,
|
||||
billing_required: true,
|
||||
},
|
||||
);
|
||||
|
||||
// 外部命令路由
|
||||
router.register_route(
|
||||
CommandType::External { category: ExternalCommandCategory::ApiRequest },
|
||||
QueueRoute {
|
||||
queue_name: "external.api".to_string(),
|
||||
handler: "api_request_handler".to_string(),
|
||||
priority: CommandPriority::High,
|
||||
billing_required: true,
|
||||
},
|
||||
);
|
||||
|
||||
// Agent 命令路由
|
||||
router.register_route(
|
||||
CommandType::Agent { category: AgentCommandCategory::AgentMessage },
|
||||
QueueRoute {
|
||||
queue_name: "agent.messages".to_string(),
|
||||
handler: "agent_message_handler".to_string(),
|
||||
priority: CommandPriority::Critical,
|
||||
billing_required: false, // Agent 消息不计费
|
||||
},
|
||||
);
|
||||
|
||||
router
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎮 命令分发器设计
|
||||
|
||||
### 1. 处理器注册
|
||||
|
||||
```rust
|
||||
pub struct CommandDispatcher {
|
||||
handlers: HashMap<String, Box<dyn CommandHandler>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait CommandHandler: Send + Sync {
|
||||
async fn handle(&self, command: Command) -> Result<CommandResult, CommandError>;
|
||||
}
|
||||
|
||||
impl CommandDispatcher {
|
||||
/// 注册处理器
|
||||
pub fn register<H: CommandHandler + 'static>(&mut self, name: &str, handler: H) {
|
||||
self.handlers.insert(name.to_string(), Box::new(handler));
|
||||
}
|
||||
|
||||
/// 分发命令
|
||||
pub async fn dispatch(&self, message: QueueMessage) -> Result<CommandResult, CommandError> {
|
||||
// 解析命令
|
||||
let command: Command = serde_json::from_str(&message.value)?;
|
||||
|
||||
// 获取路由
|
||||
let route = message.metadata.get("route")
|
||||
.ok_or(CommandError::MissingRoute)?;
|
||||
|
||||
// 查找处理器
|
||||
let handler = self.handlers.get(route.handler)
|
||||
.ok_or(CommandError::HandlerNotFound(route.handler.clone()))?;
|
||||
|
||||
// 执行命令
|
||||
let result = handler.handle(command).await?;
|
||||
|
||||
// 记录执行日志
|
||||
self.log_execution(&message.message_id, &route.handler, &result).await?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 设计
|
||||
|
||||
### 1. 命令提交 API
|
||||
|
||||
```rust
|
||||
// POST /api/v1/commands
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SubmitCommandRequest {
|
||||
pub command_type: CommandType,
|
||||
pub payload: JsonValue,
|
||||
pub priority: Option<CommandPriority>,
|
||||
pub scheduled_at: Option<DateTime<Utc>>,
|
||||
pub metadata: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SubmitCommandResponse {
|
||||
pub command_id: String,
|
||||
pub queue_name: String,
|
||||
pub status: String,
|
||||
pub priority: CommandPriority,
|
||||
pub billing: BillingInfo,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// 处理函数
|
||||
pub async fn submit_command(
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Extension(billing): Extension<Arc<BillingManager>>,
|
||||
Extension(queue): Extension<Arc<CommandQueue>>,
|
||||
Json(req): Json<SubmitCommandRequest>,
|
||||
) -> Result<Json<SubmitCommandResponse>, APIError> {
|
||||
// 1. 检查 quota
|
||||
billing.check_quota(&auth.key_id).await?;
|
||||
|
||||
// 2. 创建 billing 上下文
|
||||
let billing_ctx = billing.create_billing_context(&auth.key_id).await?;
|
||||
|
||||
// 3. 路由命令
|
||||
let route = queue.router().route(&req.command_type)?;
|
||||
|
||||
// 4. 创建命令
|
||||
let command = Command {
|
||||
command_type: req.command_type,
|
||||
payload: req.payload,
|
||||
priority: req.priority.unwrap_or_else(|| req.command_type.default_priority()),
|
||||
metadata: {
|
||||
let mut m = req.metadata.unwrap_or_default();
|
||||
m.insert("billing_context".to_string(), serde_json::to_string(&billing_ctx)?);
|
||||
m.insert("api_key".to_string(), auth.key_id.clone());
|
||||
m
|
||||
},
|
||||
};
|
||||
|
||||
// 5. 提交到队列
|
||||
let message_id = queue.produce(
|
||||
&route.queue_name,
|
||||
command,
|
||||
ProduceOptions {
|
||||
priority: Some(command.priority as i32),
|
||||
scheduled_at: req.scheduled_at,
|
||||
billing_context: Some(billing_ctx.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
).await?;
|
||||
|
||||
// 6. 返回响应
|
||||
Ok(Json(SubmitCommandResponse {
|
||||
command_id: message_id.clone(),
|
||||
queue_name: route.queue_name,
|
||||
status: "queued".to_string(),
|
||||
priority: command.priority,
|
||||
billing: BillingInfo {
|
||||
quota_remaining: billing_ctx.quota_remaining,
|
||||
},
|
||||
created_at: Utc::now(),
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 命令查询 API
|
||||
|
||||
```rust
|
||||
// GET /api/v1/commands/{command_id}
|
||||
pub async fn get_command_status(
|
||||
Path(command_id): Path<String>,
|
||||
Extension(queue): Extension<Arc<CommandQueue>>,
|
||||
) -> Result<Json<CommandStatusResponse>, APIError> {
|
||||
let status = queue.get_command_status(&command_id).await?;
|
||||
|
||||
Ok(Json(status))
|
||||
}
|
||||
|
||||
// GET /api/v1/commands?status=pending&queue=external.api
|
||||
pub async fn list_commands(
|
||||
Query(params): Query<ListCommandsQuery>,
|
||||
Extension(queue): Extension<Arc<CommandQueue>>,
|
||||
) -> Result<Json<ListCommandsResponse>, APIError> {
|
||||
let commands = queue.list_commands(ListOptions {
|
||||
queue_name: params.queue,
|
||||
status: params.status,
|
||||
limit: params.limit.unwrap_or(100),
|
||||
offset: params.offset.unwrap_or(0),
|
||||
}).await?;
|
||||
|
||||
Ok(Json(ListCommandsResponse {
|
||||
commands,
|
||||
total: commands.len(),
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 监控指标
|
||||
|
||||
```rust
|
||||
lazy_static! {
|
||||
// 命令计数
|
||||
static ref COMMANDS_TOTAL: CounterVec = register_counter_vec!(
|
||||
"command_queue_commands_total",
|
||||
"Total commands processed",
|
||||
&["queue", "type", "status"]
|
||||
).unwrap();
|
||||
|
||||
// 队列长度
|
||||
static ref QUEUE_LENGTH: GaugeVec = register_gauge_vec!(
|
||||
"command_queue_length",
|
||||
"Current queue length",
|
||||
&["queue"]
|
||||
).unwrap();
|
||||
|
||||
// 命令延迟
|
||||
static ref COMMAND_LATENCY: HistogramVec = register_histogram_vec!(
|
||||
"command_queue_latency_seconds",
|
||||
"Command processing latency",
|
||||
&["queue", "type"]
|
||||
).unwrap();
|
||||
|
||||
// 命令错误率
|
||||
static ref COMMAND_ERRORS: CounterVec = register_counter_vec!(
|
||||
"command_queue_errors_total",
|
||||
"Total command errors",
|
||||
&["queue", "type", "error"]
|
||||
).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 数据库与模型(2 天)
|
||||
|
||||
- [ ] 创建 command_queue 表
|
||||
- [ ] 创建 command_execution_log 表
|
||||
- [ ] 实现命令类型定义
|
||||
- [ ] 实现优先级系统
|
||||
|
||||
### Phase 2: 队列核心(3 天)
|
||||
|
||||
- [ ] 实现 CommandQueue
|
||||
- [ ] 实现 CommandRouter
|
||||
- [ ] 实现 CommandDispatcher
|
||||
- [ ] 实现命令处理器接口
|
||||
|
||||
### Phase 3: 内部命令集成(2 天)
|
||||
|
||||
- [ ] 迁移视频注册到队列
|
||||
- [ ] 迁移文件处理到队列
|
||||
- [ ] 迁移数据处理到队列
|
||||
|
||||
### Phase 4: 外部命令集成(2 天)
|
||||
|
||||
- [ ] 实现 API 命令提交
|
||||
- [ ] 实现命令查询
|
||||
- [ ] 集成 Billing
|
||||
|
||||
### Phase 5: Agent 沟通集成(3 天)
|
||||
|
||||
- [ ] 实现 Agent 消息队列
|
||||
- [ ] 实现 Agent 订阅机制
|
||||
- [ ] 实现 Agent 广播机制
|
||||
|
||||
### Phase 6: 监控与测试(2 天)
|
||||
|
||||
- [ ] 添加监控指标
|
||||
- [ ] 配置告警
|
||||
- [ ] 集成测试
|
||||
- [ ] 性能测试
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- Billing 集成: `docs_v1.0/DESIGN/MarkBase_Queue_Billing_Integration.md`
|
||||
- API 文档: `docs_v1.0/API_WORKSPACE/modules/command_api.md`
|
||||
- 运维指南: `docs_v1.0/GUIDES/command_queue_operations.md`
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,297 @@
|
||||
# 文件处理流程对比 - V1 vs V2
|
||||
|
||||
**日期**: 2026-10-10
|
||||
|
||||
---
|
||||
|
||||
## 对比概览
|
||||
|
||||
### V1: 过程导向 (原设计)
|
||||
|
||||
| 阶段 | 名称 | 产出 | 可查看性 |
|
||||
|------|------|------|----------|
|
||||
| 1 | Processors | ❌ 模糊 | ❌ 无 |
|
||||
| 2 | Rule1 Ingestion | ❌ 模糊 | ❌ 无 |
|
||||
| 3 | Face Tracing | ❌ 模糊 | ❌ 无 |
|
||||
| 4 | Face Dedup | ❌ 模糊 | ❌ 无 |
|
||||
| 5 | TKG Nodes | ❌ 模糊 | ❌ 无 |
|
||||
| 6 | TKG Edges | ❌ 模糊 | ❌ 无 |
|
||||
| 7 | Rule2 Ingestion | ❌ 模糊 | ❌ 无 |
|
||||
| 8 | VLM Summary | ❌ 模糊 | ❌ 无 |
|
||||
| 9 | Scene VLM | ❌ 模糊 | ❌ 无 |
|
||||
| 10 | Moment Chunks | ❌ 模糊 | ❌ 无 |
|
||||
|
||||
**问题**:
|
||||
- ❌ 用户不知道每个阶段产生什么
|
||||
- ❌ 无法查看中间结果
|
||||
- ❌ 技术术语难理解
|
||||
|
||||
---
|
||||
|
||||
### V2: 产出导向 (新设计)
|
||||
|
||||
| 阶段 | 名称 | 产出 | 可查看方式 |
|
||||
|------|------|------|------------|
|
||||
| 1 | 媒体分析 | ✅ `{file_uuid}.workspace.sqlite` | SQLite Browser |
|
||||
| 2 | 文本块 | ✅ PostgreSQL `chunks` 表 | `/api/v1/chunks` |
|
||||
| 3 | 人脸轨迹 | ✅ `{file_uuid}.faces.json` | `/api/v1/faces/tracks` |
|
||||
| 4 | 身份识别 | ✅ PostgreSQL `identities` 表 | `/api/v1/identities` |
|
||||
| 5 | 知识图谱 | ✅ PostgreSQL `tkg_*` 表 | `/api/v1/tkg/nodes` |
|
||||
| 6 | 向量索引 | ✅ Qdrant collections | `/api/v1/search/semantic` |
|
||||
| 7 | 人脸描述 | ✅ `{file_uuid}.face_vlm.json` | `/api/v1/faces/tracks/{id}` |
|
||||
| 8 | 场景描述 | ✅ `{file_uuid}.scene_vlm.json` | `/api/v1/scenes` |
|
||||
| 9 | 时刻块 | ✅ PostgreSQL `moment_chunks` 表 | `/api/v1/moments` |
|
||||
|
||||
**改进**:
|
||||
- ✅ 每个阶段都有明确产品
|
||||
- ✅ 每个产品都可查看
|
||||
- ✅ 直观易懂
|
||||
|
||||
---
|
||||
|
||||
## 详细对比
|
||||
|
||||
### 阶段 1: Processors → 媒体分析
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段: Processors
|
||||
产出: ❌ 模糊(各种处理结果)
|
||||
查看: ❌ 无法直接查看
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段: 媒体分析
|
||||
产出: ✅ {file_uuid}.workspace.sqlite
|
||||
├── pre_chunks (原始文本块)
|
||||
├── face_detections (人脸检测)
|
||||
├── speaker_detections (说话人)
|
||||
└── processor_results (处理结果)
|
||||
查看: ✅ SQLite Browser / sqlite3 命令
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 2-4: 数据处理 → 文本块 + 人脸 + 身份
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 2: Rule1 Ingestion
|
||||
产出: ❌ PostgreSQL 文本块导入
|
||||
查看: ❌ 无API
|
||||
|
||||
阶段 3: Face Tracing
|
||||
产出: ❌ 人脸追踪与轨迹生成
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 4: Face Dedup
|
||||
产出: ❌ 人脸去重与聚类
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 2: 文本块
|
||||
产出: ✅ PostgreSQL chunks 表
|
||||
查看: ✅ GET /api/v1/chunks?file_uuid={uuid}
|
||||
|
||||
阶段 3: 人脸轨迹
|
||||
产出: ✅ {file_uuid}.faces.json
|
||||
查看: ✅ GET /api/v1/faces/tracks?file_uuid={uuid}
|
||||
|
||||
阶段 4: 身份识别
|
||||
产出: ✅ PostgreSQL identities 表
|
||||
查看: ✅ GET /api/v1/identities
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 5-6: TKG → 知识图谱
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 5: TKG Nodes
|
||||
产出: ❌ 时序知识图谱节点构建
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 6: TKG Edges
|
||||
产出: ❌ 时序知识图谱边构建
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 5: 知识图谱
|
||||
产出: ✅ PostgreSQL tkg_nodes + tkg_edges
|
||||
├── tkg_nodes (节点: face_track, speaker, etc.)
|
||||
└── tkg_edges (边: same_identity, speaks_in, etc.)
|
||||
查看: ✅ GET /api/v1/tkg/nodes?file_uuid={uuid}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 7: Rule2 → 向量索引
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 7: Rule2 Ingestion
|
||||
产出: ❌ Qdrant 向量导入
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 6: 向量索引
|
||||
产出: ✅ Qdrant Collections
|
||||
├── _chunks (文本向量)
|
||||
├── _faces (人脸向量)
|
||||
└── _scenes (场景向量)
|
||||
查看: ✅ POST /api/v1/search/semantic
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段 8-10: VLM → 人脸描述 + 场景描述 + 时刻块
|
||||
|
||||
**V1**:
|
||||
```
|
||||
阶段 8: VLM Summary
|
||||
产出: ❌ Face Track VLM 摘要
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 9: Scene VLM
|
||||
产出: ❌ 场景级 VLM 分析
|
||||
查看: ❌ 无
|
||||
|
||||
阶段 10: Moment Chunks
|
||||
产出: ❌ 时刻块生成
|
||||
查看: ❌ 无
|
||||
```
|
||||
|
||||
**V2**:
|
||||
```
|
||||
阶段 7: 人脸描述
|
||||
产出: ✅ {file_uuid}.face_vlm.json
|
||||
查看: ✅ GET /api/v1/faces/tracks/{trace_id}
|
||||
|
||||
阶段 8: 场景描述
|
||||
产出: ✅ {file_uuid}.scene_vlm.json
|
||||
查看: ✅ GET /api/v1/scenes?file_uuid={uuid}
|
||||
|
||||
阶段 9: 时刻块
|
||||
产出: ✅ PostgreSQL moment_chunks 表
|
||||
查看: ✅ GET /api/v1/moments?file_uuid={uuid}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 产出类型对比
|
||||
|
||||
### V1: 抽象概念
|
||||
|
||||
| 类型 | 占比 | 说明 |
|
||||
|------|------|------|
|
||||
| 过程 | 100% | 全是过程,无明确产出 |
|
||||
| 文件 | 0% | 无可查看文件 |
|
||||
| 数据 | 0% | 无可访问数据 |
|
||||
|
||||
### V2: 具体产品
|
||||
|
||||
| 类型 | 占比 | 说明 |
|
||||
|------|------|------|
|
||||
| 文件产物 | 44% | .sqlite, .json 文件 |
|
||||
| 数据库产物 | 56% | PostgreSQL, Qdrant |
|
||||
|
||||
---
|
||||
|
||||
## 用户理解度对比
|
||||
|
||||
### V1: 需要技术背景
|
||||
|
||||
**问题**:
|
||||
- ❌ "Processors" 是什么?
|
||||
- ❌ "Rule1 Ingestion" 做什么?
|
||||
- ❌ "Face Dedup" 产出什么?
|
||||
- ❌ "TKG Edges" 有什么用?
|
||||
|
||||
**结果**: 用户困惑,无法理解进度
|
||||
|
||||
### V2: 直观易懂
|
||||
|
||||
**清晰**:
|
||||
- ✅ "媒体分析" → 产生 workspace.sqlite
|
||||
- ✅ "文本块" → 可搜索文本
|
||||
- ✅ "人脸轨迹" → 人脸追踪数据
|
||||
- ✅ "知识图谱" → 支持复杂查询
|
||||
|
||||
**结果**: 用户理解,可追踪进度
|
||||
|
||||
---
|
||||
|
||||
## 可查看性对比
|
||||
|
||||
### V1: 无法查看
|
||||
|
||||
| 阶段 | 可查看 | 方式 |
|
||||
|------|:------:|------|
|
||||
| 1-10 | ❌ | 无 |
|
||||
|
||||
### V2: 全部可查看
|
||||
|
||||
| 阶段 | 可查看 | 方式 |
|
||||
|------|:------:|------|
|
||||
| 1 | ✅ | SQLite Browser |
|
||||
| 2 | ✅ | `/api/v1/chunks` |
|
||||
| 3 | ✅ | `/api/v1/faces/tracks` |
|
||||
| 4 | ✅ | `/api/v1/identities` |
|
||||
| 5 | ✅ | `/api/v1/tkg/nodes` |
|
||||
| 6 | ✅ | `/api/v1/search/semantic` |
|
||||
| 7 | ✅ | `/api/v1/faces/tracks/{id}` |
|
||||
| 8 | ✅ | `/api/v1/scenes` |
|
||||
| 9 | ✅ | `/api/v1/moments` |
|
||||
|
||||
---
|
||||
|
||||
## 设计哲学对比
|
||||
|
||||
### V1: 工程师视角
|
||||
|
||||
```
|
||||
设计哲学: 暴露实现细节
|
||||
目标用户: 开发者
|
||||
问题: 用户看不懂
|
||||
```
|
||||
|
||||
### V2: 用户视角
|
||||
|
||||
```
|
||||
设计哲学: 展示可用产品
|
||||
目标用户: 所有用户
|
||||
优势: 直观易懂
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 总结
|
||||
|
||||
### 关键改进
|
||||
|
||||
| 维度 | V1 | V2 | 改善 |
|
||||
|------|----|----|------|
|
||||
| **产出明确性** | ❌ 模糊 | ✅ 明确 | +100% |
|
||||
| **可查看性** | ❌ 无法查看 | ✅ 全部可查看 | +100% |
|
||||
| **用户理解度** | ❌ 需技术背景 | ✅ 直观易懂 | +100% |
|
||||
| **API 覆盖** | ❌ 0% | ✅ 89% | +89% |
|
||||
|
||||
### 设计原则
|
||||
|
||||
**V2 核心原则**:
|
||||
1. ✅ 产出导向 - 每个阶段都有产品
|
||||
2. ✅ 可查看性 - 每个产品都可查看
|
||||
3. ✅ 用户友好 - 无需技术背景
|
||||
4. ✅ 过程透明 - 隐藏实现细节
|
||||
|
||||
---
|
||||
|
||||
**设计改进完成,建议采用 V2。**
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
title: Queue Comparison Table
|
||||
version: 1.0
|
||||
date: 2026-10-10
|
||||
author: OpenCode
|
||||
status: draft
|
||||
---
|
||||
|
||||
# Queue Comparison Table
|
||||
|
||||
## 四种队列特征对比
|
||||
|
||||
| 维度 | File Processor | Search Requests | Agent to Agent | VLM Requests |
|
||||
|------|---------------|----------------|----------------|--------------|
|
||||
| **请求来源** | API/CLI/监控 | API | API/内部 | 内部 |
|
||||
| **执行时间** | 分钟-小时 | 秒 (0.1-5s) | 秒 (5-30s) | 秒 (10-30s) |
|
||||
| **CPU 需求** | 高 (4-8 cores) | 低-中 | 中 | 中 |
|
||||
| **内存需求** | 高 (2-8 GB) | 低 (100-500 MB) | 中 (4-8 GB) | 高 (6.6 GB) |
|
||||
| **GPU 需求** | 中 (可选) | 低 | 高 | 极高 (瓶颈) |
|
||||
| **I/O 需求** | 极高 | 中 | 低 | 低 |
|
||||
| **并发特性** | 高 (4 workers) | 极高 (HTTP) | 低-中 (LLM 限制) | 极低 (单实例) |
|
||||
| **优先级** | 低 (批处理) | 高 (实时) | 中 (准实时) | 混合 |
|
||||
| **当前队列** | PostgreSQL + Redis | 无 (同步) | 无 (同步) | 无 (外部服务) |
|
||||
| **是否分离** | ✅ 建议独立队列 | ❌ 保持同步 | ⚠️ 可选队列 | ✅ 必须独立队列 |
|
||||
|
||||
---
|
||||
|
||||
## 资源冲突矩阵
|
||||
|
||||
| 资源 | File Processor | Search | Agent | VLM | 冲突级别 |
|
||||
|------|---------------|--------|-------|-----|---------|
|
||||
| **CPU** | 🟡 中度占用 | 🟢 低 | 🟡 中 | 🟡 中 | 🟢 低 |
|
||||
| **内存** | 🔴 高占用 | 🟢 低 | 🟡 中 | 🔴 高 | 🟡 中 |
|
||||
| **GPU** | 🟢 无/可选 | 🟢 无 | 🔴 高 | 🔴 极高 | 🔴 **严重** |
|
||||
| **数据库** | 🟡 中 | 🔴 高 | 🟡 中 | 🟢 低 | 🟡 中 |
|
||||
| **Redis** | 🟡 中 | 🟢 无 | 🟢 无 | 🟢 无 | 🟢 低 |
|
||||
| **VLM 服务** | 🟡 间接调用 | 🟢 无 | 🔴 直接调用 | 🔴 **独占** | 🔴 **严重** |
|
||||
|
||||
---
|
||||
|
||||
## 优先级需求
|
||||
|
||||
| 场景 | 用户等待 | 可延迟 | 中断影响 | 建议优先级 |
|
||||
|------|---------|--------|---------|-----------|
|
||||
| **Search** | ✅ 是 | ❌ 否 | 🔴 高 | P0 (实时) |
|
||||
| **Agent** | ✅ 是 | ⚠️ 可排队 | 🟡 中 | P1 (准实时) |
|
||||
| **Scene VLM** | ❌ 否 | ✅ 是 | 🟢 低 | P2 (批处理) |
|
||||
| **Face VLM** | ❌ 否 | ✅ 是 | 🟢 低 | P2 (批处理) |
|
||||
| **File Processor** | ❌ 否 | ✅ 是 | 🟢 低 | P3 (后台) |
|
||||
|
||||
---
|
||||
|
||||
## 当前架构瓶颈
|
||||
|
||||
### 瓶颈 1: VLM 服务单实例
|
||||
|
||||
**现状**:
|
||||
- Gemma4 12B + mmproj 运行在 port 8080
|
||||
- 单线程处理,无法并发
|
||||
- GPU 内存独占 (6.6 GB + 167 MB)
|
||||
|
||||
**影响**:
|
||||
- Scene VLM 阻塞 File Processor
|
||||
- Agent VLM 延迟增加
|
||||
- 无法同时处理多个 VLM 请求
|
||||
|
||||
**解决方案**:
|
||||
```
|
||||
方案 A: VLM 请求队列化 (推荐)
|
||||
- 应用层队列管理 VLM 调用
|
||||
- 优先级调度 (Agent VLM > Scene VLM)
|
||||
- 避免资源竞争
|
||||
|
||||
方案 B: 多 VLM 实例 (成本高)
|
||||
- 部署多个 VLM 服务实例
|
||||
- 需要 GPU 资源翻倍
|
||||
- 适用于高并发场景
|
||||
```
|
||||
|
||||
### 瓶颈 2: File Processor 内存泄漏
|
||||
|
||||
**现状**:
|
||||
- Python subprocess 长期运行
|
||||
- 内存占用持续增长
|
||||
- 最终导致 OOM
|
||||
|
||||
**影响**:
|
||||
- 需要定期重启 worker
|
||||
- 任务中断风险
|
||||
- 资源浪费
|
||||
|
||||
**解决方案**:
|
||||
```
|
||||
方案 A: Worker 生命周期管理
|
||||
- 每个 job 完成后重启 worker
|
||||
- 或者定期重启 (如每 24 小时)
|
||||
|
||||
方案 B: 资源隔离
|
||||
- 每个 processor 运行在独立进程
|
||||
- 使用 process pool
|
||||
- 失败不影响其他任务
|
||||
```
|
||||
|
||||
### 瓶颈 3: 无优先级机制
|
||||
|
||||
**现状**:
|
||||
- JobWorker 轮询所有 pending jobs
|
||||
- 先到先处理,无优先级
|
||||
- 实时请求可能被批处理任务阻塞
|
||||
|
||||
**影响**:
|
||||
- 用户体验差
|
||||
- 无法保证 SLA
|
||||
|
||||
**解决方案**:
|
||||
```
|
||||
方案: Redis 优先级队列
|
||||
- 使用多个 Redis list
|
||||
- high_priority_queue: Search/Agent
|
||||
- normal_queue: File Processor
|
||||
- low_priority_queue: Scene VLM
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 迁移路径
|
||||
|
||||
### Phase 1: File Processor Queue (2 周)
|
||||
|
||||
**目标**:将 File Processor 任务迁移到 Redis 队列
|
||||
|
||||
**任务清单**:
|
||||
- [ ] 设计 Redis 队列结构
|
||||
- [ ] 实现 JobProducer (写入队列)
|
||||
- [ ] 实现 JobConsumer (消费队列)
|
||||
- [ ] 迁移 monitor_jobs 状态
|
||||
- [ ] 测试与验证
|
||||
|
||||
**影响范围**:
|
||||
- `job_worker.rs`
|
||||
- `processing.rs`
|
||||
- `files.rs` (register)
|
||||
|
||||
### Phase 2: VLM Request Queue (1 周)
|
||||
|
||||
**目标**:VLM 请求队列化,避免资源竞争
|
||||
|
||||
**任务清单**:
|
||||
- [ ] 实现 VLMRequestQueue
|
||||
- [ ] 优先级调度 (Agent > Scene)
|
||||
- [ ] 限制并发 (max 1)
|
||||
- [ ] 超时与重试机制
|
||||
|
||||
**影响范围**:
|
||||
- `scene_vlm.rs`
|
||||
- `vlm_summary.rs`
|
||||
- `tools.rs` (analyze_frame)
|
||||
|
||||
### Phase 3: Monitoring & Optimization (1 周)
|
||||
|
||||
**目标**:监控队列状态,优化性能
|
||||
|
||||
**任务清单**:
|
||||
- [ ] 队列长度监控
|
||||
- [ ] 处理时间统计
|
||||
- [ ] 告警机制
|
||||
- [ ] 性能优化
|
||||
|
||||
---
|
||||
|
||||
## 成本效益分析
|
||||
|
||||
| 方案 | 开发成本 | 运维成本 | 性能提升 | 用户体验 | 推荐度 |
|
||||
|------|---------|---------|---------|---------|--------|
|
||||
| **当前架构** | 🟢 低 | 🔴 高 (重启频繁) | 🔴 差 | 🔴 差 | ❌ 不推荐 |
|
||||
| **分离队列** | 🟡 中 (4 周) | 🟢 低 | 🟢 好 | 🟢 好 | ✅ 推荐 |
|
||||
| **多 VLM 实例** | 🟡 中 | 🔴 高 (GPU 成本) | 🟢 极好 | 🟢 极好 | ⚠️ 可选 |
|
||||
|
||||
---
|
||||
|
||||
## 决策建议
|
||||
|
||||
### 短期 (1 个月)
|
||||
- ✅ **立即实施**:VLM 请求队列化
|
||||
- 原因:GPU 独占是最严重瓶颈
|
||||
- 成本:低 (应用层队列)
|
||||
- 收益:高 (避免阻塞)
|
||||
|
||||
### 中期 (3 个月)
|
||||
- ✅ **优先实施**:File Processor 队列化
|
||||
- 原因:解决内存泄漏、支持优先级
|
||||
- 成本:中 (Redis 重构)
|
||||
- 收益:高 (稳定性 + 性能)
|
||||
|
||||
### 长期 (6 个月)
|
||||
- ⚠️ **评估后决定**:多 VLM 实例
|
||||
- 原因:成本高,需评估业务需求
|
||||
- 适用场景:高并发 VLM 请求
|
||||
- 替代方案:更高效的 VLM 模型
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
# Momentry Core 四种队列需求分析
|
||||
|
||||
## 执行摘要
|
||||
|
||||
Momentry Core 当前使用 **统一的 JobWorker 轮询机制** 处理所有任务,没有独立的队列系统。四种需求各有不同的特征,需要评估是否应该分离队列管理。
|
||||
|
||||
---
|
||||
|
||||
## 1. File Processor Jobs(文件处理任务)
|
||||
|
||||
### 请求来源
|
||||
- **API 调用**:`POST /api/v1/register` (files.rs)
|
||||
- **CLI 命令**:`cargo run -- register /path/to/video.mp4`
|
||||
- **内部调用**:文件监控自动注册
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:单个 processor (Face/OCR) 5-30秒
|
||||
- **分钟级**:完整 pipeline 3-10分钟
|
||||
- **小时级**:大型视频 (>1小时) 可能需要 30-120 分钟
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 峰值 |
|
||||
|------|------|------|
|
||||
| **CPU** | 高 (多核并行) | ASR/Face: 4-8 cores |
|
||||
| **内存** | 高 (Python subprocess) | 2-8 GB per job |
|
||||
| **GPU** | 中 (Face/Scene VLM) | 可选,ANE 加速 |
|
||||
| **I/O** | 极高 (视频帧提取) | SSD required |
|
||||
|
||||
### 并发特性
|
||||
- **高并发**:`max_concurrent = 4` (可配置)
|
||||
- **长期占用**:每个 job 持续数分钟到数小时
|
||||
- **Pipeline 限制**:
|
||||
- Frame pipeline: max 4 concurrent (OCR, Face, Pose, YOLO)
|
||||
- Time pipeline: max 2 concurrent (ASR, ASRX, Cut)
|
||||
|
||||
### 优先级需求
|
||||
- **批处理优先级**:后台任务,可延迟
|
||||
- **可中断**:支持取消 (`cancel_token`)
|
||||
- **容错**:retry 机制 (max 3 retries)
|
||||
|
||||
### 当前队列机制
|
||||
- **PostgreSQL `monitor_jobs` 表**:存储任务状态
|
||||
- **Redis 临时存储**:PID tracking, 进度信息
|
||||
- **ProcessorPool**:内存中的并发控制
|
||||
- **轮询机制**:`poll_interval_secs = 10` 秒轮询一次
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/worker/job_worker.rs (4645 lines)
|
||||
/Users/accusys/momentry_core/src/worker/processor.rs (ProcessorPool)
|
||||
/Users/accusys/momentry_core/src/api/processing.rs (API endpoints)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Search Requests(搜索请求)
|
||||
|
||||
### 请求来源
|
||||
- **API 调用**:
|
||||
- `POST /api/v1/search/smart` (search.rs)
|
||||
- `POST /api/v1/search/universal` (universal_search.rs)
|
||||
- `POST /api/v1/search/agent` (agent_search.rs)
|
||||
- **无 CLI 接口**
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:0.1-5秒
|
||||
- Smart Search (BM25): 0.1-0.5秒
|
||||
- Semantic Search (Qdrant): 0.2-2秒
|
||||
- Universal Search: 1-5秒
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 说明 |
|
||||
|------|------|------|
|
||||
| **CPU** | 低-中 | 数据库查询 + 向量相似度 |
|
||||
| **内存** | 低 | 100-500 MB |
|
||||
| **GPU** | 低 | Embedding 计算可离线预计算 |
|
||||
| **I/O** | 中 | 数据库查询 + Qdrant 查询 |
|
||||
|
||||
### 并发特性
|
||||
- **高并发**:HTTP API 天然支持并发
|
||||
- **短时占用**:每次请求 <5秒
|
||||
- **无状态**:无需跟踪状态
|
||||
|
||||
### 优先级需求
|
||||
- **实时响应**:用户等待结果,需立即返回
|
||||
- **不可延迟**:用户交互必需
|
||||
- **低延迟要求**:<2秒响应时间
|
||||
|
||||
### 当前队列机制
|
||||
- **无队列**:直接 HTTP 同步处理
|
||||
- **Database connection pool**:限制数据库连接数
|
||||
- **Qdrant connection**:独立连接池
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/api/search.rs (846 lines)
|
||||
/Users/accusys/momentry_core/src/api/universal_search.rs (875 lines)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Agent to Agent CLI(Agent 对话)
|
||||
|
||||
### 请求来源
|
||||
- **API 调用**:`POST /api/v1/search/agent` (agent_search.rs)
|
||||
- **内部调用**:工具链调用 (tools.rs)
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:5-30秒
|
||||
- 简单查询 (单工具调用): 5-10秒
|
||||
- 复杂查询 (多工具链): 10-30秒
|
||||
- VLM 分析: 10-20秒
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 说明 |
|
||||
|------|------|------|
|
||||
| **CPU** | 中 | LLM 推理 (Gemma4 12B) |
|
||||
| **内存** | 中 | 4-8 GB (Gemma4 模型) |
|
||||
| **GPU** | 高 | ANE/GPU 加速 LLM 推理 |
|
||||
| **I/O** | 低 | 少量数据库查询 |
|
||||
|
||||
### 并发特性
|
||||
- **低-中并发**:受 LLM 服务限制
|
||||
- **有状态**:会话管理 (conversation_id)
|
||||
- **工具链**:可能调用多个工具 (smart_search, semantic_search, analyze_frame)
|
||||
|
||||
### 优先级需求
|
||||
- **准实时**:用户交互,可接受 10-30秒延迟
|
||||
- **可排队**:用户可等待
|
||||
- **资源竞争**:与 VLM requests 竞争 GPU
|
||||
|
||||
### 当前队列机制
|
||||
- **无队列**:直接 HTTP 同步处理
|
||||
- **会话缓存**:内存中的 `CONVERSATIONS` HashMap
|
||||
- **LLM 服务**:外部 llama.cpp server (port 8080)
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/api/agent_search.rs (543 lines)
|
||||
/Users/accusys/momentry_core/src/core/agent/tools.rs (2080 lines)
|
||||
/Users/accusys/momentry_core/src/core/llm/function_calling.rs (371 lines)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. VLM Requests(视觉语言模型请求)
|
||||
|
||||
### 请求来源
|
||||
- **内部调用**:
|
||||
- Scene VLM: `job_worker.rs` -> `process_scene_vlm()`
|
||||
- Face VLM: `vlm_summary.rs` -> `call_llm_vision()`
|
||||
- Agent VLM: `tools.rs` -> `analyze_frame()`
|
||||
|
||||
### 执行时间
|
||||
- **秒级**:10-30秒
|
||||
- Scene VLM (单场景): 10-15秒
|
||||
- Face VLM (单 trace): 10-20秒
|
||||
- Agent analyze_frame: 10-20秒
|
||||
|
||||
### 资源需求
|
||||
| 资源 | 需求 | 说明 |
|
||||
|------|------|------|
|
||||
| **CPU** | 中 | Gemma4 推理 |
|
||||
| **内存** | 高 | 6.6 GB (Gemma4 Q4_K_M) + 167 MB (mmproj) |
|
||||
| **GPU** | 极高 | **瓶颈资源** - 单实例服务 |
|
||||
| **I/O** | 低 | 图片 base64 传输 |
|
||||
|
||||
### 并发特性
|
||||
- **极低并发**:**单实例 VLM 服务** (port 8080)
|
||||
- **串行处理**:llama.cpp server 单线程
|
||||
- **GPU 独占**:模型加载到 VRAM,无法多进程共享
|
||||
|
||||
### 优先级需求
|
||||
- **混合优先级**:
|
||||
- Scene VLM: 批处理,可延迟
|
||||
- Face VLM: 批处理,可延迟
|
||||
- Agent VLM: 准实时,用户等待
|
||||
|
||||
### 当前队列机制
|
||||
- **无应用层队列**:直接调用外部 VLM 服务
|
||||
- **VLM 服务限制**:llama.cpp server 自身的请求队列
|
||||
- **HTTP timeout**:120秒 (generate_scene_description)
|
||||
|
||||
### 代码位置
|
||||
```
|
||||
/Users/accusys/momentry_core/src/core/processor/scene_vlm.rs (701 lines)
|
||||
/Users/accusys/momentry_core/src/core/processor/vlm_summary.rs
|
||||
/Users/accusys/momentry_core/src/core/llm/function_calling.rs (call_llm_vision)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 当前队列实现方式总结
|
||||
|
||||
### 统一的 JobWorker 轮询机制
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ JobWorker (poll every 10s) │
|
||||
│ │
|
||||
│ 1. 查询 monitor_jobs (status = 'pending') │
|
||||
│ 2. 检查 ProcessorPool 并发限制 │
|
||||
│ 3. 启动 processor (tokio::spawn) │
|
||||
│ 4. 监控进度,写入 Redis │
|
||||
│ 5. 更新 PostgreSQL 状态 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
File Processor Scene VLM Face VLM
|
||||
(异步批处理) (异步批处理) (异步批处理)
|
||||
```
|
||||
|
||||
### 无队列的场景
|
||||
|
||||
| 场景 | 处理方式 | 限制机制 |
|
||||
|------|---------|---------|
|
||||
| **Search Requests** | HTTP 同步处理 | DB connection pool |
|
||||
| **Agent to Agent** | HTTP 同步处理 | LLM 服务限制 |
|
||||
| **VLM Requests** | HTTP 同步调用外部服务 | VLM 服务队列 |
|
||||
|
||||
---
|
||||
|
||||
## 是否需要分开管理?
|
||||
|
||||
### 建议:**分离队列管理**
|
||||
|
||||
### 理由
|
||||
|
||||
1. **资源竞争严重**
|
||||
- File Processor: 长时间占用 CPU/内存
|
||||
- VLM Requests: GPU 独占,无法并发
|
||||
- 混合在一起会导致 VLM 请求被长时间阻塞
|
||||
|
||||
2. **优先级冲突**
|
||||
- Search/Agent: 用户等待,需实时响应
|
||||
- File Processor: 批处理,可延迟
|
||||
- 当前架构无法区分优先级
|
||||
|
||||
3. **并发特性差异巨大**
|
||||
- File Processor: 4 concurrent (可配置)
|
||||
- VLM: **单实例服务,无法并发**
|
||||
- Search: 高并发,短时占用
|
||||
|
||||
### 推荐架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ API Gateway (Axum) │
|
||||
└──────────┬──────────┬──────────┬───────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||
│ Search │ │ Agent │ │ Register │
|
||||
│ Handler │ │ Handler │ │ Handler │
|
||||
│ (sync) │ │ (sync) │ │ (async) │
|
||||
└────┬─────┘ └────┬─────┘ └────┬─────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||
│ Database │ │ LLM Pool │ │ JobQueue │
|
||||
│ Pool │ │ (limited)│ │ (Redis) │
|
||||
└──────────┘ └──────────┘ └────┬─────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ JobWorker │
|
||||
│ (poll Redis) │
|
||||
└────┬─────┬──────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────┐ ┌─────────┐
|
||||
│File Proc│ │VLM Proc │
|
||||
│Pool (4) │ │Pool (1) │
|
||||
└─────────┘ └─────────┘
|
||||
```
|
||||
|
||||
### 队列分离方案
|
||||
|
||||
#### Queue 1: File Processor Queue (Redis-based)
|
||||
- **类型**:FIFO + Priority
|
||||
- **生产者**:Register API, File Monitor
|
||||
- **消费者**:JobWorker (polling)
|
||||
- **并发**:4 workers
|
||||
- **优先级**:低 (batch)
|
||||
|
||||
#### Queue 2: VLM Request Queue (Application-level)
|
||||
- **类型**:FIFO
|
||||
- **生产者**:File Processor, Agent Tools
|
||||
- **消费者**:VLM Worker (single-threaded)
|
||||
- **并发**:1 worker
|
||||
- **优先级**:中 (hybrid)
|
||||
|
||||
#### Queue 3: Search/Agent Requests (No queue)
|
||||
- **类型**:Synchronous HTTP
|
||||
- **并发**:Limited by DB connection pool + LLM service
|
||||
- **优先级**:高 (real-time)
|
||||
|
||||
---
|
||||
|
||||
## 迁移建议
|
||||
|
||||
### Phase 1: 引入 Redis Job Queue (File Processor)
|
||||
1. 将 `monitor_jobs` 状态迁移到 Redis
|
||||
2. 实现优先级队列
|
||||
3. 支持任务取消、重试
|
||||
|
||||
### Phase 2: VLM 请求队列化
|
||||
1. 应用层队列管理 VLM 调用
|
||||
2. 优先级调度 (Agent VLM > Scene VLM)
|
||||
3. 避免与 File Processor 竞争
|
||||
|
||||
### Phase 3: 监控与优化
|
||||
1. 队列长度监控
|
||||
2. 处理时间统计
|
||||
3. 自动扩缩容
|
||||
|
||||
---
|
||||
|
||||
## 当前瓶颈分析
|
||||
|
||||
| 瓶颈 | 原因 | 影响 | 解决方案 |
|
||||
|------|------|------|---------|
|
||||
| **VLM 服务单实例** | GPU 独占 | Scene VLM 阻塞 File Processor | 分离 VLM 队列 |
|
||||
| **File Processor 内存泄漏** | Python subprocess | 长时间运行后 OOM | 定期重启 worker |
|
||||
| **Search/Agent 无并发控制** | 共享 LLM 服务 | 高并发时延迟增加 | 限流 + 队列 |
|
||||
| **无优先级机制** | 轮询无优先级 | 实时请求被阻塞 | 优先级队列 |
|
||||
|
||||
@@ -0,0 +1,756 @@
|
||||
# Momentry Core Replay 系统设计
|
||||
|
||||
**日期**: 2026-10-11
|
||||
**版本**: V1.0
|
||||
**状态**: 设计阶段
|
||||
|
||||
---
|
||||
|
||||
## 🎯 目标
|
||||
|
||||
实现命令队列 Replay 功能,用于:
|
||||
1. 验证系统稳定度
|
||||
2. 测试幂等性
|
||||
3. 压力测试
|
||||
4. 容错能力测试
|
||||
|
||||
---
|
||||
|
||||
## 📊 支持的 Replay 场景
|
||||
|
||||
| 场景 | 用途 | 命令来源 | 验证方法 |
|
||||
|------|------|---------|----------|
|
||||
| **重放成功命令** | 验证幂等性 | status=completed | 对比前后结果 |
|
||||
| **重放失败命令** | 测试容错能力 | status=failed | 记录恢复率 |
|
||||
| **批量重放** | 压力测试 | 时间范围或数量 | 性能监控 |
|
||||
| **场景回放** | 测试特定场景 | 命令序列 | 状态验证 |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构设计
|
||||
|
||||
### 1. 数据模型
|
||||
|
||||
#### replay_sessions 表
|
||||
|
||||
```sql
|
||||
CREATE TABLE replay_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
-- Session 信息
|
||||
session_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
session_name VARCHAR(255),
|
||||
replay_type VARCHAR(20) NOT NULL CHECK (
|
||||
replay_type IN ('success', 'failed', 'batch', 'scenario')
|
||||
),
|
||||
|
||||
-- 源命令过滤条件
|
||||
source_filter JSONB NOT NULL DEFAULT '{}',
|
||||
/*
|
||||
{
|
||||
"status": ["completed", "failed"],
|
||||
"job_types": ["register", "unregister"],
|
||||
"time_range": {
|
||||
"start": "2026-10-01T00:00:00Z",
|
||||
"end": "2026-10-11T00:00:00Z"
|
||||
},
|
||||
"limit": 100,
|
||||
"command_ids": ["abc123", "def456"]
|
||||
}
|
||||
*/
|
||||
|
||||
-- 配置
|
||||
config JSONB NOT NULL DEFAULT '{}',
|
||||
/*
|
||||
{
|
||||
"concurrency": 5,
|
||||
"delay_ms": 100,
|
||||
"stop_on_error": false,
|
||||
"compare_results": true,
|
||||
"timeout_secs": 300
|
||||
}
|
||||
*/
|
||||
|
||||
-- 执行状态
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (
|
||||
status IN ('pending', 'running', 'paused', 'completed', 'failed', 'cancelled')
|
||||
),
|
||||
|
||||
-- 统计信息
|
||||
total_commands INTEGER DEFAULT 0,
|
||||
processed_commands INTEGER DEFAULT 0,
|
||||
succeeded_commands INTEGER DEFAULT 0,
|
||||
failed_commands INTEGER DEFAULT 0,
|
||||
skipped_commands INTEGER DEFAULT 0,
|
||||
|
||||
-- 结果对比
|
||||
comparison_results JSONB DEFAULT '[]',
|
||||
/*
|
||||
[
|
||||
{
|
||||
"original_command_id": "abc123",
|
||||
"replay_command_id": "xyz789",
|
||||
"status": "match", // match, mismatch, error
|
||||
"original_result": {...},
|
||||
"replay_result": {...},
|
||||
"differences": [...]
|
||||
}
|
||||
]
|
||||
*/
|
||||
|
||||
-- 性能指标
|
||||
started_at TIMESTAMP WITH TIME ZONE,
|
||||
completed_at TIMESTAMP WITH TIME ZONE,
|
||||
duration_secs DOUBLE PRECISION,
|
||||
|
||||
-- 错误信息
|
||||
error_message TEXT,
|
||||
|
||||
-- 时间戳
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
-- 用户信息
|
||||
user_id BIGINT,
|
||||
|
||||
-- 索引
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_replay_sessions_status ON replay_sessions (status, created_at);
|
||||
CREATE INDEX idx_replay_sessions_type ON replay_sessions (replay_type, created_at);
|
||||
```
|
||||
|
||||
#### replay_commands 表
|
||||
|
||||
```sql
|
||||
CREATE TABLE replay_commands (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
-- 关联信息
|
||||
session_id VARCHAR(36) NOT NULL,
|
||||
original_command_id VARCHAR(36) NOT NULL,
|
||||
replay_command_id VARCHAR(36),
|
||||
|
||||
-- 执行状态
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
|
||||
-- 结果对比
|
||||
original_result JSONB,
|
||||
replay_result JSONB,
|
||||
comparison_status VARCHAR(20), -- match, mismatch, error
|
||||
differences JSONB,
|
||||
|
||||
-- 性能指标
|
||||
original_duration_secs DOUBLE PRECISION,
|
||||
replay_duration_secs DOUBLE PRECISION,
|
||||
|
||||
-- 错误信息
|
||||
error_message TEXT,
|
||||
|
||||
-- 时间戳
|
||||
started_at TIMESTAMP WITH TIME ZONE,
|
||||
completed_at TIMESTAMP WITH TIME ZONE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
|
||||
-- 外键
|
||||
FOREIGN KEY (session_id) REFERENCES replay_sessions(session_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_replay_commands_session ON replay_commands (session_id);
|
||||
CREATE INDEX idx_replay_commands_status ON replay_commands (status);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. API 设计
|
||||
|
||||
#### 2.1 创建 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"session_name": "Test idempotency for October registrations",
|
||||
"replay_type": "success", // success, failed, batch, scenario
|
||||
"source_filter": {
|
||||
"status": ["completed"],
|
||||
"job_types": ["register"],
|
||||
"time_range": {
|
||||
"start": "2026-10-01T00:00:00Z",
|
||||
"end": "2026-10-11T00:00:00Z"
|
||||
},
|
||||
"limit": 100
|
||||
},
|
||||
"config": {
|
||||
"concurrency": 5,
|
||||
"delay_ms": 100,
|
||||
"stop_on_error": false,
|
||||
"compare_results": true,
|
||||
"timeout_secs": 300
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"session": {
|
||||
"session_id": "replay_abc123",
|
||||
"session_name": "Test idempotency for October registrations",
|
||||
"replay_type": "success",
|
||||
"status": "pending",
|
||||
"total_commands": 50,
|
||||
"created_at": "2026-10-11T09:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.2 启动 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/start
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"status": "running",
|
||||
"message": "Replay session started"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.3 暂停 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/pause
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.4 恢复 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/resume
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.5 取消 Replay Session
|
||||
|
||||
```http
|
||||
POST /api/v1/replay/sessions/{session_id}/cancel
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.6 查询 Replay Session 状态
|
||||
|
||||
```http
|
||||
GET /api/v1/replay/sessions/{session_id}
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"session_id": "replay_abc123",
|
||||
"status": "running",
|
||||
"progress": {
|
||||
"total": 50,
|
||||
"processed": 25,
|
||||
"succeeded": 23,
|
||||
"failed": 2,
|
||||
"percentage": 50.0
|
||||
},
|
||||
"performance": {
|
||||
"started_at": "2026-10-11T09:00:00Z",
|
||||
"elapsed_secs": 120.5,
|
||||
"avg_command_time_secs": 4.82
|
||||
},
|
||||
"comparison": {
|
||||
"match_count": 20,
|
||||
"mismatch_count": 3,
|
||||
"error_count": 2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.7 列出 Replay Sessions
|
||||
|
||||
```http
|
||||
GET /api/v1/replay/sessions?status=completed&limit=20
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 2.8 获取 Replay 结果报告
|
||||
|
||||
```http
|
||||
GET /api/v1/replay/sessions/{session_id}/report
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"session": {
|
||||
"session_id": "replay_abc123",
|
||||
"session_name": "Test idempotency for October registrations",
|
||||
"status": "completed"
|
||||
},
|
||||
|
||||
"summary": {
|
||||
"total_commands": 50,
|
||||
"succeeded": 45,
|
||||
"failed": 3,
|
||||
"skipped": 2,
|
||||
"success_rate": 90.0
|
||||
},
|
||||
|
||||
"comparison": {
|
||||
"match": 40,
|
||||
"mismatch": 5,
|
||||
"error": 3,
|
||||
"match_rate": 80.0
|
||||
},
|
||||
|
||||
"performance": {
|
||||
"total_duration_secs": 241.0,
|
||||
"avg_command_time_secs": 4.82,
|
||||
"commands_per_minute": 12.4
|
||||
},
|
||||
|
||||
"mismatches": [
|
||||
{
|
||||
"original_command_id": "abc123",
|
||||
"replay_command_id": "xyz789",
|
||||
"differences": [
|
||||
{
|
||||
"field": "file_uuid",
|
||||
"original": "384b0ff44aaaa1f1",
|
||||
"replay": "384b0ff44aaaa1f2"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
"errors": [
|
||||
{
|
||||
"command_id": "def456",
|
||||
"error": "File not found"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Replay 执行流程
|
||||
|
||||
```
|
||||
1. 创建 Session
|
||||
↓
|
||||
2. 查询源命令(根据 filter)
|
||||
↓
|
||||
3. 生成 replay_commands 记录
|
||||
↓
|
||||
4. 启动 Replay Worker
|
||||
↓
|
||||
5. 并发执行重放
|
||||
├── 读取原始命令
|
||||
├── 克隆命令 payload
|
||||
├── 提交到 command_queue
|
||||
├── 等待执行完成
|
||||
├── 对比结果(如果启用)
|
||||
└── 更新 replay_commands 状态
|
||||
↓
|
||||
6. 生成报告
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 幂等性验证
|
||||
|
||||
#### 4.1 结果对比逻辑
|
||||
|
||||
```rust
|
||||
pub struct ResultComparator {
|
||||
compare_fields: Vec<String>, // 要对比的字段
|
||||
ignore_fields: Vec<String>, // 忽略的字段
|
||||
}
|
||||
|
||||
impl ResultComparator {
|
||||
pub fn compare(
|
||||
&self,
|
||||
original: &serde_json::Value,
|
||||
replay: &serde_json::Value,
|
||||
) -> ComparisonResult {
|
||||
let mut differences = Vec::new();
|
||||
|
||||
for field in &self.compare_fields {
|
||||
let orig_val = original.get(field);
|
||||
let replay_val = replay.get(field);
|
||||
|
||||
if orig_val != replay_val {
|
||||
differences.push(Difference {
|
||||
field: field.clone(),
|
||||
original: orig_val.cloned(),
|
||||
replay: replay_val.cloned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ComparisonResult {
|
||||
status: if differences.is_empty() { "match" } else { "mismatch" },
|
||||
differences,
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 4.2 Register 命令幂等性验证
|
||||
|
||||
**关键点**:
|
||||
- ✅ 相同文件路径应返回相同 `file_uuid`
|
||||
- ✅ 第二次注册应标记为 `already_exists=true`
|
||||
- ✅ 不应创建重复记录
|
||||
|
||||
**验证字段**:
|
||||
```json
|
||||
{
|
||||
"compare_fields": [
|
||||
"file_uuid",
|
||||
"file_type",
|
||||
"file_size",
|
||||
"already_exists"
|
||||
],
|
||||
"ignore_fields": [
|
||||
"created_at", // 时间戳必然不同
|
||||
"message" // 提示信息可能不同
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 批量重放配置
|
||||
|
||||
#### 5.1 压力测试配置
|
||||
|
||||
```json
|
||||
{
|
||||
"replay_type": "batch",
|
||||
"source_filter": {
|
||||
"job_types": ["register"],
|
||||
"time_range": {
|
||||
"start": "2026-10-01T00:00:00Z",
|
||||
"end": "2026-10-11T00:00:00Z"
|
||||
},
|
||||
"limit": 1000
|
||||
},
|
||||
"config": {
|
||||
"concurrency": 10, // 高并发
|
||||
"delay_ms": 0, // 无延迟
|
||||
"stop_on_error": false, // 遇错不停
|
||||
"compare_results": false, // 不对比结果
|
||||
"timeout_secs": 600 // 更长超时
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**性能监控**:
|
||||
- 吞吐量(commands/min)
|
||||
- 平均延迟
|
||||
- 错误率
|
||||
- 资源使用(CPU, 内存, GPU)
|
||||
|
||||
---
|
||||
|
||||
### 6. 场景回放
|
||||
|
||||
#### 6.1 定义场景
|
||||
|
||||
```json
|
||||
{
|
||||
"replay_type": "scenario",
|
||||
"session_name": "Test register -> unregister cycle",
|
||||
"source_filter": {
|
||||
"command_sequence": [
|
||||
{
|
||||
"job_type": "register",
|
||||
"file_path": "/test/video1.mp4"
|
||||
},
|
||||
{
|
||||
"job_type": "unregister",
|
||||
"file_path": "/test/video1.mp4"
|
||||
},
|
||||
{
|
||||
"job_type": "register",
|
||||
"file_path": "/test/video1.mp4"
|
||||
}
|
||||
]
|
||||
},
|
||||
"config": {
|
||||
"stop_on_error": true, // 遇错停止
|
||||
"compare_results": true, // 验证每步
|
||||
"validate_state": true // 验证中间状态
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 6.2 状态验证
|
||||
|
||||
```rust
|
||||
// 验证 register 后状态
|
||||
async fn validate_after_register(file_uuid: &str) -> Result<()> {
|
||||
let video = db.get_video(file_uuid).await?;
|
||||
|
||||
assert!(video.is_some(), "Video should exist");
|
||||
assert!(video.unwrap().status == "registered", "Status should be registered");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 验证 unregister 后状态
|
||||
async fn validate_after_unregister(file_uuid: &str) -> Result<()> {
|
||||
let video = db.get_video(file_uuid).await?;
|
||||
|
||||
assert!(video.is_none(), "Video should not exist");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7. 错误处理
|
||||
|
||||
#### 7.1 错误分类
|
||||
|
||||
| 错误类型 | 处理方式 | 重试 |
|
||||
|---------|---------|------|
|
||||
| **文件不存在** | 标记为 skipped | ❌ 不重试 |
|
||||
| **权限错误** | 标记为 failed | ❌ 不重试 |
|
||||
| **网络错误** | 自动重试 3 次 | ✅ 重试 |
|
||||
| **超时** | 自动重试 2 次 | ✅ 重试 |
|
||||
| **资源不足** | 等待后重试 | ✅ 重试 |
|
||||
|
||||
#### 7.2 错误记录
|
||||
|
||||
```rust
|
||||
struct ReplayError {
|
||||
command_id: String,
|
||||
error_type: ErrorType,
|
||||
error_message: String,
|
||||
retry_count: u32,
|
||||
timestamp: DateTime<Utc>,
|
||||
|
||||
// 上下文信息
|
||||
context: HashMap<String, String>,
|
||||
}
|
||||
|
||||
// 记录错误
|
||||
async fn record_error(session_id: &str, error: ReplayError) {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
UPDATE replay_commands
|
||||
SET status = 'failed', error_message = $1, completed_at = NOW()
|
||||
WHERE session_id = $2 AND original_command_id = $3
|
||||
"#,
|
||||
error.error_message,
|
||||
session_id,
|
||||
error.command_id,
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 8. 监控和告警
|
||||
|
||||
#### 8.1 实时监控
|
||||
|
||||
```rust
|
||||
// WebSocket 推送进度
|
||||
pub async fn monitor_replay_progress(
|
||||
session_id: &str,
|
||||
) -> impl Stream<Item = ReplayProgress> {
|
||||
let db = get_db();
|
||||
|
||||
async_stream::stream! {
|
||||
loop {
|
||||
let progress = get_replay_progress(session_id).await?;
|
||||
yield progress;
|
||||
|
||||
if progress.status == "completed" {
|
||||
break;
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/v1/replay/sessions/{session_id}/stream (WebSocket)
|
||||
```
|
||||
|
||||
#### 8.2 告警规则
|
||||
|
||||
| 指标 | 阈值 | 告警级别 |
|
||||
|------|------|---------|
|
||||
| 失败率 | > 10% | 🟡 Warning |
|
||||
| 失败率 | > 30% | 🔴 Critical |
|
||||
| 不匹配率 | > 20% | 🟡 Warning |
|
||||
| 不匹配率 | > 50% | 🔴 Critical |
|
||||
| 平均延迟 | > 10s | 🟡 Warning |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用示例
|
||||
|
||||
### 示例 1: 验证幂等性
|
||||
|
||||
```bash
|
||||
# 创建 replay session
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"session_name": "Verify register idempotency",
|
||||
"replay_type": "success",
|
||||
"source_filter": {
|
||||
"status": ["completed"],
|
||||
"job_types": ["register"],
|
||||
"limit": 100
|
||||
},
|
||||
"config": {
|
||||
"compare_results": true
|
||||
}
|
||||
}'
|
||||
|
||||
# 启动 replay
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions/replay_abc123/start \
|
||||
-H "Authorization: Bearer $API_KEY"
|
||||
|
||||
# 查看报告
|
||||
curl http://localhost:3002/api/v1/replay/sessions/replay_abc123/report \
|
||||
-H "Authorization: Bearer $API_KEY"
|
||||
```
|
||||
|
||||
### 示例 2: 压力测试
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"session_name": "Stress test - 1000 commands",
|
||||
"replay_type": "batch",
|
||||
"source_filter": {
|
||||
"limit": 1000
|
||||
},
|
||||
"config": {
|
||||
"concurrency": 10,
|
||||
"delay_ms": 0,
|
||||
"compare_results": false
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
### 示例 3: 容错测试
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3002/api/v1/replay/sessions \
|
||||
-H "Authorization: Bearer $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"session_name": "Test recovery from failed commands",
|
||||
"replay_type": "failed",
|
||||
"source_filter": {
|
||||
"status": ["failed"]
|
||||
},
|
||||
"config": {
|
||||
"stop_on_error": false
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据库迁移
|
||||
|
||||
```sql
|
||||
-- migrations/20261011_replay_system.sql
|
||||
|
||||
CREATE TABLE replay_sessions (
|
||||
-- (如上定义)
|
||||
);
|
||||
|
||||
CREATE TABLE replay_commands (
|
||||
-- (如上定义)
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 基础功能 (1 周)
|
||||
|
||||
- [ ] 创建数据库表
|
||||
- [ ] 实现 Replay Session 管理 API
|
||||
- [ ] 实现 Replay Worker
|
||||
- [ ] 基础结果对比
|
||||
|
||||
### Phase 2: 高级功能 (1 周)
|
||||
|
||||
- [ ] 幂等性验证
|
||||
- [ ] 批量重放优化
|
||||
- [ ] 场景回放
|
||||
- [ ] 监控和告警
|
||||
|
||||
### Phase 3: 报告和可视化 (3 天)
|
||||
|
||||
- [ ] 详细报告生成
|
||||
- [ ] WebSocket 实时监控
|
||||
- [ ] Web UI (可选)
|
||||
|
||||
---
|
||||
|
||||
## 📝 注意事项
|
||||
|
||||
### 安全考虑
|
||||
|
||||
1. **权限控制**: 只有管理员可以执行 Replay
|
||||
2. **资源限制**: 限制并发数,避免系统过载
|
||||
3. **数据隔离**: Replay 不影响生产数据
|
||||
4. **审计日志**: 记录所有 Replay 操作
|
||||
|
||||
### 性能考虑
|
||||
|
||||
1. **批量查询**: 避免频繁查询数据库
|
||||
2. **并发控制**: 动态调整并发数
|
||||
3. **资源监控**: 监控系统资源,避免过载
|
||||
4. **背压机制**: 当队列过长时自动降速
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,706 @@
|
||||
# MarkBase Search Messenger 设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 设计规范
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
将 Studio 的 Search 介面定位为 **Messenger 的变形**,通过统一的消息传递机制实现搜索功能。
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构设计
|
||||
|
||||
### 核心理念
|
||||
|
||||
```
|
||||
Search Request → Messenger Queue → Search Worker → Messenger Response
|
||||
```
|
||||
|
||||
Search 不是独立的 API,而是 **Messenger 的一个特定应用场景**。
|
||||
|
||||
---
|
||||
|
||||
## 📊 Search 消息类型
|
||||
|
||||
### 1. Search Request Message
|
||||
|
||||
```rust
|
||||
// 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 crate::core::command::messenger::types::{Message, MessageType, MessageSource, MessagePriority};
|
||||
|
||||
/// Search 类型
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SearchType {
|
||||
/// 关键词搜索
|
||||
Keyword,
|
||||
/// 语义搜索
|
||||
Semantic,
|
||||
/// 混合搜索
|
||||
Hybrid,
|
||||
/// 人物搜索
|
||||
People,
|
||||
/// 场景搜索
|
||||
Scene,
|
||||
/// 时间范围搜索
|
||||
TimeRange,
|
||||
/// 自定义搜索
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// Search 请求
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchRequest {
|
||||
pub query: String,
|
||||
pub search_type: SearchType,
|
||||
pub filters: SearchFilters,
|
||||
pub options: SearchOptions,
|
||||
}
|
||||
|
||||
/// Search 过滤器
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchFilters {
|
||||
pub file_uuids: Option<Vec<String>>,
|
||||
pub date_range: Option<DateRange>,
|
||||
pub tags: Option<Vec<String>>,
|
||||
pub identities: Option<Vec<String>>,
|
||||
pub locations: Option<Vec<String>>,
|
||||
pub custom: Option<JsonValue>,
|
||||
}
|
||||
|
||||
/// Search 选项
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SearchOptions {
|
||||
pub limit: Option<i32>,
|
||||
pub offset: Option<i32>,
|
||||
pub include_metadata: Option<bool>,
|
||||
pub include_thumbnails: Option<bool>,
|
||||
pub sort_by: Option<String>,
|
||||
pub sort_order: Option<String>,
|
||||
pub highlight: Option<bool>,
|
||||
pub explain: Option<bool>,
|
||||
}
|
||||
|
||||
/// 日期范围
|
||||
#[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,
|
||||
pub facets: Option<JsonValue>,
|
||||
pub suggestions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Search 结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchResult {
|
||||
pub id: String,
|
||||
pub score: f64,
|
||||
pub file_uuid: String,
|
||||
pub timestamp: Option<f64>,
|
||||
pub duration: Option<f64>,
|
||||
pub snippet: Option<String>,
|
||||
pub highlights: Option<Vec<Highlight>>,
|
||||
pub metadata: Option<JsonValue>,
|
||||
pub thumbnail: Option<String>,
|
||||
}
|
||||
|
||||
/// 高亮
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Highlight {
|
||||
pub field: String,
|
||||
pub fragments: Vec<String>,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// 转换为 Messenger Message
|
||||
pub fn to_message(&self, source: MessageSource) -> Message {
|
||||
Message::new(
|
||||
MessageType::Command,
|
||||
source,
|
||||
serde_json::to_value(self).unwrap(),
|
||||
)
|
||||
.with_priority(MessagePriority::High)
|
||||
.with_metadata("search_type".to_string(), serde_json::to_string(&self.search_type).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl SearchResponse {
|
||||
/// 从 Message 解析
|
||||
pub fn from_message(message: &Message) -> Result<Self, serde_json::Error> {
|
||||
serde_json::from_value(message.payload.clone())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Search Messenger Service
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::messenger::types::{MessageSource, DeliveryOptions};
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Search Messenger 服务
|
||||
pub struct SearchMessenger {
|
||||
messenger: Messenger,
|
||||
}
|
||||
|
||||
impl SearchMessenger {
|
||||
pub fn new(db: 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 mut message = request.to_message(source);
|
||||
|
||||
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), // 5分钟 TTL
|
||||
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, // 30秒超时
|
||||
).await?;
|
||||
|
||||
if let Some(message) = messages.first() {
|
||||
let response = SearchResponse::from_message(message)?;
|
||||
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 = crate::core::command::messenger::types::Message::new(
|
||||
crate::core::command::messenger::types::MessageType::Command,
|
||||
MessageSource::System {
|
||||
component: "search_service".to_string(),
|
||||
},
|
||||
json!({
|
||||
"action": "cancel",
|
||||
"request_id": request_id,
|
||||
}),
|
||||
)
|
||||
.with_priority(crate::core::command::messenger::types::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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Search Worker
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::CommandResult;
|
||||
use crate::core::command::messenger::types::{Message, MessageSource, DeliveryOptions};
|
||||
use crate::core::db::{PostgresDb, QdrantDb};
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, error, info};
|
||||
|
||||
/// Search Worker
|
||||
pub struct SearchWorker {
|
||||
messenger: Messenger,
|
||||
db: PostgresDb,
|
||||
vector_db: QdrantDb,
|
||||
worker_id: String,
|
||||
}
|
||||
|
||||
impl SearchWorker {
|
||||
pub fn new(db_pool: sqlx::PgPool, db: PostgresDb, vector_db: QdrantDb) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db_pool),
|
||||
db,
|
||||
vector_db,
|
||||
worker_id: uuid::Uuid::new_v4().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动 Worker
|
||||
pub async fn start(&self) -> CommandResult<()> {
|
||||
info!(worker_id = %self.worker_id, "Search worker started");
|
||||
|
||||
loop {
|
||||
match self.process_requests().await {
|
||||
Ok(count) => {
|
||||
debug!(count = count, "Processed search requests");
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = ?e, "Error processing search requests");
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 处理搜索请求
|
||||
async fn process_requests(&self) -> CommandResult<usize> {
|
||||
let messages = self.messenger.receive(
|
||||
"search.requests",
|
||||
&self.worker_id,
|
||||
10,
|
||||
5000,
|
||||
).await?;
|
||||
|
||||
let count = messages.len();
|
||||
|
||||
for message in messages {
|
||||
if let Err(e) = self.handle_search(message).await {
|
||||
error!(error = ?e, "Error handling search message");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// 处理单个搜索
|
||||
async fn handle_search(&self, message: Message) -> CommandResult<()> {
|
||||
let start = Instant::now();
|
||||
let request: SearchRequest = serde_json::from_value(message.payload.clone())?;
|
||||
|
||||
debug!(
|
||||
request_id = %message.message_id,
|
||||
query = %request.query,
|
||||
type = ?request.search_type,
|
||||
"Processing search request"
|
||||
);
|
||||
|
||||
// 执行搜索
|
||||
let response = self.execute_search(&request, &message.message_id).await?;
|
||||
|
||||
// 发送结果
|
||||
self.send_result(response, &message.message_id).await?;
|
||||
|
||||
// 确认消息
|
||||
self.messenger.acknowledge(&message.message_id, &self.worker_id).await?;
|
||||
|
||||
info!(
|
||||
request_id = %message.message_id,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
"Search request completed"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 执行搜索逻辑
|
||||
async fn execute_search(
|
||||
&self,
|
||||
request: &SearchRequest,
|
||||
request_id: &str,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
let results = match request.search_type {
|
||||
SearchType::Keyword => self.keyword_search(request).await?,
|
||||
SearchType::Semantic => self.semantic_search(request).await?,
|
||||
SearchType::Hybrid => self.hybrid_search(request).await?,
|
||||
SearchType::People => self.people_search(request).await?,
|
||||
SearchType::Scene => self.scene_search(request).await?,
|
||||
SearchType::TimeRange => self.time_range_search(request).await?,
|
||||
SearchType::Custom => self.custom_search(request).await?,
|
||||
};
|
||||
|
||||
Ok(SearchResponse {
|
||||
request_id: request_id.to_string(),
|
||||
query: request.query.clone(),
|
||||
search_type: request.search_type.clone(),
|
||||
results,
|
||||
total_count: results.len() as i64,
|
||||
took_ms: start.elapsed().as_millis() as i64,
|
||||
facets: None,
|
||||
suggestions: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 发送结果
|
||||
async fn send_result(&self, response: SearchResponse, request_id: &str) -> CommandResult<()> {
|
||||
let message = crate::core::command::messenger::types::Message::new(
|
||||
crate::core::command::messenger::types::MessageType::Event,
|
||||
MessageSource::Worker {
|
||||
worker_id: self.worker_id.clone(),
|
||||
worker_type: "search".to_string(),
|
||||
},
|
||||
serde_json::to_value(&response)?,
|
||||
)
|
||||
.with_metadata("request_id".to_string(), request_id.to_string());
|
||||
|
||||
let options = DeliveryOptions {
|
||||
persistent: true,
|
||||
ttl_seconds: Some(3600), // 1小时
|
||||
require_ack: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.messenger.send("search.results", message, options).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 具体搜索方法实现...
|
||||
async fn keyword_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现 BM25 关键词搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn semantic_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现向量语义搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn hybrid_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现混合搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn people_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现人物搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn scene_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现场景搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn time_range_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现时间范围搜索
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn custom_search(&self, request: &SearchRequest) -> CommandResult<Vec<SearchResult>> {
|
||||
// 实现自定义搜索
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 工作流程
|
||||
|
||||
### 1. 同步搜索
|
||||
|
||||
```
|
||||
Studio UI → API Server → SearchMessenger.search()
|
||||
↓
|
||||
send to "search.requests"
|
||||
↓
|
||||
Search Worker receives
|
||||
↓
|
||||
Execute search
|
||||
↓
|
||||
send to "search.results"
|
||||
↓
|
||||
SearchMessenger.get_result()
|
||||
↓
|
||||
Return to Studio UI
|
||||
```
|
||||
|
||||
### 2. 异步搜索
|
||||
|
||||
```
|
||||
Studio UI → API Server → SearchMessenger.search()
|
||||
↓
|
||||
Return request_id
|
||||
|
||||
(Background)
|
||||
Search Worker processes → Sends result to "search.results"
|
||||
|
||||
Studio UI polls → API Server → SearchMessenger.get_result()
|
||||
↓
|
||||
Return result when ready
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💡 设计优势
|
||||
|
||||
### 1. 统一架构
|
||||
- ✅ Search 是 Messenger 的变形,不是独立系统
|
||||
- ✅ 复用消息传递、队列管理、错误处理机制
|
||||
- ✅ 统一的监控和日志
|
||||
|
||||
### 2. 可扩展性
|
||||
- ✅ 多个 Search Worker 并行处理
|
||||
- ✅ 按类型分片处理(keyword, semantic, hybrid)
|
||||
- ✅ 负载均衡
|
||||
|
||||
### 3. 可靠性
|
||||
- ✅ 消息持久化
|
||||
- ✅ 重试机制
|
||||
- ✅ 超时处理
|
||||
|
||||
### 4. 异步支持
|
||||
- ✅ 同步搜索(等待结果)
|
||||
- ✅ 异步搜索(立即返回 request_id)
|
||||
- ✅ 批量搜索
|
||||
|
||||
---
|
||||
|
||||
## 📊 队列配置
|
||||
|
||||
### Queue Names
|
||||
|
||||
| Queue | 用途 | 优先级 | TTL |
|
||||
|-------|------|--------|-----|
|
||||
| `search.requests` | 搜索请求 | High | 5分钟 |
|
||||
| `search.results` | 搜索结果 | Normal | 1小时 |
|
||||
| `search.control` | 控制命令(取消、暂停) | Critical | 1分钟 |
|
||||
|
||||
### Priority Distribution
|
||||
|
||||
```
|
||||
Search Requests:
|
||||
- P0 (Critical): 实时搜索(用户等待)
|
||||
- P1 (High): 批量搜索
|
||||
- P2 (Normal): 后台索引
|
||||
- P3 (Low): 分析任务
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 API 设计
|
||||
|
||||
### REST API
|
||||
|
||||
```rust
|
||||
// POST /api/v1/search
|
||||
pub async fn search_endpoint(
|
||||
Extension(search_messenger): Extension<Arc<SearchMessenger>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<SearchRequest>,
|
||||
) -> Result<Json<SearchResponse>, APIError> {
|
||||
let response = search_messenger
|
||||
.execute_search(request, Some(auth.user_id.clone()), Some(auth.key_id.clone()))
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
// POST /api/v1/search/async
|
||||
pub async fn search_async_endpoint(
|
||||
Extension(search_messenger): Extension<Arc<SearchMessenger>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<SearchRequest>,
|
||||
) -> Result<Json<AsyncSearchResponse>, APIError> {
|
||||
let request_id = search_messenger
|
||||
.search(request, Some(auth.user_id.clone()), Some(auth.key_id.clone()))
|
||||
.await?;
|
||||
|
||||
Ok(Json(AsyncSearchResponse {
|
||||
request_id,
|
||||
status: "processing".to_string(),
|
||||
message: "Search request submitted".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// GET /api/v1/search/results/{request_id}
|
||||
pub async fn get_search_result(
|
||||
Path(request_id): Path<String>,
|
||||
Extension(search_messenger): Extension<Arc<SearchMessenger>>,
|
||||
) -> Result<Json<Option<SearchResponse>>, APIError> {
|
||||
let result = search_messenger.get_result(&request_id).await?;
|
||||
Ok(Json(result))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📈 监控指标
|
||||
|
||||
```rust
|
||||
lazy_static! {
|
||||
static ref SEARCH_REQUESTS_TOTAL: CounterVec = register_counter_vec!(
|
||||
"search_requests_total",
|
||||
"Total search requests",
|
||||
&["type", "status"]
|
||||
).unwrap();
|
||||
|
||||
static ref SEARCH_LATENCY: HistogramVec = register_histogram_vec!(
|
||||
"search_latency_seconds",
|
||||
"Search latency in seconds",
|
||||
&["type"]
|
||||
).unwrap();
|
||||
|
||||
static ref SEARCH_QUEUE_LENGTH: GaugeVec = register_gauge_vec!(
|
||||
"search_queue_length",
|
||||
"Search queue length",
|
||||
&["queue"]
|
||||
).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 实施计划
|
||||
|
||||
### Phase 1: 基础实现(2 天)
|
||||
|
||||
- [ ] 实现 SearchMessenger
|
||||
- [ ] 实现 SearchWorker
|
||||
- [ ] 实现 API 端点
|
||||
- [ ] 单元测试
|
||||
|
||||
### Phase 2: 集成(1 天)
|
||||
|
||||
- [ ] 集成到 Studio UI
|
||||
- [ ] 集成 Billing
|
||||
- [ ] 集成 Log
|
||||
|
||||
### Phase 3: 优化(1 天)
|
||||
|
||||
- [ ] 性能测试
|
||||
- [ ] 负载测试
|
||||
- [ ] 监控配置
|
||||
|
||||
---
|
||||
|
||||
**Search 作为 Messenger 变形的设计完成!统一架构,易于扩展。**
|
||||
@@ -0,0 +1,285 @@
|
||||
# MarkBase Search 命名规范
|
||||
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 正式规范
|
||||
|
||||
---
|
||||
|
||||
## 📝 命名规范
|
||||
|
||||
### 顶层介面
|
||||
|
||||
**正式名称**: **Agent Search**
|
||||
|
||||
**全称**: Agent Search Service (统一智能搜尋介面)
|
||||
|
||||
**API 路径**: `/api/v1/agent/search`
|
||||
|
||||
**定位**:
|
||||
- 统一智能搜索入口
|
||||
- 用户无需选择搜索类型
|
||||
- Query Analyzer 自动路由
|
||||
- 支持单一或混合搜索策略
|
||||
|
||||
---
|
||||
|
||||
### 底层搜索类型(保持不变)
|
||||
|
||||
Agent Search 内部调用以下 5 种搜索类型:
|
||||
|
||||
| 名称 | 技术栈 | 队列名称 | Worker |
|
||||
|------|--------|----------|--------|
|
||||
| **Keyword** | BM25 + FTS | `search.keyword` | KeywordSearchWorker |
|
||||
| **Semantic** | Vector Embedding | `search.semantic` | SemanticSearchWorker |
|
||||
| **Visual** | VLM + CLIP | `search.visual` | VisualSearchWorker |
|
||||
| **Agent** | LLM + RAG | `search.agent` | AgentSearchWorker |
|
||||
| **People** | Face Identity | `search.people` | PeopleSearchWorker |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构层次
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Agent Search (统一智能搜尋介面) │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ Query Analyzer (智能路由) │ │
|
||||
│ │ - 分析查询意图 │ │
|
||||
│ │ - 选择搜索类型 │ │
|
||||
│ │ - 生成搜索策略 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ Strategy Executor (策略执行) │ │
|
||||
│ │ - Single: 单一类型 │ │
|
||||
│ │ - Hybrid: 混合类型 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ Result Processor (结果处理) │ │
|
||||
│ │ - 合并结果 │ │
|
||||
│ │ - 重新排序 │ │
|
||||
│ │ - 生成摘要 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
│
|
||||
├──────┬──────┬──────┬──────┐
|
||||
▼ ▼ ▼ ▼ ▼
|
||||
Keyword Semantic Visual Agent People
|
||||
Search Search Search Search Search
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 API 规范
|
||||
|
||||
### Agent Search API
|
||||
|
||||
**端点**: `POST /api/v1/agent/search`
|
||||
|
||||
**请求**:
|
||||
```json
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"context": {
|
||||
"user_id": "user_123",
|
||||
"conversation_id": "conv_456",
|
||||
"filters": {},
|
||||
"options": {
|
||||
"limit": 20,
|
||||
"include_thumbnails": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应**:
|
||||
```json
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"intent": {
|
||||
"primary_type": "people",
|
||||
"confidence": 0.85,
|
||||
"search_types": ["people", "keyword", "semantic"]
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"id": "video_123",
|
||||
"score": 0.96,
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"snippet": "Obama delivers speech...",
|
||||
"thumbnail": "https://..."
|
||||
}
|
||||
],
|
||||
"total_count": 15,
|
||||
"summary": "Found 15 videos featuring Barack Obama discussing healthcare...",
|
||||
"took_ms": 250
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 底层搜索 API(内部使用)
|
||||
|
||||
**端点**: `POST /api/v1/search/{type}`
|
||||
|
||||
**类型**:
|
||||
- `/api/v1/search/keyword`
|
||||
- `/api/v1/search/semantic`
|
||||
- `/api/v1/search/visual`
|
||||
- `/api/v1/search/agent`
|
||||
- `/api/v1/search/people`
|
||||
|
||||
**用途**: 内部 Worker 调用,不对外暴露
|
||||
|
||||
---
|
||||
|
||||
## 📊 数据模型
|
||||
|
||||
### Rust 类型
|
||||
|
||||
```rust
|
||||
/// Agent Search 服务
|
||||
pub struct AgentSearchService {
|
||||
messenger: Messenger,
|
||||
llm_client: LLMClient,
|
||||
query_analyzer: QueryAnalyzer,
|
||||
}
|
||||
|
||||
/// Agent Search 请求
|
||||
pub struct AgentSearchRequest {
|
||||
pub query: String,
|
||||
pub context: Option<SearchContext>,
|
||||
}
|
||||
|
||||
/// Agent Search 响应
|
||||
pub struct AgentSearchResponse {
|
||||
pub query: String,
|
||||
pub intent: QueryIntent,
|
||||
pub results: Vec<SearchResult>,
|
||||
pub total_count: i64,
|
||||
pub summary: String,
|
||||
pub took_ms: i64,
|
||||
}
|
||||
|
||||
/// 底层搜索类型
|
||||
pub enum SearchType {
|
||||
Keyword,
|
||||
Semantic,
|
||||
Visual,
|
||||
Agent,
|
||||
People,
|
||||
}
|
||||
|
||||
/// 底层搜索请求
|
||||
pub struct SearchRequest {
|
||||
pub query: String,
|
||||
pub search_type: SearchType,
|
||||
pub filters: SearchFilters,
|
||||
pub options: SearchOptions,
|
||||
}
|
||||
|
||||
/// 底层搜索响应
|
||||
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,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 场景 1: 简单搜索
|
||||
|
||||
**用户**: "interview with Obama"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: Keyword (0.9)
|
||||
- 执行: KeywordSearchWorker
|
||||
- 结果: 15 个视频
|
||||
|
||||
---
|
||||
|
||||
### 场景 2: 语义搜索
|
||||
|
||||
**用户**: "people discussing politics"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: Semantic (0.8)
|
||||
- 执行: SemanticSearchWorker
|
||||
- 结果: 23 个视频
|
||||
|
||||
---
|
||||
|
||||
### 场景 3: 混合搜索
|
||||
|
||||
**用户**: "Obama healthcare speech 2010"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: People (0.8), Keyword (0.7), Semantic (0.6)
|
||||
- 执行: 并行调用 3 个 Worker
|
||||
- 合并: 去重、重排
|
||||
- 结果: 25 个视频
|
||||
|
||||
---
|
||||
|
||||
### 场景 4: Agent 推理
|
||||
|
||||
**用户**: "compare Obama and Biden on healthcare"
|
||||
|
||||
**Agent Search**:
|
||||
- 分析: Agent (0.95)
|
||||
- 执行: AgentSearchWorker (LLM + RAG)
|
||||
- 推理: 多步骤搜索 + 比较
|
||||
- 结果: 比较报告 + 相关视频
|
||||
|
||||
---
|
||||
|
||||
## 📚 文档索引
|
||||
|
||||
### 设计文档
|
||||
|
||||
1. **Agent Search 设计**:
|
||||
- `docs_v1.0/DESIGN/Agent_Search_Interface.md`
|
||||
|
||||
2. **底层搜索类型**:
|
||||
- `docs_v1.0/DESIGN/Search_As_Messenger_Variant.md`
|
||||
|
||||
3. **架构设计**:
|
||||
- `docs_v1.0/DESIGN/MarkBase_Unified_Command_Queue.md`
|
||||
|
||||
---
|
||||
|
||||
### API 文档
|
||||
|
||||
1. **Agent Search API**:
|
||||
- `docs_v1.0/API_WORKSPACE/modules/agent_search_api.md`
|
||||
|
||||
2. **底层搜索 API**:
|
||||
- `docs_v1.0/API_WORKSPACE/modules/search_api.md`
|
||||
|
||||
---
|
||||
|
||||
## 🚀 开发状态
|
||||
|
||||
| 模块 | 状态 | 文件 |
|
||||
|------|------|------|
|
||||
| **AgentSearchService** | ⚠️ 待实现 | `src/core/command/agent_search/mod.rs` |
|
||||
| **QueryAnalyzer** | ⚠️ 待实现 | `src/core/command/agent_search/analyzer.rs` |
|
||||
| **SearchType 定义** | ✅ 完成 | `src/core/command/search/types.rs` |
|
||||
| **设计文档** | ✅ 完成 | `docs_v1.0/DESIGN/` |
|
||||
|
||||
---
|
||||
|
||||
## ✅ 命名规范确认
|
||||
|
||||
**正式命名**:
|
||||
- ✅ 顶层介面: **Agent Search**
|
||||
- ✅ 底层类型: Keyword, Semantic, Visual, Agent, People
|
||||
- ✅ API 路径: `/api/v1/agent/search`
|
||||
- ✅ 服务名称: `AgentSearchService`
|
||||
|
||||
**命名完成,设计规范已确认!**
|
||||
@@ -0,0 +1,742 @@
|
||||
# 独立队列系统架构设计
|
||||
|
||||
**版本**: V2.0
|
||||
**日期**: 2026-10-11
|
||||
**目标**: 独立部署、通用队列服务、支持任何队列需求
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
### 当前问题
|
||||
|
||||
| 问题 | 影响 | 解决方案 |
|
||||
|------|------|---------|
|
||||
| VLM 队列硬编码在 Job Worker | ❌ 无法独立部署 | 独立队列服务 |
|
||||
| 缺少通用队列抽象 | ❌ 每个队列重复实现 | 统一队列框架 |
|
||||
| 无法动态扩展队列类型 | ❌ 新队列需修改代码 | 插件式队列类型 |
|
||||
| 缺少队列管理 API | ❌ 难以监控和管理 | REST API 管理接口 |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 新架构设计
|
||||
|
||||
### 系统架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Queue Service (独立进程) │
|
||||
│ Port: 4000 │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ REST API (Axum) │ │
|
||||
│ │ ├─ POST /api/v1/queues 创建队列 │ │
|
||||
│ │ ├─ GET /api/v1/queues 列出队列 │ │
|
||||
│ │ ├─ DELETE /api/v1/queues/{name} 删除队列 │ │
|
||||
│ │ ├─ POST /api/v1/queues/{name}/messages 提交消息 │ │
|
||||
│ │ ├─ GET /api/v1/queues/{name}/messages 拉取消息 │ │
|
||||
│ │ ├─ POST /api/v1/queues/{name}/commit 提交确认 │ │
|
||||
│ │ └─ GET /api/v1/queues/{name}/stats 队列统计 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Queue Manager │ │
|
||||
│ │ ├─ 队列注册与管理 │ │
|
||||
│ │ ├─ 插件式队列类型支持 │ │
|
||||
│ │ └─ 生命周期管理 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Queue Implementations │ │
|
||||
│ │ ├─ VLM Queue (priority, retry, DLQ) │ │
|
||||
│ │ ├─ Command Queue (FIFO, deduplication) │ │
|
||||
│ │ ├─ Task Queue (dependency, parallel) │ │
|
||||
│ │ ├─ Notification Queue (broadcast) │ │
|
||||
│ │ └─ Custom Queue (plugin) │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Storage Backend │ │
|
||||
│ │ ├─ PostgreSQL (default, durable) │ │
|
||||
│ │ ├─ Redis (fast, in-memory) │ │
|
||||
│ │ └─ Custom (plugin) │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Worker Pool (可选) │ │
|
||||
│ │ ├─ 自动处理队列消息 │ │
|
||||
│ │ ├─ 自定义处理函数 │ │
|
||||
│ │ └─ 并发控制 │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 核心组件
|
||||
|
||||
### 1. Queue Service (主服务)
|
||||
|
||||
**职责**:
|
||||
- ✅ 独立进程,监听 HTTP API
|
||||
- ✅ 管理多个队列实例
|
||||
- ✅ 提供统一的队列操作接口
|
||||
- ✅ 支持插件式队列类型
|
||||
- ✅ 可选的 Worker Pool
|
||||
|
||||
**启动方式**:
|
||||
```bash
|
||||
# 独立启动
|
||||
cargo run --bin queue_service -- --port 4000
|
||||
|
||||
# 后台运行
|
||||
./target/release/queue_service --port 4000 > logs/queue_service.log 2>&1 &
|
||||
|
||||
# 配置文件
|
||||
queue_service --config queue_service.toml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Queue Manager
|
||||
|
||||
**职责**:
|
||||
- ✅ 注册和管理队列
|
||||
- ✅ 队列生命周期管理
|
||||
- ✅ 插件式队列类型加载
|
||||
- ✅ 配置管理
|
||||
|
||||
**API**:
|
||||
```rust
|
||||
impl QueueManager {
|
||||
// 创建队列
|
||||
pub async fn create_queue(&mut self, config: QueueConfig) -> Result<String>;
|
||||
|
||||
// 删除队列
|
||||
pub async fn delete_queue(&mut self, name: &str) -> Result<()>;
|
||||
|
||||
// 获取队列
|
||||
pub fn get_queue(&self, name: &str) -> Option<Arc<dyn Queue>>;
|
||||
|
||||
// 列出队列
|
||||
pub fn list_queues(&self) -> Vec<QueueInfo>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Queue Trait (通用接口)
|
||||
|
||||
```rust
|
||||
/// 通用队列接口
|
||||
#[async_trait]
|
||||
pub trait Queue: Send + Sync {
|
||||
/// 提交消息
|
||||
async fn enqueue(&self, message: Message) -> Result<MessageId>;
|
||||
|
||||
/// 拉取消息
|
||||
async fn dequeue(&self, options: DequeueOptions) -> Result<Vec<Message>>;
|
||||
|
||||
/// 确认消息
|
||||
async fn commit(&self, message_id: MessageId) -> Result<()>;
|
||||
|
||||
/// 失败消息
|
||||
async fn fail(&self, message_id: MessageId, error: &str) -> Result<()>;
|
||||
|
||||
/// 获取统计
|
||||
async fn stats(&self) -> Result<QueueStats>;
|
||||
|
||||
/// 清空队列
|
||||
async fn clear(&self) -> Result<()>;
|
||||
|
||||
/// 队列名称
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// 队列类型
|
||||
fn queue_type(&self) -> QueueType;
|
||||
}
|
||||
|
||||
/// 消息
|
||||
pub struct Message {
|
||||
pub id: MessageId,
|
||||
pub payload: serde_json::Value,
|
||||
pub priority: i32,
|
||||
pub metadata: HashMap<String, String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// 队列类型
|
||||
pub enum QueueType {
|
||||
Priority, // 优先级队列
|
||||
FIFO, // 先进先出
|
||||
Delayed, // 延迟队列
|
||||
Broadcast, // 广播队列
|
||||
Custom(String), // 自定义队列
|
||||
}
|
||||
|
||||
/// 队列配置
|
||||
pub struct QueueConfig {
|
||||
pub name: String,
|
||||
pub queue_type: QueueType,
|
||||
pub storage: StorageConfig,
|
||||
pub options: QueueOptions,
|
||||
}
|
||||
|
||||
pub struct QueueOptions {
|
||||
pub max_retries: u32,
|
||||
pub timeout_secs: u64,
|
||||
pub max_size: usize,
|
||||
pub deduplication: bool,
|
||||
pub priority_levels: u32,
|
||||
pub delayed_delivery: bool,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 队列类型实现
|
||||
|
||||
### 1. VLM Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ 优先级调度(P0-P1)
|
||||
- ✅ 重试机制
|
||||
- ✅ 死信队列
|
||||
- ✅ Offset 追踪
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "vlm"
|
||||
type = "priority"
|
||||
storage = "postgres"
|
||||
max_retries = 2
|
||||
timeout_secs = 60
|
||||
priority_levels = 2
|
||||
|
||||
[queues.dlq]
|
||||
enabled = true
|
||||
max_size = 1000
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 提交 VLM 请求
|
||||
curl -X POST http://localhost:4000/api/v1/queues/vlm/messages \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"priority": 0,
|
||||
"payload": {
|
||||
"request_type": "agent_vlm",
|
||||
"image_path": "/path/to/image.jpg",
|
||||
"prompt": "Analyze this image"
|
||||
}
|
||||
}'
|
||||
|
||||
# 拉取消息
|
||||
curl -X GET "http://localhost:4000/api/v1/queues/vlm/messages?max_messages=5&timeout=10"
|
||||
|
||||
# 确认消息
|
||||
curl -X POST http://localhost:4000/api/v1/queues/vlm/commit \
|
||||
-d '{"message_id": "vlm_abc123"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Command Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ FIFO 先进先出
|
||||
- ✅ 去重机制
|
||||
- ✅ 命令历史
|
||||
- ✅ 并发控制
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "command"
|
||||
type = "fifo"
|
||||
storage = "postgres"
|
||||
deduplication = true
|
||||
max_size = 1000
|
||||
|
||||
[queues.deduplication]
|
||||
window_secs = 3600
|
||||
key_fields = ["job_type", "file_path"]
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 提交注册命令
|
||||
curl -X POST http://localhost:4000/api/v1/queues/command/messages \
|
||||
-d '{
|
||||
"payload": {
|
||||
"job_type": "register",
|
||||
"file_path": "/path/to/video.mp4"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Task Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ 依赖管理
|
||||
- ✅ 并行处理
|
||||
- ✅ 进度追踪
|
||||
- ✅ 结果收集
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "task"
|
||||
type = "dependency"
|
||||
storage = "postgres"
|
||||
parallel = 6
|
||||
|
||||
[queues.dependency]
|
||||
check_interval_secs = 5
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 提交任务(带依赖)
|
||||
curl -X POST http://localhost:4000/api/v1/queues/task/messages \
|
||||
-d '{
|
||||
"payload": {
|
||||
"processor": "scene_vlm",
|
||||
"file_uuid": "abc123"
|
||||
},
|
||||
"metadata": {
|
||||
"dependencies": ["asr", "face", "cut"]
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. Notification Queue
|
||||
|
||||
**特性**:
|
||||
- ✅ 广播模式
|
||||
- ✅ 多订阅者
|
||||
- ✅ 实时推送
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "notification"
|
||||
type = "broadcast"
|
||||
storage = "redis"
|
||||
|
||||
[queues.broadcast]
|
||||
retention_secs = 3600
|
||||
```
|
||||
|
||||
**使用**:
|
||||
```bash
|
||||
# 发布通知
|
||||
curl -X POST http://localhost:4000/api/v1/queues/notification/messages \
|
||||
-d '{
|
||||
"payload": {
|
||||
"type": "job_completed",
|
||||
"file_uuid": "abc123"
|
||||
}
|
||||
}'
|
||||
|
||||
# 订阅通知 (WebSocket)
|
||||
ws://localhost:4000/api/v1/queues/notification/subscribe
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 插件系统
|
||||
|
||||
### 创建自定义队列
|
||||
|
||||
```rust
|
||||
// src/queue_plugins/my_queue.rs
|
||||
|
||||
use crate::queue::{Queue, Message, MessageId, QueueStats, DequeueOptions};
|
||||
|
||||
pub struct MyCustomQueue {
|
||||
name: String,
|
||||
storage: Arc<dyn Storage>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Queue for MyCustomQueue {
|
||||
async fn enqueue(&self, message: Message) -> Result<MessageId> {
|
||||
// 自定义逻辑
|
||||
}
|
||||
|
||||
async fn dequeue(&self, options: DequeueOptions) -> Result<Vec<Message>> {
|
||||
// 自定义逻辑
|
||||
}
|
||||
|
||||
// ... 实现其他方法
|
||||
}
|
||||
|
||||
// 注册插件
|
||||
#[no_mangle]
|
||||
pub extern "C" fn create_queue(config: QueueConfig) -> Box<dyn Queue> {
|
||||
Box::new(MyCustomQueue::new(config))
|
||||
}
|
||||
```
|
||||
|
||||
**配置**:
|
||||
```toml
|
||||
[[queues]]
|
||||
name = "my_custom"
|
||||
type = "custom:my_queue"
|
||||
plugin = "plugins/libmy_queue.dylib"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 部署架构
|
||||
|
||||
### 单实例部署
|
||||
|
||||
```
|
||||
Queue Service (port 4000)
|
||||
↓
|
||||
PostgreSQL (持久化)
|
||||
Redis (缓存,可选)
|
||||
```
|
||||
|
||||
**启动**:
|
||||
```bash
|
||||
# 方式 1: 直接运行
|
||||
cargo run --release --bin queue_service -- --port 4000
|
||||
|
||||
# 方式 2: Docker
|
||||
docker run -p 4000:4000 momentry/queue-service
|
||||
|
||||
# 方式 3: launchd
|
||||
launchctl start gui/$(id -u)/com.momentry.queue-service
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 集群部署(未来)
|
||||
|
||||
```
|
||||
┌──────────────────┐
|
||||
│ Load Balancer │
|
||||
└──────────────────┘
|
||||
│
|
||||
┌────┴────┐
|
||||
│ │
|
||||
┌───▼───┐ ┌───▼───┐
|
||||
│Queue │ │Queue │
|
||||
│Node 1 │ │Node 2 │
|
||||
└───────┘ └───────┘
|
||||
│ │
|
||||
└────┬────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ Shared Storage │
|
||||
│ (PostgreSQL) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 REST API 完整规范
|
||||
|
||||
### 队列管理
|
||||
|
||||
```http
|
||||
# 创建队列
|
||||
POST /api/v1/queues
|
||||
{
|
||||
"name": "my_queue",
|
||||
"type": "priority",
|
||||
"config": {
|
||||
"max_retries": 3,
|
||||
"timeout_secs": 60
|
||||
}
|
||||
}
|
||||
|
||||
# 列出队列
|
||||
GET /api/v1/queues
|
||||
|
||||
# 删除队列
|
||||
DELETE /api/v1/queues/my_queue
|
||||
|
||||
# 获取队列信息
|
||||
GET /api/v1/queues/my_queue
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 消息操作
|
||||
|
||||
```http
|
||||
# 提交消息
|
||||
POST /api/v1/queues/my_queue/messages
|
||||
{
|
||||
"priority": 0,
|
||||
"payload": {...},
|
||||
"metadata": {...}
|
||||
}
|
||||
|
||||
# 响应
|
||||
{
|
||||
"message_id": "msg_abc123",
|
||||
"status": "pending",
|
||||
"created_at": "2026-10-11T09:00:00Z"
|
||||
}
|
||||
|
||||
# 拉取消息
|
||||
GET /api/v1/queues/my_queue/messages?max_messages=10&timeout=30
|
||||
|
||||
# 响应
|
||||
{
|
||||
"messages": [
|
||||
{
|
||||
"id": "msg_abc123",
|
||||
"payload": {...},
|
||||
"priority": 0,
|
||||
"created_at": "2026-10-11T09:00:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# 确认消息
|
||||
POST /api/v1/queues/my_queue/commit
|
||||
{
|
||||
"message_id": "msg_abc123",
|
||||
"result": "success",
|
||||
"output": {...}
|
||||
}
|
||||
|
||||
# 失败消息
|
||||
POST /api/v1/queues/my_queue/fail
|
||||
{
|
||||
"message_id": "msg_abc123",
|
||||
"error": "Processing failed"
|
||||
}
|
||||
|
||||
# 获取消息状态
|
||||
GET /api/v1/queues/my_queue/messages/msg_abc123
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 统计与监控
|
||||
|
||||
```http
|
||||
# 队列统计
|
||||
GET /api/v1/queues/my_queue/stats
|
||||
|
||||
# 响应
|
||||
{
|
||||
"queue_name": "my_queue",
|
||||
"queue_type": "priority",
|
||||
"pending": 10,
|
||||
"processing": 2,
|
||||
"completed": 50,
|
||||
"failed": 3,
|
||||
"avg_processing_time_ms": 1250.5,
|
||||
"throughput_per_min": 12.5
|
||||
}
|
||||
|
||||
# 健康检查
|
||||
GET /api/v1/health
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ 客户端 SDK
|
||||
|
||||
### Rust SDK
|
||||
|
||||
```rust
|
||||
use momentry_queue::{QueueClient, Message};
|
||||
|
||||
let client = QueueClient::new("http://localhost:4000")?;
|
||||
|
||||
// 创建队列
|
||||
client.create_queue("my_queue", QueueConfig::priority()).await?;
|
||||
|
||||
// 提交消息
|
||||
let msg = Message::new(json!({"key": "value"}))
|
||||
.with_priority(0);
|
||||
let msg_id = client.enqueue("my_queue", msg).await?;
|
||||
|
||||
// 拉取消息
|
||||
let messages = client.dequeue("my_queue", 10).await?;
|
||||
|
||||
// 确认消息
|
||||
client.commit("my_queue", msg_id).await?;
|
||||
```
|
||||
|
||||
### Python SDK
|
||||
|
||||
```python
|
||||
from momentry_queue import QueueClient
|
||||
|
||||
client = QueueClient("http://localhost:4000")
|
||||
|
||||
# 提交消息
|
||||
msg_id = client.enqueue("my_queue", {"key": "value"}, priority=0)
|
||||
|
||||
# 拉取消息
|
||||
messages = client.dequeue("my_queue", max_messages=10)
|
||||
|
||||
# 确认消息
|
||||
client.commit("my_queue", msg_id)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 配置文件示例
|
||||
|
||||
```toml
|
||||
# queue_service.toml
|
||||
|
||||
[server]
|
||||
host = "0.0.0.0"
|
||||
port = 4000
|
||||
|
||||
[storage]
|
||||
default = "postgres"
|
||||
|
||||
[storage.postgres]
|
||||
url = "postgres://accusys@localhost:5432/momentry"
|
||||
pool_size = 10
|
||||
|
||||
[storage.redis]
|
||||
url = "redis://localhost:6379"
|
||||
pool_size = 5
|
||||
|
||||
# VLM Queue
|
||||
[[queues]]
|
||||
name = "vlm"
|
||||
type = "priority"
|
||||
storage = "postgres"
|
||||
max_retries = 2
|
||||
timeout_secs = 60
|
||||
priority_levels = 2
|
||||
|
||||
[queues.dlq]
|
||||
enabled = true
|
||||
max_size = 1000
|
||||
|
||||
# Command Queue
|
||||
[[queues]]
|
||||
name = "command"
|
||||
type = "fifo"
|
||||
storage = "postgres"
|
||||
deduplication = true
|
||||
max_size = 1000
|
||||
|
||||
# Task Queue
|
||||
[[queues]]
|
||||
name = "task"
|
||||
type = "dependency"
|
||||
storage = "postgres"
|
||||
parallel = 6
|
||||
|
||||
# Notification Queue
|
||||
[[queues]]
|
||||
name = "notification"
|
||||
type = "broadcast"
|
||||
storage = "redis"
|
||||
retention_secs = 3600
|
||||
|
||||
[worker_pool]
|
||||
enabled = false # 如果 true,自动处理消息
|
||||
max_workers = 10
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 安装
|
||||
|
||||
```bash
|
||||
# 编译
|
||||
cargo build --release --bin queue_service
|
||||
|
||||
# 或安装
|
||||
cargo install --path . --bin queue_service
|
||||
```
|
||||
|
||||
### 启动
|
||||
|
||||
```bash
|
||||
# 方式 1: 默认配置
|
||||
queue_service
|
||||
|
||||
# 方式 2: 指定配置
|
||||
queue_service --config queue_service.toml
|
||||
|
||||
# 方式 3: 指定端口
|
||||
queue_service --port 4000
|
||||
```
|
||||
|
||||
### 使用
|
||||
|
||||
```bash
|
||||
# 创建队列
|
||||
curl -X POST http://localhost:4000/api/v1/queues \
|
||||
-d '{"name": "test", "type": "fifo"}'
|
||||
|
||||
# 提交消息
|
||||
curl -X POST http://localhost:4000/api/v1/queues/test/messages \
|
||||
-d '{"payload": {"message": "hello"}}'
|
||||
|
||||
# 拉取消息
|
||||
curl http://localhost:4000/api/v1/queues/test/messages
|
||||
|
||||
# 查看统计
|
||||
curl http://localhost:4000/api/v1/queues/test/stats
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 迁移计划
|
||||
|
||||
### 阶段 1: 实现核心框架(1 周)
|
||||
|
||||
- [ ] Queue Trait 定义
|
||||
- [ ] Queue Manager 实现
|
||||
- [ ] REST API 实现
|
||||
- [ ] PostgreSQL Storage 实现
|
||||
|
||||
### 阶段 2: 迁移现有队列(1 周)
|
||||
|
||||
- [ ] VLM Queue 实现
|
||||
- [ ] Command Queue 实现
|
||||
- [ ] Task Queue 实现
|
||||
|
||||
### 阶段 3: 高级功能(1 周)
|
||||
|
||||
- [ ] Worker Pool
|
||||
- [ ] 插件系统
|
||||
- [ ] 监控告警
|
||||
|
||||
### 阶段 4: 集成与测试(3 天)
|
||||
|
||||
- [ ] 与 Momentry Core 集成
|
||||
- [ ] 性能测试
|
||||
- [ ] 文档完善
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- API 规范: `docs_v1.0/API_WORKSPACE/queue_service_api.md`
|
||||
- 客户端 SDK: `docs_v1.0/GUIDES/queue_sdk_guide.md`
|
||||
- 插件开发: `docs_v1.0/GUIDES/queue_plugin_development.md`
|
||||
|
||||
---
|
||||
|
||||
**设计完成,准备实施!**
|
||||
@@ -0,0 +1,812 @@
|
||||
# MarkBase Search 统一交谈介面设计
|
||||
|
||||
**版本**: 1.0
|
||||
**日期**: 2026-10-11
|
||||
**状态**: 设计规范
|
||||
|
||||
---
|
||||
|
||||
## 🎯 设计目标
|
||||
|
||||
创建 **统一的交谈介面服务**,支持 5 种搜索类别,用户无需指定类型,系统自动选择最佳搜索方式。
|
||||
|
||||
---
|
||||
|
||||
## 📊 搜索类别定义
|
||||
|
||||
### 1. 五大搜索类别
|
||||
|
||||
```rust
|
||||
/// Search 类型
|
||||
#[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,
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 各类型特点
|
||||
|
||||
| 类型 | 技术 | 数据源 | 特点 | 用例 |
|
||||
|------|------|--------|------|------|
|
||||
| **Keyword** | BM25, FTS | PostgreSQL | 精确匹配,快速 | "news report", "interview" |
|
||||
| **Semantic** | Vector Search | Qdrant | 语义理解,模糊匹配 | "people talking about politics" |
|
||||
| **Visual** | VLM, CLIP | Qdrant, Frames | 视觉内容,场景描述 | "sunset beach", "woman in red dress" |
|
||||
| **Agent** | LLM + RAG | All Sources | 复杂查询,推理 | "find all videos where Obama discusses healthcare" |
|
||||
| **People** | Face Identity | Qdrant Faces | 人物识别,身份关联 | "videos with Barack Obama" |
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 统一介面架构
|
||||
|
||||
### 核心理念
|
||||
|
||||
```
|
||||
User Query
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Unified Search Interface │
|
||||
│ ┌───────────────────────────────────────────────────┐ │
|
||||
│ │ Query Analyzer (智能路由) │ │
|
||||
│ │ - 分析查询意图 │ │
|
||||
│ │ - 选择搜索类型 │ │
|
||||
│ │ - 生成搜索策略 │ │
|
||||
│ └───────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ├─→ Keyword Search (30%) │
|
||||
│ ├─→ Semantic Search (25%) │
|
||||
│ ├─→ Visual Search (15%) │
|
||||
│ ├─→ Agent Search (20%) │
|
||||
│ └─→ People Search (10%) │
|
||||
│ │
|
||||
│ ┌───────────────────────────────────────────────────┐ │
|
||||
│ │ Result Merger (结果合并) │ │
|
||||
│ │ - 统一排序 │ │
|
||||
│ │ - 去重 │ │
|
||||
│ │ - 上下文丰富 │ │
|
||||
│ └───────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
Unified Results
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💬 统一交谈介面服务
|
||||
|
||||
### 1. UnifiedSearchService
|
||||
|
||||
```rust
|
||||
// MarkBase Queue Protocol - Independent Implementation
|
||||
// This is NOT compatible with Apache Kafka protocol or API.
|
||||
|
||||
use super::types::*;
|
||||
use crate::core::command::messenger::Messenger;
|
||||
use crate::core::command::error::{CommandError, CommandResult};
|
||||
use crate::core::command::messenger::types::{Message, MessageSource, MessagePriority, MessageType, DeliveryOptions};
|
||||
use crate::core::llm::LLMClient;
|
||||
use std::time::Instant;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// 统一搜索服务
|
||||
pub struct UnifiedSearchService {
|
||||
messenger: Messenger,
|
||||
llm_client: LLMClient,
|
||||
query_analyzer: QueryAnalyzer,
|
||||
}
|
||||
|
||||
impl UnifiedSearchService {
|
||||
pub fn new(db: sqlx::PgPool, llm_client: LLMClient) -> Self {
|
||||
Self {
|
||||
messenger: Messenger::new(db),
|
||||
llm_client: llm_client.clone(),
|
||||
query_analyzer: QueryAnalyzer::new(llm_client),
|
||||
}
|
||||
}
|
||||
|
||||
/// 统一搜索入口(智能路由)
|
||||
pub async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<UnifiedSearchResponse> {
|
||||
let start = Instant::now();
|
||||
|
||||
// 1. 分析查询意图
|
||||
let intent = self.query_analyzer.analyze(query, context.clone()).await?;
|
||||
|
||||
debug!(
|
||||
query = %query,
|
||||
intent = ?intent.search_types,
|
||||
confidence = intent.confidence,
|
||||
"Query intent analyzed"
|
||||
);
|
||||
|
||||
// 2. 根据意图选择搜索策略
|
||||
let strategy = self.select_strategy(&intent);
|
||||
|
||||
// 3. 执行搜索(可能是并行多个类型)
|
||||
let results = self.execute_strategy(&strategy, query, context.clone()).await?;
|
||||
|
||||
// 4. 合并结果
|
||||
let unified_response = self.merge_results(results, query, intent).await?;
|
||||
|
||||
info!(
|
||||
query = %query,
|
||||
took_ms = start.elapsed().as_millis(),
|
||||
total_results = unified_response.total_count,
|
||||
"Unified search completed"
|
||||
);
|
||||
|
||||
Ok(unified_response)
|
||||
}
|
||||
|
||||
/// 选择搜索策略
|
||||
fn select_strategy(&self, intent: &QueryIntent) -> SearchStrategy {
|
||||
match intent.primary_type {
|
||||
// 单一类型高置信度
|
||||
SearchType::Keyword if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Keyword)
|
||||
}
|
||||
SearchType::Semantic if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Semantic)
|
||||
}
|
||||
SearchType::Visual if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::Visual)
|
||||
}
|
||||
SearchType::People if intent.confidence > 0.8 => {
|
||||
SearchStrategy::Single(SearchType::People)
|
||||
}
|
||||
SearchType::Agent if intent.confidence > 0.7 => {
|
||||
SearchStrategy::Single(SearchType::Agent)
|
||||
}
|
||||
|
||||
// 混合策略
|
||||
_ => {
|
||||
let mut types = Vec::new();
|
||||
|
||||
if intent.scores.keyword > 0.3 {
|
||||
types.push((SearchType::Keyword, intent.scores.keyword));
|
||||
}
|
||||
if intent.scores.semantic > 0.3 {
|
||||
types.push((SearchType::Semantic, intent.scores.semantic));
|
||||
}
|
||||
if intent.scores.visual > 0.3 {
|
||||
types.push((SearchType::Visual, intent.scores.visual));
|
||||
}
|
||||
if intent.scores.people > 0.3 {
|
||||
types.push((SearchType::People, intent.scores.people));
|
||||
}
|
||||
|
||||
// Agent 作为后备
|
||||
if types.is_empty() {
|
||||
types.push((SearchType::Agent, 1.0));
|
||||
}
|
||||
|
||||
SearchStrategy::Hybrid(types)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行搜索策略
|
||||
async fn execute_strategy(
|
||||
&self,
|
||||
strategy: &SearchStrategy,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<Vec<SearchResponse>> {
|
||||
match strategy {
|
||||
SearchStrategy::Single(search_type) => {
|
||||
let response = self.execute_single_search(search_type, query, context).await?;
|
||||
Ok(vec![response])
|
||||
}
|
||||
|
||||
SearchStrategy::Hybrid(types) => {
|
||||
// 并行执行多个搜索
|
||||
let mut handles = Vec::new();
|
||||
|
||||
for (search_type, weight) in types {
|
||||
let handle = self.execute_single_search(search_type, query, context.clone());
|
||||
handles.push((search_type.clone(), weight, handle));
|
||||
}
|
||||
|
||||
// 收集结果
|
||||
let mut results = Vec::new();
|
||||
for (search_type, weight, handle) in handles {
|
||||
match handle.await {
|
||||
Ok(response) => {
|
||||
results.push((response, weight));
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(
|
||||
search_type = ?search_type,
|
||||
error = ?e,
|
||||
"Search type failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results.into_iter().map(|(r, _)| r).collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行单一类型搜索
|
||||
async fn execute_single_search(
|
||||
&self,
|
||||
search_type: &SearchType,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<SearchResponse> {
|
||||
let request = SearchRequest::new(query.to_string(), search_type.clone())
|
||||
.with_filters(context.clone().map(|c| c.filters).unwrap_or_default())
|
||||
.with_options(context.clone().map(|c| c.options).unwrap_or_default());
|
||||
|
||||
let request_id = self.messenger.send_search_request(&request).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.messenger.get_search_result(&request_id).await? {
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 合并搜索结果
|
||||
async fn merge_results(
|
||||
&self,
|
||||
results: Vec<SearchResponse>,
|
||||
query: &str,
|
||||
intent: QueryIntent,
|
||||
) -> CommandResult<UnifiedSearchResponse> {
|
||||
let mut all_results = Vec::new();
|
||||
let mut seen_ids = std::collections::HashSet::new();
|
||||
|
||||
// 1. 收集所有结果
|
||||
for response in results {
|
||||
for result in response.results {
|
||||
if !seen_ids.contains(&result.id) {
|
||||
seen_ids.insert(result.id.clone());
|
||||
all_results.push(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 重新评分和排序
|
||||
for result in &mut all_results {
|
||||
// 根据查询意图调整分数
|
||||
result.score = self.adjust_score(result.score, &intent);
|
||||
}
|
||||
|
||||
// 3. 排序
|
||||
all_results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
|
||||
|
||||
// 4. 生成摘要(使用 LLM)
|
||||
let summary = self.generate_summary(query, &all_results).await?;
|
||||
|
||||
Ok(UnifiedSearchResponse {
|
||||
query: query.to_string(),
|
||||
intent,
|
||||
results: all_results,
|
||||
total_count: all_results.len() as i64,
|
||||
summary,
|
||||
took_ms: 0, // 由外层设置
|
||||
})
|
||||
}
|
||||
|
||||
/// 调整分数
|
||||
fn adjust_score(&self, original_score: f64, intent: &QueryIntent) -> f64 {
|
||||
// 根据意图置信度调整分数
|
||||
original_score * (0.5 + 0.5 * intent.confidence)
|
||||
}
|
||||
|
||||
/// 生成摘要
|
||||
async fn generate_summary(
|
||||
&self,
|
||||
query: &str,
|
||||
results: &[SearchResult],
|
||||
) -> CommandResult<String> {
|
||||
if results.is_empty() {
|
||||
return Ok("No results found.".to_string());
|
||||
}
|
||||
|
||||
// 使用 LLM 生成自然语言摘要
|
||||
let prompt = format!(
|
||||
"Summarize the search results for query '{}' in 2-3 sentences. Found {} results.",
|
||||
query,
|
||||
results.len()
|
||||
);
|
||||
|
||||
let summary = self.llm_client.chat(&prompt).await?;
|
||||
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// 对话式搜索(多轮)
|
||||
pub async fn conversational_search(
|
||||
&self,
|
||||
conversation_id: &str,
|
||||
query: &str,
|
||||
) -> CommandResult<UnifiedSearchResponse> {
|
||||
// 1. 获取对话历史
|
||||
let history = self.get_conversation_history(conversation_id).await?;
|
||||
|
||||
// 2. 结合历史理解查询
|
||||
let context = SearchContext {
|
||||
conversation_history: history,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 3. 执行搜索
|
||||
let mut response = self.search(query, Some(context)).await?;
|
||||
|
||||
// 4. 更新对话历史
|
||||
self.update_conversation(conversation_id, query, &response).await?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn get_conversation_history(&self, _conversation_id: &str) -> CommandResult<Vec<Message>> {
|
||||
// TODO: 从数据库获取对话历史
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn update_conversation(
|
||||
&self,
|
||||
_conversation_id: &str,
|
||||
_query: &str,
|
||||
_response: &UnifiedSearchResponse,
|
||||
) -> CommandResult<()> {
|
||||
// TODO: 更新对话历史到数据库
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 搜索策略
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SearchStrategy {
|
||||
/// 单一类型搜索
|
||||
Single(SearchType),
|
||||
/// 混合搜索
|
||||
Hybrid(Vec<(SearchType, 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<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,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Query Analyzer (智能路由)
|
||||
|
||||
```rust
|
||||
/// 查询分析器
|
||||
pub struct QueryAnalyzer {
|
||||
llm_client: LLMClient,
|
||||
}
|
||||
|
||||
/// 查询意图
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl QueryAnalyzer {
|
||||
pub fn new(llm_client: LLMClient) -> Self {
|
||||
Self { llm_client }
|
||||
}
|
||||
|
||||
/// 分析查询意图
|
||||
pub async fn analyze(
|
||||
&self,
|
||||
query: &str,
|
||||
context: Option<SearchContext>,
|
||||
) -> CommandResult<QueryIntent> {
|
||||
// 1. 提取实体和关键词
|
||||
let entities = self.extract_entities(query).await?;
|
||||
let keywords = self.extract_keywords(query).await?;
|
||||
|
||||
// 2. 判断搜索类型
|
||||
let scores = self.score_search_types(query, &entities, &keywords).await?;
|
||||
|
||||
// 3. 确定主要类型
|
||||
let (primary_type, confidence) = self.determine_primary_type(&scores);
|
||||
|
||||
// 4. 确定次要类型
|
||||
let search_types = self.determine_secondary_types(&scores);
|
||||
|
||||
Ok(QueryIntent {
|
||||
primary_type,
|
||||
search_types,
|
||||
confidence,
|
||||
scores,
|
||||
entities,
|
||||
keywords,
|
||||
})
|
||||
}
|
||||
|
||||
/// 提取实体
|
||||
async fn extract_entities(&self, query: &str) -> CommandResult<Vec<String>> {
|
||||
let prompt = format!(
|
||||
"Extract named entities from this query: '{}'. Return as JSON array.",
|
||||
query
|
||||
);
|
||||
|
||||
let response = self.llm_client.chat(&prompt).await?;
|
||||
let entities: Vec<String> = serde_json::from_str(&response)?;
|
||||
|
||||
Ok(entities)
|
||||
}
|
||||
|
||||
/// 提取关键词
|
||||
async fn extract_keywords(&self, query: &str) -> CommandResult<Vec<String>> {
|
||||
let prompt = format!(
|
||||
"Extract keywords from this query: '{}'. Return as JSON array.",
|
||||
query
|
||||
);
|
||||
|
||||
let response = self.llm_client.chat(&prompt).await?;
|
||||
let keywords: Vec<String> = serde_json::from_str(&response)?;
|
||||
|
||||
Ok(keywords)
|
||||
}
|
||||
|
||||
/// 评分搜索类型
|
||||
async fn score_search_types(
|
||||
&self,
|
||||
query: &str,
|
||||
entities: &[String],
|
||||
keywords: &[String],
|
||||
) -> CommandResult<SearchTypeScores> {
|
||||
let prompt = format!(
|
||||
r#"Analyze the search query and score each search type (0.0-1.0):
|
||||
Query: "{}"
|
||||
Entities: {:?}
|
||||
Keywords: {:?}
|
||||
|
||||
Score each type based on:
|
||||
- keyword: precise text matching (dates, names, specific terms)
|
||||
- semantic: conceptual understanding (actions, relationships, ideas)
|
||||
- visual: image/video content (colors, objects, scenes, appearances)
|
||||
- agent: complex reasoning (multi-step, inference needed)
|
||||
- people: person-focused (names, faces, identities)
|
||||
|
||||
Return as JSON: {{"keyword": 0.8, "semantic": 0.5, "visual": 0.3, "agent": 0.2, "people": 0.0}}"#,
|
||||
query, entities, keywords
|
||||
);
|
||||
|
||||
let response = self.llm_client.chat(&prompt).await?;
|
||||
let scores: SearchTypeScores = serde_json::from_str(&response)?;
|
||||
|
||||
Ok(scores)
|
||||
}
|
||||
|
||||
/// 确定主要类型
|
||||
fn determine_primary_type(&self, scores: &SearchTypeScores) -> (SearchType, f64) {
|
||||
let types = vec![
|
||||
(SearchType::Keyword, scores.keyword),
|
||||
(SearchType::Semantic, scores.semantic),
|
||||
(SearchType::Visual, scores.visual),
|
||||
(SearchType::Agent, scores.agent),
|
||||
(SearchType::People, scores.people),
|
||||
];
|
||||
|
||||
types
|
||||
.into_iter()
|
||||
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// 确定次要类型
|
||||
fn determine_secondary_types(&self, scores: &SearchTypeScores) -> Vec<SearchType> {
|
||||
let mut types = vec![
|
||||
(SearchType::Keyword, scores.keyword),
|
||||
(SearchType::Semantic, scores.semantic),
|
||||
(SearchType::Visual, scores.visual),
|
||||
(SearchType::Agent, scores.agent),
|
||||
(SearchType::People, scores.people),
|
||||
];
|
||||
|
||||
types.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
|
||||
|
||||
types
|
||||
.into_iter()
|
||||
.filter(|(_, score)| *score > 0.3)
|
||||
.map(|(t, _)| t)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 工作流程示例
|
||||
|
||||
### 示例 1: 简单关键词搜索
|
||||
|
||||
```
|
||||
Query: "interview with Obama"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["Obama"]
|
||||
- keywords: ["interview"]
|
||||
- scores: {keyword: 0.9, people: 0.7, semantic: 0.3, ...}
|
||||
- primary_type: Keyword (confidence: 0.9)
|
||||
|
||||
Strategy: Single(Keyword)
|
||||
|
||||
Execution:
|
||||
→ Keyword Search Worker
|
||||
→ FTS + BM25
|
||||
|
||||
Results:
|
||||
- Video 1: "Obama Interview 2020" (score: 0.95)
|
||||
- Video 2: "Interview with Barack Obama" (score: 0.92)
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 示例 2: 复杂语义搜索
|
||||
|
||||
```
|
||||
Query: "videos where people discuss climate change solutions"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["climate change", "solutions"]
|
||||
- keywords: ["videos", "people", "discuss"]
|
||||
- scores: {semantic: 0.8, agent: 0.6, keyword: 0.3, ...}
|
||||
- primary_type: Semantic (confidence: 0.8)
|
||||
|
||||
Strategy: Single(Semantic)
|
||||
|
||||
Execution:
|
||||
→ Semantic Search Worker
|
||||
→ Vector Similarity Search
|
||||
→ Embedding: "discussing climate change solutions"
|
||||
|
||||
Results:
|
||||
- Video 1: Documentary on renewable energy (score: 0.88)
|
||||
- Video 2: Town hall on climate policy (score: 0.85)
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 示例 3: 混合搜索
|
||||
|
||||
```
|
||||
Query: "Obama giving speech about healthcare in 2010"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["Obama", "2010"]
|
||||
- keywords: ["speech", "healthcare"]
|
||||
- scores: {keyword: 0.7, people: 0.8, semantic: 0.6, agent: 0.5, ...}
|
||||
- primary_type: People (confidence: 0.8)
|
||||
|
||||
Strategy: Hybrid([
|
||||
(People, 0.8),
|
||||
(Keyword, 0.7),
|
||||
(Semantic, 0.6),
|
||||
])
|
||||
|
||||
Execution (Parallel):
|
||||
→ People Search: Face identity match "Obama"
|
||||
→ Keyword Search: "healthcare", "speech", "2010"
|
||||
→ Semantic Search: "healthcare policy speech"
|
||||
|
||||
Merge Results:
|
||||
- Combine and re-rank
|
||||
- Remove duplicates
|
||||
- Adjust scores by intent confidence
|
||||
|
||||
Final Results:
|
||||
- Video 1: Obama healthcare speech 2010 (score: 0.96)
|
||||
- Video 2: Obama discusses healthcare reform (score: 0.89)
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 示例 4: Agent 搜索
|
||||
|
||||
```
|
||||
Query: "Find all videos where Obama talks about healthcare and compare with Biden's positions"
|
||||
|
||||
Query Analyzer:
|
||||
- entities: ["Obama", "Biden", "healthcare"]
|
||||
- complexity: High (multi-step, comparison)
|
||||
- scores: {agent: 0.95, ...}
|
||||
- primary_type: Agent (confidence: 0.95)
|
||||
|
||||
Strategy: Single(Agent)
|
||||
|
||||
Execution:
|
||||
→ Agent Search Worker
|
||||
→ LLM Agent:
|
||||
1. Search for Obama healthcare videos
|
||||
2. Search for Biden healthcare videos
|
||||
3. Extract positions from each
|
||||
4. Compare and summarize
|
||||
|
||||
Results:
|
||||
- Obama: "Healthcare should be universal..."
|
||||
- Biden: "We need to build on ACA..."
|
||||
- Comparison: "Both support universal coverage..."
|
||||
- Related Videos: [...]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 用户介面设计
|
||||
|
||||
### 统一搜索框
|
||||
|
||||
```html
|
||||
<!-- Studio UI -->
|
||||
<div class="unified-search">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search videos, people, scenes, or ask a question..."
|
||||
class="search-input"
|
||||
/>
|
||||
<div class="search-hints">
|
||||
<span class="hint" data-type="keyword">"interview with Obama"</span>
|
||||
<span class="hint" data-type="semantic">"people discussing politics"</span>
|
||||
<span class="hint" data-type="visual">"sunset at beach"</span>
|
||||
<span class="hint" data-type="agent">"compare Obama and Biden on healthcare"</span>
|
||||
<span class="hint" data-type="people">"videos with Barack Obama"</span>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### 搜索结果显示
|
||||
|
||||
```rust
|
||||
// 统一搜索响应
|
||||
{
|
||||
"query": "Obama healthcare speech",
|
||||
"intent": {
|
||||
"primary_type": "people",
|
||||
"confidence": 0.85,
|
||||
"search_types": ["people", "keyword", "semantic"]
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"id": "video_123",
|
||||
"file_uuid": "384b0ff44aaaa1f1",
|
||||
"score": 0.96,
|
||||
"snippet": "Obama delivers speech on healthcare reform...",
|
||||
"thumbnail": "https://...",
|
||||
"metadata": {
|
||||
"duration": 1800,
|
||||
"date": "2010-03-23",
|
||||
"identities": ["Barack Obama"]
|
||||
}
|
||||
},
|
||||
...
|
||||
],
|
||||
"total_count": 15,
|
||||
"summary": "Found 15 videos featuring Barack Obama discussing healthcare, primarily from 2009-2010 during the ACA debate.",
|
||||
"took_ms": 250
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 API 端点
|
||||
|
||||
```rust
|
||||
// POST /api/v1/search
|
||||
pub async fn unified_search(
|
||||
Extension(search_service): Extension<Arc<UnifiedSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<UnifiedSearchRequest>,
|
||||
) -> Result<Json<UnifiedSearchResponse>, APIError> {
|
||||
let context = SearchContext {
|
||||
user_id: Some(auth.user_id),
|
||||
..request.context.unwrap_or_default()
|
||||
};
|
||||
|
||||
let response = search_service.search(&request.query, Some(context)).await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
// POST /api/v1/search/conversation
|
||||
pub async fn conversational_search(
|
||||
Extension(search_service): Extension<Arc<UnifiedSearchService>>,
|
||||
Extension(auth): Extension<UserAuth>,
|
||||
Json(request): Json<ConversationalSearchRequest>,
|
||||
) -> Result<Json<UnifiedSearchResponse>, APIError> {
|
||||
let response = search_service
|
||||
.conversational_search(&request.conversation_id, &request.query)
|
||||
.await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 实施计划
|
||||
|
||||
### Phase 1: 核心实现(3 天)
|
||||
|
||||
- [ ] 实现 UnifiedSearchService
|
||||
- [ ] 实现 QueryAnalyzer
|
||||
- [ ] 实现 5 种搜索 Worker
|
||||
- [ ] 单元测试
|
||||
|
||||
### Phase 2: 集成(2 天)
|
||||
|
||||
- [ ] 集成到 Studio UI
|
||||
- [ ] 实现 API 端点
|
||||
- [ ] 集成 Billing 和 Log
|
||||
|
||||
### Phase 3: 优化(2 天)
|
||||
|
||||
- [ ] 性能优化
|
||||
- [ ] 智能路由优化
|
||||
- [ ] 用户体验改进
|
||||
|
||||
---
|
||||
|
||||
**统一交谈介面设计完成!用户无需选择搜索类型,系统智能选择最佳方式。**
|
||||
Reference in New Issue
Block a user