Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: share inotify fd across watchers #26200

Merged
merged 7 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ once_cell.workspace = true
percent-encoding.workspace = true
regex.workspace = true
rustyline = { workspace = true, features = ["custom-bindings"] }
same-file = "1.0.6"
serde.workspace = true
signal-hook = "0.3.17"
signal-hook-registry = "1.4.0"
Expand Down
2 changes: 1 addition & 1 deletion runtime/js/40_fs_events.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class FsWatcher {

constructor(paths, options) {
const { recursive } = options;
this.#rid = op_fs_events_open({ recursive, paths });
this.#rid = op_fs_events_open(recursive, paths);
}

unref() {
Expand Down
92 changes: 69 additions & 23 deletions runtime/ops/fs_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ use notify::EventKind;
use notify::RecommendedWatcher;
use notify::RecursiveMode;
use notify::Watcher;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;
use std::cell::RefCell;
use std::convert::From;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use tokio::sync::mpsc;

deno_core::extension!(
Expand All @@ -35,8 +36,6 @@ deno_core::extension!(
);

struct FsEventsResource {
#[allow(unused)]
watcher: RecommendedWatcher,
receiver: AsyncRefCell<mpsc::Receiver<Result<FsEvent, AnyError>>>,
cancel: CancelHandle,
}
Expand All @@ -59,7 +58,7 @@ impl Resource for FsEventsResource {
///
/// Feel free to expand this struct as long as you can add tests to demonstrate
/// the complexity.
#[derive(Serialize, Debug)]
#[derive(Serialize, Debug, Clone)]
struct FsEvent {
kind: &'static str,
paths: Vec<PathBuf>,
Expand Down Expand Up @@ -93,43 +92,90 @@ impl From<NotifyEvent> for FsEvent {
}
}

#[derive(Deserialize)]
pub struct OpenArgs {
recursive: bool,
type WatchSender = (Vec<String>, mpsc::Sender<Result<FsEvent, AnyError>>);

struct WatcherState {
senders: Arc<Mutex<Vec<WatchSender>>>,
watcher: RecommendedWatcher,
}

fn starts_with_canonicalized(path: &Path, prefix: &str) -> bool {
#[allow(clippy::disallowed_methods)]
let path = path.canonicalize().ok();
#[allow(clippy::disallowed_methods)]
let prefix = std::fs::canonicalize(prefix).ok();
match (path, prefix) {
(Some(path), Some(prefix)) => path.starts_with(prefix),
_ => false,
}
}

fn start_watcher(
state: &mut OpState,
paths: Vec<String>,
sender: mpsc::Sender<Result<FsEvent, AnyError>>,
) -> Result<(), AnyError> {
if let Some(watcher) = state.try_borrow_mut::<WatcherState>() {
watcher.senders.lock().push((paths, sender));
return Ok(());
}

let senders = Arc::new(Mutex::new(vec![(paths, sender)]));

let sender_clone = senders.clone();
let watcher: RecommendedWatcher = Watcher::new(
move |res: Result<NotifyEvent, NotifyError>| {
let res2 = res.map(FsEvent::from).map_err(AnyError::from);
for (paths, sender) in sender_clone.lock().iter() {
// Ignore result, if send failed it means that watcher was already closed,
// but not all messages have been flushed.

// Only send the event if the path matches one of the paths that the user is watching
if let Ok(event) = &res2 {
if paths.iter().any(|path| {
event.paths.iter().any(|event_path| {
same_file::is_same_file(event_path, path).unwrap_or(false)
|| starts_with_canonicalized(event_path, path)
})
Comment on lines +147 to +150
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we be smarter here? Iterating over all paths specified for each watcher can be costly. Maybe a hash set would work better here to try and match file path directly?

Copy link
Member Author

@littledivy littledivy Oct 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two watchers can be watching the same file/directory so HashSet won't work.

That would work but won't be fast for most cases that require high file watchers (recursive) because we need to fallback when paths are inside directory or symlinked.

}) {
let _ = sender.try_send(Ok(event.clone()));
}
}
}
},
Default::default(),
)?;

state.put::<WatcherState>(WatcherState { watcher, senders });

Ok(())
}

#[op2]
#[smi]
fn op_fs_events_open(
state: &mut OpState,
#[serde] args: OpenArgs,
recursive: bool,
#[serde] paths: Vec<String>,
) -> Result<ResourceId, AnyError> {
let (sender, receiver) = mpsc::channel::<Result<FsEvent, AnyError>>(16);
let sender = Mutex::new(sender);
let mut watcher: RecommendedWatcher = Watcher::new(
move |res: Result<NotifyEvent, NotifyError>| {
let res2 = res.map(FsEvent::from).map_err(AnyError::from);
let sender = sender.lock();
// Ignore result, if send failed it means that watcher was already closed,
// but not all messages have been flushed.
let _ = sender.try_send(res2);
},
Default::default(),
)?;
let recursive_mode = if args.recursive {

start_watcher(state, paths.clone(), sender)?;

let recursive_mode = if recursive {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
};
for path in &args.paths {
for path in &paths {
let path = state
.borrow_mut::<PermissionsContainer>()
.check_read(path, "Deno.watchFs()")?;
watcher.watch(&path, recursive_mode)?;

let watcher = state.borrow_mut::<WatcherState>();
watcher.watcher.watch(&path, recursive_mode)?;
}
let resource = FsEventsResource {
watcher,
receiver: AsyncRefCell::new(receiver),
cancel: Default::default(),
};
Expand Down
Loading