forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

dependency_guard.rs278 lines, 10.0 KiBHistoryRawDownload
1//! The dependency graph of `engine` and `engine-hw` holds none of
2//! the crates the dependency replacement removed: only rav1e and symphonia
3//! stay as third-party media crates.
4//!
5//! The graph is read from the workspace `Cargo.lock`, not from `cargo metadata`:
6//! metadata wants every locked package on disk, and a lane VPS without the
7//! packages that only dev or other-platform builds need cannot run it offline.
8//! The lock does not record dependency kinds, so this walk follows build edges
9//! as well as normal ones. That is stricter than `cargo tree -e normal`, and it
10//! is exact today because none of the three roots declares a dev or build
11//! dependency.
12
13use std::collections::{BTreeSet, HashMap, VecDeque};
14
15/// The packages whose dependency graphs are guarded.
16const ROOTS: [&str; 2] = ["engine", "engine-hw"];
17
18/// Crates that must not be reachable through a dependency of any root.
19const FORBIDDEN: [&str; 9] = [
20 "symphonia-codec-aac",
21 "mp4",
22 "cros-codecs",
23 "gbm",
24 "image",
25 "ravif",
26 "flacenc",
27 "hound",
28 "miniz_oxide",
29];
30
31/// Every crate whose name starts with this is forbidden as well.
32const FORBIDDEN_PREFIX: &str = "oxideav-";
33
34/// Hardware crates `engine-hw` still linked until the VA-API wave replaced them.
35/// Emptied: cros-codecs and gbm are gone; cros-libva is back under ec-va (see ONLY_UNDER).
36const PENDING_WAVE2: [&str; 0] = [];
37
38/// Crates that may appear only as a direct dependency of the named crate.
39/// cros-libva is the safe VA-API binding under ec-va: it lets ec-va forbid
40/// unsafe code, so it stays, but nothing else may pull it in.
41const ONLY_UNDER: [(&str, &str); 1] = [("cros-libva", "ec-va")];
42
43/// Crates that may appear only as a direct dependency of `engine`, or as a
44/// dependency of one another (symphonia pulls symphonia-core in itself).
45const ALLOWED_FROM_ENGINE: [&str; 3] = ["rav1e", "symphonia", "symphonia-core"];
46
47/// One `[[package]]` of Cargo.lock: its key (`name version`), its name, whether
48/// it comes from a registry, and its raw dependency entries.
49struct Locked {
50 key: String,
51 name: String,
52 registry: bool,
53 deps: Vec<String>,
54}
55
56/// Reads the `[[package]]` blocks of Cargo.lock. Dependency entries are either
57/// `"name"` or `"name version"` (optionally followed by a source), and the
58/// version is only written when the name is ambiguous.
59fn locked_packages() -> Vec<Locked> {
60 let lock = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../Cargo.lock"))
61 .expect("read the workspace Cargo.lock");
62 let mut packages = Vec::new();
63 for block in lock.split("[[package]]\n").skip(1) {
64 let mut name = String::new();
65 let mut version = String::new();
66 let mut registry = false;
67 let mut deps = Vec::new();
68 let mut in_deps = false;
69 for line in block.lines() {
70 if in_deps {
71 if line == "]" {
72 in_deps = false;
73 } else {
74 let entry = line.trim().trim_end_matches(',').trim_matches('"');
75 deps.push(entry.to_string());
76 }
77 } else if let Some(v) = line.strip_prefix("name = ") {
78 name = v.trim_matches('"').to_string();
79 } else if let Some(v) = line.strip_prefix("version = ") {
80 version = v.trim_matches('"').to_string();
81 } else if line.starts_with("source = ") {
82 registry = true;
83 } else if line == "dependencies = [" {
84 in_deps = true;
85 }
86 }
87 packages.push(Locked {
88 key: format!("{name} {version}"),
89 name,
90 registry,
91 deps,
92 });
93 }
94 packages
95}
96
97/// Turns a lock dependency entry into the key of the package it names.
98fn resolve(entry: &str, keys_by_name: &HashMap<&str, Vec<&str>>) -> String {
99 let mut parts = entry.split_whitespace();
100 let name = parts.next().unwrap();
101 match parts.next() {
102 Some(version) => format!("{name} {version}"),
103 None => {
104 let keys = &keys_by_name[name];
105 assert_eq!(
106 keys.len(),
107 1,
108 "{name} is ambiguous in Cargo.lock but written bare"
109 );
110 keys[0].to_string()
111 }
112 }
113}
114
115/// Breadth-first walk over the edges, from `starts`, never entering a package
116/// `blocked` returns true for. Maps each reached key to the key it came from.
117fn walk(
118 starts: &[String],
119 edges: &HashMap<&str, Vec<String>>,
120 name_of: &HashMap<&str, &str>,
121 blocked: impl Fn(&str) -> bool,
122) -> HashMap<String, Option<String>> {
123 let mut parent: HashMap<String, Option<String>> =
124 starts.iter().map(|s| (s.clone(), None)).collect();
125 let mut queue: VecDeque<String> = starts.iter().cloned().collect();
126 while let Some(key) = queue.pop_front() {
127 for next in edges.get(key.as_str()).into_iter().flatten() {
128 if !parent.contains_key(next) && !blocked(name_of[next.as_str()]) {
129 parent.insert(next.clone(), Some(key.clone()));
130 queue.push_back(next.clone());
131 }
132 }
133 }
134 parent
135}
136
137/// The chain of names from the walk's start to `key`.
138fn path_to(
139 key: &str,
140 parent: &HashMap<String, Option<String>>,
141 name_of: &HashMap<&str, &str>,
142) -> String {
143 let mut names = Vec::new();
144 let mut cur = Some(key.to_string());
145 while let Some(c) = cur {
146 names.push(name_of[c.as_str()].to_string());
147 cur = parent[&c].clone();
148 }
149 names.reverse();
150 names.join(" -> ")
151}
152
153#[test]
154fn no_forbidden_crate_is_in_the_dependency_graph() {
155 let packages = locked_packages();
156 let mut keys_by_name: HashMap<&str, Vec<&str>> = HashMap::new();
157 for p in &packages {
158 keys_by_name
159 .entry(p.name.as_str())
160 .or_default()
161 .push(p.key.as_str());
162 }
163 let name_of: HashMap<&str, &str> = packages
164 .iter()
165 .map(|p| (p.key.as_str(), p.name.as_str()))
166 .collect();
167 // Workspace members and path packages have no `source`; the roots are among them.
168 let roots: Vec<String> = packages
169 .iter()
170 .filter(|p| !p.registry && ROOTS.contains(&p.name.as_str()))
171 .map(|p| p.key.clone())
172 .collect();
173 assert_eq!(
174 roots.len(),
175 ROOTS.len(),
176 "every guarded root is in Cargo.lock"
177 );
178 let engine = roots
179 .iter()
180 .find(|k| name_of[k.as_str()] == "engine")
181 .expect("engine is in Cargo.lock")
182 .clone();
183
184 let edges: HashMap<&str, Vec<String>> = packages
185 .iter()
186 .map(|p| {
187 let deps = p.deps.iter().map(|d| resolve(d, &keys_by_name)).collect();
188 (p.key.as_str(), deps)
189 })
190 .collect();
191
192 let is_allowed = |name: &str| ALLOWED_FROM_ENGINE.contains(&name);
193 let mut violations = Vec::new();
194
195 // Everything reachable from the three roots.
196 let parent = walk(&roots, &edges, &name_of, |_| false);
197 let mut reached: Vec<&String> = parent.keys().collect();
198 reached.sort_unstable();
199 let mut seen_pending = BTreeSet::new();
200 for key in reached {
201 let name = name_of[key.as_str()];
202 if PENDING_WAVE2.contains(&name) {
203 seen_pending.insert(name);
204 } else if FORBIDDEN.contains(&name) || name.starts_with(FORBIDDEN_PREFIX) {
205 violations.push(format!(
206 "{name} is in the dependency graph: {}",
207 path_to(key, &parent, &name_of)
208 ));
209 }
210 }
211
212 // The allowed crates may come in only through engine's own direct dependencies.
213 // Walk from everything else, never entering an allowed crate: any allowed crate
214 // that walk reaches arrived by another route.
215 let mut other_starts: Vec<String> = roots.iter().filter(|r| **r != engine).cloned().collect();
216 for dep in edges.get(engine.as_str()).into_iter().flatten() {
217 if !is_allowed(name_of[dep.as_str()]) {
218 other_starts.push(dep.clone());
219 }
220 }
221 let other = walk(&other_starts, &edges, &name_of, is_allowed);
222 let mut stray: Vec<&String> = other.keys().collect();
223 stray.sort_unstable();
224 for key in stray {
225 // A start of this walk is never itself an allowed crate, so this is a route in.
226 let name = name_of[key.as_str()];
227 if is_allowed(name) {
228 violations.push(format!(
229 "{name} may only be a direct dependency of engine, but it is reached by: {}",
230 path_to(key, &other, &name_of)
231 ));
232 }
233 }
234 // Direct allowed dependencies of other roots are caught by the walk above (they are
235 // edges out of a start), but a root listing one directly is reported explicitly.
236 for root in roots.iter().filter(|r| **r != engine) {
237 for dep in edges.get(root.as_str()).into_iter().flatten() {
238 if is_allowed(name_of[dep.as_str()]) {
239 violations.push(format!(
240 "{} depends on {} directly, but only engine may",
241 name_of[root.as_str()],
242 name_of[dep.as_str()]
243 ));
244 }
245 }
246 }
247
248 for (name, owner) in ONLY_UNDER {
249 for key in parent.keys().filter(|k| name_of[k.as_str()] == name) {
250 for (from, deps) in &edges {
251 if parent.contains_key(*from)
252 && name_of[*from] != owner
253 && deps.iter().any(|d| d == key)
254 {
255 violations.push(format!(
256 "{name} may only be a dependency of {owner}, but {} depends on it",
257 name_of[*from]
258 ));
259 }
260 }
261 }
262 }
263
264 for name in PENDING_WAVE2 {
265 if !seen_pending.contains(name) {
266 violations.push(format!(
267 "{name} is no longer in the dependency graph: delete it from PENDING_WAVE2"
268 ));
269 }
270 }
271
272 violations.sort();
273 assert!(
274 violations.is_empty(),
275 "dependency guard failed:\n {}",
276 violations.join("\n ")
277 );
278}