Skip to main content

moq_ext_sources/
local_task.rs

1//! A task on a thread of its own, for capture streams that cannot move.
2//!
3//! On Apple platforms a camera or screen stream holds AVFoundation and
4//! ScreenCaptureKit objects, which are not `Send`. The same streams are `Send`
5//! on Linux, so the problem only shows in macOS builds.
6//!
7//! [`spawn`] runs such a future on its own thread in a current-thread runtime.
8//! Only the frames it produces leave that thread. The runtime is built on the
9//! calling thread, so a runtime or thread that does not start is an error the
10//! caller sees.
11
12use std::future::Future;
13
14use tokio_util::sync::CancellationToken;
15
16/// A handle that stops its task when dropped.
17///
18/// A thread cannot be aborted like a tokio task, so dropping this cancels a
19/// token the task selects on.
20#[derive(Debug)]
21pub struct LocalTask {
22    shutdown: CancellationToken,
23    /// Cancelled once the thread has finished.
24    ///
25    /// This includes a thread that panicked or never started.
26    released: CancellationToken,
27}
28
29impl Drop for LocalTask {
30    fn drop(&mut self) {
31        // Not joined: releasing a device can take a moment, and joining here
32        // would block a runtime worker. A caller that needs the device back
33        // awaits `joined`.
34        self.shutdown.cancel();
35    }
36}
37
38impl LocalTask {
39    /// Waits until the task has finished and released its device.
40    ///
41    /// Returns at once after that, on every later call. Cancellation safe: a
42    /// later call waits again.
43    pub async fn joined(&self) {
44        self.released.cancelled().await;
45    }
46
47    /// Returns a token that is cancelled once the thread has finished.
48    ///
49    /// It outlives this handle, so a caller can wait for the release after the
50    /// handle is gone.
51    pub(crate) fn released(&self) -> CancellationToken {
52        self.released.clone()
53    }
54}
55
56/// Runs `make` on a dedicated thread, in a current-thread runtime.
57///
58/// `make` is called on that thread, so it may build values that are not `Send`.
59/// Only the closure has to cross. The returned handle cancels `stop`, which
60/// `make` gets to watch.
61///
62/// # Errors
63///
64/// Fails if the runtime or the thread cannot be started.
65pub fn spawn<F, Fut>(name: &str, stop: CancellationToken, make: F) -> std::io::Result<LocalTask>
66where
67    F: FnOnce(CancellationToken) -> Fut + Send + 'static,
68    Fut: Future<Output = ()>,
69{
70    let token = stop.clone();
71    let released = CancellationToken::new();
72    // Dropped with the closure, so a panic or a thread that does not start
73    // also counts as released.
74    let release = released.clone().drop_guard();
75    let runtime = tokio::runtime::Builder::new_current_thread()
76        .enable_all()
77        .build()?;
78    std::thread::Builder::new()
79        .name(name.to_string())
80        .spawn(move || {
81            runtime.block_on(make(token));
82            // The runtime may still own tasks that hold the device.
83            drop(runtime);
84            drop(release);
85        })?;
86    Ok(LocalTask {
87        shutdown: stop,
88        released,
89    })
90}
91
92#[cfg(test)]
93mod tests {
94    use std::time::Duration;
95
96    use super::*;
97
98    /// A cancelled `joined` does not count as finished.
99    ///
100    /// The next call still waits until the thread releases the device.
101    #[tokio::test]
102    async fn a_cancelled_join_still_waits_the_next_time() {
103        let (release, released) = std::sync::mpsc::sync_channel::<()>(1);
104        let task = spawn(
105            "test-late-release",
106            CancellationToken::new(),
107            move |_shutdown| async move {
108                // Holds the device until the test releases it.
109                let _ = released.recv();
110            },
111        )
112        .expect("the thread starts");
113
114        assert!(
115            tokio::time::timeout(Duration::from_millis(50), task.joined())
116                .await
117                .is_err(),
118            "the task has not released anything yet",
119        );
120        assert!(
121            tokio::time::timeout(Duration::from_millis(50), task.joined())
122                .await
123                .is_err(),
124            "a cancelled wait must not report the task as finished",
125        );
126
127        release.send(()).expect("the task is still running");
128        tokio::time::timeout(Duration::from_secs(5), task.joined())
129            .await
130            .expect("the task released its device");
131        // Every later call returns at once.
132        tokio::time::timeout(Duration::from_secs(5), task.joined())
133            .await
134            .expect("a second call after completion returns");
135    }
136
137    /// A task that panics still releases, so nobody waits on it forever.
138    #[tokio::test]
139    async fn a_panicked_task_counts_as_released() {
140        let task = spawn("test-panic", CancellationToken::new(), |_shutdown| async {
141            panic!("the device driver crashed");
142        })
143        .expect("the thread starts");
144        tokio::time::timeout(Duration::from_secs(5), task.joined())
145            .await
146            .expect("the panic released the task");
147    }
148}