ch-database 0.1.0

Database and object storage primitives for SQLx, SpacetimeDB, and S3
Documentation
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;

use anyhow::{Context, Result};
use sqlx::mysql::MySqlPoolOptions;
use sqlx::{MySql, MySqlPool, Transaction};
use thiserror::Error;
use tokio::time::sleep;
use tracing::{debug, warn};

use super::url::{MySqlUrlError, normalize_mysql_url, redact_mysql_url};

/// Errors returned while opening or probing a MySQL connection pool.
#[derive(Debug, Error)]
pub enum MySqlConnectionError {
    /// The connection URL is invalid.
    #[error(transparent)]
    Url(#[from] MySqlUrlError),
    /// At least one connection must be allowed.
    #[error("max_connections must be greater than zero")]
    InvalidMaxConnections,
    /// At least one connection attempt must be allowed.
    #[error("max_attempts must be greater than zero")]
    InvalidMaxAttempts,
    /// All configured connection attempts failed.
    #[error("failed to connect to the database after {attempts} attempt(s)")]
    Connect {
        /// Number of attempted connections.
        attempts: u32,
        /// Last error reported by SQLx.
        #[source]
        source: sqlx::Error,
    },
}

/// Result returned by MySQL pool lifecycle helpers.
pub type MySqlConnectionResult<T> = std::result::Result<T, MySqlConnectionError>;

/// Connection settings used when building SQLx MySQL pools.
#[derive(Debug, Clone)]
pub struct MySqlPoolSettings {
    /// Maximum number of connections maintained by the pool.
    pub max_connections: u32,
    /// Number of connection attempts before failing.
    pub max_attempts: u32,
    /// Delay between connection attempts.
    pub retry_delay: Duration,
}

impl Default for MySqlPoolSettings {
    fn default() -> Self {
        Self {
            max_connections: 5,
            max_attempts: 5,
            retry_delay: Duration::from_secs(4),
        }
    }
}

/// Creates a new SQLx pool from a MySQL connection URL with retry/backoff.
pub async fn connect_mysql_pool(
    url: &str,
    settings: &MySqlPoolSettings,
) -> MySqlConnectionResult<MySqlPool> {
    if settings.max_connections == 0 {
        return Err(MySqlConnectionError::InvalidMaxConnections);
    }
    if settings.max_attempts == 0 {
        return Err(MySqlConnectionError::InvalidMaxAttempts);
    }
    let normalized = normalize_mysql_url(url)?;
    let redacted = redact_mysql_url(&normalized);

    let mut attempt = 0;
    loop {
        attempt += 1;

        match MySqlPoolOptions::new()
            .max_connections(settings.max_connections)
            .connect(&normalized)
            .await
        {
            Ok(pool) => return Ok(pool),
            Err(error) if attempt < settings.max_attempts => {
                warn!(
                    attempt,
                    max_attempts = settings.max_attempts,
                    url = %redacted,
                    retry_delay_secs = settings.retry_delay.as_secs(),
                    error = %error,
                    "failed to connect to database, retrying"
                );
                sleep(settings.retry_delay).await;
            }
            Err(error) => {
                return Err(MySqlConnectionError::Connect {
                    attempts: attempt,
                    source: error,
                });
            }
        }
    }
}

/// Runs the given async function inside a SQL transaction.
pub type TransactionFuture<'c, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'c>>;

/// Runs the given async function inside a SQL transaction.
pub async fn transaction<'p, T, F>(pool: &'p MySqlPool, f: F) -> Result<T>
where
    T: Send + 'static,
    F: for<'c> FnOnce(&'c mut Transaction<'p, MySql>) -> TransactionFuture<'c, T>,
{
    debug!("starting database transaction");
    let mut tx = pool.begin().await.context("failed to begin transaction")?;
    let result = f(&mut tx).await;

    match result {
        Ok(value) => {
            tx.commit().await.context("failed to commit transaction")?;
            Ok(value)
        }
        Err(error) => {
            tx.rollback()
                .await
                .context("failed to rollback transaction")?;
            Err(error)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{MySqlConnectionError, MySqlPoolSettings, connect_mysql_pool};

    #[tokio::test]
    async fn rejects_zero_pool_limits_before_connecting() {
        let settings = MySqlPoolSettings {
            max_connections: 0,
            ..MySqlPoolSettings::default()
        };
        assert!(matches!(
            connect_mysql_pool("mysql://localhost/example", &settings).await,
            Err(MySqlConnectionError::InvalidMaxConnections)
        ));

        let settings = MySqlPoolSettings {
            max_connections: 1,
            max_attempts: 0,
            ..MySqlPoolSettings::default()
        };
        assert!(matches!(
            connect_mysql_pool("mysql://localhost/example", &settings).await,
            Err(MySqlConnectionError::InvalidMaxAttempts)
        ));
    }
}