Skip to main content

ch_database/mariadb/
pool.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::time::Duration;
4
5use anyhow::{Context, Result};
6use sqlx::mysql::MySqlPoolOptions;
7use sqlx::{ConnectOptions, MySql, MySqlPool, Transaction};
8use thiserror::Error;
9use tokio::time::sleep;
10use tracing::{debug, warn};
11
12use super::url::{MySqlUrlError, parse_mysql_url};
13
14/// Errors returned while opening or probing a MySQL connection pool.
15#[derive(Debug, Error)]
16pub enum MySqlConnectionError {
17    /// The connection URL is invalid.
18    #[error(transparent)]
19    Url(#[from] MySqlUrlError),
20    /// At least one connection must be allowed.
21    #[error("max_connections must be greater than zero")]
22    InvalidMaxConnections,
23    /// At least one connection attempt must be allowed.
24    #[error("max_attempts must be greater than zero")]
25    InvalidMaxAttempts,
26    /// All configured connection attempts failed.
27    #[error("failed to connect to the database after {attempts} attempt(s)")]
28    Connect {
29        /// Number of attempted connections.
30        attempts: u32,
31        /// Last error reported by SQLx.
32        #[source]
33        source: sqlx::Error,
34    },
35}
36
37/// Result returned by MySQL pool lifecycle helpers.
38pub type MySqlConnectionResult<T> = std::result::Result<T, MySqlConnectionError>;
39
40/// Connection settings used when building SQLx MySQL pools.
41#[derive(Debug, Clone)]
42pub struct MySqlPoolSettings {
43    /// Maximum number of connections maintained by the pool.
44    pub max_connections: u32,
45    /// Number of connection attempts before failing.
46    pub max_attempts: u32,
47    /// Delay between connection attempts.
48    pub retry_delay: Duration,
49}
50
51impl Default for MySqlPoolSettings {
52    fn default() -> Self {
53        Self {
54            max_connections: 5,
55            max_attempts: 5,
56            retry_delay: Duration::from_secs(4),
57        }
58    }
59}
60
61/// Creates a new SQLx pool from a validated MySQL URL with retries.
62///
63/// SQLx decodes URL credentials directly. For raw, separate credentials use
64/// [`connect_mysql_pool_with_options`] instead of assembling a URL.
65pub async fn connect_mysql_pool(
66    url: &str,
67    settings: &MySqlPoolSettings,
68) -> MySqlConnectionResult<MySqlPool> {
69    if settings.max_connections == 0 {
70        return Err(MySqlConnectionError::InvalidMaxConnections);
71    }
72    if settings.max_attempts == 0 {
73        return Err(MySqlConnectionError::InvalidMaxAttempts);
74    }
75    let parsed = parse_mysql_url(url)?;
76    let options = sqlx::mysql::MySqlConnectOptions::from_url(&parsed).map_err(|source| {
77        MySqlConnectionError::Connect {
78            attempts: 0,
79            source,
80        }
81    })?;
82    connect_mysql_pool_with_options(options, settings).await
83}
84
85/// Opens a pool from validated SQLx options with the shared retry policy.
86pub async fn connect_mysql_pool_with_options(
87    options: sqlx::mysql::MySqlConnectOptions,
88    settings: &MySqlPoolSettings,
89) -> MySqlConnectionResult<MySqlPool> {
90    if settings.max_connections == 0 {
91        return Err(MySqlConnectionError::InvalidMaxConnections);
92    }
93    if settings.max_attempts == 0 {
94        return Err(MySqlConnectionError::InvalidMaxAttempts);
95    }
96    let mut attempt = 0;
97    loop {
98        attempt += 1;
99
100        match MySqlPoolOptions::new()
101            .max_connections(settings.max_connections)
102            .connect_with(options.clone())
103            .await
104        {
105            Ok(pool) => return Ok(pool),
106            Err(error) if attempt < settings.max_attempts => {
107                warn!(
108                    attempt,
109                    max_attempts = settings.max_attempts,
110                    retry_delay_secs = settings.retry_delay.as_secs(),
111                    error = %error,
112                    "failed to connect to database, retrying"
113                );
114                sleep(settings.retry_delay).await;
115            }
116            Err(error) => {
117                return Err(MySqlConnectionError::Connect {
118                    attempts: attempt,
119                    source: error,
120                });
121            }
122        }
123    }
124}
125
126/// Runs the given async function inside a SQL transaction.
127pub type TransactionFuture<'c, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'c>>;
128
129/// Runs the given async function inside a SQL transaction.
130///
131/// If the operation fails, rollback errors are logged and the original operation
132/// error is returned.
133pub async fn transaction<'p, T, F>(pool: &'p MySqlPool, f: F) -> Result<T>
134where
135    T: Send + 'static,
136    F: for<'c> FnOnce(&'c mut Transaction<'p, MySql>) -> TransactionFuture<'c, T>,
137{
138    debug!("starting database transaction");
139    let mut tx = pool.begin().await.context("failed to begin transaction")?;
140    let result = f(&mut tx).await;
141
142    match result {
143        Ok(value) => {
144            tx.commit().await.context("failed to commit transaction")?;
145            Ok(value)
146        }
147        Err(error) => {
148            if let Err(rollback_error) = tx.rollback().await {
149                warn!(error = %rollback_error, "failed to rollback transaction");
150            }
151            Err(error)
152        }
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::{MySqlConnectionError, MySqlPoolSettings, connect_mysql_pool};
159
160    #[test]
161    fn sqlx_parses_credentials_without_a_normalization_pass() {
162        use crate::mariadb::url::{normalize_mysql_url, parse_mysql_url};
163        use sqlx::{ConnectOptions, mysql::MySqlConnectOptions};
164
165        for raw in [
166            "mysql://user:p@ss word@localhost/db",
167            "mysql://user:päss%20%zz@localhost/db",
168            "mysql://user:p%2Fa%3Fb%23c%25@localhost/db?ssl-mode=REQUIRED&charset=utf8mb4",
169            "mysql://user@name:pass@localhost:3307/db",
170        ] {
171            let direct = MySqlConnectOptions::from_url(&parse_mysql_url(raw).unwrap()).unwrap();
172            let normalized: MySqlConnectOptions =
173                normalize_mysql_url(raw).unwrap().parse().unwrap();
174            assert_eq!(direct.to_url_lossy(), normalized.to_url_lossy());
175        }
176    }
177
178    #[tokio::test]
179    async fn rejects_zero_pool_limits_before_connecting() {
180        let settings = MySqlPoolSettings {
181            max_connections: 0,
182            ..MySqlPoolSettings::default()
183        };
184        assert!(matches!(
185            connect_mysql_pool("mysql://localhost/example", &settings).await,
186            Err(MySqlConnectionError::InvalidMaxConnections)
187        ));
188
189        let settings = MySqlPoolSettings {
190            max_connections: 1,
191            max_attempts: 0,
192            ..MySqlPoolSettings::default()
193        };
194        assert!(matches!(
195            connect_mysql_pool("mysql://localhost/example", &settings).await,
196            Err(MySqlConnectionError::InvalidMaxAttempts)
197        ));
198    }
199}