fallow_graph/
read_trace.rs1use std::io;
20use std::path::{Path, PathBuf};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
24pub enum ReadKind {
25 Content,
27 File,
29 Dir,
31}
32
33#[cfg(feature = "read-trace")]
35pub(crate) type ResolverFs = recording::TracingFs;
36#[cfg(not(feature = "read-trace"))]
38pub(crate) type ResolverFs = oxc_resolver::FileSystemOs;
39
40pub(crate) type Resolver = oxc_resolver::ResolverGeneric<ResolverFs>;
42
43#[cfg(feature = "read-trace")]
44pub use recording::{ReadEvent, ReadRecorder};
45
46#[cfg(feature = "read-trace")]
47use recording::note;
48
49#[cfg(not(feature = "read-trace"))]
50#[inline(always)]
51const fn note(_path: &Path, _kind: ReadKind) {}
52
53pub(crate) trait TracedPath {
55 fn traced_is_file(&self) -> bool;
57 fn traced_is_dir(&self) -> bool;
59 fn traced_exists(&self) -> bool;
61}
62
63impl TracedPath for Path {
64 fn traced_is_file(&self) -> bool {
65 note(self, ReadKind::File);
66 self.is_file()
67 }
68
69 fn traced_is_dir(&self) -> bool {
70 note(self, ReadKind::Dir);
71 self.is_dir()
72 }
73
74 fn traced_exists(&self) -> bool {
75 note(self, ReadKind::File);
76 self.exists()
77 }
78}
79
80pub(crate) fn read_to_string(path: impl AsRef<Path>) -> io::Result<String> {
82 let path = path.as_ref();
83 let result = std::fs::read_to_string(path);
84 note(path, content_kind(result.is_ok()));
85 result
86}
87
88pub(crate) fn canonicalize(path: impl AsRef<Path>) -> io::Result<PathBuf> {
90 let path = path.as_ref();
91 note(path, ReadKind::File);
92 dunce::canonicalize(path)
93}
94
95const fn content_kind(found: bool) -> ReadKind {
97 if found {
98 ReadKind::Content
99 } else {
100 ReadKind::File
101 }
102}
103
104#[cfg(feature = "read-trace")]
105mod recording {
106 use std::io;
107 use std::path::{Path, PathBuf};
108 use std::sync::Mutex;
109 use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
110
111 use oxc_resolver::{FileMetadata, FileSystem, FileSystemOs, ResolveError};
112 use rustc_hash::FxHashSet;
113
114 use super::{ReadKind, content_kind};
115
116 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
118 pub struct ReadEvent {
119 pub path: PathBuf,
121 pub kind: ReadKind,
123 }
124
125 struct Active {
126 id: u64,
127 scopes: Vec<PathBuf>,
128 events: FxHashSet<ReadEvent>,
129 }
130
131 static OPEN: AtomicUsize = AtomicUsize::new(0);
134 static NEXT_ID: AtomicU64 = AtomicU64::new(0);
135 static RECORDERS: Mutex<Vec<Active>> = Mutex::new(Vec::new());
136
137 #[derive(Debug)]
143 pub struct ReadRecorder {
144 id: u64,
145 }
146
147 impl ReadRecorder {
148 #[must_use]
151 pub fn start(scope: &Path) -> Self {
152 let mut scopes = vec![scope.to_path_buf()];
153 if let Ok(canonical) = dunce::canonicalize(scope)
154 && canonical != scope
155 {
156 scopes.push(canonical);
157 }
158 let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
159 RECORDERS
160 .lock()
161 .unwrap_or_else(|e| e.into_inner())
162 .push(Active {
163 id,
164 scopes,
165 events: FxHashSet::default(),
166 });
167 OPEN.fetch_add(1, Ordering::SeqCst);
168 Self { id }
169 }
170
171 #[must_use]
173 pub fn finish(self) -> Vec<ReadEvent> {
174 let Some(active) = remove(self.id) else {
175 return Vec::new();
176 };
177 let mut events: Vec<ReadEvent> = active.events.into_iter().collect();
178 events.sort_unstable();
179 events
180 }
181 }
182
183 impl Drop for ReadRecorder {
186 fn drop(&mut self) {
187 let _ = remove(self.id);
188 }
189 }
190
191 fn remove(id: u64) -> Option<Active> {
192 let active = {
193 let mut recorders = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
194 let index = recorders.iter().position(|active| active.id == id)?;
195 recorders.swap_remove(index)
196 };
197 OPEN.fetch_sub(1, Ordering::SeqCst);
198 Some(active)
199 }
200
201 pub fn note(path: &Path, kind: ReadKind) {
202 if OPEN.load(Ordering::Relaxed) == 0 || !path.is_absolute() {
203 return;
204 }
205 let mut recorders = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
206 for active in recorders.iter_mut() {
207 if active.scopes.iter().any(|scope| path.starts_with(scope)) {
208 active.events.insert(ReadEvent {
209 path: path.to_path_buf(),
210 kind,
211 });
212 }
213 }
214 }
215
216 pub struct TracingFs(FileSystemOs);
218
219 impl FileSystem for TracingFs {
220 fn new(yarn_pnp: bool) -> Self {
221 Self(FileSystemOs::new(yarn_pnp))
222 }
223
224 fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
225 let result = self.0.read(path);
226 note(path, content_kind(result.is_ok()));
227 result
228 }
229
230 fn read_to_string(&self, path: &Path) -> io::Result<String> {
231 let result = self.0.read_to_string(path);
232 note(path, content_kind(result.is_ok()));
233 result
234 }
235
236 fn metadata(&self, path: &Path) -> io::Result<FileMetadata> {
237 note(path, ReadKind::File);
238 self.0.metadata(path)
239 }
240
241 fn symlink_metadata(&self, path: &Path) -> io::Result<FileMetadata> {
242 note(path, ReadKind::File);
243 self.0.symlink_metadata(path)
244 }
245
246 fn read_link(&self, path: &Path) -> Result<PathBuf, ResolveError> {
247 note(path, ReadKind::File);
248 self.0.read_link(path)
249 }
250
251 fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
252 note(path, ReadKind::File);
253 self.0.canonicalize(path)
254 }
255 }
256}