tokio_run_until_stalled/
lib.rs1use std::future::Future;
4use std::pin::Pin;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::Arc;
7use std::task::{Context, RawWaker, RawWakerVTable, Waker};
8
9use tokio::task::LocalSet;
10
11pub trait RuntimeExt {
16 fn run_until_stalled(&self, local_set: LocalSet) -> Option<LocalSet>;
45}
46
47pub trait LocalSetExt {
49 fn run_until_stalled(self) -> RunUntilStalled;
50}
51
52pub struct RunUntilStalled {
80 local_set: Option<LocalSet>,
81}
82
83impl RunUntilStalled {
84 pub fn into_local_set(self) -> Option<LocalSet> {
86 self.local_set
87 }
88
89 pub fn is_done(&self) -> bool {
91 self.local_set.is_none()
92 }
93
94 pub fn as_local_set(&self) -> &Option<LocalSet> {
96 &self.local_set
97 }
98
99 pub fn as_local_set_force(&self) -> &LocalSet {
101 self.local_set.as_ref().unwrap()
102 }
103}
104
105struct DetectWaker {
106 flag: AtomicBool,
107 waker: Waker,
108}
109
110impl DetectWaker {
111 fn wake(&self) {
112 self.flag.store(true, Ordering::Release);
113 self.waker.wake_by_ref();
114 }
115
116 fn has_waked(&self) -> bool {
117 self.flag.load(Ordering::Acquire)
118 }
119}
120
121fn create_detector_waker(waker: Waker) -> (Arc<DetectWaker>, Waker) {
122 let detector = Arc::new(DetectWaker {
123 flag: AtomicBool::default(),
124 waker,
125 });
126 static VTABLE: RawWakerVTable = RawWakerVTable::new(
127 |data| {
128 let origin = unsafe { Arc::from_raw(data as *const DetectWaker) };
129 let cloned = origin.clone();
130 std::mem::forget(origin);
131 RawWaker::new(Arc::into_raw(cloned) as *const _ as *const (), &VTABLE)
132 },
133 |data| {
134 let waker = unsafe { Arc::from_raw(data as *const DetectWaker) };
135 waker.wake();
136 },
137 |data| {
138 let waker = unsafe { Arc::from_raw(data as *const DetectWaker) };
139 waker.wake();
140 std::mem::forget(waker);
141 },
142 |data| {
143 let _ = unsafe { Arc::from_raw(data as *const DetectWaker) };
144 },
145 );
146
147 let waker = unsafe {
148 Waker::from_raw(RawWaker::new(
149 Arc::into_raw(detector.clone()) as *const _ as *const (),
150 &VTABLE,
151 ))
152 };
153 (detector, waker)
154}
155
156impl Future for RunUntilStalled {
157 type Output = Self;
158 fn poll(
159 mut self: std::pin::Pin<&mut Self>,
160 cx: &mut std::task::Context<'_>,
161 ) -> std::task::Poll<Self::Output> {
162 if self.local_set.is_none() {
163 return std::task::Poll::Ready(RunUntilStalled { local_set: None });
164 }
165
166 let (detector, waker) = create_detector_waker(cx.waker().clone());
167 let mut new_ctx = Context::from_waker(&waker);
168 let mut local_set = self.local_set.take().unwrap();
169 if std::task::Poll::Ready(()) == Pin::new(&mut local_set).poll(&mut new_ctx) {
170 std::task::Poll::Ready(RunUntilStalled { local_set: None })
171 } else if detector.has_waked() {
172 self.local_set = Some(local_set);
173 cx.waker().wake_by_ref();
174 std::task::Poll::Pending
175 } else {
176 std::task::Poll::Ready(RunUntilStalled {
177 local_set: Some(local_set),
178 })
179 }
180 }
181}
182
183impl LocalSetExt for LocalSet {
184 fn run_until_stalled(self) -> RunUntilStalled {
185 RunUntilStalled {
186 local_set: Some(self),
187 }
188 }
189}
190
191impl RuntimeExt for tokio::runtime::Runtime {
192 fn run_until_stalled(&self, local_set: LocalSet) -> Option<LocalSet> {
193 self.block_on(local_set.run_until_stalled())
194 .into_local_set()
195 }
196}
197
198impl RuntimeExt for tokio::runtime::Handle {
199 fn run_until_stalled(&self, local_set: LocalSet) -> Option<LocalSet> {
200 self.block_on(local_set.run_until_stalled())
201 .into_local_set()
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use std::{cell::RefCell, rc::Rc};
208
209 use super::*;
210
211 use tokio::{
212 sync::mpsc::channel,
213 task,
214 time::{sleep, Duration},
215 };
216
217 #[tokio::test]
218 async fn test_run_until_stalled() {
219 let local_set = LocalSet::new();
220 let logs = Rc::new(RefCell::new(vec![]));
221 local_set.spawn_local({
222 let logger = logs.clone();
223 async move {
224 logger.borrow_mut().push("task 1");
225 async {
226 logger.borrow_mut().push("async log in task 1");
227 }
228 .await;
229 task::spawn_local({
230 let logger = logger.clone();
231 async move {
232 logger.borrow_mut().push("inner spawn task");
233 sleep(Duration::from_millis(100)).await;
234 logger.borrow_mut().push("inner spawn task completed");
235 }
236 });
237 logger.borrow_mut().push("Task 1 completed");
238 }
239 });
240
241 let mut run_stalled = local_set.run_until_stalled();
242
243 run_stalled = run_stalled.await;
244 assert_eq!(
245 &*logs.borrow(),
246 &[
247 "task 1",
248 "async log in task 1",
249 "Task 1 completed",
250 "inner spawn task"
251 ]
252 );
253 sleep(Duration::from_millis(150)).await;
254 run_stalled = run_stalled.await;
255 assert_eq!(
256 &*logs.borrow(),
257 &[
258 "task 1",
259 "async log in task 1",
260 "Task 1 completed",
261 "inner spawn task",
262 "inner spawn task completed"
263 ]
264 );
265 assert!(run_stalled.is_done());
266 }
267
268 #[tokio::test]
269 async fn test_depend_on_each() {
270 let local_set = LocalSet::new();
271 let logs = Rc::new(RefCell::new(vec![]));
272 let (tx1, mut rx1) = channel::<()>(1);
273 let (tx2, mut rx2) = channel::<()>(1);
274 local_set.spawn_local({
275 let logger = logs.clone();
276 async move {
277 logger.borrow_mut().push("task1");
278 logger.borrow_mut().push("wait for rx2");
279 if let Some(_) = rx2.recv().await {
280 logger.borrow_mut().push("rx2 recv");
281 logger.borrow_mut().push("tx1 send");
282 let _ = tx1.send(()).await;
283 }
284 logger.borrow_mut().push("task1 completed");
285 }
286 });
287
288 local_set.spawn_local({
289 let logger = logs.clone();
290 async move {
291 logger.borrow_mut().push("task2");
292 logger.borrow_mut().push("tx2 send");
293 let _ = tx2.send(()).await;
294 logger.borrow_mut().push("wait for rx1");
295 if let Some(_) = rx1.recv().await {
296 logger.borrow_mut().push("rx1 recv");
297 }
298 logger.borrow_mut().push("task2 completed");
299 }
300 });
301
302 let mut run_stalled = local_set.run_until_stalled();
303
304 run_stalled = run_stalled.await;
305 assert_eq!(
306 &*logs.borrow(),
307 &[
308 "task1",
309 "wait for rx2",
310 "task2",
311 "tx2 send",
312 "wait for rx1",
313 "rx2 recv",
314 "tx1 send",
315 "task1 completed",
316 "rx1 recv",
317 "task2 completed"
318 ]
319 );
320 assert!(run_stalled.is_done());
321 }
322}