use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
use crate::{Error, Result};
mod spill;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlobId(pub [u8; 32]);
impl BlobId {
#[must_use]
pub fn of(bytes: &[u8]) -> Self {
let mut hasher = Sha256::new();
hasher.update(bytes);
Self(hasher.finalize().into())
}
#[must_use]
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
#[must_use]
pub fn to_hex(&self) -> String {
to_hex(&self.0)
}
}
impl std::fmt::Display for BlobId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.to_hex())
}
}
#[derive(Debug, Clone, Default)]
pub enum Storage {
#[default]
Memory,
Spill(std::path::PathBuf),
}
pub(crate) trait ArtifactSource: Read + Seek + std::fmt::Debug {}
impl<T: Read + Seek + std::fmt::Debug> ArtifactSource for T {}
#[derive(Debug)]
enum Backing {
Memory(BTreeMap<BlobId, Vec<u8>>),
File {
file: RefCell<std::fs::File>,
index: BTreeMap<BlobId, (u64, u64)>,
dir: PathBuf,
},
Artifact {
source: RefCell<Box<dyn ArtifactSource>>,
index: BTreeMap<BlobId, (u64, u64)>,
},
ArtifactCompact {
source: RefCell<Box<dyn ArtifactSource>>,
frames: Vec<crate::artifact::frame::FrameLoc>,
index: BTreeMap<BlobId, (usize, u64, u64)>,
cache: RefCell<std::collections::VecDeque<(usize, Vec<u8>)>>,
},
}
#[derive(Debug)]
pub struct ContentStore {
backing: Backing,
}
impl Default for ContentStore {
fn default() -> Self {
Self::new()
}
}
impl PartialEq for ContentStore {
fn eq(&self, other: &Self) -> bool {
self.ids().eq(other.ids())
}
}
impl Eq for ContentStore {}
impl ContentStore {
#[must_use]
pub fn new() -> Self {
Self {
backing: Backing::Memory(BTreeMap::new()),
}
}
pub fn spilling(dir: &Path) -> Result<Self> {
let file = spill::create(dir)?;
Ok(Self {
backing: Backing::File {
file: RefCell::new(file),
index: BTreeMap::new(),
dir: dir.to_path_buf(),
},
})
}
pub fn for_storage(storage: &Storage) -> Result<Self> {
match storage {
Storage::Memory => Ok(Self::new()),
Storage::Spill(dir) => Self::spilling(dir),
}
}
pub(crate) fn from_artifact_source(
source: impl ArtifactSource + 'static,
index: BTreeMap<BlobId, (u64, u64)>,
) -> Self {
Self {
backing: Backing::Artifact {
source: RefCell::new(Box::new(source)),
index,
},
}
}
pub(crate) fn from_artifact_source_compact(
source: impl ArtifactSource + 'static,
frames: Vec<crate::artifact::frame::FrameLoc>,
index: BTreeMap<BlobId, (usize, u64, u64)>,
) -> Self {
Self {
backing: Backing::ArtifactCompact {
source: RefCell::new(Box::new(source)),
frames,
index,
cache: RefCell::new(std::collections::VecDeque::new()),
},
}
}
pub fn insert(&mut self, bytes: Vec<u8>) -> Result<BlobId> {
let id = BlobId::of(&bytes);
match &mut self.backing {
Backing::Memory(blobs) => {
blobs.entry(id).or_insert(bytes);
}
Backing::File { file, index, dir } => {
if let std::collections::btree_map::Entry::Vacant(e) = index.entry(id) {
let mut f = file.borrow_mut();
let name = |e: std::io::Error| {
Error::io_msg(format!(
"cannot write to the spill file in {}: {e}",
dir.display()
))
};
let offset = f.seek(SeekFrom::End(0)).map_err(name)?;
f.write_all(&bytes).map_err(name)?;
e.insert((offset, bytes.len() as u64));
}
}
Backing::Artifact { .. } | Backing::ArtifactCompact { .. } => {
return Err(Error::Invariant(
"cannot insert into an artifact-backed content store (read-only)".to_string(),
));
}
}
Ok(id)
}
pub fn get(&self, id: &BlobId) -> Result<Option<Vec<u8>>> {
match &self.backing {
Backing::Memory(blobs) => Ok(blobs.get(id).cloned()),
Backing::File { file, index, dir } => {
let Some(&(offset, len)) = index.get(id) else {
return Ok(None);
};
let mut f = file.borrow_mut();
let name = |e: std::io::Error| {
Error::io_msg(format!(
"cannot read the spill file in {}: {e}",
dir.display()
))
};
f.seek(SeekFrom::Start(offset)).map_err(name)?;
let mut buf =
vec![0u8; usize::try_from(len).map_err(|e| Error::io_msg(e.to_string()))?];
f.read_exact(&mut buf).map_err(name)?;
Ok(Some(buf))
}
Backing::Artifact { source, index } => {
let Some(&(offset, len)) = index.get(id) else {
return Ok(None);
};
let mut s = source.borrow_mut();
s.seek(SeekFrom::Start(offset)).map_err(Error::io)?;
let mut buf =
vec![0u8; usize::try_from(len).map_err(|e| Error::io_msg(e.to_string()))?];
s.read_exact(&mut buf).map_err(Error::io)?;
if BlobId::of(&buf) != *id {
return Err(Error::ArtifactChanged(format!(
"blob {id} no longer matches its content; the artifact changed after it was \
verified"
)));
}
Ok(Some(buf))
}
Backing::ArtifactCompact {
source,
frames,
index,
cache,
} => {
let Some(&(frame_index, offset, len)) = index.get(id) else {
return Ok(None);
};
let frame = frames.get(frame_index).ok_or_else(|| {
Error::ArtifactChanged(format!("blob {id}'s frame no longer exists"))
})?;
let raw = if len == frame.raw_len {
crate::artifact::frame::inflate_frame(&mut *source.borrow_mut(), frame)?
} else {
let mut c = cache.borrow_mut();
if let Some((_, raw)) = c.iter().find(|(idx, _)| *idx == frame_index) {
raw.clone()
} else {
let raw = crate::artifact::frame::inflate_frame(
&mut *source.borrow_mut(),
frame,
)?;
if c.len() >= 8 {
c.pop_front();
}
c.push_back((frame_index, raw.clone()));
raw
}
};
let start = usize::try_from(offset).map_err(|e| Error::io_msg(e.to_string()))?;
let end = start + usize::try_from(len).map_err(|e| Error::io_msg(e.to_string()))?;
let buf = raw
.get(start..end)
.ok_or_else(|| {
Error::ArtifactChanged(format!(
"blob {id}'s frame no longer holds enough bytes"
))
})?
.to_vec();
if BlobId::of(&buf) != *id {
return Err(Error::ArtifactChanged(format!(
"blob {id} no longer matches its content; the artifact changed after it was \
verified"
)));
}
Ok(Some(buf))
}
}
}
pub(crate) fn blob_len(&self, id: &BlobId) -> Option<u64> {
match &self.backing {
Backing::Memory(blobs) => blobs.get(id).map(|b| b.len() as u64),
Backing::File { index, .. } | Backing::Artifact { index, .. } => {
index.get(id).map(|&(_, len)| len)
}
Backing::ArtifactCompact { index, .. } => index.get(id).map(|&(_, _, len)| len),
}
}
#[must_use]
pub fn contains(&self, id: &BlobId) -> bool {
match &self.backing {
Backing::Memory(blobs) => blobs.contains_key(id),
Backing::File { index, .. } | Backing::Artifact { index, .. } => index.contains_key(id),
Backing::ArtifactCompact { index, .. } => index.contains_key(id),
}
}
#[must_use]
pub fn len(&self) -> usize {
match &self.backing {
Backing::Memory(blobs) => blobs.len(),
Backing::File { index, .. } | Backing::Artifact { index, .. } => index.len(),
Backing::ArtifactCompact { index, .. } => index.len(),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
pub fn total_bytes(&self) -> u64 {
match &self.backing {
Backing::Memory(blobs) => blobs.values().map(|b| b.len() as u64).sum(),
Backing::File { index, .. } | Backing::Artifact { index, .. } => {
index.values().map(|&(_, len)| len).sum()
}
Backing::ArtifactCompact { index, .. } => index.values().map(|&(_, _, len)| len).sum(),
}
}
pub fn ids(&self) -> impl Iterator<Item = &BlobId> {
match &self.backing {
Backing::Memory(blobs) => Either::Left(blobs.keys()),
Backing::File { index, .. } | Backing::Artifact { index, .. } => {
Either::Right(Either::Left(index.keys()))
}
Backing::ArtifactCompact { index, .. } => Either::Right(Either::Right(index.keys())),
}
}
pub(crate) fn retain(&mut self, mut keep: impl FnMut(&BlobId) -> bool) {
match &mut self.backing {
Backing::Memory(blobs) => blobs.retain(|id, _| keep(id)),
Backing::File { index, .. } | Backing::Artifact { index, .. } => {
index.retain(|id, _| keep(id));
}
Backing::ArtifactCompact { index, .. } => {
index.retain(|id, _| keep(id));
}
}
}
}
enum Either<L, R> {
Left(L),
Right(R),
}
impl<'a, L, R> Iterator for Either<L, R>
where
L: Iterator<Item = &'a BlobId>,
R: Iterator<Item = &'a BlobId>,
{
type Item = &'a BlobId;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Left(l) => l.next(),
Self::Right(r) => r.next(),
}
}
}
pub(crate) fn to_hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
let _ = write!(out, "{b:02x}");
}
out
}
#[cfg(test)]
mod tests;