mod cli; mod config; mod db; mod handler; mod logger; use axum::{ routing::{get, post}, Router, }; use clap::{Parser, Subcommand}; use std::sync::Arc; // ⚠ 共享实现,修改需同步至 mysql/ssh/redis-proxy/src/main.rs /// 默认请求日志路径(未设置 MONGO_PROXY_LOG 时): exe同目录 logs/mongo-proxy.log fn default_log_path(name: &str) -> String { match std::env::current_exe() { Ok(exe) => exe.parent() .map(|d| d.join("logs").join(format!("{}.log", name)).to_string_lossy().into_owned()) .unwrap_or_else(|| format!("{}.log", name)), Err(_) => format!("{}.log", name), } } #[derive(Parser, Debug)] #[command(name = "mongo-proxy")] #[command(about = "MongoDB HTTP proxy with connection pooling")] struct Args { #[command(subcommand)] command: Option, /// Config file path #[arg(long, default_value = "mongo-proxy.toml", global = true)] config: String, /// Server URL (for CLI mode) #[arg(short = 'S', long, default_value = "http://127.0.0.1:3309", global = true)] server: String, } #[derive(Debug, Subcommand)] enum Commands { /// Start HTTP server (default) Server { #[arg(short = 'P', long)] port: Option, #[arg(short = 'H', long)] host: Option, }, /// Find documents Find { /// Connection name #[arg(short, long)] conn: String, /// Collection name #[arg(short = 'C', long)] collection: String, /// Filter JSON #[arg(short, long, default_value = "{}")] filter: String, /// Projection JSON #[arg(short, long)] projection: Option, /// Limit #[arg(short, long)] limit: Option, /// Skip #[arg(short, long)] skip: Option, /// Output format: json, pretty #[arg(short = 'F', long, default_value = "pretty")] format: String, }, /// Insert documents Insert { #[arg(short, long)] conn: String, #[arg(short = 'C', long)] collection: String, /// Documents JSON array #[arg(short, long)] documents: String, }, /// Update documents Update { #[arg(short, long)] conn: String, #[arg(short = 'C', long)] collection: String, /// Filter JSON #[arg(short, long)] filter: String, /// Update JSON #[arg(short, long)] update: String, /// Upsert #[arg(long)] upsert: bool, /// Update multiple #[arg(long)] multi: bool, }, /// Delete documents Delete { #[arg(short, long)] conn: String, #[arg(short = 'C', long)] collection: String, /// Filter JSON #[arg(short, long)] filter: String, /// Delete multiple #[arg(long)] multi: bool, }, /// Aggregate pipeline Aggregate { #[arg(short, long)] conn: String, #[arg(short = 'C', long)] collection: String, /// Pipeline JSON array #[arg(long)] pipeline: String, }, /// Count documents Count { #[arg(short, long)] conn: String, #[arg(short = 'C', long)] collection: String, /// Filter JSON #[arg(short, long)] filter: Option, }, /// List available connections Connections, } // ⚠ 共享实现,修改需同步至 mysql/ssh/redis-proxy/src/main.rs /// 将相对路径基于可执行文件所在目录解析为绝对路径 fn resolve_config_path(path: &str) -> String { if std::path::Path::new(path).is_absolute() || path.starts_with('~') { return path.to_string(); } match std::env::current_exe() { Ok(exe) => { if let Some(dir) = exe.parent() { dir.join(path).to_string_lossy().into_owned() } else { path.to_string() } } Err(_) => path.to_string(), } } #[tokio::main] async fn main() -> anyhow::Result<()> { let args = Args::parse(); let config_path = resolve_config_path(&args.config); match args.command { Some(Commands::Server { port, host }) => { run_server(&config_path, port, host).await } Some(Commands::Find { conn, collection, filter, projection, limit, skip, format }) => { run_find(&args.server, &conn, &collection, &filter, &format, projection.as_deref(), limit, skip) } Some(Commands::Insert { conn, collection, documents }) => { run_insert(&args.server, &conn, &collection, &documents) } Some(Commands::Update { conn, collection, filter, update, upsert, multi }) => { run_update(&args.server, &conn, &collection, &filter, &update, upsert, multi) } Some(Commands::Delete { conn, collection, filter, multi }) => { run_delete(&args.server, &conn, &collection, &filter, multi) } Some(Commands::Aggregate { conn, collection, pipeline }) => { run_aggregate(&args.server, &conn, &collection, &pipeline) } Some(Commands::Count { conn, collection, filter }) => { run_count(&args.server, &conn, &collection, filter.as_deref()) } Some(Commands::Connections) => { list_connections(&args.server) } None => { run_server(&config_path, None, None).await } } } async fn run_server(config_path: &str, port: Option, host: Option) -> anyhow::Result<()> { println!("MongoDB HTTP Proxy v0.1.0\n"); let mut config = config::Config::from_file(config_path)?; if let Some(port) = port { config.server.port = port; } if let Some(host) = host { config.server.host = host; } let log_path = std::env::var("MONGO_PROXY_LOG").ok() .or_else(|| Some(default_log_path("mongo-proxy"))); let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref())); if logger.is_enabled() { println!("Request logging: enabled"); } println!("Initializing connection pools...\n"); let manager = Arc::new(db::ConnectionManager::new(&config.connections, config.pool.clone())?); let manager_clone = manager.clone(); let check_interval = config.pool.check_interval_secs; tokio::spawn(async move { let mut interval = tokio::time::interval(std::time::Duration::from_secs(check_interval)); loop { interval.tick().await; manager_clone.cleanup_idle(); } }); let app = Router::new() .route("/find", post(handler::find)) .route("/insert", post(handler::insert)) .route("/update", post(handler::update)) .route("/delete", post(handler::delete)) .route("/aggregate", post(handler::aggregate)) .route("/count", post(handler::count)) .route("/connections", get(handler::connections)) .route("/connections/add", post(handler::add_connection)) .route("/health", get(handler::health)) .with_state(Arc::new((manager, logger))); let addr = format!("{}:{}", config.server.host, config.server.port); let listener = tokio::net::TcpListener::bind(&addr).await?; println!("\nServer started at http://{}", addr); println!("\nAPI Endpoints:"); println!(" POST /find - Query documents"); println!(" POST /insert - Insert documents"); println!(" POST /update - Update documents"); println!(" POST /delete - Delete documents"); println!(" POST /aggregate - Aggregation pipeline"); println!(" POST /count - Count documents"); println!(" GET /connections - List all connections"); println!(" POST /connections/add - Add connection (temporary)"); println!(" GET /health - Health check"); println!("\nCLI Usage:"); println!(" mongo-proxy find -c flux_dev -C users -f '{{\"status\": 1}}'"); println!(" mongo-proxy insert -c flux_dev -C users -d '[{{\"name\": \"test\"}}]'"); println!(" mongo-proxy aggregate -c flux_dev -C users --pipeline '[{{\"$match\": {{}}}}]'"); println!(" mongo-proxy connections"); axum::serve(listener, app).await?; Ok(()) } fn run_cli(server: &str) -> anyhow::Result { let c = cli::Cli::new(Some(server.to_string())); if !c.check_server()? { eprintln!(); eprintln!("=== mongo-proxy 未运行,请使用降级方案 ==="); eprintln!(); eprintln!("启动代理: mongo-proxy"); eprintln!(); eprintln!("或直接使用 mongosh:"); eprintln!(" mongosh \"mongodb://user:pass@host:27017/db\""); eprintln!(); eprintln!("配置文件中的连接信息见: mongo-proxy.toml"); anyhow::bail!("Proxy server not running at {}", server); } Ok(c) } fn run_find(server: &str, conn: &str, collection: &str, filter: &str, format: &str, projection: Option<&str>, limit: Option, skip: Option) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.find(conn, collection, filter, format, projection, limit, skip) } fn run_insert(server: &str, conn: &str, collection: &str, documents: &str) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.insert(conn, collection, documents) } fn run_update(server: &str, conn: &str, collection: &str, filter: &str, update: &str, upsert: bool, multi: bool) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.update(conn, collection, filter, update, upsert, multi) } fn run_delete(server: &str, conn: &str, collection: &str, filter: &str, multi: bool) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.delete(conn, collection, filter, multi) } fn run_aggregate(server: &str, conn: &str, collection: &str, pipeline: &str) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.aggregate(conn, collection, pipeline) } fn run_count(server: &str, conn: &str, collection: &str, filter: Option<&str>) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.count(conn, collection, filter) } fn list_connections(server: &str) -> anyhow::Result<()> { let cli = run_cli(server)?; cli.list_connections() }