quickjs_jit_stdlib/llrt/llrt_async_hooks/
lib.rs1use std::{cell::RefCell, collections::HashMap, marker::PhantomData, rc::Rc};
6
7use crate::hooking::register_finalization_registry;
8use crate::utils::{
9 module::{export_default, ModuleInfo},
10 result::ResultExt,
11};
12use rquickjs::{
13 module::{Declarations, Exports, ModuleDef},
14 prelude::Func,
15 promise::PromiseHookType,
16 qjs,
17 runtime::PromiseHook,
18 Ctx, Function, JsLifetime, Object, Result, Value,
19};
20use tracing::trace;
21
22mod finalization_registry;
23
24use crate::async_hooks::finalization_registry::init_finalization_registry;
25
26struct Hook<'js> {
27 enabled: Rc<RefCell<bool>>,
28 init: Option<Function<'js>>,
29 before: Option<Function<'js>>,
30 after: Option<Function<'js>>,
31 promise_resolve: Option<Function<'js>>,
32 destroy: Option<Function<'js>>,
33}
34
35struct AsyncHookState<'js> {
36 hooks: Vec<Hook<'js>>,
37}
38
39impl Default for AsyncHookState<'_> {
40 fn default() -> Self {
41 Self::new()
42 }
43}
44
45impl AsyncHookState<'_> {
46 fn new() -> Self {
47 Self { hooks: Vec::new() }
48 }
49}
50
51unsafe impl<'js> JsLifetime<'js> for AsyncHookState<'js> {
52 type Changed<'to> = AsyncHookState<'to>;
53}
54
55struct AsyncHookIds<'js> {
56 next_async_id: u64,
57 id_map: HashMap<usize, (u64, u64)>, current_id: (u64, u64), _marker: PhantomData<&'js ()>,
60}
61
62impl Default for AsyncHookIds<'_> {
63 fn default() -> Self {
64 Self::new()
65 }
66}
67
68impl AsyncHookIds<'_> {
69 fn new() -> Self {
70 Self {
71 next_async_id: 1,
72 id_map: HashMap::new(),
73 current_id: (1, 1),
74 _marker: PhantomData,
75 }
76 }
77}
78
79unsafe impl<'js> JsLifetime<'js> for AsyncHookIds<'js> {
80 type Changed<'to> = AsyncHookIds<'to>;
81}
82
83fn create_hook<'js>(ctx: Ctx<'js>, hooks_obj: Object<'js>) -> Result<Value<'js>> {
84 let init = hooks_obj.get::<_, Function>("init").ok();
85 let before = hooks_obj.get::<_, Function>("before").ok();
86 let after = hooks_obj.get::<_, Function>("after").ok();
87 let promise_resolve = hooks_obj.get::<_, Function>("promiseResolve").ok();
88 let destroy = hooks_obj.get::<_, Function>("destroy").ok();
89 let enabled = Rc::new(RefCell::new(false));
90
91 let hook = Hook {
92 enabled: enabled.clone(),
93 init,
94 before,
95 after,
96 promise_resolve,
97 destroy,
98 };
99
100 let binding = ctx.userdata::<RefCell<AsyncHookState>>().or_throw(&ctx)?;
101 let mut state = binding.borrow_mut();
102 state.hooks.push(hook);
103
104 let obj = Object::new(ctx.clone())?;
105 {
106 let enabled_clone = enabled.clone();
107 obj.set(
108 "enable",
109 Function::new(ctx.clone(), move || -> Result<()> {
110 *enabled_clone.borrow_mut() = true;
111 Ok(())
112 }),
113 )?;
114 }
115 {
116 let enabled_clone = enabled.clone();
117 obj.set(
118 "disable",
119 Function::new(ctx.clone(), move || -> Result<()> {
120 *enabled_clone.borrow_mut() = false;
121 Ok(())
122 }),
123 )?;
124 }
125
126 Ok(obj.into())
127}
128
129fn current_id() -> u64 {
130 0
133}
134
135fn execution_async_id(ctx: Ctx<'_>) -> Result<u64> {
136 let bind_ids = ctx.userdata::<RefCell<AsyncHookIds>>().or_throw(&ctx)?;
137 let ids = bind_ids.borrow();
138 Ok(ids.current_id.0)
139}
140
141fn trigger_async_id(ctx: Ctx<'_>) -> Result<u64> {
142 let bind_ids = ctx.userdata::<RefCell<AsyncHookIds>>().or_throw(&ctx)?;
143 let ids = bind_ids.borrow();
144 Ok(ids.current_id.1)
145}
146
147pub struct AsyncHooksModule;
148
149impl ModuleDef for AsyncHooksModule {
150 fn declare(declare: &Declarations) -> Result<()> {
151 declare.declare("createHook")?;
152 declare.declare("currentId")?;
153 declare.declare("executionAsyncId")?;
154 declare.declare("triggerAsyncId")?;
155 declare.declare("default")?;
156
157 Ok(())
158 }
159
160 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
161 export_default(ctx, exports, |default| {
162 default.set("createHook", Func::from(create_hook))?;
163 default.set("currentId", Func::from(current_id))?;
164 default.set("executionAsyncId", Func::from(execution_async_id))?;
165 default.set("triggerAsyncId", Func::from(trigger_async_id))?;
166
167 Ok(())
168 })?;
169
170 Ok(())
171 }
172}
173
174impl From<AsyncHooksModule> for ModuleInfo<AsyncHooksModule> {
175 fn from(val: AsyncHooksModule) -> Self {
176 ModuleInfo {
177 name: "async_hooks",
178 module: val,
179 }
180 }
181}
182
183pub fn init(ctx: &Ctx<'_>) -> Result<()> {
184 let global = ctx.globals();
185
186 let _ = ctx.store_userdata(RefCell::new(AsyncHookState::default()));
187 let _ = ctx.store_userdata(RefCell::new(AsyncHookIds::default()));
188
189 global.set(
190 "invokeAsyncHook",
191 Func::from(
192 move |ctx: Ctx<'_>, type_: String, async_type: String, uid: usize| {
193 let type_ = match type_.as_ref() {
194 "init" => PromiseHookType::Init,
195 "before" => PromiseHookType::Before,
196 "after" => PromiseHookType::After,
197 "resolve" => PromiseHookType::Resolve,
198 _ => return,
199 };
200
201 let _ = invoke_async_hook(&ctx, type_, async_type.as_ref(), uid, None);
202 },
203 ),
204 )?;
205
206 init_finalization_registry(ctx)?;
207
208 Ok(())
209}
210
211pub fn promise_hook_tracker() -> PromiseHook {
212 Box::new(
213 |ctx: Ctx<'_>, type_: PromiseHookType, promise: Value<'_>, parent: Value<'_>| {
214 let object = promise
216 .as_object()
217 .map(|v| unsafe { qjs::JS_VALUE_GET_PTR(v.as_raw()) } as usize)
218 .unwrap();
219 let parent = parent
220 .as_object()
221 .map(|v| unsafe { qjs::JS_VALUE_GET_PTR(v.as_raw()) } as usize);
222
223 if type_ == PromiseHookType::Init {
224 let _ = register_finalization_registry(&ctx, promise, object);
225 }
226
227 let _ = invoke_async_hook(&ctx, type_, "PROMISE", object, parent);
228 },
229 )
230}
231
232fn invoke_async_hook(
233 ctx: &Ctx<'_>,
234 type_: PromiseHookType,
235 async_type: &str,
236 object: usize,
237 parent: Option<usize>,
238) -> Result<()> {
239 let bind_state = ctx.userdata::<RefCell<AsyncHookState>>().or_throw(ctx)?;
240 let state = bind_state.borrow();
241
242 if state.hooks.is_empty() {
243 return Ok(());
244 }
245
246 match type_ {
247 PromiseHookType::Init => {
248 let current_id = insert_id_map(ctx, object, parent, async_type == "PROMISE")?;
249 trace!("Init(async_id, trigger_id): {:?}", current_id);
250 update_current_id(ctx, current_id)?;
251
252 for hook in &state.hooks {
253 if *hook.enabled.as_ref().borrow() {
254 if let Some(func) = &hook.init {
255 let _ = func
256 .call::<_, ()>((current_id.0, async_type, current_id.1))
257 .or_else(|_| func.call::<_, ()>((current_id.0, async_type)))
258 .or_else(|_| func.call::<_, ()>((current_id.0,)))
259 .or_else(|_| func.call::<_, ()>(()));
260 }
261 }
262 }
263 }
264 PromiseHookType::Before | PromiseHookType::After | PromiseHookType::Resolve => {
265 let current_id = get_id_map(ctx, object)?;
266 if current_id.0 == 0 {
267 return Ok(());
268 }
269
270 let _type = match type_ {
271 PromiseHookType::Before => "Before",
272 PromiseHookType::After => "After",
273 PromiseHookType::Resolve => "Resolve",
274 _ => unreachable!(),
275 };
276 trace!("{}(async_id, trigger_id): {:?}", _type, current_id);
277 update_current_id(ctx, current_id)?;
278
279 for hook in &state.hooks {
280 if *hook.enabled.as_ref().borrow() {
281 if let Some(func) = match type_ {
282 PromiseHookType::Before => &hook.before,
283 PromiseHookType::After => &hook.after,
284 PromiseHookType::Resolve => &hook.promise_resolve,
285 _ => unreachable!(),
286 } {
287 let _ = func
288 .call::<_, ()>((current_id.0,))
289 .or_else(|_| func.call::<_, ()>(()));
290 }
291 }
292 }
293 }
294 }
295 Ok(())
296}
297
298fn insert_id_map(
299 ctx: &Ctx<'_>,
300 target: usize,
301 parent: Option<usize>,
302 is_promise: bool,
303) -> Result<(u64, u64)> {
304 let bind_ids = ctx.userdata::<RefCell<AsyncHookIds>>().or_throw(ctx)?;
305 let mut ids = bind_ids.borrow_mut();
306 ids.next_async_id = ids.next_async_id.wrapping_add(1);
307 let async_id = ids.next_async_id;
308 let trigger_id = parent
309 .and_then(|tid| ids.id_map.get(&tid))
310 .map(|id| id.0)
311 .unwrap_or(if is_promise { 1 } else { ids.current_id.1 });
312 ids.id_map.insert(target, (async_id, trigger_id));
313 Ok((async_id, trigger_id))
314}
315
316fn get_id_map(ctx: &Ctx<'_>, target: usize) -> Result<(u64, u64)> {
317 let bind_ids = ctx.userdata::<RefCell<AsyncHookIds>>().or_throw(ctx)?;
318 let ids = bind_ids.borrow();
319 Ok(*ids.id_map.get(&target).unwrap_or(&(0, 0)))
320}
321
322fn remove_id_map(ctx: &Ctx<'_>, target: usize) -> Result<(u64, u64)> {
323 let bind_ids = ctx.userdata::<RefCell<AsyncHookIds>>().or_throw(ctx)?;
324 let mut ids = bind_ids.borrow_mut();
325 Ok(ids
326 .id_map
327 .remove_entry(&target)
328 .map(|(_, (async_id, trigger_id))| (async_id, trigger_id))
329 .unwrap_or((0, 0)))
330}
331
332fn update_current_id(ctx: &Ctx<'_>, id: (u64, u64)) -> Result<()> {
333 let bind_ids = ctx.userdata::<RefCell<AsyncHookIds>>().or_throw(ctx)?;
334 bind_ids.borrow_mut().current_id = id;
335 Ok(())
336}