Files
momentry_core/src/bin/rust_unregister.rs
T
Accusys 06397e5957 feat: add rust_unregister CLI tool
新增功能:
- 獨立的 unregister CLI 工具
- 不依賴 API 和 Worker
- 直接刪除數據庫、文件、Qdrant、Redis

特性:
- ✅ 完整刪除功能
- ✅ Dry-run 模式
- ✅ 詳細輸出模式
- ✅ 錯誤處理

使用方法:
```bash
# 模擬刪除
rust_unregister --uuid <uuid> --dry-run

# 實際刪除
rust_unregister --uuid <uuid> --verbose
```

刪除內容:
1. 數據庫記錄 (19 個表)
2. 輸出文件
3. Qdrant 向量 (7 個 collections + workspace)
4. Redis keys

優勢:
- 同步執行(無需等待 Worker)
- 獨立運行(無需 API Server)
- 詳細輸出(便於調試)

文檔:
- docs_v1.0/OPERATIONS/Rust_Unregister_CLI_Tool.md

測試:
- ✅ 編譯成功
- ✅ Dry-run 測試通過
- ✅ Help 信息正確

Binary:
- target/debug/rust_unregister (27MB)
2026-09-28 18:51:55 +08:00

300 lines
9.4 KiB
Rust

use anyhow::{Context, Result};
use clap::Parser;
use momentry_core::core::db::{
postgres_db::PostgresDb,
qdrant_db::QdrantDb,
redis_client::RedisClient,
qdrant_workspace::QdrantWorkspace
};
use momentry_core::core::config;
use momentry_core::Database;
#[derive(Parser, Debug)]
#[command(name = "rust_unregister")]
#[command(about = "Unregister a video file from Momentry database")]
struct Args {
#[arg(short, long)]
uuid: String,
#[arg(short, long, default_value = "false")]
dry_run: bool,
#[arg(short, long, default_value = "false")]
verbose: bool,
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
println!("[UNREGISTER] Starting for file_uuid: {}", args.uuid);
if args.dry_run {
println!("[UNREGISTER] DRY-RUN MODE - No actual deletion");
}
let schema = std::env::var("DATABASE_SCHEMA")
.unwrap_or_else(|_| "public".to_string());
if args.verbose {
println!("[UNREGISTER] Schema: {}", schema);
println!("[UNREGISTER] Output dir: {}", *config::OUTPUT_DIR);
}
if !args.dry_run {
let db = PostgresDb::init().await
.context("Failed to connect to database")?;
unregister_database(&db, &args.uuid, args.verbose).await?;
unregister_output_files(&args.uuid, args.verbose)?;
unregister_qdrant(&args.uuid, &schema, args.verbose).await?;
unregister_redis(&args.uuid, args.verbose).await?;
} else {
println!("[UNREGISTER] Would delete from database");
println!("[UNREGISTER] Would delete output files");
println!("[UNREGISTER] Would delete Qdrant vectors");
println!("[UNREGISTER] Would delete Redis keys");
}
println!("[UNREGISTER] Done");
Ok(())
}
async fn unregister_database(db: &PostgresDb, uuid: &str, verbose: bool) -> Result<()> {
use momentry_core::core::db::schema;
println!("[UNREGISTER] Deleting database records...");
let mut deleted_total = 0i64;
let tables = [
("processor_results", "file_uuid = $1", "processor_results"),
("chunk", "file_uuid = $1", "chunks"),
("parent_chunks", "uuid = $1", "parent_chunks"),
("pre_chunks", "file_uuid = $1", "pre_chunks"),
("tkg_nodes", "file_uuid = $1", "TKG nodes"),
("cuts", "file_uuid = $1", "cuts"),
("strangers", "file_uuid = $1", "strangers"),
("chunk_vectors", "uuid = $1", "chunk vectors"),
("monitor_jobs", "uuid = $1", "monitor jobs"),
("file_identities", "file_uuid = $1", "file identities"),
("speaker_detections", "file_uuid = $1", "speaker detections"),
("face_clusters", "file_uuid = $1", "face clusters"),
("face_recognition_results", "file_uuid = $1", "face recognition results"),
("characters", "file_uuid = $1", "characters"),
("chunks_rule1", "uuid = $1", "chunks_rule1"),
("processor_alerts", "file_uuid = $1", "processor alerts"),
("processor_versions", "file_uuid = $1", "processor versions"),
("trace_profiles", "file_uuid = $1", "trace profiles"),
];
for (table, where_clause, label) in tables.iter() {
let table_name = schema::table_name(table);
let query = format!("DELETE FROM {} WHERE {}", table_name, where_clause);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context(format!("Failed to delete from {}", table_name))?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} {}", deleted, label);
}
}
let frames_table = schema::table_name("frames");
let videos_table = schema::table_name("videos");
let query = format!(
"DELETE FROM {} WHERE file_id = (SELECT id FROM {} WHERE file_uuid = $1)",
frames_table, videos_table
);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete frames")?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} frames", deleted);
}
let query = format!("DELETE FROM {} WHERE file_uuid = $1", videos_table);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete from videos table")?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} videos", deleted);
}
println!("[UNREGISTER] Total deleted: {} database records", deleted_total);
Ok(())
}
fn unregister_output_files(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting output files...");
let mut deleted_count = 0u64;
let output_dir = config::OUTPUT_DIR.to_string();
if let Ok(entries) = std::fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let is_uuid_file = name.starts_with(uuid) && !path.is_dir();
let is_pipeline_log = name.starts_with("pipeline_")
&& name.contains(uuid)
&& name.ends_with(".log");
let is_scenes_json = name == &format!("{}.scenes.json", uuid);
if is_uuid_file || is_pipeline_log || is_scenes_json {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted: {}", name);
}
}
}
}
}
}
let uuid_dir = std::path::Path::new(&output_dir).join(uuid);
if uuid_dir.is_dir() {
if std::fs::remove_dir_all(&uuid_dir).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted directory: {}", uuid_dir.display());
}
}
}
let workspace_sqlite = format!("{}.workspace.sqlite", uuid);
let sqlite_path = std::path::Path::new(&output_dir).join(&workspace_sqlite);
if sqlite_path.exists() && std::fs::remove_file(&sqlite_path).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted: {}", workspace_sqlite);
}
}
println!("[UNREGISTER] Deleted {} output files", deleted_count);
Ok(())
}
async fn unregister_qdrant(uuid: &str, schema: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting Qdrant vectors...");
let qdrant = QdrantDb::new();
let speaker_collection = if schema == "public" {
"momentry_public_speaker".to_string()
} else {
format!("momentry_{}_speaker", schema)
};
let face_embeddings_collection = format!("{}_face_embeddings", schema);
let collections: Vec<String> = vec![
qdrant.collection_name.clone(),
"_faces".to_string(),
"_scenes".to_string(),
"_vlm".to_string(),
"_seeds".to_string(),
face_embeddings_collection,
speaker_collection,
];
let mut success_count = 0;
for collection in &collections {
match QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
collection,
uuid,
)
.await
{
Ok(_) => {
success_count += 1;
if verbose {
println!("[UNREGISTER] Deleted from Qdrant: {}", collection);
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete from {}: {:?}", collection, e);
}
}
}
}
let workspace = QdrantWorkspace::new();
match workspace.delete_by_file_uuid(uuid).await {
Ok(_) => {
success_count += 1;
if verbose {
println!("[UNREGISTER] Deleted from Qdrant workspace");
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete from workspace: {:?}", e);
}
}
}
println!("[UNREGISTER] Deleted from {} Qdrant collections", success_count);
Ok(())
}
async fn unregister_redis(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting Redis keys...");
match RedisClient::new() {
Ok(redis) => {
match redis.delete_worker_job(uuid).await {
Ok(_) => {
if verbose {
println!("[UNREGISTER] Deleted Redis keys");
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete Redis keys: {:?}", e);
}
}
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to connect to Redis: {:?}", e);
}
}
}
Ok(())
}