use std::path::Path;
use std::sync::Arc;
use znippy_common::{ZnippyArchive, ZnippyReader};
use crate::backend::{unsupported, Archive, Cap, HttpReply};
use crate::{ArchiveTokens, ArtifactEntry, ArtifactId};
pub struct ZnippyBase {
name: String,
archive: Option<Arc<ZnippyArchive>>,
reader: Option<Arc<dyn ZnippyReader>>,
tokens: ArchiveTokens,
}
impl ZnippyBase {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
archive: None,
reader: None,
tokens: ArchiveTokens::none(),
}
}
pub fn with_archive(name: impl Into<String>, path: impl AsRef<Path>) -> anyhow::Result<Self> {
let path = path.as_ref();
let archive = Arc::new(ZnippyArchive::open(path)?);
Ok(Self {
name: name.into(),
reader: Some(Arc::clone(&archive) as Arc<dyn ZnippyReader>),
archive: Some(archive),
tokens: ArchiveTokens::at(path),
})
}
pub fn with_reader(name: impl Into<String>, reader: Arc<dyn ZnippyReader>) -> Self {
Self {
name: name.into(),
archive: None,
reader: Some(reader),
tokens: ArchiveTokens::none(),
}
}
pub fn writable(name: impl Into<String>, path: impl AsRef<Path>) -> Self {
Self {
name: name.into(),
archive: None,
reader: None,
tokens: ArchiveTokens::at(path.as_ref()),
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn typed(&self) -> Option<&Arc<ZnippyArchive>> {
self.archive.as_ref()
}
pub fn reader(&self) -> Option<&Arc<dyn ZnippyReader>> {
self.reader.as_ref()
}
pub fn has_archive(&self) -> bool {
self.reader.is_some()
}
pub fn tokens(&self) -> &ArchiveTokens {
&self.tokens
}
pub fn list_files(&self) -> Vec<String> {
self.reader
.as_ref()
.and_then(|r| r.list_files().ok())
.unwrap_or_default()
}
pub fn get_file(&self, relative_path: &str) -> anyhow::Result<Vec<u8>> {
let reader = self
.reader
.as_ref()
.ok_or_else(|| anyhow::anyhow!("No reader configured"))?;
reader.extract_file(relative_path)
}
pub fn archive(&self) -> anyhow::Result<Archive> {
match &self.reader {
Some(r) => Archive::read(&self.name, r.as_ref()),
None => unsupported(&self.name, Cap::Archive),
}
}
pub fn refuse_put(&self) -> anyhow::Result<()> {
anyhow::bail!("znippy repository '{}' is read-only", self.name)
}
pub fn strip_repo<'a>(&self, suburl: &'a str) -> &'a str {
strip_repo(&self.name, suburl)
}
pub fn list_entries<F>(
&self,
name_filter: Option<&str>,
limit: usize,
content_type: &str,
coordinate: F,
) -> anyhow::Result<Vec<ArtifactEntry>>
where
F: Fn(&str) -> Option<ArtifactId>,
{
let Some(reader) = &self.reader else {
return Ok(Vec::new());
};
let tokens = self.tokens.open();
crate::list_archive_entries(
reader.as_ref(),
tokens.as_ref(),
name_filter,
limit,
content_type,
coordinate,
)
}
}
pub fn strip_repo<'a>(repo: &str, suburl: &'a str) -> &'a str {
let path = suburl.trim_start_matches('/');
path.strip_prefix(repo)
.map(|r| r.trim_start_matches('/'))
.unwrap_or(path)
}
pub fn not_found(reason: &str) -> HttpReply {
(404, Vec::new(), reason.as_bytes().to_vec())
}
pub fn ok(content_type: &str, body: Vec<u8>) -> HttpReply {
(
200,
vec![("Content-Type".into(), content_type.into())],
body,
)
}
pub struct DocMemo<V: Clone = crate::Bytes> {
cap: usize,
map: std::sync::Mutex<std::collections::HashMap<String, V>>,
}
impl<V: Clone> DocMemo<V> {
pub fn new(cap: usize) -> Self {
Self {
cap,
map: std::sync::Mutex::new(std::collections::HashMap::new()),
}
}
pub fn get_or(&self, key: &str, build: impl FnOnce() -> Option<V>) -> Option<V> {
if let Some(hit) = self.map.lock().unwrap_or_else(|p| p.into_inner()).get(key) {
return Some(hit.clone());
}
let built = build()?;
let mut map = self.map.lock().unwrap_or_else(|p| p.into_inner());
if map.len() >= self.cap {
map.clear();
}
map.insert(key.to_string(), built.clone());
Some(built)
}
}
impl<V: Clone> Default for DocMemo<V> {
fn default() -> Self {
Self::new(16_384)
}
}
pub fn ok_bytes(content_type: &str, body: crate::Bytes) -> crate::HttpBytesReply {
(
200,
vec![("Content-Type".into(), content_type.into())],
body,
)
}
pub fn not_found_bytes(reason: &str) -> crate::HttpBytesReply {
(
404,
Vec::new(),
crate::Bytes::copy_from_slice(reason.as_bytes()),
)
}
pub fn sha256_hex(data: &[u8]) -> String {
nornir_hash::sha256_hex(data)
}
#[macro_export]
macro_rules! znippy_read_only {
($base:ident) => {
fn name(&self) -> &str {
self.$base.name()
}
fn is_writable(&self) -> bool {
false
}
fn put(&self, _id: &$crate::ArtifactId, _data: &[u8]) -> $crate::anyhow::Result<()> {
self.$base.refuse_put()
}
fn caps(&self) -> $crate::Caps {
$crate::Caps::znippy(self.$base.has_archive())
}
fn archive(&self) -> $crate::anyhow::Result<$crate::Archive> {
self.$base.archive()
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_repo_prefix_is_stripped_once() {
assert_eq!(strip_repo("pkgs", "/pkgs/a/b"), "a/b");
assert_eq!(strip_repo("pkgs", "pkgs/a"), "a");
assert_eq!(strip_repo("pkgs", "/other/a"), "other/a");
}
#[test]
fn no_archive_is_unsupported_not_empty() {
let b = ZnippyBase::new("r");
assert!(!b.has_archive());
assert!(crate::is_unsupported(&b.archive().unwrap_err()));
assert!(b.refuse_put().is_err());
assert!(b.list_entries(None, 0, "x", |_| None).unwrap().is_empty());
}
#[test]
fn sha256_hex_is_the_known_vector() {
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
}