Skip to main content

dm_pure/
pool.rs

1//! 连接池:复用连接避免重复握手(Web 服务场景必需)。
2//!
3//! ```no_run
4//! use dm_pure::{ConnectionPool, ClientConfig, Param};
5//!
6//! let mut pool = ConnectionPool::new(ClientConfig {
7//!     user: "SYSDBA".into(),
8//!     password: "password".into(),
9//!     ..Default::default()
10//! }, 2, 10)?;
11//! {
12//!     let mut conn = pool.acquire()?; // 借用/归还(Drop 自动归还)
13//!     let mut cur = conn.cursor();
14//!     cur.execute("SELECT 1", &[])?;
15//! }
16//! pool.close();
17//! # Ok::<(), dm_pure::DmError>(())
18//! ```
19
20use std::ops::{Deref, DerefMut};
21use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use crate::client::ClientConfig;
26use crate::{DmClient, Result};
27
28/// 已连接会话的封装。
29pub struct Connection {
30    pub(crate) client: DmClient,
31}
32
33impl Connection {
34    pub fn connect(cfg: ClientConfig) -> Result<Self> {
35        let mut client = DmClient::with_config(cfg);
36        client.connect()?;
37        Ok(Connection { client })
38    }
39
40    pub fn cursor(&mut self) -> crate::Cursor<'_> {
41        crate::Cursor::new(&mut self.client)
42    }
43
44    pub fn execute(&mut self, sql: &str, params: &[crate::Param]) -> Result<crate::ExecuteResult> {
45        self.client.execute(sql, params)
46    }
47
48    pub fn begin(&mut self) -> Result<()> {
49        self.client.begin()
50    }
51
52    pub fn commit(&mut self) -> Result<()> {
53        self.client.commit()
54    }
55
56    pub fn rollback(&mut self) -> Result<()> {
57        self.client.rollback()
58    }
59
60    pub fn close(&mut self) {
61        self.client.close();
62    }
63}
64
65/// 连接池。
66pub struct ConnectionPool {
67    cfg: ClientConfig,
68    idle: Mutex<Vec<(Connection, Instant)>>,
69    total: AtomicUsize,
70    max: usize,
71    idle_timeout: Duration,
72    closed: AtomicBool,
73    /// acquire 时跳过 SELECT 1 保活:坏连接延迟到首次使用时由 auto_reconnect 重连
74    lazy_check: bool,
75}
76
77impl ConnectionPool {
78    /// `min_connections`: 最小空闲连接数;`max_connections`: 最大连接数。
79    /// 预热时创建的连接失败会被忽略(服务器未启动时仍可创建池)。
80    pub fn new(cfg: ClientConfig, min_connections: usize, max_connections: usize) -> Result<Self> {
81        let pool = ConnectionPool {
82            cfg,
83            idle: Mutex::new(Vec::new()),
84            total: AtomicUsize::new(0),
85            max: max_connections.max(1),
86            idle_timeout: Duration::from_secs(300),
87            closed: AtomicBool::new(false),
88            lazy_check: false,
89        };
90        for _ in 0..min_connections.min(max_connections.max(1)) {
91            if let Ok(c) = pool.new_connection() {
92                pool.total.fetch_add(1, Ordering::SeqCst);
93                pool.idle.lock().unwrap().push((c, Instant::now()));
94            }
95        }
96        Ok(pool)
97    }
98
99    /// 开启/关闭惰性保活检查:`acquire` 跳过 SELECT 1,坏连接延迟到首次使用时
100    /// 由 auto_reconnect 自动重连(省一次往返;需 `ClientConfig.auto_reconnect = true`)。
101    /// 用法:`ConnectionPool::new(cfg, 1, 10)?.with_lazy_check(true)`
102    pub fn with_lazy_check(mut self, v: bool) -> Self {
103        self.lazy_check = v;
104        self
105    }
106
107    fn new_connection(&self) -> Result<Connection> {
108        Connection::connect(self.cfg.clone())
109    }
110
111    fn check_alive(&self, conn: &mut Connection) -> bool {
112        let mut cur = conn.cursor();
113        cur.execute("SELECT 1", &[]).map(|_| true).unwrap_or(false)
114    }
115
116    /// 借用一个连接(必要时新建;坏连接自动剔除重连)。
117    pub fn acquire(&self) -> Result<PooledConnection<'_>> {
118        let mut retry = 0;
119        loop {
120            if self.closed.load(Ordering::SeqCst) {
121                return Err(crate::DmError::arg("连接池已关闭"));
122            }
123            // 1. 优先取空闲连接
124            {
125                let mut idle = self.idle.lock().unwrap();
126                while let Some((mut conn, _)) = idle.pop() {
127                    if !self.lazy_check && !self.check_alive(&mut conn) {
128                        // 坏连接:关闭并重连
129                        conn.close();
130                        self.total.fetch_sub(1, Ordering::SeqCst);
131                        continue;
132                    }
133                    return Ok(PooledConnection { pool: self, conn: Some(conn) });
134                }
135            }
136            // 2. 未达上限则新建
137            let total = self.total.load(Ordering::SeqCst);
138            if total < self.max {
139                if self.total.compare_exchange(total, total + 1, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
140                    match self.new_connection() {
141                        Ok(conn) => return Ok(PooledConnection { pool: self, conn: Some(conn) }),
142                        Err(e) => {
143                            self.total.fetch_sub(1, Ordering::SeqCst);
144                            return Err(e);
145                        }
146                    }
147                }
148                continue;
149            }
150            // 3. 达到上限:等待空闲(简化实现:轮询等待)
151            if retry >= 600 {
152                // ~30s
153                return Err(crate::DmError::arg("连接池已满,等待超时"));
154            }
155            retry += 1;
156            std::thread::sleep(Duration::from_millis(50));
157        }
158    }
159
160    /// 归还连接;连接无效则丢弃。
161    pub fn release(&self, mut conn: Connection) {
162        if self.closed.load(Ordering::SeqCst) {
163            conn.close();
164            return;
165        }
166        let alive = self.check_alive(&mut conn);
167        if alive {
168            self.idle.lock().unwrap().push((conn, Instant::now()));
169        } else {
170            conn.close();
171            self.total.fetch_sub(1, Ordering::SeqCst);
172        }
173    }
174
175    /// 回收超时空闲连接。
176    pub fn reap_idle(&self) {
177        let now = Instant::now();
178        let mut keep = Vec::new();
179        {
180            let mut idle = self.idle.lock().unwrap();
181            for (mut c, last) in idle.drain(..) {
182                if now.duration_since(last) > self.idle_timeout {
183                    c.close();
184                    self.total.fetch_sub(1, Ordering::SeqCst);
185                } else {
186                    keep.push((c, last));
187                }
188            }
189        }
190        *self.idle.lock().unwrap() = keep;
191    }
192
193    pub fn close(&self) {
194        self.closed.store(true, Ordering::SeqCst);
195        let mut idle = self.idle.lock().unwrap();
196        for (mut c, _) in idle.drain(..) {
197            c.close();
198            self.total.fetch_sub(1, Ordering::SeqCst);
199        }
200    }
201
202    pub fn total(&self) -> usize {
203        self.total.load(Ordering::SeqCst)
204    }
205
206    pub fn idle_count(&self) -> usize {
207        self.idle.lock().unwrap().len()
208    }
209}
210
211/// 借出的连接:Drop 时自动归还连接池。
212pub struct PooledConnection<'a> {
213    pool: &'a ConnectionPool,
214    conn: Option<Connection>,
215}
216
217impl<'a> Deref for PooledConnection<'a> {
218    type Target = Connection;
219    fn deref(&self) -> &Connection {
220        self.conn.as_ref().unwrap()
221    }
222}
223
224impl<'a> DerefMut for PooledConnection<'a> {
225    fn deref_mut(&mut self) -> &mut Connection {
226        self.conn.as_mut().unwrap()
227    }
228}
229
230impl<'a> Drop for PooledConnection<'a> {
231    fn drop(&mut self) {
232        if let Some(conn) = self.conn.take() {
233            self.pool.release(conn);
234        }
235    }
236}
237
238/// 便于跨线程共享的池句柄。
239pub type SharedPool = Arc<ConnectionPool>;
240
241impl ConnectionPool {
242    /// 包装为 Arc 以便跨线程共享。
243    pub fn shared(self) -> Arc<Self> {
244        Arc::new(self)
245    }
246}