Skip to main content

fallow_graph/
installed_versions.rs

1//! The versions of the hoisted Bun packages that import resolution read.
2//!
3//! The graph cache key reads the lockfiles and install markers that a
4//! package manager writes on each install. Bun writes no install marker, and
5//! the key lists only the package names in `node_modules` of a Bun project.
6//! A `bun install` of a pulled lockfile change can replace a hoisted package
7//! with another version under the same name, and the new version can have
8//! other `exports` (#4197).
9//!
10//! A cold run records each `node_modules/<name>/package.json` that the
11//! resolver read (see [`crate::missed_probes`]). The graph cache payload
12//! stores the `version` field of each of these manifests that a Bun lockfile
13//! governs, and a warm run refuses the payload when one of the versions
14//! changed. The imports of the project bound this set, so the size of the
15//! install does not change the cost of a warm run.
16
17use std::path::{Component, Path};
18
19use rustc_hash::FxHashMap;
20
21/// Lockfiles of Bun.
22const BUN_LOCKFILES: &[&str] = &["bun.lock", "bun.lockb"];
23
24/// Below this number of entries, a check runs on the calling thread: the
25/// rayon pool costs more than a few `stat` calls.
26pub(crate) const PARALLEL_MIN: usize = 64;
27
28/// The `version` field of each read package manifest that a Bun lockfile
29/// governs.
30#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
31pub struct InstalledVersions {
32    /// Sorted by path.
33    entries: Vec<InstalledVersion>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37struct InstalledVersion {
38    /// The manifest path relative to the root, with forward slashes and
39    /// with `../` steps for a manifest above the root.
40    manifest: String,
41    /// `None` when the manifest has no string `version` field or is not
42    /// valid JSON.
43    version: Option<String>,
44}
45
46impl InstalledVersions {
47    /// Read the version of each manifest in `manifests` (root-relative, see
48    /// [`crate::resolve::ResolvedProject::package_manifests`]) whose
49    /// `node_modules` directory a Bun lockfile governs. A manifest that is
50    /// gone now is left out: the package names in the graph cache key cover
51    /// an uninstall.
52    #[must_use]
53    pub(crate) fn read(root: &Path, manifests: &[String]) -> Self {
54        let mut governed: FxHashMap<&str, bool> = FxHashMap::default();
55        let mut entries: Vec<InstalledVersion> = manifests
56            .iter()
57            .filter(|manifest| {
58                let owner = owner_dir(manifest);
59                *governed
60                    .entry(owner)
61                    .or_insert_with(|| has_bun_lockfile(&root.join(owner)))
62            })
63            .filter_map(|manifest| {
64                let content = std::fs::read(root.join(manifest)).ok()?;
65                Some(InstalledVersion {
66                    manifest: manifest.clone(),
67                    version: version_of(&content),
68                })
69            })
70            .collect();
71        entries.sort_unstable_by(|a, b| a.manifest.cmp(&b.manifest));
72        Self { entries }
73    }
74
75    /// The number of stored manifests.
76    #[must_use]
77    pub fn len(&self) -> usize {
78        self.entries.len()
79    }
80
81    /// True when no manifest is stored.
82    #[must_use]
83    pub fn is_empty(&self) -> bool {
84        self.entries.is_empty()
85    }
86
87    /// True when a stored manifest has another version now, or is gone.
88    #[must_use]
89    pub(crate) fn any_changed(&self, root: &Path) -> bool {
90        let check = |entry: &InstalledVersion| {
91            !std::fs::read(root.join(&entry.manifest))
92                .is_ok_and(|content| version_of(&content) == entry.version)
93        };
94        if self.entries.len() < PARALLEL_MIN {
95            return self.entries.iter().any(check);
96        }
97        use rayon::prelude::*;
98        self.entries.par_iter().any(check)
99    }
100}
101
102/// The directory before the first `node_modules` step of `manifest`, which
103/// is the directory where the package manager installed the package.
104fn owner_dir(manifest: &str) -> &str {
105    manifest
106        .split_once("node_modules/")
107        .map_or("", |(owner, _)| owner.trim_end_matches('/'))
108}
109
110/// True when `dir` or one of its ancestors holds a Bun lockfile. A Bun
111/// workspace keeps one lockfile at the repository root and can install a
112/// package into the `node_modules` of a workspace package.
113fn has_bun_lockfile(dir: &Path) -> bool {
114    dir.ancestors()
115        .any(|dir| BUN_LOCKFILES.iter().any(|name| dir.join(name).is_file()))
116}
117
118fn version_of(content: &[u8]) -> Option<String> {
119    #[derive(serde::Deserialize)]
120    struct Manifest {
121        version: Option<serde_json::Value>,
122    }
123    let manifest: Manifest = serde_json::from_slice(content).ok()?;
124    match manifest.version? {
125        serde_json::Value::String(version) => Some(version),
126        _ => None,
127    }
128}
129
130/// The manifest path of a package below a `node_modules` directory,
131/// relative to one of `scopes`, or `None` for another file.
132///
133/// A path below a scope is spelled relative to it. A path below the
134/// `node_modules` directory of an ancestor of a scope, where Node looks up a
135/// package for a project in a subdirectory, gets one `../` step for each
136/// level.
137pub(crate) fn manifest_key(scopes: &[std::path::PathBuf], path: &Path) -> Option<String> {
138    if path.file_name()? != "package.json" || !has_node_modules_step(path) {
139        return None;
140    }
141    scopes.iter().find_map(|scope| {
142        scope.ancestors().enumerate().find_map(|(depth, base)| {
143            let rest = path.strip_prefix(base).ok()?;
144            if depth > 0 && rest.components().next() != Some(node_modules()) {
145                return None;
146            }
147            let mut key = "../".repeat(depth);
148            key.push_str(&rest.to_string_lossy().replace('\\', "/"));
149            Some(key)
150        })
151    })
152}
153
154fn has_node_modules_step(path: &Path) -> bool {
155    path.components()
156        .any(|component| component == node_modules())
157}
158
159fn node_modules() -> Component<'static> {
160    Component::Normal("node_modules".as_ref())
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    fn write(path: &Path, content: &str) {
168        std::fs::create_dir_all(path.parent().expect("parent")).expect("directory");
169        std::fs::write(path, content).expect("file");
170    }
171
172    #[test]
173    fn manifest_keys_cover_the_root_and_ancestor_node_modules_only() {
174        let scopes = vec![std::path::PathBuf::from("/repo/app")];
175        let key = |path: &str| manifest_key(&scopes, Path::new(path));
176        assert_eq!(
177            key("/repo/app/node_modules/a/package.json").as_deref(),
178            Some("node_modules/a/package.json")
179        );
180        assert_eq!(
181            key("/repo/node_modules/@s/b/package.json").as_deref(),
182            Some("../node_modules/@s/b/package.json")
183        );
184        assert_eq!(key("/repo/app/package.json"), None);
185        assert_eq!(key("/repo/app/node_modules/a/index.js"), None);
186        assert_eq!(key("/repo/other/node_modules/a/package.json"), None);
187    }
188
189    #[test]
190    fn owner_dir_is_the_directory_before_the_first_node_modules_step() {
191        assert_eq!(owner_dir("node_modules/a/package.json"), "");
192        assert_eq!(
193            owner_dir("packages/ui/node_modules/a/node_modules/b/package.json"),
194            "packages/ui"
195        );
196        assert_eq!(owner_dir("../node_modules/a/package.json"), "..");
197    }
198
199    #[test]
200    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
201    fn a_hoisted_bun_version_change_is_seen() {
202        let temp = tempfile::tempdir().expect("temp");
203        let root = temp.path().join("repo");
204        write(&root.join("bun.lock"), "{}");
205        let manifest = root.join("node_modules/a/package.json");
206        write(&manifest, r#"{"name":"a","version":"1.0.0"}"#);
207        let manifests = vec!["node_modules/a/package.json".to_string()];
208        let versions = InstalledVersions::read(&root, &manifests);
209        assert_eq!(versions.len(), 1);
210        assert!(!versions.any_changed(&root));
211
212        write(&manifest, r#"{"version":"1.0.0","name":"a","main":"x.js"}"#);
213        assert!(
214            !versions.any_changed(&root),
215            "a rewrite with the same version must keep the payload"
216        );
217
218        write(&manifest, r#"{"name":"a","version":"2.0.0"}"#);
219        assert!(versions.any_changed(&root));
220
221        std::fs::remove_file(&manifest).expect("remove");
222        assert!(versions.any_changed(&root));
223    }
224
225    #[test]
226    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
227    fn only_a_bun_install_is_stored() {
228        let temp = tempfile::tempdir().expect("temp");
229        let root = temp.path().join("repo/app");
230        let workspace = temp.path().join("repo/app/packages/ui");
231        write(&root.join("node_modules/a/package.json"), "{}");
232        write(&workspace.join("node_modules/b/package.json"), "{}");
233        let manifests = vec![
234            "node_modules/a/package.json".to_string(),
235            "packages/ui/node_modules/b/package.json".to_string(),
236        ];
237        assert!(InstalledVersions::read(&root, &manifests).is_empty());
238
239        write(&temp.path().join("repo/bun.lockb"), "");
240        assert_eq!(
241            InstalledVersions::read(&root, &manifests).len(),
242            2,
243            "a Bun lockfile above the owner directory governs it"
244        );
245    }
246}