refactor: eliminate all CARGO_MANIFEST_DIR compile-time dependencies (A-4)

- Add src/core/path_utils.rs with runtime path resolution helpers
- Replace all env!("CARGO_MANIFEST_DIR") with runtime resolution
- Priority: env var -> current_exe sibling -> dev fallback

Changes:
- executor.rs: scripts_dir(), cli_dir() (4 locations)
- face.rs: swift_processor_path()
- tool_selector.rs: swift_binary_path()
- thumbnail/mod.rs: script_path()

Issue: CARGO_MANIFEST_DIR expands to build machine path at compile time,
       breaking on binary-only release hosts.

Solution: Resolve paths at runtime in this order:
1. Explicit environment variable (MOMENTRY_SCRIPTS_DIR, MOMENTRY_CLI_DIR)
2. Sibling of current_exe (same directory as running binary)
3. Relative path fallback (dev machine)

Verified: cargo check --lib passes
This commit is contained in:
Accusys
2026-10-04 13:44:40 +08:00
parent 3d363e6266
commit a3c3ed8dc1
850 changed files with 130339 additions and 91 deletions
+94
View File
@@ -0,0 +1,94 @@
use axum::{
extract::Path,
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
pub name: String,
pub r#type: String,
pub size: u64,
pub modified: String,
pub is_dir: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FolderInfo {
pub name: String,
pub parent: String,
}
// 列出用戶文件夾
pub async fn list_user_folders(
Path(username): Path<String>,
) -> Result<Json<Vec<FolderInfo>>, StatusCode> {
let base_path = PathBuf::from("/Users/nextorageai/momentry_studio/data")
.join(&username)
.join("files");
let mut folders = Vec::new();
if let Ok(mut entries) = fs::read_dir(&base_path).await {
while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(file_type) = entry.file_type().await {
if file_type.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
folders.push(FolderInfo {
name: name.clone(),
parent: String::new(),
});
}
}
}
}
Ok(Json(folders))
}
// 列出用戶文件
pub async fn list_user_files(
Path(username): Path<String>,
) -> Result<Json<Vec<FileInfo>>, StatusCode> {
let base_path = PathBuf::from("/Users/nextorageai/momentry_studio/data")
.join(&username)
.join("files");
let mut files = Vec::new();
if let Ok(mut entries) = fs::read_dir(&base_path).await {
while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(metadata) = entry.metadata().await {
let name = entry.file_name().to_string_lossy().to_string();
let is_dir = metadata.is_dir();
let size = if is_dir { 0 } else { metadata.len() };
let modified = metadata.modified()
.ok()
.map(|t| format!("{:?}", t))
.unwrap_or_else(|| "Unknown".to_string());
files.push(FileInfo {
name,
r#type: if is_dir { "directory".to_string() } else { "file".to_string() },
size,
modified,
is_dir,
});
}
}
}
Ok(Json(files))
}
pub fn markbase_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v2/myfiles/:username/folders", get(list_user_folders))
.route("/api/v2/myfiles/:username/files", get(list_user_files))
}
+1
View File
@@ -21,6 +21,7 @@ pub mod profile;
pub mod scan;
pub mod search;
pub mod server;
pub mod markbase_compat;
pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
+30
View File
@@ -0,0 +1,30 @@
pub mod admin_config;
pub mod agent_api;
pub mod agent_search;
pub mod auth;
pub mod billing;
pub mod checkin_api;
pub mod cluster_agent;
pub mod docs;
pub mod face_filter;
pub mod files;
pub mod health;
pub mod identities;
pub mod identity_api;
pub mod identity_binding;
pub mod llm_search;
pub mod media_api;
pub mod middleware;
pub mod pipeline;
pub mod processing;
pub mod profile;
pub mod scan;
pub mod search;
pub mod server;
pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
pub mod universal_search;
pub mod vlm_search;
pub use server::start_server;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2
View File
@@ -19,6 +19,7 @@ use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::files;
use super::markbase_compat;
use super::health;
use super::health::{health, health_consistency, health_detailed};
use super::identities;
@@ -128,6 +129,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(markbase_compat::markbase_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
+193
View File
@@ -0,0 +1,193 @@
use std::time::Duration;
use axum::{Json, Router};
use serde_json::json;
use tokio::time::timeout;
use tower_http::cors::{Any, CorsLayer};
use crate::core::cache::{MongoCache, RedisCache};
use crate::core::db::{Database, PostgresDb, QdrantDb};
use crate::Embedder;
use super::admin_config;
use super::agent_api;
use super::agent_search;
use super::auth;
use super::billing;
use super::checkin_api;
use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::files;
use super::health;
use super::health::{health, health_consistency, health_detailed};
use super::identities;
use super::identity_api;
use super::identity_binding;
use super::llm_search;
use super::media_api;
use super::middleware::unified_auth;
use super::pipeline;
use super::processing;
use super::profile;
use super::scan;
use super::search::search_routes;
use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::universal_search::universal_search_routes;
use super::vlm_search;
pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
health::init_server_state(host, port);
let embedder = std::sync::Arc::new(Embedder::new("embeddinggemma-300m".to_string()));
// ── ⚠️ WARNING: DO NOT move MongoCache::init() back to critical path ──
//
// MongoDB is ONLY a cache layer — if unavailable, the server MUST still
// start with Redis cache alone. This keeps 3002 bootable on machines
// without MongoDB installed. If you add a new dependency here, ask:
// "Can this service degrade gracefully if the dependant is missing?"
//
// See also: MongoCache::disabled() in mongo_cache.rs
let mongo_cache = match timeout(Duration::from_secs(5), MongoCache::init()).await {
Ok(Ok(cache)) => cache,
Ok(Err(e)) => {
tracing::warn!("MongoDB cache unavailable (continuing without): {e}");
MongoCache::disabled().await
}
Err(_) => {
tracing::warn!("MongoDB init timed out (continuing without cache)");
MongoCache::disabled().await
}
};
let redis_cache = RedisCache::new()?;
let db = PostgresDb::init().await?;
// Run migrations (create identity_history table if not exists)
PostgresDb::run_migrations(db.pool()).await?;
let schema_health = health::check_schema_migrations(db.pool()).await;
if schema_health.ok {
tracing::info!(
"[SCHEMA] All {}/{} required migrations applied ✓",
schema_health.required.len(),
schema_health.required.len()
);
} else if !schema_health.table_exists {
tracing::warn!("[SCHEMA] schema_migrations table not found!");
} else {
let missing: Vec<&str> = schema_health
.required
.iter()
.filter(|req| {
!schema_health
.applied
.iter()
.any(|app| app.filename == req.filename && app.checksum == req.checksum)
})
.map(|m| m.filename.as_str())
.collect();
tracing::warn!(
"[SCHEMA] {}/{} migrations match. Missing: {}",
schema_health.applied.len(),
schema_health.required.len(),
missing.join(", ")
);
}
let db = std::sync::Arc::new(db);
let api_state = super::middleware::ApiState { db: db.clone() };
let qdrant = std::sync::Arc::new(QdrantDb::new());
// Initialize AdminConfigManager
let admin_config_manager = std::sync::Arc::new(
crate::core::admin_config::AdminConfigManager::new(
&crate::core::admin_config::get_default_config_path(),
)
.expect("Failed to initialize AdminConfigManager"),
);
// Ensure trash collection exists for trace hard-delete undo
if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await {
tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e);
}
let state = AppState {
db,
qdrant,
embedder,
embedder_model: "nomic-embed-text-v2-moe:latest".to_string(),
mongo_cache,
redis_cache,
api_state,
admin_config_manager,
};
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
.merge(tmdb_api::tmdb_routes())
.merge(identity_api::identity_routes())
.merge(agent_api::agent_routes())
.merge(agent_search::agent_search_routes())
.merge(processing::processing_routes())
.merge(media_api::bbox_routes())
.merge(media_api::media_proxy_routes())
.merge(media_api::pose_appearance_routes())
.merge(trace_agent_api::trace_agent_routes())
.merge(search_routes())
.merge(llm_search::llm_smart_routes())
.merge(universal_search_routes())
.merge(pipeline::pipeline_routes())
.merge(checkin_api::checkin_routes())
.merge(cluster_agent::cluster_agent_routes())
.merge(profile::profile_routes())
.merge(face_filter::face_filter_routes())
.merge(admin_config::admin_config_routes())
.merge(vlm_search::vlm_search_routes())
.merge(billing::billing_routes())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
))
.with_state(state.clone());
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let public_health_routes = Router::new()
.route("/api/v1/health", axum::routing::get(health))
.route(
"/api/v1/health/detailed",
axum::routing::get(health_detailed),
)
.route(
"/api/v1/health/consistency",
axum::routing::get(health_consistency),
);
let app = Router::new()
.merge(auth::auth_routes())
.merge(public_health_routes)
.merge(health::health_routes())
.merge(docs::doc_routes())
.merge(protected_routes)
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.with_state(state);
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap();
tracing::info!("Starting API server at http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}