veilid_tools/
deferred_stream_processor.rs1use 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#[derive(Debug, Clone, Copy, Eq, PartialEq)]
19pub enum DeferredStreamResult {
20 Done,
22 Continue,
24}
25
26#[derive(Debug, Clone)]
29pub struct DeferredStreamProcessor {
30 inner: Arc<Mutex<DeferredStreamProcessorInner>>,
31}
32
33impl DeferredStreamProcessor {
34 #[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 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 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 unord.push(Box::pin(stop_token));
83
84 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 x.is_none() {
93 break;
94 }
95
96 unord_fut = unord.next();
98 dsc_fut = old_dsc_fut;
100 }
101 Either::Right((new_proc, old_unord_fut)) => {
102 drop(old_unord_fut);
105 let Ok(new_proc) = new_proc else {
106 break;
107 };
108
109 unord.push(new_proc);
111
112 unord_fut = unord.next();
116 dsc_fut = dsc_rx.recv_async();
118 }
119 }
120 }
121 }
122
123 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 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}