use std::io;
use std::path::{Path, PathBuf};
use oxc_resolver::{FileMetadata, FileSystem, FileSystemOs, ResolveError};
use crate::missed_probes;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ReadKind {
Content,
File,
Dir,
}
pub(crate) type ResolverFs = ProbeFs;
pub(crate) type Resolver = oxc_resolver::ResolverGeneric<ResolverFs>;
#[cfg(feature = "read-trace")]
pub use recording::{ReadEvent, ReadRecorder};
#[cfg(feature = "read-trace")]
use recording::note;
#[cfg(not(feature = "read-trace"))]
#[inline(always)]
const fn note(_path: &Path, _kind: ReadKind) {}
pub(crate) trait TracedPath {
fn traced_is_file(&self) -> bool;
fn traced_is_dir(&self) -> bool;
fn traced_exists(&self) -> bool;
}
impl TracedPath for Path {
fn traced_is_file(&self) -> bool {
note(self, ReadKind::File);
checked_metadata(self).is_ok_and(|metadata| metadata.is_file())
}
fn traced_is_dir(&self) -> bool {
note(self, ReadKind::Dir);
checked_metadata(self).is_ok_and(|metadata| metadata.is_dir())
}
fn traced_exists(&self) -> bool {
note(self, ReadKind::File);
checked_metadata(self).is_ok()
}
}
fn checked_metadata(path: &Path) -> io::Result<std::fs::Metadata> {
let result = std::fs::metadata(path);
missed_probes::note_if_missing(path, &result);
result
}
pub(crate) fn read_to_string(path: impl AsRef<Path>) -> io::Result<String> {
let path = path.as_ref();
let result = std::fs::read_to_string(path);
missed_probes::note_read(path, &result);
note(path, content_kind(result.is_ok()));
result
}
pub(crate) fn canonicalize(path: impl AsRef<Path>) -> io::Result<PathBuf> {
let path = path.as_ref();
note(path, ReadKind::File);
let result = dunce::canonicalize(path);
missed_probes::note_if_missing(path, &result);
result
}
pub(crate) struct ProbeFs(FileSystemOs);
impl FileSystem for ProbeFs {
fn new(yarn_pnp: bool) -> Self {
Self(FileSystemOs::new(yarn_pnp))
}
fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
let result = self.0.read(path);
missed_probes::note_read(path, &result);
note(path, content_kind(result.is_ok()));
result
}
fn read_to_string(&self, path: &Path) -> io::Result<String> {
let result = self.0.read_to_string(path);
missed_probes::note_read(path, &result);
note(path, content_kind(result.is_ok()));
result
}
fn metadata(&self, path: &Path) -> io::Result<FileMetadata> {
note(path, ReadKind::File);
let result = self.0.metadata(path);
missed_probes::note_if_missing(path, &result);
result
}
fn symlink_metadata(&self, path: &Path) -> io::Result<FileMetadata> {
note(path, ReadKind::File);
let result = self.0.symlink_metadata(path);
missed_probes::note_if_missing(path, &result);
result
}
fn read_link(&self, path: &Path) -> Result<PathBuf, ResolveError> {
note(path, ReadKind::File);
self.0.read_link(path)
}
fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
note(path, ReadKind::File);
let result = self.0.canonicalize(path);
missed_probes::note_if_missing(path, &result);
result
}
}
const fn content_kind(found: bool) -> ReadKind {
if found {
ReadKind::Content
} else {
ReadKind::File
}
}
#[cfg(feature = "read-trace")]
mod recording {
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use rustc_hash::FxHashSet;
use super::ReadKind;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ReadEvent {
pub path: PathBuf,
pub kind: ReadKind,
}
struct Active {
id: u64,
scopes: Vec<PathBuf>,
events: FxHashSet<ReadEvent>,
}
static OPEN: AtomicUsize = AtomicUsize::new(0);
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
static RECORDERS: Mutex<Vec<Active>> = Mutex::new(Vec::new());
#[derive(Debug)]
pub struct ReadRecorder {
id: u64,
}
impl ReadRecorder {
#[must_use]
pub fn start(scope: &Path) -> Self {
let mut scopes = vec![scope.to_path_buf()];
if let Ok(canonical) = dunce::canonicalize(scope)
&& canonical != scope
{
scopes.push(canonical);
}
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
RECORDERS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Active {
id,
scopes,
events: FxHashSet::default(),
});
OPEN.fetch_add(1, Ordering::SeqCst);
Self { id }
}
#[must_use]
pub fn finish(self) -> Vec<ReadEvent> {
let Some(active) = remove(self.id) else {
return Vec::new();
};
let mut events: Vec<ReadEvent> = active.events.into_iter().collect();
events.sort_unstable();
events
}
}
impl Drop for ReadRecorder {
fn drop(&mut self) {
let _ = remove(self.id);
}
}
fn remove(id: u64) -> Option<Active> {
let active = {
let mut recorders = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
let index = recorders.iter().position(|active| active.id == id)?;
recorders.swap_remove(index)
};
OPEN.fetch_sub(1, Ordering::SeqCst);
Some(active)
}
pub fn note(path: &Path, kind: ReadKind) {
if OPEN.load(Ordering::Relaxed) == 0 || !path.is_absolute() {
return;
}
let mut recorders = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
for active in recorders.iter_mut() {
if active.scopes.iter().any(|scope| path.starts_with(scope)) {
active.events.insert(ReadEvent {
path: path.to_path_buf(),
kind,
});
}
}
}
}