Skip to main content

flume/
async.rs

1//! Futures and other types that allow asynchronous interaction with channels.
2
3use std::{
4    future::Future,
5    pin::Pin,
6    task::{Context, Poll, Waker},
7    any::Any,
8    ops::Deref,
9};
10use crate::*;
11use futures_core::{stream::{Stream, FusedStream}, future::FusedFuture};
12use futures_sink::Sink;
13use spin1::Mutex as Spinlock;
14
15struct AsyncSignal {
16    waker: Spinlock<Waker>,
17    woken: AtomicBool,
18    stream: bool,
19}
20
21impl AsyncSignal {
22    fn new(cx: &Context, stream: bool) -> Self {
23        AsyncSignal {
24            waker: Spinlock::new(cx.waker().clone()),
25            woken: AtomicBool::new(false),
26            stream,
27        }
28    }
29}
30
31impl Signal for AsyncSignal {
32    fn fire(&self) -> bool {
33        self.woken.store(true, Ordering::SeqCst);
34        self.waker.lock().wake_by_ref();
35        self.stream
36    }
37
38    fn as_any(&self) -> &(dyn Any + 'static) { self }
39    fn as_ptr(&self) -> *const () { self as *const _ as *const () }
40}
41
42impl<T> Hook<T, AsyncSignal> {
43    // Update the hook to point to the given Waker.
44    // Returns whether the hook has been previously awakened
45    fn update_waker(&self, cx_waker: &Waker) -> bool {
46        let mut waker = self.1.waker.lock();
47        let woken = self.1.woken.load(Ordering::SeqCst);
48        if !waker.will_wake(cx_waker) {
49            *waker = cx_waker.clone();
50
51            // Avoid the edge case where the waker was woken just before the wakers were
52            // swapped.
53            if woken {
54                cx_waker.wake_by_ref();
55            }
56        }
57        woken
58    }
59}
60
61#[derive(Clone)]
62enum OwnedOrRef<'a, T> {
63    Owned(T),
64    Ref(&'a T),
65}
66
67impl<'a, T> Deref for OwnedOrRef<'a, T> {
68    type Target = T;
69
70    fn deref(&self) -> &T {
71        match self {
72            OwnedOrRef::Owned(arc) => &arc,
73            OwnedOrRef::Ref(r) => r,
74        }
75    }
76}
77
78impl<T> Sender<T> {
79    /// Asynchronously send a value into the channel, returning an error if all receivers have been
80    /// dropped. If the channel is bounded and is full, the returned future will yield to the async
81    /// runtime.
82    ///
83    /// In the current implementation, the returned future will not yield to the async runtime if the
84    /// channel is unbounded. This may change in later versions.
85    pub fn send_async(&self, item: T) -> SendFut<T> {
86        SendFut {
87            sender: OwnedOrRef::Ref(&self),
88            hook: Some(SendState::NotYetSent(item)),
89        }
90    }
91
92    /// Convert this sender into a future that asynchronously sends a single message into the channel,
93    /// returning an error if all receivers have been dropped. If the channel is bounded and is full,
94    /// this future will yield to the async runtime.
95    ///
96    /// In the current implementation, the returned future will not yield to the async runtime if the
97    /// channel is unbounded. This may change in later versions.
98    pub fn into_send_async<'a>(self, item: T) -> SendFut<'a, T> {
99        SendFut {
100            sender: OwnedOrRef::Owned(self),
101            hook: Some(SendState::NotYetSent(item)),
102        }
103    }
104
105    /// Create an asynchronous sink that uses this sender to asynchronously send messages into the
106    /// channel. The sender will continue to be usable after the sink has been dropped.
107    ///
108    /// In the current implementation, the returned sink will not yield to the async runtime if the
109    /// channel is unbounded. This may change in later versions.
110    pub fn sink(&self) -> SendSink<'_, T> {
111        SendSink(SendFut {
112            sender: OwnedOrRef::Ref(&self),
113            hook: None,
114        })
115    }
116
117    /// Convert this sender into a sink that allows asynchronously sending messages into the channel.
118    ///
119    /// In the current implementation, the returned sink will not yield to the async runtime if the
120    /// channel is unbounded. This may change in later versions.
121    pub fn into_sink<'a>(self) -> SendSink<'a, T> {
122        SendSink(SendFut {
123            sender: OwnedOrRef::Owned(self),
124            hook: None,
125        })
126    }
127}
128
129enum SendState<T> {
130    NotYetSent(T),
131    QueuedItem(Arc<Hook<T, AsyncSignal>>),
132}
133
134/// A future that sends a value into a channel.
135///
136/// Can be created via [`Sender::send_async`] or [`Sender::into_send_async`].
137#[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"]
138pub struct SendFut<'a, T> {
139    sender: OwnedOrRef<'a, Sender<T>>,
140    // Only none after dropping
141    hook: Option<SendState<T>>,
142}
143
144impl<T> std::marker::Unpin for SendFut<'_, T> {}
145
146impl<'a, T> SendFut<'a, T> {
147    /// Reset the hook, clearing it and removing it from the waiting sender's queue. This is called
148    /// on drop and just before `start_send` in the `Sink` implementation.
149    fn reset_hook(&mut self) {
150        if let Some(SendState::QueuedItem(hook)) = self.hook.take() {
151            let hook: Arc<Hook<T, dyn Signal>> = hook;
152            wait_lock(&self.sender.shared.chan).sending
153                .as_mut()
154                .unwrap().1
155                .retain(|s| s.signal().as_ptr() != hook.signal().as_ptr());
156        }
157    }
158
159    /// See [`Sender::is_disconnected`].
160    pub fn is_disconnected(&self) -> bool {
161        self.sender.is_disconnected()
162    }
163
164    /// See [`Sender::is_empty`].
165    pub fn is_empty(&self) -> bool {
166        self.sender.is_empty()
167    }
168
169    /// See [`Sender::is_full`].
170    pub fn is_full(&self) -> bool {
171        self.sender.is_full()
172    }
173
174    /// See [`Sender::len`].
175    pub fn len(&self) -> usize {
176        self.sender.len()
177    }
178
179    /// See [`Sender::capacity`].
180    pub fn capacity(&self) -> Option<usize> {
181        self.sender.capacity()
182    }
183}
184
185impl<'a, T> Drop for SendFut<'a, T> {
186    fn drop(&mut self) {
187        self.reset_hook()
188    }
189}
190
191
192impl<'a, T> Future for SendFut<'a, T> {
193    type Output = Result<(), SendError<T>>;
194
195    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
196        if let Some(SendState::QueuedItem(hook)) = self.hook.as_ref() {
197            if hook.is_empty() {
198                Poll::Ready(Ok(()))
199            } else if self.sender.shared.is_disconnected() {
200                let item = hook.try_take();
201                self.hook = None;
202                match item {
203                    Some(item) => Poll::Ready(Err(SendError(item))),
204                    None => Poll::Ready(Ok(())),
205                }
206            } else {
207                hook.update_waker(cx.waker());
208                Poll::Pending
209            }
210        } else if let Some(SendState::NotYetSent(item)) = self.hook.take() {
211            let this = self.get_mut();
212            let (shared, this_hook) = (&this.sender.shared, &mut this.hook);
213
214            shared.send(
215                // item
216                item,
217                // should_block
218                true,
219                // make_signal
220                |msg| Hook::slot(Some(msg), AsyncSignal::new(cx, false)),
221                // do_block
222                |hook| {
223                    *this_hook = Some(SendState::QueuedItem(hook));
224                    Poll::Pending
225                },
226            )
227                .map(|r| r.map_err(|err| match err {
228                    TrySendTimeoutError::Disconnected(msg) => SendError(msg),
229                    _ => unreachable!(),
230                }))
231        } else { // Nothing to do
232            Poll::Ready(Ok(()))
233        }
234    }
235}
236
237impl<'a, T> FusedFuture for SendFut<'a, T> {
238    fn is_terminated(&self) -> bool {
239        self.sender.shared.is_disconnected()
240    }
241}
242
243/// A sink that allows sending values into a channel.
244///
245/// Can be created via [`Sender::sink`] or [`Sender::into_sink`].
246pub struct SendSink<'a, T>(SendFut<'a, T>);
247
248impl<'a, T> SendSink<'a, T> {
249    /// Returns a clone of a sending half of the channel of this sink.
250    pub fn sender(&self) -> &Sender<T> {
251        &self.0.sender
252    }
253
254    /// See [`Sender::is_disconnected`].
255    pub fn is_disconnected(&self) -> bool {
256        self.0.is_disconnected()
257    }
258
259    /// See [`Sender::is_empty`].
260    pub fn is_empty(&self) -> bool {
261        self.0.is_empty()
262    }
263
264    /// See [`Sender::is_full`].
265    pub fn is_full(&self) -> bool {
266        self.0.is_full()
267    }
268
269    /// See [`Sender::len`].
270    pub fn len(&self) -> usize {
271        self.0.len()
272    }
273
274    /// See [`Sender::capacity`].
275    pub fn capacity(&self) -> Option<usize> {
276        self.0.capacity()
277    }
278
279    /// Returns whether the SendSinks are belong to the same channel.
280    pub fn same_channel(&self, other: &Self) -> bool {
281        self.sender().same_channel(other.sender())
282    }
283}
284
285impl<'a, T> Sink<T> for SendSink<'a, T> {
286    type Error = SendError<T>;
287
288    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
289        Pin::new(&mut self.0).poll(cx)
290    }
291
292    fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
293        self.0.reset_hook();
294        self.0.hook = Some(SendState::NotYetSent(item));
295
296        Ok(())
297    }
298
299    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
300        Pin::new(&mut self.0).poll(cx) // TODO: A different strategy here?
301    }
302
303    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
304        Pin::new(&mut self.0).poll(cx) // TODO: A different strategy here?
305    }
306}
307
308impl<'a, T> Clone for SendSink<'a, T> {
309    fn clone(&self) -> SendSink<'a, T> {
310        SendSink(SendFut {
311            sender: self.0.sender.clone(),
312            hook: None,
313        })
314    }
315}
316
317impl<T> Receiver<T> {
318    /// Asynchronously receive a value from the channel, returning an error if all senders have been
319    /// dropped. If the channel is empty, the returned future will yield to the async runtime.
320    pub fn recv_async(&self) -> RecvFut<'_, T> {
321        RecvFut::new(OwnedOrRef::Ref(self))
322    }
323
324    /// Convert this receiver into a future that asynchronously receives a single message from the
325    /// channel, returning an error if all senders have been dropped. If the channel is empty, this
326    /// future will yield to the async runtime.
327    pub fn into_recv_async<'a>(self) -> RecvFut<'a, T> {
328        RecvFut::new(OwnedOrRef::Owned(self))
329    }
330
331    /// Create an asynchronous stream that uses this receiver to asynchronously receive messages
332    /// from the channel. The receiver will continue to be usable after the stream has been dropped.
333    pub fn stream(&self) -> RecvStream<'_, T> {
334        RecvStream(RecvFut::new(OwnedOrRef::Ref(self)))
335    }
336
337    /// Convert this receiver into a stream that allows asynchronously receiving messages from the channel.
338    pub fn into_stream<'a>(self) -> RecvStream<'a, T> {
339        RecvStream(RecvFut::new(OwnedOrRef::Owned(self)))
340    }
341}
342
343/// A future which allows asynchronously receiving a message.
344///
345/// Can be created via [`Receiver::recv_async`] or [`Receiver::into_recv_async`].
346#[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"]
347pub struct RecvFut<'a, T> {
348    receiver: OwnedOrRef<'a, Receiver<T>>,
349    hook: Option<Arc<Hook<T, AsyncSignal>>>,
350}
351
352impl<'a, T> RecvFut<'a, T> {
353    fn new(receiver: OwnedOrRef<'a, Receiver<T>>) -> Self {
354        Self {
355            receiver,
356            hook: None,
357        }
358    }
359
360    /// Reset the hook, clearing it and removing it from the waiting receivers queue and waking
361    /// another receiver if this receiver has been woken, so as not to cause any missed wakeups.
362    /// This is called on drop and after a new item is received in `Stream::poll_next`.
363    fn reset_hook(&mut self) {
364        if let Some(hook) = self.hook.take() {
365            let hook: Arc<Hook<T, dyn Signal>> = hook;
366            let mut chan = wait_lock(&self.receiver.shared.chan);
367            // We'd like to use `Arc::ptr_eq` here but it doesn't seem to work consistently with wide pointers?
368            chan.waiting.retain(|s| s.signal().as_ptr() != hook.signal().as_ptr());
369            if hook.signal().as_any().downcast_ref::<AsyncSignal>().unwrap().woken.load(Ordering::SeqCst) {
370                // If this signal has been fired, but we're being dropped (and so not listening to it),
371                // pass the signal on to another receiver
372                chan.try_wake_receiver_if_pending();
373            }
374        }
375    }
376
377    fn poll_inner(
378        self: Pin<&mut Self>,
379        cx: &mut Context,
380        stream: bool,
381    ) -> Poll<Result<T, RecvError>> {
382        if self.hook.is_some() {
383            match self.receiver.shared.recv_sync(None) {
384                Ok(msg) => return Poll::Ready(Ok(msg)),
385                Err(TryRecvTimeoutError::Disconnected) => {
386                    return Poll::Ready(Err(RecvError::Disconnected))
387                }
388                _ => (),
389            }
390
391            let hook = self.hook.as_ref().map(Arc::clone).unwrap();
392            if hook.update_waker(cx.waker()) {
393                // If the previous hook was awakened, we need to insert it back to the
394                // queue, otherwise, it remains valid.
395                wait_lock(&self.receiver.shared.chan)
396                    .waiting
397                    .push_back(hook);
398            }
399            // To avoid a missed wakeup, re-check disconnect status here because the channel might have
400            // gotten shut down before we had a chance to push our hook
401            if self.receiver.shared.is_disconnected() {
402                // And now, to avoid a race condition between the first recv attempt and the disconnect check we
403                // just performed, attempt to recv again just in case we missed something.
404                Poll::Ready(
405                    self.receiver
406                        .shared
407                        .recv_sync(None)
408                        .map(Ok)
409                        .unwrap_or(Err(RecvError::Disconnected)),
410                )
411            } else {
412                Poll::Pending
413            }
414        } else {
415            let mut_self = self.get_mut();
416            let (shared, this_hook) = (&mut_self.receiver.shared, &mut mut_self.hook);
417
418            shared.recv(
419                // should_block
420                true,
421                // make_signal
422                || Hook::trigger(AsyncSignal::new(cx, stream)),
423                // do_block
424                |hook| {
425                    *this_hook = Some(hook);
426                    Poll::Pending
427                },
428            )
429                .map(|r| r.map_err(|err| match err {
430                    TryRecvTimeoutError::Disconnected => RecvError::Disconnected,
431                    _ => unreachable!(),
432                }))
433        }
434    }
435
436    /// See [`Receiver::is_disconnected`].
437    pub fn is_disconnected(&self) -> bool {
438        self.receiver.is_disconnected()
439    }
440
441    /// See [`Receiver::is_empty`].
442    pub fn is_empty(&self) -> bool {
443        self.receiver.is_empty()
444    }
445
446    /// See [`Receiver::is_full`].
447    pub fn is_full(&self) -> bool {
448        self.receiver.is_full()
449    }
450
451    /// See [`Receiver::len`].
452    pub fn len(&self) -> usize {
453        self.receiver.len()
454    }
455
456    /// See [`Receiver::capacity`].
457    pub fn capacity(&self) -> Option<usize> {
458        self.receiver.capacity()
459    }
460}
461
462impl<'a, T> Drop for RecvFut<'a, T> {
463    fn drop(&mut self) {
464        self.reset_hook();
465    }
466}
467
468impl<'a, T> Future for RecvFut<'a, T> {
469    type Output = Result<T, RecvError>;
470
471    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
472        self.poll_inner(cx, false) // stream = false
473    }
474}
475
476impl<'a, T> FusedFuture for RecvFut<'a, T> {
477    fn is_terminated(&self) -> bool {
478        self.receiver.shared.is_disconnected() && self.receiver.shared.is_empty()
479    }
480}
481
482/// A stream which allows asynchronously receiving messages.
483///
484/// Can be created via [`Receiver::stream`] or [`Receiver::into_stream`].
485pub struct RecvStream<'a, T>(RecvFut<'a, T>);
486
487impl<'a, T> RecvStream<'a, T> {
488    /// See [`Receiver::is_disconnected`].
489    pub fn is_disconnected(&self) -> bool {
490        self.0.is_disconnected()
491    }
492
493    /// See [`Receiver::is_empty`].
494    pub fn is_empty(&self) -> bool {
495        self.0.is_empty()
496    }
497
498    /// See [`Receiver::is_full`].
499    pub fn is_full(&self) -> bool {
500        self.0.is_full()
501    }
502
503    /// See [`Receiver::len`].
504    pub fn len(&self) -> usize {
505        self.0.len()
506    }
507
508    /// See [`Receiver::capacity`].
509    pub fn capacity(&self) -> Option<usize> {
510        self.0.capacity()
511    }
512
513    /// Returns whether the SendSinks are belong to the same channel.
514    pub fn same_channel(&self, other: &Self) -> bool {
515        self.0.receiver.same_channel(&*other.0.receiver)
516    }
517}
518
519impl<'a, T> Clone for RecvStream<'a, T> {
520    fn clone(&self) -> RecvStream<'a, T> {
521        RecvStream(RecvFut::new(self.0.receiver.clone()))
522    }
523}
524
525impl<'a, T> Stream for RecvStream<'a, T> {
526    type Item = T;
527
528    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
529        match Pin::new(&mut self.0).poll_inner(cx, true) { // stream = true
530            Poll::Pending => Poll::Pending,
531            Poll::Ready(item) => {
532                self.0.reset_hook();
533                Poll::Ready(item.ok())
534            }
535        }
536    }
537}
538
539impl<'a, T> FusedStream for RecvStream<'a, T> {
540    fn is_terminated(&self) -> bool {
541        self.0.is_terminated()
542    }
543}