use std::collections::BTreeMap;
use std::sync::Mutex;
use async_trait::async_trait;
use sui_cache::CacheError;
use sui_cache::{MemNarRefIndex, NarRefIndex, StorageBackend};
#[derive(Default)]
pub struct MockCacheBackend {
narinfos: Mutex<BTreeMap<String, String>>,
nar_refs: MemNarRefIndex,
}
impl MockCacheBackend {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_entry(self, hash: &str, image_ref: &str) -> Self {
self.narinfos
.lock()
.expect("mock mutex poisoned")
.insert(hash.to_string(), image_ref.to_string());
self
}
}
#[async_trait]
impl StorageBackend for MockCacheBackend {
async fn get_narinfo(&self, hash: &str) -> Result<Option<String>, CacheError> {
Ok(self.narinfos.lock().expect("mock mutex poisoned").get(hash).cloned())
}
async fn put_narinfo_record(&self, hash: &str, content: &str) -> Result<(), CacheError> {
self.narinfos
.lock()
.expect("mock mutex poisoned")
.insert(hash.to_string(), content.to_string());
Ok(())
}
async fn delete_narinfo_record(&self, hash: &str) -> Result<(), CacheError> {
self.narinfos.lock().expect("mock mutex poisoned").remove(hash);
Ok(())
}
async fn delete_nar_record(&self, _nar_path: &str) -> Result<(), CacheError> {
Ok(())
}
fn nar_ref_index(&self) -> &dyn NarRefIndex {
&self.nar_refs
}
async fn get_nar(&self, _path: &str) -> Result<Option<Vec<u8>>, CacheError> {
Ok(None)
}
async fn put_nar(&self, _path: &str, _data: &[u8]) -> Result<(), CacheError> {
Ok(())
}
fn nar_residency(&self) -> sui_cache::NarResidency {
sui_cache::NarResidency::WholeValue
}
async fn list_narinfos(&self) -> Result<Vec<String>, CacheError> {
Ok(self.narinfos.lock().expect("mock mutex poisoned").keys().cloned().collect())
}
}