diff --git a/Cargo.lock b/Cargo.lock index 20dd53f..ac00f94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -290,7 +290,7 @@ checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" [[package]] name = "netwatcher" -version = "0.8.0" +version = "0.9.0" dependencies = [ "aligned-vec", "android-build", diff --git a/Cargo.toml b/Cargo.toml index e1a37ab..6e24ca7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "netwatcher" -version = "0.8.0" +version = "0.9.0" edition = "2021" license = "MIT" description = "List network interfaces and watch for changes efficiently" diff --git a/android/app-native/Cargo.lock b/android/app-native/Cargo.lock index bc06220..1e3ebc0 100644 --- a/android/app-native/Cargo.lock +++ b/android/app-native/Cargo.lock @@ -211,7 +211,7 @@ checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" [[package]] name = "netwatcher" -version = "0.8.0" +version = "0.9.0" dependencies = [ "aligned-vec", "android-build", diff --git a/src/async_adapter.rs b/src/async_adapter.rs index f040966..a2bb370 100644 --- a/src/async_adapter.rs +++ b/src/async_adapter.rs @@ -41,7 +41,7 @@ impl AsyncFd { } } -/// Borrowed readiness source returned by an [`AsyncFdReadyGuard`]. +/// Borrowed readiness source passed to an [`AsyncFdRegistration`] drain callback. /// /// On non-Android Unix platforms this wraps the watch file descriptor. /// On other platforms the value is never used. @@ -72,18 +72,20 @@ pub trait AsyncFdAdapter { fn register(fd: AsyncFd) -> std::io::Result>; } -pub type AsyncFdReadableFuture<'a> = - Pin>> + Send + 'a>>; +/// Boxed future returned by [`AsyncFdRegistration::readable_and_drain`]. +pub type AsyncFdReadableFuture<'a> = Pin> + Send + 'a>>; /// Registered readiness source for a watch file descriptor. +/// +/// After the file descriptor becomes readable, an implementation must invoke `drain` before it +/// acknowledges the readiness event to the runtime. The callback must be invoked exactly once +/// before the returned future completes successfully, and must not be invoked if the future +/// completes with an error. pub trait AsyncFdRegistration: Send + Sync { - fn readable(&self) -> AsyncFdReadableFuture<'_>; -} - -/// Guard returned once the runtime reports the watch file descriptor as readable. -pub trait AsyncFdReadyGuard: Send { - fn fd(&self) -> AsyncFdRef<'_>; - fn clear_ready(&mut self); + fn readable_and_drain<'a>( + &'a self, + drain: &'a mut (dyn for<'fd> FnMut(AsyncFdRef<'fd>) + Send + 'a), + ) -> AsyncFdReadableFuture<'a>; } #[cfg(feature = "async-io")] @@ -101,25 +103,19 @@ impl AsyncFdAdapter for Tokio { #[cfg(all(feature = "tokio", unix, not(target_os = "android")))] impl AsyncFdRegistration for tokio::io::unix::AsyncFd { - fn readable(&self) -> AsyncFdReadableFuture<'_> { + fn readable_and_drain<'a>( + &'a self, + drain: &'a mut (dyn for<'fd> FnMut(AsyncFdRef<'fd>) + Send + 'a), + ) -> AsyncFdReadableFuture<'a> { Box::pin(async move { - let guard = self.readable().await?; - Ok(Box::new(guard) as Box) + let mut guard = self.readable().await?; + drain(AsyncFdRef::from_borrowed_fd(guard.get_inner().as_fd())); + guard.clear_ready(); + Ok(()) }) } } -#[cfg(all(feature = "tokio", unix, not(target_os = "android")))] -impl AsyncFdReadyGuard for tokio::io::unix::AsyncFdReadyGuard<'_, OwnedFd> { - fn fd(&self) -> AsyncFdRef<'_> { - AsyncFdRef::from_borrowed_fd(self.get_inner().as_fd()) - } - - fn clear_ready(&mut self) { - tokio::io::unix::AsyncFdReadyGuard::clear_ready(self); - } -} - #[cfg(all(feature = "tokio", any(windows, target_os = "android")))] impl AsyncFdAdapter for Tokio { fn register(_fd: AsyncFd) -> std::io::Result> { @@ -130,40 +126,87 @@ impl AsyncFdAdapter for Tokio { #[cfg(all(feature = "async-io", unix, not(target_os = "android")))] impl AsyncFdAdapter for AsyncIo { fn register(fd: AsyncFd) -> io::Result> { - Ok(Box::new(AsyncIoRegistration(async_io::Async::new( - fd.into_owned_fd(), - )?))) + Ok(Box::new(async_io::Async::new(fd.into_owned_fd())?)) } } #[cfg(all(feature = "async-io", unix, not(target_os = "android")))] -struct AsyncIoRegistration(async_io::Async); - -#[cfg(all(feature = "async-io", unix, not(target_os = "android")))] -struct AsyncIoReadyGuard<'a>(&'a async_io::Async); - -#[cfg(all(feature = "async-io", unix, not(target_os = "android")))] -impl AsyncFdRegistration for AsyncIoRegistration { - fn readable(&self) -> AsyncFdReadableFuture<'_> { +impl AsyncFdRegistration for async_io::Async { + fn readable_and_drain<'a>( + &'a self, + drain: &'a mut (dyn for<'fd> FnMut(AsyncFdRef<'fd>) + Send + 'a), + ) -> AsyncFdReadableFuture<'a> { Box::pin(async move { - self.0.readable().await?; - Ok(Box::new(AsyncIoReadyGuard(&self.0)) as Box) + self.readable().await?; + drain(AsyncFdRef::from_borrowed_fd(self.get_ref().as_fd())); + Ok(()) }) } } -#[cfg(all(feature = "async-io", unix, not(target_os = "android")))] -impl AsyncFdReadyGuard for AsyncIoReadyGuard<'_> { - fn fd(&self) -> AsyncFdRef<'_> { - AsyncFdRef::from_borrowed_fd(self.0.get_ref().as_fd()) - } - - fn clear_ready(&mut self) {} -} - #[cfg(all(feature = "async-io", any(windows, target_os = "android")))] impl AsyncFdAdapter for AsyncIo { fn register(_fd: AsyncFd) -> std::io::Result> { unreachable!("async-io AsyncFd registration is not used on this platform") } } + +#[cfg(all( + test, + unix, + not(target_os = "android"), + any(feature = "async-io", feature = "tokio") +))] +mod tests { + use std::os::fd::{AsRawFd, OwnedFd}; + use std::os::unix::net::UnixDatagram; + + use nix::errno::Errno; + use nix::sys::socket::{recv, MsgFlags}; + + use super::{AsyncFd, AsyncFdAdapter}; + + async fn registration_drains_and_rearms() { + let (reader, writer) = UnixDatagram::pair().unwrap(); + reader.set_nonblocking(true).unwrap(); + let registration = A::register(AsyncFd::from_owned_fd(OwnedFd::from(reader))).unwrap(); + + for expected_drain_count in 1..=2 { + writer.send(&[expected_drain_count]).unwrap(); + + let mut drain_count = 0; + registration + .readable_and_drain(&mut |fd| { + let mut buffer = [0_u8; 8]; + loop { + match recv(fd.as_fd().as_raw_fd(), &mut buffer, MsgFlags::empty()) { + Ok(_) => continue, + Err(Errno::EAGAIN) => break, + Err(err) => panic!("failed to drain test socket: {err}"), + } + } + drain_count += 1; + }) + .await + .unwrap(); + + assert_eq!(drain_count, 1); + } + } + + #[cfg(feature = "tokio")] + #[test] + fn tokio_registration_drains_and_rearms() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(registration_drains_and_rearms::()); + } + + #[cfg(feature = "async-io")] + #[test] + fn async_io_registration_drains_and_rearms() { + async_io::block_on(registration_drains_and_rearms::()); + } +} diff --git a/src/watch_fd.rs b/src/watch_fd.rs index 0f4d599..f5eb586 100644 --- a/src/watch_fd.rs +++ b/src/watch_fd.rs @@ -46,16 +46,18 @@ impl AsyncWatch { } loop { - let mut ready = match self.registration.readable().await { - Ok(ready) => ready, + let drain_event_socket = self.drain_event_socket; + let readiness = self + .registration + .readable_and_drain(&mut |fd| drain_event_socket(fd.as_fd())) + .await; + match readiness { + Ok(()) => {} Err(_) => { self.readiness_failed = true; return std::future::pending().await; } - }; - - (self.drain_event_socket)(ready.fd().as_fd()); - ready.clear_ready(); + } let Ok(new_list) = crate::list::list_interfaces() else { continue;