优化: ssh/mongo/redis-proxy 超时分级与日志默认开
- ssh: exec_timeout_secs 600s(408断会话)/idle 300→1800s/日志级别规则/截断500→2000 - mongo/redis: query_timeout 60s + idle_timeout 落配置 - 四代理: 日志默认开启(default_log_path exe同目录logs/),未设env也记录 - mysql: default_log_path 共享实现注释同步
This commit is contained in:
1 parent
ecdebdd6c0
commit
95dfe8504d
20 files changed
+3494
-121
No files matched your search
@@ -19,16 +19,20 @@ pub struct PoolConfig {
|
||||
pub idle_timeout_secs: u64,
|
||||
#[serde(default = "default_check_interval")]
|
||||
pub check_interval_secs: u64,
|
||||
#[serde(default = "default_query_timeout")]
|
||||
pub query_timeout_secs: u64,
|
||||
}
|
||||
|
||||
fn default_idle_timeout() -> u64 { 300 }
|
||||
fn default_check_interval() -> u64 { 60 }
|
||||
fn default_query_timeout() -> u64 { 60 }
|
||||
|
||||
impl Default for PoolConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
idle_timeout_secs: default_idle_timeout(),
|
||||
check_interval_secs: default_check_interval(),
|
||||
query_timeout_secs: default_query_timeout(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,11 @@ impl ConnectionManager {
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// 单次操作执行超时(秒),用于 API handler 的 tokio::time::timeout
|
||||
pub fn query_timeout_secs(&self) -> u64 {
|
||||
self.pool_config.query_timeout_secs
|
||||
}
|
||||
|
||||
pub fn cleanup_idle(&self) {
|
||||
let mut clients = self.clients.lock().unwrap();
|
||||
let now = Instant::now();
|
||||
|
||||
+107
-51
@@ -7,7 +7,7 @@ use futures_util::TryStreamExt;
|
||||
use mongodb::bson::Document;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::db::ConnectionManager;
|
||||
use crate::logger::{LogEntry, RequestLogger};
|
||||
@@ -197,19 +197,27 @@ pub async fn find(
|
||||
if let Some(l) = req.limit { find = find.limit(l); }
|
||||
if let Some(s) = req.skip { find = find.skip(s); }
|
||||
|
||||
let mut cursor = find.await
|
||||
.map_err(|e| {
|
||||
let timeout_secs = manager.query_timeout_secs();
|
||||
let operation = async {
|
||||
let mut cursor = find.await?;
|
||||
let mut documents = Vec::new();
|
||||
while let Some(result) = cursor.try_next().await? {
|
||||
documents.push(bson_to_json(&result));
|
||||
}
|
||||
Ok::<_, mongodb::error::Error>(documents)
|
||||
};
|
||||
let documents = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
|
||||
Ok(Ok(documents)) => documents,
|
||||
Ok(Err(e)) => {
|
||||
logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?;
|
||||
|
||||
let mut documents = Vec::new();
|
||||
while let Some(result) = cursor.try_next().await.map_err(|e: mongodb::error::Error| {
|
||||
logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})? {
|
||||
documents.push(bson_to_json(&result));
|
||||
}
|
||||
return Err(error_response(&e.to_string()));
|
||||
}
|
||||
Err(_) => {
|
||||
let msg = format!("操作超时(>{}s)", timeout_secs);
|
||||
logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
|
||||
return Err(timeout_response(timeout_secs));
|
||||
}
|
||||
};
|
||||
|
||||
let count = documents.len();
|
||||
let duration = start.elapsed();
|
||||
@@ -240,11 +248,18 @@ pub async fn insert(
|
||||
let db = client.database(&get_database(manager, &req.conn));
|
||||
let coll = db.collection::<Document>(&req.collection);
|
||||
|
||||
let result = coll.insert_many(req.documents).await
|
||||
.map_err(|e| {
|
||||
let timeout_secs = manager.query_timeout_secs();
|
||||
let result = match tokio::time::timeout(Duration::from_secs(timeout_secs), coll.insert_many(req.documents)).await {
|
||||
Ok(r) => r.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/insert", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?;
|
||||
})?,
|
||||
Err(_) => {
|
||||
let msg = format!("操作超时(>{}s)", timeout_secs);
|
||||
logger.log(&LogEntry::new("/insert", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
|
||||
return Err(timeout_response(timeout_secs));
|
||||
}
|
||||
};
|
||||
|
||||
let inserted_ids: Vec<String> = result.inserted_ids.iter()
|
||||
.map(|(k, v)| format!("{}:{}", k, v))
|
||||
@@ -278,18 +293,29 @@ pub async fn update(
|
||||
let db = client.database(&get_database(manager, &req.conn));
|
||||
let coll = db.collection::<Document>(&req.collection);
|
||||
|
||||
let result = if req.multi.unwrap_or(false) {
|
||||
let mut cmd = coll.update_many(req.filter, req.update);
|
||||
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
|
||||
cmd.await
|
||||
} else {
|
||||
let mut cmd = coll.update_one(req.filter, req.update);
|
||||
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
|
||||
cmd.await
|
||||
}.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/update", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?;
|
||||
let timeout_secs = manager.query_timeout_secs();
|
||||
let operation = async {
|
||||
if req.multi.unwrap_or(false) {
|
||||
let mut cmd = coll.update_many(req.filter, req.update);
|
||||
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
|
||||
cmd.await
|
||||
} else {
|
||||
let mut cmd = coll.update_one(req.filter, req.update);
|
||||
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
|
||||
cmd.await
|
||||
}
|
||||
};
|
||||
let result = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
|
||||
Ok(r) => r.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/update", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?,
|
||||
Err(_) => {
|
||||
let msg = format!("操作超时(>{}s)", timeout_secs);
|
||||
logger.log(&LogEntry::new("/update", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
|
||||
return Err(timeout_response(timeout_secs));
|
||||
}
|
||||
};
|
||||
|
||||
let upserted_id = result.upserted_id.map(|id| format!("{:?}", id));
|
||||
let duration = start.elapsed();
|
||||
@@ -324,14 +350,25 @@ pub async fn delete(
|
||||
let db = client.database(&get_database(manager, &req.conn));
|
||||
let coll = db.collection::<Document>(&req.collection);
|
||||
|
||||
let result = if req.multi.unwrap_or(false) {
|
||||
coll.delete_many(req.filter).await
|
||||
} else {
|
||||
coll.delete_one(req.filter).await
|
||||
}.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/delete", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?;
|
||||
let timeout_secs = manager.query_timeout_secs();
|
||||
let operation = async {
|
||||
if req.multi.unwrap_or(false) {
|
||||
coll.delete_many(req.filter).await
|
||||
} else {
|
||||
coll.delete_one(req.filter).await
|
||||
}
|
||||
};
|
||||
let result = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
|
||||
Ok(r) => r.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/delete", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?,
|
||||
Err(_) => {
|
||||
let msg = format!("操作超时(>{}s)", timeout_secs);
|
||||
logger.log(&LogEntry::new("/delete", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
|
||||
return Err(timeout_response(timeout_secs));
|
||||
}
|
||||
};
|
||||
|
||||
let deleted_count = result.deleted_count;
|
||||
let duration = start.elapsed();
|
||||
@@ -361,19 +398,27 @@ pub async fn aggregate(
|
||||
let db = client.database(&get_database(manager, &req.conn));
|
||||
let coll = db.collection::<Document>(&req.collection);
|
||||
|
||||
let mut cursor = coll.aggregate(req.pipeline).await
|
||||
.map_err(|e| {
|
||||
let timeout_secs = manager.query_timeout_secs();
|
||||
let operation = async {
|
||||
let mut cursor = coll.aggregate(req.pipeline).await?;
|
||||
let mut documents = Vec::new();
|
||||
while let Some(result) = cursor.try_next().await? {
|
||||
documents.push(bson_to_json(&result));
|
||||
}
|
||||
Ok::<_, mongodb::error::Error>(documents)
|
||||
};
|
||||
let documents = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
|
||||
Ok(Ok(documents)) => documents,
|
||||
Ok(Err(e)) => {
|
||||
logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?;
|
||||
|
||||
let mut documents = Vec::new();
|
||||
while let Some(result) = cursor.try_next().await.map_err(|e: mongodb::error::Error| {
|
||||
logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})? {
|
||||
documents.push(bson_to_json(&result));
|
||||
}
|
||||
return Err(error_response(&e.to_string()));
|
||||
}
|
||||
Err(_) => {
|
||||
let msg = format!("操作超时(>{}s)", timeout_secs);
|
||||
logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
|
||||
return Err(timeout_response(timeout_secs));
|
||||
}
|
||||
};
|
||||
|
||||
let count = documents.len();
|
||||
let duration = start.elapsed();
|
||||
@@ -404,11 +449,18 @@ pub async fn count(
|
||||
let db = client.database(&get_database(manager, &req.conn));
|
||||
let coll = db.collection::<Document>(&req.collection);
|
||||
|
||||
let count = coll.count_documents(req.filter.unwrap_or_default()).await
|
||||
.map_err(|e| {
|
||||
let timeout_secs = manager.query_timeout_secs();
|
||||
let count = match tokio::time::timeout(Duration::from_secs(timeout_secs), coll.count_documents(req.filter.unwrap_or_default())).await {
|
||||
Ok(r) => r.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/count", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
|
||||
error_response(&e.to_string())
|
||||
})?;
|
||||
})?,
|
||||
Err(_) => {
|
||||
let msg = format!("操作超时(>{}s)", timeout_secs);
|
||||
logger.log(&LogEntry::new("/count", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
|
||||
return Err(timeout_response(timeout_secs));
|
||||
}
|
||||
};
|
||||
|
||||
let duration = start.elapsed();
|
||||
|
||||
@@ -482,6 +534,10 @@ fn error_response_with_usage(msg: &str, usage: &str) -> (StatusCode, Json<ErrorR
|
||||
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage)))
|
||||
}
|
||||
|
||||
fn timeout_response(secs: u64) -> (StatusCode, Json<ErrorResponse>) {
|
||||
(StatusCode::REQUEST_TIMEOUT, Json(ErrorResponse::new(&format!("操作超时(>{}s)", secs))))
|
||||
}
|
||||
|
||||
fn list_conn_names(manager: &ConnectionManager) -> String {
|
||||
manager.list_connections()
|
||||
.iter()
|
||||
|
||||
@@ -97,7 +97,7 @@ impl LogEntry {
|
||||
}
|
||||
|
||||
pub fn with_command(mut self, cmd: &str) -> Self {
|
||||
self.command = Some(truncate_string(cmd, 500));
|
||||
self.command = Some(truncate_string(cmd, 2000));
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
+34
-3
@@ -11,6 +11,17 @@ use axum::{
|
||||
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")]
|
||||
@@ -154,13 +165,32 @@ enum Commands {
|
||||
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(&args.config, port, host).await
|
||||
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)
|
||||
@@ -184,7 +214,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
list_connections(&args.server)
|
||||
}
|
||||
None => {
|
||||
run_server(&args.config, None, None).await
|
||||
run_server(&config_path, None, None).await
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,7 +231,8 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
|
||||
config.server.host = host;
|
||||
}
|
||||
|
||||
let log_path = std::env::var("MONGO_PROXY_LOG").ok();
|
||||
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");
|
||||
|
||||
Reference in new issue
Block a user