laravel-nestedset 0.2.2

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! The locks a write holds on its tree until its transaction ends.
//!
//! PostgreSQL takes transaction-scoped advisory locks and SQLite has one writer at a time. MySQL
//! and MariaDB have neither, and their row locks in REPEATABLE READ also lock the gaps of the
//! index next to a tree, so writers in neighbouring trees deadlock. There a write takes a named
//! lock per tree with `GET_LOCK`, on a session of the package's own small pool, and releases it
//! once the outermost transaction commits; its reads and writes then go by primary key, which
//! locks rows without gaps.

use laravel::db::{self, AnyTransaction, Builder, Condition, Driver, Values, col};
use laravel::model::__query;

use crate::node::NestedSet;
use crate::scope::Scope;

/// Rows per `UPDATE` or `DELETE` by primary key.
const BATCH: usize = 1_000;

/// The locks of one write.
pub(crate) struct Locks {
    driver: Driver,
    /// Whether the write runs inside a transaction of the caller's, whose snapshot may be older
    /// than the locks.
    nested: bool,
    #[cfg(feature = "mysql")]
    session: Option<mysql::Session>,
}

impl Locks {
    /// Starts the locks of a write in `tx`.
    #[cfg_attr(
        not(feature = "mysql"),
        allow(
            clippy::unused_async,
            clippy::unused_async_trait_impl,
            clippy::extra_unused_type_parameters
        )
    )]
    pub(crate) async fn open<M: NestedSet>(tx: &AnyTransaction<'_>) -> laravel::Result<Self> {
        let driver = tx.driver();
        Ok(Self {
            driver,
            nested: tx.level() > 1,
            #[cfg(feature = "mysql")]
            session: if is_mysql(driver) {
                Some(mysql::Session::open::<M>().await?)
            } else {
                None
            },
        })
    }

    /// The database the write runs on.
    pub(crate) fn driver(&self) -> Driver {
        self.driver
    }

    /// Whether the rows go by primary key: on MySQL and MariaDB.
    fn by_key(&self) -> bool {
        is_mysql(self.driver)
    }

    /// Makes every other root creation and move to root in the table wait until this transaction
    /// ends.
    pub(crate) async fn roots<M: NestedSet>(&mut self, tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
        let name = format!("{}|roots", M::META.table);
        if self.named(&name).await? {
            return Ok(());
        }
        match self.driver {
            Driver::Postgres => advisory(tx, &name).await,
            Driver::MySql | Driver::MariaDb => {
                __query::<M>().filter(M::where_root()).lock_for_update().get().await?;
                Ok(())
            }
            Driver::Sqlite => take_write_lock::<M>().await,
        }
    }

    /// Makes every other write to the tree of `scope` wait until this transaction ends.
    pub(crate) async fn tree<M: NestedSet>(
        &mut self,
        tx: &mut AnyTransaction<'_>,
        scope: &Scope<M>,
    ) -> laravel::Result<()> {
        let name = scope.lock_name();
        if self.named(&name).await? {
            return Ok(());
        }
        match self.driver {
            Driver::Postgres => advisory(tx, &name).await,
            Driver::MySql | Driver::MariaDb => {
                // Without the `mysql` feature: the roots' rows, and the gaps next to them.
                scope
                    .apply(__query::<M>())
                    .filter(M::where_root())
                    .lock_for_update()
                    .get()
                    .await?;
                Ok(())
            }
            Driver::Sqlite => take_write_lock::<M>().await,
        }
    }

    /// Takes the named lock `name` when this write uses named locks.
    #[cfg_attr(not(feature = "mysql"), allow(clippy::unused_async, clippy::unused_async_trait_impl))]
    async fn named(&mut self, name: &str) -> laravel::Result<bool> {
        #[cfg(feature = "mysql")]
        if let Some(session) = &mut self.session {
            session.lock(name).await?;
            return Ok(true);
        }
        let _ = name;
        Ok(false)
    }

    /// Releases the named locks once the outermost transaction commits. When it rolls back
    /// instead, the session closes, and the server releases them.
    #[cfg_attr(not(feature = "mysql"), allow(clippy::unused_async, clippy::unused_async_trait_impl))]
    pub(crate) async fn release_after_commit(self, tx: &AnyTransaction<'_>) -> laravel::Result<()> {
        #[cfg(feature = "mysql")]
        if let Some(session) = self.session {
            tx.after_commit(move || session.release()).await?;
        }
        let _ = tx;
        Ok(())
    }

    /// `query`, reading the latest committed rows: inside a caller's transaction on MySQL, a
    /// plain read could see a snapshot from before the locks.
    pub(crate) fn fresh<M: NestedSet>(&self, query: Builder<M>) -> Builder<M> {
        if self.by_key() && self.nested {
            query.lock_for_update()
        } else {
            query
        }
    }

    /// `query`, reading the latest committed rows on MySQL even outside a caller's transaction:
    /// for a read that follows other reads of the same transaction made before the locks.
    pub(crate) fn latest<M: NestedSet>(&self, query: Builder<M>) -> Builder<M> {
        if self.by_key() { query.lock_for_update() } else { query }
    }

    /// Updates the rows of `scope` that `condition` matches. On MySQL it finds their keys first
    /// and updates by key, so the update locks just those rows.
    pub(crate) async fn update<M: NestedSet>(
        &self,
        scope: &Scope<M>,
        condition: Condition,
        values: Values,
    ) -> laravel::Result<()> {
        if !self.by_key() {
            scope
                .apply(__query::<M>())
                .filter(condition)
                .update_values(values)
                .await?;
            return Ok(());
        }
        for chunk in self.keys(scope, condition).await?.chunks(BATCH) {
            __query::<M>()
                .filter(M::META.key.is_in(chunk.to_vec()))
                .update_values(values.clone())
                .await?;
        }
        Ok(())
    }

    /// Deletes the rows of `scope` that `condition` matches, by key on MySQL. Returns how many.
    pub(crate) async fn delete<M: NestedSet>(&self, scope: &Scope<M>, condition: Condition) -> laravel::Result<u64> {
        if !self.by_key() {
            return scope.apply(__query::<M>()).filter(condition).delete().await;
        }
        let mut deleted = 0;
        for chunk in self.keys(scope, condition).await?.chunks(BATCH) {
            deleted += __query::<M>()
                .filter(M::META.key.is_in(chunk.to_vec()))
                .delete()
                .await?;
        }
        Ok(deleted)
    }

    async fn keys<M: NestedSet>(&self, scope: &Scope<M>, condition: Condition) -> laravel::Result<Vec<M::Key>> {
        self.fresh(scope.apply(__query::<M>()).filter(condition))
            .pluck(M::META.key)
            .await
    }
}

