Skip to main content

raf_source/tree/
sources.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//! Dispatch independently rooted trees by typed source authority.
5
6use super::{Entry, EntryKind, FileId, Opened, Tree};
7use crate::{RelPath, SourceAuthorityId, TreeError};
8use std::cell::Cell;
9
10/// A first-party tree and borrowed, independently rooted dependency trees.
11///
12/// This provides physical source separation, not package or revision proof.
13/// The caller guarantees each supplied tree's source identity; a locked catalog
14/// must validate that correspondence before publishing grounded dependencies.
15/// Authority handles are local to this collection. Relative spelling, module
16/// traversal and filesystem containment remain within the selected tree.
17/// Each supplied backend accepts unqualified paths and returns authority-zero
18/// file identities. Already-scoped backend identities are refused, never flattened.
19pub struct SourceTrees<'a> {
20    first_party: &'a dyn Tree,
21    dependencies: &'a [&'a dyn Tree],
22}
23
24impl<'a> SourceTrees<'a> {
25    /// Borrow source trees without copying or retaining their contents.
26    #[must_use]
27    pub const fn new(first_party: &'a dyn Tree, dependencies: &'a [&'a dyn Tree]) -> Self {
28        Self {
29            first_party,
30            dependencies,
31        }
32    }
33
34    /// The load-local authorities, starting with the first-party tree.
35    pub fn authorities(&self) -> impl Iterator<Item = SourceAuthorityId> {
36        std::iter::once(SourceAuthorityId::FIRST_PARTY)
37            .chain((0..self.dependencies.len()).map(|index| SourceAuthorityId(index + 1)))
38    }
39
40    /// The root of an available source, or `None` for an unknown authority.
41    #[must_use]
42    pub fn root(&self, authority: SourceAuthorityId) -> Option<RelPath> {
43        self.source(authority)
44            .map(|_| RelPath::root().in_source(authority))
45    }
46
47    fn source(&self, authority: SourceAuthorityId) -> Option<&dyn Tree> {
48        match authority.index() {
49            0 => Some(self.first_party),
50            index => self.dependencies.get(index - 1).copied(),
51        }
52    }
53
54    fn selected(&self, path: &RelPath) -> Result<(&dyn Tree, RelPath), TreeError> {
55        let tree = self
56            .source(path.authority())
57            .ok_or_else(|| TreeError::WrongAuthority {
58                path: path.to_string(),
59                authority: path.authority(),
60            })?;
61        Ok((tree, path.in_source(SourceAuthorityId::FIRST_PARTY)))
62    }
63}
64
65impl Tree for SourceTrees<'_> {
66    fn read(&self, path: &RelPath, max_bytes: u64) -> Result<String, TreeError> {
67        let (tree, local) = self.selected(path)?;
68        tree.read(&local, max_bytes)
69    }
70
71    fn read_bytes(&self, path: &RelPath, max_bytes: u64) -> Result<Vec<u8>, TreeError> {
72        let (tree, local) = self.selected(path)?;
73        tree.read_bytes(&local, max_bytes)
74    }
75
76    fn read_unseen(
77        &self,
78        path: &RelPath,
79        max_bytes: u64,
80        seen: &dyn Fn(&FileId) -> bool,
81    ) -> Result<Opened, TreeError> {
82        let (tree, local) = self.selected(path)?;
83        let authority = path.authority();
84        let wrong = Cell::new(None);
85        let result = tree.read_unseen(&local, max_bytes, &|id| {
86            if wrong.get().is_some() {
87                return false;
88            }
89            if id.authority() != SourceAuthorityId::FIRST_PARTY {
90                wrong.set(Some(id.authority()));
91                return false;
92            }
93            seen(&id.clone().in_source(authority))
94        });
95        if let Some(authority) = wrong.get() {
96            return Err(TreeError::BackendAuthority {
97                path: path.to_string(),
98                authority,
99            });
100        }
101        let opened = result?;
102        let id = match &opened {
103            Opened::Seen(id) | Opened::Read { id, .. } => id,
104        };
105        if id.authority() != SourceAuthorityId::FIRST_PARTY {
106            return Err(TreeError::BackendAuthority {
107                path: path.to_string(),
108                authority: id.authority(),
109            });
110        }
111        Ok(match opened {
112            Opened::Seen(id) => Opened::Seen(id.in_source(authority)),
113            Opened::Read { id, text } => Opened::Read {
114                id: id.in_source(authority),
115                text,
116            },
117        })
118    }
119
120    fn list(&self, path: &RelPath) -> Result<Vec<Entry>, TreeError> {
121        let (tree, local) = self.selected(path)?;
122        tree.list(&local)
123    }
124
125    fn entry(&self, path: &RelPath) -> Result<Option<EntryKind>, TreeError> {
126        let (tree, local) = self.selected(path)?;
127        tree.entry(&local)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::MemoryTree;
135
136    /// A backend exposing explicit identity tags to exercise the mount boundary.
137    struct TaggedBackend {
138        tree: MemoryTree,
139        authority: SourceAuthorityId,
140    }
141
142    impl Tree for TaggedBackend {
143        fn read(&self, path: &RelPath, max_bytes: u64) -> Result<String, TreeError> {
144            self.tree.read(path, max_bytes)
145        }
146
147        fn read_unseen(
148            &self,
149            path: &RelPath,
150            max_bytes: u64,
151            seen: &dyn Fn(&FileId) -> bool,
152        ) -> Result<Opened, TreeError> {
153            Ok(
154                match self.tree.read_unseen(path, max_bytes, &|id| {
155                    seen(&id.clone().in_source(self.authority))
156                })? {
157                    Opened::Seen(id) => Opened::Seen(id.in_source(self.authority)),
158                    Opened::Read { id, text } => Opened::Read {
159                        id: id.in_source(self.authority),
160                        text,
161                    },
162                },
163            )
164        }
165
166        fn list(&self, path: &RelPath) -> Result<Vec<Entry>, TreeError> {
167            self.tree.list(path)
168        }
169        fn entry(&self, path: &RelPath) -> Result<Option<EntryKind>, TreeError> {
170            self.tree.entry(path)
171        }
172    }
173
174    #[test]
175    fn scoped_backend_ids_are_refused_before_seen_and_preserve_the_first_cause() {
176        let first = MemoryTree::default();
177        let bad = TaggedBackend {
178            tree: MemoryTree::from([("lib.rs", "source")]),
179            authority: SourceAuthorityId(7),
180        };
181        let good = TaggedBackend {
182            tree: MemoryTree::from([("lib.rs", "source")]),
183            authority: SourceAuthorityId::FIRST_PARTY,
184        };
185        let dependencies: [&dyn Tree; 2] = [&bad, &good];
186        let sources = SourceTrees::new(&first, &dependencies);
187        let ids: Vec<_> = sources.authorities().collect();
188        let local = RelPath::new("lib.rs").expect("path");
189        // Even a later byte-limit failure cannot replace the backend-identity refusal.
190        let error = sources
191            .read_unseen(&local.in_source(ids[1]), 0, &|_| {
192                panic!("an invalid backend ID must not reach the caller")
193            })
194            .expect_err("already-scoped backend ID");
195        assert!(matches!(
196            error,
197            TreeError::BackendAuthority {
198                authority: SourceAuthorityId(7),
199                ..
200            }
201        ));
202        assert!(
203            matches!(sources.read_unseen(&local.in_source(ids[2]), 0, &|_| true),
204            Ok(Opened::Seen(id)) if id.authority() == ids[2])
205        );
206        assert_eq!(
207            sources
208                .read(&local.in_source(ids[2]), 6)
209                .expect("valid backend"),
210            "source"
211        );
212    }
213
214    #[test]
215    fn equal_relative_paths_and_backend_keys_remain_separate_sources() {
216        let first = MemoryTree::from([("src/lib.rs", "first")]);
217        let second = MemoryTree::from([("src/lib.rs", "second")]);
218        let dependencies: [&dyn Tree; 1] = [&second];
219        let sources = SourceTrees::new(&first, &dependencies);
220        let authorities: Vec<_> = sources.authorities().collect();
221        let plain = RelPath::new("src/lib.rs").expect("relative path");
222        let other = plain.in_source(authorities[1]);
223        assert_ne!(plain, other);
224        assert_eq!(plain.as_str(), other.as_str());
225        assert_eq!(sources.read(&plain, 5).expect("first"), "first");
226        assert_eq!(sources.read(&other, 6).expect("second"), "second");
227        assert!(matches!(
228            sources.read(&other, 5),
229            Err(TreeError::TooLarge { limit: 5, .. })
230        ));
231        let first_id = sources.identity(&plain).expect("first identity");
232        let second_id = sources.identity(&other).expect("second identity");
233        assert_ne!(first_id, second_id);
234        assert_eq!(second_id.authority(), authorities[1]);
235        assert!(
236            matches!(sources.read_unseen(&other, 0, &|id| id == &second_id),
237            Ok(Opened::Seen(id)) if id == second_id)
238        );
239        assert!(
240            matches!(sources.read_unseen(&other, 6, &|id| id == &first_id),
241            Ok(Opened::Read { text, .. }) if text == "second")
242        );
243        let root = sources.root(authorities[1]).expect("source root");
244        assert_eq!(sources.list(&root).expect("directory").len(), 1);
245        assert_eq!(sources.entry(&other).expect("entry"), Some(EntryKind::File));
246        let unknown = other.in_source(SourceAuthorityId(2));
247        assert!(matches!(
248            sources.entry(&unknown),
249            Err(TreeError::WrongAuthority { .. })
250        ));
251        assert!(sources.root(unknown.authority()).is_none());
252    }
253
254    #[test]
255    fn parent_join_and_real_directory_normalization_keep_the_selected_root() {
256        let first = MemoryTree::from([("src/lib.rs", "first")]);
257        let second = MemoryTree::from([("src/lib.rs", "second"), ("src/sub/item.rs", "item")]);
258        let dependencies: [&dyn Tree; 1] = [&second];
259        let sources = SourceTrees::new(&first, &dependencies);
260        let authority = sources.authorities().nth(1).expect("dependency");
261        let path = sources
262            .root(authority)
263            .expect("root")
264            .join("src/sub/../lib.rs")
265            .expect("join");
266        assert_eq!(path.authority(), authority);
267        assert_eq!(path.parent().expect("parent").authority(), authority);
268        let tidy = crate::modtree::tidy(&sources, &path).expect("real directory normalization");
269        assert_eq!(tidy.as_str(), "src/lib.rs");
270        assert_eq!(tidy.authority(), authority);
271        assert_eq!(sources.read(&tidy, 6).expect("selected source"), "second");
272        let inside = sources
273            .root(authority)
274            .expect("root")
275            .join("src/../src/lib.rs")
276            .expect("inside");
277        assert_eq!(sources.read(&inside, 6).expect("inside neighbor"), "second");
278        assert!(
279            sources
280                .root(authority)
281                .expect("root")
282                .join("../src/lib.rs")
283                .is_err()
284        );
285        // No source handle is a textual prefix that `..` could remove.
286        assert_eq!(
287            path.source_root(),
288            sources.root(authority).expect("same root")
289        );
290    }
291
292    #[test]
293    fn standalone_memory_tree_refuses_another_sources_tag_before_seen_callback() {
294        let tree = MemoryTree::from([("src/lib.rs", "source")]);
295        let local = RelPath::new("src/lib.rs").expect("path");
296        let foreign = local.in_source(SourceAuthorityId(1));
297        assert!(matches!(
298            tree.read(&foreign, 6),
299            Err(TreeError::WrongAuthority { .. })
300        ));
301        assert!(matches!(
302            tree.entry(&foreign),
303            Err(TreeError::WrongAuthority { .. })
304        ));
305        assert!(matches!(
306            tree.list(&foreign.source_root()),
307            Err(TreeError::WrongAuthority { .. })
308        ));
309        assert!(matches!(
310            tree.identity(&foreign),
311            Err(TreeError::WrongAuthority { .. })
312        ));
313        assert!(matches!(
314            tree.read_unseen(&foreign, 6, &|_| panic!("must refuse before callback")),
315            Err(TreeError::WrongAuthority { .. })
316        ));
317        assert_eq!(tree.read(&local, 6).expect("ordinary source"), "source");
318    }
319}