navid/veins / eb4f3d934fd0144c58b4695b6e7abf7fb638b384d96c5e06a1d58231e91071f6 / veinsrs/src/store/reader.rs

reader.rs

← veinsrs/src/store · 13802 bytes · raw · download

use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use crate::encoding::Reader;
use crate::error::{Error, Result};
use crate::object::id::{Id, object_id};
use crate::object::view::{self, Operation, View};
use crate::object::{MAX_STORE_PACK_BYTES, TYPE_CHUNK, type_valid};
use crate::platform::{self, Mapping};
use crate::store::index::{self, Index};
use crate::store::layout;
use crate::store::pack::{self, Pack, record_limit};

type PromisorFetcher = Box<dyn Fn(&Path, Id) -> bool + Send + Sync>;

fn fetcher() -> &'static Mutex<Option<PromisorFetcher>> {
    static FETCHER: OnceLock<Mutex<Option<PromisorFetcher>>> = OnceLock::new();
    FETCHER.get_or_init(|| Mutex::new(None))
}

pub fn set_promisor_fetcher(value: Option<PromisorFetcher>) {
    if let Ok(mut slot) = fetcher().lock() {
        *slot = value;
    }
}

fn fetch_promised(root: &Path, id: Id) -> bool {
    let Ok(slot) = fetcher().lock() else {
        return false;
    };
    slot.as_ref().is_some_and(|fetch| fetch(root, id))
}

#[derive(Clone, Copy)]
pub struct Location {
    pub pack: usize,
    pub kind: u8,
    pub record_offset: u64,
    pub data_offset: u64,
    pub raw_len: u64,
    pub stored_len: u64,
    pub compression: u8,
}

fn read_at_into(file: &File, offset: u64, buffer: &mut [u8]) -> Option<usize> {
    let mut done = 0;
    while done < buffer.len() {
        match platform::read_at(file, &mut buffer[done..], offset + done as u64) {
            Ok(0) => break,
            Ok(count) => done += count,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(_) => return None,
        }
    }
    Some(done)
}

struct PackFile {
    path: PathBuf,
    mtime_ns: u64,
    index: Option<Index>,
    file: Option<File>,
    map: Option<Mapping>,
}

pub struct Store {
    root: PathBuf,
    packs: Vec<PackFile>,
}

