Skip to main content

cdk_sql_common/
pool.rs

1//! Very simple connection pool, to avoid an external dependency on r2d2 and other crates. If this
2//! endup work it can be re-used in other parts of the project and may be promoted to its own
3//! generic crate
4
5use std::fmt::Debug;
6use std::ops::{Deref, DerefMut};
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11#[cfg(feature = "prometheus")]
12use cdk_prometheus::metrics::METRICS;
13use tokio::sync::{OwnedSemaphorePermit, Semaphore};
14
15use crate::database::DatabaseConnector;
16
17/// Pool error
18#[derive(Debug, thiserror::Error)]
19pub enum Error<E>
20where
21    E: std::error::Error + Send + Sync + 'static,
22{
23    /// Mutex Poison Error
24    #[error("Internal: PoisonError")]
25    Poison,
26
27    /// Timeout error
28    #[error("Timed out waiting for a resource")]
29    Timeout,
30
31    /// Internal database error
32    #[error(transparent)]
33    Resource(#[from] E),
34}
35
36/// Configuration
37pub trait DatabaseConfig: Clone + Debug + Send + Sync {
38    /// Max resource sizes
39    fn max_size(&self) -> usize;
40
41    /// Default timeout
42    fn default_timeout(&self) -> Duration;
43}
44
45/// Trait to manage resources
46pub trait DatabasePool: Debug {
47    /// The resource to be pooled
48    type Connection: DatabaseConnector;
49
50    /// The configuration that is needed in order to create the resource
51    type Config: DatabaseConfig;
52
53    /// The error the resource may return when creating a new instance
54    type Error: Debug + std::error::Error + Send + Sync + 'static;
55
56    /// Creates a new resource with a given config.
57    ///
58    /// If `stale` is ever set to TRUE it is assumed the resource is no longer valid and it will be
59    /// dropped.
60    fn new_resource(
61        config: &Self::Config,
62        stale: Arc<AtomicBool>,
63        timeout: Duration,
64    ) -> Result<Self::Connection, Error<Self::Error>>;
65
66    /// The object is dropped
67    fn drop(_resource: Self::Connection) {}
68}
69
70/// Generic connection pool of resources R
71pub struct Pool<RM>
72where
73    RM: DatabasePool,
74{
75    config: RM::Config,
76    queue: Mutex<Vec<(Arc<AtomicBool>, RM::Connection)>>,
77    max_size: usize,
78    default_timeout: Duration,
79    semaphore: Arc<Semaphore>,
80}
81
82impl<RM> Debug for Pool<RM>
83where
84    RM: DatabasePool,
85{
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct("Pool")
88            .field("config", &self.config)
89            .field("max_size", &self.max_size)
90            .field("default_timeout", &self.default_timeout)
91            .field("available_permits", &self.semaphore.available_permits())
92            .finish()
93    }
94}
95
96/// The pooled resource
97pub struct PooledResource<RM>
98where
99    RM: DatabasePool,
100{
101    resource: Option<(Arc<AtomicBool>, RM::Connection)>,
102    pool: Arc<Pool<RM>>,
103    _permit: OwnedSemaphorePermit,
104    #[cfg(feature = "prometheus")]
105    start_time: std::time::Instant,
106}
107
108impl<RM> Debug for PooledResource<RM>
109where
110    RM: DatabasePool,
111{
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        write!(f, "Resource: {:?}", self.resource)
114    }
115}
116
117impl<RM> Drop for PooledResource<RM>
118where
119    RM: DatabasePool,
120{
121    fn drop(&mut self) {
122        if let Some(resource) = self.resource.take() {
123            let mut active_resource = self.pool.queue.lock().expect("active_resource");
124            active_resource.push(resource);
125
126            #[cfg(feature = "prometheus")]
127            {
128                METRICS.decrement_db_connections_active();
129
130                let duration = self.start_time.elapsed().as_secs_f64();
131
132                METRICS.record_db_operation(duration, "drop");
133            }
134
135            // The semaphore permit is dropped automatically after this,
136            // which wakes any async task waiting in `get()`.
137        }
138    }
139}
140
141impl<RM> Deref for PooledResource<RM>
142where
143    RM: DatabasePool,
144{
145    type Target = RM::Connection;
146
147    fn deref(&self) -> &Self::Target {
148        &self.resource.as_ref().expect("resource already dropped").1
149    }
150}
151
152impl<RM> DerefMut for PooledResource<RM>
153where
154    RM: DatabasePool,
155{
156    fn deref_mut(&mut self) -> &mut Self::Target {
157        &mut self.resource.as_mut().expect("resource already dropped").1
158    }
159}
160
161impl<RM> Pool<RM>
162where
163    RM: DatabasePool,
164{
165    /// Creates a new pool
166    pub fn new(config: RM::Config) -> Arc<Self> {
167        let max_size = config.max_size();
168        Arc::new(Self {
169            default_timeout: config.default_timeout(),
170            max_size,
171            config,
172            queue: Default::default(),
173            semaphore: Arc::new(Semaphore::new(max_size)),
174        })
175    }
176
177    /// Similar to get_timeout but uses the default timeout value.
178    #[inline(always)]
179    pub async fn get(self: &Arc<Self>) -> Result<PooledResource<RM>, Error<RM::Error>> {
180        self.get_timeout(self.default_timeout).await
181    }
182
183    /// Get a new resource or fail after timeout is reached.
184    ///
185    /// This function will return a free resource or create a new one if there is still room for it;
186    /// otherwise, it will asynchronously wait for a resource to be released for reuse.
187    #[inline(always)]
188    pub async fn get_timeout(
189        self: &Arc<Self>,
190        timeout: Duration,
191    ) -> Result<PooledResource<RM>, Error<RM::Error>> {
192        // Fast path: try to grab a permit without waiting.
193        let permit = match self.semaphore.clone().try_acquire_owned() {
194            Ok(permit) => permit,
195            Err(tokio::sync::TryAcquireError::Closed) => return Err(Error::Poison),
196            Err(tokio::sync::TryAcquireError::NoPermits) => {
197                // All permits are in use — wait asynchronously.  This yields
198                // the task instead of blocking the OS thread, preventing Tokio
199                // worker thread starvation.
200                tracing::debug!(
201                    "Pool exhausted (size: {}), waiting for a connection",
202                    self.max_size,
203                );
204                tokio::time::timeout(timeout, self.semaphore.clone().acquire_owned())
205                    .await
206                    .map_err(|_| Error::Timeout)?
207                    .map_err(|_| Error::Poison)?
208            }
209        };
210
211        #[cfg(feature = "prometheus")]
212        METRICS.increment_db_connections_active();
213
214        // Briefly lock the idle queue to try to pop a non-stale connection.
215        // This mutex is held for nanoseconds (just a Vec::pop).
216        {
217            let mut resources = match self.queue.lock() {
218                Ok(resources) => resources,
219                Err(_) => {
220                    #[cfg(feature = "prometheus")]
221                    METRICS.decrement_db_connections_active();
222                    return Err(Error::Poison);
223                }
224            };
225            while let Some((stale, resource)) = resources.pop() {
226                if !stale.load(Ordering::SeqCst) {
227                    return Ok(PooledResource {
228                        resource: Some((stale, resource)),
229                        pool: self.clone(),
230                        _permit: permit,
231                        #[cfg(feature = "prometheus")]
232                        start_time: std::time::Instant::now(),
233                    });
234                }
235                // Stale connection — drop it and keep looking.
236            }
237        }
238
239        // No idle connection available — create a new one.
240        // The semaphore already guarantees we won't exceed max_size.
241        let stale: Arc<AtomicBool> = Arc::new(false.into());
242        match RM::new_resource(&self.config, stale.clone(), timeout) {
243            Ok(new_resource) => Ok(PooledResource {
244                resource: Some((stale, new_resource)),
245                pool: self.clone(),
246                _permit: permit,
247                #[cfg(feature = "prometheus")]
248                start_time: std::time::Instant::now(),
249            }),
250            Err(e) => {
251                #[cfg(feature = "prometheus")]
252                METRICS.decrement_db_connections_active();
253
254                // Permit is dropped here, releasing the slot back to the semaphore.
255                Err(e)
256            }
257        }
258    }
259}
260
261impl<RM> Drop for Pool<RM>
262where
263    RM: DatabasePool,
264{
265    fn drop(&mut self) {
266        // Close the semaphore so no new acquisitions can succeed.
267        self.semaphore.close();
268
269        // Drain all idle connections.
270        if let Ok(mut resources) = self.queue.lock() {
271            while let Some(resource) = resources.pop() {
272                RM::drop(resource.1);
273            }
274        }
275    }
276}
277
278#[cfg(all(test, feature = "prometheus"))]
279mod tests {
280    use std::fmt;
281    use std::sync::atomic::AtomicBool;
282    use std::sync::Arc;
283    use std::time::Duration;
284
285    use cdk_common::database::Error as DatabaseError;
286    use cdk_prometheus::METRICS;
287
288    use super::{DatabaseConfig, DatabasePool, Error, Pool};
289    use crate::database::{DatabaseConnector, DatabaseExecutor, DatabaseTransaction};
290    use crate::stmt::{Column, Statement};
291
292    #[derive(Debug, Clone)]
293    struct TestConfig {
294        max_size: usize,
295        default_timeout: Duration,
296        fail_new_resource: bool,
297    }
298
299    impl DatabaseConfig for TestConfig {
300        fn max_size(&self) -> usize {
301            self.max_size
302        }
303
304        fn default_timeout(&self) -> Duration {
305            self.default_timeout
306        }
307    }
308
309    #[derive(Debug)]
310    struct TestResourceError;
311
312    impl fmt::Display for TestResourceError {
313        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314            f.write_str("test resource error")
315        }
316    }
317
318    impl std::error::Error for TestResourceError {}
319
320    #[derive(Debug)]
321    struct TestConnection;
322
323    #[async_trait::async_trait]
324    impl DatabaseExecutor for TestConnection {
325        fn name() -> &'static str {
326            "test"
327        }
328
329        async fn execute(&self, _statement: Statement) -> Result<usize, DatabaseError> {
330            Ok(0)
331        }
332
333        async fn fetch_one(
334            &self,
335            _statement: Statement,
336        ) -> Result<Option<Vec<Column>>, DatabaseError> {
337            Ok(None)
338        }
339
340        async fn fetch_all(
341            &self,
342            _statement: Statement,
343        ) -> Result<Vec<Vec<Column>>, DatabaseError> {
344            Ok(Vec::new())
345        }
346
347        async fn pluck(&self, _statement: Statement) -> Result<Option<Column>, DatabaseError> {
348            Ok(None)
349        }
350
351        async fn batch(&self, _statement: Statement) -> Result<(), DatabaseError> {
352            Ok(())
353        }
354    }
355
356    #[derive(Debug)]
357    struct TestTransaction;
358
359    #[async_trait::async_trait]
360    impl DatabaseTransaction<TestConnection> for TestTransaction {
361        async fn commit(_conn: &mut TestConnection) -> Result<(), DatabaseError> {
362            Ok(())
363        }
364
365        async fn begin(_conn: &mut TestConnection) -> Result<(), DatabaseError> {
366            Ok(())
367        }
368
369        async fn rollback(_conn: &mut TestConnection) -> Result<(), DatabaseError> {
370            Ok(())
371        }
372    }
373
374    impl DatabaseConnector for TestConnection {
375        type Transaction = TestTransaction;
376    }
377
378    #[derive(Debug)]
379    struct TestPool;
380
381    impl DatabasePool for TestPool {
382        type Connection = TestConnection;
383        type Config = TestConfig;
384        type Error = TestResourceError;
385
386        fn new_resource(
387            config: &Self::Config,
388            _stale: Arc<AtomicBool>,
389            _timeout: Duration,
390        ) -> Result<Self::Connection, Error<Self::Error>> {
391            if config.fail_new_resource {
392                Err(Error::Resource(TestResourceError))
393            } else {
394                Ok(TestConnection)
395            }
396        }
397    }
398
399    fn test_config(max_size: usize, fail_new_resource: bool) -> TestConfig {
400        TestConfig {
401            max_size,
402            default_timeout: Duration::from_millis(10),
403            fail_new_resource,
404        }
405    }
406
407    fn db_connections_active() -> f64 {
408        for family in METRICS.registry().gather() {
409            if family.name() != "cdk_db_connections_active" {
410                continue;
411            }
412
413            return family
414                .get_metric()
415                .first()
416                .expect("active connections metric should exist")
417                .get_gauge()
418                .value();
419        }
420
421        panic!("active connections metric should be registered");
422    }
423
424    #[tokio::test(flavor = "current_thread")]
425    async fn active_connections_gauge_tracks_current_checkout_and_drop_counts() {
426        let _lock = crate::metrics_test_lock::lock().await;
427        METRICS.set_db_connections_active(0);
428
429        let pool = Pool::<TestPool>::new(test_config(2, false));
430
431        let first = pool
432            .get()
433            .await
434            .expect("first resource should be checked out");
435        assert_eq!(db_connections_active(), 1.0);
436
437        let second = pool
438            .get()
439            .await
440            .expect("second resource should be checked out");
441        assert_eq!(db_connections_active(), 2.0);
442
443        drop(first);
444        assert_eq!(db_connections_active(), 1.0);
445
446        drop(second);
447        assert_eq!(db_connections_active(), 0.0);
448        assert_eq!(pool.semaphore.available_permits(), pool.max_size);
449    }
450
451    #[tokio::test(flavor = "current_thread")]
452    async fn active_connections_gauge_is_restored_when_resource_creation_fails() {
453        let _lock = crate::metrics_test_lock::lock().await;
454        METRICS.set_db_connections_active(0);
455
456        let pool = Pool::<TestPool>::new(test_config(1, true));
457        let result = pool.get().await;
458
459        assert!(matches!(result, Err(Error::Resource(_))));
460        assert_eq!(db_connections_active(), 0.0);
461        assert_eq!(pool.semaphore.available_permits(), pool.max_size);
462    }
463
464    #[tokio::test(flavor = "current_thread")]
465    async fn active_connections_gauge_aggregates_multiple_pools() {
466        let _lock = crate::metrics_test_lock::lock().await;
467        METRICS.set_db_connections_active(0);
468
469        let regular_pool = Pool::<TestPool>::new(test_config(1, false));
470        let second_pool = Pool::<TestPool>::new(test_config(1, false));
471        let regular = regular_pool.get().await.expect("regular resource");
472        let second = second_pool.get().await.expect("second resource");
473
474        assert_eq!(db_connections_active(), 2.0);
475
476        drop(regular);
477        drop(second);
478        assert_eq!(db_connections_active(), 0.0);
479    }
480}