laravel-nestedset 0.2.3

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! 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: &mut 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>(tx).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::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
    use std::time::{Duration, Instant};

    use laravel::config::database::{ConnectionConfig, Database, Source};
    use laravel::db::sqlx::pool::PoolConnection;
    use laravel::db::sqlx::{self, MySql};
    use laravel::db::{self, AnyConnection, AnyTransaction, 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;

    /// How long a write waits between two tries of a lock that another session holds.
    const RETRY: Duration = Duration::from_millis(20);

    /// A session holding named locks for the writes on one transaction connection. `GET_LOCK` is
    /// re-entrant on a session, so two writes in one transaction share the locks instead of
    /// waiting for each other until the commit that would release them.
    struct Shared {
        connection: tokio::sync::Mutex<Option<PoolConnection<MySql>>>,
        /// How long `InnoDB` waits for a row lock: a lock wait gives up after as long.
        timeout: Duration,
    }

    /// The writes using each shared session, by the transaction connection's id.
    type Registry = HashMap<i64, (Arc<Shared>, usize)>;

    fn registry() -> MutexGuard<'static, Registry> {
        static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
        REGISTRY
            .get_or_init(|| Mutex::new(HashMap::new()))
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// One write's use of a shared session, with the locks it took. It releases exactly those,
    /// so another write sharing the session keeps its own, even a write of the next transaction
    /// on the same connection that starts before this one's release has run.
    pub(super) struct Session {
        key: i64,
        shared: Arc<Shared>,
        held: Vec<String>,
        released: bool,
    }

    impl Session {
        pub(super) async fn open<M: NestedSet>(tx: &mut AnyTransaction<'_>) -> laravel::Result<Self> {
            let key: i64 = db::query!(tx, "SELECT CAST(CONNECTION_ID() AS SIGNED)")
                .scalar()
                .await?
                .unwrap_or_default();
            if let Some(shared) = join(key) {
                return Ok(Self::new(key, shared));
            }
            let pool = pool(&connection::<M>()?)?;
            let mut session = pool.typed::<MySql>()?.acquire().await?;
            let seconds: i64 = sqlx::query_scalar("SELECT CAST(@@innodb_lock_wait_timeout AS SIGNED)")
                .fetch_one(&mut *session)
                .await?;
            let fresh = Arc::new(Shared {
                connection: tokio::sync::Mutex::new(Some(session)),
                timeout: Duration::from_secs(u64::try_from(seconds).unwrap_or(50)),
            });
            let mut registry = registry();
            // Another write on this connection may have got there first: then share its session,
            // and this one goes back to the pool unused.
            let shared = if let Some((shared, users)) = registry.get_mut(&key) {
                *users += 1;
                Arc::clone(shared)
            } else {
                registry.insert(key, (Arc::clone(&fresh), 1));
                fresh
            };
            drop(registry);
            Ok(Self::new(key, shared))
        }

        fn new(key: i64, shared: Arc<Shared>) -> Self {
            Self {
                key,
                shared,
                held: Vec::new(),
                released: false,
            }
        }

        /// Takes the lock `name`, trying again while another session holds it, as long as
        /// `InnoDB` waits for a row lock. The shared session is free between the tries, so a
        /// write waiting here never blocks a release on the same session.
        pub(super) async fn lock(&mut self, name: &str) -> laravel::Result<()> {
            let deadline = Instant::now() + self.shared.timeout;
            loop {
                let locked: Option<i64> = {
                    let mut connection = self.shared.connection.lock().await;
                    let Some(connection) = connection.as_mut() else {
                        return Err(laravel::Error::msg("The nested set lock session closed."));
                    };
                    sqlx::query_scalar("SELECT GET_LOCK(CONCAT('nestedset:', SHA1(?)), 0)")
                        .bind(name)
                        .fetch_one(&mut **connection)
                        .await?
                };
                if locked == Some(1) {
                    self.held.push(name.to_owned());
                    return Ok(());
                }
                if Instant::now() >= deadline {
                    return Err(laravel::Error::msg(format!(
                        "Timed out waiting for the nested set lock on `{name}`."
                    )));
                }
                tokio::time::sleep(RETRY).await;
            }
        }

        /// Releases this write's locks, after the outermost transaction commits.
        pub(super) async fn release(mut self) -> laravel::Result<()> {
            self.released = true;
            leave(self.key, Arc::clone(&self.shared), std::mem::take(&mut self.held)).await;
            Ok(())
        }
    }

    impl Drop for Session {
        /// A write that ends without its release, after an error or a rollback, releases its
        /// locks in the background.
        fn drop(&mut self) {
            if self.released {
                return;
            }
            let (key, shared, held) = (self.key, Arc::clone(&self.shared), std::mem::take(&mut self.held));
            match tokio::runtime::Handle::try_current() {
                Ok(runtime) => drop(runtime.spawn(leave(key, shared, held))),
                // Without a runtime, close the session: the server drops every lock it holds.
                Err(_) => {
                    if let Ok(mut connection) = shared.connection.try_lock()
                        && let Some(connection) = connection.take()
                    {
                        drop(connection.detach());
                    }
                }
            }
        }
    }

    /// The shared session of the transaction connection `key`, counting one more write on it.
    fn join(key: i64) -> Option<Arc<Shared>> {
        let mut registry = registry();
        let (shared, users) = registry.get_mut(&key)?;
        *users += 1;
        Some(Arc::clone(shared))
    }

    /// Releases `held` on `shared`, and counts one write fewer on it. The last write releases
    /// anything left and lets the session go back to its pool.
    async fn leave(key: i64, shared: Arc<Shared>, held: Vec<String>) {
        {
            let mut connection = shared.connection.lock().await;
            for name in &held {
                let Some(session) = connection.as_mut() else {
                    break;
                };
                let released = sqlx::query("SELECT RELEASE_LOCK(CONCAT('nestedset:', SHA1(?)))")
                    .bind(name)
                    .execute(&mut **session)
                    .await;
                if released.is_err() {
                    // A session that can't release closes, which releases its locks.
                    if let Some(session) = connection.take() {
                        drop(session.detach());
                    }
                }
            }
        }
        let last = {
            let mut registry = registry();
            match registry.get_mut(&key) {
                Some((current, users)) if Arc::ptr_eq(current, &shared) => {
                    *users -= 1;
                    let last = *users == 0;
                    if last {
                        registry.remove(&key);
                    }
                    last
                }
                _ => false,
            }
        };
        if last {
            let mut connection = shared.connection.lock().await;
            if let Some(session) = connection.as_mut()
                && sqlx::query("SELECT RELEASE_ALL_LOCKS()")
                    .execute(&mut **session)
                    .await
                    .is_err()
                && let Some(session) = connection.take()
            {
                drop(session.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(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)
    }
}