File size: 10,891 Bytes
b2cad4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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<Project>) -> 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<RcStr>, 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<Project>,
+    relative_path: RcStr,
+) -> Result<Vc<RcStr>> {
+    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<TurboTasksBackend>> {
+    turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
+        BackendOptions::default(),
+        noop_backing_storage(),
+    ))
+}
+
+#[turbo_tasks::function(operation, root)]
+async fn get_project(container: ResolvedVc<ProjectContainer>) -> Result<ResolvedVc<Project>> {
+    container.project().to_resolved().await
+}
+
+pub async fn initialize_project(
+    root: RcStr,
+    poll_interval: Option<Duration>,
+) -> Result<ResolvedVc<Project>> {
+    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<ResolvedVc<Project>> {
+    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<Project>, relative_path: RcStr) -> Result<Vc<RcStr>> {
+    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()))
+}