zino_orm/
pool.rs

1use super::DatabasePool;
2use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
3
4/// A database connection pool with metadata.
5#[derive(Debug)]
6pub struct ConnectionPool<P = DatabasePool> {
7    /// Name.
8    name: &'static str,
9    /// Database.
10    database: &'static str,
11    /// Pool.
12    pool: P,
13    /// Availability.
14    available: AtomicBool,
15    /// Missed count.
16    missed_count: AtomicUsize,
17}
18
19impl<P> ConnectionPool<P> {
20    /// Creates a new instance.
21    #[inline]
22    pub fn new(name: &'static str, database: &'static str, pool: P) -> Self {
23        Self {
24            name,
25            database,
26            pool,
27            available: AtomicBool::new(true),
28            missed_count: AtomicUsize::new(0),
29        }
30    }
31
32    /// Returns `true` if the connection pool is available.
33    #[inline]
34    pub fn is_available(&self) -> bool {
35        self.available.load(Relaxed)
36    }
37
38    /// Stores the value into the availability of the connection pool.
39    pub fn store_availability(&self, available: bool) {
40        self.available.store(available, Relaxed);
41        if available {
42            self.reset_missed_count();
43        } else {
44            self.increment_missed_count();
45        }
46    }
47
48    /// Returns the number of missed count.
49    #[inline]
50    pub fn missed_count(&self) -> usize {
51        self.missed_count.load(Relaxed)
52    }
53
54    /// Increments the missed count by 1.
55    #[inline]
56    pub fn increment_missed_count(&self) {
57        self.missed_count.fetch_add(1, Relaxed);
58    }
59
60    /// Resets the number of missed count.
61    #[inline]
62    pub fn reset_missed_count(&self) {
63        self.missed_count.store(0, Relaxed);
64    }
65
66    /// Returns `true` if the connection pool is retryable to connect.
67    #[inline]
68    pub fn is_retryable(&self) -> bool {
69        let missed_count = self.missed_count();
70        missed_count > 2 && missed_count.is_power_of_two()
71    }
72
73    /// Returns the name.
74    #[inline]
75    pub fn name(&self) -> &'static str {
76        self.name
77    }
78
79    /// Returns the database.
80    #[inline]
81    pub fn database(&self) -> &'static str {
82        self.database
83    }
84
85    /// Returns a reference to the pool.
86    #[inline]
87    pub fn pool(&self) -> &P {
88        &self.pool
89    }
90}