新增: MongoDB/Redis 代理工具
This commit is contained in:
1 parent
f59ed9aae0
commit
5c56046234
18 files changed
+6344
-2
No files matched your search
@@ -0,0 +1,310 @@
|
||||
mod cli;
|
||||
mod config;
|
||||
mod db;
|
||||
mod handler;
|
||||
mod logger;
|
||||
|
||||
use axum::{
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "mongo-proxy")]
|
||||
#[command(about = "MongoDB HTTP proxy with connection pooling")]
|
||||
struct Args {
|
||||
#[command(subcommand)]
|
||||
command: Option<Commands>,
|
||||
|
||||
/// 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<u16>,
|
||||
|
||||
#[arg(short = 'H', long)]
|
||||
host: Option<String>,
|
||||
},
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// Limit
|
||||
#[arg(short, long)]
|
||||
limit: Option<i64>,
|
||||
|
||||
/// Skip
|
||||
#[arg(short, long)]
|
||||
skip: Option<u64>,
|
||||
|
||||
/// 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<String>,
|
||||
},
|
||||
|
||||
/// List available connections
|
||||
Connections,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
match args.command {
|
||||
Some(Commands::Server { port, host }) => {
|
||||
run_server(&args.config, 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(&args.config, None, None).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>) -> 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();
|
||||
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<cli::Cli> {
|
||||
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<i64>, skip: Option<u64>) -> 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()
|
||||
}
|
||||
Reference in new issue
Block a user