1use crate::host::{invoke, with_host};
39use fusevm::Value;
40use indexmap::IndexMap;
41use std::cell::RefCell;
42
43thread_local! {
44
45 static NEXT_ASYNC_ID: RefCell<f64> = const { RefCell::new(2.0) };
48
49 static EXEC_STACK: RefCell<Vec<(f64, f64)>> = const { RefCell::new(Vec::new()) };
55}
56
57pub fn execution_async_id() -> f64 {
59 EXEC_STACK.with(|s| s.borrow().last().map(|p| p.0).unwrap_or(1.0))
60}
61
62pub fn trigger_async_id() -> f64 {
64 EXEC_STACK.with(|s| s.borrow().last().map(|p| p.1).unwrap_or(0.0))
65}
66
67fn fresh_async_id() -> f64 {
69 NEXT_ASYNC_ID.with(|n| {
70 let mut n = n.borrow_mut();
71 let id = *n;
72 *n += 1.0;
73 id
74 })
75}
76
77fn in_async_scope<T>(async_id: f64, trigger_id: f64, f: impl FnOnce() -> T) -> T {
80 EXEC_STACK.with(|s| s.borrow_mut().push((async_id, trigger_id)));
81 let r = f();
82 EXEC_STACK.with(|s| {
83 s.borrow_mut().pop();
84 });
85 r
86}
87
88pub const METHODS: &[&str] = &["executionAsyncId", "triggerAsyncId", "createHook"];
90
91pub const ALS_METHODS: &[&str] = &["getStore", "run", "enterWith", "exit", "disable"];
94pub const HOOK_METHODS: &[&str] = &["enable", "disable"];
95pub const RESOURCE_METHODS: &[&str] = &[
96 "runInAsyncScope",
97 "emitDestroy",
98 "asyncId",
99 "triggerAsyncId",
100 "bind",
101];
102
103pub const RESOURCE_STATIC_METHODS: &[&str] = &["bind"];
105
106pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
111 match method {
112 "bind" => {
113 let f = args.first().cloned().unwrap_or(Value::Undef);
114 let bound = bind_to(f, args.get(2).cloned());
115 let frame = with_host(|h| h.async_frame.clone());
116 Some(frame_runner(frame, Some(bound)))
117 }
118 _ => None,
119 }
120}
121
122fn bind_to(f: Value, this: Option<Value>) -> Value {
124 match this.filter(|t| !with_host(|h| h.is_nullish(t))) {
125 Some(t) => with_host(|h| {
126 h.alloc(crate::host::JsObj::BoundFunc {
127 target: f,
128 this: t,
129 args: Vec::new(),
130 })
131 }),
132 None => f,
133 }
134}
135
136pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
137 Some(match method {
138 "@@runInFrame" => run_in_frame(args),
139 "executionAsyncId" => Ok(Value::Float(execution_async_id())),
140 "triggerAsyncId" => Ok(Value::Float(trigger_async_id())),
141 "createHook" => Ok(new_hook()),
143 _ => return None,
144 })
145}
146
147pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
150 match name {
151 "AsyncLocalStorage" => Some(Ok(new_native("AsyncLocalStorage"))),
152 "AsyncResource" => {
157 let r = new_native("AsyncResource");
158 let frame_id = hold_frame(with_host(|h| h.async_frame.clone()));
159 let trigger = args
160 .get(1)
161 .and_then(|o| {
162 with_host(|h| match h.get(o) {
163 Some(crate::host::JsObj::Object(p)) => p
164 .get("triggerAsyncId")
165 .filter(|v| !matches!(v, Value::Undef))
166 .map(|v| h.to_number(v)),
167 _ => None,
168 })
169 })
170 .unwrap_or_else(execution_async_id);
171 with_host(|h| {
172 if let Some(crate::host::JsObj::Object(p)) = h.get_mut(&r) {
173 p.insert("@@asyncId".into(), Value::Float(fresh_async_id()));
174 p.insert("@@triggerAsyncId".into(), Value::Float(trigger));
175 p.insert("@@frame".into(), Value::Float(frame_id));
178 }
179 });
180 Some(Ok(r))
181 }
182 _ => None,
183 }
184}
185
186fn new_native(tag: &'static str) -> Value {
188 with_host(|h| {
189 let mut m = IndexMap::new();
190 m.insert("@@native".into(), h.new_str(tag));
191 h.new_object(m)
192 })
193}
194
195fn hidden_num(recv: &Value, key: &str, fallback: f64) -> f64 {
197 with_host(|h| match h.get(recv) {
198 Some(crate::host::JsObj::Object(p)) => {
199 p.get(key).map(|v| h.to_number(v)).unwrap_or(fallback)
200 }
201 _ => fallback,
202 })
203}
204
205fn new_hook() -> Value {
208 new_native("AsyncHook")
209}
210
211pub fn instance_call(
213 tag: &str,
214 recv: &Value,
215 method: &str,
216 args: Vec<Value>,
217) -> Result<Value, String> {
218 match tag {
219 "AsyncHook" => match method {
222 "enable" | "disable" => Ok(recv.clone()),
223 _ => Err(crate::host::type_error(&format!(
224 "{method} is not a function"
225 ))),
226 },
227 "AsyncLocalStorage" => als_call(recv, method, args),
228 "AsyncResource" => resource_call(recv, method, args),
229 _ => Err(crate::host::type_error(&format!(
230 "{method} is not a function"
231 ))),
232 }
233}
234
235fn resource_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
242 match method {
243 "runInAsyncScope" => {
246 let f = args.first().cloned().unwrap_or(Value::Undef);
247 let this = args.get(1).cloned();
251 let rest = args.get(2..).map(|s| s.to_vec()).unwrap_or_default();
252 let id = hidden_num(recv, "@@asyncId", 1.0);
253 let trigger = hidden_num(recv, "@@triggerAsyncId", 0.0);
254 let frame = resource_frame(recv);
255 in_async_scope(id, trigger, || {
256 crate::host::in_frame(frame, || invoke(&f, rest, this))
257 })
258 }
259 "bind" => {
260 let f = args.first().cloned().unwrap_or(Value::Undef);
261 let bound = bind_to(f, args.get(1).cloned());
262 frame_runner(resource_frame(recv), Some(bound))
263 }
264 "emitDestroy" => Ok(recv.clone()),
265 "asyncId" => Ok(Value::Float(hidden_num(recv, "@@asyncId", 1.0))),
266 "triggerAsyncId" => Ok(Value::Float(hidden_num(recv, "@@triggerAsyncId", 0.0))),
267 _ => Err(crate::host::type_error(&format!(
268 "{method} is not a function"
269 ))),
270 }
271}
272
273fn key(recv: &Value) -> u32 {
275 match recv {
276 Value::Obj(i) => *i,
277 _ => 0,
278 }
279}
280
281fn als_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
282 let id = key(recv);
283 match method {
284 "getStore" => Ok(with_host(|h| {
286 h.async_frame
287 .iter()
288 .find(|(k, _)| *k == id)
289 .map(|(_, v)| v.clone())
290 .unwrap_or(Value::Undef)
291 })),
292 "run" => {
295 let store = args.first().cloned().unwrap_or(Value::Undef);
296 let cb = args.get(1).cloned().unwrap_or(Value::Undef);
297 let rest = args.get(2..).map(|s| s.to_vec()).unwrap_or_default();
298 let frame = crate::host::frame_with(id, Some(store));
299 crate::host::in_frame(frame, || invoke(&cb, rest, None))
300 }
301 "exit" => {
303 let cb = args.first().cloned().unwrap_or(Value::Undef);
304 let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
305 let frame = crate::host::frame_with(id, None);
306 crate::host::in_frame(frame, || invoke(&cb, rest, None))
307 }
308 "enterWith" | "disable" => {
311 let store =
312 (method == "enterWith").then(|| args.first().cloned().unwrap_or(Value::Undef));
313 let frame = crate::host::frame_with(id, store);
314 with_host(|h| h.async_frame = frame);
315 Ok(Value::Undef)
316 }
317 _ => Err(crate::host::type_error(&format!(
318 "{method} is not a function"
319 ))),
320 }
321}
322
323fn resource_frame(recv: &Value) -> crate::host::AsyncFrame {
325 let id = hidden_num(recv, "@@frame", -1.0);
326 if id < 0.0 {
327 return with_host(|h| h.async_frame.clone());
328 }
329 HELD_FRAMES
330 .with(|f| f.borrow().get(id as usize).cloned())
331 .unwrap_or_default()
332}
333
334pub const ALS_STATIC_METHODS: &[&str] = &["bind", "snapshot"];
336
337pub fn als_static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
341 let frame = with_host(|h| h.async_frame.clone());
342 Some(match method {
343 "snapshot" => frame_runner(frame, None),
344 "bind" => frame_runner(frame, Some(args.first().cloned().unwrap_or(Value::Undef))),
345 _ => return None,
346 })
347}
348
349thread_local! {
350 static HELD_FRAMES: RefCell<Vec<crate::host::AsyncFrame>> = const { RefCell::new(Vec::new()) };
352}
353
354fn hold_frame(frame: crate::host::AsyncFrame) -> f64 {
355 HELD_FRAMES.with(|f| {
356 let mut f = f.borrow_mut();
357 f.push(frame);
358 (f.len() - 1) as f64
359 })
360}
361
362fn frame_runner(frame: crate::host::AsyncFrame, target: Option<Value>) -> Result<Value, String> {
366 thread_local! {
367 static FACTORY: RefCell<Option<Value>> = const { RefCell::new(None) };
368 }
369 let factory = match FACTORY.with(|f| f.borrow().clone()) {
370 Some(f) => f,
371 None => {
372 let f = crate::eval_internal(
373 "(function (runner, id, target) {\n\
374 if (target === undefined) return function runInAsyncScope(fn, ...args) { return runner(id, fn, undefined, ...args); };\n\
375 return function (...args) { return runner(id, target, this, ...args); };\n\
376 })",
377 )?;
378 FACTORY.with(|c| *c.borrow_mut() = Some(f.clone()));
379 f
380 }
381 };
382 let id = Value::Float(hold_frame(frame));
383 let runner = with_host(|h| {
384 h.alloc(crate::host::JsObj::Builtin(
385 "async_hooks.@@runInFrame".into(),
386 ))
387 });
388 invoke(
389 &factory,
390 vec![runner, id, target.unwrap_or(Value::Undef)],
391 None,
392 )
393}
394
395pub fn run_in_frame(args: &[Value]) -> Result<Value, String> {
397 let id = with_host(|h| h.to_number(args.first().unwrap_or(&Value::Undef))) as usize;
398 let frame = HELD_FRAMES
399 .with(|f| f.borrow().get(id).cloned())
400 .unwrap_or_default();
401 let f = args.get(1).cloned().unwrap_or(Value::Undef);
402 let this = args.get(2).cloned().filter(|t| !matches!(t, Value::Undef));
403 let rest = args.get(3..).map(|s| s.to_vec()).unwrap_or_default();
404 crate::host::in_frame(frame, || invoke(&f, rest, this))
405}