Skip to main content

raf_source/workspace/locked/
observed.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//! Structural source contexts, kept separate from configured provider admission.
5
6use super::super::Reader;
7use super::{BindingLoad, LockedBinding, Purpose};
8use super::{LockedManifest, Sources, failure};
9use crate::{
10    CommittedGitTree, DiskTree, LoadError, LoadOptions, LockedCatalog, LockedPackageId,
11    LockedSource, PackageId, RegistryArchiveTree, RelPath, SourceAuthorityId, Tree, Workspace,
12};
13
14/// Manifest/lock identity retained for structural reference navigation.
15///
16/// This view has no configured target context and cannot be converted into a
17/// provider-admitted [`LockedBinding`]. Its package/source contents retain the
18/// observation contract of the actual selected backend.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct ReferenceBinding<'a> {
21    binding: &'a LockedBinding,
22}
23
24impl ReferenceBinding<'_> {
25    /// The selected row in the catalog supplied to this load.
26    #[must_use]
27    pub const fn row(&self) -> LockedPackageId {
28        self.binding.row()
29    }
30    /// The actual manifest's validated package name.
31    #[must_use]
32    pub fn name(&self) -> &str {
33        self.binding.name()
34    }
35    /// The actual explicit or inherited package version.
36    #[must_use]
37    pub fn version(&self) -> &str {
38        self.binding.version()
39    }
40    /// Declared source identity; contents may be an observation, not an archive.
41    #[must_use]
42    pub fn source(&self) -> Option<&LockedSource> {
43        self.binding.source()
44    }
45}
46
47impl BindingLoad<'_> {
48    pub(super) fn check_observed_path(
49        &self,
50        reader: &Reader<'_>,
51        declaration: &crate::DependencyDeclaration,
52        manifest: &RelPath,
53        destination: &RelPath,
54    ) -> Result<(), LoadError> {
55        let Purpose::Structural(contexts) = self.purpose else {
56            return Err(failure(
57                manifest,
58                "declared path does not name the selected row's actual admitted manifest",
59            ));
60        };
61        let (base, specification) = declaration
62            .inherited
63            .as_ref()
64            .map_or((manifest, &declaration.specification), |inherited| {
65                (&inherited.manifest, &inherited.specification)
66            });
67        let relative = specification.path.as_deref().ok_or_else(|| {
68            failure(
69                manifest,
70                "path relationship has no written path declaration",
71            )
72        })?;
73        let owner = contexts
74            .get(base.authority().index())
75            .ok_or_else(|| failure(manifest, "unknown owning source authority"))?;
76        let target = contexts
77            .get(destination.authority().index())
78            .ok_or_else(|| failure(destination, "unknown destination source authority"))?;
79        let bytes = base
80            .as_str()
81            .len()
82            .saturating_add(relative.len())
83            .saturating_add(destination.as_str().len());
84        reader.meter.work(bytes.saturating_add(1), manifest, None)?;
85        let matches = match (owner, target) {
86            (ReferenceTree::Disk(owner), ReferenceTree::Disk(target)) => {
87                reader.meter.items(
88                    bytes
89                        .saturating_add(owner.root_path_bytes())
90                        .saturating_add(target.root_path_bytes())
91                        .saturating_mul(4),
92                    manifest,
93                    None,
94                )?;
95                owner
96                    .dependency_directory_matches(
97                        &base.in_source(SourceAuthorityId::FIRST_PARTY),
98                        relative,
99                        target,
100                        &destination.in_source(SourceAuthorityId::FIRST_PARTY),
101                    )
102                    .map_err(|error| {
103                        LoadError::tree(manifest, None, &crate::error::Origin::Discovery, error)
104                    })?
105            }
106            (ReferenceTree::Git(owner), ReferenceTree::Git(target))
107                if owner.source() == target.source() =>
108            {
109                let directory = base
110                    .parent()
111                    .ok_or_else(|| failure(base, "manifest has no owning directory"))?;
112                let expected = directory
113                    .join(relative)
114                    .and_then(|path| path.join("Cargo.toml"))
115                    .map_err(|error| failure(manifest, &error.to_string()))?;
116                let expected = crate::modtree::tidy(reader.tree, &expected).map_err(|error| {
117                    LoadError::tree(manifest, None, &crate::error::Origin::Discovery, error)
118                })?;
119                expected.in_source(destination.authority()) == *destination
120            }
121            _ => {
122                return Err(failure(
123                    manifest,
124                    "cross-authority path relationships require actual disk roots or one exact committed Git source",
125                ));
126            }
127        };
128        if !matches {
129            return Err(failure(
130                manifest,
131                "declared path names a different package directory from the supplied destination",
132            ));
133        }
134        Ok(())
135    }
136}
137
138/// The actual backend of a structural reference source.
139///
140/// Disk contexts retain the root needed to verify cross-root path declarations.
141/// Opaque trees permit path edges only inside their own authority. Git contexts
142/// retain their exact committed source; registry contexts retain authenticated
143/// archives. None supplies configured provider proof.
144#[derive(Clone, Copy)]
145#[non_exhaustive]
146pub enum ReferenceTree<'a> {
147    /// A caller-owned tree with no host-directory relationship to other trees.
148    Opaque(&'a dyn Tree),
149    /// A contained disk root whose actual directory relationship can be checked.
150    Disk(&'a DiskTree),
151    /// An opaque exact committed Git source.
152    Git(&'a CommittedGitTree<'a>),
153    /// An opaque checksum-authenticated registry archive.
154    Registry(&'a RegistryArchiveTree<'a>),
155}
156
157impl<'a> ReferenceTree<'a> {
158    pub(super) fn tree(self) -> &'a dyn Tree {
159        match self {
160            Self::Opaque(tree) => tree,
161            Self::Disk(tree) => tree,
162            Self::Git(tree) => tree,
163            Self::Registry(tree) => tree,
164        }
165    }
166
167    pub(super) fn source(self) -> Option<&'a LockedSource> {
168        match self {
169            Self::Git(tree) => Some(tree.source()),
170            Self::Registry(tree) => Some(tree.source()),
171            Self::Opaque(_) | Self::Disk(_) => None,
172        }
173    }
174}
175
176/// Explicit manifest associations in one actual structural reference context.
177///
178/// Package names and lock rows are checked against the loaded manifests. Disk
179/// and opaque contents remain observations, not archive authentication.
180#[derive(Clone, Copy)]
181pub struct ReferencePackageRoots<'a> {
182    pub(super) tree: ReferenceTree<'a>,
183    pub(super) packages: &'a [LockedManifest<'a>],
184}
185
186impl<'a> ReferencePackageRoots<'a> {
187    /// Select the actual source backend and exact retained declaration keys.
188    #[must_use]
189    pub const fn new(tree: ReferenceTree<'a>, packages: &'a [LockedManifest<'a>]) -> Self {
190        Self { tree, packages }
191    }
192}
193
194impl Workspace {
195    /// Structural reference identity without configured provider admission.
196    #[must_use]
197    pub fn reference_binding(&self, package: PackageId) -> Option<ReferenceBinding<'_>> {
198        self.references
199            .get(package.index())
200            .map(|binding| ReferenceBinding { binding })
201    }
202
203    /// Load one structural identity domain for first-party and reference code.
204    ///
205    /// Every discovered package needs an exact manifest/lock association. Edges
206    /// use retained declaration keys, aliases and dependency kinds. Path edges
207    /// must name the actual destination directory, including across disk roots.
208    /// Optional and conditional declarations remain structural observations;
209    /// no target activation or configured provider proof is asserted.
210    /// Unrequested local paths retain ordinary structural lookup; unselected
211    /// external dependencies remain unresolved.
212    ///
213    /// The ordinary index is built once over all selected sources. Returned
214    /// packages have no [`Self::locked_binding`], even for sealed Git sources.
215    /// All source reads and indexing share the original supplied limits.
216    ///
217    /// # Errors
218    /// Refuses missing or ambiguous manifests, wrong rows or path destinations,
219    /// configured inputs, unproved opaque cross-authority paths and exhausted
220    /// source/index limits. No partial identity domain is returned.
221    pub fn load_reference_sources_under(
222        catalog: &LockedCatalog,
223        first_party: ReferenceTree<'_>,
224        first_party_roots: &[RelPath],
225        local: &[LockedManifest<'_>],
226        sources: &[ReferencePackageRoots<'_>],
227        options: &LoadOptions,
228    ) -> Result<Self, LoadError> {
229        super::check_first_party_roots(first_party_roots)?;
230        Self::load_locked_with(
231            catalog,
232            first_party,
233            Some(first_party_roots),
234            local,
235            Sources::Observed(sources),
236            options,
237            super::SyntaxLoad::Ordinary(None),
238        )
239    }
240}