holger_traits/lib.rs
1//! Foundational contracts and shared types for holger — the seam every backend,
2//! upstream, and connector implements, plus the coordinate/format vocabulary they
3//! all speak. This crate deliberately sits at the bottom of the dep graph and
4//! stays thin: it depends on `znippy-common` (for the source-of-truth type ids)
5//! but NOT on the sibling `znippy-plugin-*` crates.
6//!
7//! The three server-side seams:
8//! * [`RepositoryBackendTrait`] — a repo that serves an ecosystem's native index
9//! (see [`backend`]): the core six, ONE [`Caps`] answer, and the methods the
10//! caps unlock. A wrapper implements [`Decorator`] and forwards by construction.
11//! * [`Upstream`] — a read-oriented `RepositoryBackendTrait` that a proxy
12//! reads through on a miss and asks what the origin published.
13//! * [`HolgerObject`] — the transport-agnostic facade (in-process engine vs gRPC
14//! client, one `Arc<dyn>` handle), the Rust mirror of `holger.proto`.
15//!
16//! Agent-side, [`ConnectorTrait`] moves assets between a Source and Target; its
17//! [`UpstreamAuth`] cousin here is the *server-side* auth enum, distinct from the
18//! agent's `ConnectorAuth`.
19//!
20//! GOTCHA: znippy is the single source of truth for [`ArtifactFormat::znippy_type_id`]
21//! discriminants — most are derived by calling the znippy handler's `type_id()`
22//! directly so they can't drift, but `Pip` (2) and `Maven3` (3) stay hardcoded
23//! literals because their native handlers live in the plugin crates this crate
24//! won't depend on. The `znippy_type_ids_match_*` tests guard those two.
25
26use async_trait::async_trait;
27use serde::{Deserialize, Serialize};
28
29/// The artifact byte buffer every backend hands back. Re-exported so a
30/// backend spells `traits::Bytes` and no repository manifest has to name the
31/// crate. See `.nornir/vec-to-bytes-migration.md`.
32// znippy-common, re-exported so a consumer binds the SAME copy this crate's
33// `ZnippyReader` signatures mean. holger's workspace has resolved TWO of them
34// before now (a registry copy for `traits` and a path copy for a feature
35// elsewhere), and the failure mode is a type that implements `ZnippyReader` and
36// still will not go where one is wanted.
37pub use znippy_common;
38
39pub use bytes::Bytes;
40
41/// anyhow, re-exported for [`znippy_read_only!`]'s expansion.
42pub use anyhow;
43
44/// The repository backend seam: [`RepositoryBackendTrait`], [`Caps`],
45/// [`Decorator`] and the [`backend::conformance`] check that holds caps and
46/// methods against each other.
47pub mod backend;
48pub use backend::{
49 chunks_of, collect_body, is_unsupported, unsupported, Access, Archive, ArchiveInfo, Cap, Caps,
50 ChunkIter, Decorator, HttpBytesReply, HttpReply, RepositoryBackendTrait, StreamedGet,
51 Unsupported, READER_PREALLOC_CAP,
52};
53
54#[cfg(feature = "http")]
55pub mod http;
56/// What every read-only `znippy-*` backend shares.
57pub mod znippy_base;
58pub use nornir_hash::hex_encode;
59pub use znippy_base::{sha256_hex, DocMemo, ZnippyBase};
60
61/// holger's own pin on the znippy on-disk archive format it will parse — the
62/// reader-side gate that refuses a *newer*-than-known archive with a typed,
63/// request-facing error instead of letting an unknown layout reach the parser.
64/// Lives here so every `znippy-*` repository backend (all of which already depend
65/// on this crate) consumes the one implementation.
66pub mod znippy_format;
67
68/// **MIGRATE** — the vocabulary for the ONE-TIME move of an existing Nexus or
69/// Artifactory registry into holger. The format map, the repository creation plan
70/// with its collision refusal, and the [`migrate::MigrationSink`] seam the byte
71/// mover writes through. It lives here because the agent CLI and the server's
72/// `MigrationService` must classify a repository the SAME way, and a classifier
73/// that exists twice will disagree once.
74pub mod migrate;
75/// **One rule for a path a request names** (R1 follow-up): refuse or fold a string into a
76/// segment or a relative path below a root; every join of request data goes through it.
77pub mod safe_path;
78
79pub mod format;
80pub mod index_row;
81
82/// The shared test kit. Dev-dependency only (`features = ["test-support"]`).
83#[cfg(feature = "test-support")]
84pub mod test_support;
85
86pub use znippy_format::{
87 ensure_supported_format, recorded_format_version, ArchiveFormatError, FormatGate,
88 MAX_SUPPORTED_ZNIPPY_FORMAT, ZNIPPY_FORMAT_VERSION_KEY,
89};
90
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
92pub struct ArtifactId {
93 pub namespace: Option<String>,
94 pub name: String,
95 pub version: String,
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
99#[serde(rename_all = "lowercase")]
100pub enum ArtifactFormat {
101 Maven3,
102 Pip,
103 Rust,
104 Go,
105 Nuget,
106 Npm,
107 Gem,
108 Deb,
109 Rpm,
110 Helm,
111 Docker,
112 Conda,
113 Composer,
114 /// znippy's own native package format (a merged/signed `.znippy` package
115 /// served as the artifact itself, rather than a backing store for some
116 /// other ecosystem). The one format that is znippy all the way down.
117 Znippy,
118 Raw,
119}
120
121impl ArtifactFormat {
122 /// Canonical znippy `pkg_type` / DenseUnion discriminant for this format.
123 ///
124 /// znippy is the **single source of truth** for these numbers (see
125 /// `znippy-common`'s native + skeleton handlers). Every variant whose handler
126 /// is reachable from `znippy-common` calls that handler's
127 /// [`ArchiveTypePlugin::type_id`] directly — including `Rust`, whose native
128 /// `cargo_native::CargoPlugin` lives in `znippy-common` — so the two can never
129 /// drift (the test below asserts the equality as data). Only `Pip` (2) and
130 /// `Maven3` (3) remain literals: their native handlers live in the sibling
131 /// `znippy-plugin-python` / `znippy-plugin-maven` crates, which this
132 /// foundational `traits` crate deliberately does NOT depend on (keeping the
133 /// base dep graph thin). The `znippy_type_ids_match_*` tests assert those two
134 /// literals still equal znippy's published discriminants.
135 pub fn znippy_type_id(&self) -> i8 {
136 use znippy_common::plugin::ArchiveTypePlugin;
137 use znippy_common::plugins::{cargo_native, skeletons};
138 match self {
139 // Native cargo handler lives in znippy-common — derive, don't hardcode.
140 ArtifactFormat::Rust => cargo_native::CargoPlugin::new().type_id(),
141 ArtifactFormat::Pip => 2,
142 ArtifactFormat::Maven3 => 3,
143 ArtifactFormat::Go => skeletons::GoPlugin.type_id(),
144 ArtifactFormat::Nuget => skeletons::NugetPlugin.type_id(),
145 // npm is a real native handler now (`plugins::npm_native`), not a skeleton.
146 ArtifactFormat::Npm => znippy_common::plugins::npm_native::NpmPlugin.type_id(),
147 // rpm is a real native handler now (`plugins::rpm_native`), not a skeleton.
148 ArtifactFormat::Rpm => znippy_common::plugins::rpm_native::RpmPlugin.type_id(),
149 // deb is a real native handler now (`plugins::deb_native`), not a skeleton.
150 ArtifactFormat::Deb => znippy_common::plugins::deb_native::DebPlugin.type_id(),
151 // gem is a real native handler now (`plugins::gem_native`), not a skeleton.
152 ArtifactFormat::Gem => znippy_common::plugins::gem_native::GemPlugin.type_id(),
153 ArtifactFormat::Docker => skeletons::DockerPlugin.type_id(),
154 ArtifactFormat::Helm => skeletons::HelmPlugin.type_id(),
155 // conda is a real native handler now (`plugins::conda_native`), not a skeleton.
156 ArtifactFormat::Conda => znippy_common::plugins::conda_native::CondaPlugin.type_id(),
157 ArtifactFormat::Composer => skeletons::ComposerPlugin.type_id(),
158 // znippy's own container format — not one of the ecosystem handler
159 // discriminants, so it gets a dedicated reserved id.
160 ArtifactFormat::Znippy => 100,
161 ArtifactFormat::Raw => 0,
162 }
163 }
164
165 /// Parse a Nexus/Artifactory/CLI format string into an `ArtifactFormat`.
166 pub fn from_format_str(s: &str) -> Option<Self> {
167 Some(match s.to_lowercase().as_str() {
168 "maven2" | "maven" | "maven3" | "java" => ArtifactFormat::Maven3,
169 "pip" | "pypi" | "python" => ArtifactFormat::Pip,
170 "rust" | "cargo" | "crates.io" | "cratesio" => ArtifactFormat::Rust,
171 "go" | "golang" => ArtifactFormat::Go,
172 "nuget" | "dotnet" => ArtifactFormat::Nuget,
173 "npm" | "node" => ArtifactFormat::Npm,
174 "gem" | "ruby" | "rubygems" => ArtifactFormat::Gem,
175 "deb" | "debian" | "apt" => ArtifactFormat::Deb,
176 "rpm" | "yum" | "dnf" => ArtifactFormat::Rpm,
177 "helm" | "chart" => ArtifactFormat::Helm,
178 "docker" | "oci" => ArtifactFormat::Docker,
179 "conda" | "anaconda" => ArtifactFormat::Conda,
180 "composer" | "php" => ArtifactFormat::Composer,
181 "znippy" | "snippy" => ArtifactFormat::Znippy,
182 // Artifactory calls this repo class "Generic"; holger calls it Raw.
183 "raw" | "generic" => ArtifactFormat::Raw,
184 _ => return None,
185 })
186 }
187
188 /// **Where this format's backend actually LIVES.** The answer to "I know the
189 /// capability by one name — which crate implements it?"
190 ///
191 /// # Why this exists (a real, repeated cost)
192 ///
193 /// A capability in holger routinely carries FOUR different names, and the one
194 /// in the docs is usually not the one in the source tree. PyPI is the worst
195 /// case, and it has already caused two wrong answers and a nearly-started
196 /// 677-LOC re-implementation of code that was sitting right there:
197 ///
198 /// | where | the name it uses |
199 /// |---|---|
200 /// | README / design docs / the UI | **PyPI** |
201 /// | `ron_repo_type` an operator writes | `pip` |
202 /// | this enum + the backend struct | `Pip` / `PipRepoZnippy` |
203 /// | the crate + its directory | **`znippy-python`** / `holger-znippy-python-repository` |
204 ///
205 /// So `grep -ri pypi server/` returns **nothing from the implementation**, and
206 /// `grep -ri python` finds only a directory. [`from_format_str`] already maps
207 /// the spoken aliases onto the variant, but it stops there — it never says
208 /// where the code is. That last hop is the one that was missing, so this is it.
209 ///
210 /// `crate_dir` is relative to `server/repository/`, or empty for a format whose
211 /// backend is not a separate repository crate (`Raw` lives in
212 /// `server/lib/src/raw.rs`). `also` names a SECOND backend for the same format
213 /// where one exists (a file-backed peer of the znippy-backed one).
214 ///
215 /// The mapping is asserted against the real directory layout by
216 /// `every_format_names_a_crate_that_exists`, so a renamed crate breaks the
217 /// build instead of quietly re-opening the trap.
218 ///
219 /// [`from_format_str`]: ArtifactFormat::from_format_str
220 pub fn home(&self) -> FormatHome {
221 // (config_key, aliases, crate_dir, package, also)
222 let (config_key, aliases, crate_dir, package, also) = match self {
223 ArtifactFormat::Maven3 => (
224 "maven3",
225 &["maven", "maven2", "java"][..],
226 "znippy-maven",
227 "holger-znippy-maven-repository",
228 None,
229 ),
230 // The four-name case documented above: docs say PyPI, config says pip,
231 // code says Pip, the crate says python.
232 ArtifactFormat::Pip => (
233 "pip",
234 &["pypi", "python"][..],
235 "znippy-python",
236 "holger-znippy-python-repository",
237 None,
238 ),
239 // Note the word order flips between dir and package here too:
240 // `znippy-rust/` is `holger-rust-znippy-repository`.
241 ArtifactFormat::Rust => (
242 "rust",
243 &["cargo", "crates.io", "cratesio"][..],
244 "znippy-rust",
245 "holger-rust-znippy-repository",
246 Some(("file-rust", "holger-rust-file-repository")),
247 ),
248 ArtifactFormat::Go => (
249 "go",
250 &["golang"][..],
251 "znippy-go",
252 "holger-znippy-go-repository",
253 None,
254 ),
255 ArtifactFormat::Nuget => (
256 "nuget",
257 &["dotnet"][..],
258 "znippy-nuget",
259 "holger-znippy-nuget-repository",
260 None,
261 ),
262 ArtifactFormat::Npm => (
263 "npm",
264 &["node"][..],
265 "znippy-npm",
266 "holger-znippy-npm-repository",
267 None,
268 ),
269 ArtifactFormat::Gem => (
270 "gem",
271 &["ruby", "rubygems"][..],
272 "znippy-gem",
273 "holger-znippy-gem-repository",
274 None,
275 ),
276 ArtifactFormat::Deb => (
277 "deb",
278 &["debian", "apt"][..],
279 "znippy-deb",
280 "holger-znippy-deb-repository",
281 None,
282 ),
283 ArtifactFormat::Rpm => (
284 "rpm",
285 &["yum", "dnf"][..],
286 "znippy-rpm",
287 "holger-znippy-rpm-repository",
288 None,
289 ),
290 ArtifactFormat::Helm => (
291 "helm",
292 &["chart"][..],
293 "znippy-helm",
294 "holger-znippy-helm-repository",
295 None,
296 ),
297 // `oci` is the config alias AND a second, file-backed implementation.
298 ArtifactFormat::Docker => (
299 "docker",
300 &["oci"][..],
301 "znippy-docker",
302 "holger-znippy-docker-repository",
303 Some(("file-oci", "holger-file-oci-repository")),
304 ),
305 ArtifactFormat::Conda => (
306 "conda",
307 &["anaconda"][..],
308 "znippy-conda",
309 "holger-znippy-conda-repository",
310 None,
311 ),
312 ArtifactFormat::Composer => (
313 "composer",
314 &["php"][..],
315 "znippy-composer",
316 "holger-znippy-composer-repository",
317 None,
318 ),
319 // znippy-as-the-artifact. The crate is `znippy-package`, not `znippy`.
320 ArtifactFormat::Znippy => (
321 "znippy",
322 &["snippy"][..],
323 "znippy-package",
324 "holger-znippy-package-repository",
325 None,
326 ),
327 // Not a repository crate: the backend is `server/lib/src/raw.rs`.
328 ArtifactFormat::Raw => ("raw", &["generic"][..], "", "holger-server-lib", None),
329 };
330 FormatHome {
331 format: self.clone(),
332 config_key,
333 aliases,
334 crate_dir,
335 package,
336 also,
337 }
338 }
339}
340
341/// Where one [`ArtifactFormat`]'s backend lives, plus every other name the same
342/// capability is called by. See [`ArtifactFormat::home`] for why this is needed.
343#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct FormatHome {
345 /// The format itself.
346 pub format: ArtifactFormat,
347 /// The canonical `ron_repo_type` string an operator writes in a config.
348 pub config_key: &'static str,
349 /// The OTHER names this capability is known by — docs, UI labels, ecosystem
350 /// spellings. Searching any of them should lead here.
351 pub aliases: &'static [&'static str],
352 /// Directory under `server/repository/`, or `""` when the backend is not a
353 /// separate repository crate.
354 pub crate_dir: &'static str,
355 /// The cargo package name of that crate.
356 pub package: &'static str,
357 /// A second `(crate_dir, package)` backend for the same format, when one
358 /// exists (e.g. the file-backed peer of a znippy-backed repo).
359 pub also: Option<(&'static str, &'static str)>,
360}
361
362impl FormatHome {
363 /// Every name this capability answers to — the config key first, then the
364 /// aliases. Handy for a "did you mean?" or a docs table.
365 pub fn all_names(&self) -> Vec<&'static str> {
366 std::iter::once(self.config_key)
367 .chain(self.aliases.iter().copied())
368 .collect()
369 }
370}
371
372/// Every format holger knows, in declaration order — so a caller can enumerate
373/// the capability set instead of hand-maintaining a second list.
374pub const ALL_ARTIFACT_FORMATS: &[ArtifactFormat] = &[
375 ArtifactFormat::Maven3,
376 ArtifactFormat::Pip,
377 ArtifactFormat::Rust,
378 ArtifactFormat::Go,
379 ArtifactFormat::Nuget,
380 ArtifactFormat::Npm,
381 ArtifactFormat::Gem,
382 ArtifactFormat::Deb,
383 ArtifactFormat::Rpm,
384 ArtifactFormat::Helm,
385 ArtifactFormat::Docker,
386 ArtifactFormat::Conda,
387 ArtifactFormat::Composer,
388 ArtifactFormat::Znippy,
389 ArtifactFormat::Raw,
390];
391
392// === Upstreams (server side, sync request path) ===
393//
394// An upstream is a registry holger reads from on a local miss (another holger,
395// crates.io, a Skidbladnir source). It is a read-oriented
396// [`RepositoryBackendTrait`], so it drops straight into `ProxyBackend`: `fetch()`
397// is the read and a writable primary write-through-caches the hit. Its HTTP is
398// impl-side and SYNC (`ureq`): the server request path runs inside the async
399// hyper handler, where a blocked-on `reqwest` panics.
400
401/// How an upstream authenticates with its registry — the server-side enum,
402/// distinct from the agent-side `ConnectorAuth`.
403#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
404pub enum UpstreamAuth {
405 /// No authentication.
406 #[default]
407 None,
408 /// HTTP Basic auth.
409 Basic { username: String, password: String },
410 /// Bearer token.
411 Bearer { token: String },
412 /// Custom API-key header.
413 ApiKey { header: String, key: String },
414 /// mTLS client cert (built into the HTTP client, no per-request header).
415 Mtls { cert_pem: String, key_pem: String },
416}
417
418/// Size + checksum + content-type for an upstream artifact: lets the proxy
419/// verify a fetched body before it caches it.
420#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
421pub struct ArtifactMeta {
422 pub size: Option<u64>,
423 pub sha256: Option<String>,
424 pub content_type: Option<String>,
425}
426
427/// **An upstream registry** — a read-oriented [`RepositoryBackendTrait`] that
428/// knows its base URL and auth and can state what the ORIGIN published for a
429/// coordinate, the one fact a pull-through cache cannot compute for itself.
430pub trait Upstream: RepositoryBackendTrait {
431 /// The upstream base, e.g. `https://index.crates.io`.
432 fn base_url(&self) -> &str;
433
434 /// Credentials attached to upstream requests.
435 fn auth(&self) -> &UpstreamAuth;
436
437 /// Size + checksum + content-type; `Ok(None)` when the upstream has no such artifact.
438 fn metadata(&self, id: &ArtifactId) -> anyhow::Result<Option<ArtifactMeta>>;
439
440 /// The lowercase-hex sha256 the origin publishes for `id`, or `Ok(None)`
441 /// when it publishes none (an honest "no claim", never a pass mark). `Err`
442 /// is "I could not ask", which is not a pass mark either.
443 fn advertised_sha256(&self, id: &ArtifactId) -> anyhow::Result<Option<String>> {
444 Ok(self
445 .metadata(id)?
446 .and_then(|m| m.sha256)
447 .and_then(|s| normalize_sha256(s.trim().trim_start_matches("sha256:"))))
448 }
449}
450
451// === The change token a znippy-backed listing CAN answer ===
452
453/// **A handle on the archive path whose lookup sub-index can answer change
454/// tokens.**
455///
456/// Cheap and `Clone`: it holds a path and nothing else. The index itself is
457/// opened per listing by [`ArchiveTokens::open`], never cached, because a
458/// writable / hot-append archive is re-opened per read on the backends that
459/// have one and a cached index would answer about bytes that have since moved.
460/// An index read is bounded — footer, manifest, lookup section, trie — and
461/// touches **no chunk data at all**, which is the property the whole feature
462/// rests on and which `a_znippy_listing_stamps_a_token_and_never_extracts_a_byte`
463/// counts.
464#[derive(Debug, Clone, Default)]
465pub struct ArchiveTokens {
466 path: Option<std::path::PathBuf>,
467}
468
469impl ArchiveTokens {
470 /// No archive, so no tokens. The honest state for a backend built from a
471 /// bare [`znippy_common::ZnippyReader`] (no path to read an index from) or
472 /// from nothing at all.
473 pub const fn none() -> Self {
474 Self { path: None }
475 }
476
477 /// Tokens from the archive at `path`.
478 pub fn at(path: impl Into<std::path::PathBuf>) -> Self {
479 Self {
480 path: Some(path.into()),
481 }
482 }
483
484 /// The archive this reads, when there is one.
485 pub fn path(&self) -> Option<&std::path::Path> {
486 self.path.as_deref()
487 }
488
489 /// Open the lookup sub-index for ONE listing.
490 ///
491 /// `None` when there is no archive, or when the archive carries no lookup
492 /// sub-index (a pre-v0.7 seal), or when it cannot be read. All three are
493 /// "this listing cannot answer a token", which is a state the wire already
494 /// has a spelling for — never an error and never a fabricated value.
495 pub fn open(&self) -> Option<ArchiveTokenIndex> {
496 let path = self.path.as_deref()?;
497 znippy_common::ArchiveReader::open(path)
498 .ok()
499 .map(|reader| ArchiveTokenIndex { reader })
500 }
501}
502
503/// One archive's lookup sub-index, held open for the duration of one listing.
504///
505/// Every [`token`](Self::token) after the open is pure memory: an fst lookup or
506/// a binary search over the already-decoded columns, then a fold of checksums
507/// that were loaded with the index.
508pub struct ArchiveTokenIndex {
509 reader: znippy_common::ArchiveReader,
510}
511
512/// Domain separator for holger's change-token fold. It is holger's own and
513/// deliberately NOT znippy's `sign::file_digest` tag: `sign` is an optional
514/// feature carrying the whole CMS stack, and a change token is **source-scoped**
515/// — nothing outside this server ever compares one against a value computed by
516/// other code, so agreeing with another implementation buys nothing. The INPUTS
517/// are the same index columns either way.
518const CHANGE_TOKEN_TAG: &[u8] = b"holger.change-token.v1";
519
520impl ArchiveTokenIndex {
521 /// Chunk rows the index carries, across all files. The counter the
522 /// "reads the index, not the store" measurement reports.
523 pub fn rows(&self) -> usize {
524 self.reader.row_count()
525 }
526
527 /// The change token for one archive-relative path: a BLAKE3 fold of the
528 /// path and of the per-chunk checksums the index already holds, in
529 /// `chunk_seq` order, as 64 lowercase hex characters.
530 ///
531 /// **No artifact byte is read.** The chunk checksums come off the lookup
532 /// sub-index that was loaded at [`ArchiveTokens::open`]; the fold hashes 32
533 /// bytes per chunk. This is why a znippy-backed listing can answer this and
534 /// cannot answer [`ArtifactEntry::sha256`] — the latter is a hash of the
535 /// bytes and would mean extracting the whole repository.
536 ///
537 /// `None` when the path is not in the archive.
538 ///
539 /// The path is part of the fold on purpose, exactly as znippy's own
540 /// provenance digest does it: two entries with identical bytes are two
541 /// different artifacts at this source, and a token that collapsed them
542 /// would say `unchanged` about a coordinate that had been repointed. It is
543 /// also, precisely, why this value is NOT a content digest and must never
544 /// be put in `sha256`.
545 pub fn token(&self, relative_path: &str) -> Option<String> {
546 let chunks = self.reader.locate(relative_path);
547 if chunks.is_empty() {
548 return None;
549 }
550 let mut h = znippy_common::blake3::Hasher::new();
551 h.update(CHANGE_TOKEN_TAG);
552 h.update(&(relative_path.len() as u64).to_le_bytes());
553 h.update(relative_path.as_bytes());
554 h.update(&(chunks.len() as u64).to_le_bytes());
555 // `ArchiveReader::locate` returns the file's chunks sorted by
556 // `chunk_seq`, so the fold is order-stable without a second sort.
557 for c in &chunks {
558 h.update(&c.chunk_seq.to_le_bytes());
559 h.update(&c.checksum);
560 }
561 Some(nornir_hash::hex_encode(h.finalize().as_bytes()))
562 }
563}
564
565// === The list() shape every znippy-backed backend was writing out by hand ===
566
567/// Walk a znippy archive's file table and turn the entries a `coordinate`
568/// function recognises into [`ArtifactEntry`] rows.
569///
570/// Only the path→coordinate parse differs per ecosystem, so that is the only
571/// part left to the caller ([`ZnippyBase::list_entries`] passes the tokens).
572/// `limit == 0` means no cap. Paths `coordinate` returns `None` for are
573/// skipped, which is how a backend ignores its own index/metadata entries.
574/// `tokens` is the archive's lookup sub-index, when the backend has a path to
575/// read one from ([`ArchiveTokens::open`]). Every row it can answer for gets an
576/// [`ArtifactEntry::change_token`]; the rest stay absent. Passing `None` is the
577/// honest answer for a backend built from a bare reader with no archive path.
578pub fn list_archive_entries<F>(
579 reader: &dyn znippy_common::ZnippyReader,
580 tokens: Option<&ArchiveTokenIndex>,
581 name_filter: Option<&str>,
582 limit: usize,
583 content_type: &str,
584 coordinate: F,
585) -> anyhow::Result<Vec<ArtifactEntry>>
586where
587 F: Fn(&str) -> Option<ArtifactId>,
588{
589 let mut out = Vec::new();
590 for path in reader.list_files()? {
591 let Some(id) = coordinate(&path) else {
592 continue;
593 };
594 if let Some(f) = name_filter {
595 if !id.name.contains(f) {
596 continue;
597 }
598 }
599 // Publication time and digest are UNKNOWN here, and that is measured,
600 // not lazy. `ZnippyReader` is `list_files` / `file_size` / `contains` /
601 // `extract_file`: there is no modification time in the file table and
602 // no per-entry SHA-256. Answering either would mean `extract_file` +
603 // hash for every row — the whole repository read and hashed on a
604 // listing. Every znippy-backed backend therefore says `None` here, and
605 // a caller that needs a digest asks for the artifact.
606 //
607 // The CHANGE TOKEN is the one provenance question this backend can
608 // answer, and it is answered from the index alone — no chunk of any
609 // artifact is read to produce it. See [`ArchiveTokenIndex::token`].
610 out.push(
611 ArtifactEntry::unknown_provenance(
612 id,
613 reader.file_size(&path).unwrap_or(0) as i64,
614 content_type,
615 )
616 .with_change_token(tokens.and_then(|t| t.token(&path))),
617 );
618 if limit != 0 && out.len() >= limit {
619 break;
620 }
621 }
622 Ok(out)
623}
624
625/// The Cargo download path `/{repo}/crates/{name}/{version}/download` (query
626/// string ignored) as a coordinate; `None` for every other path a Rust
627/// registry serves (`config.json`, the sparse index), which name no artifact.
628/// The one mapping both Rust backends answer `coordinate_for_path` with.
629pub fn crate_download_coordinate(repo: &str, suburl: &str) -> Option<ArtifactId> {
630 let path = suburl.split('?').next().unwrap_or("");
631 match path
632 .trim_start_matches('/')
633 .split('/')
634 .collect::<Vec<_>>()
635 .as_slice()
636 {
637 [r, "crates", name, version, "download"]
638 if *r == repo && !name.is_empty() && !version.is_empty() =>
639 {
640 Some(ArtifactId {
641 namespace: None,
642 name: name.to_string(),
643 version: version.to_string(),
644 })
645 }
646 _ => None,
647 }
648}
649
650/// THE name↔version split of a `name-version` stem: at the FIRST `-` that is
651/// followed by a digit (`my-chart-1.2.0-rc-1` → `my-chart`, `1.2.0-rc-1`). The
652/// serving doors and the identity gate all name a file with it.
653pub fn split_name_version(stem: &str) -> Option<(&str, &str)> {
654 let b = stem.as_bytes();
655 let i = (0..b.len().saturating_sub(1)).find(|&i| b[i] == b'-' && b[i + 1].is_ascii_digit())?;
656 let (n, v) = (&stem[..i], &stem[i + 1..]);
657 (!n.is_empty() && !v.is_empty()).then_some((n, v))
658}
659
660/// The commonest path→coordinate parse: take the last path segment, strip
661/// `suffix`, [`split_name_version`] the stem. Serves helm (`.tgz`) and
662/// znippy-package (`.znippy`) verbatim.
663pub fn coordinate_from_name_dash_version(path: &str, suffix: &str) -> Option<ArtifactId> {
664 let file = path.rsplit('/').next().unwrap_or(path);
665 let (name, version) = split_name_version(file.strip_suffix(suffix)?)?;
666 Some(ArtifactId {
667 namespace: None,
668 name: name.to_string(),
669 version: version.to_string(),
670 })
671}
672
673// === Connector trait for external systems (Nexus, Artifactory, crates.io) ===
674
675#[derive(Debug, Clone, Serialize, Deserialize)]
676pub struct RemoteRepository {
677 pub name: String,
678 pub format: String,
679 pub repo_type: String,
680 pub url: Option<String>,
681}
682
683#[derive(Debug, Clone, Serialize, Deserialize)]
684pub struct RemoteAsset {
685 pub path: String,
686 pub download_url: String,
687 pub content_type: Option<String>,
688 pub size: Option<u64>,
689 /// **The digest the coordinate was PUBLISHED with**, when the source knew
690 /// one: `Cargo.lock`'s `checksum`, PyPI's `sha256` digest. Lowercase hex,
691 /// no algorithm prefix.
692 ///
693 /// It exists so the bytes that cross the airgap are the bytes the lockfile
694 /// pinned. Before this field the agent parsed both digests and threw them
695 /// away: a compromised registry or CDN serving substituted bytes for one
696 /// pinned coordinate had them packed into the znippy archive and certified
697 /// by a receipt whose sha256 was computed over the substitution. The
698 /// allowlist and https stopped a network-position attacker; nothing stopped
699 /// the origin itself.
700 ///
701 /// `None` means the source published no digest — it does NOT mean the bytes
702 /// are trusted, and a connector that has one must fill it in.
703 #[serde(default)]
704 pub sha256: Option<String>,
705 /// **An opaque CHANGE TOKEN for this coordinate, as published by THIS
706 /// source.**
707 ///
708 /// Equal ⇒ unchanged at this source. Different ⇒ changed at this source.
709 /// It is **never** compared across sources, and it is **never** a content
710 /// digest: it may bind the path, the storage layout, or anything else the
711 /// source finds cheap, so two sources holding byte-identical artifacts will
712 /// legitimately publish different tokens. Anything that treats it as a hash
713 /// of the bytes is wrong.
714 ///
715 /// # Why it exists
716 ///
717 /// 15 of holger's 17 repository backends are `znippy-*`, and a znippy file
718 /// table carries neither a modification time nor a per-entry SHA-256 — so
719 /// [`ArtifactEntry::published_unix_ms`] and [`ArtifactEntry::sha256`] are
720 /// both `None` and every such repository landed in `unproven` on every
721 /// mirror tick, re-fetching itself whole every cycle under the default
722 /// [`UnprovenPolicy::Refetch`](crate::RemoteAsset). What znippy DOES have,
723 /// for free, is a merkle fold of the per-chunk BLAKE3 hashes its index
724 /// already stores — a value that is stable while the bytes are stable and
725 /// differs when they differ, and which is emphatically not a content
726 /// digest. That is a change token, and this is the field for it.
727 ///
728 /// # The scope is part of the value
729 ///
730 /// A token carried here is SCOPE-STAMPED: `"<scope>|<opaque>"`, where the
731 /// scope names the source it came from and the part after the first `|` is
732 /// never interpreted. [`scope_change_token`] builds one, and
733 /// [`split_change_token`] takes it apart. A comparison between two tokens
734 /// with different scopes is refused rather than answered — which is what
735 /// makes "never compared across sources" a property of the code instead of
736 /// a rule someone has to remember.
737 ///
738 /// `None` means this source published no token. It does NOT mean the bytes
739 /// are unchanged and it does not mean they changed.
740 #[serde(default)]
741 pub change_token: Option<String>,
742}
743
744#[async_trait]
745pub trait ConnectorTrait: Send + Sync {
746 fn name(&self) -> &str;
747
748 async fn list_repositories(&self) -> anyhow::Result<Vec<RemoteRepository>>;
749
750 async fn list_assets(&self, repository: &str) -> anyhow::Result<Vec<RemoteAsset>>;
751
752 async fn download_asset(&self, asset: &RemoteAsset) -> anyhow::Result<Vec<u8>>;
753
754 async fn upload_asset(&self, repository: &str, path: &str, data: &[u8]) -> anyhow::Result<()>;
755}
756
757// === HolgerObject: the transport-agnostic facade ===
758//
759// `HolgerObject` is the single Rust contract an external partner programs
760// against. Hold an `Arc<dyn HolgerObject>` and you don't care what's behind the
761// vtable — exactly like a Java interface reference. Two transports implement it
762// today:
763// * an in-process adapter that calls the local Holger engine directly, and
764// * a remote adapter that forwards each call over gRPC (tonic client).
765// The language-neutral contract for non-Rust / remote partners is `holger.proto`
766// (the generated client/server stubs); this trait mirrors it for Rust callers.
767
768/// Summary of one configured repository (mirror of the proto `RepositoryInfo`).
769#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
770pub struct RepositoryInfo {
771 pub name: String,
772 pub repo_type: String,
773 pub writable: bool,
774 pub has_archive: bool,
775 /// Mirror of `RepositoryInfo.supports_listing`: [`Caps::listing`].
776 pub supports_listing: bool,
777 /// Mirror of `RepositoryInfo.is_group`: a read-only view whose archive
778 /// figures are the SUM of `members` — skip it when summing a fleet.
779 pub is_group: bool,
780 /// Mirror of `RepositoryInfo.members`: the group's member names, in order;
781 /// empty for a repository that owns its storage.
782 pub members: Vec<String>,
783}
784
785impl RepositoryInfo {
786 /// The ONE mapping from a backend to its catalog row: every field is read
787 /// off the backend's own [`Caps`], so the catalog cannot drift from it.
788 pub fn of(name: &str, repo: &dyn RepositoryBackendTrait) -> RepositoryInfo {
789 let caps = repo.caps();
790 RepositoryInfo {
791 name: name.to_string(),
792 repo_type: format!("{:?}", repo.format()),
793 writable: repo.is_writable(),
794 has_archive: caps.archive,
795 supports_listing: caps.listing,
796 is_group: caps.group,
797 members: repo.members(),
798 }
799 }
800}
801
802/// One artifact in a repository listing (mirror of the proto `ArtifactEntry`).
803///
804/// # The two fields that are allowed to say "I don't know"
805///
806/// [`published_unix_ms`](Self::published_unix_ms) and [`sha256`](Self::sha256)
807/// are `Option`, and the `None` is the whole point. A listing is assembled by
808/// whichever backend owns the bytes, and the backends genuinely differ in what
809/// they can answer WITHOUT reading the artifact:
810///
811/// * a loose-file backend stats the file it is already statting, so a
812/// modification time costs nothing extra;
813/// * a znippy-backed backend reads its file table through
814/// [`znippy_common::ZnippyReader`], which publishes `list_files`,
815/// `file_size`, `contains` and `extract_file` and **no** modification time
816/// and **no** per-entry digest — so the only way it could answer either is to
817/// extract and hash every artifact in the repository, on the listing path.
818///
819/// A listing that takes minutes is a worse defect than a listing that is
820/// missing a column, so a backend that would have to read bytes answers `None`.
821///
822/// **`None` means "not known here", never "zero" and never "empty".** The same
823/// discipline [`RemoteAsset::sha256`] already states: an absent digest is not a
824/// statement about the bytes. Do not paper over it with `unwrap_or(0)` or
825/// `unwrap_or_default()` — a fabricated `0` timestamp sorts as 1970 and a
826/// fabricated empty digest compares equal to another empty digest, and both of
827/// those read as real answers.
828///
829/// Build one with [`ArtifactEntry::unknown_provenance`] and then say what you
830/// do know with [`with_published_unix_ms`](Self::with_published_unix_ms) /
831/// [`with_sha256`](Self::with_sha256), so that "I cannot answer this" is spelled
832/// out loud at the call site instead of being a field somebody forgot.
833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
834pub struct ArtifactEntry {
835 pub id: ArtifactId,
836 pub size_bytes: i64,
837 pub content_type: String,
838 /// When these bytes were published, in **Unix milliseconds UTC**.
839 ///
840 /// `None` = this backend does not know. Milliseconds rather than seconds
841 /// because two artifacts published in the same second are ordinary, and a
842 /// "most recently changed" list that ties on them shuffles between loads.
843 ///
844 /// Non-positive values are not carried: see [`normalize_published_unix_ms`].
845 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub published_unix_ms: Option<i64>,
847 /// Lowercase-hex SHA-256 of the artifact's bytes, 64 characters, no
848 /// `sha256:` prefix — the same spelling [`RemoteAsset::sha256`] carries, so
849 /// a mirror can compare the two without reformatting either.
850 ///
851 /// `None` = this backend does not know. A malformed value is dropped to
852 /// `None` on the way in rather than carried: see [`normalize_sha256`].
853 #[serde(default, skip_serializing_if = "Option::is_none")]
854 pub sha256: Option<String>,
855 /// **An opaque CHANGE TOKEN for these bytes, as this backend computes it.**
856 ///
857 /// Equal ⇒ unchanged **in this repository on this server**. Different ⇒
858 /// changed here. It is not a content digest and must never be compared
859 /// against one, nor against a token from any other source: see
860 /// [`RemoteAsset::change_token`], which is where a consumer stamps its own
861 /// source scope onto the value before storing or comparing it.
862 ///
863 /// This is the field a `znippy-*` backend CAN answer, which is why it
864 /// exists: `ZnippyReader`'s index already carries a BLAKE3 per chunk, so a
865 /// per-entry merkle fold of them costs one hash of already-loaded
866 /// checksums and reads no artifact bytes at all. The same backends still
867 /// answer `None` for [`published_unix_ms`](Self::published_unix_ms) and
868 /// [`sha256`](Self::sha256), because those two genuinely are not in the
869 /// file table.
870 ///
871 /// `None` = this backend does not know. Never fabricated, never empty: an
872 /// empty token would compare equal to another empty token, which is the
873 /// exact lie the whole `Option` exists to prevent.
874 #[serde(default, skip_serializing_if = "Option::is_none")]
875 pub change_token: Option<String>,
876}
877
878impl ArtifactEntry {
879 /// **"The rest of this row is unknown", for the functional-record-update
880 /// tail of a struct literal.**
881 ///
882 /// `..ArtifactEntry::UNKNOWN_PROVENANCE` at the end of a literal reads as a
883 /// sentence, and it is deliberately not `..Default::default()`: a reader
884 /// who sees `Default` has to go and look up whether the default timestamp
885 /// is `None` or `0`. This one says it in the name, and the day a third
886 /// "might not be knowable" field is added, every backend that cannot answer
887 /// it keeps compiling and keeps saying `None` — which is the correct
888 /// answer — instead of being handed a zero by a `#[derive(Default)]`.
889 ///
890 /// The `id`, `size_bytes` and `content_type` in it are never used: a
891 /// literal always overrides all three, and `String::new()` does not
892 /// allocate, so the discarded value costs nothing.
893 pub const UNKNOWN_PROVENANCE: ArtifactEntry = ArtifactEntry {
894 id: ArtifactId {
895 namespace: None,
896 name: String::new(),
897 version: String::new(),
898 },
899 size_bytes: 0,
900 content_type: String::new(),
901 published_unix_ms: None,
902 sha256: None,
903 change_token: None,
904 };
905
906 /// The three fields every backend has, and an explicit "I know nothing
907 /// about when this was published or what it hashes to".
908 ///
909 /// This is the constructor a backend that cannot answer cheaply should
910 /// call, because the name says what it is doing.
911 pub fn unknown_provenance(
912 id: ArtifactId,
913 size_bytes: i64,
914 content_type: impl Into<String>,
915 ) -> Self {
916 ArtifactEntry {
917 id,
918 size_bytes,
919 content_type: content_type.into(),
920 published_unix_ms: None,
921 sha256: None,
922 change_token: None,
923 }
924 }
925
926 /// Attach a publication time. A non-positive or absent value stays `None`
927 /// — see [`normalize_published_unix_ms`].
928 #[must_use]
929 pub fn with_published_unix_ms(mut self, ms: Option<i64>) -> Self {
930 self.published_unix_ms = normalize_published_unix_ms(ms);
931 self
932 }
933
934 /// Attach a digest. Anything that is not 64 hex characters stays `None` —
935 /// see [`normalize_sha256`].
936 #[must_use]
937 pub fn with_sha256(mut self, digest: Option<impl AsRef<str>>) -> Self {
938 self.sha256 = digest.and_then(|d| normalize_sha256(d.as_ref()));
939 self
940 }
941
942 /// Attach an opaque change token. Anything that is not a usable token —
943 /// empty, whitespace-only, over-long, or carrying a control character —
944 /// stays `None`; see [`normalize_change_token`].
945 ///
946 /// The value passed here is the backend's own RAW token. Scoping it to a
947 /// source is the consumer's job and happens at the edge that knows which
948 /// source it asked ([`scope_change_token`]).
949 #[must_use]
950 pub fn with_change_token(mut self, token: Option<impl AsRef<str>>) -> Self {
951 self.change_token = token.and_then(|t| normalize_change_token(t.as_ref()));
952 self
953 }
954
955 /// The system-time flavour of [`with_published_unix_ms`], for the loose-file
956 /// backends that get a [`std::time::SystemTime`] out of `fs::metadata`.
957 ///
958 /// A time at or before the Unix epoch, or one that does not fit an `i64` of
959 /// milliseconds, is `None` — a clock that answers nonsense is a backend
960 /// that does not know.
961 #[must_use]
962 pub fn with_published_system_time(self, t: Option<std::time::SystemTime>) -> Self {
963 self.with_published_unix_ms(t.and_then(system_time_to_unix_ms))
964 }
965}
966
967/// `SystemTime` → Unix milliseconds, or `None` when it is not after the epoch
968/// or does not fit.
969///
970/// Separate from the builder so the mapping is testable on its own, and so the
971/// "a bad clock is an unknown, not a zero" rule lives in exactly one place.
972pub fn system_time_to_unix_ms(t: std::time::SystemTime) -> Option<i64> {
973 let d = t.duration_since(std::time::UNIX_EPOCH).ok()?;
974 i64::try_from(d.as_millis()).ok().filter(|ms| *ms > 0)
975}
976
977/// PEP 503 project name: runs of `-`, `_` and `.` become one `-`, letters lowercase. The
978/// one rule of every pip door (the pip repository, the intake, the connectors); it is
979/// modgunn's `scan::canonical_pkg("pypi", _)`, and znippy-python's test
980/// `the_name_rule_is_modgunns` holds the two equal. Here, not in modgunn, so a build that
981/// links no scanner (the downstream) has it too.
982pub fn pep503_name(s: &str) -> String {
983 let mut out = String::with_capacity(s.len());
984 let mut prev_sep = false;
985 for ch in s.chars() {
986 if matches!(ch, '-' | '_' | '.') {
987 if !prev_sep {
988 out.push('-');
989 }
990 prev_sep = true;
991 } else {
992 out.push(ch.to_ascii_lowercase());
993 prev_sep = false;
994 }
995 }
996 out
997}
998
999/// The only accepted spelling of a digest in an [`ArtifactEntry`]: exactly 64
1000/// hex characters, lowercased. Everything else — an empty string, a `sha256:`
1001/// prefix, a truncated hash, a blake3 hash, whitespace — becomes `None`.
1002///
1003/// Dropping a malformed digest is the house rule (the connector path does the
1004/// same): a digest that is carried but wrong is worse than no digest, because
1005/// a mirror would compare against it and decide the bytes had changed when they
1006/// had not — or, worse, that they had not when they had.
1007pub fn normalize_sha256(s: &str) -> Option<String> {
1008 let t = s.trim();
1009 if t.len() != 64 || !t.bytes().all(|b| b.is_ascii_hexdigit()) {
1010 return None;
1011 }
1012 Some(t.to_ascii_lowercase())
1013}
1014
1015/// The only accepted spelling of a publication time: strictly positive Unix
1016/// milliseconds.
1017///
1018/// `0` and negatives become `None` on purpose. `0` is what a proto3 scalar
1019/// carries when nobody set it, and an artifact published at exactly the Unix
1020/// epoch does not occur; treating the boundary as "unknown" costs a millisecond
1021/// of expressiveness and buys the guarantee that a peer which does not know how
1022/// to answer can never accidentally claim 1970.
1023pub fn normalize_published_unix_ms(ms: Option<i64>) -> Option<i64> {
1024 ms.filter(|v| *v > 0)
1025}
1026
1027// ───────────────────────── the change token ─────────────────────────
1028
1029/// The longest change token that will be carried. A token is opaque, so there
1030/// is nothing to validate about its contents — but it is stored once per
1031/// coordinate in a map that can hold half a million of them, so it is bounded.
1032/// 512 bytes is eight times the longest token holger itself produces (a 64-char
1033/// hex fold) and still keeps a full map inside a few hundred megabytes.
1034pub const MAX_CHANGE_TOKEN_LEN: usize = 512;
1035
1036/// The only accepted spelling of a change token: non-empty after trimming, at
1037/// most [`MAX_CHANGE_TOKEN_LEN`] bytes, and free of control characters.
1038///
1039/// Everything else becomes `None`. The contents are NOT otherwise inspected —
1040/// that is what "opaque" means — but an empty string must never survive,
1041/// because an empty token compares equal to another empty token and would
1042/// report two different artifacts as `unchanged`. This is the same rule
1043/// [`normalize_sha256`] applies for the same reason.
1044pub fn normalize_change_token(s: &str) -> Option<String> {
1045 let t = s.trim();
1046 if t.is_empty() || t.len() > MAX_CHANGE_TOKEN_LEN || t.chars().any(char::is_control) {
1047 return None;
1048 }
1049 Some(t.to_string())
1050}
1051
1052/// Server health (mirror of the proto `HealthResponse`).
1053#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1054pub struct Health {
1055 pub status: String,
1056 pub version: String,
1057 pub uptime_seconds: i64,
1058}
1059
1060/// Server operating profile (mirror of the proto `ServerProfileResponse`).
1061///
1062/// This is *server truth*: whether the server accepts writes at all, derived
1063/// from the live route table (or an explicit sealed-mode override). The UI
1064/// drives its static "silent running" chrome off this rather than a local
1065/// toggle.
1066#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1067pub struct ServerProfile {
1068 /// "static" (sealed / read-only) or "dynamic" (writable / proxy).
1069 pub profile: String,
1070 /// True when the server accepts no writes on any repository.
1071 pub read_only: bool,
1072 /// Human label for the UI chrome / badge.
1073 pub label: String,
1074 /// Number of configured repositories that accept writes.
1075 pub writable_repo_count: i32,
1076}
1077
1078impl Default for ServerProfile {
1079 /// A conservative dynamic (writable) default for transports that don't
1080 /// report a profile.
1081 fn default() -> Self {
1082 Self {
1083 profile: "dynamic".into(),
1084 read_only: false,
1085 label: "DYNAMIC / WRITABLE".into(),
1086 writable_repo_count: 0,
1087 }
1088 }
1089}
1090
1091/// A cross-repo search query (mirror of the proto `SearchRequest`). Every axis
1092/// is optional (empty = unconstrained); axes AND-compose on the server.
1093#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1094pub struct SearchQuery {
1095 /// Case-insensitive substring match on the artifact name. Empty = any.
1096 pub name: String,
1097 /// Case-insensitive substring match on the namespace. Empty = any.
1098 pub namespace: String,
1099 /// Exact version match. Empty = any.
1100 pub version: String,
1101 /// Case-insensitive substring match on a raw archive file path.
1102 pub path: String,
1103 /// Restrict to these repositories. Empty = every configured repo.
1104 pub repositories: Vec<String>,
1105 /// Cap hits per kind. 0 ⇒ the server default.
1106 pub limit: i32,
1107}
1108
1109/// One artifact matched by a search, tagged with the repo it was found in
1110/// (mirror of the proto `ArtifactHit`).
1111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1112pub struct SearchArtifactHit {
1113 pub repository: String,
1114 pub id: ArtifactId,
1115 pub size_bytes: i64,
1116 pub content_type: String,
1117}
1118
1119/// One raw archive path matched by the `path` axis (mirror of the proto `PathHit`).
1120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1121pub struct SearchPathHit {
1122 pub repository: String,
1123 pub path: String,
1124}
1125
1126/// A search result page (mirror of the proto `SearchResponse`).
1127#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1128pub struct SearchResults {
1129 pub artifacts: Vec<SearchArtifactHit>,
1130 pub paths: Vec<SearchPathHit>,
1131 /// True when the result hit the limit cap and more hits exist.
1132 pub truncated: bool,
1133}
1134
1135/// A hosted SBOM document for one artifact coordinate (mirror of the proto
1136/// `FetchSbomResponse`).
1137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1138pub struct SbomDoc {
1139 /// The document bytes (byte-identical to what was attached).
1140 pub document: Vec<u8>,
1141 pub size_bytes: i64,
1142 /// blake3 hex of the document (its content address).
1143 pub content_address: String,
1144}
1145
1146/// One custom property on an artifact coordinate: a key with its ordered values
1147/// (mirror of the proto `PropertyEntry`).
1148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1149pub struct PropertyKv {
1150 pub key: String,
1151 pub values: Vec<String>,
1152}
1153
1154/// Transport-agnostic Holger facade — the Rust mirror of `holger.proto`.
1155/// Callable over either transport (in-process or gRPC) behind the same handle.
1156/// Every method is required: a transport that cannot answer one says so with an
1157/// error, never with an empty default a caller would believe.
1158#[async_trait]
1159pub trait HolgerObject: Send + Sync {
1160 /// Fetch an artifact by id from a named repository.
1161 async fn fetch(&self, repository: &str, id: &ArtifactId) -> anyhow::Result<Option<Bytes>>;
1162
1163 /// Store an artifact (write-enabled repositories only).
1164 async fn put(&self, repository: &str, id: &ArtifactId, data: &[u8]) -> anyhow::Result<()>;
1165
1166 /// List all configured repositories.
1167 async fn list_repositories(&self) -> anyhow::Result<Vec<RepositoryInfo>>;
1168
1169 /// One page of a repository's artifacts, optionally filtered by a
1170 /// `name_filter` substring, `limit` per page, paged by an opaque
1171 /// `page_token`. Returns the entries and the next token (empty when exhausted).
1172 async fn list_artifacts(
1173 &self,
1174 repository: &str,
1175 name_filter: Option<String>,
1176 limit: u32,
1177 page_token: Option<String>,
1178 ) -> anyhow::Result<(Vec<ArtifactEntry>, String)>;
1179
1180 /// The raw file paths inside the archive backing `repository`, optionally
1181 /// filtered to those starting with `prefix`.
1182 async fn list_archive_files(
1183 &self,
1184 repository: &str,
1185 prefix: Option<String>,
1186 ) -> anyhow::Result<Vec<String>>;
1187
1188 /// Stats for the archive backing `repository`.
1189 async fn archive_info(&self, repository: &str) -> anyhow::Result<ArchiveInfo>;
1190
1191 /// Server health / version / uptime.
1192 async fn health(&self) -> anyhow::Result<Health>;
1193
1194 /// Server operating profile (static/read-only vs dynamic/writable).
1195 async fn server_profile(&self) -> anyhow::Result<ServerProfile>;
1196
1197 /// Cross-repo artifact search (`SearchService.Search`).
1198 async fn search(&self, query: &SearchQuery) -> anyhow::Result<SearchResults>;
1199
1200 /// The hosted SBOM document for a coordinate (`SbomService.FetchSbom`);
1201 /// `Ok(None)` when none is attached.
1202 async fn fetch_sbom(
1203 &self,
1204 repository: &str,
1205 id: &ArtifactId,
1206 ) -> anyhow::Result<Option<SbomDoc>>;
1207
1208 /// All custom properties on a coordinate (`PropertyService.GetProperties`);
1209 /// empty when none are set.
1210 async fn get_properties(
1211 &self,
1212 repository: &str,
1213 id: &ArtifactId,
1214 ) -> anyhow::Result<Vec<PropertyKv>>;
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219 use super::*;
1220
1221 #[cfg(feature = "testmatrix")]
1222 use nornir_testmatrix::functional_status as fstatus;
1223
1224 #[test]
1225 fn znippy_type_ids_match_znippy_skeletons() {
1226 // znippy is the source of truth — these literals must equal the znippy
1227 // handler discriminants, or the mapping has drifted.
1228 assert_eq!(ArtifactFormat::Go.znippy_type_id(), 4);
1229 assert_eq!(ArtifactFormat::Nuget.znippy_type_id(), 5);
1230 assert_eq!(ArtifactFormat::Npm.znippy_type_id(), 6);
1231 assert_eq!(ArtifactFormat::Rpm.znippy_type_id(), 8);
1232 assert_eq!(ArtifactFormat::Deb.znippy_type_id(), 9);
1233 assert_eq!(ArtifactFormat::Gem.znippy_type_id(), 11);
1234 assert_eq!(ArtifactFormat::Docker.znippy_type_id(), 12);
1235 assert_eq!(ArtifactFormat::Helm.znippy_type_id(), 13);
1236 assert_eq!(ArtifactFormat::Conda.znippy_type_id(), 14);
1237 assert_eq!(ArtifactFormat::Composer.znippy_type_id(), 17);
1238 // natives
1239 assert_eq!(ArtifactFormat::Rust.znippy_type_id(), 1);
1240 assert_eq!(ArtifactFormat::Pip.znippy_type_id(), 2);
1241 assert_eq!(ArtifactFormat::Maven3.znippy_type_id(), 3);
1242
1243 #[cfg(feature = "testmatrix")]
1244 {
1245 let ok = ArtifactFormat::Helm.znippy_type_id() == 13
1246 && ArtifactFormat::Rust.znippy_type_id() == 1
1247 && ArtifactFormat::Composer.znippy_type_id() == 17;
1248 fstatus(
1249 "traits",
1250 "znippy_type_ids_match",
1251 ok,
1252 &format!(
1253 "Rust=1 Pip=2 Maven3=3 Helm=13 Composer=17 (helm={})",
1254 ArtifactFormat::Helm.znippy_type_id()
1255 ),
1256 );
1257 }
1258 }
1259
1260 /// Drift guard sourced from znippy itself: instead of comparing against
1261 /// hand-typed literals, assert each format's `znippy_type_id()` equals the
1262 /// `type_id()` of the corresponding znippy-common handler. If holger's table
1263 /// (or znippy's handler register) ever drifts, this fails — proving the two
1264 /// stay a single source of truth, as data rather than by eyeballing.
1265 ///
1266 /// Only the handlers reachable from `znippy-common` are covered (every native
1267 /// and skeleton handler except the maven/python natives, which live in the
1268 /// sibling plugin crates that `traits` does not depend on — those two stay
1269 /// guarded by the literal assertions in `znippy_type_ids_match_znippy_skeletons`).
1270 #[test]
1271 fn znippy_type_ids_derive_from_znippy_handlers_not_holger_copies() {
1272 use znippy_common::plugin::ArchiveTypePlugin;
1273 use znippy_common::plugins::{
1274 cargo_native::CargoPlugin, conda_native::CondaPlugin, deb_native::DebPlugin,
1275 gem_native::GemPlugin, npm_native::NpmPlugin, rpm_native::RpmPlugin, skeletons,
1276 };
1277
1278 // (format, znippy handler's own type_id) — the right-hand side is znippy's
1279 // source of truth, never a literal copied into holger.
1280 let pairs: &[(ArtifactFormat, i8)] = &[
1281 // Rust is now derived from cargo_native (in znippy-common) rather than
1282 // a hardcoded `1` — this asserts the derivation, not a copy.
1283 (ArtifactFormat::Rust, CargoPlugin::new().type_id()),
1284 (ArtifactFormat::Npm, NpmPlugin.type_id()),
1285 (ArtifactFormat::Gem, GemPlugin.type_id()),
1286 (ArtifactFormat::Conda, CondaPlugin.type_id()),
1287 (ArtifactFormat::Rpm, RpmPlugin.type_id()),
1288 (ArtifactFormat::Deb, DebPlugin.type_id()),
1289 (ArtifactFormat::Go, skeletons::GoPlugin.type_id()),
1290 (ArtifactFormat::Nuget, skeletons::NugetPlugin.type_id()),
1291 (ArtifactFormat::Docker, skeletons::DockerPlugin.type_id()),
1292 (ArtifactFormat::Helm, skeletons::HelmPlugin.type_id()),
1293 (
1294 ArtifactFormat::Composer,
1295 skeletons::ComposerPlugin.type_id(),
1296 ),
1297 ];
1298
1299 let mut all_ok = true;
1300 for (fmt, znippy_id) in pairs {
1301 let holger_id = fmt.znippy_type_id();
1302 if holger_id != *znippy_id {
1303 all_ok = false;
1304 }
1305 assert_eq!(
1306 holger_id, *znippy_id,
1307 "{fmt:?}: holger znippy_type_id()={holger_id} drifted from znippy handler type_id()={znippy_id}"
1308 );
1309 }
1310
1311 #[cfg(feature = "testmatrix")]
1312 fstatus(
1313 "traits",
1314 "znippy_type_ids_derive_from_handlers",
1315 all_ok,
1316 &format!(
1317 "{} formats derive their discriminant from znippy handlers",
1318 pairs.len()
1319 ),
1320 );
1321 let _ = all_ok;
1322 }
1323
1324 #[test]
1325 fn upstream_auth_defaults_to_none() {
1326 assert_eq!(UpstreamAuth::default(), UpstreamAuth::None);
1327 assert_ne!(
1328 UpstreamAuth::Bearer { token: "t".into() },
1329 UpstreamAuth::Basic {
1330 username: "u".into(),
1331 password: "p".into()
1332 }
1333 );
1334 }
1335
1336 /// **The naming-mismatch guard.** Every format must name a crate that really
1337 /// exists on disk, and every name it is known by must resolve back to it.
1338 ///
1339 /// RED when a crate is renamed/moved without updating [`ArtifactFormat::home`]
1340 /// — which is the exact moment the trap re-opens: the docs keep saying "PyPI",
1341 /// the map keeps saying `znippy-python`, and the directory has become something
1342 /// else. A stale signpost is worse than none, so this fails the build instead.
1343 #[test]
1344 fn every_format_names_a_crate_that_exists() {
1345 // `traits/` sits beside `server/`, so the repo root is one level up.
1346 let repo_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1347 .parent()
1348 .expect("traits/ has a parent")
1349 .to_path_buf();
1350
1351 for fmt in ALL_ARTIFACT_FORMATS {
1352 let home = fmt.home();
1353
1354 // 1. The canonical config key and EVERY alias must parse back to this
1355 // same format — so searching any spoken name lands on this map.
1356 for name in home.all_names() {
1357 assert_eq!(
1358 ArtifactFormat::from_format_str(name),
1359 Some(fmt.clone()),
1360 "{fmt:?}: the name {name:?} must resolve back to it"
1361 );
1362 }
1363
1364 // 2. The named crate directory must EXIST (and be a real crate).
1365 for (dir, package) in std::iter::once((home.crate_dir, home.package))
1366 .chain(home.also)
1367 .filter(|(d, _)| !d.is_empty())
1368 {
1369 let manifest = repo_root
1370 .join("server/repository")
1371 .join(dir)
1372 .join("Cargo.toml");
1373 assert!(
1374 manifest.is_file(),
1375 "{fmt:?}: home() points at server/repository/{dir}, which does not exist \
1376 (renamed? then update ArtifactFormat::home)"
1377 );
1378 let text = std::fs::read_to_string(&manifest).expect("read Cargo.toml");
1379 assert!(
1380 text.lines()
1381 .any(|l| l.trim() == format!("name = \"{package}\"")),
1382 "{fmt:?}: server/repository/{dir} is not package {package:?} \
1383 (renamed? then update ArtifactFormat::home)"
1384 );
1385 }
1386 }
1387 }
1388
1389 // ── The two fields that are allowed to say "I don't know" ────────────────
1390
1391 /// A digest is 64 hex characters or it is nothing. Everything else is
1392 /// DROPPED rather than carried, because a wrong digest is worse than no
1393 /// digest: it is compared against.
1394 #[test]
1395 fn a_digest_that_is_not_a_digest_becomes_unknown() {
1396 assert_eq!(normalize_sha256(&"a".repeat(64)), Some("a".repeat(64)));
1397 assert_eq!(
1398 normalize_sha256(&"A".repeat(64)),
1399 Some("a".repeat(64)),
1400 "hex is lowercased"
1401 );
1402 assert_eq!(
1403 normalize_sha256(&format!(" {} ", "a".repeat(64))),
1404 Some("a".repeat(64))
1405 );
1406 for bad in [
1407 "",
1408 "sha256:".to_string().as_str(),
1409 &format!("sha256:{}", "a".repeat(64)),
1410 &"a".repeat(63),
1411 &"a".repeat(65),
1412 &"z".repeat(64),
1413 ] {
1414 assert_eq!(
1415 normalize_sha256(bad),
1416 None,
1417 "{bad:?} must not be accepted as a digest"
1418 );
1419 }
1420 }
1421
1422 // ── The change token ─────────────────────────────────────────────────────
1423
1424 /// An empty token is not a token. The reason is the same one that drops a
1425 /// malformed digest, and it is sharper here: an empty token compares EQUAL
1426 /// to another empty token, so a listing that published one would tell a
1427 /// mirror that two different artifacts are the same artifact.
1428 #[test]
1429 fn an_empty_or_unusable_change_token_becomes_unknown() {
1430 assert_eq!(normalize_change_token(""), None);
1431 assert_eq!(normalize_change_token(" "), None);
1432 assert_eq!(
1433 normalize_change_token("a\u{0}b"),
1434 None,
1435 "control characters are refused"
1436 );
1437 assert_eq!(
1438 normalize_change_token(&"x".repeat(MAX_CHANGE_TOKEN_LEN + 1)),
1439 None
1440 );
1441 assert_eq!(
1442 normalize_change_token(" abc "),
1443 Some("abc".to_string()),
1444 "trimmed"
1445 );
1446 assert_eq!(
1447 ArtifactEntry::unknown_provenance(
1448 ArtifactId {
1449 namespace: None,
1450 name: "a".into(),
1451 version: "1".into()
1452 },
1453 1,
1454 "t",
1455 )
1456 .with_change_token(Some(""))
1457 .change_token,
1458 None,
1459 "and the builder drops it rather than carrying it"
1460 );
1461 }
1462
1463 /// **The proto3 zero values cannot become answers.**
1464 ///
1465 /// The fields are `optional` on the wire, so absence is a state — but a
1466 /// peer that is not this codebase can still put `0` and `""` on the wire,
1467 /// and neither is allowed past this line. A zero timestamp would sort as
1468 /// the oldest thing in the repository; an empty digest would compare equal
1469 /// to another empty digest and turn `unproven` into a false `unchanged`.
1470 #[test]
1471 fn the_proto3_zero_values_are_not_answers() {
1472 assert_eq!(
1473 normalize_published_unix_ms(Some(0)),
1474 None,
1475 "0 is what nobody-set looks like"
1476 );
1477 assert_eq!(normalize_published_unix_ms(Some(-1)), None);
1478 assert_eq!(normalize_published_unix_ms(None), None);
1479 assert_eq!(normalize_published_unix_ms(Some(1)), Some(1));
1480 assert_eq!(
1481 normalize_sha256(""),
1482 None,
1483 "the empty string is not a digest"
1484 );
1485 }
1486
1487 /// `unknown_provenance` says it in its name, and the builders refuse to
1488 /// turn a bad value into a good-looking one.
1489 #[test]
1490 fn an_entry_that_knows_nothing_says_so_and_cannot_be_talked_into_a_value() {
1491 let id = ArtifactId {
1492 namespace: None,
1493 name: "a".into(),
1494 version: "1".into(),
1495 };
1496 let e = ArtifactEntry::unknown_provenance(id.clone(), 7, "application/octet-stream");
1497 assert_eq!(e.published_unix_ms, None);
1498 assert_eq!(e.sha256, None);
1499 assert_eq!(e.size_bytes, 7);
1500
1501 let e = e.with_published_unix_ms(Some(0)).with_sha256(Some(""));
1502 assert_eq!(e.published_unix_ms, None, "a zero must not become a time");
1503 assert_eq!(e.sha256, None, "an empty string must not become a digest");
1504
1505 let e = e
1506 .with_published_unix_ms(Some(1_726_000_000_000))
1507 .with_sha256(Some("B".repeat(64)));
1508 assert_eq!(e.published_unix_ms, Some(1_726_000_000_000));
1509 assert_eq!(e.sha256, Some("b".repeat(64)));
1510
1511 // The record-update tail is the same "I don't know", for a literal.
1512 let lit = ArtifactEntry {
1513 id,
1514 size_bytes: 7,
1515 content_type: "application/octet-stream".into(),
1516 ..ArtifactEntry::UNKNOWN_PROVENANCE
1517 };
1518 assert_eq!(lit.published_unix_ms, None);
1519 assert_eq!(lit.sha256, None);
1520 }
1521
1522 /// A clock at or before the epoch is a backend that does not know, not a
1523 /// backend that knows 1970.
1524 #[test]
1525 fn a_system_time_at_the_epoch_is_unknown_rather_than_zero() {
1526 assert_eq!(system_time_to_unix_ms(std::time::UNIX_EPOCH), None);
1527 assert_eq!(
1528 system_time_to_unix_ms(std::time::UNIX_EPOCH - std::time::Duration::from_secs(1)),
1529 None
1530 );
1531 let ms = system_time_to_unix_ms(std::time::SystemTime::now()).expect("now is after 1970");
1532 assert!(ms > 1_700_000_000_000, "milliseconds, not seconds: {ms}");
1533 }
1534
1535 /// A znippy listing says unknown for every row. This is the helper thirteen
1536 /// backends share, so it is the one place the rule has to hold.
1537 #[test]
1538 fn the_shared_znippy_listing_answers_unknown_for_every_row() {
1539 // No archive needed: the entry shape is what is asserted, and the
1540 // helper's contract is that it never sets either field.
1541 let e = ArtifactEntry::unknown_provenance(
1542 ArtifactId {
1543 namespace: None,
1544 name: "x".into(),
1545 version: "1".into(),
1546 },
1547 1,
1548 "application/octet-stream",
1549 );
1550 assert_eq!((e.published_unix_ms, e.sha256), (None, None));
1551 }
1552
1553 /// The specific case that cost real time: PyPI is spelled four ways, and the
1554 /// implementation directory matches NONE of the two an operator or a reader
1555 /// would try first. Pin it by name so the map is not silently "simplified".
1556 #[test]
1557 fn the_pypi_four_name_split_is_pinned() {
1558 let home = ArtifactFormat::Pip.home();
1559 assert_eq!(
1560 home.config_key, "pip",
1561 "operators write ron_repo_type: \"pip\""
1562 );
1563 assert!(
1564 home.aliases.contains(&"pypi"),
1565 "the docs/UI name must be findable"
1566 );
1567 assert!(
1568 home.aliases.contains(&"python"),
1569 "the crate's own name must be findable"
1570 );
1571 assert_eq!(
1572 home.crate_dir, "znippy-python",
1573 "the implementation lives under a THIRD name — that is the whole point"
1574 );
1575 // The trap, stated as an assertion: neither name the reader reaches for
1576 // first is the directory name.
1577 assert_ne!(home.crate_dir, home.config_key);
1578 assert_ne!(home.crate_dir, "pypi");
1579 }
1580
1581 #[test]
1582 fn format_str_roundtrips_aliases() {
1583 assert_eq!(
1584 ArtifactFormat::from_format_str("cargo"),
1585 Some(ArtifactFormat::Rust)
1586 );
1587 assert_eq!(
1588 ArtifactFormat::from_format_str("golang"),
1589 Some(ArtifactFormat::Go)
1590 );
1591 assert_eq!(
1592 ArtifactFormat::from_format_str("dotnet"),
1593 Some(ArtifactFormat::Nuget)
1594 );
1595 assert_eq!(
1596 ArtifactFormat::from_format_str("oci"),
1597 Some(ArtifactFormat::Docker)
1598 );
1599 assert_eq!(ArtifactFormat::from_format_str("nope"), None);
1600
1601 #[cfg(feature = "testmatrix")]
1602 {
1603 let ok = ArtifactFormat::from_format_str("cargo") == Some(ArtifactFormat::Rust)
1604 && ArtifactFormat::from_format_str("oci") == Some(ArtifactFormat::Docker)
1605 && ArtifactFormat::from_format_str("nope").is_none();
1606 fstatus(
1607 "traits",
1608 "format_str_aliases_roundtrip",
1609 ok,
1610 "cargo->Rust golang->Go dotnet->Nuget oci->Docker nope->None",
1611 );
1612 }
1613 }
1614}