ch-database 0.1.0

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

use sqlx::MySqlPool;
use sqlx::migrate::{MigrateError, Migrator};
use tracing::debug;

/// Default time spent waiting for another migration runner to release its lock.
pub const DEFAULT_MIGRATION_LOCK_TIMEOUT: Duration = Duration::from_secs(30);

/// Errors returned while acquiring the migration lock or applying migrations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum MigrationError {
    /// The configured lock name is not supported by MariaDB/MySQL.
    #[error("migration lock name must contain between 1 and 64 bytes")]
    InvalidLockName,
    /// A dedicated connection for the advisory lock could not be acquired.
    #[error("failed to acquire migration connection: {source}")]
    AcquireConnection {
        /// Underlying database error.
        #[source]
        source: sqlx::Error,
    },
    /// The database rejected the lock query.
    #[error("failed to acquire migration lock: {source}")]
    AcquireLock {
        /// Underlying database error.
        #[source]
        source: sqlx::Error,
    },
    /// Another migration runner retained the lock until the timeout elapsed.
    #[error("migration lock was not acquired before the timeout elapsed")]
    LockUnavailable,
    /// SQLx could not apply the migration set.
    #[error("failed to apply database migrations: {source}")]
    Apply {
        /// Underlying migration error.
        #[source]
        source: MigrateError,
    },
    /// The database rejected the lock-release query.
    #[error("failed to release migration lock: {source}")]
    ReleaseLock {
        /// Underlying database error.
        #[source]
        source: sqlx::Error,
    },
    /// The database reported that the connection no longer owned the lock.
    #[error("migration lock could not be released because it was no longer owned")]
    LockNotOwned,
    /// Applying migrations and releasing their advisory lock both failed.
    #[error(
        "failed to apply database migrations ({migration}) and release the migration lock ({release})"
    )]
    ApplyAndRelease {
        /// Underlying migration error.
        migration: MigrateError,
        /// Underlying lock-release error.
        release: sqlx::Error,
    },
    /// Applying migrations failed and the database no longer reported lock ownership.
    #[error(
        "failed to apply database migrations ({migration}) and the migration lock was no longer owned"
    )]
    ApplyAndLockNotOwned {
        /// Underlying migration error.
        migration: MigrateError,
    },
}

/// Result type used by migration helpers.
pub type MigrationResult<T> = Result<T, MigrationError>;

/// Runs SQLx migrations with an advisory lock to avoid concurrent migration runs.
///
/// MariaDB/MySQL advisory locks are connection-scoped, so this helper acquires a lock on the pool
/// before running migrations and releases it afterwards.
pub async fn run_migrations_with_lock(
    pool: &MySqlPool,
    migrator: &Migrator,
    lock_name: &str,
) -> MigrationResult<()> {
    run_migrations_with_lock_timeout(pool, migrator, lock_name, DEFAULT_MIGRATION_LOCK_TIMEOUT)
        .await
}

/// Runs SQLx migrations while waiting at most `lock_timeout` for the advisory lock.
pub async fn run_migrations_with_lock_timeout(
    pool: &MySqlPool,
    migrator: &Migrator,
    lock_name: &str,
    lock_timeout: Duration,
) -> MigrationResult<()> {
    let lock_name = lock_name.trim();
    if lock_name.is_empty() {
        debug!("running database migrations without an advisory lock");
        return migrator
            .run(pool)
            .await
            .map_err(|source| MigrationError::Apply { source });
    }
    if lock_name.len() > 64 {
        return Err(MigrationError::InvalidLockName);
    }

    let mut conn = pool
        .acquire()
        .await
        .map_err(|source| MigrationError::AcquireConnection { source })?;

    let timeout_seconds = lock_timeout.as_secs().min(i64::MAX as u64) as i64;
    let acquired = sqlx::query_scalar::<_, Option<i64>>("SELECT GET_LOCK(?, ?)")
        .bind(lock_name)
        .bind(timeout_seconds)
        .fetch_one(&mut *conn)
        .await
        .map_err(|source| MigrationError::AcquireLock { source })?;
    if acquired != Some(1) {
        return Err(MigrationError::LockUnavailable);
    }

    let migration_result = migrator.run(pool).await;
    let release_result = sqlx::query_scalar::<_, Option<i64>>("SELECT RELEASE_LOCK(?)")
        .bind(lock_name)
        .fetch_one(&mut *conn)
        .await;

    match (migration_result, release_result) {
        (Ok(()), Ok(Some(1))) => Ok(()),
        (Ok(()), Ok(_)) => Err(MigrationError::LockNotOwned),
        (Ok(()), Err(source)) => Err(MigrationError::ReleaseLock { source }),
        (Err(source), Ok(Some(1))) => Err(MigrationError::Apply { source }),
        (Err(migration), Ok(_)) => Err(MigrationError::ApplyAndLockNotOwned { migration }),
        (Err(migration), Err(release)) => {
            Err(MigrationError::ApplyAndRelease { migration, release })
        }
    }
}