fn is_mysql(driver: Driver) -> bool {
    matches!(driver, Driver::MySql | Driver::MariaDb)
}

async fn advisory(tx: &mut AnyTransaction<'_>, name: &str) -> laravel::Result<()> {
    db::query!(tx, "SELECT pg_advisory_xact_lock(hashtext({name}))")
        .select()
        .await?;
    Ok(())
}

/// SQLite has one writer at a time: take the write lock now, before reading any bound.
async fn take_write_lock<M: NestedSet>() -> laravel::Result<()> {
    let name = M::lft_column().name();
    __query::<M>()
        .filter(db::raw!("1 = 0"))
        .update_values(Values::new().set(name, col(name)))
        .await?;
    Ok(())
}

#[cfg(feature = "mysql")]
mod mysql {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};

    use laravel::config::database::{ConnectionConfig, Database, Source};
    use laravel::db::sqlx::pool::PoolConnection;
    use laravel::db::sqlx::{self, MySql};
    use laravel::db::{AnyConnection, DatabaseManager};

    use crate::node::NestedSet;
    use crate::ops::connection;

    /// Connections the package's pools hold at most: a write waits here for a session, not on
    /// the application's pool, so writers waiting for a lock never starve the transactions that
    /// hold it.
    const SESSIONS: u32 = 16;

    /// A session that holds named locks, from a pool kept per database URL.
    pub(super) struct Session {
        connection: Option<PoolConnection<MySql>>,
    }

    impl Session {
        pub(super) async fn open<M: NestedSet>() -> laravel::Result<Self> {
            let pool = pool(&connection::<M>()?)?;
            let connection = pool.typed::<MySql>()?.acquire().await?;
            Ok(Self {
                connection: Some(connection),
            })
        }

        /// Waits for the lock `name`, as long as `InnoDB` waits for a row lock.
        pub(super) async fn lock(&mut self, name: &str) -> laravel::Result<()> {
            let connection = self.connection.as_mut().expect("a session is open until it's released");
            let locked: Option<i64> =
                sqlx::query_scalar("SELECT GET_LOCK(CONCAT('nestedset:', SHA1(?)), @@innodb_lock_wait_timeout)")
                    .bind(name)
                    .fetch_one(&mut **connection)
                    .await?;
            if locked == Some(1) {
                return Ok(());
            }
            Err(laravel::Error::msg(format!(
                "Timed out waiting for the nested set lock on `{name}`."
            )))
        }

        /// Releases every lock and returns the session to its pool. A session that can't release
        /// them closes instead, which releases them too.
        pub(super) async fn release(mut self) -> laravel::Result<()> {
            if let Some(mut connection) = self.connection.take() {
                let released = sqlx::query("SELECT RELEASE_ALL_LOCKS()")
                    .execute(&mut *connection)
                    .await;
                if released.is_err() {
                    drop(connection.detach());
                }
            }
            Ok(())
        }
    }

    impl Drop for Session {
        /// A session dropped with its locks, after an error or a rollback, closes: the server then
        /// releases its locks, and no pooled session keeps one.
        fn drop(&mut self) {
            if let Some(connection) = self.connection.take() {
                drop(connection.detach());
            }
        }
    }

    /// The package's pool for the database `connection` points at.
    fn pool(connection: &AnyConnection) -> laravel::Result<AnyConnection> {
        static POOLS: OnceLock<Mutex<HashMap<String, AnyConnection>>> = OnceLock::new();
        let configuration = connection.configuration();
        let key = match &configuration.source {
            Source::Url(url) => url.clone(),
            _ => connection.name().to_owned(),
        };
        let pools = POOLS.get_or_init(|| Mutex::new(HashMap::new()));
        let mut pools = pools.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(pool) = pools.get(&key) {
            return Ok(pool.clone());
        }
        let mut config: ConnectionConfig = configuration.clone();
        config.max_connections = SESSIONS;
        config.init_sql.clear();
        let pool = DatabaseManager::new(&Database::default(), std::env::temp_dir()).connect(config)?;
        pools.insert(key, pool.clone());
        Ok(pool)
    }
}