diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 663c7c098..5e266c294 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -894,7 +894,7 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | -**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in or, above the scanned directory, is the home directory or above it; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or the directory holds more than 500,000 directories and links; when a link resolves to a directory outside the directory that was read, to a file outside it that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read for its own sake. A link to a directory outside it is followed: that directory, and each `node_modules` in a directory above it (up to the home directory, which is not read), are read the same way and once each, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read; a directory above the scanned one is read only this way. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in or, above the scanned directory, is the home directory or above it; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the home directory or one above it, to a file outside what was read that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: diff --git a/crates/socket-patch-cli/tests/common/pnpm_links.rs b/crates/socket-patch-cli/tests/common/pnpm_links.rs index 3c4b6c6e8..66a3ffe99 100644 --- a/crates/socket-patch-cli/tests/common/pnpm_links.rs +++ b/crates/socket-patch-cli/tests/common/pnpm_links.rs @@ -45,13 +45,49 @@ fn links_below(tree: &Path) -> Vec<(PathBuf, PathBuf)> { } /// The entries of the virtual store `store` that a path which starts -/// below `tree` and outside the store's entries leads into: each entry -/// that a link outside the entries resolves into, each entry that a link -/// inside one of those resolves into, and so on. +/// below `tree`, or below what a link leads to outside it, and outside +/// the store's entries leads into: each entry that a link outside the +/// entries resolves into, each entry that a link inside one of those +/// resolves into, and so on. pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { let tree = std::fs::canonicalize(tree).unwrap(); let store = std::fs::canonicalize(store).unwrap(); - let links = links_below(&tree); + // Node loads what a link leads to from where it really is: every + // directory a link leads to outside the trees read so far is read as + // well, and so is the `node_modules` of each directory above it. A + // `node_modules` that is a link is one more link, and what it leads + // to is read the same way. Nothing at the temp dir or above it is + // read: the tests build below it. + let stop = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let mut trees = vec![tree]; + let mut links = Vec::new(); + let mut next = 0; + while next < trees.len() { + let found = links_below(&trees[next]); + next += 1; + let mut targets: Vec = found.iter().map(|(_, to)| to.clone()).collect(); + links.extend(found); + while let Some(target) = targets.pop() { + let read = trees.iter().any(|tree| target.starts_with(tree)); + if read || target.starts_with(&store) || !target.is_dir() || stop.starts_with(&target) { + continue; + } + for above in target.ancestors().skip(1) { + if stop.starts_with(above) { + break; + } + let modules = above.join("node_modules"); + let Ok(real) = std::fs::canonicalize(&modules) else { + continue; + }; + if real != modules { + links.push((modules, real.clone())); + } + targets.push(real); + } + trees.push(target); + } + } let mut reachable = BTreeSet::new(); loop { let before = reachable.len(); diff --git a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs index 8a046719a..761614d5a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -3655,7 +3655,16 @@ fn write_route_workspace(proj: &Path, registry: &MockServer, modules_dir: Option /// it attests with their status, and its stderr. #[cfg(unix)] fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, String) { - let (code, stdout, stderr) = run_socket( + route_vex_env(dir, server, &[]) +} + +/// [`route_vex`] with extra env. +fn route_vex_env( + dir: &Path, + server: &MockServer, + env: &[(String, String)], +) -> (i32, Vec<(String, String)>, String) { + let (code, stdout, stderr) = run_socket_env( dir, &[ "vex", @@ -3670,6 +3679,7 @@ fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, St "--patch-server-url", &server.uri(), ], + env, ); let statements = serde_json::from_str::(&stdout) .ok() @@ -3911,6 +3921,78 @@ async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: attested.contains(¬_affected(leaf)), "{tag}: without the links leaf is attested again: {attested:?}\n{stderr}" ); + + // A link that leads out of the project is followed. A directory + // beside the project that links nothing of the store changes nothing; + // one whose `node_modules` links the upstream leaf, as a member that + // left the workspace keeps doing, refuses the patch. The test's own + // directory stands in for the home directory, so no `node_modules` + // that the machine keeps above it is read. + let home = [("HOME".to_string(), tmp.path().to_str().unwrap().to_string())]; + let outside = tmp.path().join("shared"); + std::fs::create_dir_all(outside.join("lib")).unwrap(); + std::fs::create_dir_all(proj.join("tools")).unwrap(); + std::os::unix::fs::symlink(outside.join("lib"), proj.join("tools/lib")).unwrap(); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!( + code, 0, + "{tag}: vex with a link out of the project:\n{stderr}" + ); + assert!( + attested.contains(¬_affected(leaf)) && attested.contains(¬_affected(peer_user)), + "{tag}: a link to a directory that links nothing must change nothing: \ + {attested:?}\n{stderr}" + ); + std::fs::create_dir_all(outside.join("node_modules")).unwrap(); + std::os::unix::fs::symlink(&old_leaf, outside.join("node_modules/leaf")).unwrap(); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must follow the link out of the project: {reachable:?}" + ); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!(code, 0, "{tag}: vex with a stale member outside:\n{stderr}"); + assert!( + !attested.contains(¬_affected(leaf)) + && attested.contains(¬_affected(peer_user)) + && stderr.contains("not_applied"), + "{tag}: a directory outside that links the upstream leaf must refuse its patch: \ + {attested:?}\n{stderr}" + ); + std::fs::remove_file(outside.join("node_modules/leaf")).unwrap(); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!(code, 0, "{tag}: vex once the stale link is gone:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without the stale link leaf is attested again: {attested:?}\n{stderr}" + ); + + // A `node_modules` there that is a link itself is one more link: into + // the upstream entry's `node_modules`, it loads the upstream leaf. + std::fs::remove_dir(outside.join("node_modules")).unwrap(); + std::os::unix::fs::symlink(old_leaf.parent().unwrap(), outside.join("node_modules")).unwrap(); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must read a linked node_modules: {reachable:?}" + ); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!( + code, 0, + "{tag}: vex with a linked node_modules outside:\n{stderr}" + ); + assert!( + !attested.contains(¬_affected(leaf)) && stderr.contains("not_applied"), + "{tag}: a node_modules outside that is a link into the upstream entry must refuse \ + the patch: {attested:?}\n{stderr}" + ); + std::fs::remove_file(outside.join("node_modules")).unwrap(); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!(code, 0, "{tag}: vex once that link is gone:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without that link leaf is attested again: {attested:?}\n{stderr}" + ); } #[cfg(unix)] diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index c2d25959a..fc1133567 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; use std::ffi::{OsStr, OsString}; use std::fs::FileType; use std::path::{Path, PathBuf}; @@ -843,7 +843,7 @@ fn pnpm_current_lockfile_sync( /// This tells which packages the install holds, by name and version, /// which is what the scan lists. Which of two entries holding the same /// name and version the install loads is another question, answered by -/// [`live_pnpm_store_entries_sync`]. +/// [`live_pnpm_store_entries_under_sync`]. fn orphaned_pnpm_store_entry_sync( store_path: &Path, entry_name: &str, @@ -891,8 +891,9 @@ fn orphaned_pnpm_store_entry_sync( /// /// The links read are all the links there are, not the ones pnpm should /// have written: every symbolic link below `tree`, whatever its directory -/// is named (see [`links_below_sync`]; `sweeps` holds the trees read so -/// far). An entry is live when a link that sits outside the store's +/// is named, and below what a link leads to outside it (see +/// [`links_reached_from_sync`]; `sweeps` holds what was read so far). An +/// entry is live when a link that sits outside the store's /// entries resolves into it, or a link inside a live entry does. So an /// entry left out is one that only other left-out entries link, and no /// path that starts outside them leads into it. Such chains are what a @@ -903,11 +904,16 @@ fn orphaned_pnpm_store_entry_sync( /// /// `tree` is the outer of the directory `scanned` and the workspace's /// root (the directory that holds the store's `node_modules`, or the one -/// a `modulesDir` setting points from). A link outside it is not read (one -/// in a `node_modules` above it, which pnpm does not write into this -/// store, or in another checkout), so every entry is kept wherever pnpm -/// may have written one there, or the links cannot all be read or -/// followed: +/// a `modulesDir` setting points from). Nothing above it is read for its +/// own sake: pnpm writes no link there into a store below it. +/// +/// A link that leads out of `tree` is followed (see +/// [`links_reached_from_sync`]): the directory behind it is read, and +/// each `node_modules` above that directory, up to the home directory. +/// Only so is a directory above `tree` read: when a link leads to it, or +/// to a directory below it. +/// +/// Every entry is kept wherever a link may have gone unread: /// /// - on Windows, where pnpm links directories with junctions; /// - when neither of the two directories holds the other (a @@ -936,15 +942,13 @@ fn orphaned_pnpm_store_entry_sync( /// level, the nearest directory above it whose `modulesDir` setting /// names that `node_modules` (pnpm 10.12 and later put the store /// there); with members found at neither, the root is not known; -/// - when a directory below `tree`, the type of one of its children or -/// the target of a link cannot be read, or `tree` holds more than -/// [`LINK_SWEEP_BUDGET`] directories and links; -/// - when a link resolves to a directory outside `tree` (a `link:` -/// dependency on another checkout, a former workspace member): what -/// the `node_modules` below it link is not read. Nor is what a file -/// outside `tree` loads, so a link to one counts the same way when a -/// directory above the file holds a `node_modules` (see -/// [`node_modules_above_sync`]); +/// - when a directory that is read, the type of one of its children or +/// the target of a link cannot be read, or what is read comes to more +/// than [`LINK_SWEEP_BUDGET`] directories and links; +/// - when a link leads to the home directory or a directory above it, or +/// to a file outside what is read that has a `node_modules` in a +/// directory above it: what that file loads by paths of its own is not +/// read; /// - when a link resolves to the store itself, into it by a path that is /// spelled another way than the store's (macOS reaches a volume under /// `/System/Volumes/Data` as well, and a file system that folds case @@ -952,9 +956,11 @@ fn orphaned_pnpm_store_entry_sync( /// could be an entry and is not one of those listed, so that its entry /// cannot be named; /// - when no link reaches any entry (`symlink=false`). -fn live_pnpm_store_entries_sync( +fn live_pnpm_store_entries_under_sync( store_path: &Path, scanned: &Path, + home: Option<&Path>, + budget: usize, sweeps: &mut HashMap>>>, ) -> Option> { use crate::constants::npm_family::PNPM_LOCK; @@ -976,12 +982,11 @@ fn live_pnpm_store_entries_sync( // directory, or holds it and may be read from there: like any other // file a project run looks up above the scanned directory, not past // the checkout, and not at the home directory. - let home = crate::utils::repo_root::home(); let readable = |dir: &Path| { dir.starts_with(&scanned) || (scanned.starts_with(dir) && (dir == scanned - || (!crate::utils::repo_root::at_or_above_home(dir, home.as_deref()) + || (!crate::utils::repo_root::at_or_above_home(dir, home) && upward_readable(ReadScope::Workspace, &scanned, dir)))) }; // The workspace's root, which the lockfiles name their importers @@ -1081,20 +1086,19 @@ fn live_pnpm_store_entries_sync( return None; }; let entries = pnpm_store_entry_names(list_dir_sync(&store))?; + // Every link below `tree` and below what its links lead to: the same + // for each store of the tree, so it is read once. let links = sweeps .entry(tree.to_path_buf()) - .or_insert_with(|| links_below_sync(tree).map(Arc::new)) + .or_insert_with(|| links_reached_from_sync(tree, home, budget).map(Arc::new)) .clone()?; - // A link whose target is not below `store` as the store is spelled. - // A directory outside `tree` behind it is not read. And wherever it - // leads, it may still lie in the store by another spelling of the - // store's path, so each directory above it is held against the store - // by identity, once (nothing is opened: a target may be a pipe). + // Wherever a link leads, it may lie in the store by another spelling + // of the store's path: each directory above its target is held + // against the store by identity, once (nothing is opened: a target + // may be a pipe). let store_id = file_id(&store)?; let mut elsewhere: HashSet<&Path> = HashSet::new(); - // The directories above the files that links out of `tree` lead to. - let mut above_files: HashSet<&Path> = HashSet::new(); for link in links.iter() { if link.target.starts_with(&store) { // The store itself: a path through the link names any entry. @@ -1103,15 +1107,6 @@ fn live_pnpm_store_entries_sync( } continue; } - // Out of `tree`: nothing behind a directory is read, and node - // loads a file from where it really is, with the packages of the - // `node_modules` above it. - if !link.target.starts_with(tree) - && (link.target.is_dir() - || node_modules_above_sync(&link.target, home.as_deref(), &mut above_files)?) - { - return None; - } for dir in link.target.ancestors() { if !elsewhere.insert(dir) { break; @@ -1173,6 +1168,150 @@ fn live_pnpm_store_entries_sync( (!live.is_empty()).then(|| live.into_iter().map(OsStr::to_os_string).collect()) } +/// Every link below `tree` and below what a link leads to outside it, +/// with the real path each resolves to; `None` when they cannot all be +/// read. +/// +/// Node loads what a link leads to from where it really is. So a +/// directory behind a link that leads out of what was read is read like +/// `tree`, and so is each `node_modules` in a directory above it, which +/// is where node looks up the packages of what it loads from there (a +/// member that left the workspace keeps the links pnpm wrote for it, and +/// Bazel's `bazel-*` links lead into an output tree with links of its +/// own). A `node_modules` that is a link itself is one more link, and +/// what it leads to is read the same way. A directory is read once: one +/// that holds directories already read is read around them. +/// +/// The home directory and what lies above it are not read (git's own +/// home rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): +/// a `node_modules` there is not looked at, and a link to a directory +/// there leaves the answer unknown. So does a link to a file outside +/// with a `node_modules` in a directory above it: what that file loads +/// by paths of its own is not read. The home directory is told by what +/// names it however its path is spelled ([`file_id`]), not by its path +/// alone. `budget` holds for all the directories and links read, and for +/// each `node_modules` looked for. +fn links_reached_from_sync( + tree: &Path, + home: Option<&Path>, + budget: usize, +) -> Option> { + use crate::utils::repo_root::at_or_above_home; + use std::ops::Bound; + + // The home directory and the ones above it, by path and by identity: + // a link may spell one another way (macOS reaches a volume under + // `/System/Volumes/Data` as well). + let home_ids: Vec<_> = home + .into_iter() + .flat_map(Path::ancestors) + .filter_map(file_id) + .collect(); + let not_read = |dir: &Path| { + at_or_above_home(dir, home) + || (!home_ids.is_empty() && file_id(dir).is_some_and(|id| home_ids.contains(&id))) + }; + + let mut links: Vec = Vec::new(); + // The directories read (in order, so that those below one are found + // without going through them all), and those still to read. + let mut roots: BTreeSet = BTreeSet::new(); + let mut queue: VecDeque = VecDeque::from([tree.to_path_buf()]); + let mut queued: HashSet = queue.iter().cloned().collect(); + // Directories whose `node_modules` was looked for. + let mut above: HashSet = HashSet::new(); + // The files that links lead to outside what was read at the time. + let mut files: Vec = Vec::new(); + let mut left = budget; + let inside = + |roots: &BTreeSet, path: &Path| path.ancestors().any(|dir| roots.contains(dir)); + while let Some(root) = queue.pop_front() { + if inside(&roots, &root) { + continue; + } + // Read around what was read already: the directories below + // `root` sort right after it. + let read: HashSet = roots + .range::((Bound::Excluded(root.as_path()), Bound::Unbounded)) + .take_while(|done| done.starts_with(&root)) + .cloned() + .collect(); + let sweep = sweep_tree_sync(&root, left, &read).ok()?; + left -= sweep.cost; + roots.insert(root); + // What the links of this directory lead to outside what is read. + let mut targets: VecDeque = + sweep.links.iter().map(|link| link.target.clone()).collect(); + links.extend(sweep.links); + while let Some(target) = targets.pop_front() { + if inside(&roots, &target) || queued.contains(&target) { + continue; + } + if !target.is_dir() { + files.push(target); + continue; + } + if not_read(&target) { + return None; + } + for dir in target.ancestors().skip(1) { + if above.contains(dir) || not_read(dir) { + break; + } + above.insert(dir.to_path_buf()); + left = left.checked_sub(1)?; + let nm = dir.join("node_modules"); + let real = match std::fs::canonicalize(&nm) { + Ok(real) if real.is_dir() => real, + Ok(_) => continue, + Err(e) if leads_nowhere(&e) => continue, + Err(_) => return None, + }; + if real == nm { + if queued.insert(real.clone()) { + queue.push_back(real); + } + } else { + // A link like any other: it may lead into a store, + // and what it leads to is read in its turn. + links.push(SweptLink { + path: nm, + target: real.clone(), + }); + targets.push_back(real); + } + } + if queued.insert(target.clone()) { + queue.push_back(target); + } + } + } + // A file outside everything that was read: what it loads by paths of + // its own is not read, so it must have no `node_modules` to load + // packages from. One inside what was read in the end is like any + // other file there. + let mut above_files: HashSet<&Path> = HashSet::new(); + for file in &files { + if inside(&roots, file) { + continue; + } + for dir in file.ancestors().skip(1) { + if above_files.contains(dir) || not_read(dir) { + break; + } + above_files.insert(dir); + left = left.checked_sub(1)?; + match std::fs::metadata(dir.join("node_modules")) { + Ok(meta) if meta.is_dir() => return None, + Ok(_) => {} + Err(e) if leads_nowhere(&e) => {} + Err(_) => return None, + } + } + } + Some(links) +} + /// Whether a link failed to resolve because it leads nowhere: its target /// is not there, a level of its path is a file, or it loops. Nothing is /// loaded through such a link, so it is left out; any other failure (a @@ -1192,34 +1331,6 @@ fn leads_nowhere(error: &std::io::Error) -> bool { } } -/// Whether a directory above the file `file` holds a `node_modules` dir, -/// which is where node looks up the packages of a file it loads from -/// there. pnpm links a workspace member's dependencies in the member's -/// `node_modules`, and a member that left the workspace keeps them. The -/// home directory and what lies above it are not looked at (git's own -/// home rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): -/// a stray `~/node_modules` says nothing of this project. `seen` holds -/// the directories already found to have none. `None` when one cannot be -/// told. -fn node_modules_above_sync<'a>( - file: &'a Path, - home: Option<&Path>, - seen: &mut HashSet<&'a Path>, -) -> Option { - for dir in file.ancestors().skip(1) { - if crate::utils::repo_root::at_or_above_home(dir, home) || !seen.insert(dir) { - break; - } - match std::fs::metadata(dir.join("node_modules")) { - Ok(meta) if meta.is_dir() => return Some(true), - Ok(_) => {} - Err(e) if leads_nowhere(&e) => {} - Err(_) => return None, - } - } - Some(false) -} - /// The device and inode of the file at `path`, which name one file however /// its path is spelled. Read with `stat`, so nothing is opened. `None` /// when it cannot be read, and on a platform without the pair. @@ -1264,7 +1375,7 @@ fn pnpm_store_entry_names(listing: Listing) -> Option> { Some(entries) } -/// A symbolic link [`links_below_sync`] found. +/// A symbolic link [`sweep_tree_sync`] found. struct SweptLink { /// Where the link is: a path below the swept tree, through real /// directories alone. @@ -1273,15 +1384,42 @@ struct SweptLink { target: PathBuf, } -/// How many directories and links [`links_below_sync`] reads before it -/// gives up: a tree this large is no single project (a home directory, a -/// disk), and the caller keeps every store entry instead of waiting on -/// it. A monorepo with a store of 5,200 entries holds about 98,000 -/// directories and 20,000 links. The links are kept, so this bounds the -/// memory as well. +/// How many directories and links [`links_reached_from_sync`] reads +/// before it gives up, in the project and in what its links lead to: more +/// than this is no single project (a home directory, a disk), and the +/// caller keeps every store entry instead of waiting on it. A monorepo +/// with a store of 5,200 entries holds about 98,000 directories and +/// 20,000 links; the output tree of a Bazel workspace of 1,200 packages +/// adds about 16,000 directories and 7,000 links. The links are kept, so +/// this bounds the memory as well. const LINK_SWEEP_BUDGET: usize = 500_000; +/// The links of one tree ([`sweep_tree_sync`]). +struct Sweep { + links: Vec, + /// The directories and links read for it. + cost: usize, +} + +/// Why a tree has no [`Sweep`]. +enum NoSweep { + /// A directory, the type of a child or the target of a link cannot be + /// read: so it is on every read. + Unreadable, + /// It holds more than the budget that was left. + OverBudget, +} + +/// [`sweep_tree_sync`]'s links, for a caller with one tree. +#[cfg(test)] +fn links_below_within_sync(tree: &Path, budget: usize) -> Option> { + sweep_tree_sync(tree, budget, &HashSet::new()) + .ok() + .map(|sweep| sweep.links) +} + /// [`links_below_within_sync`] under [`LINK_SWEEP_BUDGET`]. +#[cfg(test)] fn links_below_sync(tree: &Path) -> Option> { links_below_within_sync(tree, LINK_SWEEP_BUDGET) } @@ -1294,15 +1432,20 @@ fn links_below_sync(tree: &Path) -> Option> { /// or outside it. A link that leads nowhere (see [`leads_nowhere`]) is /// left out. /// -/// `None` when the answer would not be complete: a directory, the type of -/// a child or the target of a link cannot be read, or the tree holds more +/// The directories in `read` are not entered: they were read already. +/// +/// No answer when it would not be complete: a directory, the type of a +/// child or the target of a link cannot be read, or the tree holds more /// than `budget` directories (itself included) and links. Each level of /// the tree is read in parallel. -fn links_below_within_sync(tree: &Path, mut budget: usize) -> Option> { +fn sweep_tree_sync(tree: &Path, budget: usize, read: &HashSet) -> Result { let mut links = Vec::new(); let mut frontier = vec![tree.to_path_buf()]; + let mut left = budget; while !frontier.is_empty() { - budget = budget.checked_sub(frontier.len())?; + left = left + .checked_sub(frontier.len()) + .ok_or(NoSweep::OverBudget)?; let reads = par_map(frontier, |dir| { let mut links = Vec::new(); let mut dirs = Vec::new(); @@ -1319,7 +1462,10 @@ fn links_below_within_sync(tree: &Path, mut budget: usize) -> Option Option>>, - /// The trees whose links were read so far (see [`links_below_sync`]), - /// so that several pnpm stores below one scanned directory share one - /// read of it. + /// The links reached from each tree read so far (see + /// [`links_reached_from_sync`]), so that several pnpm stores below one + /// scanned directory share one read of it. sweeps: HashMap>>>, + /// The home directory, which is not read, nor is anything above it + /// (see [`links_reached_from_sync`]). + home: Option, } impl LiveStoreEntries { @@ -1648,6 +1800,7 @@ impl LiveStoreEntries { pub fn new(scanned: Option) -> Self { Self { scanned, + home: crate::utils::repo_root::home(), ..Self::default() } } @@ -1745,7 +1898,13 @@ impl LiveStoreEntries { None => { let live = if *layout == StoreLayout::Pnpm { self.scanned.as_deref().and_then(|scanned| { - live_pnpm_store_entries_sync(store, scanned, &mut self.sweeps) + live_pnpm_store_entries_under_sync( + store, + scanned, + self.home.as_deref(), + LINK_SWEEP_BUDGET, + &mut self.sweeps, + ) }) } else { let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); @@ -8529,7 +8688,12 @@ mod tests { .iter() .map(|copies| copies.iter().map(|path| (*path).clone()).collect()) .collect(); - let mut live = LiveStoreEntries::new(Some(scanned.to_path_buf())); + // Nothing at the temp dir or above it is read, whatever the + // machine keeps there: it stands in for the home directory. + let mut live = LiveStoreEntries { + home: Some(std::fs::canonicalize(std::env::temp_dir()).unwrap()), + ..LiveStoreEntries::new(Some(scanned.to_path_buf())) + }; live.retain_live_copies(lists.iter_mut()).await; (lists, live) } @@ -8946,9 +9110,50 @@ mod tests { abs_link(&store.join("minimist@1.2.2"), &store.join("alias")) }), ), - // Node loads a linked file from where it is: beside the - // `node_modules` of a member that left the workspace, which is - // not read, so every entry is kept while the link is there. + // Node loads what a link leads to from where it really is: a + // directory outside the project is read like the project, and + // so is each `node_modules` above it, or above a file outside. + ( + "a link to a directory outside the project that links the leftover", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link(&root.join(LEFTOVER), &shared.join("node_modules/minimist")); + abs_link(&shared, &root.join("tools/shared")) + }), + ), + ( + "a link to a directory below the node_modules of one outside the project", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link(&root.join(LEFTOVER), &shared.join("node_modules/@s/mini")); + std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); + abs_link(&shared.join("lib/deep"), &root.join("tools/deep")) + }), + ), + ( + "a directory outside the project whose node_modules is a link into the leftover", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + std::fs::create_dir_all(shared.join("lib")).unwrap(); + abs_link( + root.join(LEFTOVER).parent().unwrap(), + &shared.join("node_modules"), + ); + abs_link(&shared.join("lib"), &root.join("tools/lib")) + }), + ), + ( + "a chain of two directories outside the project", + Box::new(|root: &Path| { + let (x, y) = ( + root.parent().unwrap().join("x"), + root.parent().unwrap().join("y"), + ); + abs_link(&root.join(LEFTOVER), &y.join("vendor/minimist")); + abs_link(&y, &x.join("deps/y")); + abs_link(&x, &root.join("tools/x")) + }), + ), ( "a link to a file of a former member outside the project", Box::new(|root: &Path| { @@ -9205,36 +9410,59 @@ mod tests { }), ), ]; - // A link to a file outside the project, with no `node_modules` in - // a directory above the file: a file named so, and a link named - // so whose target is not there, are none. Only on a machine with - // no `node_modules` above the temp dir itself. + // What a link leads to outside the project is read, and links + // nothing of the store: a file with a `node_modules` above it, a + // file below a file and a dangling link of that name, a pipe, and + // directories that link each other and the project. let mut cases = cases; - let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); - let home = crate::utils::repo_root::home(); - let above_temp = - node_modules_above_sync(&temp.join("x/file"), home.as_deref(), &mut HashSet::new()); - if above_temp == Some(false) { - cases.push(( - "a link to a file outside the project", - Box::new(|root: &Path| { - let outside = root.ancestors().nth(2).unwrap().join("elsewhere"); - std::fs::create_dir_all(outside.join("deep")).unwrap(); - std::fs::write(outside.join("deep/file"), "").unwrap(); - abs_link(&outside.join("deep/file"), &root.join("tools/file")); - std::fs::write(outside.join("node_modules"), "").unwrap(); - rel_link("nowhere", &outside.join("deep/node_modules")); - }), - )); - cases.push(( - "a link to a named pipe outside the project", - Box::new(|root: &Path| { - let pipe = root.ancestors().nth(2).unwrap().join("pipe"); - mkfifo(&pipe); - abs_link(&pipe, &root.join("tools/ctl")); - }), - )); - } + cases.push(( + "a link to a file outside the project", + Box::new(|root: &Path| { + let outside = root.ancestors().nth(2).unwrap().join("elsewhere"); + std::fs::create_dir_all(outside.join("deep")).unwrap(); + std::fs::write(outside.join("deep/file"), "").unwrap(); + abs_link(&outside.join("deep/file"), &root.join("tools/file")); + std::fs::write(outside.join("node_modules"), "").unwrap(); + rel_link("nowhere", &outside.join("deep/node_modules")); + }), + )); + // A file that a link leads to is judged once every directory is + // read: this one lies in a directory another link leads to, which + // is found after it. + cases.push(( + "a link to a file in a directory outside the project that is read", + Box::new(|root: &Path| { + let out = root.parent().unwrap().join("out"); + write_pkg(&out.join("node_modules/real"), "real", "1.0.0"); + std::fs::create_dir_all(out.join("lib")).unwrap(); + std::fs::write(out.join("lib/gen.js"), "").unwrap(); + abs_link(&out.join("lib/gen.js"), &root.join("a-file.js")); + abs_link(&out, &root.join("z-dir")); + }), + )); + cases.push(( + "a link to a named pipe outside the project", + Box::new(|root: &Path| { + let pipe = root.ancestors().nth(2).unwrap().join("pipe"); + mkfifo(&pipe); + abs_link(&pipe, &root.join("tools/ctl")); + }), + )); + cases.push(( + "links to directories outside the project", + Box::new(|root: &Path| { + let (x, y) = ( + root.parent().unwrap().join("x"), + root.parent().unwrap().join("y"), + ); + write_pkg(&y.join("node_modules/real"), "real", "1.0.0"); + abs_link(&y, &x.join("deps/y")); + abs_link(&x, &y.join("deps/x")); + abs_link(root, &y.join("app")); + abs_link(&x, &root.join("node_modules/linked")); + abs_link(&x.join("deps"), &root.join("bazel-bin")); + }), + )); for (case, change) in cases { let (_tmp, _, root) = pnpm_project_dir(); let (_, stale, routed) = pnpm_hosted_route_leftover(&root); @@ -9257,51 +9485,179 @@ mod tests { assert!(made.success(), "mkfifo {path:?}"); } - /// #2353: node looks up the packages of a file in the `node_modules` - /// of each directory above it, up to the home directory, which is - /// not looked at, nor is anything above it. A file or a dangling link - /// named `node_modules` is none. + /// #2353: what a link leads to outside the project is read up to the + /// home directory. A `node_modules` there or above it is not looked + /// at, and a link to the home directory, or to one above it, leaves the + /// answer unknown. A `node_modules` that is a link itself is followed + /// like any other link. #[cfg(unix)] #[test] - fn test_node_modules_above_a_file_stops_at_the_home_directory() { + fn test_pnpm_store_links_outside_are_read_below_the_home_directory() { let tmp = tempfile::tempdir().unwrap(); let base = std::fs::canonicalize(tmp.path()).unwrap(); let home = base.join("home"); - let file = home.join("projects/shared/lib/gen.js"); - std::fs::create_dir_all(file.parent().unwrap()).unwrap(); - std::fs::write(&file, "").unwrap(); - let above = |home: &Path| node_modules_above_sync(&file, Some(home), &mut HashSet::new()); - - assert_eq!(above(&home), Some(false)); - std::fs::write(home.join("projects/shared/lib/node_modules"), "").unwrap(); - rel_link("nowhere", &home.join("projects/shared/node_modules")); - std::fs::create_dir_all(home.join("node_modules")).unwrap(); - std::fs::create_dir_all(base.join("node_modules")).unwrap(); - assert_eq!(above(&home), Some(false), "not in the home directory"); - assert_eq!( - above(&base.join("elsewhere")), - Some(true), - "with the home directory elsewhere" - ); - std::fs::create_dir_all(home.join("projects/node_modules")).unwrap(); - assert_eq!(above(&home), Some(true), "below the home directory"); + let root = home.join("projects/app"); + std::fs::create_dir_all(&root).unwrap(); + let (nm, _, _) = pnpm_hosted_route_leftover(&root); + let store = nm.join(".pnpm"); + let outside = home.join("projects/shared/lib"); + std::fs::create_dir_all(&outside).unwrap(); + abs_link(&outside, &root.join("tools/lib")); + let leftover = OsString::from("minimist@1.2.2"); + let live = |home: &Path| { + live_pnpm_store_entries_under_sync( + &store, + &root, + Some(home), + LINK_SWEEP_BUDGET, + &mut HashMap::new(), + ) + }; + let reaches_leftover = + |home: &Path| live(home).expect("the store is judged").contains(&leftover); - // A directory found to have none is not asked again. - let mut seen = HashSet::new(); - let other = home.join("other/a/file"); - assert_eq!( - node_modules_above_sync(&other, Some(&home), &mut seen), - Some(false) - ); - std::fs::create_dir_all(home.join("other/node_modules")).unwrap(); - assert_eq!( - node_modules_above_sync(&other, Some(&home), &mut seen), - Some(false) - ); - assert_eq!( - node_modules_above_sync(&other, Some(&home), &mut HashSet::new()), - Some(true) - ); + // In the home directory itself, and above it: not looked at. + abs_link(&root.join(LEFTOVER), &home.join("node_modules/minimist")); + abs_link(&root.join(LEFTOVER), &base.join("node_modules/minimist")); + assert!(!reaches_leftover(&home)); + assert!( + reaches_leftover(&base.join("elsewhere")), + "with another home" + ); + // Below the home directory: read. + let below = abs_link( + &root.join(LEFTOVER), + &home.join("projects/node_modules/minimist"), + ); + assert!(reaches_leftover(&home)); + std::fs::remove_file(below).unwrap(); + std::fs::remove_dir(home.join("projects/node_modules")).unwrap(); + assert!(!reaches_leftover(&home)); + + // A `node_modules` above the directory that is a link: what it + // leads to is read, and the `node_modules` above that as well. + let real = home.join("real/deps/nm"); + std::fs::create_dir_all(&real).unwrap(); + let linked = abs_link(&real, &home.join("projects/shared/node_modules")); + assert!(!reaches_leftover(&home)); + let behind = abs_link( + &root.join(LEFTOVER), + &home.join("real/node_modules/minimist"), + ); + assert!(reaches_leftover(&home)); + std::fs::remove_file(behind).unwrap(); + std::fs::remove_file(linked).unwrap(); + + // A link to the home directory, or to a directory above it. + for (name, target) in [("home", &home), ("above", &base)] { + let link = abs_link(target, &root.join("tools").join(name)); + assert!(live(&home).is_none(), "{name}"); + std::fs::remove_file(link).unwrap(); + } + assert!(!reaches_leftover(&home)); + + // The home directory by another spelling of its path is the home + // directory still: macOS reaches the data volume under + // `/System/Volumes/Data` as well, and `canonicalize` keeps that + // spelling. Only where the temp dir is on that volume. + #[cfg(target_os = "macos")] + { + let spelled = Path::new("/System/Volumes/Data").join(home.strip_prefix("/").unwrap()); + if spelled.is_dir() { + let link = abs_link(&spelled, &root.join("tools/home")); + assert!(live(&home).is_none(), "a link to the home directory"); + std::fs::remove_file(link).unwrap(); + // The `node_modules` in it still links the leftover. + let link = abs_link( + &spelled.join("projects/shared/lib"), + &root.join("tools/spelled"), + ); + assert!(!reaches_leftover(&home), "a directory below it"); + std::fs::remove_file(link).unwrap(); + } + } + + // The home rule holds above the scanned directory, not at it: a + // project whose root is the home directory is judged. + let at_home = home.join("app"); + std::fs::create_dir_all(&at_home).unwrap(); + std::fs::write( + at_home.join("pnpm-workspace.yaml"), + "packages:\n - packages/*\nmodulesDir: sub/node_modules\n", + ) + .unwrap(); + let nested = pnpm_install_into(&at_home.join("sub/node_modules"), &["packages/a"]); + pnpm_entry(&nested, "minimist@1.2.2", "minimist", "1.2.2"); + let nested_routed = pnpm_entry(&nested, ROUTED_ENTRY, "minimist", "1.2.2"); + write_pkg(&at_home.join("packages/a"), "a", "1.0.0"); + abs_link( + &nested_routed, + &at_home.join("packages/a/sub/node_modules/minimist"), + ); + let judged = live_pnpm_store_entries_under_sync( + &nested, + &at_home, + Some(&at_home), + LINK_SWEEP_BUDGET, + &mut HashMap::new(), + ) + .expect("a root at the home directory is judged"); + assert!(!judged.contains(&leftover) && judged.len() == 1); + } + + /// #2353: one budget holds for the project and what its links lead + /// to, and a directory is read once however many links lead into it + /// and in whatever order: the links of Bazel's `bazel-bin`, + /// `bazel-out` and `bazel-` lead to directories inside each + /// other, and a link may lead to a directory above the project. + #[cfg(unix)] + #[test] + fn test_pnpm_store_links_outside_are_read_once_within_one_budget() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("ws/app"); + std::fs::create_dir_all(&root).unwrap(); + let (nm, _, _) = pnpm_hosted_route_leftover(&root); + let store = nm.join(".pnpm"); + let out = base.join("out/execroot"); + std::fs::create_dir_all(out.join("bazel-out/cfg/bin/pkg")).unwrap(); + std::fs::create_dir_all(out.join("bazel-out/cfg/testlogs")).unwrap(); + let live = |budget: usize| { + live_pnpm_store_entries_under_sync( + &store, + &root, + Some(&base), + budget, + &mut HashMap::new(), + ) + }; + let cost = |tree: &Path| { + sweep_tree_sync(tree, LINK_SWEEP_BUDGET, &HashSet::new()) + .ok() + .unwrap() + .cost + }; + let project = cost(&root); + assert!(live(project).is_some() && live(project - 1).is_none()); + + // The innermost directory first, then two that hold it: each is + // read once, so the whole comes to the project (with its three + // new links) and the output tree. + abs_link(&out.join("bazel-out/cfg/bin"), &root.join("bazel-bin")); + abs_link(&out.join("bazel-out"), &root.join("bazel-out")); + abs_link(&out, &root.join("bazel-ws")); + // A `node_modules` is looked for in the four directories above + // them (`cfg`, `bazel-out`, `execroot`, `out`), once each. + let whole = project + 3 + cost(&out) + 4; + assert!(live(whole).is_some()); + assert!(live(whole - 1).is_none()); + + // A link back to the project, and one to the directory above it, + // read nothing twice either: only `ws` itself is new. + abs_link(&root, &out.join("app")); + abs_link(root.parent().unwrap(), &root.join("up")); + assert!(live(whole + 2 + 1).is_some()); + assert!(live(whole + 2).is_none()); } /// #2353: a pnpm store is judged for a package version only when its @@ -9831,12 +10187,6 @@ mod tests { write_lock(root, false, &pnpm_lock_of(&["packages/out"])); }), ), - ( - "a link to a directory outside the project", - Box::new(|root: &Path| { - abs_link(&beside(root), &root.join("node_modules/linked")); - }), - ), ( "a link to the store itself", Box::new(|root: &Path| { @@ -9844,10 +10194,10 @@ mod tests { }), ), ( - "a link to a file outside the project below an empty node_modules", + "a link to a file outside the project below a node_modules", Box::new(|root: &Path| { let shared = beside(root); - std::fs::create_dir_all(shared.join("node_modules")).unwrap(); + write_pkg(&shared.join("node_modules/real"), "real", "1.0.0"); std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); abs_link( @@ -9856,6 +10206,18 @@ mod tests { ); }), ), + ( + "a link to a directory outside the project that is a link to the store", + Box::new(|root: &Path| { + let shared = beside(root); + abs_link( + &root.join("node_modules/.pnpm"), + &shared.join("node_modules"), + ); + std::fs::create_dir_all(shared.join("lib")).unwrap(); + abs_link(&shared.join("lib"), &root.join("tools/lib")); + }), + ), ( "a link into the store that names none of its entries", Box::new(|root: &Path| { @@ -9932,26 +10294,26 @@ mod tests { assert_eq!(global, both); // Directories that cannot be read (not as root, which reads them - // all the same): one below the project, and one that the target - // of a link lies behind. That target is a file outside the - // project, which keeps every entry by itself on a machine with a - // `node_modules` above the temp dir. - let mut locked_dirs = vec![( - "an unreadable directory below the project", - "ws/app/dist/private", - None, - )]; - let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); - let home = crate::utils::repo_root::home(); - let above_temp = - node_modules_above_sync(&temp.join("x/file"), home.as_deref(), &mut HashSet::new()); - if above_temp == Some(false) { - locked_dirs.push(( + // all the same): one below the project, one that the target of a + // link lies behind, and one below a directory outside the project + // that a link leads to. + let locked_dirs = [ + ( + "an unreadable directory below the project", + "ws/app/dist/private", + None, + ), + ( "a link whose target lies behind an unreadable directory", "locked", Some(("locked/file", "ws/app/vendor/x")), - )); - } + ), + ( + "an unreadable directory below one outside the project", + "ws/out/private", + Some(("ws/out", "ws/app/tools/out")), + ), + ]; for (case, locked, link) in locked_dirs { let (_tmp, base, root) = pnpm_project_dir(); let (_, stale, routed) = pnpm_hosted_route_leftover(&root); @@ -9959,7 +10321,9 @@ mod tests { std::fs::create_dir_all(&locked).unwrap(); std::fs::write(locked.join("file"), "").unwrap(); if let Some((target, link)) = link { - std::fs::write(base.join(target), "").unwrap(); + if !base.join(target).is_dir() { + std::fs::write(base.join(target), "").unwrap(); + } abs_link(&base.join(target), &base.join(link)); } assert_eq!( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index b74e0ef43..e2f8365f7 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -893,9 +893,20 @@ For pnpm the rule is narrow: `node_modules` when the scan started inside it (a run from a workspace member reads the whole project). No directory is skipped by name, so a link in `vendor/`, `dist/`, a hidden directory, a package's own - `node_modules` or a directory that left the workspace counts. A link is - resolved, never followed. Nothing above that directory is read: pnpm - writes no link there into a store below it. + `node_modules` or a directory that left the workspace counts. Nothing + above that directory is read for its own sake: pnpm writes no link + there into a store below it. +- A link to a directory outside that directory is followed, since node + loads what is behind it from where it really is. The directory is read + the same way, and so is each `node_modules` in a directory above it (a + member that left the workspace keeps the links pnpm wrote for it). So + a `link:` dependency on another checkout and the `bazel-*` links into + Bazel's output tree are read. A directory is read once, however many + links lead into it. The home directory and what lies above it are not + read. A directory above the project is read only this way: when a + link leads to it, or its `node_modules` sits above what a link leads + to. Only links are read there, as in the project: a path out of such + a directory that a file spells out (`require('../util')`) is not. - An entry is judged when a link that sits outside the store's entries resolves into it (into its package, a file of it, or the entry itself), or when a link inside a judged entry does. The store's hoist directory, @@ -959,21 +970,19 @@ judged, as before: the store in `/.pnpm` and each member's links in `/`. Where the setting comes from somewhere the project's files do not show, the root is not known; -- when a directory below the one that is read, the type of one of its - children or the target of a link cannot be read, or it holds more than - 500,000 directories and links. A link that leads nowhere is left out: - its target is not there, it loops, or its path passes through a file; -- when a link resolves to a directory outside the one that is read: what - the `node_modules` of that directory links is not read. A `link:` - dependency on another checkout is such a link, and so is a - convenience link to a build tool's output elsewhere on the disk. A - link to a file outside counts the same way when a directory above the - file holds a `node_modules`: node loads the file from where it is, - with the packages it finds there, and a member that left the - workspace keeps the links pnpm wrote for it. The home directory and - what lies above it are not looked at for this, so a link to an - interpreter under the home directory (a virtualenv's `python`) and a - stray `~/node_modules` change nothing; +- when a directory that is read (below the scanned one, or behind a + link that leads out of it), the type of one of its children or the + target of a link cannot be read, or all that is read comes to more + than 500,000 directories and links. A link that leads nowhere is left + out: its target is not there, it loops, or its path passes through a + file; +- when a link leads to the home directory or to a directory above it; +- when a link leads to a file outside what is read and a directory above + that file holds a `node_modules`: what the file loads by paths of its + own is not read. The home directory and what lies above it are not + looked at for this, so a link to an interpreter under the home + directory (a virtualenv's `python`) and a stray `~/node_modules` + change nothing; - when a link resolves to the store itself, or into it by a path that names none of its entries: the store's own path spelled another way (macOS reaches a volume under `/System/Volumes/Data` as well, and a file system that diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index f95d17c0c..12398e43a 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -403,6 +403,17 @@ one. `pnpm prune` removes the entry at once (measured on 11.29.0 and 12.25.1, on the registry route), and a clean `node_modules` has no such entry. +A link that leads out of the scanned directory is followed. Measured in a +Bazel 9.3.2 workspace that links about 1,200 packages with aspect_rules_js +3.6.0: the `bazel-bin`, `bazel-out`, `bazel-testlogs` and `bazel-` +links lead into the output tree, which holds about 7,000 directories and +6,700 links, and from there into the contents of the external repositories +(about 9,200 directories). After a vendored scan and the `pnpm install` +over the existing `node_modules`, `vex` reads all of it and attests without +a warning; a link to the upstream entry in `bazel-bin`, in an external +repository's contents, or in a `node_modules` above the output tree's +workspace directory brings the warning back. + A workspace with a `modulesDir` of more than one level is judged from the workspace's root. Measured with `modulesDir: sub/node_modules`: pnpm 10.12.1, 10.34.9, 11.29.0 and 12.25.1 put the virtual store in