Unverified Commit 7830cfc3 authored by Benjamin Woodruff ‮'s avatar Benjamin Woodruff Committed by GitHub

Turbopack: Cache canonicalized paths without turbo-tasks, try to find the…

Turbopack: Cache canonicalized paths without turbo-tasks, try to find the longest cached prefix first (#99270)

When converting from an absolute system path to a filesystem-relative
path, we'd first try to lexically `strip_prefix`, but if that failed,
we'd fall back to trying to canonicalize the root path before stripping.

Because we don't know how many of the path segments refer to the root,
we have to canonicalize one path segment at a time.

With turbo-tasks, we have to probe the cache once per path segment,
starting from the shortest possible path segment.

This removes the `turbo_tasks::function` we were using to cache the
canonicalization calls, and instead stores caches in `BTreeMap`s. This
lets us efficiently look up the longest matching prefix in the cache,
which (in the happy path) should be a match for a filesystem root.

## Possible concerns

- ~We have duplicated canonicalization caches, one for the map, one for
each `DiskFileSystem`. Would a per-process (`OnceLock`) cache of
canonicalization calls make more sense?~ We now prefer lookups in the
map, which effectively solves this.
- A `PatriciaMap` would likely be more space efficient. `PatriciaMap` is
currently only used in `AliasMap`:
https://github.com/vercel/next.js/blob/ff6ac752af572467f35187e421dd7e558797b412/turbopack/crates/turbopack-core/src/resolve/alias_map.rs#L16

## Things I don't think are concerns

- `RwLock`: If we have a lot of writes, that means we're spending a lot
of time doing canonicalization, which would be a bigger problem than
locking.
parent e4801332
use std::{
collections::BTreeMap,
fs::canonicalize,
ops::{Bound, ControlFlow},
path::{Path, PathBuf},
sync::Arc,
};
use parking_lot::RwLock;
use smallvec::SmallVec;
use turbo_rcstr::RcStr;
use turbo_tasks::ResolvedVc;
use turbo_unix_path::{normalize_path, sys_to_unix};
use crate::{DiskFileSystem, FileSystemPath, retry::retry_blocking};
/// Cached canonicalization information about paths outside of the project root for the sake
/// of converting absolute paths into root-relative ones. These canonicalization operations are
/// potentially expensive, hence why we cache them.
///
/// These paths are unwatched (we only watch inside of roots), but we do not persist them, so if
/// there is stale data here, restarting the process will resolve the issue.
#[derive(Default)]
pub(crate) struct CanonicalizedPathWalkCache(RwLock<BTreeMap<PathBuf, CheckedPrefix>>);
enum CheckedPrefix {
/// The prefix is non-UTF-8, canonicalization failed or produced a non-UTF-8 path, or `visit`
/// rejected the canonical path.
Invalid,
/// The canonical path is outside the tracked roots; use it to check the next prefix.
Unmatched(Arc<PathBuf>),
/// The prefix reached a tracked root; append the untouched suffix in that filesystem.
Matched(ResolvedVc<DiskFileSystem>),
}
fn strip_longest_prefix<'a, 'p, T>(
prefixes: &'a BTreeMap<PathBuf, T>,
path: &'p Path,
) -> Option<(&'p Path, &'a T)> {
let mut upper = path;
loop {
let (prefix, value) = prefixes.upper_bound(Bound::Included(upper)).peek_prev()?;
if let Ok(rest) = path.strip_prefix(prefix) {
return Some((rest, value));
}
// Find the longest common ancestor before doing another lookup in the map
upper = prefix
.ancestors()
.find(|ancestor| path.starts_with(ancestor))?;
}
}
impl CanonicalizedPathWalkCache {
/// Performs untracked canonicalization on successive prefixes of `target_sys_path`, from the
/// system root toward the full path. Passes each canonical prefix to `visit`, until `visit`
/// finds a filesystem root.
///
/// This is different than canonicalizing the full path because we want to avoid untracked
/// canonicalization inside of the watched filesystem root. We only want to canonicalize and
/// cache paths leading up to the root. This can be useful when translating an absolute system
/// path to a filesystem-relative path if cheaper lexical prefix-stripping has failed.
///
/// This operation is cached, so it starts looking from the longest known canonicalized prefix.
///
/// The result of `visit` is cached for each prefix, so every call on this cache must use a
/// visitor with the same behavior for a given canonical path.
///
/// This is a helper for [`DiskFileSystem::resolve_path_ancestry_slow_path`].
pub(crate) async fn walk_canonicalized_ancestry(
&self,
target: &Path,
visit: impl Fn(&Path) -> ControlFlow<Option<ResolvedVc<DiskFileSystem>>>,
) -> Option<FileSystemPath> {
let unmatched_checkpoint = {
let cache = self.0.read();
match strip_longest_prefix(&cache, target) {
Some((_, CheckedPrefix::Invalid)) => return None,
Some((rest, CheckedPrefix::Matched(found))) => {
return path_from_root(*found, rest);
}
Some((rest, CheckedPrefix::Unmatched(canonical))) => {
Some((rest.ancestors().count() - 1, canonical.clone()))
}
None => None,
}
};
let ancestors: SmallVec<[&Path; 8]> = target.ancestors().collect();
let (remaining, mut canonical_parent) =
if let Some((remaining, canonical)) = unmatched_checkpoint {
(remaining, Some(canonical))
} else {
(ancestors.len() - 1, None)
};
for prefix in ancestors[..remaining].iter().rev() {
let canonical = if prefix.to_str().is_some() {
let path = if let Some(parent) = &canonical_parent {
let suffix = prefix
.strip_prefix(prefix.parent().expect("prefix has a parent"))
.expect("parent is an ancestor");
parent.join(suffix)
} else {
prefix.to_path_buf()
};
retry_blocking(|| canonicalize(&path))
.await
.ok()
.filter(|path| path.to_str().is_some())
.map(Arc::new)
} else {
None
};
let Some(canonical) = canonical else {
self.0
.write()
.insert(prefix.to_path_buf(), CheckedPrefix::Invalid);
return None;
};
let mut cache = self.0.write();
match visit(canonical.as_path()) {
ControlFlow::Continue(()) => {
// `visit` has found a partial match
cache.insert(
prefix.to_path_buf(),
CheckedPrefix::Unmatched(canonical.clone()),
);
canonical_parent = Some(canonical);
}
ControlFlow::Break(Some(found)) => {
// `visit` has found an exact match for a filesystem root
cache.insert(prefix.to_path_buf(), CheckedPrefix::Matched(found));
let rest = target.strip_prefix(prefix).expect("prefix is an ancestor");
return path_from_root(found, rest);
}
// `visit` has found a path it considers invalid (e.g. the canonicalization read
// gave us a path inside of the root)
ControlFlow::Break(None) => {
cache.insert(prefix.to_path_buf(), CheckedPrefix::Invalid);
return None;
}
}
}
None
}
}
fn path_from_root(root: ResolvedVc<DiskFileSystem>, rest: &Path) -> Option<FileSystemPath> {
let rest = rest.to_str()?;
// The walk preserves the original path until it finds a root: removing `link/..` earlier
// could skip a symlink and select a different root. Normalize only the suffix here, without
// reading paths inside the watched root.
let path = if rest.is_empty() {
RcStr::default()
} else {
RcStr::from(normalize_path(&sys_to_unix(rest))?)
};
Some(FileSystemPath::new_normalized_unchecked(
ResolvedVc::upcast(root),
path,
))
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use super::*;
#[tokio::test]
async fn walk_caches_invalid_prefix() {
let cache = CanonicalizedPathWalkCache::default();
let target = canonicalize(".").unwrap();
let calls = Cell::new(0);
let visit = |_: &Path| {
calls.set(calls.get() + 1);
ControlFlow::Break(None)
};
assert!(
cache
.walk_canonicalized_ancestry(&target, &visit)
.await
.is_none()
);
assert_eq!(calls.get(), 1);
assert!(
cache
.walk_canonicalized_ancestry(&target, &visit)
.await
.is_none()
);
assert_eq!(calls.get(), 1);
}
#[test]
fn strip_longest_prefix_matches_path_ancestors() {
#[cfg(unix)]
let paths = ["/a/b/c", "/a/../b", "/a//b", "/a/./b"];
#[cfg(windows)]
let paths = [r"C:\a\b", r"\\?\C:\a\b", r"\\server\share\a\b", r"C:/a/b"];
for path in paths {
let path = Path::new(path);
for prefix in path.ancestors() {
let prefixes = BTreeMap::from([(prefix.to_path_buf(), ())]);
let (rest, _) = strip_longest_prefix(&prefixes, path).unwrap();
assert_eq!(rest, path.strip_prefix(prefix).unwrap());
assert_eq!(
rest.ancestors().count() - 1,
path.ancestors()
.position(|ancestor| ancestor == prefix)
.unwrap()
);
}
}
let mut prefixes = BTreeMap::from([
(PathBuf::from("/a/b"), ()),
(PathBuf::from("/a/b/earlier-sibling"), ()),
(PathBuf::from("/a/bc/sibling"), ()),
]);
assert_eq!(
strip_longest_prefix(&prefixes, Path::new("/a/b/later-sibling")).map(|(rest, _)| rest),
Some(Path::new("later-sibling"))
);
assert!(strip_longest_prefix(&prefixes, Path::new("/a/bc/file")).is_none());
prefixes.insert(PathBuf::from("/a"), ());
prefixes.insert(PathBuf::from("/a/bc/earlier-sibling"), ());
assert_eq!(
strip_longest_prefix(&prefixes, Path::new("/a/bc/later-sibling")).map(|(rest, _)| rest),
Some(Path::new("bc/later-sibling"))
);
}
}
......@@ -166,8 +166,8 @@ pub(crate) enum FileComparison {
/// The target of a symbolic link, as read from a filesystem.
///
/// Every variant carries the `resolved` path the link points at, computed once by
/// [`crate::FileSystem::read_link`], which is also what guarantees the target stays inside the
/// filesystem root — a link whose target leaves the root is [`LinkContent::Invalid`] instead.
/// [`crate::FileSystem::read_link`]. A link whose target cannot be resolved into its filesystem
/// or another configured filesystem is [`LinkContent::Invalid`] instead.
#[derive(Clone, Debug, Hash, PartialEq, Eq, NonLocalValue, Encode, Decode)]
pub enum LinkTarget {
/// The link is an absolute path on disk.
......
......@@ -18,7 +18,6 @@ use bincode::{Decode, Encode};
#[cfg(windows)]
use omnipath::WinPathExt;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use tokio::{
runtime::Handle,
sync::{RwLock, RwLockReadGuard},
......@@ -37,8 +36,9 @@ use turbo_unix_path::{normalize_path, sys_to_unix, unix_to_sys};
use crate::windows::{is_link_junction_point, to_verbatim_with_case_folded_disk};
use crate::{
AnyhowWrapper, DiskFileSystemMap, File, FileComparison, FileContent, FileMeta, FileSystem,
FileSystemPath, LinkContent, LinkTarget, PersistedFileContent, RawDirectoryContent,
RawDirectoryEntry, WriteLinkContent, WriteLinkTargetType,
FileSystemPath, FileSystemPathOption, LinkContent, LinkTarget, PersistedFileContent,
RawDirectoryContent, RawDirectoryEntry, WriteLinkContent, WriteLinkTargetType,
canonicalized_path_cache::CanonicalizedPathWalkCache,
invalidation::Write,
invalidator_map::InvalidatorMap,
mutex_map::MutexMap,
......@@ -214,6 +214,10 @@ pub(crate) struct DiskFileSystemInner {
/// In the future, we should consider using `Path`/`PathBuf` here. Paths inside of the
/// `DiskFileSystem` must be valid unicode, but the root path doesn't need to be.
root: RcStr,
/// Results of checking prefixes for this root when the filesystem map does not contain it.
#[turbo_tasks(debug_ignore, unsafe_ignore)]
#[bincode(skip)]
root_prefixes: CanonicalizedPathWalkCache,
#[turbo_tasks(debug_ignore, unsafe_ignore)]
#[bincode(skip)]
mutex_map: MutexMap<Arc<PathBuf>>,
......@@ -448,55 +452,6 @@ impl DiskFileSystemInner {
}
}
#[turbo_tasks::value(transparent)]
struct OptionRcStr(Option<RcStr>);
/// Canonicalizes successive prefixes of `target_sys_path`, from the system root toward the full
/// path, and passes each canonical prefix together with the untouched suffix to `visit`.
///
/// Helper for [`DiskFileSystem::resolve_path_ancestry_slow_path`] and
/// [`DiskFileSystem::lookup_in_file_system_map`]
async fn visit_canonicalized_ancestry(
target_sys_path: &Path,
mut visit: impl FnMut(&Path, &Path) -> ControlFlow<Option<FileSystemPath>>,
) -> Result<Option<FileSystemPath>> {
// Canonicalization here is an untracked read of state the watcher can't see (outside the
// filesystem root), and is not portable across machines, hence it is `session_dependent`.
#[turbo_tasks::function(fs, session_dependent)]
async fn canonicalize_untracked(sys_path: RcStr) -> Vc<OptionRcStr> {
Vc::cell(
retry_blocking(|| canonicalize_to_rcstr(Path::new(&*sys_path)))
.await
.ok(),
)
}
// Reversed, `ancestors` yields every prefix of the target, from the system root (e.g. `/`
// or `\\?\C:\`) down to the full target path. `skip(1)` skips the bare system root: it has
// no symlink/short-name/casing ambiguity to resolve. Each prefix borrows from
// `target_sys_path`, so no paths are copied here.
let ancestors: SmallVec<[&Path; 8]> = target_sys_path.ancestors().collect();
for prefix in ancestors.into_iter().rev().skip(1) {
let Some(prefix_str) = prefix.to_str() else {
return Ok(None);
};
let Some(canonical) = canonicalize_untracked(RcStr::from(prefix_str))
.owned()
.await?
else {
return Ok(None);
};
let rest = target_sys_path
.strip_prefix(prefix)
.expect("`ancestors` yields prefixes of `target_sys_path`");
if let ControlFlow::Break(result) = visit(Path::new(canonical.as_str()), rest) {
return Ok(result);
}
}
Ok(None)
}
/// `DiskFileSystem` carries serializable fields (`name`, `root`,
/// `denied_paths`) inside `DiskFileSystemInner` alongside session-scoped
/// state (the `notify` watcher, invalidator maps, weak `TurboTasksApi`,
......@@ -520,7 +475,7 @@ impl DiskFileSystem {
#[cfg(debug_assertions)]
async fn ensure_path_is_realpath(&self, operation: &str, path: &Path) -> Result<()> {
if let Ok(realpath) = retry_blocking(|| fs_err::canonicalize(path))
if let Ok(realpath) = retry_blocking(|| std::fs::canonicalize(path))
.instrument(tracing::info_span!("realpath for filesystem read", name = ?path))
.concurrency_limited(&self.inner.read_semaphore)
.await
......@@ -648,6 +603,23 @@ impl DiskFileSystem {
sys_path: &Path,
relative_to: &FileSystemPath,
) -> Result<Option<FileSystemPath>> {
// The non-lexical fallback is an untracked read of state the watcher can't see (outside
// the filesystem root), and is not portable across machines, hence it is
// `session_dependent`. That also makes it okay to take a system path as a task input, as
// the result is never reused across sessions.
#[turbo_tasks::function(fs, session_dependent)]
async fn slow_non_lexical(
vc_self: ResolvedVc<DiskFileSystem>,
absolute_path: RcStr,
) -> Result<Vc<FileSystemPathOption>> {
let this = vc_self.await?;
let absolute_path = Path::new(&*absolute_path);
let path = this
.resolve_path_ancestry_slow_path(vc_self, absolute_path)
.await?;
Ok(Vc::cell(path))
}
debug_assert_eq!(
relative_to.fs,
ResolvedVc::upcast(vc_self),
......@@ -662,13 +634,11 @@ impl DiskFileSystem {
.to_sys_path_raw(relative_to)
.join(sys_path)
.normalize_lexically()?;
if let Some(path) = self
.resolve_path_ancestry_slow_path(vc_self, &absolute_path)
.await?
{
return Ok(Some(path));
}
self.lookup_in_file_system_map(vc_self, &absolute_path)
let Some(absolute_path) = absolute_path.to_str() else {
return Ok(None);
};
slow_non_lexical(*vc_self, RcStr::from(absolute_path))
.owned()
.await
}
......@@ -708,62 +678,89 @@ impl DiskFileSystem {
return sys_path;
}
/// Resolves an absolute path whose spelling differs from the [`DiskFileSystem`] root,
/// creating a [`FileSystemPath`] relative to that root.
/// Resolves an absolute path into this filesystem or another configured filesystem by
/// canonicalizing successive prefixes as needed. For performance reasons, the caller should
/// attempt to perform lexical prefix stripping against the current root before calling this
/// method.
///
/// Returns [`None`] if the path never reaches the filesystem root or an ancestor can't be
/// canonicalized.
/// Returns [`None`] if the path never reaches a filesystem root, an ancestor can't be
/// canonicalized, or the first matching prefix lands inside the root.
///
/// In some cases that absolute path may contain symlinks, different capitalization, or Windows
/// 8.3 short paths. Resolving this requires performing untracked IO outside of the filesystem
/// root, where we have no filesystem watcher configured. This is mostly okay as we assume the
/// [`DiskFileSystem`] root is stable.
///
/// To avoid performing untracked reads of files outside of the filesystem root, we iteratively
/// canonicalize each prefix of the given `target_sys_path` using a session-dependent task.
/// A prefix that first lands inside the root may have followed an internal symlink through
/// untracked IO. Only an exact root match is valid; leave the remaining path untouched.
async fn resolve_path_ancestry_slow_path(
&self,
vc_self: ResolvedVc<Self>,
target_sys_path: &Path,
) -> Result<Option<FileSystemPath>> {
let root_sys_path = self.inner.root_path();
visit_canonicalized_ancestry(target_sys_path, |canonical, rest| {
if canonical.starts_with(root_sys_path) {
// Reached the filesystem root. Keep the rest of the target as spelled and let
// `try_from_sys_path` strip the root prefix lexically.
ControlFlow::Break(self.try_from_sys_path(vc_self, &canonical.join(rest), None))
// Assumption: The map only changes across process restarts, and the map is updated upon
// process start (e.g. when processing the Turbopack config) before any root tasks depending
// on this (e.g. building bundled outputs) are alive, so in-memory caches that depend on
// this value are okay.
let map = self.inner.map.connect().await?;
// The fs map could be empty (i.e. this DiskFileSystem doesn't use additional roots), or
// (less likely) it may not contain the current root (e.g. paths are allowed to navigate out
// of this root, but not back in).
//
// For these cases, try to match against the current root before looking at the map. Use the
// cache stored on the `DiskFileSystem` instead of the one on the `DiskFileSystemMap`.
if !map.contains(self.inner.root_path(), vc_self) {
if let Some(found) = self
.inner
.root_prefixes
.walk_canonicalized_ancestry(target_sys_path, |canonical| {
let root_path = self.inner.root_path();
if canonical == root_path {
ControlFlow::Break(Some(vc_self))
} else if canonical.starts_with(root_path) {
// Unlikely: We unexpectedly ended up deep *inside* of `root_path`, which
// means we did some untracked reads inside of the filesystem root, just
// bail out and treat this path as invalid.
ControlFlow::Break(None)
} else {
ControlFlow::Continue(())
}
})
.await
{
return Ok(Some(found));
}
/// Looks up a system path in any configured filesystem other than the current filesystem.
///
/// Like [`Self::resolve_path_ancestry_slow_path`], the fallback handles paths whose
/// spelling differs from a configured root.
async fn lookup_in_file_system_map(
&self,
vc_self: ResolvedVc<Self>,
target_sys_path: &Path,
) -> Result<Option<FileSystemPath>> {
let map = self.inner.map.connect().await?;
if !map.has_file_system_other_than(vc_self) {
if map.is_empty() {
// don't bother canonicalizing paths again and checking the map if there's no map
return Ok(None);
}
if let Some(path) = map.lookup(target_sys_path) {
return Ok(Some(path));
}
visit_canonicalized_ancestry(target_sys_path, |canonical, rest| {
if let Some(path) = map.lookup(&canonical.join(rest)) {
ControlFlow::Break(Some(path))
// Less slow path: Lexically compare against the map. The caller of this function should
// already tried to lexically compare with the current root, but not the full map.
if let Some(found) = target_sys_path
.normalize_lexically()
.ok()
.and_then(|path| map.lookup_fs_path(&path))
{
return Ok(Some(found));
}
// Slow path: Try to canonicalize and compare each ancestor against the map.
Ok(map
.canonicalized_paths
.walk_canonicalized_ancestry(target_sys_path, |canonical| {
let Some(found) = map.lookup_sys_path_suffix(canonical) else {
return ControlFlow::Continue(());
};
if found.remaining.as_os_str().is_empty() {
ControlFlow::Break(Some(found.fs))
} else {
ControlFlow::Continue(())
ControlFlow::Break(None)
}
})
.await
.await)
}
}
......@@ -851,6 +848,7 @@ impl DiskFileSystem {
inner: Arc::new(DiskFileSystemInner {
name,
root,
root_prefixes: Default::default(),
mutex_map: Default::default(),
invalidation_lock: Default::default(),
invalidator_map: InvalidatorMap::new(),
......@@ -1056,11 +1054,6 @@ impl FileSystem for DiskFileSystem {
.resolve_path_ancestry_slow_path(self, &target_sys_path)
.await?;
}
if target_fs_path.is_none() {
target_fs_path = this
.lookup_in_file_system_map(self, &target_sys_path)
.await?;
}
let Some(target_fs_path) = target_fs_path else {
// The target leaves the filesystem root (or is a dangling link whose parent
......@@ -1123,11 +1116,8 @@ impl FileSystem for DiskFileSystem {
};
let raw = RcStr::from(sys_to_unix(target_str));
// Require the target to stay within the filesystem root at every step, not just at
// the end. A target like `../../<root dir name>/foo` steps out of the root and back
// in; resolving that needs the names of the root's own ancestors, which a
// root-relative `FileSystemPath` doesn't carry. Rejecting it here is what lets
// `LinkTarget` carry a resolved path at all.
// If the relative target steps above the root, resolve its absolute system path
// against this filesystem and the other configured roots.
let resolved = if let Some(resolved) = fs_path.parent().try_join(&raw) {
resolved
} else {
......@@ -1137,7 +1127,7 @@ impl FileSystem for DiskFileSystem {
.normalize_lexically()
.ok();
let Some(resolved) = (match absolute_target {
Some(path) => this.lookup_in_file_system_map(self, &path).await?,
Some(path) => this.resolve_path_ancestry_slow_path(self, &path).await?,
None => None,
}) else {
return Ok(LinkContent::Invalid {
......@@ -2247,10 +2237,8 @@ mod tests {
tt.stop_and_wait().await;
}
/// A relative target must stay inside the filesystem root at every step, not just at the
/// end. Both of these step above the root; one comes back into it and one doesn't, but
/// neither resolves into a configured filesystem, so `read_link` rejects both and every
/// [`LinkContent::Link`] stays resolvable by construction.
/// A relative target can step above the root and return to it, but a target that ends
/// outside all configured roots is invalid.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_read_escaping_relative_symlink() {
......@@ -2289,15 +2277,16 @@ mod tests {
fs: ResolvedVc<DiskFileSystem>,
root_path: FileSystemPath,
) -> anyhow::Result<()> {
// sub/link-reentrant -> ../../<root dir name>/root.txt, which steps above the root
// and back down into it. It cannot be resolved through the configured filesystem
// map because no filesystem owns the path while it is outside the root.
let reentrant = fs.read_link(root_path.join("sub/link-reentrant")?).await?;
assert!(matches!(
&*reentrant,
LinkContent::Invalid { reason }
if reason == "the symlink target leaves the configured filesystem roots"
));
assert_eq!(
*reentrant,
LinkContent::Link {
target: LinkTarget::Relative {
raw: rcstr!("../../the-root/root.txt"),
resolved: root_path.join("root.txt")?,
},
}
);
// sub/link-sideways -> ../../sibling/root.txt, which steps above the root and down
// into a sibling, so it genuinely ends outside.
......
......@@ -8,14 +8,27 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{OperationVc, ResolvedVc, Vc};
use turbo_unix_path::sys_to_unix;
use crate::{DiskFileSystem, FileSystemPath};
use crate::{DiskFileSystem, FileSystemPath, canonicalized_path_cache::CanonicalizedPathWalkCache};
/// An ordered set of canonical system roots and their owning filesystems.
///
/// The roots must not overlap: no root may be an ancestor of another root. [`Self::lookup`]
/// relies on this invariant when selecting the nearest preceding root in path order.
#[turbo_tasks::value(shared)]
pub struct DiskFileSystemMap(FrozenMap<PathBuf, ResolvedVc<DiskFileSystem>>);
#[turbo_tasks::value(shared, eq = "manual")]
pub struct DiskFileSystemMap {
roots: FrozenMap<PathBuf, ResolvedVc<DiskFileSystem>>,
#[turbo_tasks(debug_ignore, unsafe_ignore)]
#[bincode(skip)]
pub(crate) canonicalized_paths: CanonicalizedPathWalkCache,
}
impl PartialEq for DiskFileSystemMap {
fn eq(&self, other: &Self) -> bool {
self.roots == other.roots
}
}
impl Eq for DiskFileSystemMap {}
impl FromIterator<(PathBuf, ResolvedVc<DiskFileSystem>)> for DiskFileSystemMap {
fn from_iter<T: IntoIterator<Item = (PathBuf, ResolvedVc<DiskFileSystem>)>>(iter: T) -> Self {
......@@ -29,27 +42,53 @@ impl FromIterator<(PathBuf, ResolvedVc<DiskFileSystem>)> for DiskFileSystemMap {
root.display()
);
}
DiskFileSystemMap(filesystems)
DiskFileSystemMap {
roots: filesystems,
canonicalized_paths: Default::default(),
}
}
}
impl DiskFileSystemMap {
pub fn has_file_system_other_than(&self, current: ResolvedVc<DiskFileSystem>) -> bool {
self.0.values().any(|file_system| *file_system != current)
pub(crate) fn contains(&self, root: &Path, current: ResolvedVc<DiskFileSystem>) -> bool {
self.roots.get(root).is_some_and(|fs| *fs == current)
}
pub fn len(&self) -> usize {
self.roots.len()
}
pub fn is_empty(&self) -> bool {
self.roots.is_empty()
}
/// Finds the containing root; the suffix is empty only when `path` is that root.
pub(crate) fn lookup_sys_path_suffix<'a>(
&self,
path: &'a Path,
) -> Option<LookupSysPathSuffix<'a>> {
let (root, fs) = self
.roots
.range::<Path, _>((Bound::Unbounded, Bound::Included(path)))
.next_back()?;
Some(LookupSysPathSuffix {
fs: *fs,
remaining: path.strip_prefix(root).ok()?,
})
}
/// Converts an absolute system path into a path owned by one of the installed filesystems.
///
/// Returns `None` if the file path does not exist inside any other root, or if the relative
/// path would not be valid unicode.
pub fn lookup(&self, path: &Path) -> Option<FileSystemPath> {
let (root, fs) = self
.0
.range::<Path, _>((Bound::Unbounded, Bound::Included(path)))
.next_back()?;
let relative = path.strip_prefix(root).ok()?.to_str()?;
pub fn lookup_fs_path(&self, path: &Path) -> Option<FileSystemPath> {
let LookupSysPathSuffix {
fs,
remaining: relative,
} = self.lookup_sys_path_suffix(path)?;
let relative = relative.to_str()?;
Some(FileSystemPath::new_normalized_unchecked(
ResolvedVc::upcast(*fs),
ResolvedVc::upcast(fs),
RcStr::from(sys_to_unix(relative)),
))
}
......@@ -59,12 +98,21 @@ impl DiskFileSystemMap {
pub fn empty() -> OperationVc<DiskFileSystemMap> {
#[turbo_tasks::function(operation)]
pub fn operation() -> Vc<DiskFileSystemMap> {
DiskFileSystemMap(FrozenMap::new()).cell()
DiskFileSystemMap {
roots: FrozenMap::new(),
canonicalized_paths: Default::default(),
}
.cell()
}
operation()
}
}
pub struct LookupSysPathSuffix<'a> {
pub fs: ResolvedVc<DiskFileSystem>,
pub remaining: &'a Path,
}
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
......@@ -80,12 +128,18 @@ mod tests {
.to_resolved()
.await?;
let map: DiskFileSystemMap = [(PathBuf::from("/tmp/root"), fs)].into_iter().collect();
assert!(!map.has_file_system_other_than(fs));
assert_eq!(map.len(), 1);
assert!(map.contains(Path::new("/tmp/root"), fs));
assert_eq!(
map.lookup(Path::new("/tmp/root/file")).unwrap().path,
map.lookup_fs_path(Path::new("/tmp/root/file"))
.unwrap()
.path,
"file"
);
assert!(map.lookup(Path::new("/tmp/root-other/file")).is_none());
assert!(
map.lookup_fs_path(Path::new("/tmp/root-other/file"))
.is_none()
);
Ok(())
}
......
......@@ -15,6 +15,7 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
#![allow(clippy::mutable_key_type)]
mod canonicalized_path_cache;
mod content;
mod disk;
pub mod embed;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment