diff --git a/crates/next-api/tests/project_file_system_directory.rs b/crates/next-api/tests/project_file_system_directory.rs new file mode 100644 index 0000000000..e05c1d70a1 --- /dev/null +++ b/crates/next-api/tests/project_file_system_directory.rs @@ -0,0 +1,42 @@ +mod support; + +use std::fs; + +use anyhow::Result; +use next_api::project::Project; +use support::{initialize_unwatched_project, turbo_tasks}; +use turbo_rcstr::{RcStr, rcstr}; +use turbo_tasks::ResolvedVc; +use turbo_tasks_fs::{DirectoryContent, FileSystemPath}; + +#[turbo_tasks::function(operation, root)] +async fn assert_root_entries(project: ResolvedVc) -> Result<()> { + let root: FileSystemPath = (*project.project_root_path().await?).clone(); + let content = root.read_dir().await?; + let DirectoryContent::Entries(entries) = &*content else { + anyhow::bail!("expected directory entries") + }; + assert!(entries.contains_key(&rcstr!("first.txt"))); + assert!(entries.contains_key(&rcstr!("second.txt"))); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn project_lists_all_adjacent_root_entries() { + let scratch = tempfile::tempdir().unwrap(); + fs::create_dir(scratch.path().join("project")).unwrap(); + fs::write(scratch.path().join("first.txt"), "first").unwrap(); + fs::write(scratch.path().join("second.txt"), "second").unwrap(); + let root: RcStr = scratch.path().to_str().unwrap().into(); + + turbo_tasks() + .run_once(async move { + let project = initialize_unwatched_project(root).await?; + assert_root_entries(project) + .read_strongly_consistent() + .await?; + anyhow::Ok(()) + }) + .await + .unwrap(); +} diff --git a/crates/next-api/tests/project_file_system_read.rs b/crates/next-api/tests/project_file_system_read.rs new file mode 100644 index 0000000000..f63bb4dd62 --- /dev/null +++ b/crates/next-api/tests/project_file_system_read.rs @@ -0,0 +1,26 @@ +mod support; + +use std::fs; + +use support::{initialize_unwatched_project, read_text, turbo_tasks}; +use turbo_rcstr::{RcStr, rcstr}; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn project_reads_files_from_its_configured_root() { + let scratch = tempfile::tempdir().unwrap(); + fs::create_dir(scratch.path().join("project")).unwrap(); + fs::write(scratch.path().join("message.txt"), "hello from disk").unwrap(); + let root: RcStr = scratch.path().to_str().unwrap().into(); + + turbo_tasks() + .run_once(async move { + let project = initialize_unwatched_project(root).await?; + let content = read_text(project, rcstr!("message.txt")) + .read_strongly_consistent() + .await?; + assert_eq!(&*content, "hello from disk"); + anyhow::Ok(()) + }) + .await + .unwrap(); +} diff --git a/crates/next-api/tests/project_polling_watcher.rs b/crates/next-api/tests/project_polling_watcher.rs new file mode 100644 index 0000000000..723f8b49f0 --- /dev/null +++ b/crates/next-api/tests/project_polling_watcher.rs @@ -0,0 +1,115 @@ +mod support; + +use std::{ + fs, + sync::atomic::{AtomicUsize, Ordering}, + time::{Duration, Instant, SystemTime}, +}; + +use anyhow::{Result, bail}; +use next_api::project::Project; +use support::{initialize_project, read_text, turbo_tasks}; +use turbo_rcstr::{RcStr, rcstr}; +use turbo_tasks::{OperationVc, ResolvedVc, Vc}; +use turbo_tasks_fs::{FileContent, FileSystemPath}; + +static METADATA_READ_RUNS: AtomicUsize = AtomicUsize::new(0); + +async fn wait_for_text(operation: OperationVc, expected: &str) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let value = operation.read_strongly_consistent().await?; + if &*value == expected { + return Ok(()); + } + if Instant::now() >= deadline { + bail!("timed out waiting for the updated file contents") + } + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +#[turbo_tasks::function(operation, root)] +async fn read_text_counted( + project: ResolvedVc, + relative_path: RcStr, +) -> Result> { + METADATA_READ_RUNS.fetch_add(1, Ordering::SeqCst); + let path: FileSystemPath = project.project_root_path().await?.join(&relative_path)?; + let content = path.read().await?; + let FileContent::Content(file) = &*content else { + bail!("expected a file") + }; + Ok(Vc::cell(file.content().to_str()?.into())) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn project_polling_observes_file_updates() { + let scratch = tempfile::tempdir().unwrap(); + fs::create_dir(scratch.path().join("project")).unwrap(); + let path = scratch.path().join("message.txt"); + fs::write(&path, "before").unwrap(); + fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(SystemTime::now() - Duration::from_secs(10)) + .unwrap(); + let root: RcStr = scratch.path().to_str().unwrap().into(); + + turbo_tasks() + .run_once(async move { + let project = initialize_project(root, Some(Duration::from_millis(20))).await?; + let operation = read_text(project, rcstr!("message.txt")); + assert_eq!(&*operation.read_strongly_consistent().await?, "before"); + + fs::write(path, "after")?; + wait_for_text(operation, "after").await?; + anyhow::Ok(()) + }) + .await + .unwrap(); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_metadata_only_changes_do_not_invalidate_file_data_on_linux() { + use std::os::unix::fs::PermissionsExt; + + if cfg!(target_os = "macos") { + return; + } + + METADATA_READ_RUNS.store(0, Ordering::SeqCst); + let scratch = tempfile::tempdir().unwrap(); + fs::create_dir(scratch.path().join("project")).unwrap(); + let path = scratch.path().join("message.txt"); + fs::write(&path, "unchanged").unwrap(); + let root: RcStr = scratch.path().to_str().unwrap().into(); + + turbo_tasks() + .run_once(async move { + let project = initialize_project(root, None).await?; + let operation = read_text_counted(project, rcstr!("message.txt")); + assert_eq!(&*operation.read_strongly_consistent().await?, "unchanged"); + assert_eq!(METADATA_READ_RUNS.load(Ordering::SeqCst), 1); + + let mut permissions = fs::metadata(&path)?.permissions(); + permissions.set_mode(0o444); + fs::set_permissions(&path, permissions)?; + + let deadline = Instant::now() + Duration::from_millis(500); + while Instant::now() < deadline { + assert_eq!(&*operation.read_strongly_consistent().await?, "unchanged"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!( + METADATA_READ_RUNS.load(Ordering::SeqCst), + 1, + "metadata-only changes must not invalidate cached file data on this platform" + ); + anyhow::Ok(()) + }) + .await + .unwrap(); +} diff --git a/crates/next-api/tests/support/mod.rs b/crates/next-api/tests/support/mod.rs new file mode 100644 index 0000000000..81a9ba058b --- /dev/null +++ b/crates/next-api/tests/support/mod.rs @@ -0,0 +1,93 @@ +#![allow(dead_code)] + +use std::{sync::Arc, time::Duration}; + +use anyhow::{Result, bail}; +use next_api::project::{ + DefineEnv, DraftModeOptions, Project, ProjectContainer, ProjectOptions, WatchOptions, +}; +use turbo_rcstr::{RcStr, rcstr}; +use turbo_tasks::{ResolvedVc, Vc}; +use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; +use turbo_tasks_fs::{FileContent, FileSystemPath}; + +pub fn options(root_path: RcStr, watch: WatchOptions) -> ProjectOptions { + ProjectOptions { + root_path, + project_path: rcstr!("project"), + next_config: rcstr!("{}"), + env: Vec::new(), + define_env: DefineEnv { + client: Vec::new(), + edge: Vec::new(), + nodejs: Vec::new(), + }, + watch, + dev: true, + encryption_key: rcstr!("test"), + build_id: rcstr!("test"), + preview_props: DraftModeOptions { + preview_mode_id: rcstr!("test"), + preview_mode_encryption_key: rcstr!("test"), + preview_mode_signing_key: rcstr!("test"), + }, + browserslist_query: rcstr!("defaults"), + no_mangling: false, + write_routes_hashes_manifest: false, + current_node_js_version: rcstr!("20.0.0"), + debug_build_paths: None, + deferred_entries: None, + is_persistent_caching_enabled: false, + next_version: rcstr!("test"), + server_hmr: true, + } +} + +pub fn turbo_tasks() -> Arc> { + turbo_tasks::TurboTasks::new(TurboTasksBackend::new( + BackendOptions::default(), + noop_backing_storage(), + )) +} + +#[turbo_tasks::function(operation, root)] +async fn get_project(container: ResolvedVc) -> Result> { + container.project().to_resolved().await +} + +pub async fn initialize_project( + root: RcStr, + poll_interval: Option, +) -> Result> { + let container = ProjectContainer::new_operation(rcstr!("watcher-test"), true); + ProjectContainer::initialize( + container, + options( + root, + WatchOptions { + enable: true, + poll_interval, + }, + ), + ) + .await?; + let container = container.resolve().strongly_consistent().await?; + get_project(container).resolve().strongly_consistent().await +} + +pub async fn initialize_unwatched_project(root: RcStr) -> Result> { + let container = ProjectContainer::new_operation(rcstr!("filesystem-test"), true); + ProjectContainer::initialize(container, options(root, WatchOptions::default())).await?; + let container = container.resolve().strongly_consistent().await?; + get_project(container).resolve().strongly_consistent().await +} + +#[turbo_tasks::function(operation, root)] +pub async fn read_text(project: ResolvedVc, relative_path: RcStr) -> Result> { + let path: FileSystemPath = project.project_root_path().await?.join(&relative_path)?; + let content = path.read().await?; + let FileContent::Content(file) = &*content else { + bail!("expected a file") + }; + Ok(Vc::cell(file.content().to_str()?.into())) +}