holger-traits 2.0.0

holger's shared vocabulary: ArtifactId, RepositoryBackendTrait, ZnippyPlugin discriminants, and ArtifactFormat — including `ArtifactFormat::home()`, the format→crate map that answers which crate serves PyPI when grepping cannot.
Documentation
//! **`ZnippyBase`** — what every read-only `znippy-*` repository backend holds
//! and does the same way: the name, the archive (typed and as a plain reader),
//! the change-token index, the repo-prefix strip, the 404/text replies and the
//! one SHA-256 helper. A backend keeps a `base: ZnippyBase` and supplies only
//! its format logic; [`znippy_read_only!`](crate::znippy_read_only) writes the
//! five trait methods that are the same everywhere.

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,
    /// The typed archive, when the backend was opened from a file (the typed
    /// views — `as_maven()`, `as_python()`, … — live on it).
    archive: Option<Arc<ZnippyArchive>>,
    /// The archive as a plain reader: the typed archive above, or the reader
    /// handed to [`with_reader`](Self::with_reader).
    reader: Option<Arc<dyn ZnippyReader>>,
    tokens: ArchiveTokens,
}

impl ZnippyBase {
    /// No archive: every read misses and [`Caps::archive`](crate::Caps::archive) is off.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into(), archive: None, reader: None, tokens: ArchiveTokens::none() }
    }

    /// Open the archive at `path`; its lookup sub-index answers change tokens.
    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),
        })
    }

    /// Any reader. No typed views, no path, so no change tokens.
    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() }
    }

    /// A writable archive at `path` that may not exist yet: no reader is held
    /// (the backend re-opens per read), but change tokens are read from `path`.
    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
    }

    /// The typed archive, when opened from a file.
    pub fn typed(&self) -> Option<&Arc<ZnippyArchive>> {
        self.archive.as_ref()
    }

    /// The archive as a plain reader.
    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
    }

    /// The archive's file table, or empty with no archive.
    pub fn list_files(&self) -> Vec<String> {
        self.reader.as_ref().and_then(|r| r.list_files().ok()).unwrap_or_default()
    }

    /// One file's bytes out of the archive.
    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)
    }

    /// The trait's `archive()`: the paths and sizes, `Unsupported` with no archive.
    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),
        }
    }

    /// The trait's `put()` on a read-only archive.
    pub fn refuse_put(&self) -> anyhow::Result<()> {
        anyhow::bail!("znippy repository '{}' is read-only", self.name)
    }

    /// `suburl` without its leading `/` and `/<repo>/` prefix.
    pub fn strip_repo<'a>(&self, suburl: &'a str) -> &'a str {
        strip_repo(&self.name, suburl)
    }

    /// The shared archive listing: every path `coordinate` names, with a change
    /// token where the archive's lookup sub-index can answer one.
    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)
    }
}

/// `suburl` without its leading `/` and `/<repo>/` prefix.
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)
}

/// A `404` with a plain-text reason.
pub fn not_found(reason: &str) -> HttpReply {
    (404, Vec::new(), reason.as_bytes().to_vec())
}

/// A `200` with one `Content-Type`.
pub fn ok(content_type: &str, body: Vec<u8>) -> HttpReply {
    (200, vec![("Content-Type".into(), content_type.into())], body)
}

/// SHA-256 of `data`, lowercase hex — the digest pip, apt, dnf, cargo and OCI
/// clients verify served bytes against. The ONE helper the backends share.
pub fn sha256_hex(data: &[u8]) -> String {
    nornir_hash::sha256_hex(data)
}

/// The five trait methods every read-only znippy backend spells the same way:
/// `name`, `is_writable` (false), `put` (refused), `caps` (a listing, plus the
/// archive while one is loaded) and `archive`. Invoke inside the
/// `impl RepositoryBackendTrait` block with the `ZnippyBase` field's name.
#[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");
    }
}