armdb 0.15.0

sharded bitcask key-value storage optimized for NVMe
Documentation
//! Owned generation index guards. The lifetime extension is confined here.

use std::marker::PhantomData;
use std::rc::Rc;

use super::*;

/// Pins the generation allocation while its index mutexes are locked.
/// Fields drop in declaration order: every guard drops before `generation`.
/// The Rc marker prevents Send/Sync independently of the synchronization backend.
pub(crate) struct GenerationLocks<K: Key + Hash + Eq + Send + Sync + 'static> {
    guards: Vec<(usize, MutexGuard<'static, ShardIndex<K, GenLoc>>)>,
    generation: Arc<Generation<K>>,
    _local: PhantomData<Rc<()>>,
}

impl<K: Key + Hash + Eq + Send + Sync + 'static> Generation<K> {
    /// Take each requested index mutex once, in ascending order.
    /// Callers must release the View RwLock before entering this operation.
    pub(crate) fn lock_owned(self: &Arc<Self>, shards: &[usize]) -> DbResult<GenerationLocks<K>> {
        let mut shards = shards.to_vec();
        if shards.iter().any(|&shard| shard >= self.shard_count) {
            return Err(DbError::Internal("segmented index shard is out of range"));
        }
        shards.sort_unstable();
        shards.dedup();
        let mut held = GenerationLocks {
            guards: Vec::with_capacity(shards.len()),
            generation: self.clone(),
            _local: PhantomData,
        };
        for shard in shards {
            let guard = sync::lock(&held.generation.indexes[shard]);
            // SAFETY: Arc pins the Generation allocation and its index Vec is
            // never resized. `held` owns an Arc before any guard is extended.
            // Its guards field drops before that Arc, including when locking
            // a later shard panics during partial construction. Capacity was
            // reserved before locking, so inserting a guard cannot allocate.
            // No guard or static reference escapes: every operation borrows
            // through `held`, whose generation field cannot be replaced.
            let guard = unsafe {
                std::mem::transmute::<
                    MutexGuard<'_, ShardIndex<K, GenLoc>>,
                    MutexGuard<'static, ShardIndex<K, GenLoc>>,
                >(guard)
            };
            held.guards.push((shard, guard));
        }
        Ok(held)
    }
}

impl<K: Key + Hash + Eq + Send + Sync + 'static> GenerationLocks<K> {
    pub(crate) fn generation(&self) -> &Arc<Generation<K>> {
        &self.generation
    }

    fn position(&self, h: u64) -> DbResult<usize> {
        let shard = self.generation.shard_of(h);
        self.guards
            .binary_search_by_key(&shard, |(s, _)| *s)
            .map_err(|_| DbError::Internal("segmented key belongs to an unlocked shard"))
    }

    /// Probe without acquiring the index mutex a second time.
    pub(crate) fn probe(&self, h: u64, key: &K) -> DbResult<GenProbe> {
        let index = &self.guards[self.position(h)?].1;
        Ok(match index.get(key) {
            None => GenProbe::Absent,
            Some(found) if found.tombstone => GenProbe::Tombstone,
            Some(_) => GenProbe::Live,
        })
    }

    /// Read without acquiring the index mutex a second time.
    pub(crate) fn lookup(&self, h: u64, key: &K) -> DbResult<GenLookup> {
        let index = &self.guards[self.position(h)?].1;
        Ok(match index.get(key) {
            None => GenLookup::Absent,
            Some(found) if found.tombstone => GenLookup::Tombstone,
            Some(found) => GenLookup::Live(self.generation.read_value(h, &found.loc)?),
        })
    }

    /// Apply a logged write, bypassing collection fence and size/freeze admission.
    /// The engine shard's physical fence remains enforced by append_entry.
    pub(crate) fn append(
        &mut self,
        h: u64,
        key: &K,
        value: Option<&[u8]>,
        limits: Limits,
    ) -> DbResult<()> {
        let pos = self.position(h)?;
        let (shard, index) = &mut self.guards[pos];
        let (_, should_sync) = self
            .generation
            .append_locked(*shard, index, key, value, limits)?;
        self.generation.sync_if_asked(*shard, should_sync)
    }
}