use std::fs::{self, File}; use std::os::unix::fs::FileExt; 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::store::index::{self, Index}; use crate::store::layout; use crate::store::pack::{self, Pack, record_limit}; type PromisorFetcher = Box bool + Send + Sync>; fn fetcher() -> &'static Mutex> { static FETCHER: OnceLock>> = OnceLock::new(); FETCHER.get_or_init(|| Mutex::new(None)) } pub fn set_promisor_fetcher(value: Option) { 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, } struct PackFile { path: PathBuf, mtime_ns: u64, index: Option, file: Option, } pub struct Store { root: PathBuf, packs: Vec, } impl Store { pub fn open(root: &Path) -> Result { 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| { use std::os::unix::fs::MetadataExt; (metadata.mtime() as u64) .wrapping_mul(1_000_000_000) .wrapping_add(metadata.mtime_nsec() as u64) }) .unwrap_or(0); self.packs.push(PackFile { path, mtime_ns, index: None, file: 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 read_at_shared(&self, index: usize, offset: u64, length: usize) -> Option> { if length as u64 > MAX_STORE_PACK_BYTES { return None; } let file = self.packs.get(index)?.file.as_ref()?; let mut data = vec![0u8; length]; let mut done = 0; while done < length { match file.read_at(&mut data[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, } } data.truncate(done); Some(data) } fn record_at(&self, pack_index: usize, offset: u64, expected: Option) -> Option { let header = self.read_at_shared(pack_index, offset, 96)?; 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 { 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 { 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; } 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> { 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), 1 => zstd::bulk::decompress(&stored, raw_len) .map_err(|error| Error::new(error.to_string())), 2 => { let mut reader = Reader::new(&stored); 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)?; let mut decoder = zstd::bulk::Decompressor::with_dictionary(&body) .map_err(|error| Error::new(error.to_string()))?; decoder .decompress(frame, raw_len) .map_err(|error| Error::new(error.to_string())) } _ => Err(Error::new("invalid pack compression")), } } pub fn get(&mut self, location: Location) -> Result> { if location.pack >= self.packs.len() { return Err(Error::new("pack location out of range")); } self.open_file(location.pack); self.get_at(location, 0) } pub fn body(&mut self, id: Id, expected: u8) -> Result>> { 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>> { 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)) } pub fn preload(&mut self) -> Result<()> { for index in 0..self.packs.len() { self.ensure_index(index); self.open_file(index); } Ok(()) } pub fn view(&mut self, id: Id) -> Result> { 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> { 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 { self.packs.iter().map(|pack| pack.path.clone()).collect() } pub fn decode_pack(&self, index: usize) -> Result { 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) } }