1pub use sk_runtime::redjs::api::{Atom, Context, Error, HostArgs, Result, TaKind, Value};
13use sk_runtime::JsRuntime;
14use std::collections::VecDeque;
15use std::ffi::c_void;
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::{Arc, Mutex, OnceLock};
18use std::time::{Duration, Instant};
19
20pub fn function<F>(context: &Context, name: &str, arity: u32, mut handler: F) -> Result<Value>
24where
25 F: FnMut(&Context, HostArgs) -> Result<Value> + 'static,
26{
27 context.function(name, arity, move |_g, frame| {
28 JsRuntime::with(|runtime| {
29 let context = runtime.ctx();
30 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
31 handler(context, unsafe { HostArgs::new(frame) })
32 }));
33 match result {
34 Ok(Ok(value)) => value.0,
35 Ok(Err(error)) => {
36 let exception = match error {
37 Error::Exception(value) => value,
38 other => context.error(0, &other.to_string()),
39 };
40 context.throw(exception);
41 Value::undefined().0
42 }
43 Err(_) => {
44 context.throw(context.error(0, "native plugin method panicked"));
45 Value::undefined().0
46 }
47 }
48 })
49 })
50}
51
52type Task = Box<dyn FnOnce(&Context) + Send + 'static>;
53const QUEUE_CAPACITY: usize = 1024;
54const DRAIN_CAP: usize = 16;
55
56struct DispatchState {
57 global: usize,
58 context_id: u64,
59 closed: AtomicBool,
60 queue: Mutex<VecDeque<Task>>,
61}
62static DISPATCH: OnceLock<Arc<DispatchState>> = OnceLock::new();
63
64#[derive(Clone)]
67pub struct JsDispatcher {
68 state: Arc<DispatchState>,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum PostError {
73 Closed,
74 Full,
75}
76impl std::fmt::Display for PostError {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 f.write_str(match self {
79 Self::Closed => "the JavaScript UI has closed",
80 Self::Full => "the JavaScript task queue is full",
81 })
82 }
83}
84impl std::error::Error for PostError {}
85
86impl JsDispatcher {
87 pub(crate) fn install(context: &Context) -> Self {
88 let state = DISPATCH
89 .get_or_init(|| {
90 Arc::new(DispatchState {
91 global: context.raw() as usize,
92 context_id: context.id().0,
93 closed: AtomicBool::new(false),
94 queue: Mutex::new(VecDeque::new()),
95 })
96 })
97 .clone();
98 let _ = sk_runtime::redjs::web::waker(context.id());
99 sk_runtime::redjs::web::register_pump_source(sk_runtime::redjs::web::PumpSource {
100 inflight: dispatch_inflight,
101 ready: dispatch_ready,
102 drain: dispatch_drain,
103 });
104 Self { state }
105 }
106
107 pub fn post(
108 &self,
109 task: impl FnOnce(&Context) + Send + 'static,
110 ) -> std::result::Result<(), PostError> {
111 let mut queue = self.state.queue.lock().map_err(|_| PostError::Closed)?;
112 if self.state.closed.load(Ordering::Acquire) {
113 return Err(PostError::Closed);
114 }
115 if queue.len() >= QUEUE_CAPACITY {
116 return Err(PostError::Full);
117 }
118 queue.push_back(Box::new(task));
119 drop(queue);
120 sk_runtime::redjs::web::wake(sk_runtime::redjs::context::ContextId(self.state.context_id));
121 sk_runtime::frames::wake();
122 Ok(())
123 }
124}
125
126unsafe fn dispatch_inflight(_global: *mut c_void) -> bool {
127 false
128}
129unsafe fn dispatch_ready(global: *mut c_void) -> bool {
130 DISPATCH.get().is_some_and(|s| {
131 s.global == global as usize
132 && !s.closed.load(Ordering::Acquire)
133 && s.queue.lock().is_ok_and(|q| !q.is_empty())
134 })
135}
136unsafe fn dispatch_drain(global: *mut c_void) -> usize {
137 if !unsafe { dispatch_ready(global) } {
138 return 0;
139 }
140 let state = DISPATCH.get().expect("dispatch_ready checked the state");
141 let started = Instant::now();
142 let budget = Duration::from_micros(sk_runtime::redjs::web::pump_budget_us() as u64);
143 let mut delivered = 0;
144 while delivered < DRAIN_CAP {
145 let Some(task) = state
146 .queue
147 .lock()
148 .ok()
149 .and_then(|mut queue| queue.pop_front())
150 else {
151 break;
152 };
153 JsRuntime::with(|runtime| {
154 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| task(runtime.ctx())))
155 .is_err()
156 {
157 eprintln!("[embed] a posted JavaScript task panicked");
158 }
159 });
160 delivered += 1;
161 if started.elapsed() >= budget {
162 break;
163 }
164 }
165 delivered
166}
167
168type LifecycleHook = std::rc::Rc<dyn Fn(&Context)>;
169thread_local! {
170 static RELOAD_HOOKS: std::cell::RefCell<Vec<LifecycleHook>> = const { std::cell::RefCell::new(Vec::new()) };
171 static SHUTDOWN_HOOKS: std::cell::RefCell<Vec<LifecycleHook>> = const { std::cell::RefCell::new(Vec::new()) };
172 static FRAME_HOOKS: std::cell::RefCell<Vec<std::rc::Rc<dyn Fn()>>> = const { std::cell::RefCell::new(Vec::new()) };
173}
174
175pub(crate) fn on_frame(hook: impl Fn() + 'static) {
176 FRAME_HOOKS.with(|hooks| hooks.borrow_mut().push(std::rc::Rc::new(hook)));
177}
178pub(crate) fn frame() {
179 let hooks = FRAME_HOOKS.with(|hooks| hooks.borrow().clone());
180 for hook in hooks {
181 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook())).is_err() {
182 eprintln!("[embed] a plugin frame hook panicked");
183 }
184 }
185}
186
187pub(crate) fn on_reload(hook: impl Fn(&Context) + 'static) {
188 RELOAD_HOOKS.with(|hooks| hooks.borrow_mut().push(std::rc::Rc::new(hook)));
189}
190pub(crate) fn on_shutdown(hook: impl Fn(&Context) + 'static) {
191 SHUTDOWN_HOOKS.with(|hooks| hooks.borrow_mut().push(std::rc::Rc::new(hook)));
192}
193fn run_hooks(hooks: Vec<LifecycleHook>, context: &Context) {
194 for hook in hooks {
195 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(context))).is_err() {
196 eprintln!("[embed] a plugin lifecycle hook panicked");
197 }
198 }
199}
200fn discard_queued_tasks(state: &DispatchState) {
201 let discarded = {
202 let Ok(mut queue) = state.queue.lock() else {
203 return;
204 };
205 std::mem::take(&mut *queue)
206 };
207 drop(discarded);
210}
211
212pub(crate) fn reload(context: &Context) {
213 sk_tree::pointer_lock_navigated();
214 if let Some(state) = DISPATCH.get() {
216 discard_queued_tasks(state);
217 }
218 run_hooks(RELOAD_HOOKS.with(|hooks| hooks.borrow().clone()), context);
219}
220pub(crate) fn shutdown(context: &Context) {
221 if let Some(state) = DISPATCH.get() {
222 state.closed.store(true, Ordering::Release);
223 discard_queued_tasks(state);
224 }
225 run_hooks(
226 SHUTDOWN_HOOKS.with(|hooks| std::mem::take(&mut *hooks.borrow_mut())),
227 context,
228 );
229 RELOAD_HOOKS.with(|hooks| hooks.borrow_mut().clear());
230 FRAME_HOOKS.with(|hooks| hooks.borrow_mut().clear());
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 #[test]
238 fn native_namespace_returns_sync_values_catches_panics_and_dispatches_owned_worker_data() {
239 sk_runtime::testing::on_js_thread(|| {
240 JsRuntime::with(|runtime| {
241 let context = runtime.ctx();
242 let namespace = context.object();
243 let list = function(context, "list", 0, |context, _| {
244 let array = context.array(1)?;
245 context.set_index(array, 0, context.string("native snapshot"))?;
246 Ok(array)
247 })
248 .unwrap();
249 context.set(namespace, &context.atom("list"), list).unwrap();
250 let panic =
251 function(context, "fail", 0, |_, _| panic!("test native panic")).unwrap();
252 context
253 .set(namespace, &context.atom("fail"), panic)
254 .unwrap();
255 context.global_set("__skDirectApiTest", namespace).unwrap();
256 assert_eq!(
257 context
258 .eval("__skDirectApiTest.list()[0]")
259 .and_then(|v| context.read_string(v))
260 .unwrap(),
261 "native snapshot"
262 );
263 assert_eq!(
264 context
265 .eval("__skDirectApiTest.list() instanceof Promise")
266 .unwrap()
267 .as_bool(),
268 Some(false)
269 );
270 assert_eq!(
271 context
272 .eval("try { __skDirectApiTest.fail(); false } catch (e) { true }")
273 .unwrap()
274 .as_bool(),
275 Some(true)
276 );
277 let dispatcher = JsDispatcher::install(context);
278 std::thread::spawn(move || {
279 dispatcher
280 .post(|context| {
281 context
282 .global_set("__skPostedTest", context.string("owned Rust data"))
283 .unwrap();
284 })
285 .unwrap()
286 })
287 .join()
288 .unwrap();
289 assert_eq!(unsafe { dispatch_drain(context.raw()) }, 1);
290 assert_eq!(
291 context
292 .global_get("__skPostedTest")
293 .and_then(|v| context.read_string(v))
294 .unwrap(),
295 "owned Rust data"
296 );
297 })
298 });
299 }
300
301 #[test]
302 fn discarded_task_captures_can_reenter_the_dispatcher_on_reload_and_shutdown() {
303 struct RepostOnDrop {
304 dispatcher: JsDispatcher,
305 dropped: Arc<std::sync::atomic::AtomicUsize>,
306 accepted: Arc<AtomicBool>,
307 }
308 impl Drop for RepostOnDrop {
309 fn drop(&mut self) {
310 self.accepted
311 .store(self.dispatcher.post(|_| {}).is_ok(), Ordering::Release);
312 self.dropped.fetch_add(1, Ordering::AcqRel);
313 }
314 }
315 fn discard_with_deadline(state: Arc<DispatchState>) {
316 let (done, result) = std::sync::mpsc::sync_channel(1);
317 std::thread::spawn(move || {
318 discard_queued_tasks(&state);
319 let _ = done.send(());
320 });
321 result
322 .recv_timeout(Duration::from_secs(2))
323 .expect("discarding a task must not deadlock its destructor");
324 }
325 let state = Arc::new(DispatchState {
326 global: 0,
327 context_id: 0,
328 closed: AtomicBool::new(false),
329 queue: Mutex::new(VecDeque::new()),
330 });
331 let dispatcher = JsDispatcher {
332 state: state.clone(),
333 };
334 let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
335 let accepted = Arc::new(AtomicBool::new(false));
336 let guard = RepostOnDrop {
337 dispatcher: dispatcher.clone(),
338 dropped: dropped.clone(),
339 accepted: accepted.clone(),
340 };
341 dispatcher.post(move |_| drop(guard)).unwrap();
342 discard_with_deadline(state.clone());
343 assert_eq!(dropped.load(Ordering::Acquire), 1);
344 assert!(accepted.load(Ordering::Acquire));
345 assert_eq!(
346 state.queue.lock().unwrap().len(),
347 1,
348 "reload cleanup can enqueue follow-up work"
349 );
350 discard_with_deadline(state.clone());
351 let guard = RepostOnDrop {
352 dispatcher: dispatcher.clone(),
353 dropped: dropped.clone(),
354 accepted: accepted.clone(),
355 };
356 dispatcher.post(move |_| drop(guard)).unwrap();
357 state.closed.store(true, Ordering::Release);
358 discard_with_deadline(state.clone());
359 assert_eq!(dropped.load(Ordering::Acquire), 2);
360 assert!(!accepted.load(Ordering::Acquire));
361 assert!(state.queue.lock().unwrap().is_empty());
362 }
363
364 #[test]
365 fn worker_queue_is_bounded_and_closed_handles_reject() {
366 let state = Arc::new(DispatchState {
367 global: 0,
368 context_id: 0,
369 closed: AtomicBool::new(false),
370 queue: Mutex::new(VecDeque::new()),
371 });
372 let dispatcher = JsDispatcher {
373 state: state.clone(),
374 };
375 for _ in 0..QUEUE_CAPACITY {
376 dispatcher.post(|_| {}).unwrap();
377 }
378 assert_eq!(dispatcher.post(|_| {}), Err(PostError::Full));
379 state.closed.store(true, Ordering::Release);
380 assert_eq!(dispatcher.post(|_| {}), Err(PostError::Closed));
381 }
382}