feat: backup architecture docs, source code, and scripts

This commit is contained in:
Warren
2026-04-25 17:15:45 +08:00
parent 59809dae1f
commit 1f84e5469f
368 changed files with 146329 additions and 261 deletions

View File

@@ -0,0 +1,364 @@
---
document_type: "architecture_design"
service: "MOMENTRY_CORE"
title: "處理器生命週期管理"
date: "2026-04-22"
version: "V1.0"
status: "active"
owner: "Warren"
created_by: "OpenCode"
tags:
- "處理器生命週期管理"
ai_query_hints:
- "查詢 處理器生命週期管理 的內容"
- "處理器生命週期管理 的主要目的是什麼?"
- "如何操作或實施 處理器生命週期管理?"
---
# 處理器生命週期管理
| 項目 | 內容 |
|------|------|
| 建立者 | OpenCode |
| 建立時間 | 2026-04-22 |
| 文件版本 | V1.0 |
---
## 版本歷史
| 版本 | 日期 | 目的 | 操作人 |
|------|------|------|--------|
| V1.0 | 2026-04-22 | 創建處理器生命週期管理文檔 | OpenCode |
---
## 1. 處理器生命週期概覽
處理器Processor是 Momentry Core 中執行視頻分析任務的核心組件。完整的生命週期包括以下階段:
```
開發階段 → 測試階段 → 部署階段 → 運行階段 → 維護階段 → 退役階段
```
---
## 2. 開發階段 (Development)
### 2.1 新處理器創建流程
#### 步驟 1: 需求分析
1. **功能定義**:明確處理器要實現的功能
2. **輸入輸出規範**:定義輸入參數和輸出格式
3. **依賴分析**:識別所需的 AI 模型、庫和工具
#### 步驟 2: 技術選型
1. **執行類型**:選擇 Python、Shell、CLI App 等
2. **模型選擇**:選擇合適的 AI 模型
3. **性能評估**:評估計算資源需求
#### 步驟 3: 代碼開發
1. **腳本編寫**:編寫處理器核心邏輯
2. **錯誤處理**:實現健壯的錯誤處理機制
3. **日誌記錄**:添加詳細的日誌記錄
### 2.2 開發標準
#### Python 處理器標準:
```python
# 1. 必要的導入
import json
import sys
import argparse
from pathlib import Path
# 2. 參數解析
parser = argparse.ArgumentParser()
parser.add_argument("--uuid", required=True, help="Video UUID")
parser.add_argument("--output", required=True, help="Output path")
args = parser.parse_args()
# 3. 主處理邏輯
def process_video(video_uuid, output_path):
# 處理邏輯
result = {
"status": "success",
"metadata": {...},
"chunks": [...]
}
# 4. 結果保存
with open(output_path, "w") as f:
json.dump(result, f, indent=2)
# 5. 主函數
if __name__ == "__main__":
try:
process_video(args.uuid, args.output)
sys.exit(0)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
```
---
## 3. 測試階段 (Testing)
### 3.1 測試類型
#### 單元測試:
- 測試處理器核心邏輯
- 驗證輸入輸出格式
- 測試錯誤處理
#### 集成測試:
- 測試與其他組件的集成
- 驗證數據流完整
- 測試性能表現
#### 回歸測試:
- 確保新版本不破壞現有功能
- 測試兼容性
- 驗證性能改進
### 3.2 測試數據
#### 測試視頻:
| 類型 | 用途 | 示例 |
|------|------|------|
| 短視頻(<1分鐘 | 快速測試 | test_video.mp4 |
| 中等視頻1-5分鐘 | 功能測試 | demo_video.mp4 |
| 長視頻(>10分鐘 | 性能測試 | long_video.mp4 |
#### 測試環境:
1. **本地開發環境**:快速迭代
2. **測試服務器**:集成測試
3. **生產模擬環境**:性能測試
---
## 4. 部署階段 (Deployment)
### 4.1 部署流程
#### 步驟 1: 版本管理
1. **版本號**遵循語義化版本規範SemVer
2. **構建時間**:記錄構建/部署時間戳
3. **變更日誌**:記錄版本變更內容
#### 步驟 2: 配置管理
1. **環境變量**:配置處理器運行環境
2. **模型文件**:管理 AI 模型文件
3. **依賴庫**:管理 Python 依賴
#### 步驟 3: 數據庫註冊
```sql
-- 註冊新處理器到數據庫
INSERT INTO processors (
id, name, category, execution_type,
entry_point, version, build_time,
description, technical_details,
output_spec, runtime_config, is_active
) VALUES (
'uuid', 'face_processor', 'visual', 'python',
'scripts/face_processor.py', '1.2.0', NOW(),
'人臉識別處理器,使用 InsightFace 模型',
'基於 InsightFace 的深度學習人臉識別',
'{"type": "object", "properties": {...}}'::jsonb,
'{"venv_path": "...", "timeout_secs": 3600}'::jsonb,
TRUE
);
```
### 4.2 部署檢查清單
- [ ] 處理器腳本已測試通過
- [ ] 依賴庫已正確安裝
- [ ] 模型文件已下載並配置
- [ ] 環境變量已設置
- [ ] 數據庫註冊已完成
- [ ] 權限設置正確
- [ ] 日誌配置完整
---
## 5. 運行階段 (Runtime)
### 5.1 調度與執行
#### 任務調度流程:
```
1. 任務創建 → 2. 處理器選擇 → 3. 資源分配
→ 4. 執行監控 → 5. 結果收集 → 6. 狀態更新
```
#### 執行監控:
1. **進程監控**:監控處理器進程狀態
2. **資源監控**:監控 CPU、內存、GPU 使用
3. **性能監控**:監控處理速度和進度
### 5.2 錯誤處理與恢復
#### 錯誤類型:
1. **可恢復錯誤**:臨時性問題,可重試
2. **配置錯誤**:配置問題,需要修復
3. **系統錯誤**:系統級問題,需要干預
#### 重試策略:
```rust
// Rust 中的重試機制示例
let result = run_with_retry(
|| python_executor.execute(&script, &args),
RetryConfig {
max_attempts: 3,
initial_delay: Duration::from_secs(2),
max_delay: Duration::from_secs(30),
backoff_multiplier: 2.0,
},
).await;
```
### 5.3 性能優化
#### 優化策略:
1. **並行處理**:同時處理多個視頻
2. **批處理**:批量處理相關任務
3. **緩存優化**:重用計算結果
4. **資源調度**:智能分配計算資源
---
## 6. 維護階段 (Maintenance)
### 6.1 日常維護
#### 監控項目:
1. **處理器狀態**:運行狀態、健康狀態
2. **性能指標**:處理速度、成功率
3. **資源使用**CPU、內存、存儲
4. **錯誤率**:各種錯誤的發生頻率
#### 維護任務:
1. **日誌分析**:定期分析處理器日誌
2. **性能調優**:根據監控數據進行調優
3. **安全更新**:更新依賴庫修復安全漏洞
4. **數據清理**:清理臨時文件和緩存
### 6.2 版本升級
#### 升級流程:
1. **兼容性檢查**:檢查新版本與現有系統的兼容性
2. **回滾計劃**:制定升級失敗時的回滾計劃
3. **分階段部署**:分階段逐步升級
4. **驗證測試**:升級後進行全面測試
#### 版本兼容性矩陣:
| 處理器版本 | 系統版本 | 模型版本 | 狀態 |
|------------|----------|----------|------|
| v1.0.x | v0.1.0 | insightface==0.7.3 | ✅ 兼容 |
| v1.1.x | v0.2.0 | insightface==0.7.5 | ⚠️ 需要測試 |
| v2.0.x | v0.3.0 | insightface==0.8.0 | ❌ 不兼容 |
---
## 7. 退役階段 (Retirement)
### 7.1 退役原因
1. **技術過時**:技術棧過時,需要替換
2. **功能重疊**:與其他處理器功能重疊
3. **性能問題**:性能無法滿足需求
4. **維護成本**:維護成本過高
### 7.2 退役流程
#### 步驟 1: 退役計劃
1. **替代方案**:確定替代處理器
2. **數據遷移**:計劃數據遷移方案
3. **時間安排**:安排退役時間表
#### 步驟 2: 數據遷移
1. **歷史數據**:遷移歷史處理結果
2. **配置數據**:遷移配置信息
3. **依賴關係**:處理依賴關係
#### 步驟 3: 正式退役
1. **停止服務**:停止處理器服務
2. **數據清理**:清理相關數據
3. **文檔更新**:更新系統文檔
### 7.3 退役檢查清單
- [ ] 替代處理器已部署並測試
- [ ] 數據遷移已完成
- [ ] 依賴關係已處理
- [ ] 系統配置已更新
- [ ] 用戶通知已發送
- [ ] 退役文檔已更新
---
## 8. 相關處理器示例
### 8.1 已部署處理器
| 處理器 | 類型 | 狀態 | 版本 |
|--------|------|------|------|
| asr_processor | Python | ✅ 生產 | v1.3.2 |
| face_processor | Python | ✅ 生產 | v1.1.5 |
| yolo_processor | Python | ⚠️ 測試 | v0.9.1 |
| scene_processor | Python | ⚠️ 開發 | v0.5.0 |
### 8.2 處理器開發計劃
| 處理器 | 優先級 | 預計完成時間 | 狀態 |
|--------|--------|--------------|------|
| ocr_processor | P1 | 2026-05-31 | 🚧 開發中 |
| lip_processor | P2 | 2026-06-30 | 📅 計劃中 |
| audio_classifier | P3 | 2026-07-31 | 💡 設計中 |
---
## 9. 最佳實踐
### 9.1 開發最佳實踐
1. **模塊化設計**:保持處理器模塊化和可重用
2. **配置驅動**:使用配置文件而非硬編碼
3. **完善的日誌**:記錄詳細的處理日誌
4. **錯誤處理**:實現健壯的錯誤處理機制
### 9.2 部署最佳實踐
1. **版本控制**:嚴格管理處理器版本
2. **環境隔離**:使用虛擬環境隔離依賴
3. **配置管理**:使用配置管理工具
4. **監控預警**:設置監控和預警機制
### 9.3 運維最佳實踐
1. **定期備份**:定期備份處理器配置和數據
2. **性能監控**:持續監控處理器性能
3. **安全更新**:及時更新安全補丁
4. **文檔維護**:保持文檔與實際情況一致
---
## 10. 相關文件
| 文件 | 描述 | 相關性 |
|------|------|--------|
| [PROCESSOR_REGISTRY_ARCHITECTURE.md](./PROCESSOR_REGISTRY_ARCHITECTURE.md) | 處理器資源管理架構 | 核心架構 |
| [SERVICE_REGISTRY_ARCHITECTURE.md](./SERVICE_REGISTRY_ARCHITECTURE.md) | 服務資源管理架構 | 依賴管理 |
| [ARCHITECTURE_ROADMAP.md](./ARCHITECTURE_ROADMAP.md) | 架構發展路線圖 | 發展規劃 |
---
## 11. 最後更新記錄
| 版本 | 日期 | 主要變更 | 操作人 |
|------|------|----------|--------|
| V1.0 | 2026-04-22 | 創建處理器生命週期管理文檔 | OpenCode |
**最後更新日期**: 2026-04-22

View File

@@ -0,0 +1,330 @@
---
document_type: "architecture_design"
service: "MOMENTRY_CORE"
title: "Momentry Core 處理器資源管理架構 (v1.0)"
date: "2026-04-21"
version: "V1.0"
status: "active"
owner: "Warren"
created_by: "OpenCode"
tags:
- "momentry"
- "core"
- "處理器資源管理架構"
ai_query_hints:
- "查詢 Momentry Core 處理器資源管理架構 (v1.0) 的內容"
- "Momentry Core 處理器資源管理架構 (v1.0) 的主要目的是什麼?"
- "如何操作或實施 Momentry Core 處理器資源管理架構 (v1.0)"
---
# Momentry Core 處理器資源管理架構 (v1.0)
| 項目 | 內容 |
|------|------|
| 建立者 | OpenCode |
| 建立時間 | 2026-04-21 |
| 文件版本 | V1.0 |
---
## 版本歷史
| 版本 | 日期 | 目的 | 操作人 | 工具/模型 |
|------|------|------|--------|-----------|
| V1.0 | 2026-04-21 | 創建處理器資源管理架構文件 | OpenCode | OpenCode / Qwen3.6-Plus |
---
## 0. 設計目標
將所有影片處理腳本與程式Processors視為**標準化可執行資源**,實現:
1. **插件化架構**: 支援 Python, Shell, CLI App 及未來 Docker/HTTP 擴展。
2. **版本追溯**: 精確記錄處理器版本號與構建時間 (Build Time)。
3. **產出標準化**: 定義 JSON 輸出規範,確保上下游系統相容。
4. **動態調度**: 排程器根據處理器類型與狀態分配任務。
---
## 1. 核心架構
### 1.1 處理器分類 (Execution Types)
| 類型 | 說明 | 範例 | 執行指令範例 |
|------|------|------|--------------|
| `python` | 依賴 Python 環境的腳本 | ASR (WhisperX), Face (InsightFace), OCR | `python3 script.py --uuid ...` |
| `shell` | Bash 腳本,用於系統工具串接 | Smart Thumbnail (ffmpeg) | `bash script.sh --uuid ...` |
| `cli_app` | 編譯後的二進位程式 | 高效能向量計算器 | `./bin/processor --uuid ...` |
| `docker` | 容器化執行 (未來擴展) | 隔離環境的 AI 推論 | `docker run --rm image ...` |
| `http` | 遠端 API 呼叫 (未來擴展) | 外部雲端服務 | `POST /api/process` |
### 1.2 處理器與服務的關係
```
處理器 (Processors)
├── 依賴 ──> [服務資源] (Services: Ollama, Qdrant, GPU)
├── 讀取 ──> [資產] (Assets: Video Files)
└── 產出 ──> [文件] (JSON Results in Storage)
```
---
## 2. 資料庫設計
### 2.1 `processors` 表結構
```sql
CREATE TABLE processors (
id UUID PRIMARY KEY, -- 處理器唯一標識符
name VARCHAR(100) NOT NULL, -- 顯示名稱
category VARCHAR(50) NOT NULL, -- 分類: preprocessing, audio, visual, text
execution_type VARCHAR(50) NOT NULL, -- 執行型態: python, shell, cli_app, docker, http
entry_point VARCHAR(255) NOT NULL, -- 腳本路徑或二進位檔名
version VARCHAR(20) DEFAULT '1.0.0', -- 語義化版本號
build_time TIMESTAMPTZ DEFAULT NOW(), -- 構建/部署時間
description TEXT, -- 功能說明
technical_details TEXT, -- 技術手段描述
output_spec JSONB, -- 產出規範 (JSON Schema)
runtime_config JSONB, -- 執行環境配置 (如 venv, timeout, gpu)
is_active BOOLEAN DEFAULT TRUE, -- 是否啟用
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_processors_category ON processors(category);
CREATE INDEX idx_processors_type ON processors(execution_type);
```
---
## 3. 欄位詳細說明
### 3.1 執行環境配置 (runtime_config)
根據 `execution_type` 不同,此欄位內容也會不同。
**Python**:
```json
{
"venv_path": "/Users/accusys/momentry_core_0.1/venv",
"timeout_secs": 7200,
"requirements": ["torch", "insightface", "easyocr"]
}
```
**Shell**:
```json
{
"timeout_secs": 300,
"dependencies": ["ffmpeg", "ffprobe"]
}
```
**Docker**:
```json
{
"image": "registry.gitlab.com/momentry/ocr:v1.2",
"gpu": true,
"shm_size": "4g"
}
```
### 3.2 產出規範 (output_spec)
定義處理器執行成功後應生成的 JSON 結構。
**ASR (WhisperX)**:
```json
{
"format": "json",
"structure": {
"segments": [
{
"start": "float",
"end": "float",
"text": "string",
"speaker": "string (optional)"
}
]
},
"naming_convention": "{uuid}_asr_{timestamp}.json"
}
```
**Smart Thumbnail**:
```json
{
"format": "image/jpeg",
"resolution": "320x(width/height ratio)",
"storage_path": "thumbnails/{uuid}.jpg",
"metadata_key": "thumbnail_generated_at"
}
```
---
## 4. 完整註冊範例
### 4.1 Smart Thumbnail (Shell)
```sql
INSERT INTO processors (
id, name, category, execution_type, entry_point,
description, technical_details, output_spec, runtime_config
) VALUES (
'550e8400-e29b-41d4-a716-446655440001',
'Smart Thumbnail Extractor',
'preprocessing',
'shell',
'scripts/smart_thumbnail.sh',
'Detects black screens to find the first valid frame of the main content.',
'Uses FFmpeg `blackdetect` filter to scan first 60s; applies 0.5s offset to avoid transitions.',
'{
"format": "image/jpeg",
"naming_convention": "{uuid}.jpg"
}'::jsonb,
'{
"timeout_secs": 300,
"dependencies": ["ffmpeg"]
}'::jsonb
);
```
### 4.2 ASR WhisperX (Python)
```sql
INSERT INTO processors (
id, name, category, execution_type, entry_point,
version, build_time, description, technical_details, output_spec, runtime_config
) VALUES (
'550e8400-e29b-41d4-a716-446655440002',
'WhisperX Speech Recognition',
'audio',
'python',
'scripts/asr_processor.py',
'2.1.0',
'2026-04-20 10:00:00+08', -- 真實構建時間
'High-accuracy speech-to-text with word-level timestamps and speaker diarization.',
'WhisperX (faster-whisper) + pyannote-audio for speaker diarization.',
'{
"format": "json",
"structure": {
"segments": [{"start": "f64", "end": "f64", "text": "str", "speaker": "str"}]
},
"naming_convention": "{uuid}_asr_{timestamp}.json"
}'::jsonb,
'{
"venv_path": "/Users/accusys/momentry_core_0.1/venv",
"timeout_secs": 7200,
"gpu": true
}'::jsonb
);
```
### 4.3 OCR (Python)
```sql
INSERT INTO processors (
id, name, category, execution_type, entry_point,
description, technical_details, output_spec, runtime_config
) VALUES (
'550e8400-e29b-41d4-a716-446655440003',
'EasyOCR Text Recognition',
'visual',
'python',
'scripts/ocr_processor.py',
'Extracts text blocks with coordinates from video frames.',
'Uses EasyOCR (local model) with English language support.',
'{
"format": "json",
"structure": {
"frames": [
{
"frame": "int",
"timestamp": "float",
"texts": [{"text": "str", "bbox": "object", "confidence": "float"}]
}
]
},
"naming_convention": "{uuid}_ocr_{timestamp}.json"
}'::jsonb,
'{
"venv_path": "/Users/accusys/momentry_core_0.1/venv",
"timeout_secs": 3600,
"sample_interval_frames": 30
}'::jsonb
);
```
---
## 5. 標準化執行介面 (Execution Interface)
為了讓排程器 (Scheduler) 能統一呼叫所有類型的處理器,所有處理器必須遵循以下參數規範:
| 參數 | 說明 | 範例值 |
|:---|:---|:---|
| `--uuid` | 影片/任務唯一標識符 | `--uuid 384b0ff4...` |
| `--input` | 輸入媒體檔案路徑 | `--input /data/raw/video.mp4` |
| `--output` | 產出 JSON/檔案目錄 | `--output /data/output/384b...` |
| `--config` | (選用) 額外 JSON 配置路徑 | `--config settings.json` |
**Rust 執行分發邏輯 (Dispatcher)**:
```rust
match processor.execution_type.as_str() {
"python" => {
Command::new(venv_python)
.arg(&entry_point)
.args(common_args)
.spawn()?
}
"shell" => {
Command::new("bash")
.arg(&entry_point)
.args(common_args)
.spawn()?
}
"cli_app" => {
Command::new(&entry_point)
.args(common_args)
.spawn()?
}
_ => bail!("Unsupported execution type")
}
```
---
## 6. 處理器與服務整合 (Integration)
處理器在執行時,需要查詢「服務註冊中心」來獲取依賴資源的配置。
**流程範例**:
1. 排程器啟動 `asr_processor.py`
2. Python 腳本查詢本地配置檔 (由排程器生成,內容來自 `services` 表)。
3. 腳本獲取 Ollama 的 `endpoint``model_name`
4. 腳本執行 Embedding 任務。
這樣實現了**處理器與基礎設施配置的解耦**。
---
## 7. 總結
本設計確立了 Momentry 處理器管理的標準:
| 管理維度 | 實作方式 |
|----------|----------|
| **唯一標識** | UUID (`id` 欄位) |
| **多態執行** | `execution_type` (Python/Shell/CLI/Docker...) |
| **版本控制** | `version` + `build_time` |
| **品質保證** | `output_spec` (JSON Schema 驗證) |
| **環境隔離** | `runtime_config` (Venv, Docker Image) |
| **依賴管理** | 啟動時注入 `services` 配置 |
此架構支持未來無限擴展,新的 AI 模型或工具只需編寫腳本並註冊即可納入系統管轄。

View File

@@ -0,0 +1,120 @@
# Resource Monitoring Specification (資源監控規範)
| 項目 | 內容 |
|------|------|
| 建立者 | OpenCode |
| 建立時間 | 2026-04-25 |
| 文件版本 | V1.0 |
---
## 版本歷史
| 版本 | 日期 | 目的 | 操作人 | 工具/模型 |
|------|------|------|--------|-----------|
| V1.0 | 2026-04-25 | 定義 Processor/Agent 的註冊與心跳協定 (僅限監控) | OpenCode | OpenCode |
---
## 1. 核心概念
本階段資源註冊機制 (Resource Registry) **僅用於監控 (Monitoring)**,不介入動態任務調度。
所有 Processor (YOLO, ASR...) 和 Agent (Translation, Summary...) 啟動時應主動註冊。
### 1.1 註冊時機
* **Processor**: 在 Python 腳本啟動時,呼叫 HTTP Endpoint 註冊。
* **Agent**: 在服務啟動時呼叫 HTTP Endpoint 註冊。
---
## 2. 註冊協定 (Registration Protocol)
### 2.1 API Endpoint
`POST /api/v1/resources/register`
### 2.2 Request Payload
```json
{
"resource_id": "unique_id",
"resource_type": "processor | agent",
"name": "Yolo Object Detector",
"capabilities": ["detect_object", "detect_face"],
"config": {
"model_version": "v8n",
"gpu_enabled": true
}
}
```
* **resource_id**: 建議格式 `{type}_{name}_{uuid}`,例如 `processor_yolo_a1b2c3`
### 2.3 Response
```json
{
"success": true,
"message": "Resource registered"
}
```
---
## 3. 心跳協定 (Heartbeat Protocol)
資源應定期發送心跳,回報當前狀態與進度。
### 3.1 API Endpoint
`POST /api/v1/resources/{resource_id}/heartbeat`
### 3.2 Request Payload
```json
{
"status": "idle | busy | error",
"job_uuid": "current_video_uuid",
"progress": 0.45,
"last_frame_index": 12500
}
```
* **progress**: 0.0 到 1.0 之間的浮點數。
* **job_uuid**: 當前正在處理的任務 ID。
---
## 4. 監控用途
系統後台 (Portal Dashboard) 可透過查詢 Registry 實現:
1. **即時儀表板**: 顯示目前有幾個 Processor 在運行 (`busy` 數量)。
2. **進度條**: 透過 `last_frame_index` 與影片總幀數計算百分比。
3. **健康檢查**: 若資源超過 60 秒未發送心跳,標記為 `offline`
---
## 5. Rust Worker 整合建議
`src/worker/processor.rs``run_processor` 函數中:
```rust
// 1. 生成唯一的 Resource ID
let resource_id = format!("processor_{}_{}", processor_type, job.uuid);
// 2. 註冊資源
register_resource(&resource_id, processor_type).await;
// 3. 執行腳本 (腳本內部應定期發送心跳,或由 Rust Wrapper 發送)
run_python_script(...);
// 4. 登出資源 (可選,或由 TTL 自動清理)
deregister_resource(&resource_id).await;
```
---
## 版本資訊
- 版本: V1.0
- 建立日期: 2026-04-25

View File

@@ -0,0 +1,500 @@
---
document_type: "architecture_design"
service: "MOMENTRY_CORE"
title: "Momentry Core 全域服務資源管理架構 (v1.0)"
date: "2026-04-21"
version: "V1.0"
status: "active"
owner: "Warren"
created_by: "OpenCode"
tags:
- "momentry"
- "core"
- "全域服務資源管理架構"
ai_query_hints:
- "查詢 Momentry Core 全域服務資源管理架構 (v1.0) 的內容"
- "Momentry Core 全域服務資源管理架構 (v1.0) 的主要目的是什麼?"
- "如何操作或實施 Momentry Core 全域服務資源管理架構 (v1.0)"
---
# Momentry Core 全域服務資源管理架構 (v1.0)
| 項目 | 內容 |
|------|------|
| 建立者 | OpenCode |
| 建立時間 | 2026-04-21 |
| 文件版本 | V1.0 |
---
## 版本歷史
| 版本 | 日期 | 目的 | 操作人 | 工具/模型 |
|------|------|------|--------|-----------|
| V1.0 | 2026-04-21 | 創建全域服務資源管理架構文件 | OpenCode | OpenCode / Qwen3.6-Plus |
---
## 0. 設計目標
將所有基礎設施服務Infrastructure Services視為**可管理資源**,實現:
1. **動態發現**: 處理器不再寫死服務 IP而是從註冊中心查詢可用服務
2. **健康監控**: 自動探活服務狀態,故障時標記並尋找備用節點
3. **版本追溯**: 精確記錄模型檔案、配置、依賴關係,確保可重現性
4. **運維自動化**: 統一管理備份、日誌、儲存路徑,降低人工維護成本
---
## 1. 核心架構
### 1.1 服務分類 (Service Types)
| 類型 | 說明 | 範例 |
|------|------|------|
| `embedding_engine` | 語意向量生成 | Ollama (nomic-embed-text-v2-moe) |
| `llm_engine` | 文字生成/推理 | llama.cpp (gemma-4) |
| `vector_db` | 向量儲存與搜尋 | Qdrant |
| `cache` | 快取與隊列 | Redis |
| `database` | 關聯式資料庫 | PostgreSQL |
| `storage` | 檔案管理 | SFTPGo |
| `api_server` | API 閘道 | Momentry Core Server |
### 1.2 服務資源關聯圖
```
使用者/API
├──> [Momentry Core API Server] (api_server)
│ │
│ ├──> [Qdrant] (vector_db) ─── 向量搜尋
│ │
│ ├──> [Ollama] (embedding_engine) ─── 768-dim Embedding
│ │
│ ├──> [llama.cpp] (llm_engine) ─── Gemma4 推理
│ │
│ ├──> [PostgreSQL] (database) ─── 關聯資料
│ │
│ └──> [Redis] (cache) ─── 快取與隊列
└──> [SFTPGo] (storage) ─── 檔案上傳/管理
```
---
## 2. 資料庫設計
### 2.1 `services` 表結構
```sql
CREATE TABLE services (
id UUID PRIMARY KEY,
name VARCHAR(100) NOT NULL, -- 服務名稱 (e.g., ollama-embedding-nomic-v2-moe)
type VARCHAR(50) NOT NULL, -- 服務類型 (見 1.1)
endpoint VARCHAR(255), -- 基礎連接點 (e.g., http://127.0.0.1:11434)
status VARCHAR(20) DEFAULT 'unknown', -- online, offline, degraded, unknown
metadata JSONB, -- 技術細節 (模型版本、維度等)
-- 1. 網路與端口
port_config JSONB, -- 主端口、範圍、協議
-- 2. 存取控制
access_policy JSONB, -- 認證方式、允許的使用者
-- 3. 依賴關係
dependency_graph JSONB, -- 上游/下游依賴
-- 4. 業務上下文
business_purpose TEXT, -- 用途說明
reference_docs JSONB, -- 文檔連結
-- 5. 儲存與日誌
storage_paths JSONB, -- 配置、數據、log、error_log
-- 6. 備份策略
backup_policy JSONB, -- 備份週期、方法、目標
-- 7. 健康檢查
health_check_path VARCHAR(255), -- 探活路徑 (e.g., /health)
health_check_method VARCHAR(10), -- HTTP 方法 (GET/POST)
health_check_match TEXT, -- 預期回應 (Status 200 or JSON content)
check_interval_secs INT DEFAULT 60, -- 檢查頻率 (秒)
last_check_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
```
---
## 3. 欄位詳細說明
### 3.1 技術細節 (metadata)
根據服務類型記錄不同的技術參數。
**Ollama (Embedding Engine)**:
```json
{
"provider": "ollama",
"model_name": "nomic-embed-text-v2-moe",
"model_tag": "latest",
"gguf_file": "nomic-embed-text-v2-moe-Q4_0.gguf",
"gguf_sha256": "sha256:xxxxx...",
"source_url": "https://huggingface.co/nomic-ai/nomic-embed-text-v2-moe-GGUF",
"dimensions": 768,
"capabilities": ["embedding", "text-similarity", "multilingual"],
"context_length": 2048,
"architecture": "Mixture of Experts (MoE)"
}
```
**llama.cpp (LLM Engine)**:
```json
{
"provider": "llama.cpp",
"model_name": "gemma-4-12b-it",
"model_file": "gemma-4-12b-it-Q4_K_M.gguf",
"source": "https://huggingface.co/bartowski/gemma-4-12b-it-GGUF",
"sha256": "sha256:yyyyy...",
"capabilities": ["text-generation", "chat"],
"parameters": "12B",
"quantization": "Q4_K_M",
"gpu_layers": -1
}
```
### 3.2 網路與端口 (port_config)
```json
{
"main_port": 11434,
"range": "11434-11435",
"protocol": "HTTP",
"bind_address": "127.0.0.1"
}
```
### 3.3 存取控制 (access_policy)
```json
{
"auth_type": "none",
"allowed_users": ["momentry_core", "vectorize_worker"],
"api_key_env": null,
"rate_limit": "unlimited",
"cors_origin": "localhost"
}
```
### 3.4 依賴關係 (dependency_graph)
```json
{
"upstream": ["gpu_driver", "cuda_toolkit"],
"downstream": ["qdrant_ingestion", "search_api", "smart_synonym_expander"],
"criticality": "high"
}
```
### 3.5 儲存與日誌 (storage_paths)
```json
{
"data_dir": "/Users/accusys/.ollama/models",
"config_dir": "/Users/accusys/.ollama/modelfiles",
"log_file": "/Users/accusys/Library/Logs/ollama/ollama.log",
"error_log_file": "/Users/accusys/Library/Logs/ollama/ollama.error.log",
"env_file": "/Users/accusys/.ollama/.env"
}
```
### 3.6 備份策略 (backup_policy)
```json
{
"enabled": true,
"method": "rsync",
"schedule": "daily",
"destination": "/Volumes/BackupDrive/momentry_services/ollama",
"retention_days": 30,
"pre_hook": "launchctl stop com.ollama.service",
"post_hook": "launchctl start com.ollama.service",
"exclude_patterns": ["*.tmp", "logs/*"]
}
```
### 3.7 健康檢查 (health_check)
| 欄位 | 說明 | 範例 |
|------|------|------|
| `health_check_path` | 探活路徑 | `/health``/` |
| `health_check_method` | HTTP 方法 | `GET` |
| `health_check_match` | 預期回應內容 | `Ollama is running` |
| `check_interval_secs` | 檢查頻率 | `60` |
---
## 4. 完整註冊範例
### 4.1 Ollama Embedding Engine
```sql
INSERT INTO services (
id, name, type, endpoint, status, metadata,
port_config, access_policy, dependency_graph,
business_purpose, reference_docs,
storage_paths, backup_policy,
health_check_path, health_check_method, health_check_match, check_interval_secs
) VALUES (
'550e8400-e29b-41d4-a716-446655440100',
'ollama-embedding-nomic-v2-moe',
'embedding_engine',
'http://127.0.0.1:11434',
'online',
'{"provider": "ollama", "model_name": "nomic-embed-text-v2-moe", "model_tag": "latest", "dimensions": 768}'::jsonb,
'{"main_port": 11434, "protocol": "HTTP"}'::jsonb,
'{"auth_type": "none", "allowed_users": ["momentry_core", "vectorize_worker"]}'::jsonb,
'{"upstream": ["gpu_driver"], "downstream": ["qdrant_ingestion", "search_api"], "criticality": "high"}'::jsonb,
'Generate 768-dim multilingual embeddings for chunks and semantic search.',
'{"model_url": "https://ollama.com/library/nomic-embed-text-v2-moe", "wiki": "docs/PROCESSING_PIPELINE.md"}'::jsonb,
'{
"data_dir": "/Users/accusys/.ollama/models",
"config_dir": "/Users/accusys/.ollama/modelfiles",
"log_file": "/Users/accusys/Library/Logs/ollama/ollama.log",
"error_log_file": "/Users/accusys/Library/Logs/ollama/ollama.error.log"
}'::jsonb,
'{
"enabled": true,
"method": "rsync",
"destination": "/Volumes/BackupDrive/ollama_models",
"retention_days": 30
}'::jsonb,
'/', 'GET', 'Ollama is running', 60
);
```
### 4.2 llama.cpp LLM Engine
```sql
INSERT INTO services (
id, name, type, endpoint, status, metadata,
port_config, access_policy, dependency_graph,
business_purpose, reference_docs,
storage_paths, backup_policy,
health_check_path, health_check_method, health_check_match, check_interval_secs
) VALUES (
'550e8400-e29b-41d4-a716-446655440099',
'llama-server-gemma4',
'llm_engine',
'http://127.0.0.1:8081',
'online',
'{"provider": "llama.cpp", "model_name": "gemma-4-12b-it", "model_file": "gemma-4-12b-it-Q4_K_M.gguf", "capabilities": ["text-generation", "chat"], "parameters": "12B"}'::jsonb,
'{"main_port": 8081, "protocol": "HTTP"}'::jsonb,
'{"auth_type": "none", "allowed_users": ["momentry_core"]}'::jsonb,
'{"upstream": ["gpu_driver"], "downstream": ["smart_synonym_expander", "query_parser"], "criticality": "medium"}'::jsonb,
'Provide text generation and instruction following for synonym expansion and query analysis.',
'{"model_url": "https://huggingface.co/bartowski/gemma-4-12b-it-GGUF"}'::jsonb,
'{
"data_dir": "/Users/accusys/momentry/models",
"config_dir": "/Users/accusys/momentry/config",
"log_file": "/Users/accusys/momentry/logs/llama_server.log",
"error_log_file": "/Users/accusys/momentry/logs/llama_server.error.log"
}'::jsonb,
'{
"enabled": true,
"method": "rsync",
"destination": "/Volumes/BackupDrive/llama_models",
"retention_days": 30
}'::jsonb,
'/health', 'GET', 'OK', 30
);
```
### 4.3 Qdrant Vector DB
```sql
INSERT INTO services (
id, name, type, endpoint, status, metadata,
port_config, access_policy, dependency_graph,
business_purpose, reference_docs,
storage_paths, backup_policy,
health_check_path, health_check_method, health_check_match, check_interval_secs
) VALUES (
'550e8400-e29b-41d4-a716-446655440003',
'qdrant-vector-store',
'vector_db',
'http://127.0.0.1:6333',
'online',
'{"version": "1.7.0", "collections": ["momentry_rule1", "momentry_rule2", "momentry_rule3"], "vector_dim": 768, "distance": "Cosine"}'::jsonb,
'{"main_port": 6333, "grpc_port": 6334, "protocol": "HTTP/REST+gRPC"}'::jsonb,
'{"auth_type": "api_key", "api_key_env": "QDRANT_API_KEY", "allowed_users": ["momentry_core", "vectorize_worker"]}'::jsonb,
'{"upstream": ["ollama-embedding-nomic-v2-moe"], "downstream": ["search_api"], "criticality": "critical"}'::jsonb,
'Store and search 768-dim embeddings for all chunk rules.',
'{"docs": "https://qdrant.tech/documentation"}'::jsonb,
'{
"data_dir": "/opt/qdrant/storage",
"config_dir": "/opt/qdrant/config",
"log_file": "/var/log/qdrant/qdrant.log",
"error_log_file": "/var/log/qdrant/qdrant.error.log"
}'::jsonb,
'{
"enabled": true,
"method": "snapshot",
"schedule": "daily",
"destination": "/Volumes/BackupDrive/qdrant_snapshots",
"retention_days": 14
}'::jsonb,
'/healthz', 'GET', '', 30
);
```
---
## 5. 健康監控機制 (Health Monitor)
### 5.1 監控流程
```
1. Worker 掃描 services 表 (status != 'disabled')
2. 對每個服務發送 health_check
- URL: endpoint + health_check_path
- Method: health_check_method
3. 驗證回應
- HTTP Status: 200 OK?
- Content: 包含 health_check_match?
4. 更新狀態
- success → status = 'online'
- fail → status = 'offline'
- timeout → status = 'degraded'
5. 記錄 last_check_at
```
### 5.2 Rust 實作範例
```rust
pub async fn run_health_checks(pool: &PgPool) -> anyhow::Result<()> {
let services = sqlx::query!(
"SELECT id, endpoint, health_check_path, health_check_method,
health_check_match, check_interval_secs
FROM services WHERE status != 'disabled'"
)
.fetch_all(pool)
.await?;
for svc in services {
let url = format!("{}{}", svc.endpoint, svc.health_check_path);
let new_status = match check_service_health(&url, &svc.health_check_method).await {
Ok(body) => {
if let Some(expected) = &svc.health_check_match {
if body.contains(expected) { "online" } else { "degraded" }
} else { "online" }
}
Err(_) => "offline"
};
sqlx::query!(
"UPDATE services SET status = $1, last_check_at = NOW() WHERE id = $2",
new_status,
svc.id
)
.execute(pool)
.await?;
}
Ok(())
}
```
---
## 6. 依賴影響分析
### 6.1 故障傳播查詢
```sql
-- 查詢受 Ollama 故障影響的所有服務
SELECT name, type, status
FROM services
WHERE dependency_graph->'upstream' @> '["ollama-embedding-nomic-v2-moe"]';
-- 查詢 Qdrant 依賴的所有上游服務
SELECT name, type, status
FROM services
WHERE 'qdrant-vector-store' = ANY(
ARRAY(
SELECT jsonb_array_elements_text(
dependency_graph->'downstream'
)
)
);
```
### 6.2 啟動順序
根據 `dependency_graph``upstream` 字段,系統可自動計算服務啟動順序:
```
1. gpu_driver → cuda_toolkit
2. ollama-embedding-nomic-v2-moe (需要 gpu_driver)
3. llama-server-gemma4 (需要 gpu_driver)
4. qdrant-vector-store
5. redis-cache
6. postgres-main
7. momentry-core-api (依賴以上所有)
```
---
## 7. 備份管理 (Backup Manager)
### 7.1 備份排程查詢
```sql
-- 找出今日需要備份的服務
SELECT name, backup_policy
FROM services
WHERE backup_policy->>'enabled' = 'true'
AND (backup_policy->>'schedule' = 'daily'
OR backup_policy->>'schedule' LIKE '%* * *');
```
### 7.2 備份執行邏輯
```
1. Worker 掃描 backup_policy.enabled = true
2. 執行 pre_hook (如停止服務)
3. 執行備份方法
- rsync: rsync -a --exclude="*.tmp" data_dir destination
- pg_dump: pg_dump dbname > destination/dump.sql
- snapshot: qdrant CLI create-snapshot
4. 壓縮 (gzip)
5. 執行 post_hook (如重啟服務)
6. 清理超過 retention_days 的舊備份
```
---
## 8. 總結
本設計將所有基礎設施服務納管為**可發現、可監控、可備份、可追溯**的資源實體。
| 管理維度 | 實作方式 |
|----------|----------|
| **服務發現** | `services` 表 + `endpoint` 欄位 |
| **版本追溯** | `metadata` (模型檔案 SHA256, 版本號) |
| **健康監控** | `health_check_*` 欄位 + 背景 Worker |
| **依賴管理** | `dependency_graph` (upstream/downstream) |
| **存取控制** | `access_policy` (認證方式、允許使用者) |
| **儲存管理** | `storage_paths` (配置、數據、分離日誌) |
| **備份恢復** | `backup_policy` (排程、方法、保留期、Hooks) |
透過此架構Momentry 可實現從「手動運維」到「自動化服務治理」的升級。

View File

@@ -0,0 +1,162 @@
# 統一資源註冊架構 (Unified Resource Registry Architecture)
| 項目 | 內容 |
|------|------|
| 建立者 | OpenCode |
| 建立時間 | 2026-04-25 |
| 文件版本 | V1.0 |
---
## 版本歷史
| 版本 | 日期 | 目的 | 操作人 | 工具/模型 |
|------|------|------|--------|-----------|
| V1.0 | 2026-04-25 | 定義 Service、Processor、Agent 為統一資源 (Resource) 的註冊與管理架構 | OpenCode | OpenCode |
---
## 1. 核心設計理念
在 Momentry Core 系統中,所有用於處理、分析和管理數據的組件,統一抽象為 **「資源 (Resource)」**。
這種設計允許系統以統一的方式發現、調度、監控和管理不同類型的組件。
### 1.1 資源三大分類 (Resource Types)
| 資源類型 | 英文代號 | 定義 | 特性 | 範例 |
|----------|----------|------|------|------|
| **服務** | **Service** | 系統運行依賴的基礎設施或長駐進程。 | 長生命週期 (Long-lived), 狀態保持。 | PostgreSQL, Redis, TMDB API |
| **處理器** | **Processor** | 執行確定性數據轉換的模組。 | 短生命週期 (Task-based), 輸入 A -> 輸出 B, 無狀態。 | FFmpeg (Probe), YOLO, Whisper |
| **智能體** | **Agent** | 依賴 LLM 進行語義推論或決策的模組。 | 短生命週期 (Task-based), 機率性輸出, 依賴 Prompt/Context。 | 5W1H Inference, Summarization, Identity Resolution |
---
## 2. 通用資源模型 (Universal Resource Model)
所有資源在註冊表中共享以下核心結構:
```json
{
"resource_id": "unique_identifier",
"resource_type": "processor | agent | service",
"category": "visual | speech | metadata | logic",
"capabilities": ["capability_1", "capability_2"],
"status": "idle | busy | offline | error",
"config": {
"model": "yolov8n",
"timeout": 60,
"gpu_required": false
},
"health_check": {
"endpoint": "/health",
"interval_seconds": 30,
"last_success": "2026-04-25T10:00:00Z"
},
"metadata": {
"version": "1.0.0",
"description": "..."
}
}
```
---
## 3. 資源生命週期 (Resource Lifecycle)
1. **註冊 (Registration)**:
* 組件啟動時向 **Resource Registry** 報到,聲明其 ID、類型和能力。
* *範例*: Agent 啟動,註冊 `resource_type: "agent"`, `capabilities: ["summarize_text"]`
2. **發現 (Discovery)**:
* 調度器 (Scheduler) 根據任務需求查詢 Registry 尋找合適的資源。
* *範例*: 任務需要「語音轉文字」,查詢 `capabilities: ["audio_to_text"]`
3. **分配與執行 (Allocation & Execution)**:
* 狀態變為 `busy`,接收任務並執行。
4. **健康檢查 (Health Monitoring)**:
* Registry 定期 Ping 資源。若無回應,標記為 `offline`
5. **登出 (Deregistration)**:
* 組件關閉或崩潰時從 Registry 移除。
---
## 4. 資源註冊表設計 (Registry Schema)
### 4.1 資料庫表結構 (SQL)
```sql
CREATE TABLE resources (
resource_id VARCHAR(64) PRIMARY KEY,
resource_type VARCHAR(20) NOT NULL, -- 'processor', 'agent', 'service'
category VARCHAR(50), -- 'visual', 'speech', 'logic'
name VARCHAR(100) NOT NULL,
description TEXT,
capabilities JSONB, -- Array of strings
config JSONB, -- Resource specific config
metadata JSONB, -- Version, author, etc.
status VARCHAR(20) DEFAULT 'offline',
last_heartbeat TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- 索引優化查詢
CREATE INDEX idx_res_type ON resources(resource_type);
CREATE INDEX idx_res_status ON resources(status);
CREATE INDEX idx_res_caps ON resources USING GIN(capabilities);
```
### 4.2 API 端點設計
| Method | Endpoint | 說明 |
|--------|----------|------|
| `POST` | `/api/v1/resources/register` | 資源啟動時註冊 |
| `POST` | `/api/v1/resources/:id/heartbeat` | 發送心跳 |
| `GET` | `/api/v1/resources` | 查詢所有資源 (支援過濾) |
| `GET` | `/api/v1/resources?capability=summarize` | 查詢具備特定能力的資源 |
| `POST` | `/api/v1/resources/:id/deregister` | 資源關閉時登出 |
---
## 5. 實作建議
### 5.1 Processor 實作 (確定性)
* 通常由 Python 腳本或 Rust 二進制執行。
* 啟動時呼叫 `POST /resources/register`,宣告如 `["video_to_frames", "detect_objects"]`
### 5.2 Agent 實作 (機率性)
* 通常封裝為具備 LLM Context 的服務。
* 啟動時呼叫 `POST /resources/register`,宣告如 `["summarize_text", "extract_5w1h"]`
* **重點**: 在 `metadata` 中記錄使用的 LLM 模型名稱 (e.g., `gpt-4o`, `llama3`)。
### 5.3 Service 實作 (基礎設施)
* 通常由 Docker Compose 或 Systemd 管理。
* 可透過 Sidecar 或定期腳本進行註冊與心跳更新。
---
## 6. 與其他架構的關係
* **Job/Task Scheduler**: 任務調度器依賴 Resource Registry 來尋找誰能執行任務。
* **Configuration Management**: 資源的詳細參數 (如 API Key, Threshold) 應存在 Config 中心Registry 僅儲存引用或摘要。
* **Monitoring**: Prometheus/Grafana 應抓取 Registry 狀態來展示系統資源健康度儀表板。
## 7. 關聯文檔
本目錄整合了原有的 Processor 與 Service 架構,並納入新的 Agent 架構:
- `PROCESSOR_REGISTRY_ARCHITECTURE.md` - 舊版處理器註冊設計 (已整合)。
- `SERVICE_REGISTRY_ARCHITECTURE.md` - 舊版服務註冊設計 (已整合)。
- `PROCESSOR_LIFECYCLE.md` - 處理器生命週期 (資源生命週期的子集)。
---
## 版本資訊
- 版本: V1.0
- 建立日期: 2026-04-25