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#[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#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
54#[derive(Clone)]
55pub struct AsyncRuntime {
56 pub(crate) inner: Arc<Mutex<InnerRuntime>>,
58 #[cfg(feature = "parallel")]
59 pub(crate) pending_free: Sender<crate::context::owner::OwnedContext>,
60}
61
62#[cfg(feature = "parallel")]
65unsafe impl Send for AsyncRuntime {}
66#[cfg(feature = "parallel")]
67unsafe impl Send for AsyncWeakRuntime {}
68
69#[cfg(feature = "parallel")]
73unsafe impl Sync for AsyncRuntime {}
74#[cfg(feature = "parallel")]
75unsafe impl Sync for AsyncWeakRuntime {}
76
77impl AsyncRuntime {
78 #[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 #[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 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 #[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 #[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 #[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 #[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 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 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 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 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 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 pub async fn memory_usage(&self) -> MemoryUsage {
244 unsafe { self.inner.lock().await.runtime.memory_usage() }
245 }
246
247 #[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 #[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 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 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 assert_eq!(number.load(Ordering::SeqCst),0);
396 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 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 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 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}