Skip to main content

rquickjs_core/runtime/
job_error.rs

1//! Exceptions thrown by queued jobs.
2//!
3//! QuickJS keeps a failing job's exception in a runtime-wide slot that the next
4//! job can overwrite or consume. Every drain therefore catches the exception
5//! immediately and keeps a copy in the runtime. [`JobError`] is a `Send` token
6//! for that copy; [`JobError::into_value`] clones it out with a context from
7//! the same runtime.
8
9use alloc::collections::VecDeque;
10use core::{
11    fmt,
12    mem::MaybeUninit,
13    result::Result as StdResult,
14    sync::atomic::{AtomicU64, Ordering},
15};
16
17use super::opaque::RuntimeOpaque;
18use crate::{qjs, Ctx, Error, Persistent, Result, Value};
19
20/// Process-wide ids so a token can never resolve to another runtime's error.
21static NEXT_JOB_ERROR_ID: AtomicU64 = AtomicU64::new(0);
22
23/// Retain enough failures that concurrently driven contexts can each keep one.
24/// The oldest is evicted once the queue is full, so memory stays bounded.
25pub(crate) const MAX_JOB_ERRORS: usize = 32;
26
27/// Bounded FIFO of failed-job exceptions.
28///
29/// Every access happens while the runtime lock is held, so this needs no lock
30/// of its own.
31pub(crate) struct JobErrors {
32    entries: VecDeque<Entry>,
33}
34
35impl Default for JobErrors {
36    fn default() -> Self {
37        Self::with_capacity(MAX_JOB_ERRORS)
38    }
39}
40
41impl JobErrors {
42    fn with_capacity(capacity: usize) -> Self {
43        Self {
44            entries: VecDeque::with_capacity(capacity),
45        }
46    }
47
48    /// Push a failure, returning an evicted entry for the caller to drop after
49    /// the borrow of `self` ends (a finalizer may re-enter `Opaque`).
50    pub(crate) fn push(&mut self, entry: Entry) -> Option<Entry> {
51        let evicted = if self.entries.len() == MAX_JOB_ERRORS {
52            self.entries.pop_front()
53        } else {
54            None
55        };
56        self.entries.push_back(entry);
57        evicted
58    }
59
60    /// Clone the exception with the given id out of the queue.
61    pub(crate) fn get<'js>(&self, id: u64, ctx: &Ctx<'js>) -> Result<Value<'js>> {
62        let entry = self
63            .entries
64            .iter()
65            .find(|e| e.id == id)
66            .ok_or(Error::JobErrorUnavailable)?;
67        entry.value.clone().restore(ctx)
68    }
69
70    /// Move every entry out before `JS_FreeRuntime`.
71    pub(crate) fn take_all(&mut self) -> VecDeque<Entry> {
72        core::mem::take(&mut self.entries)
73    }
74}
75
76/// A failed job's exception, kept inside its runtime.
77///
78/// Returned by [`Ctx::drain_jobs`](crate::Ctx::drain_jobs) and, with the
79/// `"futures"` feature, by `AsyncContext::async_with`, `AsyncRuntime::idle`
80/// and `AsyncRuntime::drive`.
81///
82/// The token carries no JavaScript value and is `Send`: the exception stays in
83/// its runtime until it is evicted by an older-first FIFO (holding up to
84/// [`MAX_JOB_ERRORS`](MAX_JOB_ERRORS) failures) or the runtime is dropped.
85/// The value is cloned on extraction, so a token can be used more than once.
86#[derive(Clone)]
87pub struct JobError {
88    pub(crate) id: u64,
89}
90
91impl fmt::Debug for JobError {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_struct("JobError")
94            .field("id", &self.id)
95            .finish_non_exhaustive()
96    }
97}
98
99impl fmt::Display for JobError {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        "a queued job threw an exception".fmt(f)
102    }
103}
104
105impl core::error::Error for JobError {}
106
107impl JobError {
108    /// Clone the exception out of the runtime.
109    ///
110    /// `ctx` must belong to the runtime the job ran in — not necessarily the
111    /// same context. Ids are process-wide unique, so a context from another
112    /// runtime cannot resolve to a different exception; [`Error::JobErrorUnavailable`]
113    /// is returned instead. It is also returned if the failure was evicted
114    /// from the bounded FIFO, or the runtime was dropped.
115    pub fn into_value<'js>(&self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
116        // SAFETY: a `Ctx` is only usable while the runtime lock is held, which
117        // is what guards the runtime-owned queue.
118        unsafe { ctx.get_runtime_opaque().take_job_error(self.id, ctx) }
119    }
120}
121
122/// One retained exception.
123pub(crate) struct Entry {
124    pub(crate) id: u64,
125    // SAFETY: `Persistent` erases the runtime borrow to `'static`. The entry is
126    // dropped in `RuntimeOpaque::clear` or on eviction, before `JS_FreeRuntime`,
127    // and `restore` rebinds a clone to a live `Ctx` from the same runtime.
128    pub(crate) value: Persistent<Value<'static>>,
129}
130
131/// Execute one pending job, retaining the exception if it fails.
132///
133/// # Safety
134/// `rt` must point to a live runtime whose lock is held.
135pub(crate) unsafe fn execute_pending_job(rt: *mut qjs::JSRuntime) -> StdResult<bool, JobError> {
136    let mut ctx_ptr = MaybeUninit::<*mut qjs::JSContext>::uninit();
137    match qjs::JS_ExecutePendingJob(rt, ctx_ptr.as_mut_ptr()) {
138        0 => Ok(false),
139        1 => Ok(true),
140        _ => {
141            // QuickJS always reports the failing context on its error path.
142            // Guard anyway so library code never builds a `Ctx` from null.
143            let ctx_ptr = ctx_ptr.assume_init();
144            if ctx_ptr.is_null() {
145                return Ok(true);
146            }
147            Err(failed_job(rt, ctx_ptr))
148        }
149    }
150}
151
152/// # Safety
153/// `rt` must point to a live runtime whose lock is held; `ctx` is the context
154/// `JS_ExecutePendingJob` reported for a failed job.
155unsafe fn failed_job(rt: *mut qjs::JSRuntime, ctx: *mut qjs::JSContext) -> JobError {
156    let opaque = RuntimeOpaque::from_runtime_ptr(rt);
157    let panic = opaque.take_panic();
158
159    // `JS_ExecutePendingJob` hands back a borrowed context; dup it for the guard.
160    let ctx = Ctx::from_ptr(ctx);
161    let exception = qjs::JS_GetException(ctx.as_ptr());
162
163    // A panicking Rust callback throws a `JS_TAG_EXCEPTION` sentinel. JS cannot
164    // fabricate that tag, so it is the only failure the stashed payload belongs
165    // to; resume it here instead of turning it into a JavaScript value.
166    let is_panic = qjs::JS_VALUE_GET_NORM_TAG(exception) == qjs::JS_TAG_EXCEPTION;
167    match panic {
168        Some(payload) if is_panic => crate::util::resume_unwind(payload),
169        Some(_) => {} // JS caught the synthetic exception; don't resume it later.
170        None => {}
171    }
172
173    let value = Value::from_js_value(ctx.clone(), exception);
174    let id = NEXT_JOB_ERROR_ID.fetch_add(1, Ordering::Relaxed);
175    unsafe { opaque.capture_job_error(id, &ctx, value) }
176}
177
178#[cfg(test)]
179mod test {
180    use super::JobError;
181    use crate::{function::Func, Context, Ctx, Error, Promise, Runtime};
182
183    fn message_of(ctx: &Ctx<'_>, err: &JobError) -> String {
184        err.clone()
185            .into_value(ctx)
186            .unwrap()
187            .as_object()
188            .unwrap()
189            .get::<_, String>("message")
190            .unwrap()
191    }
192
193    #[test]
194    fn drain_returns_the_failed_microtask_exception() {
195        let rt = Runtime::new().unwrap();
196        let ctx = Context::full(&rt).unwrap();
197        ctx.with(|ctx| {
198            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('foobar'); })")
199                .unwrap();
200            let err = ctx.drain_jobs().unwrap_err();
201            assert_eq!(message_of(&ctx, &err), "foobar");
202        });
203    }
204
205    #[test]
206    fn a_token_can_be_used_more_than_once() {
207        let rt = Runtime::new().unwrap();
208        let ctx = Context::full(&rt).unwrap();
209        ctx.with(|ctx| {
210            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('twice'); })")
211                .unwrap();
212            let err = ctx.drain_jobs().unwrap_err();
213            assert_eq!(message_of(&ctx, &err), "twice");
214            assert_eq!(message_of(&ctx, &err), "twice");
215        });
216    }
217
218    #[test]
219    fn multiple_failures_are_all_retained() {
220        let rt = Runtime::new().unwrap();
221        let ctx = Context::full(&rt).unwrap();
222        ctx.with(|ctx| {
223            ctx.eval::<(), _>(
224                "queueMicrotask(() => { throw new Error('first'); });\
225                 queueMicrotask(() => { throw new Error('second'); });",
226            )
227            .unwrap();
228
229            let first = ctx.drain_jobs().unwrap_err();
230            let second = ctx.drain_jobs().unwrap_err();
231            assert_eq!(message_of(&ctx, &first), "first");
232            assert_eq!(message_of(&ctx, &second), "second");
233        });
234    }
235
236    #[test]
237    fn a_live_handle_survives_later_drains() {
238        let rt = Runtime::new().unwrap();
239        let ctx = Context::full(&rt).unwrap();
240        ctx.with(|ctx| {
241            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('first'); })")
242                .unwrap();
243            let err = ctx.drain_jobs().unwrap_err();
244
245            ctx.eval::<(), _>("queueMicrotask(() => { globalThis.ok = 1; })")
246                .unwrap();
247            ctx.drain_jobs().unwrap();
248
249            assert_eq!(message_of(&ctx, &err), "first");
250            assert_eq!(ctx.eval::<i32, _>("globalThis.ok").unwrap(), 1);
251        });
252    }
253
254    #[cfg(feature = "parallel")]
255    #[test]
256    fn error_survives_a_drain_on_another_thread() {
257        use std::thread;
258
259        let rt = Runtime::new().unwrap();
260        let ctx = Context::full(&rt).unwrap();
261        ctx.with(|ctx| {
262            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('shared'); })")
263                .unwrap();
264        });
265        let err = ctx.with(|ctx| ctx.drain_jobs()).unwrap_err();
266
267        let ctx2 = ctx.clone();
268        thread::scope(|scope| {
269            scope.spawn(move || ctx2.with(|ctx| ctx.drain_jobs().unwrap()));
270        });
271
272        ctx.with(|ctx| assert_eq!(message_of(&ctx, &err), "shared"));
273    }
274
275    #[test]
276    fn a_stale_pending_exception_is_not_a_job_error() {
277        let rt = Runtime::new().unwrap();
278        let ctx = Context::full(&rt).unwrap();
279        ctx.with(|ctx| {
280            let _ = ctx.eval::<(), _>("throw new Error('stale')");
281            ctx.eval::<(), _>("queueMicrotask(() => { globalThis.ran = 1; })")
282                .unwrap();
283            ctx.drain_jobs().unwrap();
284            assert_eq!(ctx.eval::<i32, _>("globalThis.ran").unwrap(), 1);
285        });
286    }
287
288    #[test]
289    fn into_value_works_from_another_context_of_the_same_runtime() {
290        let rt = Runtime::new().unwrap();
291        let err = {
292            let ctx1 = Context::full(&rt).unwrap();
293            ctx1.with(|ctx| {
294                ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('shared'); })")
295                    .unwrap();
296                ctx.drain_jobs().unwrap_err()
297            })
298            // The failing context is dropped here; the retained value keeps it alive.
299        };
300
301        let ctx2 = Context::full(&rt).unwrap();
302        ctx2.with(|ctx| {
303            ctx.globals()
304                .set("err", err.into_value(&ctx).unwrap())
305                .unwrap();
306            assert_eq!(
307                ctx.eval::<std::string::String, _>("err.message").unwrap(),
308                "shared"
309            );
310        });
311    }
312
313    #[test]
314    fn a_stale_handle_cannot_resolve_in_a_new_runtime() {
315        let err = {
316            let rt1 = Runtime::new().unwrap();
317            let ctx1 = Context::full(&rt1).unwrap();
318            ctx1.with(|ctx| {
319                ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('old'); })")
320                    .unwrap();
321                ctx.drain_jobs().unwrap_err()
322            })
323        };
324
325        let rt2 = Runtime::new().unwrap();
326        let ctx2 = Context::full(&rt2).unwrap();
327        ctx2.with(|ctx| {
328            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('new'); })")
329                .unwrap();
330            let _ = ctx.drain_jobs().unwrap_err();
331            assert!(matches!(
332                err.into_value(&ctx),
333                Err(Error::JobErrorUnavailable)
334            ));
335        });
336    }
337
338    #[test]
339    fn into_value_rejects_an_unrelated_runtime() {
340        let rt1 = Runtime::new().unwrap();
341        let ctx1 = Context::full(&rt1).unwrap();
342        let err = ctx1.with(|ctx| {
343            ctx.eval::<(), _>("queueMicrotask(() => { throw 3; })")
344                .unwrap();
345            ctx.drain_jobs().unwrap_err()
346        });
347
348        let rt2 = Runtime::new().unwrap();
349        let ctx2 = Context::full(&rt2).unwrap();
350        ctx2.with(|ctx| {
351            assert!(matches!(
352                err.into_value(&ctx),
353                Err(Error::JobErrorUnavailable)
354            ));
355        });
356    }
357
358    #[test]
359    fn oldest_errors_are_evicted_from_the_fifo() {
360        let rt = Runtime::new().unwrap();
361        let ctx = Context::full(&rt).unwrap();
362        ctx.with(|ctx| {
363            let mut errors = Vec::new();
364            for i in 0..super::MAX_JOB_ERRORS {
365                ctx.eval::<(), _>(format!(
366                    "queueMicrotask(() => {{ throw new Error('e{i}'); }})"
367                ))
368                .unwrap();
369                errors.push(ctx.drain_jobs().unwrap_err());
370            }
371            // All retained so far.
372            assert_eq!(message_of(&ctx, &errors[0]), "e0");
373
374            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('new'); })")
375                .unwrap();
376            let newest = ctx.drain_jobs().unwrap_err();
377
378            // The oldest was evicted, the rest survived.
379            assert!(matches!(
380                errors[0].into_value(&ctx),
381                Err(Error::JobErrorUnavailable)
382            ));
383            assert_eq!(message_of(&ctx, &errors[1]), "e1");
384            assert_eq!(message_of(&ctx, &newest), "new");
385        });
386    }
387
388    #[test]
389    fn repeated_unread_errors_are_freed() {
390        let rt = Runtime::new().unwrap();
391        let ctx = Context::full(&rt).unwrap();
392        ctx.with(|ctx| {
393            for _ in 0..4 {
394                ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('x'); })")
395                    .unwrap();
396                let _ = ctx.drain_jobs().unwrap_err();
397            }
398            ctx.drain_jobs().unwrap();
399        });
400    }
401
402    #[test]
403    fn an_unconsumed_handle_survives_runtime_teardown() {
404        let err = {
405            let rt = Runtime::new().unwrap();
406            let ctx = Context::full(&rt).unwrap();
407            ctx.with(|ctx| {
408                ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('leak'); })")
409                    .unwrap();
410                ctx.drain_jobs().unwrap_err()
411            })
412        };
413        let _ = err;
414    }
415
416    #[test]
417    fn promise_finish_rethrows_a_failed_job() {
418        let rt = Runtime::new().unwrap();
419        let ctx = Context::full(&rt).unwrap();
420        ctx.with(|ctx| {
421            let promise: Promise = ctx.eval("new Promise(() => {})").unwrap();
422            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('from job'); })")
423                .unwrap();
424            assert!(matches!(promise.finish::<()>(), Err(Error::Exception)));
425            ctx.globals().set("err", ctx.catch()).unwrap();
426            assert_eq!(ctx.eval::<String, _>("err.message").unwrap(), "from job");
427        });
428    }
429
430    // wasm uses `panic=abort`, so `catch_unwind` cannot stash a panic payload
431    // and `should_panic` tests are ignored by libtest there.
432    #[cfg_attr(target_arch = "wasm32", ignore)]
433    #[test]
434    #[should_panic(expected = "boom")]
435    fn a_panicking_job_is_resumed() {
436        let rt = Runtime::new().unwrap();
437        let ctx = Context::full(&rt).unwrap();
438        ctx.with(|ctx| {
439            ctx.globals()
440                .set("boom", Func::from(|| -> () { panic!("boom") }))
441                .unwrap();
442            ctx.eval::<(), _>("queueMicrotask(boom)").unwrap();
443            let _ = ctx.drain_jobs();
444        });
445    }
446
447    #[cfg_attr(target_arch = "wasm32", ignore)]
448    #[test]
449    fn a_caught_panic_is_not_resumed_at_a_later_failure() {
450        let rt = Runtime::new().unwrap();
451        let ctx = Context::full(&rt).unwrap();
452        ctx.with(|ctx| {
453            ctx.globals()
454                .set("boom", Func::from(|| -> () { panic!("boom") }))
455                .unwrap();
456            ctx.eval::<(), _>("queueMicrotask(() => { try { boom() } catch (e) {} })")
457                .unwrap();
458            ctx.drain_jobs().unwrap();
459
460            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('later'); })")
461                .unwrap();
462            let err = ctx.drain_jobs().unwrap_err();
463            assert_eq!(message_of(&ctx, &err), "later");
464        });
465    }
466}