Skip to main content

rquickjs_core/value/
promise.rs

1//! Javascript promises and future integration.
2use crate::{
3    atom::PredefinedAtom, qjs, Ctx, Error, FromJs, Function, IntoJs, Object, Result, Value,
4};
5#[cfg(feature = "futures")]
6use crate::{function::This, CatchResultExt, CaughtError};
7#[cfg(feature = "futures")]
8use alloc::rc::Rc;
9#[cfg(feature = "futures")]
10use core::{
11    cell::RefCell,
12    future::Future,
13    marker::PhantomData,
14    pin::Pin,
15    task::{Context as TaskContext, Poll, Waker},
16};
17#[cfg(all(feature = "std", feature = "futures"))]
18use std::println;
19
20/// The execution state of a promise.
21#[derive(Clone, Copy, Eq, PartialEq, Debug)]
22pub enum PromiseState {
23    /// The promise has not yet completed.
24    Pending,
25    /// The promise completed succefully.
26    Resolved,
27    /// The promise completed with an error.
28    Rejected,
29}
30
31/// The type of promise event.
32#[derive(Clone, Copy, Eq, PartialEq, Debug)]
33pub enum PromiseHookType {
34    Init,
35    Before,
36    After,
37    Resolve,
38}
39
40/// A JavaScript promise.
41#[derive(Debug, PartialEq, Clone, Hash, Eq)]
42#[repr(transparent)]
43pub struct Promise<'js>(pub(crate) Object<'js>);
44
45impl<'js> Promise<'js> {
46    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
47    #[cfg(feature = "futures")]
48    pub fn wrap_future<F, R>(ctx: &Ctx<'js>, future: F) -> Result<Self>
49    where
50        F: Future<Output = R> + 'js,
51        R: IntoJs<'js>,
52    {
53        let (promise, resolve, reject) = ctx.promise()?;
54        let ctx_clone = ctx.clone();
55        let future = async move {
56            let res = future.await.into_js(&ctx_clone).catch(&ctx_clone);
57
58            let err = match res {
59                Ok(x) => resolve.call::<_, ()>((x,)),
60                Err(e) => match e {
61                    CaughtError::Exception(e) => reject.call::<_, ()>((e,)),
62                    CaughtError::Value(e) => reject.call::<_, ()>((e,)),
63                    CaughtError::Error(e) => {
64                        let is_exception = unsafe { qjs::JS_IsException(e.throw(&ctx_clone)) };
65                        debug_assert!(is_exception);
66                        let e = ctx_clone.catch();
67                        reject.call::<_, ()>((e,))
68                    }
69                },
70            };
71            // TODO figure out something better to do here.
72            if let Err(_e) = err {
73                #[cfg(feature = "std")]
74                println!("promise handle function returned error:{}", _e);
75            }
76        };
77        ctx.spawn(future);
78        Ok(promise)
79    }
80
81    /// Create a new JavaScript promise along with its resolve and reject functions.
82    pub fn new(ctx: &Ctx<'js>) -> Result<(Self, Function<'js>, Function<'js>)> {
83        ctx.promise()
84    }
85
86    /// Returns the state of the promise, either pending,resolved or rejected.
87    pub fn state(&self) -> PromiseState {
88        let v = unsafe { qjs::JS_PromiseState(self.ctx().as_ptr(), self.as_js_value()) };
89        match v {
90            qjs::JSPromiseStateEnum_JS_PROMISE_PENDING => PromiseState::Pending,
91            qjs::JSPromiseStateEnum_JS_PROMISE_FULFILLED => PromiseState::Resolved,
92            qjs::JSPromiseStateEnum_JS_PROMISE_REJECTED => PromiseState::Rejected,
93            _ => unreachable!(),
94        }
95    }
96
97    /// Returns the `then` function, used for chaining promises.
98    pub fn then(&self) -> Result<Function<'js>> {
99        self.0.get(PredefinedAtom::Then)
100    }
101
102    /// Returns the `catch` function, used for retrieving the result of a rejected promise.
103    pub fn catch(&self) -> Result<Function<'js>> {
104        self.0.get(PredefinedAtom::Catch)
105    }
106
107    /// Returns the result of the future if there is one.
108    ///
109    /// Returns None if the promise has not yet been completed, Ok if the promise was resolved, and
110    /// [`Error::Exception`] if the promise rejected with the rejected value as the thrown
111    /// value retrievable via [`Ctx::catch`].
112    pub fn result<T: FromJs<'js>>(&self) -> Option<Result<T>> {
113        match self.state() {
114            PromiseState::Pending => None,
115            PromiseState::Resolved => {
116                let v = unsafe { qjs::JS_PromiseResult(self.ctx().as_ptr(), self.as_js_value()) };
117                let v = unsafe { Value::from_js_value(self.ctx().clone(), v) };
118                Some(FromJs::from_js(self.ctx(), v))
119            }
120            PromiseState::Rejected => {
121                unsafe {
122                    // The rejection is surfaced as an `Err`, so it is no longer unhandled.
123                    qjs::JS_PromiseMarkAsHandled(self.ctx().as_ptr(), self.as_js_value());
124                    let v = qjs::JS_PromiseResult(self.ctx().as_ptr(), self.as_js_value());
125                    // A Rust callback that panics inside a promise reaction rejects
126                    // the promise with the unforgeable exception sentinel. Resume
127                    // the original panic instead of leaving it armed for a later,
128                    // unrelated host call.
129                    if qjs::JS_VALUE_GET_NORM_TAG(v) == qjs::JS_TAG_EXCEPTION {
130                        if let Some(payload) = self.ctx().get_runtime_opaque().take_panic() {
131                            crate::util::resume_unwind(payload);
132                        }
133                    }
134                    qjs::JS_Throw(self.ctx().as_ptr(), v);
135                };
136                Some(Err(Error::Exception))
137            }
138        }
139    }
140
141    /// Runs the quickjs job queue until the promise is either rejected or resolved.
142    ///
143    /// If blocking on the promise would result in blocking, i.e. when the job queue runs out of
144    /// jobs before the promise can be resolved, this function returns [`Error::WouldBlock`]
145    /// indicating that no more work can be done at the moment. If a job fails, its exception
146    /// is rethrown and can be retrieved with [`Ctx::catch`].
147    ///
148    /// This function only drives the quickjs job queue, futures are not polled.
149    pub fn finish<T: FromJs<'js>>(&self) -> Result<T> {
150        loop {
151            if let Some(x) = self.result() {
152                return x;
153            }
154
155            match self.ctx().try_execute_pending_job() {
156                Ok(true) => continue,
157                Ok(false) => return Err(Error::WouldBlock),
158                Err(err) => {
159                    let value = err.into_value(self.ctx())?;
160                    return Err(self.ctx().throw(value));
161                }
162            }
163        }
164    }
165
166    /// Wrap the promise into a struct which can be polled as a rust future.
167    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
168    #[cfg(feature = "futures")]
169    pub fn into_future<T>(self) -> PromiseFuture<'js, T>
170    where
171        T: FromJs<'js>,
172    {
173        PromiseFuture {
174            state: None,
175            promise: self,
176            _marker: PhantomData,
177        }
178    }
179}
180
181/// Future-aware promise
182#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
183#[cfg(feature = "futures")]
184#[must_use = "futures do nothing unless you `.await` or poll them"]
185#[derive(Debug)]
186pub struct PromiseFuture<'js, T> {
187    state: Option<Rc<RefCell<Waker>>>,
188    promise: Promise<'js>,
189    _marker: PhantomData<T>,
190}
191
192// Nothing is actually pinned so promise future is unpin.
193#[cfg(feature = "futures")]
194impl<'js, T> Unpin for PromiseFuture<'js, T> {}
195
196#[cfg(feature = "futures")]
197impl<'js, T> Future for PromiseFuture<'js, T>
198where
199    T: FromJs<'js>,
200{
201    type Output = Result<T>;
202
203    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
204        let this = self.get_mut();
205
206        if let Some(x) = this.promise.result() {
207            return Poll::Ready(x);
208        }
209
210        // Only bail on uncatchable exceptions (e.g. interrupt handler).
211        // Regular pending exceptions are transient and don't prevent settlement.
212        if this.promise.ctx.has_exception() {
213            let exc = this.promise.ctx.catch();
214            if exc.is_uncatchable_error() {
215                this.promise.ctx.throw(exc);
216                return Poll::Ready(Err(Error::Exception));
217            }
218        }
219
220        if this.state.is_none() {
221            let inner = Rc::new(RefCell::new(cx.waker().clone()));
222            this.state = Some(inner.clone());
223
224            let resolve = Function::new(this.promise.ctx.clone(), move || {
225                inner.borrow().wake_by_ref();
226            })?;
227
228            this.promise.then()?.call::<_, ()>((
229                This(this.promise.clone()),
230                resolve.clone(),
231                resolve,
232            ))?;
233            return Poll::Pending;
234        }
235
236        this.state
237            .as_ref()
238            .unwrap()
239            .borrow_mut()
240            .clone_from(cx.waker());
241
242        Poll::Pending
243    }
244}
245
246/// Wrapper for futures to convert to JS promises
247#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
248#[repr(transparent)]
249#[cfg(feature = "futures")]
250pub struct Promised<T>(pub T);
251
252#[cfg(feature = "futures")]
253impl<T> From<T> for Promised<T> {
254    fn from(future: T) -> Self {
255        Self(future)
256    }
257}
258
259#[cfg(feature = "futures")]
260impl<'js, T, R> IntoJs<'js> for Promised<T>
261where
262    T: Future<Output = R> + 'js,
263    R: IntoJs<'js> + 'js,
264{
265    fn into_js(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
266        Promise::wrap_future(ctx, self.0).map(|x| x.into_value())
267    }
268}
269
270/// A type which behaves like a promise but can wrap any javascript value.
271///
272/// This type is usefull when you are unsure if a function will return a promise.
273/// You can call finish and turn it into a future like a normal promise.
274/// When the value this type us converted isn't a promise it will behave like an promise which is
275/// already resolved, otherwise it will call the right functions on the promise.
276#[derive(Debug, PartialEq, Clone, Hash, Eq)]
277pub struct MaybePromise<'js>(Value<'js>);
278
279impl<'js> FromJs<'js> for MaybePromise<'js> {
280    fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
281        Ok(MaybePromise(value))
282    }
283}
284
285impl<'js> IntoJs<'js> for MaybePromise<'js> {
286    fn into_js(self, _ctx: &Ctx<'js>) -> Result<Value<'js>> {
287        Ok(self.0)
288    }
289}
290
291impl<'js> MaybePromise<'js> {
292    /// Reference to the inner value
293    pub fn as_value(&self) -> &Value<'js> {
294        &self.0
295    }
296
297    /// Convert into the inner value
298    pub fn into_value(self) -> Value<'js> {
299        self.0
300    }
301
302    /// Convert into the inner value
303    pub fn from_value(value: Value<'js>) -> Self {
304        MaybePromise(value)
305    }
306
307    /// Returns the [`Ctx`] object associated with this value
308    pub fn ctx(&self) -> &Ctx<'js> {
309        self.0.ctx()
310    }
311
312    /// Returns [`PromiseState::Resolved`] if the wrapped value isn't a promise, otherwise calls
313    /// [`Promise::state`] on the promise and returns it's value.
314    pub fn state(&self) -> PromiseState {
315        if let Some(x) = self.0.as_promise() {
316            x.state()
317        } else {
318            PromiseState::Resolved
319        }
320    }
321
322    /// Returns the value if self isn't a promise, otherwise calls [`Promise::result`] on the promise.
323    pub fn result<T: FromJs<'js>>(&self) -> Option<Result<T>> {
324        if let Some(x) = self.0.as_promise() {
325            x.result::<T>()
326        } else {
327            Some(T::from_js(self.0.ctx(), self.0.clone()))
328        }
329    }
330
331    /// Returns the value if self isn't a promise, otherwise calls [`Promise::finish`] on the promise.
332    pub fn finish<T: FromJs<'js>>(&self) -> Result<T> {
333        if let Some(x) = self.0.as_promise() {
334            x.finish::<T>()
335        } else {
336            T::from_js(self.0.ctx(), self.0.clone())
337        }
338    }
339
340    /// Convert self into a future which will return ready if the wrapped value isn't a promise,
341    /// otherwise it will handle the promise like the future returned from
342    /// [`Promise::into_future`].
343    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
344    #[cfg(feature = "futures")]
345    pub fn into_future<T: FromJs<'js>>(self) -> MaybePromiseFuture<'js, T> {
346        if self.0.is_promise() {
347            let fut = self.0.into_promise().unwrap().into_future();
348            MaybePromiseFuture(MaybePromiseFutureInner::Future(fut))
349        } else {
350            MaybePromiseFuture(MaybePromiseFutureInner::Ready(self.0))
351        }
352    }
353}
354
355/// Future-aware maybe promise
356#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
357#[cfg(feature = "futures")]
358#[must_use = "futures do nothing unless you `.await` or poll them"]
359#[derive(Debug)]
360pub struct MaybePromiseFuture<'js, T>(MaybePromiseFutureInner<'js, T>);
361
362#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
363#[cfg(feature = "futures")]
364#[derive(Debug)]
365enum MaybePromiseFutureInner<'js, T> {
366    Ready(Value<'js>),
367    Future(PromiseFuture<'js, T>),
368}
369
370#[cfg(feature = "futures")]
371impl<'js, T> Future for MaybePromiseFuture<'js, T>
372where
373    T: FromJs<'js>,
374{
375    type Output = Result<T>;
376
377    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
378        match self.get_mut().0 {
379            MaybePromiseFutureInner::Ready(ref x) => Poll::Ready(T::from_js(x.ctx(), x.clone())),
380            MaybePromiseFutureInner::Future(ref mut x) => Pin::new(x).poll(cx),
381        }
382    }
383}
384
385#[cfg(test)]
386mod test {
387    use std::sync::{
388        atomic::{AtomicBool, Ordering},
389        Arc, Mutex,
390    };
391    #[cfg(feature = "futures")]
392    use std::time::Duration;
393
394    use super::Promise;
395    #[cfg(feature = "futures")]
396    use crate::{function::Async, promise::Promised, AsyncContext, AsyncRuntime, Result};
397    use crate::{
398        function::Func, prelude::This, promise::PromiseState, CatchResultExt, CaughtError, Context,
399        Function, Runtime,
400    };
401
402    #[cfg(feature = "futures")]
403    async fn set_timeout<'js>(cb: Function<'js>, number: f64) -> Result<()> {
404        tokio::time::sleep(Duration::from_secs_f64(number / 1000.0)).await;
405        cb.call::<_, ()>(())
406    }
407
408    #[cfg(feature = "futures")]
409    #[tokio::test]
410    async fn promise() {
411        let rt = AsyncRuntime::new().unwrap();
412        let ctx = AsyncContext::full(&rt).await.unwrap();
413
414        ctx.async_with(async |ctx| {
415            ctx.globals()
416                .set("setTimeout", Func::from(Async(set_timeout)))
417                .unwrap();
418
419            let func = ctx
420                .eval::<Function, _>(
421                    r"
422                    (function(){
423                        return new Promise((resolve) => {
424                            setTimeout(x => {
425                                resolve(42)
426                            },100)
427                        })
428                    })
429                    ",
430                )
431                .catch(&ctx)
432                .unwrap();
433            let promise: Promise = func.call(()).unwrap();
434            assert_eq!(promise.into_future::<i32>().await.catch(&ctx).unwrap(), 42);
435
436            let func = ctx
437                .eval::<Function, _>(
438                    r"
439                    (function(){
440                        return new Promise((_,reject) => {
441                            setTimeout(x => {
442                                reject(42)
443                            },100)
444                        })
445                    })
446                    ",
447                )
448                .catch(&ctx)
449                .unwrap();
450            let promise: Promise = func.call(()).unwrap();
451            let err = promise.into_future::<()>().await.catch(&ctx);
452            match err {
453                Err(CaughtError::Value(v)) => {
454                    assert_eq!(v.as_int().unwrap(), 42)
455                }
456                _ => panic!(),
457            }
458        })
459        .await
460        .unwrap()
461    }
462
463    #[cfg(feature = "futures")]
464    #[tokio::test]
465    async fn promised() {
466        use crate::Exception;
467
468        let rt = AsyncRuntime::new().unwrap();
469        let ctx = AsyncContext::full(&rt).await.unwrap();
470
471        ctx.async_with(async |ctx| {
472            let promised = Promised::from(async {
473                tokio::time::sleep(Duration::from_millis(100)).await;
474                42
475            });
476
477            let function = ctx
478                .eval::<Function, _>(
479                    r"
480                (async function(v){
481                    let val = await v;
482                    if(val !== 42){
483                        throw new Error('not correct value')
484                    }
485                })
486            ",
487                )
488                .catch(&ctx)
489                .unwrap();
490
491            function
492                .call::<_, Promise>((promised,))
493                .unwrap()
494                .into_future::<()>()
495                .await
496                .unwrap();
497
498            let ctx_clone = ctx.clone();
499            let promised = Promised::from(async move {
500                tokio::time::sleep(Duration::from_millis(100)).await;
501                Result::<()>::Err(Exception::throw_message(&ctx_clone, "some_message"))
502            });
503
504            let function = ctx
505                .eval::<Function, _>(
506                    r"
507                (async function(v){
508                    try{
509                        await v;
510                    }catch(e) {
511                        if (e.message !== 'some_message'){
512                            throw new Error('wrong error')
513                        }
514                        return
515                    }
516                    throw new Error('no error thrown')
517                })
518            ",
519                )
520                .catch(&ctx)
521                .unwrap();
522
523            function
524                .call::<_, Promise>((promised,))
525                .unwrap()
526                .into_future::<()>()
527                .await
528                .unwrap()
529        })
530        .await
531        .unwrap()
532    }
533
534    #[test]
535    fn promise_then() {
536        static DID_EXECUTE: AtomicBool = AtomicBool::new(false);
537
538        let rt = Runtime::new().unwrap();
539        let ctx = Context::full(&rt).unwrap();
540
541        ctx.with(|ctx| {
542            let (promise, resolve, _) = Promise::new(&ctx).unwrap();
543
544            let cb = Func::new(|s: String| {
545                assert_eq!(s, "FOO");
546                DID_EXECUTE.store(true, Ordering::SeqCst);
547            });
548
549            assert_eq!(promise.state(), PromiseState::Pending);
550
551            promise
552                .get::<_, Function>("then")
553                .catch(&ctx)
554                .unwrap()
555                .call::<_, ()>((This(promise.clone()), cb))
556                .catch(&ctx)
557                .unwrap();
558
559            resolve.call::<_, ()>(("FOO",)).unwrap();
560            assert_eq!(promise.state(), PromiseState::Resolved);
561
562            ctx.drain_jobs().unwrap();
563
564            assert!(DID_EXECUTE.load(Ordering::SeqCst));
565        })
566    }
567
568    #[cfg(feature = "futures")]
569    #[tokio::test]
570    async fn promise_resolves_despite_stale_exception() {
571        let rt = AsyncRuntime::new().unwrap();
572        let ctx = AsyncContext::full(&rt).await.unwrap();
573
574        ctx.async_with(async |ctx| {
575            // Leave a stale JS exception pending
576            let _ = ctx.eval::<(), _>("throw new Error('stale')");
577
578            let func = ctx
579                .eval::<Function, _>(
580                    r"
581                    (function(){
582                        return new Promise((resolve) => resolve(42))
583                    })
584                    ",
585                )
586                .catch(&ctx)
587                .unwrap();
588            let promise: Promise = func.call(()).unwrap();
589            assert_eq!(promise.into_future::<i32>().await.catch(&ctx).unwrap(), 42);
590        })
591        .await
592        .unwrap()
593    }
594
595    #[cfg(feature = "futures")]
596    #[tokio::test]
597    async fn promise_fails_on_interrupt_exception() {
598        use std::sync::atomic::AtomicUsize;
599
600        let rt = AsyncRuntime::new().unwrap();
601        let counter = AtomicUsize::new(0);
602        rt.set_interrupt_handler(Some(Box::new(move || {
603            counter.fetch_add(1, Ordering::Relaxed) > 10
604        })))
605        .await;
606        let ctx = AsyncContext::full(&rt).await.unwrap();
607
608        let _ = ctx
609            .async_with(async |ctx| {
610                let func = ctx
611                    .eval::<Function, _>(
612                        r"
613                    (function(){
614                        return new Promise((resolve) => {
615                            while(true){}
616                            resolve(42)
617                        })
618                    })
619                    ",
620                    )
621                    .catch(&ctx)
622                    .unwrap();
623                let promise: Promise = func.call(()).catch(&ctx).unwrap();
624                let result = promise.into_future::<i32>().await;
625                assert!(result.is_err(), "should fail due to interrupt");
626            })
627            .await;
628    }
629
630    #[test]
631    fn rejected_promise_result_marks_handled() {
632        let events = Arc::new(Mutex::new(Vec::new()));
633        let rt = Runtime::new().unwrap();
634        {
635            let events = events.clone();
636            rt.set_host_promise_rejection_tracker(Some(Box::new(
637                move |_, _, reason, is_handled| {
638                    events.lock().unwrap().push((reason.as_int(), is_handled));
639                },
640            )));
641        }
642        let ctx = Context::full(&rt).unwrap();
643
644        ctx.with(|ctx| {
645            let promise: Promise = ctx.eval("Promise.reject(7)").unwrap();
646            let res = promise.result::<()>().unwrap().catch(&ctx);
647            assert!(matches!(res, Err(CaughtError::Value(v)) if v.as_int() == Some(7)));
648        });
649
650        assert_eq!(*events.lock().unwrap(), [(Some(7), false), (Some(7), true)]);
651    }
652
653    #[cfg(feature = "futures")]
654    #[tokio::test]
655    async fn rejected_promise_into_future_marks_handled() {
656        let events = Arc::new(Mutex::new(Vec::new()));
657        let rt = AsyncRuntime::new().unwrap();
658        {
659            let events = events.clone();
660            rt.set_host_promise_rejection_tracker(Some(Box::new(
661                move |_, _, reason, is_handled| {
662                    events.lock().unwrap().push((reason.as_int(), is_handled));
663                },
664            )))
665            .await;
666        }
667        let ctx = AsyncContext::full(&rt).await.unwrap();
668
669        ctx.async_with(async |ctx| {
670            let promise: Promise = ctx.eval("Promise.reject(7)").unwrap();
671            let res = promise.into_future::<()>().await.catch(&ctx);
672            assert!(matches!(res, Err(CaughtError::Value(v)) if v.as_int() == Some(7)));
673        })
674        .await
675        .unwrap();
676
677        assert_eq!(*events.lock().unwrap(), [(Some(7), false), (Some(7), true)]);
678    }
679}