优化: mysql-proxy 池满快速失败与超时兜底
风暴下池满时 get_conn 无界等待,慢查询永久霸占连接, 表层表现为"连主键查都排队 90s",真凶被无界排队掩盖。 - 池满限时等待(acquire_timeout_secs,默认 3s),超时返回 429 - 单语句整体超时(query_timeout_secs,默认 60s),超时返回 408 - 传输层:连接 10s 上限 + 读写超时,半开连接不滞留池中 - 默认池容量 5→10 - 取连接只在锁内取池副本,长等待不持全局锁(原实现会串行化全部连接) - 建池双检,防并发重复建池覆盖导致旧池连接泄漏 - 建池自检连接作用域释放,池上限 1 时不再自锁 实测:正常 200/0.3s;慢查 408/5s;池满 429/2s;10 并发全 200
This commit is contained in:
1 parent
091cb65314
commit
4283310434
6 files changed
+2299
-34
No files matched your search
@@ -25,11 +25,19 @@ pub struct PoolConfig {
|
||||
/// 检查间隔 (秒)
|
||||
#[serde(default = "default_check_interval")]
|
||||
pub check_interval_secs: u64,
|
||||
/// 获取连接等待上限(秒):池满时快速失败,防无界排队饿死
|
||||
#[serde(default = "default_acquire_timeout")]
|
||||
pub acquire_timeout_secs: u64,
|
||||
/// 单语句执行超时(秒):慢查询兜底,超时返回 408 而非无限占用连接
|
||||
#[serde(default = "default_query_timeout")]
|
||||
pub query_timeout_secs: u64,
|
||||
}
|
||||
|
||||
fn default_max_connections() -> usize { 5 }
|
||||
fn default_max_connections() -> usize { 10 }
|
||||
fn default_idle_timeout() -> u64 { 300 }
|
||||
fn default_check_interval() -> u64 { 60 }
|
||||
fn default_acquire_timeout() -> u64 { 3 }
|
||||
fn default_query_timeout() -> u64 { 60 }
|
||||
|
||||
impl Default for PoolConfig {
|
||||
fn default() -> Self {
|
||||
@@ -37,6 +45,8 @@ impl Default for PoolConfig {
|
||||
default_max_connections: default_max_connections(),
|
||||
idle_timeout_secs: default_idle_timeout(),
|
||||
check_interval_secs: default_check_interval(),
|
||||
acquire_timeout_secs: default_acquire_timeout(),
|
||||
query_timeout_secs: default_query_timeout(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+88
-25
@@ -6,10 +6,34 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use crate::config::{ConnectionConfig, PoolConfig};
|
||||
|
||||
/// 连接获取超时错误(池满快速失败),携带等待秒数供 handler 定级
|
||||
#[derive(Debug)]
|
||||
pub struct AcquireTimeout {
|
||||
pub wait_secs: u64,
|
||||
pub pool_max: usize,
|
||||
}
|
||||
impl std::error::Error for AcquireTimeout {}
|
||||
impl std::fmt::Display for AcquireTimeout {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "连接池繁忙: 等待 {}s 未拿到连接(池上限 {})", self.wait_secs, self.pool_max)
|
||||
}
|
||||
}
|
||||
|
||||
/// 连接池状态
|
||||
struct PoolState {
|
||||
pool: Arc<Pool>,
|
||||
last_used: Instant,
|
||||
last_used: Mutex<Instant>,
|
||||
}
|
||||
|
||||
impl PoolState {
|
||||
fn new(pool: Arc<Pool>) -> Self {
|
||||
Self { pool, last_used: Mutex::new(Instant::now()) }
|
||||
}
|
||||
fn touch(&self) {
|
||||
if let Ok(mut lu) = self.last_used.lock() {
|
||||
*lu = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 连接池管理器 (延迟初始化)
|
||||
@@ -40,15 +64,24 @@ impl ConnectionManager {
|
||||
})
|
||||
}
|
||||
|
||||
/// 获取或创建连接
|
||||
/// 获取或创建连接(带池满限时等待,防无界排队饿死)
|
||||
/// 池未建→建池;池已建→try_get_conn 最多等 acquire_timeout,超时抛 AcquireTimeout
|
||||
pub fn get_conn(&self, name: &str) -> Result<PooledConn> {
|
||||
// 1. 先尝试从已有池中获取
|
||||
{
|
||||
let mut pools = self.pools.lock().unwrap();
|
||||
if let Some(state) = pools.get_mut(name) {
|
||||
state.last_used = Instant::now();
|
||||
return Ok(state.pool.get_conn()?);
|
||||
let acquire_timeout = self.pool_config.acquire_timeout_secs;
|
||||
let pool_max = self.pool_max_of(name);
|
||||
|
||||
// 1. 先尝试从已有池中获取。
|
||||
// 关键:只在锁内取 Arc<Pool> 副本即放锁——try_get_conn 最长等 acquire_timeout,
|
||||
// 若持锁等待会把所有连接的请求串行化(一个慢池拖死全部连接)
|
||||
let existing = self.pools.lock().unwrap().get(name).map(|s| s.pool.clone());
|
||||
if let Some(pool) = existing {
|
||||
let conn = pool.try_get_conn(Duration::from_secs(acquire_timeout))
|
||||
.map_err(|e| acquire_timeout_err(&e, acquire_timeout, pool_max))?;
|
||||
// 放锁后再 touch(同上,避免长临界区)
|
||||
if let Some(state) = self.pools.lock().unwrap().get(name) {
|
||||
state.touch();
|
||||
}
|
||||
return Ok(conn);
|
||||
}
|
||||
|
||||
// 2. 没有则创建新池
|
||||
@@ -60,16 +93,32 @@ impl ConnectionManager {
|
||||
let pool = self.create_pool(&cfg)?;
|
||||
let arc_pool = Arc::new(pool);
|
||||
|
||||
// 3. 保存并返回连接
|
||||
{
|
||||
// 3. 保存并返回连接。双检:并发请求可能同时走到这里各自建池,
|
||||
// 以先插入者为准,后来者丢弃自己的池(否则池被覆盖、旧池连接泄漏)
|
||||
let pool = {
|
||||
let mut pools = self.pools.lock().unwrap();
|
||||
pools.insert(name.to_string(), PoolState {
|
||||
pool: arc_pool.clone(),
|
||||
last_used: Instant::now(),
|
||||
});
|
||||
}
|
||||
if let Some(state) = pools.get(name) {
|
||||
state.pool.clone()
|
||||
} else {
|
||||
pools.insert(name.to_string(), PoolState::new(arc_pool.clone()));
|
||||
arc_pool
|
||||
}
|
||||
};
|
||||
|
||||
Ok(arc_pool.get_conn()?)
|
||||
Ok(pool.try_get_conn(Duration::from_secs(acquire_timeout))
|
||||
.map_err(|e| acquire_timeout_err(&e, acquire_timeout, pool_max))?)
|
||||
}
|
||||
|
||||
/// 单语句执行超时(秒),handler 侧整体 deadline 用
|
||||
pub fn query_timeout_secs(&self) -> u64 {
|
||||
self.pool_config.query_timeout_secs
|
||||
}
|
||||
|
||||
/// 该连接名的池上限(用于池满错误提示)
|
||||
fn pool_max_of(&self, name: &str) -> usize {
|
||||
self.configs.lock().unwrap().get(name)
|
||||
.and_then(|c| c.max_connections)
|
||||
.unwrap_or(self.pool_config.default_max_connections)
|
||||
}
|
||||
|
||||
/// 创建连接池
|
||||
@@ -80,16 +129,23 @@ impl ConnectionManager {
|
||||
// 获取最大连接数 (单个配置 > 全局默认)
|
||||
let max_conn = cfg.max_connections.unwrap_or(self.pool_config.default_max_connections);
|
||||
|
||||
// 构建带连接池参数的选项
|
||||
// 传输层超时(第二道防线):连接建立 10s 上限;读写超时取 query_timeout,
|
||||
// 半开连接/网络黑洞时 socket 级先断,不让连接永久滞留池中
|
||||
let io_timeout = Duration::from_secs(self.pool_config.query_timeout_secs);
|
||||
let pool_opts = OptsBuilder::from_opts(opts)
|
||||
.tcp_connect_timeout(Some(Duration::from_secs(10)))
|
||||
.read_timeout(Some(io_timeout))
|
||||
.write_timeout(Some(io_timeout))
|
||||
.pool_opts(mysql::PoolOpts::new()
|
||||
.with_constraints(mysql::PoolConstraints::new(1, max_conn).unwrap()));
|
||||
|
||||
let pool = Pool::new(pool_opts)?;
|
||||
|
||||
// 测试连接
|
||||
let mut conn = pool.get_conn()?;
|
||||
conn.query::<String, _>("SELECT 1")?;
|
||||
{
|
||||
// 测试连接(作用域内释放,否则池上限 1 时该连接占满池导致调用方死等)
|
||||
let mut conn = pool.get_conn()?;
|
||||
conn.query::<String, _>("SELECT 1")?;
|
||||
}
|
||||
|
||||
println!("[LazyInit] ✓ Connected: {} (max_conn={})", cfg.name, max_conn);
|
||||
Ok(pool)
|
||||
@@ -118,7 +174,7 @@ impl ConnectionManager {
|
||||
let idle_timeout = Duration::from_secs(self.pool_config.idle_timeout_secs);
|
||||
|
||||
pools.retain(|name, state| {
|
||||
let elapsed = now.duration_since(state.last_used);
|
||||
let elapsed = state.last_used.lock().map(|lu| now.duration_since(*lu)).unwrap_or(Duration::ZERO);
|
||||
if elapsed > idle_timeout {
|
||||
println!("[Cleanup] Removing idle pool: {} (idle {}s)", name, elapsed.as_secs());
|
||||
return false;
|
||||
@@ -153,10 +209,7 @@ impl ConnectionManager {
|
||||
let arc_pool = Arc::new(pool);
|
||||
|
||||
// 保存
|
||||
self.pools.lock().unwrap().insert(name.clone(), PoolState {
|
||||
pool: arc_pool,
|
||||
last_used: Instant::now(),
|
||||
});
|
||||
self.pools.lock().unwrap().insert(name.clone(), PoolState::new(arc_pool));
|
||||
configs.insert(name.clone(), cfg);
|
||||
|
||||
println!("[Dynamic] ✓ Added: {}", name);
|
||||
@@ -171,3 +224,13 @@ pub struct ConnectionInfo {
|
||||
pub host: String,
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
/// 池满时 try_get_conn 的超时错误翻成 AcquireTimeout(其余保持原错)
|
||||
fn acquire_timeout_err(e: &mysql::Error, wait_secs: u64, pool_max: usize) -> anyhow::Error {
|
||||
let is_timeout = matches!(e, mysql::Error::DriverError(mysql::DriverError::Timeout));
|
||||
if is_timeout {
|
||||
anyhow::Error::new(AcquireTimeout { wait_secs, pool_max })
|
||||
} else {
|
||||
anyhow::anyhow!("{}", e)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use axum::{
|
||||
use mysql::{prelude::*, Value, Row as MysqlRow};
|
||||
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};
|
||||
@@ -134,8 +134,14 @@ pub async fn query(
|
||||
let sql = req.sql.clone();
|
||||
let conn_names = list_conn_names(manager);
|
||||
|
||||
let result = tokio::task::spawn_blocking(move || -> Result<QueryResult, (StatusCode, Json<ErrorResponse>)> {
|
||||
// 整体截止:获取连接(池满快速失败)+ 执行 总时长不超 query_timeout。
|
||||
// 超时放弃等待,阻塞线程随读写超时自行收束,HTTP 侧立即返回 408
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<QueryResult, (StatusCode, Json<ErrorResponse>)> {
|
||||
let mut conn = mgr.get_conn(&conn_name).map_err(|e| {
|
||||
if let Some(at) = e.downcast_ref::<crate::db::AcquireTimeout>() {
|
||||
return pool_busy_response(&at.to_string());
|
||||
}
|
||||
let usage = format!("Usage: POST /query {{\"conn\": \"connection_name\", \"sql\": \"SELECT ...\"}}\nAvailable connections: {}", conn_names);
|
||||
error_response_with_usage(&e.to_string(), &usage)
|
||||
})?;
|
||||
@@ -150,7 +156,16 @@ pub async fn query(
|
||||
data.push(row_to_strings(&row, columns.len()));
|
||||
}
|
||||
Ok(QueryResult { columns, rows: data })
|
||||
}).await.map_err(|_| error_response("Task join error"))?;
|
||||
});
|
||||
|
||||
let result = match tokio::time::timeout(deadline, handle).await {
|
||||
Ok(joined) => joined.map_err(|_| error_response("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/query", "http").with_conn(&req.conn).with_sql(&req.sql)
|
||||
.with_error(&format!("query timeout {}s", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let result = result.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/query", "http").with_conn(&req.conn).with_sql(&req.sql).with_error(&e.1.error));
|
||||
@@ -187,14 +202,27 @@ pub async fn execute(
|
||||
let sql = req.sql.clone();
|
||||
let conn_names = list_conn_names(manager);
|
||||
|
||||
let exec_result = tokio::task::spawn_blocking(move || -> Result<ExecResult, (StatusCode, Json<ErrorResponse>)> {
|
||||
let deadline = Duration::from_secs(manager.query_timeout_secs());
|
||||
let exec_handle = tokio::task::spawn_blocking(move || -> Result<ExecResult, (StatusCode, Json<ErrorResponse>)> {
|
||||
let mut conn = mgr.get_conn(&conn_name).map_err(|e| {
|
||||
if let Some(at) = e.downcast_ref::<crate::db::AcquireTimeout>() {
|
||||
return pool_busy_response(&at.to_string());
|
||||
}
|
||||
let usage = format!("Usage: POST /execute {{\"conn\": \"connection_name\", \"sql\": \"INSERT/UPDATE/DELETE ...\"}}\nAvailable connections: {}", conn_names);
|
||||
error_response_with_usage(&e.to_string(), &usage)
|
||||
})?;
|
||||
let result = conn.query_iter(&sql).map_err(|e| error_response(&e.to_string()))?;
|
||||
Ok(ExecResult { affected: result.affected_rows(), last_id: result.last_insert_id().unwrap_or(0) })
|
||||
}).await.map_err(|_| error_response("Task join error"))?;
|
||||
});
|
||||
|
||||
let exec_result = match tokio::time::timeout(deadline, exec_handle).await {
|
||||
Ok(joined) => joined.map_err(|_| error_response("Task join error"))?,
|
||||
Err(_) => {
|
||||
logger.log(&LogEntry::new("/execute", "http").with_conn(&req.conn).with_sql(&req.sql)
|
||||
.with_error(&format!("exec timeout {}s", deadline.as_secs())));
|
||||
return Err(query_timeout_response(deadline.as_secs()));
|
||||
}
|
||||
};
|
||||
|
||||
let exec_result = exec_result.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/execute", "http").with_conn(&req.conn).with_sql(&req.sql).with_error(&e.1.error));
|
||||
@@ -277,6 +305,16 @@ fn error_response(msg: &str) -> (StatusCode, Json<ErrorResponse>) {
|
||||
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg)))
|
||||
}
|
||||
|
||||
/// 池满快速失败:HTTP 429,明确告知调用方去重试而非等待
|
||||
fn pool_busy_response(msg: &str) -> (StatusCode, Json<ErrorResponse>) {
|
||||
(StatusCode::TOO_MANY_REQUESTS, Json(ErrorResponse::new(msg)))
|
||||
}
|
||||
|
||||
/// 语句执行超时:HTTP 408,提示调用方这是慢查询/DB 拥塞而非语法错
|
||||
fn query_timeout_response(secs: u64) -> (StatusCode, Json<ErrorResponse>) {
|
||||
(StatusCode::REQUEST_TIMEOUT, Json(ErrorResponse::new(&format!("查询超时(>{}s): 续跑或拆小查询", secs))))
|
||||
}
|
||||
|
||||
fn error_response_with_usage(msg: &str, usage: &str) -> (StatusCode, Json<ErrorResponse>) {
|
||||
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage)))
|
||||
}
|
||||
|
||||
+21
-2
@@ -63,13 +63,32 @@ enum Commands {
|
||||
Connections,
|
||||
}
|
||||
|
||||
// ⚠ 共享实现,修改需同步至 ssh/mongo/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::Cli { conn, sql, format, execute }) => {
|
||||
run_cli(&args.server, &conn, sql.as_deref(), &format, execute)
|
||||
@@ -78,7 +97,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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user