Skip to main content

ntex_io/
testing.rs

1//! In-memory I/O transport and helpers for tests.
2#![allow(clippy::missing_panics_doc)]
3use std::sync::{Arc, Mutex};
4use std::task::{Context, Poll, Waker};
5use std::{any, cell::RefCell, cmp, fmt, future::poll_fn, io, mem, net, rc::Rc};
6
7use ntex_bytes::{BufMut, BytePages, Bytes, BytesMut};
8use ntex_util::time::{Millis, sleep};
9
10use crate::{Handle, IoContext, IoStream, IoTaskStatus, Readiness, types};
11
12#[derive(Default)]
13struct AtomicWaker(Arc<Mutex<RefCell<Option<Waker>>>>);
14
15impl AtomicWaker {
16    fn wake(&self) -> bool {
17        if let Some(waker) = self.0.lock().unwrap().borrow_mut().take() {
18            waker.wake();
19            true
20        } else {
21            false
22        }
23    }
24}
25
26impl fmt::Debug for AtomicWaker {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "AtomicWaker")
29    }
30}
31
32/// One endpoint of an in-memory asynchronous byte stream.
33///
34/// Use [`IoTest::create`] to construct connected client and server endpoints.
35/// Bytes written by one endpoint become readable from the other.
36#[derive(Debug)]
37pub struct IoTest {
38    tp: Type,
39    peer_addr: Option<net::SocketAddr>,
40    state: Arc<Mutex<RefCell<State>>>,
41    local: Arc<Mutex<RefCell<Channel>>>,
42    remote: Arc<Mutex<RefCell<Channel>>>,
43}
44
45bitflags::bitflags! {
46    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
47    struct IoTestFlags: u8 {
48        const FLUSHED = 0b0000_0001;
49        const CLOSED  = 0b0000_0010;
50    }
51}
52
53#[derive(Copy, Clone, PartialEq, Eq, Debug)]
54enum Type {
55    Client,
56    Server,
57    ClientClone,
58    ServerClone,
59}
60
61#[derive(Copy, Clone, Default, Debug)]
62struct State {
63    client_dropped: bool,
64    server_dropped: bool,
65}
66
67#[derive(Default, Debug)]
68struct Channel {
69    buf: BytesMut,
70    buf_cap: usize,
71    flags: IoTestFlags,
72    waker: AtomicWaker,
73    read: IoTestState,
74    write: IoTestState,
75}
76
77impl Channel {
78    fn is_closed(&self) -> bool {
79        self.flags.contains(IoTestFlags::CLOSED)
80    }
81}
82
83impl Default for IoTestFlags {
84    fn default() -> Self {
85        IoTestFlags::empty()
86    }
87}
88
89#[derive(Debug, Default)]
90enum IoTestState {
91    #[default]
92    Ok,
93    Pending,
94    Close,
95    Err(io::Error),
96}
97
98impl IoTest {
99    /// Creates connected client and server endpoints.
100    pub fn create() -> (IoTest, IoTest) {
101        let local = Arc::new(Mutex::new(RefCell::new(Channel::default())));
102        let remote = Arc::new(Mutex::new(RefCell::new(Channel::default())));
103        let state = Arc::new(Mutex::new(RefCell::new(State::default())));
104
105        (
106            IoTest {
107                tp: Type::Client,
108                peer_addr: None,
109                local: local.clone(),
110                remote: remote.clone(),
111                state: state.clone(),
112            },
113            IoTest {
114                state,
115                peer_addr: None,
116                tp: Type::Server,
117                local: remote,
118                remote: local,
119            },
120        )
121    }
122
123    /// Returns `true` after the client endpoint has been dropped.
124    pub fn is_client_dropped(&self) -> bool {
125        self.state.lock().unwrap().borrow().client_dropped
126    }
127
128    /// Returns `true` after the server endpoint has been dropped.
129    pub fn is_server_dropped(&self) -> bool {
130        self.state.lock().unwrap().borrow().server_dropped
131    }
132
133    /// Returns `true` after the peer has closed its write side.
134    pub fn is_closed(&self) -> bool {
135        self.remote.lock().unwrap().borrow().is_closed()
136    }
137
138    /// Sets the socket address returned by transport queries.
139    #[must_use]
140    pub fn set_peer_addr(mut self, addr: net::SocketAddr) -> Self {
141        self.peer_addr = Some(addr);
142        self
143    }
144
145    /// Forces subsequent reads from the peer endpoint to remain pending.
146    pub fn read_pending(&self) {
147        self.remote.lock().unwrap().borrow_mut().read = IoTestState::Pending;
148    }
149
150    /// Makes the peer endpoint's next read fail with `err`.
151    pub fn read_error(&self, err: io::Error) {
152        let channel = self.remote.lock().unwrap();
153        channel.borrow_mut().read = IoTestState::Err(err);
154        channel.borrow().waker.wake();
155    }
156
157    /// Makes the peer endpoint's next transport write fail with `err`.
158    pub fn write_error(&self, err: io::Error) {
159        self.local.lock().unwrap().borrow_mut().write = IoTestState::Err(err);
160        self.remote.lock().unwrap().borrow().waker.wake();
161    }
162
163    /// Makes the peer endpoint's next transport write return zero bytes.
164    pub fn write_zero(&self) {
165        self.local.lock().unwrap().borrow_mut().write = IoTestState::Close;
166        self.remote.lock().unwrap().borrow().waker.wake();
167    }
168
169    /// Provides mutable access to bytes readable by this endpoint.
170    pub fn local_buffer<F, R>(&self, f: F) -> R
171    where
172        F: FnOnce(&mut BytesMut) -> R,
173    {
174        let guard = self.local.lock().unwrap();
175        let mut ch = guard.borrow_mut();
176        f(&mut ch.buf)
177    }
178
179    /// Provides mutable access to bytes readable by the peer endpoint.
180    pub fn remote_buffer<F, R>(&self, f: F) -> R
181    where
182        F: FnOnce(&mut BytesMut) -> R,
183    {
184        let guard = self.remote.lock().unwrap();
185        let mut ch = guard.borrow_mut();
186        f(&mut ch.buf)
187    }
188
189    /// Simulates this endpoint closing its write side.
190    ///
191    /// This wakes the peer endpoint's pending reader and waits briefly so the
192    /// close can be observed by asynchronous test code.
193    pub async fn close(&self) {
194        {
195            let guard = self.remote.lock().unwrap();
196            let mut remote = guard.borrow_mut();
197            remote.read = IoTestState::Close;
198            let res = remote.waker.wake();
199            log::debug!("close remote socket, waker:{res}");
200        }
201        sleep(Millis(35)).await;
202    }
203
204    /// Writes bytes for the peer endpoint to read and wakes its reader.
205    pub fn write<T: AsRef<[u8]>>(&self, data: T) {
206        let guard = self.remote.lock().unwrap();
207        let mut write = guard.borrow_mut();
208        write.buf.extend_from_slice(data.as_ref());
209        write.waker.wake();
210    }
211
212    /// Sets how many bytes the peer may write before becoming blocked.
213    ///
214    /// Increasing the capacity wakes the peer's pending writer.
215    pub fn remote_buffer_cap(&self, cap: usize) {
216        // change cap
217        self.local.lock().unwrap().borrow_mut().buf_cap = cap;
218        // wake remote
219        self.remote.lock().unwrap().borrow().waker.wake();
220    }
221
222    /// Takes all bytes currently readable by this endpoint without waiting.
223    pub fn read_any(&self) -> Bytes {
224        self.local.lock().unwrap().borrow_mut().buf.take()
225    }
226
227    /// Waits for readable data or peer closure, then takes all available bytes.
228    pub async fn read(&self) -> Result<Bytes, io::Error> {
229        if self.local.lock().unwrap().borrow().buf.is_empty() {
230            poll_fn(|cx| {
231                let guard = self.local.lock().unwrap();
232                let read = guard.borrow_mut();
233                if read.buf.is_empty() {
234                    let closed = match self.tp {
235                        Type::Client | Type::ClientClone => {
236                            self.is_server_dropped() || read.is_closed()
237                        }
238                        Type::Server | Type::ServerClone => self.is_client_dropped(),
239                    };
240                    if closed {
241                        Poll::Ready(())
242                    } else {
243                        *read.waker.0.lock().unwrap().borrow_mut() = Some(cx.waker().clone());
244                        drop(read);
245                        drop(guard);
246                        Poll::Pending
247                    }
248                } else {
249                    Poll::Ready(())
250                }
251            })
252            .await;
253        }
254        Ok(self.local.lock().unwrap().borrow_mut().buf.take())
255    }
256
257    /// Polls a transport read into `buf`.
258    ///
259    /// Returns the number of bytes copied, zero on simulated peer closure, or
260    /// `Pending` when no input is available.
261    ///
262    /// # Panics
263    ///
264    /// Panics if data is available but `buf` has no remaining capacity.
265    pub fn poll_read_buf(
266        &self,
267        cx: &mut Context<'_>,
268        buf: &mut BytesMut,
269    ) -> Poll<io::Result<usize>> {
270        let guard = self.local.lock().unwrap();
271        let mut ch = guard.borrow_mut();
272        *ch.waker.0.lock().unwrap().borrow_mut() = Some(cx.waker().clone());
273
274        if !ch.buf.is_empty() {
275            let size = std::cmp::min(ch.buf.len(), buf.remaining_mut());
276            assert!(size > 0, "Supplied buffer is zero sized");
277            let b = ch.buf.split_to(size);
278            buf.put_slice(&b);
279            return Poll::Ready(Ok(size));
280        }
281
282        match mem::take(&mut ch.read) {
283            IoTestState::Ok | IoTestState::Pending => Poll::Pending,
284            IoTestState::Close => {
285                ch.read = IoTestState::Close;
286                Poll::Ready(Ok(0))
287            }
288            IoTestState::Err(e) => Poll::Ready(Err(e)),
289        }
290    }
291
292    /// Polls a transport write from `buf`.
293    ///
294    /// The write is limited by the capacity configured with
295    /// [`remote_buffer_cap`](Self::remote_buffer_cap).
296    pub fn poll_write_buf(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
297        let guard = self.remote.lock().unwrap();
298        let mut ch = guard.borrow_mut();
299
300        match mem::take(&mut ch.write) {
301            IoTestState::Ok => {
302                let cap = cmp::min(buf.len(), ch.buf_cap);
303                if cap > 0 {
304                    ch.buf.extend(&buf[..cap]);
305                    ch.buf_cap -= cap;
306                    ch.flags.remove(IoTestFlags::FLUSHED);
307                    ch.waker.wake();
308                    Poll::Ready(Ok(cap))
309                } else {
310                    *self
311                        .local
312                        .lock()
313                        .unwrap()
314                        .borrow_mut()
315                        .waker
316                        .0
317                        .lock()
318                        .unwrap()
319                        .borrow_mut() = Some(cx.waker().clone());
320                    Poll::Pending
321                }
322            }
323            IoTestState::Close => Poll::Ready(Ok(0)),
324            IoTestState::Pending => {
325                *self
326                    .local
327                    .lock()
328                    .unwrap()
329                    .borrow_mut()
330                    .waker
331                    .0
332                    .lock()
333                    .unwrap()
334                    .borrow_mut() = Some(cx.waker().clone());
335                Poll::Pending
336            }
337            IoTestState::Err(e) => Poll::Ready(Err(e)),
338        }
339    }
340}
341
342impl Clone for IoTest {
343    fn clone(&self) -> Self {
344        let tp = match self.tp {
345            Type::Server => Type::ServerClone,
346            Type::Client => Type::ClientClone,
347            val => val,
348        };
349
350        IoTest {
351            tp,
352            local: self.local.clone(),
353            remote: self.remote.clone(),
354            state: self.state.clone(),
355            peer_addr: self.peer_addr,
356        }
357    }
358}
359
360impl Drop for IoTest {
361    fn drop(&mut self) {
362        let mut state = *self.state.lock().unwrap().borrow();
363        match self.tp {
364            Type::Server => state.server_dropped = true,
365            Type::Client => state.client_dropped = true,
366            _ => (),
367        }
368        *self.state.lock().unwrap().borrow_mut() = state;
369
370        let guard = self.remote.lock().unwrap();
371        let mut remote = guard.borrow_mut();
372        remote.read = IoTestState::Close;
373        remote.waker.wake();
374        log::debug!("drop remote socket");
375    }
376}
377
378impl IoStream for IoTest {
379    fn start(self, ctx: IoContext) -> Box<dyn Handle> {
380        let io = Rc::new(self);
381        ntex_util::spawn_detached(run(io.clone(), ctx));
382        Box::new(io)
383    }
384}
385
386impl Handle for Rc<IoTest> {
387    fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>> {
388        if id == any::TypeId::of::<types::PeerAddr>()
389            && let Some(addr) = self.peer_addr
390        {
391            return Some(Box::new(types::PeerAddr(addr)));
392        }
393        None
394    }
395}
396
397async fn run(io: Rc<IoTest>, ctx: IoContext) {
398    poll_fn(|cx| turn(&io, &ctx, cx)).await;
399
400    log::debug!("{}: Shutting down io", ctx.tag());
401
402    // shutdown WRITE side
403    io.local
404        .lock()
405        .unwrap()
406        .borrow_mut()
407        .flags
408        .insert(IoTestFlags::CLOSED);
409
410    log::debug!("{}: Shutdown complete", ctx.tag());
411    ctx.stopped(None);
412}
413
414fn turn(io: &IoTest, ctx: &IoContext, cx: &mut Context<'_>) -> Poll<()> {
415    let read = match ctx.poll_read_ready(cx) {
416        Poll::Ready(Readiness::Ready) => read(io, ctx, cx),
417        Poll::Ready(Readiness::Close | Readiness::Terminate) => Poll::Ready(()),
418        Poll::Pending => Poll::Pending,
419    };
420
421    let write = match ctx.poll_write_ready(cx) {
422        Poll::Ready(Readiness::Ready) => write(io, ctx, cx),
423        Poll::Ready(Readiness::Close | Readiness::Terminate) => Poll::Ready(()),
424        Poll::Pending => Poll::Pending,
425    };
426
427    if read.is_pending() && write.is_pending() {
428        Poll::Pending
429    } else {
430        Poll::Ready(())
431    }
432}
433
434fn write(io: &IoTest, ctx: &IoContext, cx: &mut Context<'_>) -> Poll<()> {
435    let result = ctx.with_write_dst(|buf| write_io(io, buf, cx, ctx));
436    if ctx.update_write_status(result) == IoTaskStatus::Stop {
437        Poll::Ready(())
438    } else {
439        Poll::Pending
440    }
441}
442
443fn read(io: &IoTest, ctx: &IoContext, cx: &mut Context<'_>) -> Poll<()> {
444    loop {
445        let mut pending = false;
446        let result = ctx.with_read_buf(|buf| {
447            let result = io.poll_read_buf(cx, buf);
448            pending = result.is_pending();
449            result
450        });
451        return match result {
452            IoTaskStatus::Io => {
453                if pending {
454                    Poll::Pending
455                } else {
456                    continue;
457                }
458            }
459            IoTaskStatus::Stop => Poll::Ready(()),
460            IoTaskStatus::Pause => Poll::Pending,
461        };
462    }
463}
464
465/// Flush write buffer to underlying I/O stream.
466pub(super) fn write_io(
467    io: &IoTest,
468    buf: &mut BytePages,
469    cx: &mut Context<'_>,
470    ctx: &IoContext,
471) -> io::Result<usize> {
472    let tag = ctx.tag();
473    let mut written = 0;
474
475    while let Some(mut page) = buf.take() {
476        log::debug!("{tag}: flushing framed transport: {}", page.len());
477
478        let result = io.poll_write_buf(cx, &page)?;
479        match result {
480            Poll::Ready(0) => {
481                log::trace!("{tag}: disconnected during flush, written {written}");
482                buf.prepend(page);
483                return Err(io::Error::new(
484                    io::ErrorKind::WriteZero,
485                    "failed to write frame to transport",
486                ));
487            }
488            Poll::Ready(n) => {
489                written += n;
490                page.advance_to(n);
491                buf.prepend(page);
492            }
493            Poll::Pending => {
494                buf.prepend(page);
495                break;
496            }
497        }
498    }
499
500    log::debug!("{tag}: flushed {written} bytes, remaining: {}", buf.len());
501    Ok(written)
502}
503
504#[cfg(test)]
505#[allow(clippy::redundant_clone)]
506mod tests {
507    use super::*;
508    use ntex_util::future::lazy;
509
510    /// STATEMENT: `IoTest` distinguishes endpoint clones, simulates pending I/O, and tracks endpoint drops.
511    ///
512    /// HOW:
513    /// - Check endpoint kinds and debug output, force pending reads/writes, and drop original endpoints.
514    /// - Verify drop indicators, remaining pending writes, and a configured peer-address query.
515    #[ntex::test]
516    async fn basic() {
517        let (client, server) = IoTest::create();
518        assert_eq!(client.tp, Type::Client);
519        assert_eq!(client.clone().tp, Type::ClientClone);
520        assert_eq!(server.tp, Type::Server);
521        assert_eq!(server.clone().tp, Type::ServerClone);
522        assert!(format!("{:?}", AtomicWaker::default()).contains("AtomicWaker"));
523
524        server.read_pending();
525        let mut buf = BytesMut::new();
526        let res = lazy(|cx| client.poll_read_buf(cx, &mut buf)).await;
527        assert!(res.is_pending());
528
529        server.read_pending();
530        let res = lazy(|cx| server.poll_write_buf(cx, b"123")).await;
531        assert!(res.is_pending());
532
533        assert!(!server.is_client_dropped());
534        drop(client);
535        assert!(server.is_client_dropped());
536
537        let server2 = server.clone();
538        assert!(!server2.is_server_dropped());
539        drop(server);
540        assert!(server2.is_server_dropped());
541
542        let res = lazy(|cx| server2.poll_write_buf(cx, b"123")).await;
543        assert!(res.is_pending());
544
545        let (client, _) = IoTest::create();
546        let addr: net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
547        let client = crate::Io::from(client.set_peer_addr(addr));
548        let item = client.query::<crate::types::PeerAddr>();
549        assert!(format!("{item:?}").contains("QueryItem(127.0.0.1:8080)"));
550    }
551}