rquickjs_core/context/async.rs
1use super::{intrinsic, owner::ContextOwner, ContextBuilder, Intrinsic};
2use crate::{
3 context::opaque::ContextOpaque, markers::ParallelSend, qjs, runtime::AsyncRuntime, Ctx, Error,
4 Result,
5};
6use core::{mem, ptr::NonNull};
7
8mod future;
9
10use future::WithFuture;
11
12/// A macro for safely using an asynchronous context while capturing the environment.
13///
14/// This macro was used to work around the lack of async closures, with the stabilization of async
15/// closures this macro is now deprecated.
16///
17/// Use the [`AsyncContext::async_with`] function instead.
18///
19/// # Usage
20/// ```
21/// # use rquickjs::{prelude::*, Function, async_with, AsyncRuntime, AsyncContext, Result};
22/// # use std::time::Duration;
23/// # async fn run(){
24/// let rt = AsyncRuntime::new().unwrap();
25/// let ctx = AsyncContext::full(&rt).await.unwrap();
26///
27/// // In order for futures to convert to JavaScript promises they need to return `Result`.
28/// async fn delay<'js>(amount: f64, cb: Function<'js>) -> Result<()> {
29/// tokio::time::sleep(Duration::from_secs_f64(amount)).await;
30/// cb.call::<(), ()>(());
31/// Ok(())
32/// }
33///
34/// fn print(text: String) -> Result<()> {
35/// println!("{}", text);
36/// Ok(())
37/// }
38///
39/// let mut some_var = 1;
40/// // closure always moves, so create a ref.
41/// let some_var_ref = &mut some_var;
42/// async_with!(ctx => |ctx|{
43///
44/// // With the macro you can borrow the environment.
45/// *some_var_ref += 1;
46///
47/// let delay = Function::new(ctx.clone(),Async(delay))
48/// .unwrap()
49/// .with_name("delay")
50/// .unwrap();
51///
52/// let global = ctx.globals();
53/// global.set("print",Func::from(print)).unwrap();
54/// global.set("delay",delay).unwrap();
55/// ctx.eval::<(),_>(r#"
56/// print("start");
57/// delay(1,() => {
58/// print("delayed");
59/// })
60/// print("after");
61/// "#).unwrap();
62/// }).await.unwrap();
63/// assert_eq!(some_var,2);
64///
65/// rt.idle().await.unwrap()
66/// # }
67/// ```
68#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
69#[macro_export]
70#[deprecated]
71macro_rules! async_with{
72 ($context:expr => |$ctx:ident| { $($t:tt)* }) => {
73 $crate::AsyncContext::async_with(&$context,async |$ctx| {
74 $($t)*
75 })
76 };
77}
78
79/// An asynchronous single execution context with its own global variables and stack.
80///
81/// Can share objects with other contexts of the same runtime.
82#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
83#[derive(Clone)]
84pub struct AsyncContext(pub(crate) ContextOwner<AsyncRuntime>);
85
86impl AsyncContext {
87 /// Create a async context form a raw context pointer.
88 ///
89 /// # Safety
90 /// The context must be of the correct runtime.
91 /// The context must also have valid reference count, one which can be decremented when this
92 /// object is dropped without going negative.
93 pub unsafe fn from_raw(ctx: NonNull<qjs::JSContext>, rt: AsyncRuntime) -> Self {
94 AsyncContext(ContextOwner::from_raw(ctx, rt))
95 }
96
97 /// Creates a base context with only the required functions registered.
98 /// If additional functions are required use [`AsyncContext::custom`],
99 /// [`AsyncContext::builder`] or [`AsyncContext::full`].
100 pub async fn base(runtime: &AsyncRuntime) -> Result<Self> {
101 Self::custom::<intrinsic::None>(runtime).await
102 }
103
104 /// Creates a context with only the required intrinsics registered.
105 /// If additional functions are required use [`AsyncContext::custom`],
106 /// [`AsyncContext::builder`] or [`AsyncContext::full`].
107 pub async fn custom<I: Intrinsic>(runtime: &AsyncRuntime) -> Result<Self> {
108 let guard = runtime.inner.lock().await;
109 let ctx = NonNull::new(unsafe { qjs::JS_NewContextRaw(guard.runtime.rt.as_ptr()) })
110 .ok_or(Error::Allocation)?;
111 unsafe { qjs::JS_AddIntrinsicBaseObjects(ctx.as_ptr()) };
112 unsafe { I::add_intrinsic(ctx) };
113 let res = unsafe { ContextOwner::new(ctx, ContextOpaque::new(), runtime.clone()) };
114 guard.runtime.drain_pending_free();
115 mem::drop(guard);
116
117 Ok(AsyncContext(res))
118 }
119
120 /// Creates a context with all standard available intrinsics registered.
121 /// If precise control is required of which functions are available use
122 /// [`AsyncContext::custom`] or [`AsyncContext::builder`].
123 pub async fn full(runtime: &AsyncRuntime) -> Result<Self> {
124 let guard = runtime.inner.lock().await;
125 let ctx = NonNull::new(unsafe { qjs::JS_NewContext(guard.runtime.rt.as_ptr()) })
126 .ok_or(Error::Allocation)?;
127 let res = unsafe { ContextOwner::new(ctx, ContextOpaque::new(), runtime.clone()) };
128 // Explicitly drop the guard to ensure it is valid during the entire use of runtime
129 guard.runtime.drain_pending_free();
130 mem::drop(guard);
131
132 Ok(AsyncContext(res))
133 }
134
135 /// Create a context builder for creating a context with a specific set of intrinsics
136 pub fn builder() -> ContextBuilder<()> {
137 ContextBuilder::default()
138 }
139
140 /// Returns the associated runtime
141 pub fn runtime(&self) -> &AsyncRuntime {
142 self.0.rt()
143 }
144
145 /// A entry point for manipulating and using JavaScript objects and scripts.
146 ///
147 /// # Example
148 ///
149 /// ```
150 /// # use rquickjs::{prelude::*, Function, async_with, AsyncRuntime, AsyncContext, Result};
151 /// # use std::time::Duration;
152 /// # async fn run(){
153 /// # let rt = AsyncRuntime::new().unwrap();
154 ///
155 /// // In order for futures to convert to JavaScript promises they need to return `Result`.
156 /// async fn delay<'js>(amount: f64, cb: Function<'js>) -> Result<()> {
157 /// tokio::time::sleep(Duration::from_secs_f64(amount)).await;
158 /// cb.call::<(), ()>(());
159 /// Ok(())
160 /// }
161 ///
162 /// let ctx = AsyncContext::full(&rt).await.unwrap();
163 /// ctx.async_with(async |ctx|{
164 ///
165 /// let delay = Function::new(ctx.clone(),Async(delay))
166 /// .unwrap()
167 /// .with_name("delay")
168 /// .unwrap();
169 ///
170 /// let global = ctx.globals();
171 /// global.set("delay",delay).unwrap();
172 /// ctx.eval::<(),_>(r#"
173 /// delay(1,() => {
174 /// // do something
175 /// })
176 /// "#).unwrap();
177 /// }).await.unwrap();
178 /// # }
179 /// ```
180 ///
181 /// Returns `Result<R, JobError>`: if a queued job throws, the closure is
182 /// cancelled and the failure is returned. Use
183 /// [`JobError::into_value`](crate::JobError::into_value) with a context from
184 /// this runtime to retrieve the exception.
185 pub fn async_with<F, R>(&self, f: F) -> WithFuture<F, R>
186 where
187 F: for<'js> AsyncFnOnce(Ctx<'js>) -> R + ParallelSend,
188 R: ParallelSend,
189 {
190 WithFuture::new(self, f)
191 }
192
193 /// A entry point for manipulating and using JavaScript objects and scripts.
194 ///
195 /// This closure can't return a future, if you need to await JavaScript promises prefer the
196 /// [`async_with`] function.
197 pub async fn with<F, R>(&self, f: F) -> R
198 where
199 F: for<'js> FnOnce(Ctx<'js>) -> R + ParallelSend,
200 R: ParallelSend,
201 {
202 let guard = self.0.rt().inner.lock().await;
203 guard.runtime.update_stack_top();
204 let ctx = unsafe { Ctx::new_async(self) };
205 let res = f(ctx);
206 guard.runtime.drain_pending_free();
207 res
208 }
209}
210
211// Since the reference to runtime is behind a Arc this object is send
212#[cfg(feature = "parallel")]
213unsafe impl Send for AsyncContext {}
214
215// Since all functions lock the global runtime lock access is synchronized so
216// this object is sync
217#[cfg(feature = "parallel")]
218unsafe impl Sync for AsyncContext {}
219
220#[cfg(test)]
221mod test {
222 use crate::{AsyncContext, AsyncRuntime};
223
224 #[tokio::test]
225 async fn base_asyc_context() {
226 let rt = AsyncRuntime::new().unwrap();
227 let ctx = AsyncContext::builder().build_async(&rt).await.unwrap();
228 ctx.async_with(async |ctx| {
229 ctx.globals();
230 })
231 .await
232 .unwrap();
233 }
234
235 #[tokio::test]
236 async fn clone_ctx() {
237 let rt = AsyncRuntime::new().unwrap();
238 let ctx = AsyncContext::full(&rt).await.unwrap();
239
240 let ctx_clone = ctx.clone();
241
242 ctx.with(|ctx| {
243 let val: i32 = ctx.eval(r#"1+1"#).unwrap();
244
245 assert_eq!(val, 2);
246 println!("{:?}", ctx.globals());
247 })
248 .await;
249
250 ctx_clone
251 .with(|ctx| {
252 let val: i32 = ctx.eval(r#"1+1"#).unwrap();
253
254 assert_eq!(val, 2);
255 println!("{:?}", ctx.globals());
256 })
257 .await;
258 }
259
260 #[cfg(feature = "parallel")]
261 #[tokio::test]
262 async fn parallel_drop() {
263 use std::{
264 sync::{Arc, Barrier},
265 thread,
266 };
267
268 let wait_for_entry = Arc::new(Barrier::new(2));
269 let wait_for_exit = Arc::new(Barrier::new(2));
270
271 let rt = AsyncRuntime::new().unwrap();
272 let ctx_1 = AsyncContext::full(&rt).await.unwrap();
273 let ctx_2 = AsyncContext::full(&rt).await.unwrap();
274 let wait_for_entry_c = wait_for_entry.clone();
275 let wait_for_exit_c = wait_for_exit.clone();
276 thread::spawn(move || {
277 println!("wait_for entry ctx_1");
278 wait_for_entry_c.wait();
279 println!("dropping");
280 std::mem::drop(ctx_1);
281 println!("wait_for exit ctx_1");
282 wait_for_exit_c.wait();
283 });
284
285 println!("wait_for entry ctx_2");
286 rt.run_gc().await;
287 ctx_2
288 .with(|ctx| {
289 wait_for_entry.wait();
290 println!("evaling");
291 let i: i32 = ctx.eval("2 + 8").unwrap();
292 assert_eq!(i, 10);
293 println!("wait_for exit ctx_2");
294 wait_for_exit.wait();
295 })
296 .await;
297 }
298}