优化: 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
@@ -17,14 +17,18 @@ pub struct PoolConfig {
|
||||
pub idle_timeout_secs: u64,
|
||||
#[serde(default = "default_check_interval")]
|
||||
pub check_interval_secs: u64,
|
||||
/// 单操作执行超时(秒):防无界阻塞,超时返回 408
|
||||
#[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() }
|
||||
Self { idle_timeout_secs: default_idle_timeout(), check_interval_secs: default_check_interval(), query_timeout_secs: default_query_timeout() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,10 @@ impl ConnectionManager {
|
||||
Ok(Self { clients: Mutex::new(HashMap::new()), configs: Mutex::new(config_map), pool_config })
|
||||
}
|
||||
|
||||
pub fn query_timeout_secs(&self) -> u64 {
|
||||
self.pool_config.query_timeout_secs
|
||||
}
|
||||
|
||||
pub fn get_conn(&self, name: &str) -> Result<(RedisClient, ConnectionConfig)> {
|
||||
let client = {
|
||||
let mut clients = self.clients.lock().unwrap();
|
||||
|
||||
+72
-13
@@ -2,7 +2,7 @@ use axum::{extract::State, http::StatusCode, Json};
|
||||
use redis::Commands;
|
||||
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};
|
||||
@@ -71,6 +71,11 @@ type ApiError = (StatusCode, Json<ErrorResponse>);
|
||||
fn err(msg: &str) -> ApiError { (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg))) }
|
||||
fn err_usage(msg: &str, usage: &str) -> ApiError { (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage))) }
|
||||
|
||||
/// 操作执行超时:HTTP 408,提示调用方 Redis 操作占用资源过久而非配置错误
|
||||
fn query_timeout_response(secs: u64) -> ApiError {
|
||||
(StatusCode::REQUEST_TIMEOUT, Json(ErrorResponse::new(&format!("操作超时(>{}s)", secs))))
|
||||
}
|
||||
|
||||
pub async fn run_cmd(State(state): State<AppState>, Json(req): Json<RunRequest>) -> Result<Json<RunResponse>, ApiError> {
|
||||
let (manager, logger) = state.as_ref();
|
||||
let start = Instant::now();
|
||||
@@ -78,14 +83,23 @@ pub async fn run_cmd(State(state): State<AppState>, Json(req): Json<RunRequest>)
|
||||
let conn_name = req.conn.clone();
|
||||
let cmd_str = format!("{} {}", req.command, req.args.join(" "));
|
||||
|
||||
let result: Result<serde_json::Value, ApiError> = tokio::task::spawn_blocking(move || {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<serde_json::Value, ApiError> {
|
||||
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err_usage(&e.to_string(), "Usage: POST /run {\"conn\": \"name\", \"command\": \"GET\", \"args\": [\"key\"]}"))?;
|
||||
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
|
||||
let mut cmd = redis::cmd(&req.command);
|
||||
for arg in &req.args { cmd.arg(arg); }
|
||||
let val: redis::Value = cmd.query(&mut conn).map_err(|e| err(&e.to_string()))?;
|
||||
Ok(redis_value_to_json(&val))
|
||||
}).await.map_err(|_| err("Task join error"))?;
|
||||
});
|
||||
|
||||
let result: Result<serde_json::Value, ApiError> = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/run", "http").with_conn(&req.conn).with_command(&cmd_str).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let result = result.map_err(|e| {
|
||||
let msg = &e.1.error;
|
||||
@@ -105,12 +119,21 @@ pub async fn get(State(state): State<AppState>, Json(req): Json<GetRequest>) ->
|
||||
let conn_name = req.conn.clone();
|
||||
let key_name = req.key.clone();
|
||||
|
||||
let value: Result<Option<String>, ApiError> = tokio::task::spawn_blocking(move || {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<Option<String>, ApiError> {
|
||||
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
|
||||
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
|
||||
let val: Option<String> = conn.get(&key_name).map_err(|e| err(&e.to_string()))?;
|
||||
Ok(val)
|
||||
}).await.map_err(|_| err("Task join error"))?;
|
||||
});
|
||||
|
||||
let value: Result<Option<String>, ApiError> = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/get", "http").with_conn(&req.conn).with_command(&format!("GET {}", req.key)).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let value = value.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/get", "http").with_conn(&req.conn).with_command(&format!("GET {}", req.key)).with_error(&e.1.error));
|
||||
@@ -131,7 +154,8 @@ pub async fn set(State(state): State<AppState>, Json(req): Json<SetRequest>) ->
|
||||
let value_str = req.value.clone();
|
||||
let ttl = req.ttl;
|
||||
|
||||
let result: Result<(), ApiError> = tokio::task::spawn_blocking(move || {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<(), ApiError> {
|
||||
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
|
||||
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
|
||||
if let Some(secs) = ttl {
|
||||
@@ -140,7 +164,15 @@ pub async fn set(State(state): State<AppState>, Json(req): Json<SetRequest>) ->
|
||||
conn.set::<_, _, ()>(&key_name, &value_str).map_err(|e| err(&e.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}).await.map_err(|_| err("Task join error"))?;
|
||||
});
|
||||
|
||||
let result: Result<(), ApiError> = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/set", "http").with_conn(&req.conn).with_command(&format!("SET {} {}", req.key, req.value)).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
result.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/set", "http").with_conn(&req.conn).with_command(&format!("SET {} {}", req.key, req.value)).with_error(&e.1.error));
|
||||
@@ -159,12 +191,21 @@ pub async fn del(State(state): State<AppState>, Json(req): Json<DelRequest>) ->
|
||||
let conn_name = req.conn.clone();
|
||||
let del_keys = req.keys.clone();
|
||||
|
||||
let deleted: Result<u64, ApiError> = tokio::task::spawn_blocking(move || {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<u64, ApiError> {
|
||||
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
|
||||
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
|
||||
let count: u64 = conn.del(&del_keys).map_err(|e| err(&e.to_string()))?;
|
||||
Ok(count)
|
||||
}).await.map_err(|_| err("Task join error"))?;
|
||||
});
|
||||
|
||||
let deleted: Result<u64, ApiError> = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/del", "http").with_conn(&req.conn).with_command(&format!("DEL {}", req.keys.join(" "))).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let deleted = deleted.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/del", "http").with_conn(&req.conn).with_command(&format!("DEL {}", req.keys.join(" "))).with_error(&e.1.error));
|
||||
@@ -183,12 +224,21 @@ pub async fn keys(State(state): State<AppState>, Json(req): Json<KeysRequest>) -
|
||||
let conn_name = req.conn.clone();
|
||||
let pattern = req.pattern.clone();
|
||||
|
||||
let result: Result<Vec<String>, ApiError> = tokio::task::spawn_blocking(move || {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<Vec<String>, ApiError> {
|
||||
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
|
||||
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
|
||||
let keys: Vec<String> = conn.keys(&pattern).map_err(|e| err(&e.to_string()))?;
|
||||
Ok(keys)
|
||||
}).await.map_err(|_| err("Task join error"))?;
|
||||
});
|
||||
|
||||
let result: Result<Vec<String>, ApiError> = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/keys", "http").with_conn(&req.conn).with_command(&format!("KEYS {}", req.pattern)).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let result = result.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/keys", "http").with_conn(&req.conn).with_command(&format!("KEYS {}", req.pattern)).with_error(&e.1.error));
|
||||
@@ -206,12 +256,21 @@ pub async fn info(State(state): State<AppState>, Json(req): Json<InfoRequest>) -
|
||||
let mgr = manager.clone();
|
||||
let conn_name = req.conn.clone();
|
||||
|
||||
let info: Result<String, ApiError> = tokio::task::spawn_blocking(move || {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<String, ApiError> {
|
||||
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
|
||||
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
|
||||
let info: String = redis::cmd("INFO").query(&mut conn).map_err(|e| err(&e.to_string()))?;
|
||||
Ok(info)
|
||||
}).await.map_err(|_| err("Task join error"))?;
|
||||
});
|
||||
|
||||
let info: Result<String, ApiError> = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/info", "http").with_conn(&req.conn).with_command("INFO").with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let info = info.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/info", "http").with_conn(&req.conn).with_command("INFO").with_error(&e.1.error));
|
||||
|
||||
@@ -63,7 +63,7 @@ impl LogEntry {
|
||||
}
|
||||
}
|
||||
pub fn with_conn(mut self, conn: &str) -> Self { self.conn = Some(conn.to_string()); self }
|
||||
pub fn with_command(mut self, cmd: &str) -> Self { self.command = Some(truncate_string(cmd, 500)); self }
|
||||
pub fn with_command(mut self, cmd: &str) -> Self { self.command = Some(truncate_string(cmd, 2000)); self }
|
||||
pub fn with_duration(mut self, ms: u64) -> Self {
|
||||
self.duration_ms = ms;
|
||||
if ms > 5000 && self.level == "INFO" { self.level = "ERROR".to_string(); }
|
||||
|
||||
+58
-9
@@ -8,6 +8,17 @@ use axum::{routing::{get, post}, Router};
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::sync::Arc;
|
||||
|
||||
// ⚠ 共享实现,修改需同步至 mysql/mongo/ssh-proxy/src/main.rs
|
||||
/// 默认请求日志路径(未设置 REDIS_PROXY_LOG 时): exe同目录 logs/redis-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 = "redis-proxy")]
|
||||
#[command(about = "Redis HTTP proxy with connection pooling")]
|
||||
@@ -31,18 +42,55 @@ enum Commands {
|
||||
Connections,
|
||||
}
|
||||
|
||||
// ⚠ 共享实现,修改需同步至 mysql/ssh/mongo-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,
|
||||
Some(Commands::Run { conn, command, args: ref keys }) => { let c = get_cli(&args.server)?; Ok(c.run(&conn, &command, keys)?) },
|
||||
Some(Commands::Get { conn, key }) => { let c = get_cli(&args.server)?; Ok(c.get(&conn, &key)?) },
|
||||
Some(Commands::Set { conn, key, value, ttl }) => { let c = get_cli(&args.server)?; Ok(c.set(&conn, &key, &value, ttl)?) },
|
||||
Some(Commands::Del { conn, key: ref keys }) => { let c = get_cli(&args.server)?; Ok(c.del(&conn, keys)?) },
|
||||
Some(Commands::Keys { conn, pattern }) => { let c = get_cli(&args.server)?; Ok(c.keys(&conn, &pattern)?) },
|
||||
Some(Commands::Connections) => { let c = get_cli(&args.server)?; Ok(c.list_connections()?) },
|
||||
None => run_server(&args.config, None, None).await,
|
||||
Some(Commands::Server { port, host }) => run_server(&config_path, port, host).await,
|
||||
Some(Commands::Run { conn, command, args: ref keys }) => {
|
||||
let c = get_cli(&args.server)?;
|
||||
Ok(c.run(&conn, &command, keys)?)
|
||||
}
|
||||
Some(Commands::Get { conn, key }) => {
|
||||
let c = get_cli(&args.server)?;
|
||||
Ok(c.get(&conn, &key)?)
|
||||
}
|
||||
Some(Commands::Set { conn, key, value, ttl }) => {
|
||||
let c = get_cli(&args.server)?;
|
||||
Ok(c.set(&conn, &key, &value, ttl)?)
|
||||
}
|
||||
Some(Commands::Del { conn, key: ref keys }) => {
|
||||
let c = get_cli(&args.server)?;
|
||||
Ok(c.del(&conn, keys)?)
|
||||
}
|
||||
Some(Commands::Keys { conn, pattern }) => {
|
||||
let c = get_cli(&args.server)?;
|
||||
Ok(c.keys(&conn, &pattern)?)
|
||||
}
|
||||
Some(Commands::Connections) => {
|
||||
let c = get_cli(&args.server)?;
|
||||
Ok(c.list_connections()?)
|
||||
}
|
||||
None => run_server(&config_path, None, None).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +109,8 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
|
||||
if let Some(port) = port { config.server.port = port; }
|
||||
if let Some(host) = host { config.server.host = host; }
|
||||
|
||||
let log_path = std::env::var("REDIS_PROXY_LOG").ok();
|
||||
let log_path = std::env::var("REDIS_PROXY_LOG").ok()
|
||||
.or_else(|| Some(default_log_path("redis-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