impl Store {
    pub fn open(root: &Path) -> Result<Self> {
        let mut store = Self {
            root: root.to_path_buf(),
            packs: Vec::new(),
        };
        store.refresh()?;
        Ok(store)
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn refresh(&mut self) -> Result<()> {
        let directory = layout::packs_dir(&self.root);
        let mut known = std::collections::HashSet::new();
        for pack in &self.packs {
            known.insert(pack.path.clone());
        }
        if let Ok(entries) = fs::read_dir(&directory) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().and_then(|value| value.to_str()) != Some("vpack") {
                    continue;
                }
                if known.contains(&path) {
                    continue;
                }
                let mtime_ns = entry
                    .metadata()
                    .ok()
                    .map(|metadata| platform::mtime_ns(&metadata))
                    .unwrap_or(0);
                self.packs.push(PackFile {
                    path,
                    mtime_ns,
                    index: None,
                    file: None,
                    map: None,
                });
            }
        }
        self.packs.sort_by(|left, right| {
            right
                .mtime_ns
                .cmp(&left.mtime_ns)
                .then_with(|| left.path.cmp(&right.path))
        });
        Ok(())
    }

    fn ensure_index(&mut self, index: usize) -> bool {
        let pack = &mut self.packs[index];
        if pack.index.is_some() {
            return true;
        }
        let Some(name) = pack.path.file_name().and_then(|value| value.to_str()) else {
            return false;
        };
        if name.len() <= 6 {
            return false;
        }
        let stem = &name[..name.len() - 6];
        let index_path = pack.path.with_file_name(format!("{stem}.vidx"));
        let Some(data) = crate::core::read_file_opt(&index_path, MAX_STORE_PACK_BYTES) else {
            return false;
        };
        let Ok(decoded) = index::decode(&data, None) else {
            return false;
        };
        if stem != Id(decoded.pack_trailer).to_hex() {
            return false;
        }
        pack.index = Some(decoded);
        true
    }

    fn open_file(&mut self, index: usize) -> bool {
        let pack = &mut self.packs[index];
        if pack.file.is_some() {
            return true;
        }
        match File::open(&pack.path) {
            Ok(file) => {
                pack.file = Some(file);
                true
            }
            Err(_) => false,
        }
    }

    fn ensure_mapping(&mut self, index: usize) {
        let pack = &mut self.packs[index];
        if pack.map.is_none() {
            pack.map = Mapping::open(&pack.path);
        }
    }

    fn read_at_shared(
        &self,
        index: usize,
        offset: u64,
        length: usize,
    ) -> Option<std::borrow::Cow<'_, [u8]>> {
        if length as u64 > MAX_STORE_PACK_BYTES {
            return None;
        }
        let pack = self.packs.get(index)?;
        if let Some(map) = &pack.map {
            let data = map.as_slice();
            let start = usize::try_from(offset).ok()?;
            if start >= data.len() {
                return None;
            }
            let end = start.saturating_add(length).min(data.len());
            return Some(std::borrow::Cow::Borrowed(&data[start..end]));
        }
        let file = pack.file.as_ref()?;
        let mut data = vec![0u8; length];
        let done = read_at_into(file, offset, &mut data)?;
        data.truncate(done);
        Some(std::borrow::Cow::Owned(data))
    }

    fn record_at(&self, pack_index: usize, offset: u64, expected: Option<Id>) -> Option<Location> {
        let mut header_buffer = [0u8; 96];
        let header: &[u8] = {
            let pack = self.packs.get(pack_index)?;
            if let Some(map) = &pack.map {
                let data = map.as_slice();
                let start = usize::try_from(offset).ok()?;
                if start >= data.len() {
                    return None;
                }
                let end = start.saturating_add(header_buffer.len()).min(data.len());
                &data[start..end]
            } else {
                let file = pack.file.as_ref()?;
                let length = read_at_into(file, offset, &mut header_buffer)?;
                &header_buffer[..length]
            }
        };
        if header.len() < 34 {
            return None;
        }
        let mut reader = Reader::new(header);
        let id = reader.id().ok()?;
        let kind = reader.u8().ok()?;
        let compression = reader.u8().ok()?;
        let raw_len = reader.varint().ok()?;
        let stored_len = reader.varint().ok()?;
        if expected.is_some_and(|value| value != id) {
            return None;
        }
        if !type_valid(kind) || compression > 2 || raw_len == 0 {
            return None;
        }
        if raw_len > record_limit(kind) as u64 {
            return None;
        }
        if stored_len > record_limit(kind) as u64 + crate::object::MAX_CHUNK_LEN as u64 {
            return None;
        }
        if compression == 0 && raw_len != stored_len {
            return None;
        }
        Some(Location {
            pack: pack_index,
            kind,
            record_offset: offset,
            data_offset: offset + reader.offset() as u64,
            raw_len,
            stored_len,
            compression,
        })
    }

    fn find_loaded(&self, id: Id) -> Option<Location> {
        for index in 0..self.packs.len() {
            let Some(entry) = self.packs[index].index.as_ref() else {
                continue;
            };
            let Some(position) = entry.find(id) else {
                continue;
            };
            let offset = entry.entries[position].offset;
            if let Some(location) = self.record_at(index, offset, Some(id)) {
                return Some(location);
            }
        }
        None
    }

    pub fn find(&mut self, id: Id) -> Option<Location> {
        for index in 0..self.packs.len() {
            if !self.ensure_index(index) {
                continue;
            }
            let offset = {
                let Some(entry) = self.packs[index].index.as_ref() else {
                    continue;
                };
                let Some(position) = entry.find(id) else {
                    continue;
                };
                entry.entries[position].offset
            };
            if !self.open_file(index) {
                continue;
            }
            self.ensure_mapping(index);
            if let Some(location) = self.record_at(index, offset, Some(id)) {
                return Some(location);
            }
        }
        None
    }

    pub fn contains(&mut self, id: Id) -> bool {
        self.find(id).is_some()
    }

    fn get_at(&self, location: Location, depth: usize) -> Result<Vec<u8>> {
        if depth > 32 {
            return Err(Error::new("pack delta chain is too deep"));
        }
        let stored_len = usize::try_from(location.stored_len)
            .map_err(|_| Error::new("stored length overflow"))?;
        let stored = self
            .read_at_shared(location.pack, location.data_offset, stored_len)
            .ok_or_else(|| Error::new("cannot read pack record"))?;
        if stored.len() != stored_len {
            return Err(Error::new("pack record is truncated"));
        }
        let raw_len =
            usize::try_from(location.raw_len).map_err(|_| Error::new("raw length overflow"))?;
        match location.compression {
            0 => Ok(stored.into_owned()),
            1 => crate::store::pack::decompress(stored.as_ref(), raw_len),
            2 => {
                let mut reader = Reader::new(stored.as_ref());
                let base_offset = reader.varint()?;
                if base_offset >= location.record_offset {
                    return Err(Error::new("invalid pack delta base"));
                }
                let frame = reader.raw(reader.remaining())?;
                let base = self
                    .record_at(location.pack, base_offset, None)
                    .ok_or_else(|| Error::new("missing pack delta base"))?;
                let body = self.get_at(base, depth + 1)?;
                crate::store::pack::decompress_dict(frame, raw_len, &body)
            }
            _ => Err(Error::new("invalid pack compression")),
        }
    }

    pub fn get(&mut self, location: Location) -> Result<Vec<u8>> {
        if location.pack >= self.packs.len() {
            return Err(Error::new("pack location out of range"));
        }
        self.open_file(location.pack);
        self.ensure_mapping(location.pack);
        self.get_at(location, 0)
    }

    pub fn body(&mut self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {
        let mut location = self.find(id);
        if location.is_none() && expected == TYPE_CHUNK && fetch_promised(&self.root, id) {
            self.refresh()?;
            location = self.find(id);
        }
        let Some(location) = location else {
            return Ok(None);
        };
        if location.kind != expected {
            return Ok(None);
        }
        let body = self.get(location)?;
        if object_id(expected, &body) != id {
            return Ok(None);
        }
        Ok(Some(body))
    }

    pub fn body_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {
        let Some(location) = self.find_loaded(id) else {
            return Ok(None);
        };
        if location.kind != expected {
            return Ok(None);
        }
        let body = self.get_at(location, 0)?;
        if object_id(expected, &body) != id {
            return Ok(None);
        }
        Ok(Some(body))
    }

    /// Read a body without re-hashing it, for callers that only inspect contents.
    pub fn body_raw_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {
        let Some(location) = self.find_loaded(id) else {
            return Ok(None);
        };
        if location.kind != expected {
            return Ok(None);
        }
        Ok(Some(self.get_at(location, 0)?))
    }

    pub fn preload(&mut self) -> Result<()> {
        for index in 0..self.packs.len() {
            self.ensure_index(index);
            self.open_file(index);
            self.ensure_mapping(index);
        }
        Ok(())
    }

    pub fn view(&mut self, id: Id) -> Result<Option<View>> {
        let Some(body) = self.body(id, crate::object::TYPE_VIEW)? else {
            return Ok(None);
        };
        Ok(Some(view::decode_view(&body)?))
    }

    pub fn operation(&mut self, id: Id) -> Result<Option<Operation>> {
        let Some(body) = self.body(id, crate::object::TYPE_OPERATION)? else {
            return Ok(None);
        };
        Ok(Some(view::decode_operation(&body)?))
    }

    pub fn has_promisor(&self) -> bool {
        crate::core::read_file_opt(&layout::config_path(&self.root), 0)
            .is_some_and(|data| data.windows(8).any(|window| window == b"promisor"))
    }

    pub fn pack_count(&self) -> usize {
        self.packs.len()
    }

    pub fn pack_paths(&self) -> Vec<PathBuf> {
        self.packs.iter().map(|pack| pack.path.clone()).collect()
    }

    pub fn decode_pack(&self, index: usize) -> Result<Pack> {
        let path = self
            .packs
            .get(index)
            .map(|pack| pack.path.clone())
            .ok_or_else(|| Error::new("pack out of range"))?;
        let data = crate::core::read_file_opt(&path, MAX_STORE_PACK_BYTES)
            .ok_or_else(|| Error::new("cannot read pack"))?;
        pack::decode(data)
    }
}