armdb 0.15.0

sharded bitcask key-value storage optimized for NVMe
Documentation
//! The engine's own permission to write an index target outside `db.tx()`:
//! builds, typed migrations and schema repair. Thread-local and scoped by
//! collection name. Enter it only around the engine's own write calls, never
//! while user code (a migration callback, a projection closure) runs.
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;

struct Grant {
    id: u64,
    name: &'static str,
    available: bool,
}

thread_local! {
    static ACTIVE: RefCell<Vec<Grant>> = const { RefCell::new(Vec::new()) };
    static NEXT_ID: Cell<u64> = const { Cell::new(0) };
}

pub(crate) struct IndexMaintenance {
    id: u64,
    _not_send: PhantomData<*const ()>,
}

impl IndexMaintenance {
    #[allow(dead_code)] // Maintenance callers are feature gated.
    pub(crate) fn enter(name: &'static str) -> Self {
        let id = NEXT_ID.with(|next| {
            let id = next.get();
            next.set(id.checked_add(1).expect("maintenance grant id exhausted"));
            id
        });
        ACTIVE.with(|a| {
            a.borrow_mut().push(Grant {
                id,
                name,
                available: true,
            })
        });
        Self {
            id,
            _not_send: PhantomData,
        }
    }

    /// Consume only the current grant, before any key, metrics or core work.
    /// Keep its spent marker on the stack: callbacks cannot fall through to
    /// an older grant, even one for another collection. A new legitimate
    /// engine scope may temporarily shadow the marker with its own grant.
    #[cfg_attr(not(feature = "segmented"), allow(dead_code))]
    pub(crate) fn consume(name: &str) -> bool {
        ACTIVE.with(|a| {
            let mut a = a.borrow_mut();
            let Some(grant) = a.last_mut() else {
                return false;
            };
            if grant.name != name || !grant.available {
                return false;
            }
            grant.available = false;
            true
        })
    }
}

impl Drop for IndexMaintenance {
    fn drop(&mut self) {
        ACTIVE.with(|a| {
            let mut a = a.borrow_mut();
            if let Some(pos) = a.iter().position(|grant| grant.id == self.id) {
                a.remove(pos);
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn index_maintenance_current_grant_is_one_shot_and_shadows_older_names() {
        let _outer = IndexMaintenance::enter("a");
        {
            let _inner = IndexMaintenance::enter("b");
            assert!(
                !IndexMaintenance::consume("a"),
                "only the innermost grant is callable"
            );
            assert!(IndexMaintenance::consume("b"));
            assert!(
                !IndexMaintenance::consume("b"),
                "a grant authorizes exactly one call"
            );
            assert!(
                !IndexMaintenance::consume("a"),
                "consumption must not expose an older grant"
            );
        }
        assert!(IndexMaintenance::consume("a"));
        assert!(!IndexMaintenance::consume("a"));
    }

    #[test]
    fn index_maintenance_same_name_errors_unwind_and_nested_engine_scopes() {
        assert!(!IndexMaintenance::consume("a"));
        let outer = IndexMaintenance::enter("a");
        {
            let _inner = IndexMaintenance::enter("a");
            assert!(IndexMaintenance::consume("a"));
            assert!(!IndexMaintenance::consume("a"));
            let result = std::panic::catch_unwind(|| {
                let _engine = IndexMaintenance::enter("b");
                assert!(!IndexMaintenance::consume("a"));
                assert!(IndexMaintenance::consume("b"));
                panic!("callback panic");
            });
            assert!(result.is_err());
            assert!(!IndexMaintenance::consume("b"));
            assert!(!IndexMaintenance::consume("a"));
        }
        assert!(IndexMaintenance::consume("a"));
        drop(outer);
        assert!(!IndexMaintenance::consume("a"));
        // Out-of-order destruction also removes only its own grant.
        let first = IndexMaintenance::enter("a");
        let second = IndexMaintenance::enter("a");
        drop(first);
        assert!(IndexMaintenance::consume("a"));
        drop(second);
        assert!(!IndexMaintenance::consume("a"));
    }
}