diff --git a/alioth/src/sync/notifier/notifier_macos.rs b/alioth/src/sync/notifier/notifier_macos.rs index eec614c1..da38e4cb 100644 --- a/alioth/src/sync/notifier/notifier_macos.rs +++ b/alioth/src/sync/notifier/notifier_macos.rs @@ -17,6 +17,7 @@ use std::io::{ErrorKind, Result}; use std::os::fd::{FromRawFd, OwnedFd}; use std::os::unix::io::AsRawFd; use std::ptr::{null, null_mut}; +use std::sync::atomic::{AtomicBool, Ordering}; use mio::event::Source; use mio::{Interest, Registry, Token}; @@ -27,6 +28,7 @@ use crate::ffi; pub struct Notifier { fd: OwnedFd, registered: Option<(Token, OwnedFd)>, + pending: AtomicBool, } impl Notifier { @@ -34,12 +36,14 @@ impl Notifier { Ok(Notifier { fd: File::open("/dev/null")?.into(), registered: None, + pending: AtomicBool::new(false), }) } pub fn notify(&self) -> Result<()> { let Some((token, kqfd)) = &self.registered else { - return Err(ErrorKind::NotFound.into()); + self.pending.store(true, Ordering::Release); + return Ok(()); }; let event = libc::kevent { ident: self.fd.as_raw_fd() as _, @@ -71,6 +75,10 @@ impl Source for Notifier { ffi!(unsafe { libc::kevent(kqfd.as_raw_fd(), &event, 1, null_mut(), 0, null()) })?; self.registered = Some((token, kqfd)); + if *self.pending.get_mut() { + self.notify()?; + *self.pending.get_mut() = false; + } Ok(()) } diff --git a/alioth/src/sync/notifier/notifier_test.rs b/alioth/src/sync/notifier/notifier_test.rs index 83bb757c..84f41739 100644 --- a/alioth/src/sync/notifier/notifier_test.rs +++ b/alioth/src/sync/notifier/notifier_test.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::time::Duration; + use assert_matches::assert_matches; use mio::{Events, Interest, Poll, Token}; @@ -42,3 +44,40 @@ fn test_notifier() { poll.registry().deregister(&mut n1).unwrap(); poll.registry().deregister(&mut n2).unwrap(); } + +#[test] +fn test_notifier_before_register() { + let mut n = Notifier::new().unwrap(); + let mut idle = Notifier::new().unwrap(); + + n.notify().unwrap(); + + let mut poll = Poll::new().unwrap(); + poll.registry() + .register(&mut n, Token(1), Interest::READABLE) + .unwrap(); + poll.registry() + .register(&mut idle, Token(2), Interest::READABLE) + .unwrap(); + + let mut events = Events::with_capacity(8); + poll.poll(&mut events, Some(Duration::from_secs(1))) + .unwrap(); + + let tokens: Vec<_> = events.iter().map(|e| e.token()).collect(); + assert_eq!(tokens, [Token(1)]); + + poll.registry().deregister(&mut n).unwrap(); + n.notify().unwrap(); + poll.registry() + .register(&mut n, Token(3), Interest::READABLE) + .unwrap(); + + poll.poll(&mut events, Some(Duration::from_secs(1))) + .unwrap(); + let tokens: Vec<_> = events.iter().map(|e| e.token()).collect(); + assert_eq!(tokens, [Token(3)]); + + poll.registry().deregister(&mut n).unwrap(); + poll.registry().deregister(&mut idle).unwrap(); +}