Skip to main content

ntex_net/polling/
reactor.rs

1use std::os::fd::{AsRawFd, BorrowedFd, RawFd};
2use std::{cell::Cell, cell::UnsafeCell, fmt, io, net, rc::Rc};
3use std::{collections::VecDeque, num::NonZeroUsize, time::Duration};
4
5#[cfg(unix)]
6use std::os::unix::net::UnixStream as OsUnixStream;
7
8use ::ntex_polling::{Event, Events, Notifier, PollMode, Poller};
9use ntex_io::Io;
10use ntex_rt::{DriverType, Notify, PollResult, Runtime};
11use ntex_service::cfg::SharedCfg;
12use socket2::{Protocol, SockAddr, Socket, Type};
13
14use super::{TcpStream, UnixStream, stream::StreamOps};
15use crate::channel::Receiver;
16
17pub trait Handler {
18    /// Submitted interest, `id` is the one passed to [`ReactorApi`].
19    ///
20    /// Tasks run between chunks of events of one poll, so `id` may belong to
21    /// a registration released by a task after the poll.
22    fn event(&mut self, id: usize, event: Event);
23
24    /// Operation submission has failed, `id` is the one passed to [`ReactorApi`].
25    fn error(&mut self, id: usize, err: io::Error);
26
27    /// Process deferred work after events and before the driver waits.
28    ///
29    /// Called even when no events were received.
30    fn tick(&mut self);
31
32    /// Cleanup before drop
33    fn cleanup(&mut self);
34}
35
36type HandlerItem = Box<dyn Handler>;
37
38enum Change {
39    Error {
40        batch: usize,
41        user_data: u64,
42        error: io::Error,
43    },
44}
45
46#[derive(Debug)]
47/// Polling reactor api.
48///
49/// Ids identify registrations to the handler, only their low 48 bits are
50/// available.
51pub struct ReactorApi {
52    id: usize,
53    batch: u64,
54    poll: Rc<Poller>,
55    changes: Rc<UnsafeCell<VecDeque<Change>>>,
56}
57
58impl ReactorApi {
59    /// Attach an fd to the driver.
60    ///
61    /// `fd` must be attached to the driver before using register/unregister
62    /// methods.
63    pub fn attach(&self, fd: RawFd, id: u64, event: Event) {
64        self.attach_with_mode(fd, id, event, PollMode::Oneshot);
65    }
66
67    /// Attach an fd to the driver with specific mode.
68    ///
69    /// `fd` must be attached to the driver before using register/unregister
70    /// methods.
71    pub fn attach_with_mode(&self, fd: RawFd, id: u64, mut event: Event, mode: PollMode) {
72        event.key = self.key(id);
73        // SAFETY: Internal stream callers keep `fd` open and detach it before closing it.
74        if let Err(err) = unsafe { self.poll.add_with_mode(fd, event, mode) } {
75            self.change(Change::Error {
76                batch: self.id,
77                user_data: id,
78                error: err,
79            });
80        }
81    }
82
83    /// Detach an fd from the driver.
84    pub fn detach(&self, fd: RawFd, id: u64) {
85        // SAFETY: Internal stream callers keep `fd` open until detachment returns.
86        if let Err(err) = self.poll.delete(unsafe { BorrowedFd::borrow_raw(fd) }) {
87            self.change(Change::Error {
88                batch: self.id,
89                user_data: id,
90                error: err,
91            });
92        }
93    }
94
95    /// Register interest for specified file descriptor.
96    pub fn modify(&self, fd: RawFd, id: u64, event: Event) {
97        self.modify_with_mode(fd, id, event, PollMode::Oneshot);
98    }
99
100    /// Register interest for specified file descriptor.
101    pub fn modify_with_mode(&self, fd: RawFd, id: u64, mut event: Event, mode: PollMode) {
102        event.key = self.key(id);
103
104        let result = self
105            .poll
106            // SAFETY: Internal stream callers keep `fd` open during registration.
107            .modify_with_mode(unsafe { BorrowedFd::borrow_raw(fd) }, event, mode);
108        self.check(id, result);
109    }
110
111    /// Register interest for specified file descriptor, the change may be
112    /// deferred to the next poll.
113    ///
114    /// On kqueue the change is submitted together with the next wait, saving
115    /// a syscall. A failure of a deferred change is reported as a readable
116    /// and writable event.
117    pub fn modify_with_mode_deferred(&self, fd: RawFd, id: u64, mut event: Event, mode: PollMode) {
118        event.key = self.key(id);
119
120        let result = self
121            .poll
122            // SAFETY: Internal stream callers keep `fd` open until detachment.
123            .modify_with_mode_deferred(unsafe { BorrowedFd::borrow_raw(fd) }, event, mode);
124        self.check(id, result);
125    }
126
127    /// Whether the poller supports level-triggered events.
128    pub fn supports_level(&self) -> bool {
129        self.poll.supports_level()
130    }
131
132    fn check(&self, id: u64, result: io::Result<()>) {
133        if let Err(err) = result {
134            self.change(Change::Error {
135                batch: self.id,
136                user_data: id,
137                error: err,
138            });
139        }
140    }
141
142    /// Event key of `id`, ids are limited to 48 bits.
143    fn key(&self, id: u64) -> usize {
144        debug_assert_eq!(id & !Reactor::DATA_MASK, 0, "id {id:#x} exceeds 48 bits");
145        (id | self.batch) as usize
146    }
147
148    fn change(&self, ev: Change) {
149        // SAFETY: This thread-local queue is borrowed only for this non-reentrant push.
150        unsafe { (*self.changes.get()).push_back(ev) };
151    }
152
153    /// Whether a failed poller operation is queued.
154    #[cfg(test)]
155    pub(super) fn has_changes(&self) -> bool {
156        // SAFETY: Thread-local queue, no push or pop overlaps this read.
157        unsafe { !(*self.changes.get()).is_empty() }
158    }
159}
160
161/// Polling reactor.
162///
163/// Uses `epoll` or `kqueue`, depending on the platform.
164pub struct Reactor {
165    poll: Rc<Poller>,
166    capacity: usize,
167    changes: Rc<UnsafeCell<VecDeque<Change>>>,
168    hid: Cell<u64>,
169    #[allow(clippy::box_collection)]
170    handlers: Cell<Option<Box<Vec<HandlerItem>>>>,
171}
172
173impl Reactor {
174    const BATCH: u64 = 48;
175    const BATCH_MASK: u64 = 0xFFFF_0000_0000_0000;
176    const DATA_MASK: u64 = 0x0000_FFFF_FFFF_FFFF;
177
178    /// Events read per poll.
179    const EVENTS_CAPACITY: u32 = 512;
180
181    /// Events handled between task runs.
182    ///
183    /// Small chunks let a connection write its response while its socket
184    /// state is still in cache. Handling 2048 events at once with ~1K busy
185    /// connections per worker ran ~20% slower in HTTP/1 benchmarks.
186    const EVENTS_PER_CHUNK: usize = 8;
187
188    pub fn new() -> io::Result<Self> {
189        Reactor::with_capacity(Self::EVENTS_CAPACITY)
190    }
191
192    pub fn with_capacity(io_queue_capacity: u32) -> io::Result<Self> {
193        log::trace!("New poll driver");
194
195        Ok(Self {
196            hid: Cell::new(0),
197            poll: Rc::new(Poller::new()?),
198            capacity: io_queue_capacity as usize,
199            changes: Rc::new(UnsafeCell::new(VecDeque::with_capacity(32))),
200            handlers: Cell::new(Some(Box::new(Vec::default()))),
201        })
202    }
203
204    /// Reactor type
205    pub const fn tp(&self) -> DriverType {
206        DriverType::Poll
207    }
208
209    /// Register updates handler
210    pub fn register<F>(&self, f: F)
211    where
212        F: FnOnce(ReactorApi) -> Box<dyn Handler>,
213    {
214        let id = self.hid.get();
215        let mut handlers = self
216            .handlers
217            .take()
218            .expect("Cannot register handler during event handling");
219
220        let api = ReactorApi {
221            id: id as usize,
222            batch: id << Self::BATCH,
223            poll: self.poll.clone(),
224            changes: self.changes.clone(),
225        };
226        handlers.push(f(api));
227        self.hid.set(id + 1);
228        self.handlers.set(Some(handlers));
229    }
230
231    fn apply_changes(&self, handlers: &mut [HandlerItem]) {
232        // SAFETY: Queue access is thread-local and the borrow ends before handler callbacks.
233        while let Some(op) = unsafe { (*self.changes.get()).pop_front() } {
234            match op {
235                Change::Error {
236                    batch,
237                    user_data,
238                    error,
239                } => handlers[batch].error(user_data as usize, error),
240            }
241        }
242    }
243
244    fn tick(&self, handlers: &mut [HandlerItem]) {
245        loop {
246            self.apply_changes(handlers);
247            for h in handlers.iter_mut() {
248                h.tick();
249            }
250            // Ticks can fail poller operations, and handling those errors can
251            // enqueue more deferred work. Finish both before waiting.
252            // SAFETY: No queue mutation or handler callback overlaps this thread-local read.
253            if unsafe { (*self.changes.get()).is_empty() } {
254                break;
255            }
256        }
257    }
258}
259
260impl AsRawFd for Reactor {
261    fn as_raw_fd(&self) -> RawFd {
262        self.poll.as_raw_fd()
263    }
264}
265
266impl fmt::Debug for Reactor {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        f.debug_struct("Reactor")
269            .field("poll", &self.poll)
270            .field("capacity", &self.capacity)
271            .field("hid", &self.hid)
272            .finish()
273    }
274}
275
276impl crate::Reactor for Reactor {
277    fn tcp_connect(&self, addr: net::SocketAddr, cfg: SharedCfg) -> Receiver<Io> {
278        let addr = SockAddr::from(addr);
279        let result = Socket::new(addr.domain(), Type::STREAM, Some(Protocol::TCP))
280            .and_then(crate::helpers::prep_tcp_socket)
281            .and_then(crate::helpers::prep_socket)
282            .map(move |sock| (addr, sock));
283
284        match result {
285            Err(err) => Receiver::new(Err(err)),
286            Ok((addr, sock)) => {
287                super::connect::ConnectOps::get(self).connect(sock, &addr, cfg, false)
288            }
289        }
290    }
291
292    fn unix_connect(&self, addr: std::path::PathBuf, cfg: SharedCfg) -> Receiver<Io> {
293        let result = SockAddr::unix(addr).and_then(|addr| {
294            Socket::new(addr.domain(), Type::STREAM, None)
295                .and_then(crate::helpers::prep_socket)
296                .map(move |sock| (addr, sock))
297        });
298
299        match result {
300            Err(err) => Receiver::new(Err(err)),
301            Ok((addr, sock)) => {
302                super::connect::ConnectOps::get(self).connect(sock, &addr, cfg, true)
303            }
304        }
305    }
306
307    fn from_tcp_stream(&self, stream: net::TcpStream, cfg: SharedCfg) -> io::Result<Io> {
308        Ok(Io::new(
309            TcpStream(
310                crate::helpers::prep_socket(Socket::from(stream))?,
311                StreamOps::get(self),
312                false,
313            ),
314            cfg,
315        ))
316    }
317
318    #[cfg(unix)]
319    fn from_unix_stream(&self, stream: OsUnixStream, cfg: SharedCfg) -> io::Result<Io> {
320        Ok(Io::new(
321            UnixStream(
322                crate::helpers::prep_socket(Socket::from(stream))?,
323                StreamOps::get(self),
324                false,
325            ),
326            cfg,
327        ))
328    }
329
330    fn tcp_listener(&self, sock: net::TcpListener) -> io::Result<crate::Listener> {
331        Ok(super::accept::AcceptOps::get(self).listener(sock))
332    }
333
334    fn is_tcp_listener_supported(&self) -> bool {
335        true
336    }
337}
338
339impl ntex_rt::Driver for Reactor {
340    /// Poll the driver and handle completed entries.
341    fn run(&self, rt: &Runtime) -> io::Result<()> {
342        let mut events = if self.capacity == 0 {
343            Events::new()
344        } else {
345            Events::with_capacity(NonZeroUsize::new(self.capacity).unwrap())
346        };
347
348        let result = loop {
349            let timeout = match rt.poll() {
350                PollResult::Pending(timeout) => timeout,
351                PollResult::PollAgain => Some(Duration::ZERO),
352                PollResult::Ready => break Ok(()),
353            };
354            // Runtime tasks can queue cleanup without receiving a stream event.
355            let mut handlers = self.handlers.take().unwrap();
356            self.tick(&mut handlers);
357            self.handlers.set(Some(handlers));
358
359            events.clear();
360            self.poll.wait(&mut events, timeout)?;
361            // tasks woken until the runtime is polled do not need to notify
362            rt.awake();
363
364            let mut handlers = self.handlers.take().unwrap();
365            for (idx, event) in events.iter().enumerate() {
366                if idx != 0 && idx % Self::EVENTS_PER_CHUNK == 0 {
367                    // Run the tasks woken by the previous chunk within the
368                    // same runtime turn. Handlers are released, so tasks
369                    // can register new ones. A task can also release a
370                    // registration with events still queued, handlers check
371                    // the generation in their ids.
372                    self.tick(&mut handlers);
373                    self.handlers.set(Some(handlers));
374                    rt.run_ready();
375                    handlers = self.handlers.take().unwrap();
376                }
377                let key = event.key as u64;
378                let batch = ((key & Self::BATCH_MASK) >> Self::BATCH) as usize;
379                handlers[batch].event((key & Self::DATA_MASK) as usize, event);
380            }
381            self.tick(&mut handlers);
382            self.handlers.set(Some(handlers));
383        };
384
385        for mut h in self.handlers.take().unwrap().into_iter() {
386            h.cleanup();
387        }
388        result
389    }
390
391    /// Get notification handle
392    fn handle(&self) -> Box<dyn Notify> {
393        Box::new(NotifyHandle::new(self.poll.notifier()))
394    }
395
396    /// Clear handlers
397    fn clear(&self) {}
398}
399
400#[derive(Clone, Debug)]
401/// A notify handle to the inner driver.
402pub(crate) struct NotifyHandle {
403    notifier: Notifier,
404}
405
406impl NotifyHandle {
407    fn new(notifier: Notifier) -> Self {
408        Self { notifier }
409    }
410}
411
412impl Notify for NotifyHandle {
413    /// Notify the driver
414    fn notify(&self) -> io::Result<()> {
415        self.notifier.notify()
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use std::cell::RefCell;
422
423    use super::*;
424
425    struct Recorder(Rc<RefCell<Vec<(usize, io::ErrorKind)>>>);
426
427    impl Handler for Recorder {
428        fn event(&mut self, _: usize, _: Event) {}
429
430        fn error(&mut self, id: usize, err: io::Error) {
431            self.0.borrow_mut().push((id, err.kind()));
432        }
433
434        fn tick(&mut self) {}
435
436        fn cleanup(&mut self) {}
437    }
438
439    /// STATEMENT: The polling reactor reports its driver type, a valid descriptor and its
440    /// capacity in debug output.
441    ///
442    /// HOW:
443    /// - Create a reactor with capacity 0.
444    /// - Expect `DriverType::Poll`, a non-negative fd, and `Reactor` and `capacity` in
445    ///   `Debug`.
446    #[test]
447    fn reactor_info() {
448        let reactor = Reactor::with_capacity(0).unwrap();
449        assert_eq!(reactor.tp(), DriverType::Poll);
450        assert!(reactor.as_raw_fd() >= 0);
451        let s = format!("{reactor:?}");
452        assert!(s.contains("Reactor") && s.contains("capacity"), "{s}");
453    }
454
455    /// STATEMENT: Failed poller operations are reported to the handler that submitted them,
456    /// once the changes are applied.
457    ///
458    /// HOW:
459    /// - Modify and detach a socket that is not attached, with ids 1 and 2.
460    /// - Expect no errors before the changes are applied.
461    /// - Apply the changes; expect errors for ids 1 and 2.
462    #[test]
463    fn api_errors_are_reported() {
464        let reactor = Reactor::new().unwrap();
465        let errors = Rc::new(RefCell::new(Vec::new()));
466        let mut api = None;
467        reactor.register(|a| {
468            api = Some(a);
469            Box::new(Recorder(errors.clone()))
470        });
471        let api = api.unwrap();
472
473        // the socket is not attached
474        let (sock, _peer) = OsUnixStream::pair().unwrap();
475        api.modify(sock.as_raw_fd(), 1, Event::readable(0));
476        api.detach(sock.as_raw_fd(), 2);
477        assert!(errors.borrow().is_empty());
478
479        let mut handlers = reactor.handlers.take().unwrap();
480        reactor.apply_changes(&mut handlers);
481        reactor.handlers.set(Some(handlers));
482
483        let ids: Vec<_> = errors.borrow().iter().map(|(id, _)| *id).collect();
484        assert_eq!(ids, vec![1, 2]);
485    }
486
487    /// STATEMENT: A reactor tick reports errors from changes queued by handler ticks, including
488    /// changes queued while handling those errors.
489    ///
490    /// HOW:
491    /// - Register a handler whose tick modifies an unattached socket with id 1, and that
492    ///   queues id 2 when it gets the error for id 1.
493    /// - Run one reactor tick.
494    /// - Expect errors for ids 1 and 2, and no queued changes left.
495    #[test]
496    fn tick_drains_errors_and_their_deferred_work() {
497        struct TickErrors {
498            api: ReactorApi,
499            socket: OsUnixStream,
500            next: Option<u64>,
501            errors: Rc<RefCell<Vec<usize>>>,
502        }
503
504        impl Handler for TickErrors {
505            fn event(&mut self, _: usize, _: Event) {
506                panic!("unexpected socket event");
507            }
508
509            fn error(&mut self, id: usize, _: io::Error) {
510                self.errors.borrow_mut().push(id);
511                if id == 1 {
512                    self.next = Some(2);
513                }
514            }
515
516            fn tick(&mut self) {
517                if let Some(id) = self.next.take() {
518                    // The socket is not attached, so the operation fails.
519                    self.api
520                        .modify(self.socket.as_raw_fd(), id, Event::readable(0));
521                }
522            }
523
524            fn cleanup(&mut self) {}
525        }
526
527        let reactor = Reactor::new().unwrap();
528        let (socket, _peer) = OsUnixStream::pair().unwrap();
529        let errors = Rc::new(RefCell::new(Vec::new()));
530        reactor.register(|api| {
531            Box::new(TickErrors {
532                api,
533                socket,
534                next: Some(1),
535                errors: errors.clone(),
536            })
537        });
538
539        let mut handlers = reactor.handlers.take().unwrap();
540        reactor.tick(&mut handlers);
541        reactor.handlers.set(Some(handlers));
542
543        assert_eq!(*errors.borrow(), vec![1, 2]);
544        // SAFETY: Dispatch has finished and no callback can mutate the thread-local queue.
545        assert!(unsafe { (*reactor.changes.get()).is_empty() });
546    }
547}