pi_block_device 0.1.0

Asynchronous copy-on-write block storage abstractions
Documentation
//! 基于 State 克隆构建的固定只读快照。

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use super::state::{SegmentState as FileSegmentState, State};
use super::{RetirementNotifier, SUPPORTED_BLOCK_SIZES};
use crate::{
    AnonymousRoot, BlockId, BlockStoreError, NamedRoot, ReadSnapshot, RootName, RootVersion,
    SegmentId, SegmentInfo, SegmentState,
};

/// 不随后续提交变化的文件状态快照。
pub struct FileSnapshot {
    /// 创建快照的进程内存储实例身份,用于拒绝跨实例 SegmentId。
    store_identity: u64,
    /// 该存储实例内唯一快照身份,用于拒绝跨快照 SegmentId。
    identity: u64,
    /// 固定 State 的 Arc 所有权,保证缓存所依据状态生命周期覆盖快照。
    _state: Arc<State>,
    /// 快照释放时仅用于唤醒退休 worker 的共享通知器。
    notifier: Arc<RetirementNotifier>,
    /// 从 bindings 预构建的命名根快照值集合。
    named_roots: Vec<NamedRoot>,
    /// roots 中未被任何 binding 指向的根快照值集合。
    anonymous_roots: Vec<AnonymousRoot>,
    /// BlockId 原始值到 RootVersion 的查询缓存。
    roots: BTreeMap<u64, RootVersion>,
    /// 按 State 段记录预构建的 SegmentInfo 集合。
    segment_infos: Vec<SegmentInfo>,
    /// 内部段键到位图展开 BlockId 列表的缓存。
    live_blocks: BTreeMap<u64, Vec<BlockId>>,
}

impl FileSnapshot {
    /// 消费已经通过 [`State::validate`] 的 `State` 克隆并构建根、段和存活块缓存。
    ///
    /// 当前实现按底层 `BTreeMap`/`BTreeSet` 的键顺序构建迭代缓存,因此结果通常
    /// 稳定有序,但 [`ReadSnapshot`] 公共契约不保证任何枚举顺序。无效 `BlockId`
    /// 会被过滤;生产调用方只传入已验证状态,故正常不会发生过滤。
    pub(super) fn new(
        state: Arc<State>,
        store_identity: u64,
        identity: u64,
        notifier: Arc<RetirementNotifier>,
    ) -> Self {
        let named_roots = state
            .bindings
            .iter()
            .filter_map(|(name, &raw)| {
                BlockId::try_from(raw)
                    .ok()
                    .map(|block| NamedRoot::new(RootName::from_validated(name.clone()), block))
            })
            .collect();
        let named_targets: BTreeSet<u64> = state.bindings.values().copied().collect();
        let anonymous_roots = state
            .roots
            .iter()
            .filter(|raw| !named_targets.contains(raw))
            .filter_map(|&raw| BlockId::try_from(raw).ok().map(AnonymousRoot::new))
            .collect();
        let roots = state
            .roots
            .iter()
            .filter_map(|&raw| {
                BlockId::try_from(raw)
                    .ok()
                    .map(|block| (raw, RootVersion::new(block)))
            })
            .collect();
        let mut segment_infos = Vec::with_capacity(state.segments.len());
        let mut live_blocks = BTreeMap::new();
        for record in state.segments.values() {
            let segment_value = (u64::from(record.version) << 4) | u64::from(record.level);
            let segment = SegmentId::new(store_identity, identity, segment_value);
            let blocks = (0..record.frontier)
                .filter(|index| {
                    let word = usize::try_from(index / 64).ok();
                    word.and_then(|word| record.bitmap.get(word))
                        .is_some_and(|bits| bits & (1_u64 << (index % 64)) != 0)
                })
                .map(|index| {
                    BlockId::from_raw_unchecked(
                        (index << 32) | (u64::from(record.version) << 4) | u64::from(record.level),
                    )
                })
                .collect();
            live_blocks.insert(segment_value, blocks);
            segment_infos.push(SegmentInfo::new(
                segment,
                record.level,
                SUPPORTED_BLOCK_SIZES[usize::from(record.level)],
                record.frontier,
                record.live_count,
                match record.state {
                    FileSegmentState::Active => SegmentState::Active,
                    FileSegmentState::Sealed => SegmentState::Sealed,
                },
            ));
        }
        Self {
            store_identity,
            identity,
            _state: state,
            notifier,
            named_roots,
            anonymous_roots,
            roots,
            segment_infos,
            live_blocks,
        }
    }
}

impl Drop for FileSnapshot {
    /// 快照释放只通知标准线程 worker 重新检查弱状态,不在 Drop 中执行同步文件删除。
    fn drop(&mut self) {
        self.notifier.notify();
    }
}

impl ReadSnapshot for FileSnapshot {
    /// 借用命名根缓存的切片迭代器。
    type NamedRoots<'a> = std::slice::Iter<'a, NamedRoot>;
    /// 借用匿名根缓存的切片迭代器。
    type AnonymousRoots<'a> = std::slice::Iter<'a, AnonymousRoot>;
    /// 借用段信息缓存的切片迭代器。
    type SegmentInfos<'a> = std::slice::Iter<'a, SegmentInfo>;
    /// 复制返回 BlockId 的切片迭代器。
    type LiveBlocks<'a> = std::iter::Copied<std::slice::Iter<'a, BlockId>>;

    /// 返回命名根缓存迭代器;当前按名称字典序构建,但公共 API 不承诺顺序。
    fn list_named_roots(&self) -> Self::NamedRoots<'_> {
        self.named_roots.iter()
    }

    /// 返回匿名根缓存迭代器;当前按 `BlockId` 原始值排序,但公共 API 不承诺顺序。
    fn list_anonymous_roots(&self) -> Self::AnonymousRoots<'_> {
        self.anonymous_roots.iter()
    }

    /// 按 RootName 字符串内容查找固定名称绑定。
    fn get_named_root(&self, name: &RootName) -> Option<&NamedRoot> {
        self.named_roots
            .iter()
            .find(|root| root.name().as_str() == name.as_str())
    }

    /// 按 BlockId 原始值查找固定根版本。
    fn get_root(&self, block: BlockId) -> Option<&RootVersion> {
        self.roots.get(&u64::from(block))
    }

    /// 返回段信息迭代器;当前按 `(level, version)` 排序,但公共 API 不承诺顺序。
    fn segment_infos(&self) -> Self::SegmentInfos<'_> {
        self.segment_infos.iter()
    }

    /// 验证存储与快照身份后返回指定段的存活 BlockId;作用域不匹配返回 SegmentNotFound。
    fn live_blocks(&self, segment: SegmentId) -> Result<Self::LiveBlocks<'_>, BlockStoreError> {
        if segment.store_identity() != self.store_identity
            || segment.snapshot_identity() != self.identity
        {
            return Err(BlockStoreError::SegmentNotFound);
        }
        self.live_blocks
            .get(&segment.segment_key())
            .map(|blocks| blocks.iter().copied())
            .ok_or(BlockStoreError::SegmentNotFound)
    }
}