Skip to main content

raf_source/locked/
mod.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! Exact package and outgoing-edge observations from an explicit lock profile.
5
6mod read;
7mod select;
8mod source;
9
10use std::fmt;
11
12use purrdf_lex::allocation::{Admission, Memory, StorageError};
13
14use crate::cost::shared_text;
15use crate::meter::{ItemAdmission, Meter};
16use crate::{LoadError, LoadErrorKind, LoadOptions, Origin, RelPath, Tree, Usage};
17
18pub use source::{LockedGitReference, LockedSource, LockedSourceKind};
19
20/// Explicit Cargo registry configuration supplied for one declaration selection.
21///
22/// This is an observation of configuration, not authentication of registry content.
23/// The source must include its `registry+` or `sparse+` family; no default index
24/// or registry-name mapping is inferred.
25#[derive(Debug, Clone, Copy)]
26pub struct RegistryIndex<'a> {
27    pub(crate) name: Option<&'a str>,
28    pub(crate) source: &'a str,
29}
30
31impl<'a> RegistryIndex<'a> {
32    /// Associate a registry name (`None` for the default) with an explicit index.
33    /// The source is validated when selecting an outgoing dependency.
34    #[must_use]
35    pub const fn new(name: Option<&'a str>, source: &'a str) -> Self {
36        Self { name, source }
37    }
38}
39
40/// A package row's identity within one [`LockedCatalog`], not a persistent key.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct LockedPackageId(pub(crate) usize);
43
44impl LockedPackageId {
45    /// The row position in [`LockedCatalog::packages`].
46    #[must_use]
47    pub const fn index(self) -> usize {
48        self.0
49    }
50}
51
52/// One complete locked package identity and its uniquely selected outgoing edges.
53///
54/// An absent source denotes a local lock row. Its actual manifest location still
55/// has to be supplied; absence is not a universal local source identity.
56#[derive(Debug, PartialEq, Eq)]
57pub struct LockedPackage {
58    id: LockedPackageId,
59    name: String,
60    version: String,
61    source: Option<LockedSource>,
62    checksum: Option<[u8; 32]>,
63    dependencies: Vec<LockedPackageId>,
64}
65
66impl LockedPackage {
67    /// The load-local row identity.
68    #[must_use]
69    pub const fn id(&self) -> LockedPackageId {
70        self.id
71    }
72
73    /// The exact package name, distinct from any Rust dependency alias.
74    #[must_use]
75    pub fn name(&self) -> &str {
76        &self.name
77    }
78
79    /// The validated canonical Cargo version, including prerelease and build text.
80    #[must_use]
81    pub fn version(&self) -> &str {
82        &self.version
83    }
84
85    /// The complete external source identity, or a local row awaiting binding.
86    #[must_use]
87    pub const fn source(&self) -> Option<&LockedSource> {
88        self.source.as_ref()
89    }
90
91    /// The recorded archive checksum, not authentication of a supplied tree.
92    #[must_use]
93    pub const fn checksum(&self) -> Option<&[u8; 32]> {
94        self.checksum.as_ref()
95    }
96
97    /// Actual outgoing edges after unique full-identity selection.
98    #[must_use]
99    pub fn dependencies(&self) -> &[LockedPackageId] {
100        &self.dependencies
101    }
102
103    fn key(&self) -> (&str, &str, Option<&LockedSource>) {
104        (&self.name, &self.version, self.source.as_ref())
105    }
106}
107
108/// A strict Cargo.lock version 3 or 4 package/edge profile.
109///
110/// TOML, repository IRIs, reference percent escapes, checksums and retained storage
111/// use `PurRDF`. Cargo versions use the private borrowed version adapter. Source
112/// repository spellings remain lexical identities, not guessed URL equivalences.
113/// Abbreviated edges must select exactly one complete package. Replacements and
114/// unsupported fields refuse instead of publishing partial dependency evidence.
115/// A catalog proves locked relationships, not source contents or active features.
116///
117/// Native retained conversion uses the original item allowance. Version parsing
118/// allocates nothing, and matching spends the original work grant before scanning
119/// qualifiers. The TOML decoder's temporary internal allocations have no admission
120/// callback; the original file/total-byte bounds apply to its input.
121#[derive(Debug)]
122pub struct LockedCatalog {
123    path: RelPath,
124    packages: Vec<LockedPackage>,
125    order: Vec<LockedPackageId>,
126    usage: Usage,
127}
128
129impl PartialEq for LockedCatalog {
130    fn eq(&self, other: &Self) -> bool {
131        self.path == other.path && self.packages == other.packages && self.order == other.order
132    }
133}
134
135impl Eq for LockedCatalog {}
136
137impl LockedCatalog {
138    /// Read and validate all package rows and outgoing references under bounds.
139    ///
140    /// # Errors
141    /// Returns the original tree, byte, native storage or work refusal, or an
142    /// actionable lock-profile error for malformed, unsupported, duplicate,
143    /// missing or ambiguous evidence. No first-match edge is accepted.
144    pub fn load(tree: &dyn Tree, path: &RelPath, options: &LoadOptions) -> Result<Self, LoadError> {
145        let meter = Meter::new(options);
146        let text = tree
147            .read(path, options.max_file_bytes)
148            .map_err(|error| LoadError::tree(path, None, &Origin::Discovery, error))?;
149        meter.read(path, &text)?;
150        meter.items(
151            size_of::<Self>() + shared_text(path.as_str().len()),
152            path,
153            None,
154        )?;
155        let mut admission = ItemAdmission::new(&meter, path);
156        let result = {
157            let mut memory = Memory::new(&mut admission);
158            read::catalog(&text, &mut memory, &meter, path)
159        };
160        let (packages, order) = result.map_err(|error| match error {
161            BuildError::Storage(error) => admission.error(error),
162            BuildError::Load(error) => error,
163            BuildError::Invalid {
164                field,
165                message,
166                source,
167            } => LoadError::new(
168                path,
169                None,
170                LoadErrorKind::Locked {
171                    field,
172                    message,
173                    source,
174                },
175            ),
176        })?;
177        Ok(Self {
178            path: path.clone(),
179            packages,
180            order,
181            usage: meter.usage(),
182        })
183    }
184
185    /// Package rows in lock-file order, with load-local IDs.
186    pub fn packages(&self) -> impl Iterator<Item = &LockedPackage> {
187        self.packages.iter()
188    }
189
190    /// The package of a valid row identity.
191    #[must_use]
192    pub fn package(&self, id: LockedPackageId) -> Option<&LockedPackage> {
193        self.packages.get(id.index())
194    }
195
196    /// Select one owning row's outgoing dependency by its written declaration.
197    ///
198    /// Uses the package rename, version and declared source/reference constraints.
199    /// Registry declarations need explicit matching configuration unless their
200    /// index is written directly. A path declaration retains its owner's local
201    /// or exact Git-workspace source; selection does not prove that row
202    /// corresponds to the declared directory.
203    /// Optional features and target conditions are not evaluated. Selection alone
204    /// neither binds a source tree nor establishes a loaded package's identity.
205    ///
206    /// # Errors
207    /// Refuses unknown owners, malformed declarations/configuration, missing or
208    /// ambiguous outgoing matches, incompatible constraints and budget failures.
209    /// Query storage shares the original retained catalog's item allowance; work
210    /// bounds this selection's comparisons, including compared text lengths.
211    pub fn select_dependency(
212        &self,
213        owner: LockedPackageId,
214        declaration: &crate::DependencyDeclaration,
215        registry: Option<RegistryIndex<'_>>,
216        options: &LoadOptions,
217    ) -> Result<LockedPackageId, LoadError> {
218        let meter = Meter::new(options);
219        meter.items(self.usage.item_bytes, &self.path, None)?;
220        self.select_under(owner, declaration, registry, &meter)
221    }
222
223    pub(crate) fn select_under(
224        &self,
225        owner: LockedPackageId,
226        declaration: &crate::DependencyDeclaration,
227        registry: Option<RegistryIndex<'_>>,
228        meter: &Meter,
229    ) -> Result<LockedPackageId, LoadError> {
230        let mut admission = ItemAdmission::new(meter, &self.path);
231        let result = select::dependency(
232            self,
233            owner,
234            declaration,
235            registry,
236            &mut Memory::new(&mut admission),
237            meter,
238        );
239        result.map_err(|error| match error {
240            BuildError::Storage(error) => admission.error(error),
241            BuildError::Load(error) => error,
242            BuildError::Invalid {
243                field,
244                message,
245                source,
246            } => LoadError::new(
247                &self.path,
248                None,
249                LoadErrorKind::Locked {
250                    field,
251                    message,
252                    source,
253                },
254            )
255            .reached_by(&Origin::ManifestKey {
256                key: declaration.key.clone(),
257            }),
258        })
259    }
260
261    /// The byte, retained conversion and comparison work charged by this load.
262    #[must_use]
263    pub const fn usage(&self) -> Usage {
264        self.usage
265    }
266}
267
268enum BuildError {
269    Storage(StorageError),
270    Load(LoadError),
271    Invalid {
272        field: &'static str,
273        message: String,
274        source: Option<Box<purrdf_toml::TomlError>>,
275    },
276}
277
278impl From<StorageError> for BuildError {
279    fn from(error: StorageError) -> Self {
280        Self::Storage(error)
281    }
282}
283
284impl From<LoadError> for BuildError {
285    fn from(error: LoadError) -> Self {
286        Self::Load(error)
287    }
288}
289
290fn invalid<S: Admission + ?Sized>(
291    memory: &mut Memory<'_, S>,
292    field: &'static str,
293    message: fmt::Arguments<'_>,
294) -> BuildError {
295    match memory.format(&message) {
296        Ok(message) => BuildError::Invalid {
297            field,
298            message,
299            source: None,
300        },
301        Err(error) => BuildError::Storage(error),
302    }
303}