Skip to main content

ifc_template_catalog/
catalog.rs

1//! Immutable catalog snapshots and indices.
2
3use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use thiserror::Error;
7
8use crate::definition::{SetTemplate, SetTemplateKind, SourceManifest};
9use crate::overlay::{Advisory, AppliedPatch};
10
11/// Selected source-policy profile.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum CatalogProfile {
15    /// Unmodified upstream publication data, no correction overlay applied.
16    Official,
17    /// Official data with the built-in correction overlay's patches applied.
18    Corrected,
19    /// Official or corrected data with a caller-supplied overlay applied.
20    Custom,
21}
22
23/// Immutable, cheaply cloneable template snapshot.
24#[derive(Debug, Clone)]
25pub struct Catalog(Arc<CatalogInner>);
26
27#[derive(Debug, Clone)]
28struct CatalogInner {
29    manifest: SourceManifest,
30    profile: CatalogProfile,
31    templates: Vec<SetTemplate>,
32    by_name: BTreeMap<String, usize>,
33    applied_patches: Vec<AppliedPatch>,
34    advisories: Vec<Advisory>,
35}
36
37impl Catalog {
38    /// Build a snapshot for [`CatalogProfile::Official`] or
39    /// [`CatalogProfile::Custom`]. Fails on duplicate/empty template names or
40    /// a manifest set-count mismatch; use [`crate::overlay`] to build a
41    /// [`CatalogProfile::Corrected`] snapshot instead, since this rejects that
42    /// profile directly.
43    pub fn try_new(
44        manifest: SourceManifest,
45        profile: CatalogProfile,
46        templates: Vec<SetTemplate>,
47    ) -> Result<Self, CatalogError> {
48        if profile == CatalogProfile::Corrected {
49            return Err(CatalogError::CorrectedProfileRequiresPatches);
50        }
51        Self::try_new_with_profile(manifest, profile, templates)
52    }
53
54    /// Build a snapshot for any profile, including [`CatalogProfile::Corrected`].
55    /// Reserved for callers within this crate that have already produced an
56    /// applied-patch ledger.
57    pub(crate) fn try_new_with_profile(
58        manifest: SourceManifest,
59        profile: CatalogProfile,
60        templates: Vec<SetTemplate>,
61    ) -> Result<Self, CatalogError> {
62        let mut by_name = BTreeMap::new();
63        let mut property_sets = 0;
64        let mut quantity_sets = 0;
65        for (index, template) in templates.iter().enumerate() {
66            if template.name.trim().is_empty() {
67                return Err(CatalogError::EmptyTemplateName);
68            }
69            if by_name.insert(template.name.clone(), index).is_some() {
70                return Err(CatalogError::DuplicateTemplate(template.name.clone()));
71            }
72            match template.kind {
73                SetTemplateKind::Property { .. } => property_sets += 1,
74                SetTemplateKind::Quantity { .. } => quantity_sets += 1,
75            }
76        }
77        if manifest.property_set_count != property_sets
78            || manifest.quantity_set_count != quantity_sets
79        {
80            return Err(CatalogError::ManifestCountMismatch {
81                expected_property_sets: manifest.property_set_count,
82                actual_property_sets: property_sets,
83                expected_quantity_sets: manifest.quantity_set_count,
84                actual_quantity_sets: quantity_sets,
85            });
86        }
87        Ok(Self(Arc::new(CatalogInner {
88            manifest,
89            profile,
90            templates,
91            by_name,
92            applied_patches: Vec::new(),
93            advisories: Vec::new(),
94        })))
95    }
96
97    /// Look up a set template by its exact `Name`.
98    pub fn get(&self, name: &str) -> Option<&SetTemplate> {
99        self.0
100            .by_name
101            .get(name)
102            .map(|index| &self.0.templates[*index])
103    }
104
105    /// Iterate every set template in this snapshot, in load order.
106    pub fn iter(&self) -> impl ExactSizeIterator<Item = &SetTemplate> {
107        self.0.templates.iter()
108    }
109
110    /// Total number of set templates in this snapshot.
111    pub fn len(&self) -> usize {
112        self.0.templates.len()
113    }
114
115    /// True when the snapshot holds no set templates.
116    pub fn is_empty(&self) -> bool {
117        self.0.templates.is_empty()
118    }
119
120    /// Source-policy profile this snapshot was built with.
121    pub fn profile(&self) -> CatalogProfile {
122        self.0.profile
123    }
124
125    /// Source manifest this snapshot was built from.
126    pub fn manifest(&self) -> &SourceManifest {
127        &self.0.manifest
128    }
129
130    /// Overlay patches that were applied to reach this snapshot, empty
131    /// unless `profile()` is [`CatalogProfile::Corrected`] or [`CatalogProfile::Custom`].
132    pub fn applied_patches(&self) -> &[AppliedPatch] {
133        &self.0.applied_patches
134    }
135
136    /// Advisories targeting the named template, empty if none apply.
137    pub fn advisories_for(&self, template: &str) -> Vec<&Advisory> {
138        self.0
139            .advisories
140            .iter()
141            .filter(|advisory| advisory.target_template == template)
142            .collect()
143    }
144
145    /// Every advisory recorded against this snapshot, regardless of target.
146    pub(crate) fn advisories(&self) -> &[Advisory] {
147        &self.0.advisories
148    }
149
150    /// Replace this snapshot's profile, applied-patch ledger, and advisories
151    /// in place, cloning the shared inner state first if other handles exist.
152    pub(crate) fn with_overlay_state(
153        mut self,
154        profile: CatalogProfile,
155        applied_patches: Vec<AppliedPatch>,
156        advisories: Vec<Advisory>,
157    ) -> Self {
158        let inner = Arc::make_mut(&mut self.0);
159        inner.profile = profile;
160        inner.applied_patches = applied_patches;
161        inner.advisories = advisories;
162        self
163    }
164
165    /// Unwrap the snapshot into its owned template list, cloning only if
166    /// another handle to the shared inner state is still alive.
167    pub(crate) fn into_templates(self) -> Vec<SetTemplate> {
168        match Arc::try_unwrap(self.0) {
169            Ok(inner) => inner.templates,
170            Err(inner) => inner.templates.clone(),
171        }
172    }
173}
174
175/// Catalog construction failure.
176#[derive(Debug, Clone, PartialEq, Eq, Error)]
177#[non_exhaustive]
178pub enum CatalogError {
179    /// [`Catalog::try_new`] was called with [`CatalogProfile::Corrected`];
180    /// that profile can only be built by applying an overlay's patch ledger.
181    #[error("the corrected profile requires an applied patch ledger")]
182    CorrectedProfileRequiresPatches,
183    /// A template's `name` was empty or whitespace-only.
184    #[error("template name is empty")]
185    EmptyTemplateName,
186    /// Two templates in the input shared the same `name`.
187    #[error("duplicate template `{0}`")]
188    DuplicateTemplate(String),
189    /// The manifest's declared property-set/quantity-set counts did not
190    /// match the counts actually present in the template list.
191    #[error(
192        "source manifest counts differ: property sets {actual_property_sets}/{expected_property_sets}, quantity sets {actual_quantity_sets}/{expected_quantity_sets}"
193    )]
194    ManifestCountMismatch {
195        /// Property-set count declared by the manifest.
196        expected_property_sets: usize,
197        /// Property-set count actually found in the template list.
198        actual_property_sets: usize,
199        /// Quantity-set count declared by the manifest.
200        expected_quantity_sets: usize,
201        /// Quantity-set count actually found in the template list.
202        actual_quantity_sets: usize,
203    },
204}