Unverified Commit 143d9ca1 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

feat(turbopack): change DiskFileSystem root to Vc<RcStr> for portable cache (#92603)

### What?

Changes the `root` parameter of `DiskFileSystem::new`,
`DiskFileSystem::new_with_denied_paths`, and the internal
`DiskFileSystem::new_internal` from `RcStr` to `Vc<RcStr>`.

### Why?

Part of the effort to make the Turbopack persistent cache portable when
the absolute path of the project directory changes. By accepting the
root as a `Vc<RcStr>` instead of a plain `RcStr`, the path is tracked as
a turbo-tasks value. This allows the cache to remain valid even when the
project root moves (e.g. on a different machine, a different CI working
directory, or a relocated checkout), since the value can be substituted
independently without invalidating unrelated cached computations.

### How?

- `new_internal` is now an `async fn` that awaits the `Vc<RcStr>` to
extract the underlying `RcStr` for constructing `DiskFileSystemInner`.
It returns `Result<Vc<Self>>` accordingly.
- `new` and `new_with_denied_paths` (the public constructors, which are
not `#[turbo_tasks::function]` themselves) are updated to accept
`Vc<RcStr>` and forward it to `new_internal`.
- All 23 call sites across the codebase are updated to wrap their root
string with `Vc::cell(...)` before passing it.

Verified with `cargo clippy --all-targets` (clean), `cargo test -p
turbo-tasks-backend` (all pass), and `cargo test -p turbopack-tests`
(all 89 pass).

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 74cdcde8
......@@ -808,7 +808,7 @@ impl ProjectContainer {
let env_map: Vc<EnvMap>;
let next_config;
let define_env;
let root_path;
let root_path_str: RcStr;
let project_path;
let watch;
let dev;
......@@ -837,7 +837,7 @@ impl ProjectContainer {
}
.cell();
next_config = NextConfig::from_string(Vc::cell(options.next_config.clone()));
root_path = options.root_path.clone();
root_path_str = options.root_path.clone();
project_path = options.project_path.clone();
watch = options.watch;
dev = options.dev;
......@@ -855,6 +855,7 @@ impl ProjectContainer {
hash_salt = options.hash_salt.clone();
}
let root_path = ResolvedVc::cell(root_path_str);
let dist_dir = next_config.dist_dir().owned().await?;
let dist_dir_root = next_config.dist_dir_root().owned().await?;
Ok(Project {
......@@ -922,7 +923,7 @@ pub struct Project {
/// An absolute root path (Windows or Unix path) from which all files must be nested under.
/// Trying to access a file outside this root will fail, so think of this as a chroot.
/// E.g. `/home/user/projects/my-repo`.
root_path: RcStr,
root_path: ResolvedVc<RcStr>,
/// A path which contains the app/pages directories, relative to [`Project::root_path`], always
/// a Unix path.
......@@ -1084,7 +1085,7 @@ impl Project {
Ok(DiskFileSystem::new_with_denied_paths(
rcstr!(PROJECT_FILESYSTEM_NAME),
self.root_path.clone(),
*self.root_path,
vec![denied_path],
))
}
......@@ -1097,15 +1098,16 @@ impl Project {
#[turbo_tasks::function]
pub fn output_fs(&self) -> Vc<DiskFileSystem> {
DiskFileSystem::new(rcstr!("output"), self.root_path.clone())
DiskFileSystem::new(rcstr!("output"), *self.root_path)
}
#[turbo_tasks::function]
pub fn dist_dir_absolute(&self) -> Result<Vc<RcStr>> {
pub async fn dist_dir_absolute(&self) -> Result<Vc<RcStr>> {
let root_path = self.root_path.await?;
Ok(Vc::cell(
format!(
"{}{}{}",
self.root_path,
root_path,
std::path::MAIN_SEPARATOR,
unix_to_sys(
&join_path(&self.project_path, &self.dist_dir)
......
......@@ -729,12 +729,14 @@ async fn get_mock_stylesheet(
let response_path = Path::new(&mocked_responses_path);
let mock_fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(
rcstr!("mock"),
response_path
.parent()
.context("Must be valid path")?
.to_str()
.context("Must exist")?
.into(),
Vc::cell(
response_path
.parent()
.context("Must be valid path")?
.to_str()
.context("Must exist")?
.into(),
),
));
let ExecutionContext {
......
......@@ -180,7 +180,7 @@ async fn invalidation_does_not_invalidate() {
}
fn get_issue_context() -> Vc<FileSystemPath> {
DiskFileSystem::new(rcstr!("root"), rcstr!("/")).root()
DiskFileSystem::new(rcstr!("root"), Vc::cell(rcstr!("/"))).root()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
......
......@@ -27,8 +27,8 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| {
Box::pin(async {
let root = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new(rcstr!("project"), root);
let root = RcStr::from(current_dir().unwrap().to_str().unwrap());
let disk_fs = DiskFileSystem::new(rcstr!("project"), Vc::cell(root));
disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast
......
......@@ -28,8 +28,8 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| {
Box::pin(async {
let root = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new(rcstr!("project"), root);
let root = RcStr::from(current_dir().unwrap().to_str().unwrap());
let disk_fs = DiskFileSystem::new(rcstr!("project"), Vc::cell(root));
disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast
......
......@@ -12,7 +12,7 @@ pub async fn directory_from_relative_path(
name: RcStr,
path: RcStr,
) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new(name, path);
let disk_fs = DiskFileSystem::new(name, Vc::cell(path));
disk_fs.await?.start_watching(None).await?;
Ok(Vc::upcast(disk_fs))
......
......@@ -21,7 +21,7 @@ pub async fn content_from_relative_path(
let disk_fs = DiskFileSystem::new(
root_path.to_string_lossy().into(),
root_path.to_string_lossy().into(),
Vc::cell(root_path.to_string_lossy().into()),
);
disk_fs.await?.start_watching(None).await?;
......
......@@ -634,7 +634,7 @@ impl DiskFileSystem {
/// * `name` - Name of the filesystem.
/// * `root` - Path to the given filesystem's root. Should be
/// [canonicalized][std::fs::canonicalize].
pub fn new(name: RcStr, root: RcStr) -> Vc<Self> {
pub fn new(name: RcStr, root: Vc<RcStr>) -> Vc<Self> {
Self::new_internal(name, root, Vec::new())
}
......@@ -646,7 +646,11 @@ impl DiskFileSystem {
/// [canonicalized][std::fs::canonicalize].
/// * `denied_paths` - Paths within this filesystem that are not allowed to be accessed or
/// navigated into. These must be normalized, non-empty and relative to the fs root.
pub fn new_with_denied_paths(name: RcStr, root: RcStr, denied_paths: Vec<RcStr>) -> Vc<Self> {
pub fn new_with_denied_paths(
name: RcStr,
root: Vc<RcStr>,
denied_paths: Vec<RcStr>,
) -> Vc<Self> {
for denied_path in &denied_paths {
debug_assert!(!denied_path.is_empty(), "denied_path must not be empty");
debug_assert!(
......@@ -661,7 +665,12 @@ impl DiskFileSystem {
#[turbo_tasks::value_impl]
impl DiskFileSystem {
#[turbo_tasks::function]
fn new_internal(name: RcStr, root: RcStr, denied_paths: Vec<RcStr>) -> Vc<Self> {
async fn new_internal(
name: RcStr,
root: Vc<RcStr>,
denied_paths: Vec<RcStr>,
) -> Result<Vc<Self>> {
let root = root.owned().await?;
let instance = DiskFileSystem {
inner: Arc::new(DiskFileSystemInner {
name,
......@@ -680,7 +689,7 @@ impl DiskFileSystem {
}),
};
Self::cell(instance)
Ok(Self::cell(instance))
}
}
......@@ -3038,9 +3047,12 @@ mod tests {
#[turbo_tasks::function(operation)]
async fn assert_try_from_sys_path_operation(sys_root: RcStr) -> anyhow::Result<()> {
let sys_root = Path::new(sys_root.as_str());
let fs_vc = DiskFileSystem::new(rcstr!("temp"), RcStr::from(sys_root.to_str().unwrap()))
.to_resolved()
.await?;
let fs_vc = DiskFileSystem::new(
rcstr!("temp"),
Vc::cell(RcStr::from(sys_root.to_str().unwrap())),
)
.to_resolved()
.await?;
let fs = fs_vc.await?;
let fs_root_path = fs_vc.root().await?;
......@@ -3247,7 +3259,7 @@ mod tests {
#[turbo_tasks::function(operation)]
fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> {
DiskFileSystem::new(rcstr!("test"), fs_root)
DiskFileSystem::new(rcstr!("test"), Vc::cell(fs_root))
}
fn disk_file_system_root(fs: ResolvedVc<DiskFileSystem>) -> FileSystemPath {
......@@ -3424,8 +3436,11 @@ mod tests {
async fn test_denied_path_read() {
#[turbo_tasks::function(operation)]
async fn test_operation(root: RcStr, denied_path: RcStr) -> anyhow::Result<()> {
let fs =
DiskFileSystem::new_with_denied_paths(rcstr!("test"), root, vec![denied_path]);
let fs = DiskFileSystem::new_with_denied_paths(
rcstr!("test"),
Vc::cell(root),
vec![denied_path],
);
let root_path = fs.root().await?;
// Test 1: Reading allowed file should work
......@@ -3484,8 +3499,11 @@ mod tests {
async fn test_denied_path_read_dir() {
#[turbo_tasks::function(operation)]
async fn test_operation(root: RcStr, denied_path: RcStr) -> anyhow::Result<()> {
let fs =
DiskFileSystem::new_with_denied_paths(rcstr!("test"), root, vec![denied_path]);
let fs = DiskFileSystem::new_with_denied_paths(
rcstr!("test"),
Vc::cell(root),
vec![denied_path],
);
let root_path = fs.root().await?;
// Test: read_dir on root should not include denied_dir
......@@ -3543,8 +3561,11 @@ mod tests {
async fn test_denied_path_read_glob() {
#[turbo_tasks::function(operation)]
async fn test_operation(root: RcStr, denied_path: RcStr) -> anyhow::Result<()> {
let fs =
DiskFileSystem::new_with_denied_paths(rcstr!("test"), root, vec![denied_path]);
let fs = DiskFileSystem::new_with_denied_paths(
rcstr!("test"),
Vc::cell(root),
vec![denied_path],
);
let root_path = fs.root().await?;
// Test: read_glob with ** should not reveal denied files
......@@ -3626,8 +3647,11 @@ mod tests {
file_path: RcStr,
contents: RcStr,
) -> anyhow::Result<Vc<Effects>> {
let fs =
DiskFileSystem::new_with_denied_paths(rcstr!("test"), root, vec![denied_path]);
let fs = DiskFileSystem::new_with_denied_paths(
rcstr!("test"),
Vc::cell(root),
vec![denied_path],
);
let root_path = fs.root().await?;
let allowed_file = root_path.join(&file_path)?;
let write_op = write_file_operation(allowed_file, contents);
......@@ -3642,8 +3666,11 @@ mod tests {
denied_file: RcStr,
nested_denied_file: RcStr,
) -> anyhow::Result<()> {
let fs =
DiskFileSystem::new_with_denied_paths(rcstr!("test"), root, vec![denied_path]);
let fs = DiskFileSystem::new_with_denied_paths(
rcstr!("test"),
Vc::cell(root),
vec![denied_path],
);
let root_path = fs.root().await?;
let path = root_path.join(&denied_file)?;
......
......@@ -265,7 +265,7 @@ pub mod tests {
#[turbo_tasks::function(operation)]
async fn assert_read_glob_basic_operation(path: RcStr) -> anyhow::Result<()> {
let fs = DiskFileSystem::new(rcstr!("temp"), path);
let fs = DiskFileSystem::new(rcstr!("temp"), Vc::cell(path));
let root = fs.root().await?;
let read_dir = root
.read_glob(Glob::new(rcstr!("**"), GlobOptions::default()))
......@@ -308,7 +308,7 @@ pub mod tests {
#[turbo_tasks::function(operation)]
async fn assert_read_glob_symlinks_operation(path: RcStr) -> anyhow::Result<()> {
let fs = DiskFileSystem::new(rcstr!("temp"), path);
let fs = DiskFileSystem::new(rcstr!("temp"), Vc::cell(path));
let root = fs.root().await?;
// Symlinked files
let read_dir = root
......@@ -359,7 +359,8 @@ pub mod tests {
#[turbo_tasks::function(operation)]
async fn assert_dead_symlink_read_glob_operation(path: RcStr) -> anyhow::Result<()> {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let fs =
Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), Vc::cell(path)));
let root = fs.root().owned().await?;
let read_dir = root
.read_glob(Glob::new(rcstr!("sub/*.js"), GlobOptions::default()))
......@@ -481,7 +482,8 @@ pub mod tests {
#[turbo_tasks::function(operation)]
fn disk_file_system_root_operation(path: RcStr) -> Vc<FileSystemPath> {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let fs =
Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), Vc::cell(path)));
fs.root()
}
......
......@@ -297,7 +297,7 @@ pub async fn run(args: FsWatcher) -> anyhow::Result<()> {
#[turbo_tasks::function(operation)]
fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> {
DiskFileSystem::new(rcstr!("project"), fs_root)
DiskFileSystem::new(rcstr!("project"), Vc::cell(fs_root))
}
#[turbo_tasks::function(operation)]
......
......@@ -168,7 +168,7 @@ pub async fn run(args: SymlinkStress) -> anyhow::Result<()> {
#[turbo_tasks::function(operation)]
fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> {
DiskFileSystem::new(rcstr!("project"), fs_root)
DiskFileSystem::new(rcstr!("project"), Vc::cell(fs_root))
}
#[turbo_tasks::function(operation)]
......
......@@ -67,7 +67,7 @@ pub async fn project_fs(
) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new_with_denied_paths(
rcstr!("project"),
project_dir,
Vc::cell(project_dir),
vec![denied_root_path],
);
if watch {
......@@ -78,6 +78,6 @@ pub async fn project_fs(
#[turbo_tasks::function]
pub fn output_fs(project_dir: RcStr) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new(rcstr!("output"), project_dir);
let disk_fs = DiskFileSystem::new(rcstr!("output"), Vc::cell(project_dir));
Ok(Vc::upcast(disk_fs))
}
......@@ -3740,7 +3740,7 @@ mod tests {
fully_specified: bool,
custom_extensions: Option<Vec<RcStr>>,
) -> anyhow::Result<Vc<ResolveRelativeRequestOutput>> {
let fs = DiskFileSystem::new(rcstr!("temp"), path);
let fs = DiskFileSystem::new(rcstr!("temp"), Vc::cell(path));
let lookup_path = fs.root().owned().await?;
let result = resolve_relative_helper(
......
......@@ -2670,11 +2670,13 @@ mod tests {
async fn read_matches_operation() -> anyhow::Result<Vc<ReadMatchesOutput>> {
let root = DiskFileSystem::new(
rcstr!("test"),
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/pattern/read_matches")
.to_str()
.unwrap()
.into(),
Vc::cell(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/pattern/read_matches")
.to_str()
.unwrap()
.into(),
),
)
.root()
.owned()
......
......@@ -374,10 +374,12 @@ mod tests {
};
let url_root = Url::from_directory_path(sys_root).unwrap();
let fs_root_path =
DiskFileSystem::new(rcstr!("mock"), RcStr::from(sys_root.to_str().unwrap()))
.root()
.await?;
let fs_root_path = DiskFileSystem::new(
rcstr!("mock"),
Vc::cell(RcStr::from(sys_root.to_str().unwrap())),
)
.root()
.await?;
let resolved_source_map: SourceMapJson = serde_json::from_str(
&resolve_source_map_sources(
......
......@@ -3,7 +3,7 @@ use std::{path::PathBuf, time::Duration};
use anyhow::Result;
use criterion::{BatchSize, Bencher, BenchmarkId, Criterion, criterion_group, criterion_main};
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, TurboTasks};
use turbo_tasks::{ResolvedVc, TurboTasks, Vc};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem};
use turbopack_core::{
......@@ -65,7 +65,7 @@ async fn setup(
file: &str,
analyze_mode: AnalyzeMode,
) -> Result<ResolvedVc<EcmascriptModuleAsset>> {
let fs = DiskFileSystem::new(rcstr!("project"), root_dir.into());
let fs = DiskFileSystem::new(rcstr!("project"), Vc::cell(root_dir.into()));
let environment = Environment::new(ExecutionEnvironment::NodeJsLambda(
NodeJsEnvironment::default().resolved_cell(),
......
......@@ -67,7 +67,7 @@ async fn node_file_trace_operation(
) -> Result<Vc<Vec<RcStr>>> {
let workspace_fs: Vc<Box<dyn FileSystem>> = Vc::upcast(DiskFileSystem::new(
rcstr!("workspace"),
project_root.clone(),
Vc::cell(project_root.clone()),
));
let input_dir = workspace_fs.root().owned().await?;
let input = input_dir.join(&format!("{input}"))?;
......
......@@ -319,8 +319,8 @@ async fn prepare_test(resource: RcStr) -> Result<Vc<PreparedTest>> {
resource_path.to_str().unwrap()
);
let root_fs = DiskFileSystem::new(rcstr!("workspace"), REPO_ROOT.clone());
let project_fs = DiskFileSystem::new(rcstr!("project"), REPO_ROOT.clone());
let root_fs = DiskFileSystem::new(rcstr!("workspace"), Vc::cell(REPO_ROOT.clone()));
let project_fs = DiskFileSystem::new(rcstr!("project"), Vc::cell(REPO_ROOT.clone()));
let project_root = project_fs.root().owned().await?;
let relative_path = resource_path.strip_prefix(&*REPO_ROOT).with_context(|| {
......
......@@ -276,7 +276,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
Err(_) => SnapshotOptions::default(),
Ok(options_str) => parse_json_with_source_context(&options_str).unwrap(),
};
let project_fs = DiskFileSystem::new(rcstr!("project"), REPO_ROOT.clone());
let project_fs = DiskFileSystem::new(rcstr!("project"), Vc::cell(REPO_ROOT.clone()));
let project_root = project_fs.root().owned().await?;
let relative_path = test_path.strip_prefix(&*REPO_ROOT)?;
......
......@@ -83,7 +83,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
let input: RcStr = bench_input.input.clone().into();
async move {
tt.run_once(async move {
let input_fs = DiskFileSystem::new(rcstr!("tests"), tests_root.clone());
let input_fs = DiskFileSystem::new(rcstr!("tests"), Vc::cell(tests_root.clone()));
let input = input_fs.root().await?.join(&input)?;
let input_dir = input.parent().parent();
......
......@@ -360,12 +360,12 @@ async fn node_file_trace_operation(
) -> Result<Vc<NodeFileTraceResult>> {
let workspace_fs: Vc<Box<dyn FileSystem>> = Vc::upcast(DiskFileSystem::new(
rcstr!("workspace"),
package_root.clone(),
Vc::cell(package_root.clone()),
));
let input_dir = workspace_fs.root().owned().await?;
let input = input_dir.join(&format!("tests/{input}"))?;
let output_fs = DiskFileSystem::new(rcstr!("output"), directory.clone());
let output_fs = DiskFileSystem::new(rcstr!("output"), Vc::cell(directory.clone()));
let output_dir = output_fs.root().owned().await?;
let source = FileSource::new(input);
......
......@@ -199,7 +199,7 @@ fn unit_test(#[case] input: &str) -> Result<()> {
async fn node_file_trace_operation(package_root: RcStr, input: RcStr) -> Result<Vc<Vec<RcStr>>> {
let workspace_fs: Vc<Box<dyn FileSystem>> = Vc::upcast(DiskFileSystem::new(
rcstr!("workspace"),
package_root.clone(),
Vc::cell(package_root.clone()),
));
let input_dir = workspace_fs.root().owned().await?;
let input = input_dir.join(&input)?;
......
......@@ -36,7 +36,7 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| {
Box::pin(async {
let root: RcStr = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new(PROJECT_FILESYSTEM_NAME.into(), root);
let disk_fs = DiskFileSystem::new(PROJECT_FILESYSTEM_NAME.into(), Vc::cell(root));
disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast
......
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