Skip to main content

znippy_common/
views.rs

1//! Typed specialized package views — the READ side of the plugin contract.
2//!
3//! A znippy plugin writes per-ecosystem metadata into Arrow columns at compress
4//! time (maven: `group_id`/`artifact_id`/`version`; python: `name`/`version`;
5//! rust: `crate_name`/`version`), discriminated by `pkg_type`. This module is the
6//! symmetric READ side: it turns those columns back into a typed, coord-addressed
7//! view so consumers never re-derive coordinates by parsing file paths.
8//!
9//! ## Performance contract (HARD)
10//!
11//! 1. **The coord index is built ONCE**, at view construction, via
12//!    [`read_znippy_index_filtered`](crate::read_znippy_index_filtered) with an
13//!    [`IndexFilter`](crate::IndexFilter) pinned to the plugin's `pkg_type` — so
14//!    only that one sub-index stream is read and parsed. The result is a
15//!    `HashMap<Key, FileLoc>` interned into the view; the holder ([`ZnippyArchive`])
16//!    caches it (one slot per format), so repeated `as_maven()` is free.
17//! 2. **`get(coords)` is an O(1) map lookup** returning a lightweight handle
18//!    ([`Package`]): coords + a cloned `FileLoc` + the shared fd. No scan, no
19//!    Arrow re-parse, no decompression, no bytes copied.
20//! 3. **Bytes are LAZY** — [`Package::bytes`] is the only thing that preads the
21//!    blob(s) and decompresses (the same loop as [`crate::ZnippyArchive::extract_file`]),
22//!    and only when called. A `fetch` that only needs existence/size never decompresses.
23
24use std::collections::{HashMap, HashSet};
25use std::fs::File;
26use std::hash::Hash;
27use std::os::unix::fs::FileExt;
28use std::path::Path;
29use std::sync::Arc;
30
31use anyhow::{anyhow, Result};
32use arrow::array::{Array, StringArray};
33use arrow::record_batch::RecordBatch;
34
35use crate::codec;
36use crate::index::{read_znippy_index_filtered, IndexFilter};
37use crate::plugin::file_name;
38
39// ─── pkg_type discriminants (single source of truth: each plugin's `type_id()`) ──
40//
41// These mirror the discriminant each plugin returns from `ArchiveTypePlugin::type_id()`:
42//   CargoPlugin::type_id()        == 1   (znippy-common/src/plugins/native/cargo_native.rs)
43//   NativePythonPlugin::type_id() == 2   (znippy-plugin-python)
44//   NativeMavenPlugin::type_id()  == 3   (znippy-plugin-maven)
45// They live here because `ZnippyArchive` (in this crate) builds the filtered index
46// keyed on them, and the maven/python plugin crates depend on this crate (not the
47// other way round), so the constant cannot live in those crates without a cycle.
48
49/// `pkg_type` discriminant written by the rust/cargo plugin.
50pub const RUST_PKG_TYPE: i8 = 1;
51/// `pkg_type` discriminant written by the python plugin.
52pub const PYTHON_PKG_TYPE: i8 = 2;
53/// `pkg_type` discriminant written by the maven plugin.
54pub const MAVEN_PKG_TYPE: i8 = 3;
55/// `pkg_type` discriminant written by the npm plugin (`plugins::npm_native`).
56pub const NPM_PKG_TYPE: i8 = 6;
57/// `pkg_type` discriminant written by the gem plugin (`plugins::gem_native`).
58pub const GEM_PKG_TYPE: i8 = 11;
59/// `pkg_type` discriminant written by the rpm plugin (`plugins::rpm_native`).
60pub const RPM_PKG_TYPE: i8 = 8;
61/// `pkg_type` discriminant written by the deb plugin (`plugins::deb_native`).
62pub const DEB_PKG_TYPE: i8 = 9;
63/// `pkg_type` discriminant written by the conda plugin (`plugins::conda_native`).
64pub const CONDA_PKG_TYPE: i8 = 14;
65
66/// One file's chunk locations within the archive blob region — everything needed
67/// to pread + decompress its bytes, with **no** path involved. Built from the base
68/// index columns on the same rows that carried the coord match.
69#[derive(Debug, Clone)]
70#[non_exhaustive]
71pub struct FileLoc {
72    /// The row key this file was read under: its `relative_path` column.
73    ///
74    /// The typed views index BY COORDINATE (name+version, group+artifact+version,
75    /// …), which is what a client asks with — and they threw the path away while
76    /// building that index, so a caller holding a `RustPackage` had no key to ask
77    /// the lookup sub-index with. It was never absent, only discarded:
78    /// `group_rows_by_file` keys its map by exactly this string.
79    ///
80    /// It is what a CHANGE TOKEN needs: `znippy_sign::file_digest_from_parts` binds the
81    /// relative path, so without it the six backends that list through the typed
82    /// views (maven, npm, gem, conda, python, build-thing) have no key to fold a
83    /// token from.
84    pub relative_path: String,
85    /// The file's chunks, ordered by `fdata_offset` (concatenation order).
86    pub chunks: Vec<ChunkRef>,
87    /// Total uncompressed size across all chunks.
88    pub uncompressed_size: u64,
89}
90
91/// One chunk's blob location.
92#[derive(Debug, Clone, Copy)]
93#[non_exhaustive]
94pub struct ChunkRef {
95    pub blob_offset: u64,
96    pub blob_size: u64,
97    pub fdata_offset: u64,
98    pub compressed: bool,
99}
100
101impl FileLoc {
102    /// Read + decompress this file's bytes — the lone I/O of the read API.
103    /// Reuses the exact pread/decompress loop of [`ZnippyArchive::extract_file`].
104    fn read_bytes(&self, archive: &File) -> Result<Vec<u8>> {
105        let mut result = Vec::with_capacity(self.uncompressed_size as usize);
106        let mut blob = Vec::new();
107        let mut decomp = Vec::new();
108        for chunk in &self.chunks {
109            blob.resize(chunk.blob_size as usize, 0);
110            archive.read_exact_at(&mut blob, chunk.blob_offset)?;
111            if chunk.compressed {
112                codec::decompress_into(&blob, &mut decomp)?;
113                result.extend_from_slice(&decomp);
114            } else {
115                result.extend_from_slice(&blob);
116            }
117        }
118        Ok(result)
119    }
120}
121
122/// Project the base location columns of a row into a [`ChunkRef`], appending to a
123/// per-file [`FileLoc`] keyed by `relative_path` (so chunked files group correctly).
124fn group_rows_by_file(batch: &RecordBatch) -> Result<HashMap<String, FileLoc>> {
125    use arrow::array::{BooleanArray, UInt64Array};
126
127    let col = |n: &str| {
128        batch
129            .column_by_name(n)
130            .ok_or_else(|| anyhow!("index missing column {n}"))
131    };
132    let paths = col("relative_path")?
133        .as_any()
134        .downcast_ref::<StringArray>()
135        .ok_or_else(|| anyhow!("relative_path not StringArray"))?;
136    let compressed = col("compressed")?
137        .as_any()
138        .downcast_ref::<BooleanArray>()
139        .ok_or_else(|| anyhow!("compressed not BooleanArray"))?;
140    let sizes = col("uncompressed_size")?
141        .as_any()
142        .downcast_ref::<UInt64Array>()
143        .ok_or_else(|| anyhow!("uncompressed_size not UInt64Array"))?;
144    let blob_offset = col("blob_offset")?
145        .as_any()
146        .downcast_ref::<UInt64Array>()
147        .ok_or_else(|| anyhow!("blob_offset not UInt64Array"))?;
148    let blob_size = col("blob_size")?
149        .as_any()
150        .downcast_ref::<UInt64Array>()
151        .ok_or_else(|| anyhow!("blob_size not UInt64Array"))?;
152    let fdata = col("fdata_offset")?
153        .as_any()
154        .downcast_ref::<UInt64Array>()
155        .ok_or_else(|| anyhow!("fdata_offset not UInt64Array"))?;
156
157    let mut by_path: HashMap<String, FileLoc> = HashMap::new();
158    for i in 0..batch.num_rows() {
159        let path = paths.value(i);
160        let entry = by_path.entry(path.to_string()).or_insert_with(|| FileLoc {
161            relative_path: path.to_string(),
162            chunks: Vec::new(),
163            uncompressed_size: 0,
164        });
165        entry.uncompressed_size += sizes.value(i);
166        entry.chunks.push(ChunkRef {
167            blob_offset: blob_offset.value(i),
168            blob_size: blob_size.value(i),
169            fdata_offset: fdata.value(i),
170            compressed: compressed.value(i),
171        });
172    }
173    for f in by_path.values_mut() {
174        f.chunks.sort_by_key(|c| c.fdata_offset);
175    }
176    Ok(by_path)
177}
178
179
180
181// ════════════════════════════════════════════════════════════════════════════
182// The generic coord view
183// ════════════════════════════════════════════════════════════════════════════
184
185mod sealed {
186    pub trait Sealed {}
187}
188
189/// How one format's sub-index maps to coords: which `pkg_type` it reads, which
190/// columns, and how a row becomes a `(Key, Extra)`. One small impl per format;
191/// everything else (filtered read, grouping by path, the O(1) map, the lazy
192/// bytes) is [`CoordView`]'s and written once.
193pub trait CoordSpec: sealed::Sealed + Send + Sync + 'static {
194    /// The `pkg_type` sub-index this view reads.
195    const PKG_TYPE: i8;
196    /// This format's slot in the archive's view cache.
197    const SLOT: usize;
198    /// The columns a row is read from. The first [`Self::REQUIRED`] must exist
199    /// in the batch (else the batch is skipped) and be non-null (else the row is).
200    const COLS: &'static [&'static str];
201    const REQUIRED: usize;
202    /// The lookup key (the coords).
203    type Key: Eq + Hash + Clone + Send + Sync;
204    /// Per-file metadata riding beside the location.
205    type Extra: Clone + Send + Sync;
206    /// One row → its key and extra; `path` is the row's `relative_path`.
207    fn row(c: &Cells<'_>, path: &str) -> (Self::Key, Self::Extra);
208    /// Whether a later row replaces an earlier one with the same key (default: yes).
209    fn replaces(_new: &Self::Extra) -> bool {
210        true
211    }
212}
213
214/// One row's cells, in [`CoordSpec::COLS`] order.
215pub struct Cells<'a> {
216    cols: &'a [Option<&'a StringArray>],
217    i: usize,
218}
219
220impl Cells<'_> {
221    /// Column `j`'s value, `None` when the column is absent or the cell null.
222    pub fn opt(&self, j: usize) -> Option<String> {
223        self.cols[j].filter(|a| !a.is_null(self.i)).map(|a| a.value(self.i).to_string())
224    }
225    /// Column `j`'s value, `""` when absent/null.
226    pub fn get(&self, j: usize) -> String {
227        self.opt(j).unwrap_or_default()
228    }
229    /// Column `j`'s value when present and non-empty.
230    pub fn non_empty(&self, j: usize) -> Option<String> {
231        self.opt(j).filter(|s| !s.is_empty())
232    }
233}
234
235/// A typed, coord-addressed view over one format's sub-index. Built once;
236/// lookups are O(1).
237pub struct CoordView<S: CoordSpec> {
238    archive: Arc<File>,
239    coords: HashMap<S::Key, (FileLoc, S::Extra)>,
240}
241
242/// A handle to one file in a [`CoordView`]: authoritative coords (read from the
243/// columns) + its location. Bytes are lazy — [`Package::bytes`].
244pub struct Package<S: CoordSpec> {
245    archive: Arc<File>,
246    loc: FileLoc,
247    key: S::Key,
248    extra: S::Extra,
249}
250
251impl<S: CoordSpec> CoordView<S> {
252    pub(crate) fn build(path: &Path, archive: Arc<File>) -> Result<Self> {
253        let (_schema, batches) =
254            read_znippy_index_filtered(path, &IndexFilter { pkg_type: Some(S::PKG_TYPE), repo: None })?;
255        let mut coords: HashMap<S::Key, (FileLoc, S::Extra)> = HashMap::new();
256        for batch in &batches {
257            let cols: Vec<Option<&StringArray>> = S::COLS
258                .iter()
259                .map(|n| batch.column_by_name(n).and_then(|c| c.as_any().downcast_ref::<StringArray>()))
260                .collect();
261            if cols[..S::REQUIRED].iter().any(Option::is_none) {
262                continue;
263            }
264            let paths = batch
265                .column_by_name("relative_path")
266                .and_then(|c| c.as_any().downcast_ref::<StringArray>())
267                .ok_or_else(|| anyhow!("missing relative_path"))?;
268            let locs = group_rows_by_file(batch)?;
269            let mut seen = HashSet::new();
270            for i in 0..batch.num_rows() {
271                let p = paths.value(i);
272                // The first row of a path carries its coords; later rows are chunks.
273                if !seen.insert(p) || cols[..S::REQUIRED].iter().any(|c| c.is_some_and(|a| a.is_null(i))) {
274                    continue;
275                }
276                let Some(loc) = locs.get(p) else { continue };
277                let (key, extra) = S::row(&Cells { cols: &cols, i }, p);
278                if S::replaces(&extra) || !coords.contains_key(&key) {
279                    coords.insert(key, (loc.clone(), extra));
280                }
281            }
282        }
283        Ok(Self { archive, coords })
284    }
285
286    fn package(&self, key: &S::Key) -> Option<Package<S>> {
287        let (loc, extra) = self.coords.get(key)?;
288        Some(Package { archive: Arc::clone(&self.archive), loc: loc.clone(), key: key.clone(), extra: extra.clone() })
289    }
290
291    /// Every entry's key and extra (unordered).
292    fn entries(&self) -> impl Iterator<Item = (&S::Key, &S::Extra)> {
293        self.coords.iter().map(|(k, (_, e))| (k, e))
294    }
295
296    /// Number of files indexed.
297    pub fn len(&self) -> usize {
298        self.coords.len()
299    }
300    pub fn is_empty(&self) -> bool {
301        self.coords.is_empty()
302    }
303}
304
305impl<S: CoordSpec> Package<S> {
306    /// This package's row key in the archive — its `relative_path` column. What
307    /// lets a caller holding a handle ask the lookup sub-index, or fold a
308    /// path-bound per-file digest, without listing the whole archive.
309    pub fn relative_path(&self) -> &str {
310        &self.loc.relative_path
311    }
312    /// Uncompressed size in bytes (no decompression).
313    pub fn size(&self) -> u64 {
314        self.loc.uncompressed_size
315    }
316    /// LAZY: pread + decompress the file's bytes. The only I/O of the read API.
317    pub fn bytes(&self) -> Result<Vec<u8>> {
318        self.loc.read_bytes(&self.archive)
319    }
320    pub fn into_bytes(self) -> Result<Vec<u8>> {
321        self.loc.read_bytes(&self.archive)
322    }
323}
324
325/// Declare a spec type: `spec!(RustSpec)`.
326macro_rules! spec {
327    ($t:ident) => {
328        #[doc = concat!("The coord spec behind [`", stringify!($t), "`]'s view.")]
329        pub struct $t;
330        impl sealed::Sealed for $t {}
331    };
332}
333
334fn s2(k: &(String, String)) -> (String, String) {
335    k.clone()
336}
337
338// ─── RUST: (crate_name, version) ────────────────────────────────────────────
339
340spec!(RustSpec);
341impl CoordSpec for RustSpec {
342    const PKG_TYPE: i8 = RUST_PKG_TYPE;
343    const SLOT: usize = 0;
344    const COLS: &'static [&'static str] = &["crate_name", "version"];
345    const REQUIRED: usize = 2;
346    type Key = (String, String);
347    type Extra = ();
348    fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
349        ((c.get(0), c.get(1)), ())
350    }
351}
352/// Typed view over the rust (cargo) sub-index.
353pub type RustView = CoordView<RustSpec>;
354/// A handle to one crate.
355pub type RustPackage = Package<RustSpec>;
356
357impl RustView {
358    /// O(1) lookup → handle. `None` if the crate is not in the archive.
359    pub fn get(&self, name: &str, version: &str) -> Option<RustPackage> {
360        self.package(&(name.to_string(), version.to_string()))
361    }
362    /// Authoritative `(name, version)` coords of every crate in the view.
363    pub fn list(&self) -> Vec<(String, String)> {
364        self.entries().map(|(k, _)| s2(k)).collect()
365    }
366}
367impl RustPackage {
368    /// Authoritative crate name (from the `crate_name` column, not a path parse).
369    pub fn name(&self) -> &str {
370        &self.key.0
371    }
372    pub fn version(&self) -> &str {
373        &self.key.1
374    }
375}
376
377// ─── MAVEN: (group, artifact, version, classifier?) ─────────────────────────
378
379spec!(MavenSpec);
380impl CoordSpec for MavenSpec {
381    const PKG_TYPE: i8 = MAVEN_PKG_TYPE;
382    const SLOT: usize = 1;
383    const COLS: &'static [&'static str] = &["group_id", "artifact_id", "version", "classifier"];
384    const REQUIRED: usize = 3;
385    /// The classifier is part of the key so `-sources`/`-javadoc` resolve distinctly.
386    type Key = (String, String, String, Option<String>);
387    type Extra = ();
388    fn row(c: &Cells<'_>, path: &str) -> (Self::Key, ()) {
389        let (g, a, v) = (c.get(0), c.get(1), c.get(2));
390        // Prefer the column; derive from the filename when absent/null (older archives).
391        let classifier = c.non_empty(3).or_else(|| derive_classifier(file_name(path), &a, &v));
392        ((g, a, v, classifier), ())
393    }
394}
395/// Typed view over the maven sub-index.
396pub type MavenView = CoordView<MavenSpec>;
397/// A handle to one maven artifact.
398pub type MavenPackage = Package<MavenSpec>;
399
400impl MavenView {
401    /// O(1) lookup of the primary artifact (no classifier) for a GAV.
402    pub fn get(&self, group: &str, artifact: &str, version: &str) -> Option<MavenPackage> {
403        self.get_classified(group, artifact, version, None)
404    }
405    /// O(1) lookup of a specific classifier (`Some("sources")`) or the primary (`None`).
406    pub fn get_classified(
407        &self,
408        group: &str,
409        artifact: &str,
410        version: &str,
411        classifier: Option<&str>,
412    ) -> Option<MavenPackage> {
413        self.package(&(group.into(), artifact.into(), version.into(), classifier.map(str::to_string)))
414    }
415    /// Authoritative coords of every artifact: `(group, artifact, version, classifier?)`.
416    pub fn list(&self) -> Vec<(String, String, String, Option<String>)> {
417        self.entries().map(|(k, _)| k.clone()).collect()
418    }
419}
420
421/// Best-effort classifier recovery from a filename when the column is absent.
422/// Maven filename: `{artifact}-{version}[-{classifier}].{ext}`.
423fn derive_classifier(filename: &str, artifact: &str, version: &str) -> Option<String> {
424    let stem = filename.rsplit_once('.').map(|(s, _)| s).unwrap_or(filename);
425    let rest = stem.strip_prefix(&format!("{artifact}-{version}"))?.strip_prefix('-')?;
426    (!rest.is_empty()).then(|| rest.to_string())
427}
428
429impl MavenPackage {
430    pub fn group(&self) -> &str {
431        &self.key.0
432    }
433    pub fn artifact(&self) -> &str {
434        &self.key.1
435    }
436    pub fn version(&self) -> &str {
437        &self.key.2
438    }
439    /// The classifier (`sources`, `javadoc`, …) or `None` for the primary artifact.
440    pub fn classifier(&self) -> Option<&str> {
441        self.key.3.as_deref()
442    }
443    /// `(group, artifact, version, classifier?)` — authoritative coords.
444    pub fn coords(&self) -> (&str, &str, &str, Option<&str>) {
445        (&self.key.0, &self.key.1, &self.key.2, self.key.3.as_deref())
446    }
447}
448
449// ─── PYTHON: (name, version), wheel preferred over sdist ────────────────────
450
451/// Wheel vs sdist discriminant.
452#[derive(Debug, Clone, Copy, PartialEq, Eq)]
453pub enum PythonKind {
454    Wheel,
455    Sdist,
456}
457
458spec!(PythonSpec);
459impl CoordSpec for PythonSpec {
460    const PKG_TYPE: i8 = PYTHON_PKG_TYPE;
461    const SLOT: usize = 2;
462    const COLS: &'static [&'static str] = &["name", "version"];
463    const REQUIRED: usize = 2;
464    type Key = (String, String);
465    type Extra = PythonKind;
466    fn row(c: &Cells<'_>, path: &str) -> (Self::Key, PythonKind) {
467        let kind = if file_name(path).ends_with(".whl") { PythonKind::Wheel } else { PythonKind::Sdist };
468        ((c.get(0), c.get(1)), kind)
469    }
470    /// Prefer a wheel over an sdist when both share a `(name, version)`.
471    fn replaces(new: &PythonKind) -> bool {
472        *new == PythonKind::Wheel
473    }
474}
475/// Typed view over the python sub-index.
476pub type PythonView = CoordView<PythonSpec>;
477/// A handle to one python distribution.
478pub type PythonPackage = Package<PythonSpec>;
479
480impl PythonView {
481    /// O(1) lookup → handle. `None` if the distribution is not in the archive.
482    pub fn get(&self, name: &str, version: &str) -> Option<PythonPackage> {
483        self.package(&(name.to_string(), version.to_string()))
484    }
485    /// Authoritative `(name, version)` coords of every distribution.
486    pub fn list(&self) -> Vec<(String, String)> {
487        self.entries().map(|(k, _)| s2(k)).collect()
488    }
489}
490impl PythonPackage {
491    pub fn name(&self) -> &str {
492        &self.key.0
493    }
494    pub fn version(&self) -> &str {
495        &self.key.1
496    }
497    /// Wheel or sdist (derived from the matched row's filename).
498    pub fn kind(&self) -> PythonKind {
499        self.extra
500    }
501}
502
503// ─── NPM: (name incl. @scope, version) ──────────────────────────────────────
504
505spec!(NpmSpec);
506impl CoordSpec for NpmSpec {
507    const PKG_TYPE: i8 = NPM_PKG_TYPE;
508    const SLOT: usize = 3;
509    const COLS: &'static [&'static str] = &["name", "version"];
510    const REQUIRED: usize = 2;
511    /// `name` is the authoritative `package.json` name, including the `@scope/`
512    /// prefix the tarball filename drops.
513    type Key = (String, String);
514    type Extra = ();
515    fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
516        ((c.get(0), c.get(1)), ())
517    }
518}
519/// Typed view over the npm sub-index.
520pub type NpmView = CoordView<NpmSpec>;
521/// A handle to one npm package tarball.
522pub type NpmPackage = Package<NpmSpec>;
523
524impl NpmView {
525    /// O(1) lookup → handle (pass `@scope/pkg` for scoped packages).
526    pub fn get(&self, name: &str, version: &str) -> Option<NpmPackage> {
527        self.package(&(name.to_string(), version.to_string()))
528    }
529    /// Authoritative `(name, version)` coords of every package in the view.
530    pub fn list(&self) -> Vec<(String, String)> {
531        self.entries().map(|(k, _)| s2(k)).collect()
532    }
533}
534impl NpmPackage {
535    /// Authoritative package name (from the `name` column — includes `@scope/`).
536    pub fn name(&self) -> &str {
537        &self.key.0
538    }
539    pub fn version(&self) -> &str {
540        &self.key.1
541    }
542}
543
544// ─── GEM: (name, version, platform) ─────────────────────────────────────────
545
546spec!(GemSpec);
547impl CoordSpec for GemSpec {
548    const PKG_TYPE: i8 = GEM_PKG_TYPE;
549    const SLOT: usize = 4;
550    const COLS: &'static [&'static str] = &["name", "version", "platform"];
551    const REQUIRED: usize = 2;
552    /// `platform` is part of the key so `foo-1.2.3-java.gem` resolves apart from
553    /// the pure-ruby gem of the same version. All three come from `metadata.gz`.
554    type Key = (String, String, String);
555    type Extra = ();
556    fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
557        ((c.get(0), c.get(1), c.non_empty(2).unwrap_or_else(|| "ruby".into())), ())
558    }
559}
560/// Typed view over the gem sub-index.
561pub type GemView = CoordView<GemSpec>;
562/// A handle to one gem.
563pub type GemPackage = Package<GemSpec>;
564
565impl GemView {
566    /// O(1) lookup of the `ruby`-platform gem for a `(name, version)`.
567    pub fn get(&self, name: &str, version: &str) -> Option<GemPackage> {
568        self.get_platform(name, version, "ruby")
569    }
570    /// O(1) lookup of a specific platform (`java`, `x86_64-linux`, …).
571    pub fn get_platform(&self, name: &str, version: &str, platform: &str) -> Option<GemPackage> {
572        self.package(&(name.into(), version.into(), platform.into()))
573    }
574    /// Authoritative `(name, version, platform)` coords of every gem in the view.
575    pub fn list(&self) -> Vec<(String, String, String)> {
576        self.entries().map(|(k, _)| k.clone()).collect()
577    }
578}
579impl GemPackage {
580    pub fn name(&self) -> &str {
581        &self.key.0
582    }
583    pub fn version(&self) -> &str {
584        &self.key.1
585    }
586    /// The gem platform (`ruby` default, e.g. `java` for a native gem).
587    pub fn platform(&self) -> &str {
588        &self.key.2
589    }
590}
591
592// ─── CONDA: (name, version, build, subdir) ──────────────────────────────────
593
594spec!(CondaSpec);
595impl CoordSpec for CondaSpec {
596    const PKG_TYPE: i8 = CONDA_PKG_TYPE;
597    const SLOT: usize = 5;
598    const COLS: &'static [&'static str] = &["name", "version", "build", "subdir"];
599    const REQUIRED: usize = 2;
600    /// `build` + `subdir` are part of the key so one `(name, version)` resolves
601    /// distinctly across builds and platforms (all from `info/index.json`).
602    type Key = (String, String, String, String);
603    type Extra = ();
604    fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
605        ((c.get(0), c.get(1), c.get(2), c.get(3)), ())
606    }
607}
608/// Typed view over the conda sub-index.
609pub type CondaView = CoordView<CondaSpec>;
610/// A handle to one conda package.
611pub type CondaPackage = Package<CondaSpec>;
612
613impl CondaView {
614    /// The first `(name, version)` match across any build/subdir (a scan).
615    /// Use [`get_exact`](CondaView::get_exact) to pin the build + subdir.
616    pub fn get(&self, name: &str, version: &str) -> Option<CondaPackage> {
617        let key = self.coords.keys().find(|k| k.0 == name && k.1 == version)?.clone();
618        self.package(&key)
619    }
620    /// O(1) lookup of an exact `(name, version, build, subdir)` coord.
621    pub fn get_exact(&self, name: &str, version: &str, build: &str, subdir: &str) -> Option<CondaPackage> {
622        self.package(&(name.into(), version.into(), build.into(), subdir.into()))
623    }
624    /// Authoritative `(name, version, build, subdir)` coords of every package.
625    pub fn list(&self) -> Vec<(String, String, String, String)> {
626        self.entries().map(|(k, _)| k.clone()).collect()
627    }
628}
629impl CondaPackage {
630    pub fn name(&self) -> &str {
631        &self.key.0
632    }
633    pub fn version(&self) -> &str {
634        &self.key.1
635    }
636    /// The build string (e.g. `py311h1234567_0`), from `info/index.json`.
637    pub fn build(&self) -> &str {
638        &self.key.2
639    }
640    /// The subdir/platform (e.g. `linux-64`), from `info/index.json`.
641    pub fn subdir(&self) -> &str {
642        &self.key.3
643    }
644}
645
646// ─── RPM: (name, version, release, arch) + header metadata ──────────────────
647
648/// One rpm's authoritative header metadata — NEVRA plus the rpm-md `primary.xml`
649/// fields — the shape holger's `primary.xml` synthesis feeds off.
650#[derive(Debug, Clone, PartialEq, Eq)]
651pub struct RpmMetaRow {
652    pub name: String,
653    pub version: String,
654    pub release: String,
655    pub arch: String,
656    pub epoch: Option<String>,
657    pub summary: Option<String>,
658    pub license: Option<String>,
659    pub url: Option<String>,
660    pub vendor: Option<String>,
661    pub sourcerpm: Option<String>,
662    pub provides: Vec<String>,
663    pub requires: Vec<String>,
664}
665
666spec!(RpmSpec);
667impl CoordSpec for RpmSpec {
668    const PKG_TYPE: i8 = RPM_PKG_TYPE;
669    const SLOT: usize = 6;
670    const COLS: &'static [&'static str] = &[
671        "name", "version", "release", "arch", "epoch", "summary", "license", "url", "vendor",
672        "sourcerpm", "provides", "requires",
673    ];
674    const REQUIRED: usize = 2;
675    /// Epoch is NOT a lookup key (an rpm filename / dnf request carries none); it
676    /// rides in the extra so the read side can surface it.
677    type Key = (String, String, String, String);
678    /// The full row; its NEVRA duplicates the key.
679    type Extra = RpmMetaRow;
680    fn row(c: &Cells<'_>, _: &str) -> (Self::Key, RpmMetaRow) {
681        let lines = |j| split_lines(c.opt(j));
682        let m = RpmMetaRow {
683            name: c.get(0),
684            version: c.get(1),
685            release: c.get(2),
686            arch: c.get(3),
687            epoch: c.opt(4),
688            summary: c.opt(5),
689            license: c.opt(6),
690            url: c.opt(7),
691            vendor: c.opt(8),
692            sourcerpm: c.opt(9),
693            provides: lines(10),
694            requires: lines(11),
695        };
696        ((m.name.clone(), m.version.clone(), m.release.clone(), m.arch.clone()), m)
697    }
698}
699/// Typed view over the rpm sub-index (coords incl. `epoch` from the RPM header).
700pub type RpmView = CoordView<RpmSpec>;
701/// A handle to one rpm.
702pub type RpmPackage = Package<RpmSpec>;
703
704impl RpmView {
705    /// O(1) lookup of the rpm for `(name, version, release, arch)`.
706    pub fn get(&self, name: &str, version: &str, release: &str, arch: &str) -> Option<RpmPackage> {
707        self.package(&(name.into(), version.into(), release.into(), arch.into()))
708    }
709    /// `(name, version, release, arch, epoch)` of every rpm — the NEVRA projection.
710    pub fn list(&self) -> Vec<(String, String, String, String, Option<String>)> {
711        self.entries().map(|(k, e)| (k.0.clone(), k.1.clone(), k.2.clone(), k.3.clone(), e.epoch.clone())).collect()
712    }
713    /// Every rpm's full header metadata — what holger's `primary.xml` synthesis emits.
714    pub fn list_meta(&self) -> Vec<RpmMetaRow> {
715        self.entries().map(|(_, e)| e.clone()).collect()
716    }
717}
718impl RpmPackage {
719    pub fn name(&self) -> &str {
720        &self.key.0
721    }
722    pub fn version(&self) -> &str {
723        &self.key.1
724    }
725    pub fn release(&self) -> &str {
726        &self.key.2
727    }
728    pub fn arch(&self) -> &str {
729        &self.key.3
730    }
731    /// The authoritative `Epoch` (from the header), or `None` when unset.
732    pub fn epoch(&self) -> Option<&str> {
733        self.extra.epoch.as_deref()
734    }
735}
736
737/// Split a newline-joined column value (how the rpm plugin stores dependency
738/// lists) back into its parts, dropping empties. `None`/`""` ⇒ `[]`.
739fn split_lines(v: Option<String>) -> Vec<String> {
740    v.map(|s| s.lines().filter(|l| !l.is_empty()).map(str::to_string).collect()).unwrap_or_default()
741}
742
743// ─── DEB: (name, version, arch) + the raw control stanza ────────────────────
744
745spec!(DebSpec);
746impl CoordSpec for DebSpec {
747    const PKG_TYPE: i8 = DEB_PKG_TYPE;
748    const SLOT: usize = 7;
749    const COLS: &'static [&'static str] = &["name", "version", "arch", "control"];
750    const REQUIRED: usize = 1;
751    type Key = (String, String, String);
752    /// The raw `control` stanza; `None` when the `.deb` was not parseable at
753    /// ingest (coords then came from the filename).
754    type Extra = Option<String>;
755    fn row(c: &Cells<'_>, _: &str) -> (Self::Key, Option<String>) {
756        ((c.get(0), c.get(1), c.get(2)), c.opt(3))
757    }
758}
759/// Typed view over the deb sub-index.
760pub type DebView = CoordView<DebSpec>;
761/// A handle to one deb.
762pub type DebPackage = Package<DebSpec>;
763
764impl DebView {
765    /// O(1) lookup of the deb for `(name, version, arch)`.
766    pub fn get(&self, name: &str, version: &str, arch: &str) -> Option<DebPackage> {
767        self.package(&(name.into(), version.into(), arch.into()))
768    }
769    /// `(name, version, arch, control)` of every deb — the APT `Packages` synthesis feeds off this.
770    pub fn list(&self) -> Vec<(String, String, String, Option<String>)> {
771        self.entries().map(|(k, e)| (k.0.clone(), k.1.clone(), k.2.clone(), e.clone())).collect()
772    }
773}
774impl DebPackage {
775    pub fn name(&self) -> &str {
776        &self.key.0
777    }
778    pub fn version(&self) -> &str {
779        &self.key.1
780    }
781    pub fn arch(&self) -> &str {
782        &self.key.2
783    }
784    /// The raw `control` stanza, or `None` when the `.deb` wasn't parseable at ingest.
785    pub fn control(&self) -> Option<&str> {
786        self.extra.as_deref()
787    }
788}
789
790/// Number of view-cache slots ([`CoordSpec::SLOT`] is below it).
791pub(crate) const VIEW_SLOTS: usize = 8;