coreshift_core/reactor/mod.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/
4
5//! Asynchronous event reactor.
6//!
7//! This module provides a lightweight wrapper around Linux `epoll` for
8//! multiplexing I/O events. It is optimized for edge-triggered monitoring.
9//! It is intentionally explicit about Linux readiness semantics rather than
10//! hiding them behind a higher-level async runtime abstraction.
11
12use crate::CoreError;
13use crate::error::syscall_ret;
14use std::io::Error as IoError;
15use std::time::Duration;
16
17#[inline(always)]
18fn errno() -> i32 {
19 IoError::last_os_error().raw_os_error().unwrap_or(0)
20}
21
22/// An owned file descriptor that closes on drop.
23///
24/// `Fd` is move-only. Constructing one from a raw descriptor transfers close
25/// ownership to `Fd`; do not also close the raw descriptor elsewhere.
26///
27/// ### Fork Safety
28/// `Fd` instances created by Core usually have `O_CLOEXEC` set. If the process
29/// forks, the descriptor will be inherited by the child but will be closed
30/// automatically upon `exec`. Callers that need a descriptor to survive `exec`
31/// must clear the flag manually.
32pub struct Fd(RawFd);
33
34use std::os::unix::io::{AsRawFd, RawFd};
35
36impl AsRawFd for Fd {
37 fn as_raw_fd(&self) -> RawFd {
38 self.0
39 }
40}
41
42impl Fd {
43 /// Wrap a raw file descriptor.
44 ///
45 /// # Errors
46 /// Returns a [`CoreError`] if the descriptor is negative.
47 #[inline(always)]
48 pub(crate) fn new(fd: RawFd, op: &'static str) -> Result<Self, CoreError> {
49 if fd < 0 {
50 Err(CoreError::sys(errno(), op))
51 } else {
52 Ok(Self(fd))
53 }
54 }
55
56 /// Wrap an owned raw file descriptor.
57 ///
58 /// # Safety
59 /// The caller must guarantee `fd` is valid, open, and uniquely owned by the
60 /// returned `Fd`. Passing a borrowed fd, or closing `fd` after this call,
61 /// can cause double-close or use-after-close bugs.
62 #[inline(always)]
63 pub unsafe fn from_owned_raw_fd(fd: RawFd, op: &'static str) -> Result<Self, CoreError> {
64 Self::new(fd, op)
65 }
66
67 /// Create a non-blocking `eventfd` with `EFD_CLOEXEC`.
68 ///
69 /// The descriptor is created with `FD_CLOEXEC` set.
70 ///
71 /// ### Errors
72 /// - `EINVAL`: `init` is invalid.
73 /// - `EMFILE`: Process limit on open file descriptors hit.
74 /// - `ENFILE`: System-wide limit on open files hit.
75 pub fn eventfd(init: u32) -> Result<Self, CoreError> {
76 let fd = unsafe { libc::eventfd(init, libc::EFD_CLOEXEC | libc::EFD_NONBLOCK) };
77 syscall_ret(fd, "eventfd")?;
78 Self::new(fd, "eventfd")
79 }
80
81 /// Create a non-blocking `timerfd` using `CLOCK_MONOTONIC` with `TFD_CLOEXEC`.
82 ///
83 /// The descriptor is created with `FD_CLOEXEC` set.
84 ///
85 /// ### Errors
86 /// - `EMFILE`: Process limit on open file descriptors hit.
87 /// - `ENFILE`: System-wide limit on open files hit.
88 /// - `ENOMEM`: Insufficient kernel memory.
89 pub fn timerfd() -> Result<Self, CoreError> {
90 let fd = unsafe {
91 libc::timerfd_create(
92 libc::CLOCK_MONOTONIC,
93 libc::TFD_CLOEXEC | libc::TFD_NONBLOCK,
94 )
95 };
96 syscall_ret(fd, "timerfd_create")?;
97 Self::new(fd, "timerfd_create")
98 }
99
100 /// Access the underlying raw file descriptor.
101 ///
102 /// NOTE: This is an escape hatch for low-level interactions. Prefer using
103 /// the safe methods on `Fd` or implementing `AsRawFd`.
104 #[inline(always)]
105 pub(crate) fn raw(&self) -> RawFd {
106 self.0
107 }
108
109 /// Duplicate this descriptor, returning a new owned `Fd`.
110 ///
111 /// Both descriptors share the same open file description, so a `dup` of
112 /// an eventfd remains a single signalable object: a write on either copy
113 /// is observed on the other. Useful for fan-out wakeups (hub keeps one
114 /// copy, a worker reactor owns another).
115 ///
116 /// ### Errors
117 /// - `EBADF`: The source descriptor is invalid.
118 /// - `EMFILE`: The process file descriptor limit is reached.
119 pub fn dup(&self) -> Result<Self, CoreError> {
120 let r = loop {
121 let d = unsafe { libc::dup(self.0) };
122 if d < 0 && errno() == libc::EINTR {
123 continue;
124 }
125 break d;
126 };
127 if r < 0 {
128 let e = errno();
129 Err(CoreError::sys(e, "dup"))
130 } else {
131 // SAFETY: `r` is a freshly duplicated owned descriptor.
132 unsafe { Self::from_owned_raw_fd(r, "dup") }
133 }
134 }
135
136 /// Perform a `dup2` syscall.
137 ///
138 /// ### Errors
139 /// - `EBADF`: The source or target file descriptor is invalid.
140 /// - `EMFILE`: The target descriptor exceeds the process limit.
141 pub fn dup2(&self, target: RawFd) -> Result<(), CoreError> {
142 loop {
143 let r = unsafe { libc::dup2(self.0, target) };
144 if r < 0 {
145 let e = errno();
146 if e == libc::EINTR {
147 continue;
148 }
149 return syscall_ret(r, "dup2");
150 }
151 return Ok(());
152 }
153 }
154
155 /// Set the `O_NONBLOCK` flag on the descriptor.
156 ///
157 /// ### Errors
158 /// - `EBADF`: The file descriptor is invalid.
159 pub fn set_nonblock(&self) -> Result<(), CoreError> {
160 let flags = unsafe { libc::fcntl(self.0, libc::F_GETFL) };
161 syscall_ret(flags, "fcntl(F_GETFL)")?;
162 let r = unsafe { libc::fcntl(self.0, libc::F_SETFL, flags | libc::O_NONBLOCK) };
163 syscall_ret(r, "fcntl(F_SETFL)")
164 }
165
166 /// Set the `FD_CLOEXEC` flag on the descriptor.
167 ///
168 /// ### Errors
169 /// - `EBADF`: The file descriptor is invalid.
170 pub fn set_cloexec(&self) -> Result<(), CoreError> {
171 let flags = unsafe { libc::fcntl(self.0, libc::F_GETFD) };
172 syscall_ret(flags, "fcntl(F_GETFD)")?;
173 let r = unsafe { libc::fcntl(self.0, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
174 syscall_ret(r, "fcntl(F_SETFD)")
175 }
176
177 /// Read bytes into a mutable slice.
178 ///
179 /// Returns `Ok(None)` if the operation would block (`EAGAIN`).
180 ///
181 /// ### Edge Cases
182 /// - **Zero-length read**: Returns `Ok(Some(0))` immediately.
183 /// - **Partial read**: Returns the number of bytes actually read.
184 ///
185 /// ### Errors
186 /// - `EBADF`: The file descriptor is invalid or not open for reading.
187 /// - `EFAULT`: `buf` points outside the process's address space.
188 /// - `EIO`: Low-level I/O error.
189 pub fn read_slice(&self, buf: &mut [u8]) -> Result<Option<usize>, CoreError> {
190 self.read_raw(buf.as_mut_ptr(), buf.len())
191 }
192
193 /// Seek to an absolute file offset.
194 ///
195 /// ### Errors
196 /// - `EBADF`: The file descriptor is not seekable.
197 /// - `EINVAL`: `offset` is invalid.
198 /// - `EOVERFLOW`: The resulting offset exceeds the off_t range.
199 pub fn seek_set(&self, offset: i64) -> Result<u64, CoreError> {
200 loop {
201 let pos = unsafe { libc::lseek(self.0, offset as libc::off_t, libc::SEEK_SET) };
202 if pos < 0 {
203 let e = errno();
204 if e == libc::EINTR {
205 continue;
206 }
207 return Err(CoreError::sys(e, "lseek"));
208 }
209 return Ok(pos as u64);
210 }
211 }
212
213 /// Write bytes from a slice.
214 ///
215 /// Returns `Ok(None)` if the operation would block (`EAGAIN`).
216 ///
217 /// ### Edge Cases
218 /// - **Zero-length write**: Returns `Ok(Some(0))` immediately.
219 /// - **Partial write**: Returns the number of bytes actually written.
220 ///
221 /// ### Errors
222 /// - `EBADF`: The file descriptor is invalid or not open for writing.
223 /// - `EFAULT`: `buf` points outside the process's address space.
224 /// - `EPIPE`: The reading end of a pipe or socket was closed.
225 pub fn write_slice(&self, buf: &[u8]) -> Result<Option<usize>, CoreError> {
226 self.write_raw(buf.as_ptr(), buf.len())
227 }
228
229 /// Read a native-endian `u64`, blocking until data is available.
230 ///
231 /// Unlike `read_u64`, this never returns `Ok(None)` — it retries on `EINTR`
232 /// and returns `Err` only on a hard I/O failure. Intended for blocking
233 /// eventfds used as inter-thread notification primitives.
234 pub fn read_u64_blocking(&self) -> Result<u64, CoreError> {
235 let mut bytes = [0u8; std::mem::size_of::<u64>()];
236 loop {
237 let n = unsafe {
238 libc::read(self.0, bytes.as_mut_ptr() as *mut libc::c_void, bytes.len())
239 };
240 if n == bytes.len() as isize {
241 return Ok(u64::from_ne_bytes(bytes));
242 }
243 if n < 0 {
244 let e = errno();
245 if e == libc::EINTR { continue; }
246 return Err(CoreError::sys(e, "read_u64_blocking"));
247 }
248 return Err(CoreError::sys(libc::EIO, "read_u64_blocking:short_read"));
249 }
250 }
251
252 /// Read a native-endian `u64`.
253 ///
254 /// Returns `Ok(None)` if the operation would block (`EAGAIN`).
255 pub fn read_u64(&self) -> Result<Option<u64>, CoreError> {
256 let mut bytes = [0u8; std::mem::size_of::<u64>()];
257 match self.read_slice(&mut bytes)? {
258 Some(n) if n == bytes.len() => Ok(Some(u64::from_ne_bytes(bytes))),
259 Some(_) => Err(CoreError::sys(libc::EIO, "read_u64")),
260 None => Ok(None),
261 }
262 }
263
264 /// Write a native-endian `u64`.
265 ///
266 /// Returns `Ok(None)` if the operation would block (`EAGAIN`).
267 pub fn write_u64(&self, value: u64) -> Result<Option<usize>, CoreError> {
268 self.write_slice(&value.to_ne_bytes())
269 }
270
271 /// Arm or disarm a one-shot `timerfd`.
272 ///
273 /// Passing `None` disarms the timer. Zero durations are rounded up to one
274 /// nanosecond so the timer still expires.
275 ///
276 /// ### Errors
277 /// - `EBADF`: The file descriptor is invalid.
278 /// - `EINVAL`: The duration is invalid or not supported by the kernel.
279 pub fn set_timer_oneshot(&self, delay: Option<Duration>) -> Result<(), CoreError> {
280 let mut spec: libc::itimerspec = unsafe { std::mem::zeroed() };
281 if let Some(delay) = delay {
282 let delay = delay.max(Duration::from_nanos(1));
283 spec.it_value.tv_sec = delay.as_secs() as libc::time_t;
284 spec.it_value.tv_nsec = delay.subsec_nanos() as libc::c_long;
285 }
286
287 let ret = unsafe { libc::timerfd_settime(self.raw(), 0, &spec, std::ptr::null_mut()) };
288 syscall_ret(ret, "timerfd_settime")
289 }
290
291 /// Read bytes into a raw buffer.
292 ///
293 /// Internal callers must ensure `buf` points to a valid writable region of
294 /// at least `count` bytes.
295 ///
296 /// Returns `Ok(None)` if the operation would block (`EAGAIN`).
297 pub(crate) fn read_raw(&self, buf: *mut u8, count: usize) -> Result<Option<usize>, CoreError> {
298 loop {
299 let n = unsafe { libc::read(self.0, buf as *mut libc::c_void, count) };
300 if n < 0 {
301 let e = errno();
302 if e == libc::EINTR {
303 continue;
304 }
305 if e == libc::EAGAIN || e == libc::EWOULDBLOCK {
306 return Ok(None);
307 }
308 return Err(CoreError::sys(e, "read"));
309 }
310 return Ok(Some(n as usize));
311 }
312 }
313
314 /// Write bytes from a raw buffer.
315 ///
316 /// Internal callers must ensure `buf` points to a valid readable region of
317 /// at least `count` bytes.
318 ///
319 /// Returns `Ok(None)` if the operation would block (`EAGAIN`).
320 pub(crate) fn write_raw(
321 &self,
322 buf: *const u8,
323 count: usize,
324 ) -> Result<Option<usize>, CoreError> {
325 loop {
326 let n = unsafe { libc::write(self.0, buf as *const libc::c_void, count) };
327 if n < 0 {
328 let e = errno();
329 if e == libc::EINTR {
330 continue;
331 }
332 if e == libc::EAGAIN || e == libc::EWOULDBLOCK {
333 return Ok(None);
334 }
335 return Err(CoreError::sys(e, "write"));
336 }
337 return Ok(Some(n as usize));
338 }
339 }
340}
341
342impl Drop for Fd {
343 fn drop(&mut self) {
344 if self.0 >= 0 {
345 unsafe {
346 libc::close(self.0);
347 }
348 }
349 }
350}
351
352/// An opaque token representing a registered file descriptor.
353#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
354pub struct Token(u64);
355
356#[allow(dead_code)]
357impl Token {
358 #[inline(always)]
359 pub(crate) fn new(val: u64) -> Self {
360 Self(val)
361 }
362
363 #[inline(always)]
364 pub(crate) fn val(&self) -> u64 {
365 self.0
366 }
367}
368
369/// A readiness event generated by the reactor.
370#[derive(Clone, Copy, Debug)]
371pub struct Event {
372 /// Token associated with the ready descriptor.
373 pub token: Token,
374 /// Descriptor is ready for reading (`EPOLLIN`).
375 pub readable: bool,
376 /// Descriptor has priority data or an exceptional condition (`EPOLLPRI`).
377 pub priority: bool,
378 /// Descriptor is ready for writing (`EPOLLOUT`).
379 pub writable: bool,
380 /// Indicates an error condition (`EPOLLERR`).
381 ///
382 /// NOTE: For edge-triggered readiness, an error condition often means both
383 /// readable and writable are set to ensure the handler drains the FD.
384 pub error: bool,
385 /// Indicates a remote hangup (`EPOLLHUP`).
386 pub hangup: bool,
387}
388
389const _: () = assert!(std::mem::size_of::<Event>() == 16);
390const _: () = assert!(std::mem::align_of::<Event>() == 8);
391
392/// A lightweight epoll reactor using edge-triggered monitoring (EPOLLET).
393///
394/// ### Edge-Triggered Contract
395/// Because this reactor uses EPOLLET, all handlers MUST drain their respective
396/// read or write sources until they receive an `EAGAIN` / `EWOULDBLOCK` error
397/// (represented as `Ok(None)` in the `Fd` helpers).
398///
399/// Failure to drain a source will result in missing future readiness events
400/// for that file descriptor until it is re-registered or another event occurs.
401///
402/// ### Fork Safety
403/// The `Reactor` owns an `epoll` descriptor which is `O_CLOEXEC`. After an
404/// `exec` call in a child process, the reactor and all its registrations are
405/// lost. If the child continues without `exec`, it shares the same epoll
406/// instance, which is generally unsafe and requires careful coordination.
407///
408/// # Example
409/// ```no_run
410/// # use coreshift_core::reactor::{Reactor, Fd, Event};
411/// # fn example(fd: Fd) -> Result<(), Box<dyn std::error::Error>> {
412/// let mut reactor = Reactor::new()?;
413/// let token = reactor.add(&fd, true, false)?;
414///
415/// let mut events = Vec::new();
416/// loop {
417/// reactor.wait(&mut events, 64, -1)?;
418/// for ev in &events {
419/// if ev.token == token {
420/// // Drain fd...
421/// }
422/// }
423/// }
424/// # Ok(())
425/// # }
426/// ```
427pub struct Reactor {
428 epfd: RawFd,
429 next_token: u64,
430 events_buf: Vec<libc::epoll_event>,
431 signalfd: Option<Fd>,
432 signalfd_previous_mask: Option<libc::sigset_t>,
433 /// Token for the signalfd (if initialized).
434 sigchld_token: Option<Token>,
435 /// Token for the inotify fd (if initialized).
436 inotify_token: Option<Token>,
437}
438
439impl Reactor {
440 /// Create a new epoll reactor.
441 ///
442 /// ### Errors
443 /// - `EMFILE`: Process limit on open file descriptors hit.
444 /// - `ENFILE`: System-wide limit on open files hit.
445 /// - `ENOMEM`: Insufficient kernel memory.
446 pub fn new() -> Result<Self, CoreError> {
447 let epfd = unsafe { libc::epoll_create1(libc::EPOLL_CLOEXEC) };
448 syscall_ret(epfd, "epoll_create1")?;
449 Ok(Self {
450 epfd,
451 next_token: 1,
452 events_buf: Vec::with_capacity(64),
453 signalfd: None,
454 signalfd_previous_mask: None,
455 sigchld_token: None,
456 inotify_token: None,
457 })
458 }
459
460 /// Initialize inotify and add it to the reactor.
461 ///
462 /// ### Errors
463 /// - `EMFILE`: Process limit on open file descriptors hit.
464 /// - `ENFILE`: System-wide limit on open files hit.
465 /// - `ENOMEM`: Insufficient kernel memory.
466 /// - `EPERM`: Permission denied to create inotify instance.
467 pub fn setup_inotify(&mut self) -> Result<(Fd, Token), CoreError> {
468 let fd = unsafe { libc::inotify_init1(libc::IN_CLOEXEC | libc::IN_NONBLOCK) };
469 syscall_ret(fd, "inotify_init1")?;
470
471 let fd_obj = Fd::new(fd, "inotify")?;
472 let token = self.add(&fd_obj, true, false)?;
473 self.inotify_token = Some(token);
474
475 Ok((fd_obj, token))
476 }
477
478 /// Initialize signalfd for SIGCHLD and add it to the reactor.
479 ///
480 /// The previous current-thread signal mask is restored when the reactor is
481 /// dropped.
482 ///
483 /// ### Errors
484 /// - `EBADF`: The provided file descriptor is invalid.
485 /// - `EINVAL`: Signal mask is invalid or already set up.
486 /// - `EMFILE`: Process limit on open file descriptors hit.
487 pub fn setup_signalfd(&mut self) -> Result<Token, CoreError> {
488 if self.signalfd.is_some() {
489 return Err(CoreError::sys(
490 libc::EINVAL,
491 "setup_signalfd already initialized",
492 ));
493 }
494
495 let mut mask: libc::sigset_t = unsafe { std::mem::zeroed() };
496 unsafe { libc::sigemptyset(&mut mask) };
497 unsafe { libc::sigaddset(&mut mask, libc::SIGCHLD) };
498
499 let mut previous_mask: libc::sigset_t = unsafe { std::mem::zeroed() };
500 let r = unsafe { libc::pthread_sigmask(libc::SIG_BLOCK, &mask, &mut previous_mask) };
501 if r != 0 {
502 return Err(CoreError::sys(r, "pthread_sigmask(SIG_BLOCK)"));
503 }
504
505 let sfd = unsafe { libc::signalfd(-1, &mask, libc::SFD_NONBLOCK | libc::SFD_CLOEXEC) };
506 if let Err(err) = syscall_ret(sfd, "signalfd") {
507 let _ = unsafe {
508 libc::pthread_sigmask(libc::SIG_SETMASK, &previous_mask, std::ptr::null_mut())
509 };
510 return Err(err);
511 }
512
513 let fd = Fd::new(sfd, "signalfd")?;
514 let token = match self.add(&fd, true, false) {
515 Ok(token) => token,
516 Err(err) => {
517 let _ = unsafe {
518 libc::pthread_sigmask(libc::SIG_SETMASK, &previous_mask, std::ptr::null_mut())
519 };
520 return Err(err);
521 }
522 };
523
524 self.signalfd = Some(fd);
525 self.signalfd_previous_mask = Some(previous_mask);
526 self.sigchld_token = Some(token);
527
528 Ok(token)
529 }
530
531 /// Drain the internal signalfd buffer.
532 pub fn drain_signalfd(&self) -> Result<(), CoreError> {
533 if let Some(fd) = &self.signalfd {
534 let mut buf = [0u8; std::mem::size_of::<libc::signalfd_siginfo>()];
535 loop {
536 match fd.read_slice(&mut buf) {
537 Ok(Some(n)) if n < buf.len() => break,
538 Ok(Some(_)) => continue,
539 Ok(None) => break,
540 Err(e) => return Err(e),
541 }
542 }
543 }
544 Ok(())
545 }
546
547 /// Register a file descriptor with the reactor.
548 ///
549 /// This assigns a new unique token for the descriptor and enables
550 /// edge-triggered monitoring.
551 #[inline(always)]
552 pub fn add(&mut self, fd: &Fd, readable: bool, writable: bool) -> Result<Token, CoreError> {
553 let token = Token(self.next_token);
554 self.next_token += 1;
555 self.add_with_token(fd.raw(), token, readable, writable, false)?;
556 Ok(token)
557 }
558
559 /// Register a file descriptor for priority readiness (EPOLLPRI).
560 #[inline(always)]
561 pub fn add_priority(&mut self, fd: &Fd) -> Result<Token, CoreError> {
562 let token = Token(self.next_token);
563 self.next_token += 1;
564 self.add_with_token(fd.raw(), token, false, false, true)?;
565 Ok(token)
566 }
567
568 /// Register a file descriptor with custom epoll flags.
569 ///
570 /// This allows registration with flags like `EPOLLONESHOT` or explicit
571 /// control over `EPOLLET`.
572 ///
573 /// # Example
574 /// ```no_run
575 /// # use coreshift_core::reactor::{Reactor, Fd};
576 /// let mut reactor = Reactor::new().unwrap();
577 /// let fd = Fd::eventfd(0).unwrap();
578 /// reactor.add_with_flags(&fd, (libc::EPOLLIN | libc::EPOLLONESHOT) as u32).unwrap();
579 /// ```
580 #[inline(always)]
581 pub fn add_with_flags(&mut self, fd: &Fd, flags: u32) -> Result<Token, CoreError> {
582 let token = Token(self.next_token);
583 self.next_token += 1;
584 let mut ev = libc::epoll_event {
585 events: flags,
586 u64: token.0,
587 };
588 let r = unsafe { libc::epoll_ctl(self.epfd, libc::EPOLL_CTL_ADD, fd.raw(), &mut ev) };
589 syscall_ret(r, "epoll_ctl_add")?;
590 Ok(token)
591 }
592
593 #[inline(always)]
594 pub(crate) fn add_with_token(
595 &mut self,
596 raw_fd: RawFd,
597 token: Token,
598 readable: bool,
599 writable: bool,
600 priority: bool,
601 ) -> Result<(), CoreError> {
602 let mut events = libc::EPOLLET as u32;
603 if readable {
604 events |= libc::EPOLLIN as u32;
605 }
606 if writable {
607 events |= libc::EPOLLOUT as u32;
608 }
609 if priority {
610 events |= libc::EPOLLPRI as u32;
611 }
612 let mut ev = libc::epoll_event {
613 events,
614 u64: token.0,
615 };
616 let r = unsafe { libc::epoll_ctl(self.epfd, libc::EPOLL_CTL_ADD, raw_fd, &mut ev) };
617 syscall_ret(r, "epoll_ctl_add")?;
618 Ok(())
619 }
620
621 /// Remove a file descriptor from the reactor.
622 #[inline(always)]
623 pub fn del(&self, fd: &Fd) -> Result<(), CoreError> {
624 self.del_raw(fd.raw())
625 }
626
627 /// Remove a raw descriptor from the reactor.
628 ///
629 /// NOTE: This is an escape hatch for low-level interactions. Prefer using
630 /// [`del`](Self::del).
631 #[inline(always)]
632 pub(crate) fn del_raw(&self, raw: RawFd) -> Result<(), CoreError> {
633 loop {
634 let ret = unsafe {
635 libc::epoll_ctl(self.epfd, libc::EPOLL_CTL_DEL, raw, std::ptr::null_mut())
636 };
637 if ret == -1 {
638 let e = errno();
639 if e == libc::EINTR {
640 continue;
641 }
642 return Err(CoreError::sys(e, "epoll_ctl_del"));
643 }
644 return Ok(());
645 }
646 }
647
648 /// Wait for events.
649 ///
650 /// This function blocks until at least one event is ready or the timeout
651 /// expires. Ready events are appended to the `buffer`.
652 ///
653 /// ### Timeout Contract
654 /// - `-1`: Block indefinitely until an event occurs or a signal interrupts.
655 /// - `0`: Return immediately, even if no events are ready.
656 /// - `> 0`: Wait for up to the specified number of milliseconds.
657 ///
658 /// Returns the number of events received.
659 #[inline(always)]
660 pub fn wait(
661 &mut self,
662 buffer: &mut Vec<Event>,
663 max_events: usize,
664 timeout: i32,
665 ) -> Result<usize, CoreError> {
666 buffer.clear();
667
668 if max_events == 0 {
669 return Ok(0);
670 }
671
672 // Ensure buffer has enough capacity
673 if buffer.capacity() < max_events {
674 buffer.reserve(max_events.saturating_sub(buffer.len()));
675 }
676
677 if self.events_buf.capacity() < max_events {
678 self.events_buf
679 .reserve(max_events.saturating_sub(self.events_buf.len()));
680 }
681
682 let n = unsafe {
683 libc::epoll_wait(
684 self.epfd,
685 self.events_buf.as_mut_ptr(),
686 max_events as i32,
687 timeout,
688 )
689 };
690
691 if n > 0 {
692 unsafe {
693 self.events_buf.set_len(n as usize);
694 }
695 for i in 0..n as usize {
696 let ev = self.events_buf[i];
697 let is_read = (ev.events & libc::EPOLLIN as u32) != 0;
698 let is_priority = (ev.events & libc::EPOLLPRI as u32) != 0;
699 let is_write = (ev.events & libc::EPOLLOUT as u32) != 0;
700 let is_err = (ev.events & libc::EPOLLERR as u32) != 0;
701 let is_hup = (ev.events & libc::EPOLLHUP as u32) != 0;
702
703 buffer.push(Event {
704 token: Token(ev.u64),
705 readable: is_read || is_err,
706 priority: is_priority || is_err,
707 writable: is_write || is_err,
708 error: is_err,
709 hangup: is_hup,
710 });
711 }
712 return Ok(n as usize);
713 }
714
715 if n < 0 {
716 let e = errno();
717 if e == libc::EINTR {
718 return Ok(0);
719 }
720 return Err(CoreError::sys(e, "epoll_wait"));
721 }
722 Ok(0)
723 }
724
725 /// Return the raw epoll file descriptor.
726 ///
727 /// NOTE: This is an escape hatch for low-level interactions.
728 #[allow(dead_code)]
729 pub(crate) fn fd(&self) -> RawFd {
730 self.epfd
731 }
732}
733
734impl Drop for Reactor {
735 fn drop(&mut self) {
736 if let Some(mask) = self.signalfd_previous_mask.take() {
737 let _ =
738 unsafe { libc::pthread_sigmask(libc::SIG_SETMASK, &mask, std::ptr::null_mut()) };
739 }
740 if self.epfd >= 0 {
741 unsafe {
742 libc::close(self.epfd);
743 }
744 }
745 }
746}