|
| 1 | +#![allow(dead_code)] |
| 2 | +#![allow(unused_variables)] |
| 3 | + |
| 4 | +use std::{future::Future, pin::Pin, rc::Rc}; |
| 5 | + |
| 6 | +use bitwarden_error::bitwarden_error; |
| 7 | +use thiserror::Error; |
| 8 | +#[cfg(not(target_arch = "wasm32"))] |
| 9 | +use tokio::task::spawn_local; |
| 10 | +#[cfg(target_arch = "wasm32")] |
| 11 | +use wasm_bindgen_futures::spawn_local; |
| 12 | + |
| 13 | +type CallFunction<ThreadState> = |
| 14 | + Box<dyn FnOnce(Rc<ThreadState>) -> Pin<Box<dyn Future<Output = ()>>> + Send>; |
| 15 | + |
| 16 | +struct CallRequest<ThreadState> { |
| 17 | + function: CallFunction<ThreadState>, |
| 18 | +} |
| 19 | + |
| 20 | +/// The call failed before it could return a value. This should not happen unless |
| 21 | +/// the thread panics, which can only happen if the function passed to `run_in_thread` |
| 22 | +/// panics. |
| 23 | +#[derive(Debug, Error)] |
| 24 | +#[error("The call failed before it could return a value: {0}")] |
| 25 | +#[bitwarden_error(basic)] |
| 26 | +pub struct CallError(String); |
| 27 | + |
| 28 | +/// A runner that takes a non-`Send`, non-`Sync` state and makes it `Send + Sync` compatible. |
| 29 | +/// |
| 30 | +/// `ThreadBoundRunner` is designed to safely encapsulate a `!Send + !Sync` state object by |
| 31 | +/// pinning it to a single thread using `spawn_local`. It provides a `Send + Sync` API that |
| 32 | +/// allows other threads to submit tasks (function pointers or closures) that operate on the |
| 33 | +/// thread-bound state. |
| 34 | +/// |
| 35 | +/// Tasks are queued via an internal channel and are executed sequentially on the owning thread. |
| 36 | +/// |
| 37 | +/// # Example |
| 38 | +/// ```ignore |
| 39 | +/// let runner = ThreadBoundRunner::new(my_state); |
| 40 | +/// |
| 41 | +/// runner.run_in_thread(|state| async move { |
| 42 | +/// // do something with `state` |
| 43 | +/// }); |
| 44 | +/// ``` |
| 45 | +/// |
| 46 | +/// This pattern is useful for interacting with APIs or data structures that must remain |
| 47 | +/// on the same thread, such as GUI toolkits, WebAssembly contexts, or other thread-bound |
| 48 | +/// environments. |
| 49 | +#[derive(Clone)] |
| 50 | +pub struct ThreadBoundRunner<ThreadState> { |
| 51 | + call_channel_tx: tokio::sync::mpsc::Sender<CallRequest<ThreadState>>, |
| 52 | +} |
| 53 | + |
| 54 | +impl<ThreadState> ThreadBoundRunner<ThreadState> |
| 55 | +where |
| 56 | + ThreadState: 'static, |
| 57 | +{ |
| 58 | + pub fn new(state: ThreadState) -> Self { |
| 59 | + let (call_channel_tx, mut call_channel_rx) = |
| 60 | + tokio::sync::mpsc::channel::<CallRequest<ThreadState>>(1); |
| 61 | + |
| 62 | + spawn_local(async move { |
| 63 | + let state = Rc::new(state); |
| 64 | + while let Some(request) = call_channel_rx.recv().await { |
| 65 | + spawn_local((request.function)(state.clone())); |
| 66 | + } |
| 67 | + }); |
| 68 | + |
| 69 | + ThreadBoundRunner { call_channel_tx } |
| 70 | + } |
| 71 | + |
| 72 | + /// Submit a task to be executed on the thread-bound state. |
| 73 | + /// |
| 74 | + /// The provided function is executed on the thread that owns the internal `ThreadState`, |
| 75 | + /// ensuring safe access to `!Send + !Sync` data. Tasks are dispatched in the order they are |
| 76 | + /// received, but because they are asynchronous, multiple tasks may be in-flight and running |
| 77 | + /// concurrently if their futures yield. |
| 78 | + /// |
| 79 | + /// # Returns |
| 80 | + /// A future that resolves to the result of the function once it has been executed. |
| 81 | + pub async fn run_in_thread<F, Fut, Output>(&self, function: F) -> Result<Output, CallError> |
| 82 | + where |
| 83 | + F: FnOnce(Rc<ThreadState>) -> Fut + Send + 'static, |
| 84 | + Fut: Future<Output = Output>, |
| 85 | + Output: Send + Sync + 'static, |
| 86 | + { |
| 87 | + let (return_channel_tx, return_channel_rx) = tokio::sync::oneshot::channel(); |
| 88 | + let request = CallRequest { |
| 89 | + function: Box::new(|state| { |
| 90 | + Box::pin(async move { |
| 91 | + let result = function(state); |
| 92 | + return_channel_tx.send(result.await).unwrap_or_else(|_| { |
| 93 | + log::warn!( |
| 94 | + "ThreadBoundDispatcher failed to send result back to the caller" |
| 95 | + ); |
| 96 | + }); |
| 97 | + }) |
| 98 | + }), |
| 99 | + }; |
| 100 | + |
| 101 | + self.call_channel_tx |
| 102 | + .send(request) |
| 103 | + .await |
| 104 | + .expect("Call channel should not be able to close while anything still still has a reference to this object"); |
| 105 | + return_channel_rx |
| 106 | + .await |
| 107 | + .map_err(|e| CallError(e.to_string())) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +#[cfg(test)] |
| 112 | +mod test { |
| 113 | + use super::*; |
| 114 | + |
| 115 | + /// Utility function to run a test in a local context (allows using tokio::..::spawn_local) |
| 116 | + async fn run_test<F>(test: F) -> F::Output |
| 117 | + where |
| 118 | + F: std::future::Future, |
| 119 | + { |
| 120 | + #[cfg(not(target_arch = "wasm32"))] |
| 121 | + { |
| 122 | + let local_set = tokio::task::LocalSet::new(); |
| 123 | + local_set.run_until(test).await |
| 124 | + } |
| 125 | + |
| 126 | + #[cfg(target_arch = "wasm32")] |
| 127 | + { |
| 128 | + test.await |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + async fn run_in_another_thread<F>(test: F) |
| 133 | + where |
| 134 | + F: std::future::Future + Send + 'static, |
| 135 | + F::Output: Send, |
| 136 | + { |
| 137 | + #[cfg(not(target_arch = "wasm32"))] |
| 138 | + { |
| 139 | + tokio::spawn(test).await.expect("Thread panicked"); |
| 140 | + } |
| 141 | + |
| 142 | + #[cfg(target_arch = "wasm32")] |
| 143 | + { |
| 144 | + test.await; |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + #[derive(Default)] |
| 149 | + struct State { |
| 150 | + /// This is a marker to ensure that the struct is not Send |
| 151 | + _un_send_marker: std::marker::PhantomData<*const ()>, |
| 152 | + } |
| 153 | + |
| 154 | + impl State { |
| 155 | + pub fn add(&self, input: (i32, i32)) -> i32 { |
| 156 | + input.0 + input.1 |
| 157 | + } |
| 158 | + |
| 159 | + #[allow(clippy::unused_async)] |
| 160 | + pub async fn async_add(&self, input: (i32, i32)) -> i32 { |
| 161 | + input.0 + input.1 |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + #[tokio::test] |
| 166 | + async fn calls_function_and_returns_value() { |
| 167 | + run_test(async { |
| 168 | + let runner = ThreadBoundRunner::new(State::default()); |
| 169 | + |
| 170 | + let result = runner |
| 171 | + .run_in_thread(|state| async move { |
| 172 | + let input = (1, 2); |
| 173 | + state.add(input) |
| 174 | + }) |
| 175 | + .await |
| 176 | + .expect("Calling function failed"); |
| 177 | + |
| 178 | + assert_eq!(result, 3); |
| 179 | + }) |
| 180 | + .await; |
| 181 | + } |
| 182 | + |
| 183 | + #[tokio::test] |
| 184 | + async fn calls_async_function_and_returns_value() { |
| 185 | + run_test(async { |
| 186 | + let runner = ThreadBoundRunner::new(State::default()); |
| 187 | + |
| 188 | + let result = runner |
| 189 | + .run_in_thread(|state| async move { |
| 190 | + let input = (1, 2); |
| 191 | + state.async_add(input).await |
| 192 | + }) |
| 193 | + .await |
| 194 | + .expect("Calling function failed"); |
| 195 | + |
| 196 | + assert_eq!(result, 3); |
| 197 | + }) |
| 198 | + .await; |
| 199 | + } |
| 200 | + |
| 201 | + #[tokio::test] |
| 202 | + async fn can_continue_running_if_a_call_panics() { |
| 203 | + run_test(async { |
| 204 | + let runner = ThreadBoundRunner::new(State::default()); |
| 205 | + |
| 206 | + runner |
| 207 | + .run_in_thread::<_, _, ()>(|state| async move { |
| 208 | + panic!("This is a test panic"); |
| 209 | + }) |
| 210 | + .await |
| 211 | + .expect_err("Calling function should have panicked"); |
| 212 | + |
| 213 | + let result = runner |
| 214 | + .run_in_thread(|state| async move { |
| 215 | + let input = (1, 2); |
| 216 | + state.async_add(input).await |
| 217 | + }) |
| 218 | + .await |
| 219 | + .expect("Calling function failed"); |
| 220 | + |
| 221 | + assert_eq!(result, 3); |
| 222 | + }) |
| 223 | + .await; |
| 224 | + } |
| 225 | +} |
0 commit comments