1use std::panic::{self, AssertUnwindSafe};
7use std::sync::mpsc;
8use std::sync::{Mutex, OnceLock};
9
10use crate::JsRuntime;
11
12type Job = Box<dyn FnOnce() + Send>;
13
14static JS_THREAD: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
15
16pub fn on_js_thread<R, F>(f: F) -> R
17where
18 F: FnOnce() -> R + Send + 'static,
19 R: Send + 'static,
20{
21 let jobs = JS_THREAD.get_or_init(|| {
22 let (tx, rx) = mpsc::channel::<Job>();
23 std::thread::Builder::new()
24 .name("sk-runtime test JS thread".into())
25 .spawn(move || {
26 JsRuntime::init();
27 for job in rx {
28 job();
29 }
30 })
31 .expect("could not start the JS test thread");
32 Mutex::new(tx)
33 });
34 let (done, result) = mpsc::sync_channel(1);
35 let job: Job = Box::new(move || {
36 let _ = done.send(panic::catch_unwind(AssertUnwindSafe(f)));
37 });
38 jobs.lock()
39 .unwrap_or_else(|poisoned| poisoned.into_inner())
40 .send(job)
41 .expect("the JS test thread has exited");
42 match result
43 .recv()
44 .expect("the JS test thread exited while running a test body")
45 {
46 Ok(value) => value,
47 Err(payload) => panic::resume_unwind(payload),
48 }
49}