rluvaton commented on code in PR #23530:
URL: https://github.com/apache/datafusion/pull/23530#discussion_r3570884432


##########
datafusion/execution/src/async_stream.rs:
##########
@@ -0,0 +1,622 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::Stream;
+use futures::future::FusedFuture;
+use futures::stream::FusedStream;
+use pin_project_lite::pin_project;
+use std::ops::DerefMut;
+use std::pin::Pin;
+use std::sync::{Arc};
+use std::task::{Context, Poll};
+use parking_lot::Mutex;
+
+/// A handle for emitting values from an [`async_stream`] generator.
+///
+/// The generator closure receives an `Emitter<T>` as its argument.
+pub struct Emitter<T> {
+    slot: Arc<Mutex<Option<T>>>,
+}
+
+/// A handle for emitting values from an [`async_try_stream`] generator.
+///
+/// The generator closure receives a `TryEmitter<T, E>` as its argument.
+pub struct TryEmitter<T, E> {
+    slot: Arc<Mutex<Option<Result<T, E>>>>,
+}
+
+struct Receiver<T> {
+    slot: Arc<Mutex<Option<T>>>,
+}
+
+impl<T> Emitter<T> {
+    /// Returns a `Future` that emits `value` as the next stream item.
+    ///
+    /// The returned future **must be awaited immediately**. On its first poll 
it
+    /// yields `Poll::Pending`, handing control back to the stream consumer so 
it
+    /// can observe the emitted value. On the next poll (triggered by the
+    /// consumer calling `poll_next` again) it completes with 
`Poll::Ready(())`,
+    /// resuming the generator.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `emit` is called a second time before the previous future has
+    /// been awaited, because doing so would silently overwrite the unconsumed
+    /// value.
+    pub fn emit(&mut self, value: T) -> impl FusedFuture<Output = ()> {
+        let mut guard = self.slot.lock();
+        match guard.deref_mut() {
+            Some(_) => panic!("Misuse: await was not called after calling 
emit"),
+            slot => *slot = Some(value),
+        }
+
+        Emit { done: false }
+    }
+}
+
+impl<T, E> TryEmitter<T, E> {
+    /// Emits `Ok(value)` as the next stream item and suspends the generator.
+    ///
+    /// Behaves identically to [`Emitter::emit`]: the returned future must be
+    /// awaited immediately and yields `Poll::Pending` on its first poll to
+    /// transfer control to the stream consumer.
+    ///
+    /// # Panics
+    ///
+    /// Panics if called before the previous emit future has been awaited.
+    pub fn emit(&mut self, value: T) -> impl FusedFuture<Output = ()> {
+        let mut guard = self.slot.lock();
+        match guard.deref_mut() {
+            Some(_) => panic!("Misuse: await was not called after calling 
emit"),
+            slot => *slot = Some(Ok::<T, E>(value)),
+        }
+
+        Emit { done: false }
+    }
+}
+
+struct Emit {
+    done: bool,
+}
+
+impl FusedFuture for Emit {
+    fn is_terminated(&self) -> bool {
+        self.done
+    }
+}
+
+impl Future for Emit {
+    type Output = ();
+
+    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
+        if !self.done {
+            self.done = true;
+            // Poll::Pending causes the generator to yield, returning control 
back to the
+            // calling Stream
+            Poll::Pending
+        } else {
+            Poll::Ready(())
+        }
+    }
+}
+
+pin_project! {
+    struct AsyncStream<T, U> {
+        rx: Receiver<T>,
+        done: bool,
+        #[pin]
+        generator: U,
+    }
+}
+
+impl<T, U> AsyncStream<T, U> {
+    fn new(rx: Receiver<T>, generator: U) -> AsyncStream<T, U> {
+        AsyncStream {
+            rx,
+            done: false,
+            generator,
+        }
+    }
+}
+
+impl<T, U> FusedStream for AsyncStream<T, U>
+where
+    U: Future<Output = ()>,
+{
+    fn is_terminated(&self) -> bool {
+        self.done
+    }
+}
+
+impl<T, U> Stream for AsyncStream<T, U>
+where
+    U: Future<Output = ()>,
+{
+    type Item = T;
+
+    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> 
Poll<Option<Self::Item>> {
+        let this = self.project();
+
+        if *this.done {
+            return Poll::Ready(None);
+        }
+
+        // The `Option::take` call below ensures the next time poll is called 
the slot is
+        // already set to None
+        debug_assert!(this.rx.slot.lock().is_none());
+        let res = this.generator.poll(cx);
+        *this.done = res.is_ready();
+
+        match this.rx.slot.lock().take() {
+            // Generator filled slot -> return next stream item
+            Some(v) => Poll::Ready(Some(v)),
+            // Generator did not fill slot and completed -> return None to 
indicate end of stream
+            None if *this.done => Poll::Ready(None),
+            // Generator did not fill slot and not completed -> return Pending 
since some Future
+            // other than Emit returned Pending.
+            None => Poll::Pending,
+        }
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        if self.done { (0, Some(0)) } else { (0, None) }
+    }
+}
+
+fn tx_rx<T>() -> (Emitter<T>, Receiver<T>) {
+    let slot = Arc::new(Mutex::new(None));
+    (
+        Emitter {
+            slot: Arc::clone(&slot),
+        },
+        Receiver { slot },
+    )
+}
+
+/// Creates a [`Stream`] from an async generator function.
+///
+/// The `generator` closure receives an [`Emitter<T>`] and runs as an async
+/// block. Each `emitter.emit(value).await` call suspends the generator and
+/// produces the next item in the stream. The stream ends when the generator
+/// future resolves.
+///
+/// # Example
+///
+/// ```
+/// use datafusion_execution::async_stream;
+/// use futures::StreamExt;
+///
+/// # #[tokio::main(flavor = "current_thread")]
+/// # async fn main() {
+/// let stream = async_stream(|mut emitter| async move {
+///     for i in 0_i32..3 {
+///         emitter.emit(i).await;
+///     }
+/// });
+///
+/// let values: Vec<i32> = stream.collect().await;
+/// assert_eq!(values, vec![0, 1, 2]);
+/// # }
+/// ```
+pub fn async_stream<T, F: Future<Output = ()>>(
+    generator: impl FnOnce(Emitter<T>) -> F,
+) -> impl FusedStream<Item = T> {
+    let (emitter, receiver) = tx_rx();
+    AsyncStream::new(receiver, generator(emitter))
+}

Review Comment:
   Can you move this function as well as the `try_async_stream` function to the 
top of the file so the reader will see the entry point immediately? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to