Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(utils): run blocking native work on a dedicated thread

Richie McIlroy3858e0f26172
diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml
index 622f6ca94..fe0e2b2e3 100644
--- a/crates/utils/Cargo.toml
+++ b/crates/utils/Cargo.toml
@@ -38,5 +38,8 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
tracing-appender = "0.2.3"
tempfile = "3"
+[target.'cfg(target_os = "linux")'.dev-dependencies]
+zbus = { version = "5.18.0", default-features = false, features = ["tokio", "blocking-api"] }
+
[lints]
workspace = true
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index 1e510081e..9a4e9e014 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -34,6 +34,25 @@ where
tokio::spawn(future.with_current_subscriber().in_current_span())
}
+/// Runs blocking native work on a new thread outside every Tokio runtime context.
+/// Some blocking APIs, such as zbus on Linux, start their own runtime and panic when
+/// called from an async task.
+pub async fn run_on_dedicated_thread<T, F>(name: &str, work: F) -> std::io::Result<T>
+where
+ F: FnOnce() -> T + Send + 'static,
+ T: Send + 'static,
+{
+ let (sender, receiver) = tokio::sync::oneshot::channel();
+ std::thread::Builder::new()
+ .name(name.to_string())
+ .spawn(move || {
+ let _ = sender.send(work());
+ })?;
+ receiver
+ .await
+ .map_err(|_| std::io::Error::other(format!("{name} thread stopped before finishing")))
+}
+
pub fn ensure_dir(path: &PathBuf) -> Result<PathBuf, std::io::Error> {
std::fs::create_dir_all(path)?;
Ok(path.clone())
@@ -427,3 +446,67 @@ mod tests {
assert_eq!(result, "test (2).cap");
}
}
+
+#[cfg(test)]
+mod dedicated_thread_tests {
+ use super::run_on_dedicated_thread;
+
+ async fn assert_work_can_start_its_own_runtime() {
+ let value = run_on_dedicated_thread("runtime-test", || {
+ tokio::runtime::Builder::new_current_thread()
+ .build()
+ .unwrap()
+ .block_on(async { 7 })
+ })
+ .await
+ .unwrap();
+ assert_eq!(value, 7);
+ }
+
+ #[tokio::test]
+ async fn work_runs_outside_a_current_thread_runtime() {
+ assert_work_can_start_its_own_runtime().await;
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn work_runs_outside_a_multi_thread_runtime() {
+ assert_work_can_start_its_own_runtime().await;
+ }
+
+ #[tokio::test]
+ async fn work_results_are_returned_unchanged() {
+ let result: Result<(), std::io::Error> = run_on_dedicated_thread("error-test", || {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::PermissionDenied,
+ "denied",
+ ))
+ })
+ .await
+ .unwrap();
+ let error = result.unwrap_err();
+ assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
+ assert_eq!(error.to_string(), "denied");
+ }
+
+ #[tokio::test]
+ async fn panicking_work_becomes_an_error() {
+ let error = run_on_dedicated_thread::<(), _>("panic-test", || panic!("worker failed"))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "panic-test thread stopped before finishing"
+ );
+ }
+
+ #[cfg(target_os = "linux")]
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn blocking_zbus_runs_from_an_async_task() {
+ // A headless host may have no session bus; only a thread failure is a regression.
+ let result = run_on_dedicated_thread("zbus-test", || {
+ zbus::blocking::Connection::session().map(drop)
+ })
+ .await;
+ assert!(result.is_ok());
+ }
+}