Skip to main content

datafusion_execution/
async_stream.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use futures::Stream;
6use futures::future::FusedFuture;
7use futures::stream::FusedStream;
8use parking_lot::Mutex;
9use pin_project_lite::pin_project;
10use std::pin::Pin;
11use std::sync::Arc;
12use std::task::{Context, Poll};
13
14/// Creates a [`Stream`] from an async generator function.
15///
16/// The `generator` closure receives an [`Emitter<T>`] and runs as an async
17/// block. Each `emitter.emit(value).await` call suspends the generator and
18/// produces the next item in the stream. The stream ends when the generator
19/// future resolves.
20///
21/// # Example
22///
23/// ```
24/// use datafusion_execution::async_stream;
25/// use futures::StreamExt;
26///
27/// # #[tokio::main(flavor = "current_thread")]
28/// # async fn main() {
29/// let stream = async_stream(|mut emitter| async move {
30///     for i in 0_i32..3 {
31///         emitter.emit(i).await;
32///     }
33/// });
34///
35/// let values: Vec<i32> = stream.collect().await;
36/// assert_eq!(values, vec![0, 1, 2]);
37/// # }
38/// ```
39pub fn async_stream<T, F: Future<Output = ()>>(
40    generator: impl FnOnce(Emitter<T>) -> F,
41) -> impl FusedStream<Item = T> {
42    let (emitter, receiver) = tx_rx();
43    AsyncStream::new(receiver, generator(emitter))
44}
45
46/// Creates a fallible [`Stream`] from an async generator function.
47///
48/// The `generator` closure receives a [`TryEmitter<T, E>`] and runs as an
49/// async block that returns `Result<(), E>`. Each `emitter.emit(value).await`
50/// call suspends the generator and produces `Ok(value)` as the next stream
51/// item. The `?` operator can be used inside the generator to short-circuit on
52/// errors: the error is emitted as the final `Err(e)` item and the stream
53/// ends. The stream also ends when the generator future resolves to `Ok(())`.
54///
55/// # Example
56///
57/// ```
58/// use datafusion_execution::async_try_stream;
59/// use futures::StreamExt;
60///
61/// # #[tokio::main(flavor = "current_thread")]
62/// # async fn main() {
63/// let stream = async_try_stream(|mut emitter| async move {
64///     emitter.emit(1_i32).await;
65///     emitter.emit(2_i32).await;
66///     Err::<(), _>("something went wrong")?;
67///     emitter.emit(3_i32).await; // never reached
68///     Ok(())
69/// });
70///
71/// let values: Vec<Result<i32, &str>> = stream.collect().await;
72/// assert_eq!(values, vec![Ok(1), Ok(2), Err("something went wrong")]);
73/// # }
74/// ```
75pub fn async_try_stream<T, E, F: Future<Output = Result<(), E>>>(
76    generator: impl FnOnce(TryEmitter<T, E>) -> F,
77) -> impl FusedStream<Item = Result<T, E>> {
78    let (try_emitter, mut emitter, receiver) = try_tx_rx::<T, E>();
79    AsyncStream::new(receiver, async move {
80        if let Err(e) = generator(try_emitter).await {
81            // Fill the slot without suspending so this future completes in the same
82            // poll that yields `Err(e)`: the stream terminates immediately and the
83            // emitter state is dropped (a consumer may never poll again after an
84            // error, which would otherwise keep this future suspended inside `emit`)
85            emitter.set(Err(e));
86        }
87    })
88}
89
90/// Creates an `Emitter`/`Receiver` pair
91fn tx_rx<T>() -> (Emitter<T>, Receiver<T>) {
92    let slot = Arc::new(Mutex::new(None));
93    (
94        Emitter {
95            slot: Arc::clone(&slot),
96        },
97        Receiver { slot },
98    )
99}
100
101/// Creates an `TryEmitter`/`Emitter`/`Receiver` triplet
102#[expect(
103    clippy::type_complexity,
104    reason = "three-element tuple is clearer than an alias here"
105)]
106fn try_tx_rx<T, E>() -> (
107    TryEmitter<T, E>,
108    Emitter<Result<T, E>>,
109    Receiver<Result<T, E>>,
110) {
111    let slot = Arc::new(Mutex::new(None));
112    (
113        TryEmitter {
114            slot: Arc::clone(&slot),
115        },
116        Emitter {
117            slot: Arc::clone(&slot),
118        },
119        Receiver { slot },
120    )
121}
122
123/// Value slot shared between [`Emitter`] and [`Receiver`].
124/// Use `Arc<Mutex>` to ensure the created `Stream` implementations
125/// are both `Send` and `Sync`.
126type SlotRef<T> = Arc<Mutex<Option<T>>>;
127
128/// A handle for emitting values from an [`async_stream`] generator.
129///
130/// The generator closure receives an `Emitter<T>` as its argument.
131pub struct Emitter<T> {
132    slot: SlotRef<T>,
133}
134
135/// A handle for emitting values from an [`async_try_stream`] generator.
136///
137/// The generator closure receives a `TryEmitter<T, E>` as its argument.
138pub struct TryEmitter<T, E> {
139    slot: SlotRef<Result<T, E>>,
140}
141
142struct Receiver<T> {
143    slot: SlotRef<T>,
144}
145
146impl<T> Emitter<T> {
147    /// Returns a `Future` that emits `value` as the next stream item.
148    ///
149    /// The returned future **must be awaited immediately**. On its first poll it
150    /// yields `Poll::Pending`, handing control back to the stream consumer so it
151    /// can observe the emitted value. On the next poll (triggered by the
152    /// consumer calling `poll_next` again) it completes with `Poll::Ready(())`,
153    /// resuming the generator.
154    ///
155    /// # Panics
156    ///
157    /// Panics if `emit` is called a second time before the previous future has
158    /// been awaited, because doing so would silently overwrite the unconsumed
159    /// value.
160    pub fn emit(&mut self, value: T) -> impl FusedFuture<Output = ()> {
161        self.set(value);
162        Emit { done: false }
163    }
164
165    /// Places `value` in the slot without suspending the generator. Only useful
166    /// as the very last action before the generator future completes, since
167    /// nothing yields control back to the consumer in between.
168    fn set(&mut self, value: T) {
169        let mut guard = self.slot.lock();
170        match &mut *guard {
171            Some(_) => panic!("Misuse: await was not called after calling emit"),
172            slot => *slot = Some(value),
173        }
174    }
175}
176
177impl<T, E> TryEmitter<T, E> {
178    /// Emits `Ok(value)` as the next stream item and suspends the generator.
179    ///
180    /// Behaves identically to [`Emitter::emit`]: the returned future must be
181    /// awaited immediately and yields `Poll::Pending` on its first poll to
182    /// transfer control to the stream consumer.
183    ///
184    /// # Panics
185    ///
186    /// Panics if called before the previous emit future has been awaited.
187    pub fn emit(&mut self, value: T) -> impl FusedFuture<Output = ()> {
188        let mut guard = self.slot.lock();
189        match &mut *guard {
190            Some(_) => panic!("Misuse: await was not called after calling emit"),
191            slot => *slot = Some(Ok::<T, E>(value)),
192        }
193
194        Emit { done: false }
195    }
196}
197
198struct Emit {
199    done: bool,
200}
201
202impl FusedFuture for Emit {
203    fn is_terminated(&self) -> bool {
204        self.done
205    }
206}
207
208impl Future for Emit {
209    type Output = ();
210
211    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
212        if !self.done {
213            self.done = true;
214            // Poll::Pending causes the generator to yield, returning control back to the
215            // calling Stream
216            Poll::Pending
217        } else {
218            Poll::Ready(())
219        }
220    }
221}
222
223pin_project! {
224    struct AsyncStream<T, U> {
225        rx: Receiver<T>,
226        done: bool,
227        #[pin]
228        generator: U,
229    }
230}
231
232impl<T, U> AsyncStream<T, U> {
233    fn new(rx: Receiver<T>, generator: U) -> AsyncStream<T, U> {
234        AsyncStream {
235            rx,
236            done: false,
237            generator,
238        }
239    }
240}
241
242impl<T, U> FusedStream for AsyncStream<T, U>
243where
244    U: Future<Output = ()>,
245{
246    fn is_terminated(&self) -> bool {
247        self.done
248    }
249}
250
251impl<T, U> Stream for AsyncStream<T, U>
252where
253    U: Future<Output = ()>,
254{
255    type Item = T;
256
257    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
258        let this = self.project();
259
260        if *this.done {
261            return Poll::Ready(None);
262        }
263
264        // The `Option::take` call below ensures the next time poll is called the slot is
265        // already set to None
266        debug_assert!(this.rx.slot.lock().is_none());
267        let res = this.generator.poll(cx);
268        *this.done = res.is_ready();
269
270        match this.rx.slot.lock().take() {
271            // Generator filled slot -> return next stream item
272            Some(v) => Poll::Ready(Some(v)),
273            // Generator did not fill slot and completed -> return None to indicate end of stream
274            None if *this.done => Poll::Ready(None),
275            // Generator did not fill slot and not completed -> return Pending since some Future
276            // other than Emit returned Pending.
277            None => Poll::Pending,
278        }
279    }
280
281    fn size_hint(&self) -> (usize, Option<usize>) {
282        if self.done { (0, Some(0)) } else { (0, None) }
283    }
284}
285
286#[cfg(test)]
287mod test {
288    use crate::async_stream::Emitter;
289    use crate::{async_stream, async_try_stream};
290    use futures::stream::FusedStream;
291    use futures::{Stream, StreamExt, pin_mut};
292    use std::pin::Pin;
293    use std::sync::Arc;
294    use std::sync::atomic::{AtomicUsize, Ordering};
295    use std::task::{Context, Poll};
296    use tokio::sync::mpsc;
297
298    #[tokio::test]
299    async fn noop_stream() {
300        let s = async_stream(|_: Emitter<()>| async {});
301        pin_mut!(s);
302
303        assert_eq!(s.next().await, None);
304    }
305
306    #[tokio::test]
307    async fn empty_stream() {
308        let mut ran = false;
309
310        {
311            let r = &mut ran;
312            let s = async_stream(|_: Emitter<()>| async {
313                *r = true;
314                println!("hello world!");
315            });
316            pin_mut!(s);
317
318            assert_eq!(s.next().await, None);
319        }
320
321        assert!(ran);
322    }
323
324    #[tokio::test]
325    async fn emit_single_value() {
326        let s = async_stream(|mut emitter| async move {
327            emitter.emit("hello").await;
328        });
329
330        let values: Vec<_> = s.collect().await;
331
332        assert_eq!(1, values.len());
333        assert_eq!("hello", values[0]);
334    }
335
336    #[tokio::test]
337    async fn fused() {
338        let s = async_stream(|mut emitter| async move {
339            emitter.emit("hello").await;
340        });
341        pin_mut!(s);
342
343        assert!(!s.is_terminated());
344        assert_eq!(s.next().await, Some("hello"));
345        assert_eq!(s.next().await, None);
346
347        assert!(s.is_terminated());
348        // This should return None from now on
349        assert_eq!(s.next().await, None);
350    }
351
352    #[tokio::test]
353    async fn emit_multi_value() {
354        let s = async_stream(|mut emitter| async move {
355            emitter.emit("hello").await;
356            emitter.emit("world").await;
357            emitter.emit("dizzy").await;
358        });
359
360        let values: Vec<_> = s.collect().await;
361
362        assert_eq!(3, values.len());
363        assert_eq!("hello", values[0]);
364        assert_eq!("world", values[1]);
365        assert_eq!("dizzy", values[2]);
366    }
367
368    #[tokio::test]
369    #[should_panic = "await was not called after calling emit"]
370    async fn emit_without_await() {
371        let s = async_stream(|mut emitter| async move {
372            #[expect(clippy::let_underscore_future)]
373            {
374                let _ = emitter.emit("hello");
375                let _ = emitter.emit("world");
376            }
377        });
378
379        let _: Vec<_> = s.collect().await;
380    }
381
382    #[tokio::test]
383    async fn unit_emit_in_select() {
384        use tokio::select;
385
386        #[expect(clippy::unused_async)]
387        async fn do_stuff_async() {}
388
389        let s = async_stream(|mut emitter| async move {
390            select! {
391                _ = do_stuff_async() => emitter.emit(()).await,
392                else => emitter.emit(()).await,
393            }
394        });
395
396        let values: Vec<_> = s.collect().await;
397        assert_eq!(values.len(), 1);
398    }
399
400    #[tokio::test]
401    async fn emit_with_select() {
402        use tokio::select;
403
404        #[expect(clippy::unused_async)]
405        async fn do_stuff_async() {}
406        #[expect(clippy::unused_async)]
407        async fn more_async_work() {}
408
409        let s = async_stream(|mut emitter| async move {
410            select! {
411                _ = do_stuff_async() => emitter.emit("hey").await,
412                _ = more_async_work() => emitter.emit("hey").await,
413                else => emitter.emit("hey").await,
414            }
415        });
416
417        let values: Vec<_> = s.collect().await;
418        assert_eq!(values, vec!["hey"]);
419    }
420
421    #[tokio::test]
422    async fn return_stream() {
423        fn build_stream() -> impl Stream<Item = u32> {
424            async_stream(|mut emitter| async move {
425                emitter.emit(1).await;
426                emitter.emit(2).await;
427                emitter.emit(3).await;
428            })
429        }
430
431        let s = build_stream();
432
433        let values: Vec<_> = s.collect().await;
434        assert_eq!(3, values.len());
435        assert_eq!(1, values[0]);
436        assert_eq!(2, values[1]);
437        assert_eq!(3, values[2]);
438    }
439
440    #[tokio::test]
441    async fn consume_channel() {
442        let (tx, mut rx) = mpsc::channel(10);
443
444        let s = async_stream(|mut emitter| async move {
445            while let Some(v) = rx.recv().await {
446                emitter.emit(v).await;
447            }
448        });
449
450        pin_mut!(s);
451
452        for i in 0..3 {
453            assert!(tx.send(i).await.is_ok());
454            assert_eq!(Some(i), s.next().await);
455        }
456
457        drop(tx);
458        assert_eq!(None, s.next().await);
459    }
460
461    #[tokio::test]
462    async fn borrow_self() {
463        struct Data(String);
464
465        impl Data {
466            fn stream(&self) -> impl Stream<Item = &str> + '_ {
467                async_stream(move |mut emitter| async move {
468                    emitter.emit(&self.0[..]).await;
469                })
470            }
471        }
472
473        let data = Data("hello".to_string());
474        let s = data.stream();
475        pin_mut!(s);
476
477        assert_eq!(Some("hello"), s.next().await);
478    }
479
480    #[tokio::test]
481    async fn stream_in_stream() {
482        let s = async_stream(|mut emitter| async move {
483            let s = async_stream(|mut inner_emitter| async move {
484                for i in 0..3 {
485                    inner_emitter.emit(i).await;
486                }
487            });
488
489            pin_mut!(s);
490            while let Some(v) = s.next().await {
491                emitter.emit(v).await;
492            }
493        });
494
495        let values: Vec<_> = s.collect().await;
496        assert_eq!(3, values.len());
497    }
498
499    // Demonstrates that capturing an outer Emitter<T> inside an inner async_stream with a
500    // different item type is no longer undefined behaviour: the outer emitter writes to its own
501    // typed slot, so the inner stream never sees any values.  The outer stream receives the
502    // "foo" strings instead because they land in its slot.
503    #[tokio::test]
504    async fn stream_in_stream_misuse() {
505        let s = async_stream(|mut emitter| async move {
506            let s = async_stream(|_inner_emitter: Emitter<i32>| async move {
507                for _i in 0..3 {
508                    emitter.emit("foo").await;
509                }
510            });
511
512            pin_mut!(s);
513            while let Some(v) = s.next().await {
514                println!("{v}");
515            }
516        });
517
518        let values: Vec<_> = s.collect().await;
519        assert_eq!(3, values.len());
520    }
521
522    #[tokio::test]
523    async fn emit_non_unpin_value() {
524        let s: Vec<_> = async_stream(|mut emitter| async move {
525            for i in 0..3 {
526                emitter.emit(async move { i }).await;
527            }
528        })
529        .buffered(1)
530        .collect()
531        .await;
532
533        assert_eq!(s, vec![0, 1, 2]);
534    }
535
536    #[tokio::test]
537    async fn should_not_call_handler_function_if_not_polled() {
538        let _ = async_stream(|_: Emitter<()>| async move {
539            panic!("should not be called");
540        });
541    }
542
543    #[tokio::test]
544    async fn should_not_continue_until_next_poll() {
545        let s = async_stream(|mut emitter| async move {
546            emitter.emit("hey").await;
547            panic!("make sure poll based and not push based");
548        });
549        pin_mut!(s);
550        let _ = s.next().await;
551    }
552
553    #[test]
554    fn inner_try_stream() {
555        use tokio::select;
556
557        #[expect(clippy::unused_async)]
558        async fn do_stuff_async() {}
559
560        let _ = async_stream(|mut emitter| async move {
561            select! {
562                _ = do_stuff_async() => {
563                    let another_s = async_try_stream(|mut inner_emitter| async move {
564                        inner_emitter.emit(()).await;
565                        Ok(())
566                    });
567                    let _: Result<(), ()> = Box::pin(another_s).next().await.unwrap();
568                },
569                else => {},
570            }
571            emitter.emit(()).await;
572        });
573    }
574
575    #[tokio::test]
576    async fn single_err() {
577        let s = async_try_stream(|mut emitter| async move {
578            if true {
579                Err("hello")?;
580            } else {
581                emitter.emit("world").await;
582            }
583
584            unreachable!();
585        });
586
587        let values: Vec<_> = s.collect().await;
588        assert_eq!(1, values.len());
589        assert_eq!(Err("hello"), values[0]);
590    }
591
592    #[tokio::test]
593    async fn emit_then_err() {
594        let s = async_try_stream(|mut emitter| async move {
595            emitter.emit("hello").await;
596            Err("world")?;
597            unreachable!();
598        });
599
600        let values: Vec<_> = s.collect().await;
601        assert_eq!(2, values.len());
602        assert_eq!(Ok("hello"), values[0]);
603        assert_eq!(Err("world"), values[1]);
604    }
605
606    #[tokio::test]
607    async fn convert_err() {
608        struct ErrorA(u8);
609        #[derive(PartialEq, Debug)]
610        struct ErrorB(u8);
611        impl From<ErrorA> for ErrorB {
612            fn from(a: ErrorA) -> ErrorB {
613                ErrorB(a.0)
614            }
615        }
616
617        fn test() -> impl Stream<Item = Result<&'static str, ErrorB>> {
618            async_try_stream(|mut emitter| async move {
619                if true {
620                    Err(ErrorA(1))?;
621                } else {
622                    Err(ErrorB(2))?;
623                }
624                emitter.emit("unreachable").await;
625                Ok(())
626            })
627        }
628
629        let values: Vec<_> = test().collect().await;
630        assert_eq!(1, values.len());
631        assert_eq!(Err(ErrorB(1)), values[0]);
632    }
633
634    #[tokio::test]
635    async fn multi_try() {
636        fn test() -> impl Stream<Item = Result<i32, String>> {
637            async_try_stream(|mut emitter| async move {
638                let a = Ok::<_, String>(Ok::<_, String>(123))??;
639                for _ in 1..10 {
640                    emitter.emit(a).await;
641                }
642                Ok(())
643            })
644        }
645        let values: Vec<_> = test().collect().await;
646        assert_eq!(9, values.len());
647        assert_eq!(
648            std::iter::repeat_n(123, 9).map(Ok).collect::<Vec<_>>(),
649            values
650        );
651    }
652
653    struct DropGuard(Arc<AtomicUsize>);
654
655    impl Drop for DropGuard {
656        fn drop(&mut self) {
657            self.0.fetch_add(1, Ordering::SeqCst);
658        }
659    }
660
661    #[tokio::test]
662    async fn generator_freed_on_done() {
663        let drops = Arc::new(AtomicUsize::new(0));
664        let guard = DropGuard(Arc::clone(&drops));
665
666        let s = async_stream(|mut emitter| async move {
667            let _guard = guard;
668            emitter.emit(1).await;
669        });
670        pin_mut!(s);
671
672        assert_eq!(s.next().await, Some(1));
673        assert_eq!(s.next().await, None);
674
675        // State captured by the generator is dropped as soon as it completes
676        // (async blocks drop their locals on return), even though the stream
677        // itself is still alive
678        assert_eq!(drops.load(Ordering::SeqCst), 1);
679        assert_eq!(s.next().await, None);
680    }
681
682    #[tokio::test]
683    async fn generator_freed_on_emitted_error() {
684        let drops = Arc::new(AtomicUsize::new(0));
685        let guard = DropGuard(Arc::clone(&drops));
686
687        let s = async_try_stream(|mut emitter| async move {
688            let _guard = guard;
689            emitter.emit(1).await;
690            Err("boom")
691        });
692        pin_mut!(s);
693
694        assert_eq!(s.next().await, Some(Ok(1)));
695        assert_eq!(s.next().await, Some(Err("boom")));
696
697        // The stream terminates in the same poll that yields the error, so the
698        // generator state is freed even if the consumer never polls again
699        assert!(s.is_terminated());
700        assert_eq!(drops.load(Ordering::SeqCst), 1);
701
702        // Polling again after the error just returns None
703        assert_eq!(s.next().await, None);
704    }
705
706    use pin_project_lite::pin_project;
707
708    pin_project! {
709        struct MyStream<T: Stream> {
710            #[pin]
711            input: T,
712        }
713    }
714
715    impl<T: Stream> Stream for MyStream<T> {
716        type Item = T::Item;
717
718        fn poll_next(
719            self: Pin<&mut Self>,
720            cx: &mut Context<'_>,
721        ) -> Poll<Option<Self::Item>> {
722            let this = self.project();
723            this.input.poll_next(cx)
724        }
725    }
726
727    #[tokio::test]
728    async fn emit_does_not_hold_on_value() {
729        let waker = futures::task::noop_waker_ref();
730        let mut cx = Context::from_waker(waker);
731
732        let run = Arc::<AtomicUsize>::new(AtomicUsize::new(0));
733        let moved = Arc::clone(&run);
734        let s = async_stream(|mut emitter| async move {
735            for _ in 0..2 {
736                let before = moved.fetch_add(1, Ordering::SeqCst);
737                emitter.emit(before).await;
738            }
739        });
740
741        let mut my_stream = Box::pin(MyStream { input: s });
742
743        #[derive(Debug, PartialEq)]
744        struct Item {
745            before: usize,
746            result: Poll<Option<usize>>,
747            after: usize,
748        }
749
750        let mut results = vec![];
751
752        assert_eq!(run.load(Ordering::SeqCst), 0);
753
754        while run.load(Ordering::SeqCst) < 2 {
755            let before = run.load(Ordering::SeqCst);
756            let result = my_stream.poll_next_unpin(&mut cx);
757            let after = run.load(Ordering::SeqCst);
758            results.push(Item {
759                before,
760                result,
761                after,
762            });
763        }
764
765        assert_eq!(
766            results,
767            vec![
768                Item {
769                    before: 0,
770                    result: Poll::Ready(Some(0)),
771                    after: 1,
772                },
773                Item {
774                    before: 1,
775                    result: Poll::Ready(Some(1)),
776                    after: 2,
777                }
778            ]
779        );
780    }
781}