Skip to main content

ntex_net/
channel.rs

1//! A one-shot, futures-aware channel.
2use std::{cell::Cell, rc::Rc};
3use std::{fmt, future::Future, future::poll_fn, io, pin::Pin, task::Context, task::Poll};
4
5use ntex_util::task::LocalWaker;
6
7/// Notified when a receiver is dropped before its value is sent.
8pub(crate) trait Cancel {
9    fn cancel(&self, id: u32);
10}
11
12/// Creates a new futures-aware, one-shot channel.
13pub fn create<T>() -> (Sender<T>, Receiver<T>) {
14    create_inner(None)
15}
16
17/// Creates a channel that calls `hnd.cancel(id)` if the receiver is
18/// dropped while the sender is still pending.
19pub(crate) fn with_cancel<T>(hnd: Rc<dyn Cancel>, id: u32) -> (Sender<T>, Receiver<T>) {
20    create_inner(Some((hnd, id)))
21}
22
23fn create_inner<T>(on_cancel: Option<(Rc<dyn Cancel>, u32)>) -> (Sender<T>, Receiver<T>) {
24    let inner = Rc::new(Inner {
25        value: Cell::new(None),
26        rx_task: LocalWaker::new(),
27        on_cancel: Cell::new(on_cancel),
28    });
29    let tx = Sender {
30        inner: inner.clone(),
31    };
32    let rx = Receiver { inner };
33    (tx, rx)
34}
35
36#[cfg(windows)]
37pub(crate) fn create_with_cancel<T>(
38    on_cancel: impl FnOnce() + 'static,
39) -> (Sender<T>, Receiver<T>) {
40    struct Callback<F>(Cell<Option<F>>);
41
42    impl<F: FnOnce()> Cancel for Callback<F> {
43        fn cancel(&self, _: u32) {
44            if let Some(on_cancel) = self.0.take() {
45                on_cancel();
46            }
47        }
48    }
49
50    with_cancel(Rc::new(Callback(Cell::new(Some(on_cancel)))), 0)
51}
52
53#[derive(Debug)]
54/// Represents the completion half of a oneshot through which the result of a
55/// computation is signaled.
56pub struct Sender<T> {
57    inner: Rc<Inner<T>>,
58}
59
60#[derive(Debug)]
61/// A future representing the completion of a computation happening elsewhere in
62/// memory.
63#[must_use = "futures do nothing unless polled"]
64pub struct Receiver<T> {
65    inner: Rc<Inner<T>>,
66}
67
68// The channels do not ever project Pin to the inner T
69impl<T> Unpin for Receiver<T> {}
70impl<T> Unpin for Sender<T> {}
71
72struct Inner<T> {
73    value: Cell<Option<io::Result<T>>>,
74    rx_task: LocalWaker,
75    on_cancel: Cell<Option<(Rc<dyn Cancel>, u32)>>,
76}
77
78impl<T> Sender<T> {
79    #[cfg(windows)]
80    pub(crate) fn is_closed(&self) -> bool {
81        Rc::strong_count(&self.inner) == 1
82    }
83
84    /// Completes this oneshot with a successful result.
85    ///
86    /// This function will consume `self` and indicate to the other end, the
87    /// `Receiver`, that the value provided is the result of the computation this
88    /// represents.
89    ///
90    /// If the value is successfully enqueued for the remote end to receive,
91    /// then `Ok(())` is returned. If the receiving end was dropped before
92    /// this function was called, however, then `Err` is returned with the value
93    /// provided.
94    pub fn send(self, val: io::Result<T>) -> Result<(), io::Result<T>> {
95        drop(self.inner.on_cancel.take());
96
97        if Rc::strong_count(&self.inner) == 2 {
98            self.inner.value.set(Some(val));
99            self.inner.rx_task.wake();
100            Ok(())
101        } else {
102            Err(val)
103        }
104    }
105
106    /// Returns `true` if the receiver is dropped.
107    pub fn is_canceled(&self) -> bool {
108        Rc::strong_count(&self.inner) == 1
109    }
110}
111
112impl<T> Drop for Sender<T> {
113    fn drop(&mut self) {
114        drop(self.inner.on_cancel.take());
115        self.inner.rx_task.wake();
116    }
117}
118
119impl<T> Receiver<T> {
120    pub fn new(val: io::Result<T>) -> Self {
121        let inner = Rc::new(Inner {
122            value: Cell::new(Some(val)),
123            rx_task: LocalWaker::new(),
124            on_cancel: Cell::new(None),
125        });
126        Receiver { inner }
127    }
128
129    /// Wait until the oneshot is ready and return value
130    pub async fn recv(&self) -> io::Result<T> {
131        poll_fn(|cx| self.poll_recv(cx)).await
132    }
133
134    /// Polls the oneshot to determine if value is ready
135    fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<io::Result<T>> {
136        // If we've got a value, then skip the logic below as we're done.
137        if let Some(val) = self.inner.value.take() {
138            return Poll::Ready(val);
139        }
140
141        // Check if sender is dropped and return error if it is.
142        if Rc::strong_count(&self.inner) == 1 {
143            Poll::Ready(Err(io::Error::other("IO Driver is gone")))
144        } else {
145            self.inner.rx_task.register(cx.waker());
146            Poll::Pending
147        }
148    }
149}
150
151impl<T> Drop for Receiver<T> {
152    fn drop(&mut self) {
153        if let Some((hnd, id)) = self.inner.on_cancel.take() {
154            hnd.cancel(id);
155        }
156    }
157}
158
159impl<T> Future for Receiver<T> {
160    type Output = io::Result<T>;
161
162    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
163        self.poll_recv(cx)
164    }
165}
166
167impl<T: fmt::Debug> fmt::Debug for Inner<T> {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        let val = self.value.take();
170        let result = f.debug_struct("Inner").field("value", &val).finish();
171        self.value.set(val);
172        result
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    /// STATEMENT: A receiver created with a value is ready at once, without a sender,
181    /// and formatting it keeps the value.
182    ///
183    /// HOW:
184    /// - Create receivers holding a value and an error.
185    /// - Format the second one and check the output shows the error.
186    /// - Await them and check they return the value and the error unchanged.
187    #[ntex::test]
188    async fn receiver_new_is_ready() {
189        assert_eq!(Receiver::new(Ok(5)).await.unwrap(), 5);
190
191        let rx = Receiver::<()>::new(Err(io::Error::other("connect failed")));
192        assert!(format!("{rx:?}").contains("connect failed"));
193        let err = rx.recv().await.unwrap_err();
194        assert_eq!(err.to_string(), "connect failed");
195    }
196
197    /// STATEMENT: The cancel callback runs once when the receiver is dropped while the
198    /// operation is still pending.
199    ///
200    /// HOW:
201    /// - Drop the receiver of a pending channel; expect the sender closed, one cancel call,
202    ///   and a failed send without another call.
203    /// - Drop receivers after a value, after an error, and after the sender is dropped; expect
204    ///   no more cancel calls.
205    #[cfg(windows)]
206    #[test]
207    fn cancellation_only_while_pending() {
208        let cancelled = Rc::new(Cell::new(0));
209        let channel = || {
210            let cancelled = cancelled.clone();
211            create_with_cancel::<()>(move || cancelled.set(cancelled.get() + 1))
212        };
213
214        let (tx, rx) = channel();
215        assert!(!tx.is_closed());
216        drop(rx);
217        assert!(tx.is_closed());
218        assert_eq!(cancelled.get(), 1);
219        assert!(tx.send(Ok(())).is_err());
220        assert_eq!(cancelled.get(), 1);
221
222        let (tx, rx) = channel();
223        tx.send(Ok(())).unwrap();
224        drop(rx);
225        assert_eq!(cancelled.get(), 1);
226
227        let (tx, rx) = channel();
228        tx.send(Err(io::Error::other("connect failed"))).unwrap();
229        drop(rx);
230        assert_eq!(cancelled.get(), 1);
231
232        let (tx, rx) = channel();
233        drop(tx);
234        drop(rx);
235        assert_eq!(cancelled.get(), 1);
236    }
237
238    /// STATEMENT: The oneshot channel delivers a sent value and reports a dropped peer.
239    ///
240    /// HOW:
241    /// - Send a value; expect it from awaiting the receiver and from `recv`.
242    /// - Drop the receiver; expect the sender canceled and a failed send.
243    /// - Drop the sender; expect the receiver to fail.
244    #[ntex::test]
245    async fn test_oneshot() {
246        let (tx, rx) = create();
247
248        tx.send(Ok("test")).unwrap();
249        assert_eq!(rx.await.unwrap(), "test");
250
251        let (tx, rx) = create();
252        tx.send(Ok("test")).unwrap();
253        assert_eq!(rx.recv().await.unwrap(), "test");
254
255        let (tx, rx) = create();
256        assert!(!tx.is_canceled());
257        drop(rx);
258        assert!(tx.is_canceled());
259        assert!(tx.send(Ok("test")).is_err());
260
261        let (tx, rx) = create::<&'static str>();
262        drop(tx);
263        assert!(rx.await.is_err());
264
265        let (tx, rx) = create::<&'static str>();
266        tx.send(Ok("test")).unwrap();
267        assert_eq!(rx.await.unwrap(), "test");
268
269        let (tx, rx) = create::<&'static str>();
270        drop(tx);
271        assert!(rx.await.is_err());
272    }
273
274    /// STATEMENT: The cancel hook gets the operation id when the receiver is dropped while it
275    /// is pending.
276    ///
277    /// HOW:
278    /// - Drop the receiver of a pending channel; expect the hook called once with id 7.
279    /// - Drop receivers after a sent value and after the sender is dropped; expect no calls.
280    #[ntex::test]
281    async fn cancel_hook() {
282        struct Hook(Cell<Option<u32>>);
283        impl Cancel for Hook {
284            fn cancel(&self, id: u32) {
285                assert!(self.0.replace(Some(id)).is_none());
286            }
287        }
288        let hook = Rc::new(Hook(Cell::new(None)));
289
290        let (_tx, rx) = with_cancel::<()>(hook.clone(), 7);
291        drop(rx);
292        assert_eq!(hook.0.take(), Some(7));
293
294        // a sent or abandoned value is not canceled
295        let (tx, rx) = with_cancel(hook.clone(), 8);
296        tx.send(Ok(())).unwrap();
297        drop(rx);
298        let (tx, rx) = with_cancel::<()>(hook.clone(), 9);
299        drop(tx);
300        drop(rx);
301        assert_eq!(hook.0.take(), None);
302    }
303}