use std::collections::BTreeMap;
use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::Mutex;
crate::define_hash_newtype! {
DrvHash
}
crate::define_hash_newtype! {
NarHash
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OutputPath(pub String);
impl OutputPath {
#[must_use]
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for OutputPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Drv {
pub drv_hash: DrvHash,
pub system: String,
pub outputs: BTreeMap<String, OutputPath>,
pub input_drvs: BTreeMap<DrvHash, Vec<String>>,
pub input_srcs: Vec<OutputPath>,
pub builder: String,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
}
impl Drv {
#[must_use]
pub fn synthetic(drv_hash: DrvHash, system: impl Into<String>) -> Self {
Self {
drv_hash,
system: system.into(),
outputs: BTreeMap::new(),
input_drvs: BTreeMap::new(),
input_srcs: Vec::new(),
builder: String::new(),
args: Vec::new(),
env: BTreeMap::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(try_from = "NarBlobRecord")]
pub struct NarBlob {
hash: NarHash,
bytes: Vec<u8>,
}
impl NarBlob {
#[must_use]
pub fn from_bytes(bytes: Vec<u8>) -> Self {
let hash = NarHash::from_bytes(&bytes);
Self { hash, bytes }
}
#[must_use]
pub fn hash(&self) -> &NarHash {
&self.hash
}
#[must_use]
pub fn size(&self) -> u64 {
self.bytes.len() as u64
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum NarBlobError {
#[error("nar record says hash {recorded}, its bytes hash to {derived}")]
HashMismatch {
recorded: NarHash,
derived: NarHash,
},
#[error("nar record says {recorded} bytes, it carries {derived}")]
SizeMismatch {
recorded: u64,
derived: u64,
},
}
crate::impl_error_kind! {
NarBlobError {
{ HashMismatch { .. } } => "hash_mismatch",
{ SizeMismatch { .. } } => "size_mismatch",
}
}
#[derive(Deserialize)]
struct NarBlobRecord {
hash: NarHash,
size: u64,
bytes: Vec<u8>,
}
#[derive(Serialize)]
struct NarBlobRecordRef<'a> {
hash: &'a NarHash,
size: u64,
bytes: &'a [u8],
}
impl TryFrom<NarBlobRecord> for NarBlob {
type Error = NarBlobError;
fn try_from(record: NarBlobRecord) -> Result<Self, Self::Error> {
let blob = Self::from_bytes(record.bytes);
if blob.hash != record.hash {
return Err(NarBlobError::HashMismatch {
recorded: record.hash,
derived: blob.hash,
});
}
if blob.size() != record.size {
return Err(NarBlobError::SizeMismatch {
recorded: record.size,
derived: blob.size(),
});
}
Ok(blob)
}
}
impl Serialize for NarBlob {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
NarBlobRecordRef {
hash: &self.hash,
size: self.size(),
bytes: &self.bytes,
}
.serialize(serializer)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Realisation {
pub drv_hash: DrvHash,
pub output_name: String,
pub output_path: OutputPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nar_hash: Option<NarHash>,
}
#[derive(Debug, Clone, Error)]
pub enum CacheError {
#[error("backend: {0}")]
Backend(String),
#[error("hash mismatch: requested {requested}, got {actual}")]
HashMismatch {
requested: String,
actual: String,
},
}
crate::impl_error_kind! {
CacheError {
(Backend(_)) => "backend",
{ HashMismatch { .. } } => "hash_mismatch",
}
}
#[async_trait]
pub trait DerivationCacheBackend: Send + Sync {
fn name(&self) -> &'static str;
async fn get_drv(&self, hash: &DrvHash) -> Result<Option<Drv>, CacheError>;
async fn put_drv(&self, drv: &Drv) -> Result<(), CacheError>;
async fn get_nar(&self, hash: &NarHash) -> Result<Option<NarBlob>, CacheError>;
async fn put_nar(&self, blob: &NarBlob) -> Result<(), CacheError>;
async fn list_realisations(&self, drv_hash: &DrvHash) -> Result<Vec<Realisation>, CacheError>;
async fn put_realisation(&self, realisation: &Realisation) -> Result<(), CacheError>;
}
#[derive(Default, Clone)]
pub struct MemoryDerivationCache {
inner: Arc<Mutex<MemoryState>>,
}
#[derive(Default)]
struct MemoryState {
drvs: BTreeMap<DrvHash, Drv>,
nars: BTreeMap<NarHash, NarBlob>,
realisations: BTreeMap<DrvHash, Vec<Realisation>>,
}
impl MemoryDerivationCache {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub async fn drv_count(&self) -> usize {
self.inner.lock().await.drvs.len()
}
pub async fn nar_count(&self) -> usize {
self.inner.lock().await.nars.len()
}
}
#[async_trait]
impl DerivationCacheBackend for MemoryDerivationCache {
fn name(&self) -> &'static str {
"memory"
}
async fn get_drv(&self, hash: &DrvHash) -> Result<Option<Drv>, CacheError> {
Ok(self.inner.lock().await.drvs.get(hash).cloned())
}
async fn put_drv(&self, drv: &Drv) -> Result<(), CacheError> {
let mut s = self.inner.lock().await;
s.drvs.insert(drv.drv_hash.clone(), drv.clone());
Ok(())
}
async fn get_nar(&self, hash: &NarHash) -> Result<Option<NarBlob>, CacheError> {
Ok(self.inner.lock().await.nars.get(hash).cloned())
}
async fn put_nar(&self, blob: &NarBlob) -> Result<(), CacheError> {
let mut s = self.inner.lock().await;
s.nars.insert(blob.hash().clone(), blob.clone());
Ok(())
}
async fn list_realisations(&self, drv_hash: &DrvHash) -> Result<Vec<Realisation>, CacheError> {
Ok(self
.inner
.lock()
.await
.realisations
.get(drv_hash)
.cloned()
.unwrap_or_default())
}
async fn put_realisation(&self, realisation: &Realisation) -> Result<(), CacheError> {
let mut s = self.inner.lock().await;
let entry = s
.realisations
.entry(realisation.drv_hash.clone())
.or_default();
entry.retain(|r| r.output_name != realisation.output_name);
entry.push(realisation.clone());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hex::hex_encode;
fn sample_drv() -> Drv {
let hash = DrvHash::from_bytes(b"sample-drv");
Drv::synthetic(hash, "x86_64-linux")
}
#[test]
fn drv_hash_and_nar_hash_are_distinct_types() {
let d = DrvHash::from_bytes(b"x");
let n = NarHash::from_bytes(b"x");
assert_eq!(d.0, n.0);
}
#[test]
fn drv_hash_hex_is_64_chars() {
let h = DrvHash::from_bytes(b"engenho-substrate");
let hex = h.to_hex();
assert_eq!(hex.len(), 64);
assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn drv_hash_display_matches_hex() {
let h = DrvHash::from_bytes(b"x");
assert_eq!(format!("{h}"), h.to_hex());
}
#[test]
fn nar_hash_display_matches_hex() {
let h = NarHash::from_bytes(b"x");
assert_eq!(format!("{h}"), h.to_hex());
}
#[test]
fn nar_blob_from_bytes_computes_hash_and_size() {
let blob = NarBlob::from_bytes(b"hello".to_vec());
assert_eq!(blob.size(), 5);
assert_eq!(blob.hash(), &NarHash::from_bytes(b"hello"));
assert_eq!(blob.bytes(), b"hello");
assert_eq!(blob.into_bytes(), b"hello".to_vec());
}
fn wire(bytes: &[u8]) -> serde_json::Value {
serde_json::to_value(NarBlob::from_bytes(bytes.to_vec())).unwrap()
}
#[test]
fn deserialising_a_record_with_a_foreign_hash_is_refused() {
let mut v = wire(b"hello");
v["hash"] = wire(b"other")["hash"].clone();
let err = serde_json::from_value::<NarBlob>(v).unwrap_err();
let expected = NarBlobError::HashMismatch {
recorded: NarHash::from_bytes(b"other"),
derived: NarHash::from_bytes(b"hello"),
};
assert_eq!(err.to_string(), expected.to_string());
}
#[test]
fn deserialising_a_record_with_a_wrong_size_is_refused() {
let mut v = wire(b"hello");
v["size"] = serde_json::json!(4);
let err = serde_json::from_value::<NarBlob>(v).unwrap_err();
let expected = NarBlobError::SizeMismatch {
recorded: 4,
derived: 5,
};
assert_eq!(err.to_string(), expected.to_string());
}
#[test]
fn deserialising_a_record_without_a_size_is_refused() {
let mut v = wire(b"hello");
v.as_object_mut().unwrap().remove("size");
assert!(serde_json::from_value::<NarBlob>(v).is_err());
}
#[test]
fn wire_shape_is_hash_size_bytes() {
let v = wire(b"abc");
assert_eq!(
v["hash"],
serde_json::to_value(NarHash::from_bytes(b"abc")).unwrap()
);
assert_eq!(v["size"], serde_json::json!(3));
assert_eq!(v["bytes"], serde_json::json!([97, 98, 99]));
assert_eq!(v.as_object().unwrap().len(), 3);
}
#[test]
fn nar_blob_error_kinds_are_stable() {
let h = NarHash::from_bytes(b"x");
assert_eq!(
NarBlobError::HashMismatch {
recorded: h.clone(),
derived: h
}
.kind(),
"hash_mismatch"
);
assert_eq!(
NarBlobError::SizeMismatch {
recorded: 1,
derived: 2
}
.kind(),
"size_mismatch"
);
}
#[test]
fn output_path_round_trips_string() {
let p = OutputPath::new("/nix/store/abc-foo");
assert_eq!(p.as_str(), "/nix/store/abc-foo");
assert_eq!(format!("{p}"), "/nix/store/abc-foo");
}
#[tokio::test]
async fn cache_put_get_drv_round_trip() {
let cache = MemoryDerivationCache::new();
let drv = sample_drv();
assert_eq!(cache.get_drv(&drv.drv_hash).await.unwrap(), None);
cache.put_drv(&drv).await.unwrap();
assert_eq!(
cache.get_drv(&drv.drv_hash).await.unwrap(),
Some(drv.clone())
);
assert_eq!(cache.drv_count().await, 1);
}
#[tokio::test]
async fn cache_put_drv_idempotent() {
let cache = MemoryDerivationCache::new();
let drv = sample_drv();
cache.put_drv(&drv).await.unwrap();
cache.put_drv(&drv).await.unwrap();
assert_eq!(cache.drv_count().await, 1);
}
#[tokio::test]
async fn cache_put_get_nar_round_trip() {
let cache = MemoryDerivationCache::new();
let blob = NarBlob::from_bytes(b"nar-content".to_vec());
let h = blob.hash().clone();
assert_eq!(cache.get_nar(&h).await.unwrap(), None);
cache.put_nar(&blob).await.unwrap();
let got = cache.get_nar(&h).await.unwrap();
assert_eq!(got, Some(blob));
assert_eq!(cache.nar_count().await, 1);
}
#[tokio::test]
async fn cache_absence_is_ok_none() {
let cache = MemoryDerivationCache::new();
assert_eq!(
cache.get_drv(&DrvHash::from_bytes(b"no")).await.unwrap(),
None
);
assert_eq!(
cache.get_nar(&NarHash::from_bytes(b"no")).await.unwrap(),
None
);
}
#[tokio::test]
async fn cache_realisations_grouped_by_drv() {
let cache = MemoryDerivationCache::new();
let drv_hash = DrvHash::from_bytes(b"d");
cache
.put_realisation(&Realisation {
drv_hash: drv_hash.clone(),
output_name: "out".into(),
output_path: OutputPath::new("/nix/store/a-out"),
nar_hash: None,
})
.await
.unwrap();
cache
.put_realisation(&Realisation {
drv_hash: drv_hash.clone(),
output_name: "dev".into(),
output_path: OutputPath::new("/nix/store/b-dev"),
nar_hash: None,
})
.await
.unwrap();
let list = cache.list_realisations(&drv_hash).await.unwrap();
assert_eq!(list.len(), 2);
assert!(list.iter().any(|r| r.output_name == "out"));
assert!(list.iter().any(|r| r.output_name == "dev"));
}
#[tokio::test]
async fn cache_realisation_put_replaces_same_output_name() {
let cache = MemoryDerivationCache::new();
let drv_hash = DrvHash::from_bytes(b"d");
let path_v1 = OutputPath::new("/nix/store/v1-out");
let path_v2 = OutputPath::new("/nix/store/v2-out");
cache
.put_realisation(&Realisation {
drv_hash: drv_hash.clone(),
output_name: "out".into(),
output_path: path_v1,
nar_hash: None,
})
.await
.unwrap();
cache
.put_realisation(&Realisation {
drv_hash: drv_hash.clone(),
output_name: "out".into(),
output_path: path_v2.clone(),
nar_hash: None,
})
.await
.unwrap();
let list = cache.list_realisations(&drv_hash).await.unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].output_path, path_v2);
}
#[tokio::test]
async fn cache_list_realisations_empty_when_unknown() {
let cache = MemoryDerivationCache::new();
let unknown = DrvHash::from_bytes(b"never-seen");
assert!(cache.list_realisations(&unknown).await.unwrap().is_empty());
}
#[tokio::test]
async fn cache_name_is_stable() {
let cache = MemoryDerivationCache::new();
assert_eq!(cache.name(), "memory");
}
#[test]
fn drv_round_trips_serde() {
let drv = sample_drv();
let bytes = serde_json::to_vec(&drv).unwrap();
let back: Drv = serde_json::from_slice(&bytes).unwrap();
assert_eq!(back, drv);
}
#[test]
fn nar_blob_round_trips_serde() {
let blob = NarBlob::from_bytes(b"abc".to_vec());
let bytes = serde_json::to_vec(&blob).unwrap();
let back: NarBlob = serde_json::from_slice(&bytes).unwrap();
assert_eq!(back, blob);
}
#[test]
fn realisation_round_trips_serde() {
let r = Realisation {
drv_hash: DrvHash::from_bytes(b"d"),
output_name: "out".into(),
output_path: OutputPath::new("/nix/store/a-out"),
nar_hash: Some(NarHash::from_bytes(b"n")),
};
let bytes = serde_json::to_vec(&r).unwrap();
let back: Realisation = serde_json::from_slice(&bytes).unwrap();
assert_eq!(back, r);
}
#[test]
fn cache_error_kinds_are_stable() {
assert_eq!(CacheError::Backend("x".into()).kind(), "backend");
assert_eq!(
CacheError::HashMismatch {
requested: "a".into(),
actual: "b".into()
}
.kind(),
"hash_mismatch"
);
}
#[test]
fn cache_error_has_no_absence_variant() {
fn tag(e: &CacheError) -> &'static str {
match e {
CacheError::Backend(_) => "backend",
CacheError::HashMismatch { .. } => "hash_mismatch",
}
}
for e in [
CacheError::Backend("x".into()),
CacheError::HashMismatch {
requested: "a".into(),
actual: "b".into(),
},
] {
assert_eq!(tag(&e), e.kind());
}
}
#[test]
fn hex_encode_known_vector() {
let h = blake3::hash(b"");
let s = hex_encode(h.as_bytes());
assert!(s.starts_with("af1349b9"));
}
}