use std::collections::HashMap;
use std::io;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::Duration;
use wtf_string::Wtf16String;
use windows_sys::Win32::Foundation::ERROR_DIRECTORY;
use windows_threadpool_sys::timer::ThreadpoolTimer;
use crate::directory::{DirectoryHandle, DirectoryId, FaultDetail, OpenFailure, classify_detail};
use crate::queue::{
DEFAULT_BOUND, Notification, Outcome, Receiver, Reservation, Sender, StandingSlot, WatchId,
channel_with_bound,
};
use crate::retry::{FaultOperation, clamp};
use crate::route::{Route, RouteScope};
use crate::servicing::{Rejected, Servicer};
use crate::session::Session;
use crate::watch::{RetryMode, VolumeChangeDecision, WatchOptions};
use crate::watcher::DirectoryWatcher;
pub(crate) enum Request {
Subscribe {
watch: WatchId,
path: PathBuf,
options: WatchOptions,
sink: Sender,
completion: Reservation,
fault_slot: Option<StandingSlot>,
},
Cancel {
watch: WatchId,
completion: Reservation,
},
Retry {
watch: WatchId,
},
Answer {
watch: WatchId,
delay: Option<Duration>,
},
AnswerVolumeChange {
watch: WatchId,
decision: VolumeChangeDecision,
},
}
impl std::fmt::Debug for Request {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Request::Subscribe {
watch,
path,
options,
..
} => f
.debug_struct("Subscribe")
.field("watch", watch)
.field("path", path)
.field("options", options)
.finish_non_exhaustive(),
Request::Cancel { watch, .. } => f
.debug_struct("Cancel")
.field("watch", watch)
.finish_non_exhaustive(),
Request::Retry { watch } => f.debug_struct("Retry").field("watch", watch).finish(),
Request::Answer { watch, delay } => f
.debug_struct("Answer")
.field("watch", watch)
.field("delay", delay)
.finish(),
Request::AnswerVolumeChange { watch, decision } => f
.debug_struct("AnswerVolumeChange")
.field("watch", watch)
.field("decision", decision)
.finish(),
}
}
}
enum Subscription {
Pending {
path: PathBuf,
options: WatchOptions,
sink: Sender,
retry_timer: ThreadpoolTimer,
fault_slot: Option<StandingSlot>,
terminal: Option<Reservation>,
awaiting_answer: bool,
},
Routed {
directory: DirectoryId,
options: WatchOptions,
},
}
impl Subscription {
fn options(&self) -> WatchOptions {
match self {
Subscription::Pending { options, .. } | Subscription::Routed { options, .. } => {
*options
}
}
}
}
#[derive(Default)]
pub(crate) struct Resident {
subscriptions: HashMap<WatchId, Subscription>,
directories: HashMap<DirectoryId, DirectoryWatcher>,
}
pub(crate) fn rekey(resident: &Mutex<Resident>, old: DirectoryId, new: DirectoryId) {
if old == new {
return;
}
let mut state = lock(resident);
let Some(watcher) = state.directories.remove(&old) else {
return;
};
let existing = state.directories.remove(&new);
if let Some(existing) = &existing {
for route in existing.take_routes() {
match DirectoryHandle::open(watcher.path()) {
Ok(handle) => watcher.add_route(route, handle),
Err(error) => {
log::warn!(
"windows-file-watcher: could not migrate a route from a redundant \
watcher during identity-collision coalescing: {error}"
);
let detail = error.detail();
let _ = route.sink.send(Notification::Completion {
watch: route.watch,
outcome: Outcome::Failed { detail },
});
state.subscriptions.remove(&route.watch);
}
}
}
}
state.directories.insert(new, watcher);
for subscription in state.subscriptions.values_mut() {
if let Subscription::Routed { directory, .. } = subscription
&& *directory == old
{
*directory = new;
}
}
drop(state);
drop(existing);
}
pub(crate) struct Core {
servicer: Servicer<Request>,
next_watch: AtomicU64,
}
impl Core {
pub(crate) fn submit(&self, request: Request) -> Result<(), Rejected<Request>> {
self.servicer.submit(request)
}
pub(crate) fn is_open(&self) -> bool {
self.servicer.is_open()
}
pub(crate) fn next_watch(&self) -> WatchId {
WatchId::from_raw(self.next_watch.fetch_add(1, Ordering::Relaxed))
}
}
pub struct Monitor {
core: Arc<Core>,
resident: Arc<Mutex<Resident>>,
}
impl Monitor {
pub fn new() -> io::Result<Self> {
let resident = Arc::new(Mutex::new(Resident::default()));
let core_cell: Arc<OnceLock<Weak<Core>>> = Arc::new(OnceLock::new());
let state = Arc::clone(&resident);
let resident_weak = Arc::downgrade(&resident);
let core_ref = Arc::clone(&core_cell);
let servicer = Servicer::new(move |request: Request| {
service(&state, &resident_weak, &core_ref, request)
})?;
let core = Arc::new(Core {
servicer,
next_watch: AtomicU64::new(1),
});
core_cell
.set(Arc::downgrade(&core))
.unwrap_or_else(|_| unreachable!("the core cell is set exactly once, here"));
Ok(Self { core, resident })
}
#[must_use]
pub fn session(&self) -> (Session, Receiver) {
self.session_with_bound(DEFAULT_BOUND)
}
#[must_use]
pub fn session_with_bound(&self, bound: NonZeroUsize) -> (Session, Receiver) {
let (sender, receiver) = channel_with_bound(bound);
(Session::new(Arc::clone(&self.core), sender), receiver)
}
pub fn quiesce(&self) {
self.core.servicer.quiesce();
}
#[must_use]
pub fn watcher_count(&self) -> usize {
lock(&self.resident).subscriptions.len()
}
#[must_use]
pub fn retry_mode(&self, watch: WatchId) -> Option<RetryMode> {
lock(&self.resident)
.subscriptions
.get(&watch)
.map(|subscription| subscription.options().retry)
}
#[must_use]
pub fn is_registered(&self, watch: WatchId) -> bool {
lock(&self.resident).subscriptions.contains_key(&watch)
}
#[must_use]
pub fn is_watching(&self, watch: WatchId) -> bool {
let resident = lock(&self.resident);
let Some(Subscription::Routed { directory, .. }) = resident.subscriptions.get(&watch)
else {
return false;
};
resident
.directories
.get(directory)
.is_some_and(|watcher| watcher.stop_reason().is_none())
}
#[must_use]
pub fn stop_reason(&self, watch: WatchId) -> Option<io::Error> {
let resident = lock(&self.resident);
let Some(Subscription::Routed { directory, .. }) = resident.subscriptions.get(&watch)
else {
return None;
};
resident
.directories
.get(directory)
.and_then(DirectoryWatcher::stop_reason)
}
#[must_use]
pub fn is_faulted(&self, watch: WatchId) -> Option<bool> {
let resident = lock(&self.resident);
match resident.subscriptions.get(&watch)? {
Subscription::Pending { .. } => Some(true),
Subscription::Routed { directory, .. } => resident
.directories
.get(directory)
.map(DirectoryWatcher::is_faulted),
}
}
#[must_use]
pub fn fault_detail(&self, watch: WatchId) -> Option<FaultDetail> {
let resident = lock(&self.resident);
let Some(Subscription::Routed { directory, .. }) = resident.subscriptions.get(&watch)
else {
return None;
};
resident
.directories
.get(directory)
.and_then(DirectoryWatcher::fault_detail)
}
#[must_use]
pub fn is_running(&self) -> bool {
self.core.is_open()
}
pub fn shut_down(&self) {
self.core.servicer.shut_down();
let mut resident = lock(&self.resident);
let directories = std::mem::take(&mut resident.directories);
resident.subscriptions.clear();
drop(resident);
drop(directories);
}
#[cfg(test)]
pub(crate) fn directory_count(&self) -> usize {
lock(&self.resident).directories.len()
}
}
fn service(
resident: &Mutex<Resident>,
resident_weak: &Weak<Mutex<Resident>>,
core_ref: &Arc<OnceLock<Weak<Core>>>,
request: Request,
) {
match request {
Request::Subscribe {
watch,
path,
options,
sink,
completion,
fault_slot,
} => {
let outcome = subscribe(
resident,
resident_weak,
core_ref,
watch,
path,
options,
sink,
fault_slot,
);
completion.send(Notification::Completion { watch, outcome });
}
Request::Cancel { watch, completion } => {
let torn_down = {
let mut state = lock(resident);
let mut torn_down = None;
if let Some(Subscription::Routed { directory, .. }) =
state.subscriptions.remove(&watch)
&& let Some((remaining, stopped)) = state
.directories
.get(&directory)
.map(|watcher| watcher.remove_route(watch))
{
for extra in stopped {
state.subscriptions.remove(&extra);
}
if remaining == 0 {
torn_down = state.directories.remove(&directory);
}
}
torn_down
};
drop(torn_down);
completion.send(Notification::Completion {
watch,
outcome: Outcome::Cancelled,
});
}
Request::Retry { watch } => retry_pending(resident, resident_weak, core_ref, watch),
Request::Answer { watch, delay } => answer(resident, watch, delay),
Request::AnswerVolumeChange { watch, decision } => {
answer_volume_change(resident, watch, decision);
}
}
}
fn answer(resident: &Mutex<Resident>, watch: WatchId, delay: Option<Duration>) {
let mut state = lock(resident);
if let Some(Subscription::Pending {
awaiting_answer, ..
}) = state.subscriptions.get(&watch)
&& *awaiting_answer
{
let resolved = delay.unwrap_or_else(|| FaultOperation::Open.default_delay());
if let Some(Subscription::Pending {
retry_timer,
awaiting_answer,
..
}) = state.subscriptions.get_mut(&watch)
{
*awaiting_answer = false;
retry_timer.set_after(clamp(resolved));
}
return;
}
if let Some(Subscription::Routed { directory, .. }) = state.subscriptions.get(&watch)
&& let Some(watcher) = state.directories.get(directory)
{
watcher.answer(watch, delay);
}
}
fn answer_volume_change(
resident: &Mutex<Resident>,
watch: WatchId,
decision: VolumeChangeDecision,
) {
let torn_down = {
let mut state = lock(resident);
let Some(Subscription::Routed { directory, .. }) = state.subscriptions.get(&watch) else {
return;
};
let directory = *directory;
let Some((remaining, stopped)) = state
.directories
.get(&directory)
.and_then(|watcher| watcher.answer_volume_change(watch, decision))
else {
return;
};
for stopped_watch in &stopped {
state.subscriptions.remove(stopped_watch);
}
if remaining == 0 {
state.directories.remove(&directory)
} else {
None
}
};
drop(torn_down);
}
enum Opened {
Handle {
handle: DirectoryHandle,
scope: RouteScope,
opened_path: PathBuf,
},
Pending(FaultDetail),
Failed(FaultDetail),
}
fn open_target(path: &std::path::Path, subtree: bool) -> Opened {
match DirectoryHandle::open(path) {
Ok(handle) => Opened::Handle {
handle,
scope: RouteScope::Directory { subtree },
opened_path: path.to_path_buf(),
},
Err(error) if error.failure() == OpenFailure::NotADirectory => open_file_target(path),
Err(error) if error.failure().is_retryable() => Opened::Pending(error.detail()),
Err(error) => Opened::Failed(error.detail()),
}
}
fn open_file_target(path: &std::path::Path) -> Opened {
let (Some(parent), Some(leaf)) = (path.parent(), path.file_name()) else {
return Opened::Failed(FaultDetail::synthetic(
OpenFailure::NotADirectory,
ERROR_DIRECTORY,
));
};
let parent = if parent.as_os_str().is_empty() {
std::path::Path::new(".")
} else {
parent
};
match DirectoryHandle::open(parent) {
Ok(handle) => Opened::Handle {
handle,
scope: RouteScope::File {
leaf: Wtf16String::from_os_str(leaf),
},
opened_path: parent.to_path_buf(),
},
Err(error) if error.failure().is_retryable() => Opened::Pending(error.detail()),
Err(error) => Opened::Failed(error.detail()),
}
}
fn awaits_open_answer(retry: RetryMode, has_fault_slot: bool) -> bool {
retry == RetryMode::Interactive && has_fault_slot
}
fn make_retry_timer(
core_ref: &Arc<OnceLock<Weak<Core>>>,
watch: WatchId,
) -> io::Result<ThreadpoolTimer> {
let core_ref = Arc::clone(core_ref);
ThreadpoolTimer::new(
move |_firing| {
if let Some(core) = core_ref.get().and_then(Weak::upgrade) {
let _ = core.submit(Request::Retry { watch });
}
},
None,
)
}
#[allow(clippy::too_many_arguments)]
fn park_pending(
resident: &Mutex<Resident>,
core_ref: &Arc<OnceLock<Weak<Core>>>,
watch: WatchId,
path: PathBuf,
options: WatchOptions,
sink: Sender,
fault_slot: Option<StandingSlot>,
detail: FaultDetail,
) -> io::Result<()> {
let retry_timer = make_retry_timer(core_ref, watch)?;
let terminal = sink.reserve();
let awaiting_answer = awaits_open_answer(options.retry, fault_slot.is_some());
let mut state = lock(resident);
state.subscriptions.insert(
watch,
Subscription::Pending {
path,
options,
sink,
retry_timer,
fault_slot,
terminal,
awaiting_answer,
},
);
if let Some(Subscription::Pending {
retry_timer,
fault_slot,
..
}) = state.subscriptions.get(&watch)
{
if awaiting_answer {
if let Some(slot) = fault_slot {
slot.send(Notification::RetryQuestion {
watch,
operation: FaultOperation::Open,
detail,
});
}
} else {
retry_timer.set_after(clamp(FaultOperation::Open.default_delay()));
}
}
Ok(())
}
fn should_report_established(report_liveness: bool, is_faulted: bool) -> bool {
report_liveness && !is_faulted
}
#[allow(clippy::too_many_arguments)]
fn route_established(
resident: &Mutex<Resident>,
resident_weak: &Weak<Mutex<Resident>>,
core_ref: &Arc<OnceLock<Weak<Core>>>,
watch: WatchId,
original_path: PathBuf,
handle: DirectoryHandle,
scope: RouteScope,
opened_path: PathBuf,
options: WatchOptions,
sink: Sender,
fault_slot: Option<StandingSlot>,
) -> Routed {
let id = handle.identity();
let route = Route {
watch,
scope,
sink: sink.clone(),
retry: options.retry,
report_liveness: options.report_liveness,
on_volume_change: options.on_volume_change,
fault_slot,
};
let mut state = lock(resident);
if let Some(watcher) = state
.directories
.get(&id)
.filter(|watcher| watcher.stop_reason().is_none())
{
watcher.add_route(route, handle);
let mode = watcher.mode();
let is_faulted = watcher.is_faulted();
state.subscriptions.insert(
watch,
Subscription::Routed {
directory: id,
options,
},
);
drop(state);
if should_report_established(options.report_liveness, is_faulted) {
let _ = sink.send(Notification::Established { watch, mode });
}
return Routed::Live;
}
let stale = state.directories.remove(&id);
drop(state);
drop(stale);
match DirectoryWatcher::start(handle, opened_path, route) {
Ok(watcher) => {
watcher.bind_resident(Weak::clone(resident_weak));
let mode = watcher.mode();
let mut state = lock(resident);
state.directories.insert(id, watcher);
state.subscriptions.insert(
watch,
Subscription::Routed {
directory: id,
options,
},
);
drop(state);
if options.report_liveness {
let _ = sink.send(Notification::Established { watch, mode });
}
Routed::Live
}
Err((error, route)) => {
let detail = classify_detail(&error);
match park_pending(
resident,
core_ref,
watch,
original_path,
options,
sink,
route.fault_slot,
detail,
) {
Ok(()) => Routed::Parked,
Err(error) => Routed::ParkFailed(FaultDetail::retry_unavailable(&error)),
}
}
}
}
enum Routed {
Live,
Parked,
ParkFailed(FaultDetail),
}
fn retry_pending(
resident: &Mutex<Resident>,
resident_weak: &Weak<Mutex<Resident>>,
core_ref: &Arc<OnceLock<Weak<Core>>>,
watch: WatchId,
) {
let taken = {
let mut state = lock(resident);
match state.subscriptions.remove(&watch) {
Some(Subscription::Pending {
path,
options,
sink,
retry_timer,
fault_slot,
terminal,
..
}) => Some((path, options, sink, retry_timer, fault_slot, terminal)),
Some(other) => {
state.subscriptions.insert(watch, other);
None
}
None => None,
}
};
let Some((path, options, sink, retry_timer, fault_slot, terminal)) = taken else {
return;
};
match open_target(&path, options.subtree) {
Opened::Pending(detail) => {
let awaiting_answer = awaits_open_answer(options.retry, fault_slot.is_some());
let mut state = lock(resident);
state.subscriptions.insert(
watch,
Subscription::Pending {
path,
options,
sink,
retry_timer,
fault_slot,
terminal,
awaiting_answer,
},
);
if let Some(Subscription::Pending {
retry_timer,
fault_slot,
..
}) = state.subscriptions.get(&watch)
{
if awaiting_answer {
if let Some(slot) = fault_slot {
slot.send(Notification::RetryQuestion {
watch,
operation: FaultOperation::Open,
detail,
});
}
} else {
retry_timer.set_after(clamp(FaultOperation::Open.default_delay()));
}
}
}
Opened::Failed(detail) => {
let outcome = Outcome::Failed { detail };
match terminal {
Some(reservation) => reservation.send(Notification::Completion { watch, outcome }),
None => {
let _ = sink.send(Notification::Completion { watch, outcome });
}
}
}
Opened::Handle {
handle,
scope,
opened_path,
} => {
let outcome_sink = sink.clone();
match route_established(
resident,
resident_weak,
core_ref,
watch,
path,
handle,
scope,
opened_path,
options,
sink,
fault_slot,
) {
Routed::Live | Routed::Parked => {}
Routed::ParkFailed(detail) => {
let _ = outcome_sink.send(Notification::Completion {
watch,
outcome: Outcome::Failed { detail },
});
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn subscribe(
resident: &Mutex<Resident>,
resident_weak: &Weak<Mutex<Resident>>,
core_ref: &Arc<OnceLock<Weak<Core>>>,
watch: WatchId,
path: PathBuf,
options: WatchOptions,
sink: Sender,
fault_slot: Option<StandingSlot>,
) -> Outcome {
match open_target(&path, options.subtree) {
Opened::Pending(detail) => {
match park_pending(
resident, core_ref, watch, path, options, sink, fault_slot, detail,
) {
Ok(()) => Outcome::Establishing,
Err(error) => Outcome::Failed {
detail: FaultDetail::retry_unavailable(&error),
},
}
}
Opened::Failed(detail) => Outcome::Failed { detail },
Opened::Handle {
handle,
scope,
opened_path,
} => {
match route_established(
resident,
resident_weak,
core_ref,
watch,
path,
handle,
scope,
opened_path,
options,
sink,
fault_slot,
) {
Routed::Live => Outcome::Subscribed,
Routed::Parked => Outcome::Establishing,
Routed::ParkFailed(detail) => Outcome::Failed { detail },
}
}
}
}
impl Drop for Monitor {
fn drop(&mut self) {
self.shut_down();
}
}
impl std::fmt::Debug for Monitor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Monitor")
.field("running", &self.is_running())
.field("watchers", &self.watcher_count())
.finish_non_exhaustive()
}
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|poison| poison.into_inner())
}
#[cfg(test)]
mod tests;