Skip to main content

ntex_util/channel/
pool.rs

1//! A one-shot pool, futures-aware channel.
2use slab::Slab;
3use std::{fmt, future::Future, pin::Pin, task::Context, task::Poll};
4
5use super::{Canceled, cell::Cell, cell::wake};
6use crate::task::LocalWaker;
7
8/// Creates a new futures-aware pool of one-shot channels.
9pub fn new<T>() -> Pool<T> {
10    Pool(Cell::new(Slab::new()))
11}
12
13/// A futures-aware pool of one-shot channels.
14pub struct Pool<T>(Cell<Slab<Inner<T>>>);
15
16impl<T> fmt::Debug for Pool<T> {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.debug_struct("Pool")
19            .field("size", &self.0.get_ref().len())
20            .finish()
21    }
22}
23
24bitflags::bitflags! {
25    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
26    struct Flags: u8 {
27        const SENDER = 0b0000_0001;
28        const RECEIVER = 0b0000_0010;
29    }
30}
31
32#[derive(Debug)]
33struct Inner<T> {
34    flags: Flags,
35    value: Option<T>,
36    tx_waker: LocalWaker,
37    rx_waker: LocalWaker,
38}
39
40impl<T> Default for Pool<T> {
41    fn default() -> Pool<T> {
42        new()
43    }
44}
45
46impl<T> Pool<T> {
47    /// Create a new one-shot channel.
48    pub fn channel(&self) -> (Sender<T>, Receiver<T>) {
49        let token = self.0.get_mut().insert(Inner {
50            flags: Flags::all(),
51            value: None,
52            tx_waker: LocalWaker::default(),
53            rx_waker: LocalWaker::default(),
54        });
55
56        (
57            Sender {
58                token,
59                inner: self.0.clone(),
60            },
61            Receiver {
62                token,
63                inner: self.0.clone(),
64            },
65        )
66    }
67
68    /// Shrinks the capacity of the pool as much as possible.
69    pub fn shrink_to_fit(&self) {
70        self.0.get_mut().shrink_to_fit();
71    }
72}
73
74impl<T> Clone for Pool<T> {
75    fn clone(&self) -> Self {
76        Pool(self.0.clone())
77    }
78}
79
80/// Represents the completion half of a oneshot through which the result of a
81/// computation is signaled.
82#[derive(Debug)]
83pub struct Sender<T> {
84    token: usize,
85    inner: Cell<Slab<Inner<T>>>,
86}
87
88/// A future representing the completion of a computation happening elsewhere in
89/// memory.
90#[derive(Debug)]
91#[must_use = "futures do nothing unless polled"]
92pub struct Receiver<T> {
93    token: usize,
94    inner: Cell<Slab<Inner<T>>>,
95}
96
97// A channel's slot stays occupied while its sender or receiver is alive.
98// Slot references must not be held across user code, which may insert into
99// the slab and reallocate it, see `Cell`.
100#[allow(clippy::mut_from_ref)]
101fn get_inner<T>(inner: &Cell<Slab<Inner<T>>>, token: usize) -> &mut Inner<T> {
102    &mut inner.get_mut()[token]
103}
104
105fn get_inner_ref<T>(inner: &Cell<Slab<Inner<T>>>, token: usize) -> &Inner<T> {
106    &inner.get_ref()[token]
107}
108
109/// Removes the channel slot, dropping its contents after the borrow ends.
110fn remove<T>(inner: &Cell<Slab<Inner<T>>>, token: usize) {
111    let removed = inner.get_mut().remove(token);
112    drop(removed);
113}
114
115// The oneshots do not ever project Pin to the inner T
116impl<T> Unpin for Receiver<T> {}
117impl<T> Unpin for Sender<T> {}
118
119impl<T> Sender<T> {
120    /// Completes this oneshot with a successful result.
121    ///
122    /// This function will consume `self` and indicate to the other end, the
123    /// `Receiver`, that the value provided is the result of the computation this
124    /// represents.
125    ///
126    /// If the value is successfully enqueued for the remote end to receive,
127    /// then `Ok(())` is returned. If the receiving end was dropped before
128    /// this function was called, however, then `Err` is returned with the value
129    /// provided.
130    pub fn send(self, val: T) -> Result<(), T> {
131        let inner = get_inner(&self.inner, self.token);
132        if inner.flags.contains(Flags::RECEIVER) {
133            inner.value = Some(val);
134            let waker = inner.rx_waker.take_local();
135            wake(waker);
136            Ok(())
137        } else {
138            Err(val)
139        }
140    }
141
142    /// Tests to see whether this `Sender`'s corresponding `Receiver`
143    /// has gone away.
144    pub fn is_canceled(&self) -> bool {
145        !get_inner_ref(&self.inner, self.token)
146            .flags
147            .contains(Flags::RECEIVER)
148    }
149
150    /// Polls the channel to determine if receiving path is dropped
151    pub fn poll_canceled(&self, cx: &mut Context<'_>) -> Poll<()> {
152        if self.is_canceled() {
153            return Poll::Ready(());
154        }
155        LocalWaker::register_in(
156            || &get_inner_ref(&self.inner, self.token).tx_waker,
157            cx.waker(),
158        );
159
160        // the waker callbacks may have dropped the receiver
161        if self.is_canceled() {
162            Poll::Ready(())
163        } else {
164            Poll::Pending
165        }
166    }
167}
168
169impl<T> Drop for Sender<T> {
170    fn drop(&mut self) {
171        let inner = get_inner(&self.inner, self.token);
172        if inner.flags.contains(Flags::RECEIVER) {
173            inner.flags.remove(Flags::SENDER);
174            let waker = inner.rx_waker.take_local();
175            wake(waker);
176        } else {
177            remove(&self.inner, self.token);
178        }
179    }
180}
181
182impl<T> Receiver<T> {
183    /// Polls for the value.
184    ///
185    /// Returns [`Canceled`] if the sender is dropped without sending a value.
186    pub fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Result<T, Canceled>> {
187        if let Poll::Ready(res) = self.try_recv() {
188            return Poll::Ready(res);
189        }
190        LocalWaker::register_in(
191            || &get_inner_ref(&self.inner, self.token).rx_waker,
192            cx.waker(),
193        );
194
195        // the waker callbacks may have sent the value or dropped the sender
196        self.try_recv()
197    }
198
199    fn try_recv(&self) -> Poll<Result<T, Canceled>> {
200        let inner = get_inner(&self.inner, self.token);
201        if let Some(val) = inner.value.take() {
202            Poll::Ready(Ok(val))
203        } else if inner.flags.contains(Flags::SENDER) {
204            Poll::Pending
205        } else {
206            Poll::Ready(Err(Canceled))
207        }
208    }
209}
210
211impl<T> Drop for Receiver<T> {
212    fn drop(&mut self) {
213        let inner = get_inner(&self.inner, self.token);
214        if inner.flags.contains(Flags::SENDER) {
215            inner.flags.remove(Flags::RECEIVER);
216            let waker = inner.tx_waker.take_local();
217            wake(waker);
218        } else {
219            remove(&self.inner, self.token);
220        }
221    }
222}
223
224impl<T> Future for Receiver<T> {
225    type Output = Result<T, Canceled>;
226
227    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
228        self.poll_recv(cx)
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use crate::future::lazy;
236    use crate::task::hooks::{ON_WAKE, hook_waker};
237
238    /// STATEMENT: Pooled one-shot channels preserve delivery and cancellation behavior.
239    ///
240    /// HOW:
241    /// - Use new, cloned, and default pools to deliver values and inspect debug representations.
242    /// - Poll before send or endpoint drop and verify receiver errors and sender cancellation state.
243    #[ntex::test]
244    async fn test_pool() {
245        let p = new();
246        p.shrink_to_fit();
247        assert!(format!("{p:?}").contains("Pool"));
248
249        let (tx, rx) = p.channel();
250
251        tx.send("test").unwrap();
252        assert_eq!(rx.await.unwrap(), "test");
253        assert!(format!("{Canceled}").contains("canceled"));
254        assert!(format!("{Canceled:?}").contains("Canceled"));
255
256        let p2 = p.clone();
257        let (tx, rx) = p2.channel();
258        assert!(!tx.is_canceled());
259        drop(rx);
260        assert!(tx.is_canceled());
261        assert!(tx.send("test").is_err());
262
263        let (tx, rx) = new::<&'static str>().channel();
264        drop(tx);
265        assert!(rx.await.is_err());
266
267        let (tx, mut rx) = new::<&'static str>().channel();
268        assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
269        tx.send("test").unwrap();
270        assert_eq!(rx.await.unwrap(), "test");
271
272        let (tx, mut rx) = new::<&'static str>().channel();
273        assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
274        drop(tx);
275        assert!(rx.await.is_err());
276
277        let (mut tx, rx) = new::<&'static str>().channel();
278        assert!(!tx.is_canceled());
279        assert_eq!(
280            lazy(|cx| Pin::new(&mut tx).poll_canceled(cx)).await,
281            Poll::Pending
282        );
283        drop(rx);
284        assert!(tx.is_canceled());
285        assert_eq!(
286            lazy(|cx| Pin::new(&mut tx).poll_canceled(cx)).await,
287            Poll::Ready(())
288        );
289
290        let p = Pool::default();
291        let (tx, rx) = p.channel();
292        tx.send("test").unwrap();
293        assert_eq!(rx.await.unwrap(), "test");
294    }
295
296    /// STATEMENT: Pooled channels access and release their shared slab slots without
297    /// undefined behavior.
298    ///
299    /// HOW:
300    /// - Poll a receiver and sender pending with `Waker::noop`, send a `String`, and receive it.
301    /// - Drop a sender before sending and check the receiver gets `Canceled`.
302    /// - Drop a receiver and check the sender is canceled and `send` returns the value.
303    /// - Drop the remaining receiver and check the pool reports no occupied slots.
304    #[test]
305    fn miri_pool_channels_share_slab_slots() {
306        let mut cx = Context::from_waker(std::task::Waker::noop());
307        let pool = new::<String>();
308
309        let (tx, rx) = pool.channel();
310        assert!(rx.poll_recv(&mut cx).is_pending());
311        assert!(tx.poll_canceled(&mut cx).is_pending());
312        assert!(!tx.is_canceled());
313        tx.send("a".to_string()).unwrap();
314        assert_eq!(rx.poll_recv(&mut cx), Poll::Ready(Ok("a".to_string())));
315        drop(rx);
316
317        let (tx, rx) = pool.channel();
318        drop(tx);
319        assert_eq!(rx.poll_recv(&mut cx), Poll::Ready(Err(Canceled)));
320
321        let (tx2, rx2) = pool.channel();
322        drop(rx2);
323        assert!(tx2.is_canceled());
324        assert!(tx2.poll_canceled(&mut cx).is_ready());
325        assert_eq!(tx2.send("b".to_string()), Err("b".to_string()));
326
327        drop(rx);
328        assert!(format!("{pool:?}").contains("size: 0"));
329        pool.shrink_to_fit();
330    }
331
332    /// STATEMENT: Dropping a sender is sound when the receiver's wake callback drops the receiver and grows the pool.
333    ///
334    /// HOW:
335    /// - Register the receiver with `hook_waker`, then move it into an `ON_WAKE` hook that drops it and creates 64 channels.
336    /// - Drop the sender and check the pool holds only the 64 new channels.
337    /// - Check a new channel still delivers a value.
338    #[test]
339    fn miri_sender_drop_with_reentrant_wake() {
340        let pool = new::<usize>();
341        let (tx, rx) = pool.channel();
342        let waker = hook_waker();
343        let mut cx = Context::from_waker(&waker);
344        assert!(rx.poll_recv(&mut cx).is_pending());
345
346        let extra = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
347        let (p, e) = (pool.clone(), extra.clone());
348        ON_WAKE.set(Some(Box::new(move || {
349            drop(rx);
350            e.borrow_mut().extend((0..64).map(|_| p.channel()));
351        })));
352        drop(tx);
353
354        assert_eq!(extra.borrow().len(), 64);
355        assert!(format!("{pool:?}").contains("size: 64"));
356
357        let (tx, rx) = pool.channel();
358        tx.send(5).unwrap();
359        assert_eq!(rx.poll_recv(&mut cx), Poll::Ready(Ok(5)));
360    }
361}