Skip to main content

rquickjs_core/runtime/
async.rs

1use alloc::{
2    ffi::CString,
3    sync::{Arc, Weak},
4    vec::Vec,
5};
6use core::{result::Result as StdResult, task::Poll};
7#[cfg(feature = "parallel")]
8use std::sync::mpsc::{self, Sender};
9
10use async_lock::Mutex;
11
12use super::{
13    job_error::JobError, opaque::RuntimeOpaque, raw::RawRuntime, schedular::SchedularPoll,
14    spawner::DriveFuture, InterruptHandler, MemoryUsage, PromiseHook, RejectionTracker,
15};
16use crate::allocator::Allocator;
17#[cfg(feature = "loader")]
18use crate::loader::{Loader, Resolver};
19#[cfg(feature = "parallel")]
20use crate::util::{AssertSendFuture, AssertSyncFuture};
21use crate::{util::ManualPoll, Result};
22
23#[derive(Debug)]
24pub(crate) struct InnerRuntime {
25    pub runtime: RawRuntime,
26}
27
28#[cfg(feature = "parallel")]
29unsafe impl Send for InnerRuntime {}
30
31/// A weak handle to the async runtime.
32///
33/// Holding onto this struct does not prevent the runtime from being dropped.
34#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
35#[derive(Clone)]
36pub struct AsyncWeakRuntime {
37    inner: Weak<Mutex<InnerRuntime>>,
38    #[cfg(feature = "parallel")]
39    pending_free: Sender<crate::context::owner::OwnedContext>,
40}
41
42impl AsyncWeakRuntime {
43    pub fn try_ref(&self) -> Option<AsyncRuntime> {
44        self.inner.upgrade().map(|inner| AsyncRuntime {
45            inner,
46            #[cfg(feature = "parallel")]
47            pending_free: self.pending_free.clone(),
48        })
49    }
50}
51
52/// Asynchronous QuickJS runtime, entry point of the library.
53#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
54#[derive(Clone)]
55pub struct AsyncRuntime {
56    // use Arc instead of Ref so we can use OwnedLock
57    pub(crate) inner: Arc<Mutex<InnerRuntime>>,
58    #[cfg(feature = "parallel")]
59    pub(crate) pending_free: Sender<crate::context::owner::OwnedContext>,
60}
61
62// Since all functions which use runtime are behind a mutex
63// sending the runtime to other threads should be fine.
64#[cfg(feature = "parallel")]
65unsafe impl Send for AsyncRuntime {}
66#[cfg(feature = "parallel")]
67unsafe impl Send for AsyncWeakRuntime {}
68
69// Since a global lock needs to be locked for safe use
70// using runtime in a sync way should be safe as
71// simultaneous accesses is synchronized behind a lock.
72#[cfg(feature = "parallel")]
73unsafe impl Sync for AsyncRuntime {}
74#[cfg(feature = "parallel")]
75unsafe impl Sync for AsyncWeakRuntime {}
76
77impl AsyncRuntime {
78    /// Create a new runtime.
79    ///
80    /// Will generally only fail if not enough memory was available.
81    ///
82    /// # Features
83    /// *If the `"rust-alloc"` feature is enabled the Rust's global allocator will be used in favor of libc's one.*
84    // Annoying false positive clippy lint
85    #[allow(clippy::arc_with_non_send_sync)]
86    pub fn new() -> Result<Self> {
87        let opaque = RuntimeOpaque::with_spawner();
88
89        #[cfg(feature = "parallel")]
90        let (pending_free, pending_free_recv) = mpsc::channel();
91        let runtime = unsafe {
92            RawRuntime::new(
93                opaque,
94                #[cfg(feature = "parallel")]
95                pending_free_recv,
96            )
97        }?;
98
99        Ok(Self {
100            inner: Arc::new(Mutex::new(InnerRuntime { runtime })),
101            #[cfg(feature = "parallel")]
102            pending_free,
103        })
104    }
105
106    /// Create a new runtime using specified allocator
107    ///
108    /// Will generally only fail if not enough memory was available.
109    // Annoying false positive clippy lint
110    #[allow(clippy::arc_with_non_send_sync)]
111    pub fn new_with_alloc<A>(allocator: A) -> Result<Self>
112    where
113        A: Allocator + 'static,
114    {
115        let opaque = RuntimeOpaque::with_spawner();
116
117        #[cfg(feature = "parallel")]
118        let (pending_free, pending_free_recv) = mpsc::channel();
119        let runtime = unsafe {
120            RawRuntime::new_with_allocator(
121                opaque,
122                allocator,
123                #[cfg(feature = "parallel")]
124                pending_free_recv,
125            )
126        }?;
127
128        Ok(Self {
129            inner: Arc::new(Mutex::new(InnerRuntime { runtime })),
130            #[cfg(feature = "parallel")]
131            pending_free,
132        })
133    }
134
135    /// Get weak ref to runtime
136    pub fn weak(&self) -> AsyncWeakRuntime {
137        AsyncWeakRuntime {
138            inner: Arc::downgrade(&self.inner),
139            #[cfg(feature = "parallel")]
140            pending_free: self.pending_free.clone(),
141        }
142    }
143
144    /// Set a closure which is called when a Promise is rejected.
145    #[inline]
146    pub async fn set_host_promise_rejection_tracker(&self, tracker: Option<RejectionTracker>) {
147        unsafe {
148            self.inner
149                .lock()
150                .await
151                .runtime
152                .set_host_promise_rejection_tracker(tracker);
153        }
154    }
155
156    /// Set a closure which is called when a promise is created, resolved, or chained.
157    #[inline]
158    pub async fn set_promise_hook(&self, tracker: Option<PromiseHook>) {
159        unsafe {
160            self.inner.lock().await.runtime.set_promise_hook(tracker);
161        }
162    }
163
164    /// Set a closure which is regularly called by the engine when it is executing code.
165    /// If the provided closure returns `true` the interpreter will raise and uncatchable
166    /// exception and return control flow to the caller.
167    #[inline]
168    pub async fn set_interrupt_handler(&self, handler: Option<InterruptHandler>) {
169        unsafe {
170            self.inner
171                .lock()
172                .await
173                .runtime
174                .set_interrupt_handler(handler);
175        }
176    }
177
178    /// Set the module loader
179    #[cfg(feature = "loader")]
180    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "loader")))]
181    pub async fn set_loader<R, L>(&self, resolver: R, loader: L)
182    where
183        R: Resolver + 'static,
184        L: Loader + 'static,
185    {
186        unsafe {
187            self.inner.lock().await.runtime.set_loader(resolver, loader);
188        }
189    }
190
191    /// Set the info of the runtime
192    pub async fn set_info<S: Into<Vec<u8>>>(&self, info: S) -> Result<()> {
193        let string = CString::new(info)?;
194        unsafe {
195            self.inner.lock().await.runtime.set_info(string);
196        }
197        Ok(())
198    }
199
200    /// Set a limit on the max amount of memory the runtime will use.
201    ///
202    /// Setting the limit to 0 is equivalent to unlimited memory.
203    ///
204    /// Note that is a Noop when a custom allocator is being used,
205    /// as is the case for the "rust-alloc" or "allocator" features.
206    pub async fn set_memory_limit(&self, limit: usize) {
207        unsafe {
208            self.inner.lock().await.runtime.set_memory_limit(limit);
209        }
210    }
211
212    /// Set a limit on the max size of stack the runtime will use.
213    ///
214    /// The default values is 256x1024 bytes.
215    pub async fn set_max_stack_size(&self, limit: usize) {
216        unsafe {
217            self.inner.lock().await.runtime.set_max_stack_size(limit);
218        }
219    }
220
221    /// Set a memory threshold for garbage collection.
222    pub async fn set_gc_threshold(&self, threshold: usize) {
223        unsafe {
224            self.inner.lock().await.runtime.set_gc_threshold(threshold);
225        }
226    }
227
228    /// Manually run the garbage collection.
229    ///
230    /// Most QuickJS values are reference counted and
231    /// will automatically free themselves when they have no more
232    /// references. The garbage collector is only for collecting
233    /// cyclic references.
234    pub async fn run_gc(&self) {
235        unsafe {
236            let mut lock = self.inner.lock().await;
237            lock.runtime.drain_pending_free();
238            lock.runtime.run_gc();
239        }
240    }
241
242    /// Get memory usage stats
243    pub async fn memory_usage(&self) -> MemoryUsage {
244        unsafe { self.inner.lock().await.runtime.memory_usage() }
245    }
246
247    /// Test for pending jobs
248    ///
249    /// Returns true when at least one job is pending.
250    #[inline]
251    pub async fn is_job_pending(&self) -> bool {
252        let lock = self.inner.lock().await;
253
254        lock.runtime.is_job_pending() || !lock.runtime.get_opaque().spawner_is_empty()
255    }
256
257    /// Run all futures and jobs in the runtime until all are finished.
258    ///
259    /// Returns the first failed job's exception as a [`JobError`]. Calling this
260    /// again continues with the jobs left in the queue. A Rust panic raised
261    /// inside a job is resumed at the failure site.
262    #[inline]
263    pub async fn idle(&self) -> StdResult<(), JobError> {
264        let lock = self.inner.lock().await;
265        lock.runtime.update_stack_top();
266        lock.runtime.drain_pending_free();
267
268        let f = ManualPoll::new(|cx| loop {
269            match lock.runtime.execute_pending_job() {
270                Ok(false) => {}
271                Ok(true) => continue,
272                Err(err) => return Poll::Ready(Err(err)),
273            }
274
275            match lock.runtime.get_opaque().poll(cx) {
276                SchedularPoll::ShouldYield => return Poll::Pending,
277                SchedularPoll::Empty => return Poll::Ready(Ok(())),
278                SchedularPoll::Pending => return Poll::Pending,
279                SchedularPoll::PendingProgress => {}
280            }
281        });
282
283        #[cfg(feature = "parallel")]
284        let f = unsafe { AssertSendFuture::assert(AssertSyncFuture::assert(f)) };
285
286        f.await
287    }
288
289    /// Returns a future that drives futures spawned inside the runtime even when
290    /// the runtime is not otherwise in use.
291    ///
292    /// The future resolves with `Ok(())` when the runtime is dropped, or with the
293    /// first failed job's exception as [`JobError`]. Poll it again to continue
294    /// driving the remaining queue.
295    pub fn drive(&self) -> DriveFuture {
296        DriveFuture::new(self.weak())
297    }
298}
299
300#[cfg(test)]
301macro_rules! async_test_case {
302    ($name:ident => ($rt:ident,$ctx:ident) { $($t:tt)* }) => {
303    #[test]
304    fn $name() {
305        #[cfg(feature = "parallel")]
306        let mut new_thread = tokio::runtime::Builder::new_multi_thread();
307
308        #[cfg(not(feature = "parallel"))]
309        let mut new_thread = tokio::runtime::Builder::new_current_thread();
310
311        let rt = new_thread
312            .enable_all()
313            .build()
314            .unwrap();
315
316        #[cfg(feature = "parallel")]
317        {
318            rt.block_on(async {
319                let $rt = crate::AsyncRuntime::new().unwrap();
320                let $ctx = crate::AsyncContext::full(&$rt).await.unwrap();
321
322                $($t)*
323
324            })
325        }
326        #[cfg(not(feature = "parallel"))]
327        {
328            let set = tokio::task::LocalSet::new();
329            set.block_on(&rt, async {
330                let $rt = crate::AsyncRuntime::new().unwrap();
331                let $ctx = crate::AsyncContext::full(&$rt).await.unwrap();
332
333                $($t)*
334            })
335        }
336    }
337    };
338}
339
340#[cfg(test)]
341mod test {
342    use std::time::Duration;
343
344    use crate::*;
345
346    use self::context::EvalOptions;
347
348    async_test_case!(basic => (_rt,ctx){
349        ctx.async_with(async |ctx|{
350            let res: i32 = ctx.eval("1 + 1").unwrap();
351            assert_eq!(res,2i32);
352        }).await.unwrap();
353    });
354
355    async_test_case!(sleep_closure => (_rt,ctx){
356
357        let mut a = 1;
358        let a_ref = &mut a;
359
360
361        ctx.async_with(async |ctx|{
362            tokio::time::sleep(Duration::from_secs_f64(0.01)).await;
363            ctx.globals().set("foo","bar").unwrap();
364            *a_ref += 1;
365        }).await.unwrap();
366        assert_eq!(a,2);
367    });
368
369    async_test_case!(drive => (rt,ctx){
370        use std::sync::{Arc, atomic::{Ordering,AtomicUsize}};
371
372        #[cfg(feature = "parallel")]
373        tokio::spawn(rt.drive());
374        #[cfg(not(feature = "parallel"))]
375        tokio::task::spawn_local(rt.drive());
376
377        // Give drive time to start.
378        tokio::time::sleep(Duration::from_secs_f64(0.01)).await;
379
380        let number = Arc::new(AtomicUsize::new(0));
381        let number_clone = number.clone();
382        let gate = Arc::new(tokio::sync::Notify::new());
383        let gate_clone = gate.clone();
384        let done = Arc::new(tokio::sync::Notify::new());
385        let done_clone = done.clone();
386
387        ctx.async_with(async |ctx|{
388            ctx.spawn(async move {
389                gate_clone.notified().await;
390                number_clone.store(1,Ordering::SeqCst);
391                done_clone.notify_one();
392            });
393        }).await.unwrap();
394        // Task is blocked on gate, so value is definitely still 0.
395        assert_eq!(number.load(Ordering::SeqCst),0);
396        // Unblock the task and wait for it to complete.
397        gate.notify_one();
398        done.notified().await;
399        assert_eq!(number.load(Ordering::SeqCst),1);
400
401    });
402
403    async_test_case!(no_drive => (rt,ctx){
404        use std::sync::{Arc, atomic::{Ordering,AtomicUsize}};
405
406        let number = Arc::new(AtomicUsize::new(0));
407        let number_clone = number.clone();
408
409        ctx.async_with(async |ctx|{
410            ctx.spawn(async move {
411                tokio::task::yield_now().await;
412                number_clone.store(1,Ordering::SeqCst);
413            });
414        }).await.unwrap();
415        assert_eq!(number.load(Ordering::SeqCst),0);
416        tokio::time::sleep(Duration::from_secs_f64(0.01)).await;
417        assert_eq!(number.load(Ordering::SeqCst),0);
418
419    });
420
421    async_test_case!(idle => (rt,ctx){
422        use std::sync::{Arc, atomic::{Ordering,AtomicUsize}};
423
424        let number = Arc::new(AtomicUsize::new(0));
425        let number_clone = number.clone();
426
427        ctx.async_with(async |ctx|{
428            ctx.spawn(async move {
429                tokio::task::yield_now().await;
430                number_clone.store(1,Ordering::SeqCst);
431            });
432        }).await.unwrap();
433        assert_eq!(number.load(Ordering::SeqCst),0);
434        rt.idle().await.unwrap();
435        assert_eq!(number.load(Ordering::SeqCst),1);
436
437    });
438
439    async_test_case!(recursive_spawn => (rt,ctx){
440        use tokio::sync::oneshot;
441
442        ctx.async_with(async |ctx|{
443            let ctx_clone = ctx.clone();
444            let (tx,rx) = oneshot::channel::<()>();
445            let (tx2,rx2) = oneshot::channel::<()>();
446            ctx.spawn(async move {
447                tokio::task::yield_now().await;
448
449                let ctx = ctx_clone.clone();
450
451                ctx_clone.spawn(async move {
452                    tokio::task::yield_now().await;
453                    ctx.spawn(async move {
454                        tokio::task::yield_now().await;
455                        tx2.send(()).unwrap();
456                        tokio::task::yield_now().await;
457                    });
458                    tokio::task::yield_now().await;
459                    tx.send(()).unwrap();
460                });
461
462                // Add a bunch of futures just to make sure possible segfaults are more likely to
463                // happen
464                for _ in 0..32{
465                    ctx_clone.spawn(async move {})
466                }
467
468            });
469            tokio::time::timeout(Duration::from_millis(500), rx).await.unwrap().unwrap();
470            tokio::time::timeout(Duration::from_millis(500), rx2).await.unwrap().unwrap();
471        }).await.unwrap();
472
473    });
474
475    async_test_case!(recursive_spawn_from_script => (rt,ctx) {
476        use std::sync::atomic::{Ordering, AtomicUsize};
477        use crate::prelude::Func;
478
479        static COUNT: AtomicUsize = AtomicUsize::new(0);
480        static SCRIPT: &str = r#"
481
482        async function main() {
483
484          setTimeout(() => {
485            inc_count()
486            setTimeout(async () => {
487                inc_count()
488            }, 100);
489          }, 100);
490        }
491
492        main().catch(print);
493
494
495        "#;
496
497        fn inc_count(){
498            COUNT.fetch_add(1,Ordering::Relaxed);
499        }
500
501        fn set_timeout_spawn<'js>(ctx: Ctx<'js>, callback: Function<'js>, millis: usize) -> Result<()> {
502            ctx.spawn(async move {
503                tokio::time::sleep(Duration::from_millis(millis as u64)).await;
504                callback.call::<_, ()>(()).unwrap();
505            });
506
507            Ok(())
508        }
509
510
511        ctx.async_with(async |ctx|{
512
513            let res: Result<Promise> = (|| {
514                let globals = ctx.globals();
515
516                globals.set("inc_count", Func::from(inc_count))?;
517
518                globals.set("setTimeout", Func::from(set_timeout_spawn))?;
519                let options = EvalOptions{
520                    promise: true,
521                    strict: false,
522                    ..EvalOptions::default()
523                };
524
525                ctx.eval_with_options(SCRIPT, options)?
526            })();
527
528            match res.catch(&ctx){
529                Ok(promise) => {
530                    if let Err(err) = promise.into_future::<Value>().await.catch(&ctx){
531                        eprintln!("{}", err)
532                    }
533                },
534                Err(err) => {
535                    eprintln!("{}", err)
536                },
537            };
538
539        })
540        .await.unwrap();
541
542        rt.idle().await.unwrap();
543
544        assert_eq!(COUNT.load(Ordering::Relaxed),2);
545    });
546
547    async_test_case!(idle_returns_failed_job => (rt, ctx) {
548        ctx.async_with(async |ctx| {
549            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('idle failure'); })").unwrap();
550        }).await.unwrap();
551
552        let err = rt.idle().await.unwrap_err();
553        ctx.with(|ctx| {
554            ctx.globals().set("err", err.into_value(&ctx).unwrap()).unwrap();
555            assert_eq!(ctx.eval::<std::string::String, _>("err.message").unwrap(), "idle failure");
556        }).await;
557    });
558
559    async_test_case!(async_with_returns_failed_job => (rt, ctx) {
560        let err = ctx.async_with(async |ctx| {
561            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('with failure'); })").unwrap();
562            tokio::task::yield_now().await;
563        }).await.unwrap_err();
564
565        ctx.with(|ctx| {
566            ctx.globals().set("err", err.into_value(&ctx).unwrap()).unwrap();
567            assert_eq!(ctx.eval::<std::string::String, _>("err.message").unwrap(), "with failure");
568        }).await;
569    });
570
571    async_test_case!(drive_returns_failed_job => (rt, ctx) {
572        ctx.async_with(async |ctx| {
573            ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('drive failure'); })").unwrap();
574        }).await.unwrap();
575
576        let err = rt.drive().await.unwrap_err();
577        ctx.with(|ctx| {
578            ctx.globals().set("err", err.into_value(&ctx).unwrap()).unwrap();
579            assert_eq!(ctx.eval::<std::string::String, _>("err.message").unwrap(), "drive failure");
580        }).await;
581    });
582
583    async_test_case!(reentering_idle_continues_the_queue => (rt, ctx) {
584        ctx.async_with(async |ctx| {
585            ctx.eval::<(), _>(
586                "queueMicrotask(() => { throw new Error('one'); });\
587                 queueMicrotask(() => { globalThis.done = 1; });",
588            ).unwrap();
589        }).await.unwrap();
590
591        let first = rt.idle().await.unwrap_err();
592        // The next drain releases unread exceptions, so consume this one first.
593        ctx.with(|ctx| {
594            ctx.globals().set("err", first.into_value(&ctx).unwrap()).unwrap();
595        }).await;
596        rt.idle().await.unwrap();
597        ctx.with(|ctx| {
598            assert_eq!(ctx.eval::<std::string::String, _>("err.message").unwrap(), "one");
599            assert_eq!(ctx.eval::<i32, _>("globalThis.done").unwrap(), 1);
600        }).await;
601    });
602
603    async_test_case!(interrupt_handler_idle => (rt, ctx) {
604        use std::time::Instant;
605
606        let timeout = Duration::from_millis(100);
607        let start_time = Instant::now();
608
609        rt.set_interrupt_handler(Some(Box::new(move || start_time.elapsed() >= timeout)))
610            .await;
611
612        let _ = ctx.async_with(async |ctx| {
613            ctx.eval::<(), _>(r#"
614                async function example() {
615                    while (true) {
616                        await Promise.resolve();
617                    }
618                }
619                example();
620            "#)
621        }).await;
622
623        // This previously caused an assertion failure in gc_decref_child
624        // due to the interrupt handler corrupting reference counts during
625        // pending job execution. The interrupt may fail a job, so the result
626        // is intentionally ignored.
627        let _ = rt.idle().await;
628    });
629
630    #[cfg(feature = "parallel")]
631    fn assert_is_send<T: Send>(t: T) -> T {
632        t
633    }
634
635    #[cfg(feature = "parallel")]
636    fn assert_is_sync<T: Send>(t: T) -> T {
637        t
638    }
639
640    #[cfg(feature = "parallel")]
641    #[tokio::test]
642    async fn ensure_types_are_send_sync() {
643        let rt = AsyncRuntime::new().unwrap();
644
645        std::mem::drop(assert_is_sync(rt.idle()));
646        std::mem::drop(assert_is_sync(rt.drive()));
647
648        std::mem::drop(assert_is_send(rt.idle()));
649        std::mem::drop(assert_is_send(rt.drive()));
650
651        fn assert_job_error_is_send<T: Send>() {}
652        assert_job_error_is_send::<JobError>();
653    }
654}