File size: 27,258 Bytes
1e92f2d | 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | 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>>,
/// Array of paths that should not notify invalidations.
/// `notify` currently doesn't support unwatching subpaths from the root,
/// so underlying we still watches filesystem event but only skips to
/// invalidate.
ignored_subpaths: Vec<PathBuf>,
/// Keeps track of which directories are currently watched. This is only
/// used on OSs that doesn't support recursive watching.
#[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()
}
}
/// Called after a rescan in case a previously watched-but-deleted directory was recreated.
#[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() {
// TODO: Report diagnostics if this error happens
let _ = self.start_watching_dir(&mut watcher, &dir_path, root_path);
}
}
/// Called when a new directory is found in a parent directory we're watching.
#[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();
// TODO: Also restore any watchers for children of this directory
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(())
}
/// Private helper, assumes that the path has already been added to `self.watching`.
#[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; // inner import due to conditional compilation
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,
..
} => {
// The path was probably deleted before we could process the event. That's
// okay, just make sure we're watching the parent directory, so we can know
// if it gets recreated.
let Some(parent_path) = path.parent() else {
// this should never happen as we break before we reach the root path
return err_with_context(err);
};
if parent_path == root_path {
// assume there's already a root watcher
break;
}
if !self.watching.insert(parent_path.to_owned()) {
// we're already watching the parent path!
break;
}
path = parent_path;
}
_ => return err_with_context(err),
}
}
}
Ok(())
}
/// Create a watcher and start watching by creating `debounced` watcher
/// via `full debouncer`
///
/// `notify` provides 2 different debouncer implementations, `-full`
/// provides below differences for the easy of use:
///
/// - Only emits a single Rename event if the rename From and To events can be matched
/// - Merges multiple Rename events
/// - Takes Rename events into account and updates paths for events that occurred before the
/// rename event, but which haven't been emitted, yet
/// - Optionally keeps track of the file system IDs all files and stitches rename events
/// together (FSevents, Windows)
/// - Emits only one Remove event when deleting a directory (inotify)
/// - Doesn't emit duplicate create events
/// - Doesn't emit Modify events after a Create event
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(());
}
// Create a channel to receive the events.
let (tx, rx) = channel();
// Create a watcher object, delivering debounced events.
// The notification back-end is selected based on the platform.
let config = Config::default();
// we should track and invalidate each part of a symlink chain ourselves in turbo-tasks-fs
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())?)
};
// Macos and Windows provide efficient recursive directory watchers. On other platforms, we
// only track the directories we need: https://github.com/vercel/turborepo/pull/4100
#[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)?;
}
// We need to invalidate all reads that happened before watching
// Best is to start_watching before starting to read
{
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);
// thread will detect the stop because the channel is disconnected
}
}
/// Internal thread that processes the events from the watcher
/// and invalidates the cache.
///
/// Should only be called once from `start_watching`.
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));
// this inner loop batches events using `try_recv`
loop {
match event_result {
Ok(Ok(event)) => {
// TODO: We might benefit from some user-facing diagnostics if it rescans
// occur frequently (i.e. more than X times in Y minutes)
//
// You can test rescans on Linux by reducing the inotify queue to something
// really small:
//
// ```
// echo 3 | sudo tee /proc/sys/fs/inotify/max_queued_events
// ```
if event.need_rescan() {
let _lock = inner.invalidation_lock.blocking_write();
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
// we can't narrow this down to a smaller set of paths: Rescan
// events (at least when tested on Linux) come with no `paths`, and
// we use only one global `notify::Watcher` instance.
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();
}
// no need to process the rest of the batch as we just
// invalidated everything
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() {
// this event isn't useful, but keep trying to process the batch
event_result = rx.try_recv();
continue;
}
// [NOTE] there is attrs in the `Event` struct, which contains few
// more metadata like process_id who triggered the event,
// or the source we may able to utilize later.
match event.kind {
// [NOTE] Observing `ModifyKind::Metadata(MetadataKind::Any)` is
// not a mistake, fix for PACK-2437.
// In here explicitly subscribes to the `ModifyKind::Data` which
// indicates file content changes - in case of fsevents backend,
// this is `kFSEventStreamEventFlagItemModified`.
// Also meanwhile we subscribe to ModifyKind::Metadata as well.
// This is due to in some cases fsevents does not emit explicit
// kFSEventStreamEventFlagItemModified kernel events,
// but only emits kFSEventStreamEventFlagItemInodeMetaMod. While
// this could cause redundant invalidation,
// it's the way to reliably detect file content changes.
// ref other implementation, i.e libuv does same thing to
// trigger UV_CHANEGS https://github.com/libuv/libuv/commit/73cf3600d75a5884b890a1a94048b8f3f9c66876#diff-e12fdb1f404f1c97bbdcc0956ac90d7db0d811d9fa9ca83a3deef90c937a486cR95-R99
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));
}
});
}
// A single event emitted with both the `From` and `To` paths.
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
// For the rename::both, notify provides an array of paths
// in given order
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 {
// If we hit here, we expect this as a bug either in
// notify or system weirdness.
panic!(
"Rename event does not contain source and destination \
paths {paths:#?}"
);
}
}
// We expect `RenameMode::Both` to cover most of the cases we
// need to invalidate,
// but we also check other RenameModes
// to cover cases where notify couldn't match the two rename
// events.
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 => {
// ignored
}
}
}
// Error raised by notify watcher itself
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) => {
// Sender has been disconnected
// which means DiskFileSystem has been dropped
// exit thread
break 'outer;
}
Err(TryRecvError::Empty) => {
// Linux watching is too fast, so we need to throttle it a bit to avoid
// reading wip files
#[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();
}
// We need to start watching first before invalidating the changed paths...
// This is only needed on platforms we don't do recursive watching on:
// https://github.com/vercel/turborepo/pull/4100
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
for path in batched_new_paths.drain() {
// TODO: Report diagnostics if this error happens
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));
}
}
}
/// Invalidation was caused by a watcher rescan event. This will likely invalidate *every* watched
/// file.
#[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)
}
}
/// [Invalidation kind][InvalidationReasonKind] for [`InvalidateRescan`].
#[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
)
}
}
|