Skip to main content

veilid_tools/
deferred_stream_processor.rs

1use futures_util::{
2    future::{select, Either},
3    stream::FuturesUnordered,
4    StreamExt,
5};
6use stop_token::future::FutureExt as _;
7
8use super::*;
9
10#[derive(Debug)]
11struct DeferredStreamProcessorInner {
12    opt_deferred_stream_channel: Option<flume::Sender<PinBoxFutureStatic<()>>>,
13    opt_stopper: Option<StopSource>,
14    opt_join_handle: Option<MustJoinHandle<()>>,
15}
16
17/// Result of a per-item handler, controlling whether stream processing continues.
18#[derive(Debug, Clone, Copy, Eq, PartialEq)]
19pub enum DeferredStreamResult {
20    /// Stop processing the stream.
21    Done,
22    /// Keep processing the next item.
23    Continue,
24}
25
26/// Background processor for streams
27/// Handles streams to completion, passing each item from the stream to a callback
28#[derive(Debug, Clone)]
29pub struct DeferredStreamProcessor {
30    inner: Arc<Mutex<DeferredStreamProcessorInner>>,
31}
32
33impl DeferredStreamProcessor {
34    /// Create a new DeferredStreamProcessor
35    #[must_use]
36    pub fn new() -> Self {
37        Self {
38            inner: Arc::new(Mutex::new(DeferredStreamProcessorInner {
39                opt_deferred_stream_channel: None,
40                opt_stopper: None,
41                opt_join_handle: None,
42            })),
43        }
44    }
45
46    /// Initialize the processor before use
47    ///
48    /// Pairs with `terminate`. Spawns the background task; not idempotent, calling it twice panics dropping the prior un-awaited join handle.
49    pub fn init(&self) {
50        let stopper = StopSource::new();
51        let stop_token = stopper.token();
52
53        let mut inner = self.inner.lock();
54        inner.opt_stopper = Some(stopper);
55        let (dsc_tx, dsc_rx) = flume::unbounded::<PinBoxFutureStatic<()>>();
56        inner.opt_deferred_stream_channel = Some(dsc_tx);
57        inner.opt_join_handle = Some(spawn(
58            "deferred stream processor",
59            Self::processor(stop_token, dsc_rx),
60        ));
61    }
62
63    /// Terminate the processor and ensure all streams are closed
64    ///
65    /// Awaits the background task's exit. Idempotent: a no-op once already terminated or never initialized.
66    pub async fn terminate(&self) {
67        let opt_jh = {
68            let mut inner = self.inner.lock();
69            drop(inner.opt_deferred_stream_channel.take());
70            drop(inner.opt_stopper.take());
71            inner.opt_join_handle.take()
72        };
73        if let Some(jh) = opt_jh {
74            jh.await;
75        }
76    }
77
78    async fn processor(stop_token: StopToken, dsc_rx: flume::Receiver<PinBoxFutureStatic<()>>) {
79        let mut unord = FuturesUnordered::<PinBoxFutureStatic<()>>::new();
80
81        // Ensure the unord never finishes unless the stop source got dropped
82        unord.push(Box::pin(stop_token));
83
84        // Processor loop
85        let mut unord_fut = unord.next();
86        let mut dsc_fut = dsc_rx.recv_async();
87        loop {
88            let res = select(unord_fut, dsc_fut).await;
89            match res {
90                Either::Left((x, old_dsc_fut)) => {
91                    // If the unord future gets empty, the stop token got dropped and all the other tasks finished
92                    if x.is_none() {
93                        break;
94                    }
95
96                    // Make another unord future to process
97                    unord_fut = unord.next();
98                    // put back the other future and keep going
99                    dsc_fut = old_dsc_fut;
100                }
101                Either::Right((new_proc, old_unord_fut)) => {
102                    // Immediately drop the old unord future
103                    // because we never care about it completing
104                    drop(old_unord_fut);
105                    let Ok(new_proc) = new_proc else {
106                        break;
107                    };
108
109                    // Add a new stream to process
110                    unord.push(new_proc);
111
112                    // Make a new unord future because we don't care about the
113                    // completion of the last unord future, they never return
114                    // anything.
115                    unord_fut = unord.next();
116                    // Make a new receiver future
117                    dsc_fut = dsc_rx.recv_async();
118                }
119            }
120        }
121    }
122
123    /// Queue a stream to process in the background
124    ///
125    /// * 'receiver' is the stream to process
126    /// * 'handler' is the callback to handle each item from the stream
127    ///
128    /// Returns 'true' if the stream was added for processing, and 'false' if the stream could not be added, possibly due to not being initialized.
129    ///
130    /// Non-blocking; the stream is processed by the background task until exhausted or `terminate` is called.
131    pub fn add_stream<
132        T: Send + 'static,
133        S: futures_util::Stream<Item = T> + Unpin + Send + 'static,
134    >(
135        &self,
136        mut receiver: S,
137        mut handler: impl FnMut(T) -> PinBoxFutureStatic<DeferredStreamResult> + Send + 'static,
138    ) -> bool {
139        let (st, dsc_tx) = {
140            let inner = self.inner.lock();
141            let Some(st) = inner.opt_stopper.as_ref().map(|s| s.token()) else {
142                return false;
143            };
144            let Some(dsc_tx) = inner.opt_deferred_stream_channel.clone() else {
145                return false;
146            };
147            (st, dsc_tx)
148        };
149        let drp = Box::pin(async move {
150            while let Ok(Some(res)) = receiver.next().timeout_at(st.clone()).await {
151                if matches!(handler(res).await, DeferredStreamResult::Done) {
152                    break;
153                }
154            }
155        });
156        if dsc_tx.send(drp).is_err() {
157            return false;
158        }
159        true
160    }
161
162    /// Queue a single future to process in the background
163    ///
164    /// Non-blocking; returns false if the processor was not initialized. The future runs until done or `terminate` is called.
165    pub fn add_future<F>(&self, fut: F) -> bool
166    where
167        F: Future<Output = ()> + Send + 'static,
168    {
169        let (st, dsc_tx) = {
170            let inner = self.inner.lock();
171            let Some(st) = inner.opt_stopper.as_ref().map(|s| s.token()) else {
172                return false;
173            };
174            let Some(dsc_tx) = inner.opt_deferred_stream_channel.clone() else {
175                return false;
176            };
177            (st, dsc_tx)
178        };
179        if dsc_tx
180            .send(Box::pin(async move {
181                let _ = fut.timeout_at(st.clone()).await;
182            }))
183            .is_err()
184        {
185            return false;
186        }
187        true
188    }
189}
190
191impl Default for DeferredStreamProcessor {
192    fn default() -> Self {
193        Self::new()
194    }
195}