|
|
use std::{ |
|
|
any::Any, |
|
|
fmt, |
|
|
mem::take, |
|
|
path::{Path, PathBuf}, |
|
|
sync::{ |
|
|
Arc, Mutex, |
|
|
mpsc::{Receiver, TryRecvError, channel}, |
|
|
}, |
|
|
time::Duration, |
|
|
}; |
|
|
|
|
|
use anyhow::Result; |
|
|
use notify::{ |
|
|
Config, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, Watcher, |
|
|
event::{MetadataKind, ModifyKind, RenameMode}, |
|
|
}; |
|
|
use rayon::iter::{IntoParallelIterator, ParallelIterator}; |
|
|
use rustc_hash::{FxHashMap, FxHashSet}; |
|
|
use serde::{Deserialize, Serialize}; |
|
|
use tracing::instrument; |
|
|
use turbo_rcstr::RcStr; |
|
|
use turbo_tasks::{ |
|
|
FxIndexSet, InvalidationReason, InvalidationReasonKind, Invalidator, spawn_thread, |
|
|
util::StaticOrArc, |
|
|
}; |
|
|
|
|
|
use crate::{ |
|
|
DiskFileSystemInner, format_absolute_fs_path, |
|
|
invalidation::{WatchChange, WatchStart}, |
|
|
invalidator_map::WriteContent, |
|
|
path_to_key, |
|
|
}; |
|
|
|
|
|
enum DiskWatcherInternal { |
|
|
Recommended(RecommendedWatcher), |
|
|
Polling(PollWatcher), |
|
|
} |
|
|
|
|
|
impl DiskWatcherInternal { |
|
|
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> notify::Result<()> { |
|
|
match self { |
|
|
DiskWatcherInternal::Recommended(watcher) => watcher.watch(path, recursive_mode), |
|
|
DiskWatcherInternal::Polling(watcher) => watcher.watch(path, recursive_mode), |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
#[derive(Default, Serialize, Deserialize)] |
|
|
pub(crate) struct DiskWatcher { |
|
|
#[serde(skip)] |
|
|
watcher: Mutex<Option<DiskWatcherInternal>>, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ignored_subpaths: Vec<PathBuf>, |
|
|
|
|
|
|
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
#[serde(skip)] |
|
|
watching: dashmap::DashSet<PathBuf>, |
|
|
} |
|
|
|
|
|
impl DiskWatcher { |
|
|
pub(crate) fn new(ignored_subpaths: Vec<PathBuf>) -> Self { |
|
|
Self { |
|
|
ignored_subpaths, |
|
|
..Default::default() |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
pub(crate) fn restore_all_watching(&self, root_path: &Path) { |
|
|
let mut watcher = self.watcher.lock().unwrap(); |
|
|
for dir_path in self.watching.iter() { |
|
|
|
|
|
let _ = self.start_watching_dir(&mut watcher, &dir_path, root_path); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
pub(crate) fn restore_if_watching(&self, dir_path: &Path, root_path: &Path) -> Result<()> { |
|
|
if self.watching.contains(dir_path) { |
|
|
let mut watcher = self.watcher.lock().unwrap(); |
|
|
|
|
|
self.start_watching_dir(&mut watcher, dir_path, root_path)?; |
|
|
} |
|
|
Ok(()) |
|
|
} |
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
pub(crate) fn ensure_watching(&self, dir_path: &Path, root_path: &Path) -> Result<()> { |
|
|
if self.watching.contains(dir_path) { |
|
|
return Ok(()); |
|
|
} |
|
|
let mut watcher = self.watcher.lock().unwrap(); |
|
|
if self.watching.insert(dir_path.to_path_buf()) { |
|
|
self.start_watching_dir(&mut watcher, dir_path, root_path)?; |
|
|
} |
|
|
Ok(()) |
|
|
} |
|
|
|
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
fn start_watching_dir( |
|
|
&self, |
|
|
watcher: &mut std::sync::MutexGuard<Option<DiskWatcherInternal>>, |
|
|
dir_path: &Path, |
|
|
root_path: &Path, |
|
|
) -> Result<()> { |
|
|
use anyhow::Context; |
|
|
|
|
|
if let Some(watcher) = watcher.as_mut() { |
|
|
let mut path = dir_path; |
|
|
let err_with_context = |err| { |
|
|
return Err(err).context(format!( |
|
|
"Unable to watch {} (tried up to {})", |
|
|
dir_path.display(), |
|
|
path.display() |
|
|
)); |
|
|
}; |
|
|
while let Err(err) = watcher.watch(path, RecursiveMode::NonRecursive) { |
|
|
match err { |
|
|
notify::Error { |
|
|
kind: notify::ErrorKind::PathNotFound, |
|
|
.. |
|
|
} => { |
|
|
|
|
|
|
|
|
|
|
|
let Some(parent_path) = path.parent() else { |
|
|
|
|
|
return err_with_context(err); |
|
|
}; |
|
|
if parent_path == root_path { |
|
|
|
|
|
break; |
|
|
} |
|
|
if !self.watching.insert(parent_path.to_owned()) { |
|
|
|
|
|
break; |
|
|
} |
|
|
path = parent_path; |
|
|
} |
|
|
_ => return err_with_context(err), |
|
|
} |
|
|
} |
|
|
} |
|
|
Ok(()) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pub(crate) fn start_watching( |
|
|
&self, |
|
|
inner: Arc<DiskFileSystemInner>, |
|
|
report_invalidation_reason: bool, |
|
|
poll_interval: Option<Duration>, |
|
|
) -> Result<()> { |
|
|
let mut watcher_guard = self.watcher.lock().unwrap(); |
|
|
if watcher_guard.is_some() { |
|
|
return Ok(()); |
|
|
} |
|
|
|
|
|
|
|
|
let (tx, rx) = channel(); |
|
|
|
|
|
|
|
|
let config = Config::default(); |
|
|
|
|
|
config.with_follow_symlinks(false); |
|
|
|
|
|
let mut watcher = if let Some(poll_interval) = poll_interval { |
|
|
let config = config.with_poll_interval(poll_interval); |
|
|
|
|
|
DiskWatcherInternal::Polling(PollWatcher::new(tx, config)?) |
|
|
} else { |
|
|
DiskWatcherInternal::Recommended(RecommendedWatcher::new(tx, Config::default())?) |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
#[cfg(any(target_os = "macos", target_os = "windows"))] |
|
|
{ |
|
|
watcher.watch(inner.root_path(), RecursiveMode::Recursive)?; |
|
|
} |
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
for dir_path in self.watching.iter() { |
|
|
watcher.watch(&dir_path, RecursiveMode::NonRecursive)?; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
{ |
|
|
let _span = tracing::info_span!("invalidate filesystem").entered(); |
|
|
let span = tracing::Span::current(); |
|
|
let invalidator_map = take(&mut *inner.invalidator_map.lock().unwrap()); |
|
|
let dir_invalidator_map = take(&mut *inner.dir_invalidator_map.lock().unwrap()); |
|
|
let iter = invalidator_map |
|
|
.into_par_iter() |
|
|
.chain(dir_invalidator_map.into_par_iter()); |
|
|
let handle = tokio::runtime::Handle::current(); |
|
|
if report_invalidation_reason { |
|
|
iter.flat_map(|(path, invalidators)| { |
|
|
let _span = span.clone().entered(); |
|
|
let reason = WatchStart { |
|
|
name: inner.name.clone(), |
|
|
path: path.into(), |
|
|
}; |
|
|
invalidators |
|
|
.into_par_iter() |
|
|
.map(move |i| (reason.clone(), i)) |
|
|
}) |
|
|
.for_each(|(reason, (invalidator, _))| { |
|
|
let _span = span.clone().entered(); |
|
|
let _guard = handle.enter(); |
|
|
invalidator.invalidate_with_reason(reason) |
|
|
}); |
|
|
} else { |
|
|
iter.flat_map(|(_, invalidators)| { |
|
|
let _span = span.clone().entered(); |
|
|
invalidators.into_par_iter().map(move |i| i) |
|
|
}) |
|
|
.for_each(|(invalidator, _)| { |
|
|
let _span = span.clone().entered(); |
|
|
let _guard = handle.enter(); |
|
|
invalidator.invalidate() |
|
|
}); |
|
|
} |
|
|
} |
|
|
|
|
|
watcher_guard.replace(watcher); |
|
|
drop(watcher_guard); |
|
|
|
|
|
spawn_thread(move || { |
|
|
inner |
|
|
.clone() |
|
|
.watcher |
|
|
.watch_thread(rx, inner, report_invalidation_reason) |
|
|
}); |
|
|
|
|
|
Ok(()) |
|
|
} |
|
|
|
|
|
pub(crate) fn stop_watching(&self) { |
|
|
if let Some(watcher) = self.watcher.lock().unwrap().take() { |
|
|
drop(watcher); |
|
|
|
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn watch_thread( |
|
|
&self, |
|
|
rx: Receiver<notify::Result<notify::Event>>, |
|
|
inner: Arc<DiskFileSystemInner>, |
|
|
report_invalidation_reason: bool, |
|
|
) { |
|
|
let mut batched_invalidate_path = FxHashSet::default(); |
|
|
let mut batched_invalidate_path_dir = FxHashSet::default(); |
|
|
let mut batched_invalidate_path_and_children = FxHashSet::default(); |
|
|
let mut batched_invalidate_path_and_children_dir = FxHashSet::default(); |
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
let mut batched_new_paths = FxHashSet::default(); |
|
|
|
|
|
'outer: loop { |
|
|
let mut event_result = rx.recv().or(Err(TryRecvError::Disconnected)); |
|
|
|
|
|
loop { |
|
|
match event_result { |
|
|
Ok(Ok(event)) => { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if event.need_rescan() { |
|
|
let _lock = inner.invalidation_lock.blocking_write(); |
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
{ |
|
|
|
|
|
|
|
|
|
|
|
self.restore_all_watching(inner.root_path()); |
|
|
batched_new_paths.clear(); |
|
|
} |
|
|
|
|
|
if report_invalidation_reason { |
|
|
inner.invalidate_with_reason(|path| InvalidateRescan { |
|
|
path: RcStr::from(path), |
|
|
}); |
|
|
} else { |
|
|
inner.invalidate(); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
batched_invalidate_path.clear(); |
|
|
batched_invalidate_path_dir.clear(); |
|
|
batched_invalidate_path_and_children.clear(); |
|
|
batched_invalidate_path_and_children_dir.clear(); |
|
|
|
|
|
break; |
|
|
} |
|
|
|
|
|
let paths: Vec<PathBuf> = event |
|
|
.paths |
|
|
.iter() |
|
|
.filter(|p| { |
|
|
!self |
|
|
.ignored_subpaths |
|
|
.iter() |
|
|
.any(|ignored| p.starts_with(ignored)) |
|
|
}) |
|
|
.cloned() |
|
|
.collect(); |
|
|
|
|
|
if paths.is_empty() { |
|
|
|
|
|
event_result = rx.try_recv(); |
|
|
continue; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
match event.kind { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
EventKind::Modify( |
|
|
ModifyKind::Data(_) | ModifyKind::Metadata(MetadataKind::Any), |
|
|
) => { |
|
|
batched_invalidate_path.extend(paths); |
|
|
} |
|
|
EventKind::Create(_) => { |
|
|
batched_invalidate_path_and_children.extend(paths.clone()); |
|
|
batched_invalidate_path_and_children_dir.extend(paths.clone()); |
|
|
paths.iter().for_each(|path| { |
|
|
if let Some(parent) = path.parent() { |
|
|
batched_invalidate_path_dir.insert(PathBuf::from(parent)); |
|
|
} |
|
|
}); |
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
batched_new_paths.extend(paths.clone()); |
|
|
} |
|
|
EventKind::Remove(_) => { |
|
|
batched_invalidate_path_and_children.extend(paths.clone()); |
|
|
batched_invalidate_path_and_children_dir.extend(paths.clone()); |
|
|
paths.iter().for_each(|path| { |
|
|
if let Some(parent) = path.parent() { |
|
|
batched_invalidate_path_dir.insert(PathBuf::from(parent)); |
|
|
} |
|
|
}); |
|
|
} |
|
|
|
|
|
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => { |
|
|
|
|
|
|
|
|
if let [source, destination, ..] = &paths[..] { |
|
|
batched_invalidate_path_and_children.insert(source.clone()); |
|
|
if let Some(parent) = source.parent() { |
|
|
batched_invalidate_path_dir.insert(PathBuf::from(parent)); |
|
|
} |
|
|
batched_invalidate_path_and_children |
|
|
.insert(destination.clone()); |
|
|
if let Some(parent) = destination.parent() { |
|
|
batched_invalidate_path_dir.insert(PathBuf::from(parent)); |
|
|
} |
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
batched_new_paths.insert(destination.clone()); |
|
|
} else { |
|
|
|
|
|
|
|
|
panic!( |
|
|
"Rename event does not contain source and destination \ |
|
|
paths {paths:#?}" |
|
|
); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
EventKind::Any |
|
|
| EventKind::Modify(ModifyKind::Any | ModifyKind::Name(..)) => { |
|
|
batched_invalidate_path.extend(paths.clone()); |
|
|
batched_invalidate_path_and_children.extend(paths.clone()); |
|
|
batched_invalidate_path_and_children_dir.extend(paths.clone()); |
|
|
for parent in paths.iter().filter_map(|path| path.parent()) { |
|
|
batched_invalidate_path_dir.insert(PathBuf::from(parent)); |
|
|
} |
|
|
} |
|
|
EventKind::Modify(ModifyKind::Metadata(..) | ModifyKind::Other) |
|
|
| EventKind::Access(_) |
|
|
| EventKind::Other => { |
|
|
|
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
Ok(Err(notify::Error { kind, paths })) => { |
|
|
println!("watch error ({paths:?}): {kind:?} "); |
|
|
|
|
|
if paths.is_empty() { |
|
|
batched_invalidate_path_and_children |
|
|
.insert(inner.root_path().to_path_buf()); |
|
|
batched_invalidate_path_and_children_dir |
|
|
.insert(inner.root_path().to_path_buf()); |
|
|
} else { |
|
|
batched_invalidate_path_and_children.extend(paths.clone()); |
|
|
batched_invalidate_path_and_children_dir.extend(paths.clone()); |
|
|
} |
|
|
} |
|
|
Err(TryRecvError::Disconnected) => { |
|
|
|
|
|
|
|
|
|
|
|
break 'outer; |
|
|
} |
|
|
Err(TryRecvError::Empty) => { |
|
|
|
|
|
|
|
|
#[cfg(target_os = "linux")] |
|
|
let delay = Duration::from_millis(10); |
|
|
#[cfg(not(target_os = "linux"))] |
|
|
let delay = Duration::from_millis(1); |
|
|
match rx.recv_timeout(delay) { |
|
|
Ok(result) => { |
|
|
event_result = Ok(result); |
|
|
continue; |
|
|
} |
|
|
Err(_) => break, |
|
|
} |
|
|
} |
|
|
} |
|
|
event_result = rx.try_recv(); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))] |
|
|
{ |
|
|
for path in batched_new_paths.drain() { |
|
|
|
|
|
let _ = self.restore_if_watching(&path, inner.root_path()); |
|
|
} |
|
|
} |
|
|
|
|
|
let _lock = inner.invalidation_lock.blocking_write(); |
|
|
{ |
|
|
let mut invalidator_map = inner.invalidator_map.lock().unwrap(); |
|
|
invalidate_path( |
|
|
&inner, |
|
|
report_invalidation_reason, |
|
|
&mut invalidator_map, |
|
|
batched_invalidate_path.drain(), |
|
|
); |
|
|
invalidate_path_and_children_execute( |
|
|
&inner, |
|
|
report_invalidation_reason, |
|
|
&mut invalidator_map, |
|
|
batched_invalidate_path_and_children.drain(), |
|
|
); |
|
|
} |
|
|
{ |
|
|
let mut dir_invalidator_map = inner.dir_invalidator_map.lock().unwrap(); |
|
|
invalidate_path( |
|
|
&inner, |
|
|
report_invalidation_reason, |
|
|
&mut dir_invalidator_map, |
|
|
batched_invalidate_path_dir.drain(), |
|
|
); |
|
|
invalidate_path_and_children_execute( |
|
|
&inner, |
|
|
report_invalidation_reason, |
|
|
&mut dir_invalidator_map, |
|
|
batched_invalidate_path_and_children_dir.drain(), |
|
|
); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
#[instrument(parent = None, level = "info", name = "DiskFileSystem file change", skip_all, fields(name = display(path.display())))] |
|
|
fn invalidate( |
|
|
inner: &DiskFileSystemInner, |
|
|
report_invalidation_reason: bool, |
|
|
path: &Path, |
|
|
invalidator: Invalidator, |
|
|
) { |
|
|
if report_invalidation_reason |
|
|
&& let Some(path) = format_absolute_fs_path(path, &inner.name, inner.root_path()) |
|
|
{ |
|
|
invalidator.invalidate_with_reason(WatchChange { path }); |
|
|
return; |
|
|
} |
|
|
invalidator.invalidate(); |
|
|
} |
|
|
|
|
|
fn invalidate_path( |
|
|
inner: &DiskFileSystemInner, |
|
|
report_invalidation_reason: bool, |
|
|
invalidator_map: &mut FxHashMap<String, FxHashMap<Invalidator, Option<WriteContent>>>, |
|
|
paths: impl Iterator<Item = PathBuf>, |
|
|
) { |
|
|
for path in paths { |
|
|
let key = path_to_key(&path); |
|
|
if let Some(invalidators) = invalidator_map.remove(&key) { |
|
|
invalidators |
|
|
.into_iter() |
|
|
.for_each(|(i, _)| invalidate(inner, report_invalidation_reason, &path, i)); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
fn invalidate_path_and_children_execute( |
|
|
inner: &DiskFileSystemInner, |
|
|
report_invalidation_reason: bool, |
|
|
invalidator_map: &mut FxHashMap<String, FxHashMap<Invalidator, Option<WriteContent>>>, |
|
|
paths: impl Iterator<Item = PathBuf>, |
|
|
) { |
|
|
for path in paths { |
|
|
let path_key = path_to_key(&path); |
|
|
for (_, invalidators) in invalidator_map.extract_if(|key, _| key.starts_with(&path_key)) { |
|
|
invalidators |
|
|
.into_iter() |
|
|
.for_each(|(i, _)| invalidate(inner, report_invalidation_reason, &path, i)); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, PartialEq, Eq, Hash)] |
|
|
pub struct InvalidateRescan { |
|
|
path: RcStr, |
|
|
} |
|
|
|
|
|
impl InvalidationReason for InvalidateRescan { |
|
|
fn kind(&self) -> Option<StaticOrArc<dyn InvalidationReasonKind>> { |
|
|
Some(StaticOrArc::Static(&INVALIDATE_RESCAN_KIND)) |
|
|
} |
|
|
} |
|
|
|
|
|
impl fmt::Display for InvalidateRescan { |
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
|
write!(f, "{} in filesystem invalidated", self.path) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
#[derive(PartialEq, Eq, Hash)] |
|
|
struct InvalidateRescanKind; |
|
|
|
|
|
static INVALIDATE_RESCAN_KIND: InvalidateRescanKind = InvalidateRescanKind; |
|
|
|
|
|
impl InvalidationReasonKind for InvalidateRescanKind { |
|
|
fn fmt( |
|
|
&self, |
|
|
reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>, |
|
|
f: &mut fmt::Formatter<'_>, |
|
|
) -> fmt::Result { |
|
|
let first_reason: &dyn InvalidationReason = &*reasons[0]; |
|
|
write!( |
|
|
f, |
|
|
"{} items in filesystem invalidated due to notify::Watcher rescan event ({}, ...)", |
|
|
reasons.len(), |
|
|
(first_reason as &dyn Any) |
|
|
.downcast_ref::<InvalidateRescan>() |
|
|
.unwrap() |
|
|
.path |
|
|
) |
|
|
} |
|
|
} |
|
|
|