use crate::host::{invoke, with_host};
use fusevm::Value;
use indexmap::IndexMap;
use std::cell::RefCell;
thread_local! {
static NEXT_ASYNC_ID: RefCell<f64> = const { RefCell::new(2.0) };
static EXEC_STACK: RefCell<Vec<(f64, f64)>> = const { RefCell::new(Vec::new()) };
}
pub fn execution_async_id() -> f64 {
EXEC_STACK.with(|s| s.borrow().last().map(|p| p.0).unwrap_or(1.0))
}
pub fn trigger_async_id() -> f64 {
EXEC_STACK.with(|s| s.borrow().last().map(|p| p.1).unwrap_or(0.0))
}
fn fresh_async_id() -> f64 {
NEXT_ASYNC_ID.with(|n| {
let mut n = n.borrow_mut();
let id = *n;
*n += 1.0;
id
})
}
fn in_async_scope<T>(async_id: f64, trigger_id: f64, f: impl FnOnce() -> T) -> T {
EXEC_STACK.with(|s| s.borrow_mut().push((async_id, trigger_id)));
let r = f();
EXEC_STACK.with(|s| {
s.borrow_mut().pop();
});
r
}
pub const METHODS: &[&str] = &["executionAsyncId", "triggerAsyncId", "createHook"];
pub const ALS_METHODS: &[&str] = &["getStore", "run", "enterWith", "exit", "disable"];
pub const HOOK_METHODS: &[&str] = &["enable", "disable"];
pub const RESOURCE_METHODS: &[&str] = &[
"runInAsyncScope",
"emitDestroy",
"asyncId",
"triggerAsyncId",
"bind",
];
pub const RESOURCE_STATIC_METHODS: &[&str] = &["bind"];
pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
match method {
"bind" => {
let f = args.first().cloned().unwrap_or(Value::Undef);
let bound = bind_to(f, args.get(2).cloned());
let frame = with_host(|h| h.async_frame.clone());
Some(frame_runner(frame, Some(bound)))
}
_ => None,
}
}
fn bind_to(f: Value, this: Option<Value>) -> Value {
match this.filter(|t| !with_host(|h| h.is_nullish(t))) {
Some(t) => with_host(|h| {
h.alloc(crate::host::JsObj::BoundFunc {
target: f,
this: t,
args: Vec::new(),
})
}),
None => f,
}
}
pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
Some(match method {
"@@runInFrame" => run_in_frame(args),
"executionAsyncId" => Ok(Value::Float(execution_async_id())),
"triggerAsyncId" => Ok(Value::Float(trigger_async_id())),
"createHook" => Ok(new_hook()),
_ => return None,
})
}
pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
match name {
"AsyncLocalStorage" => Some(Ok(new_native("AsyncLocalStorage"))),
"AsyncResource" => {
let r = new_native("AsyncResource");
let frame_id = hold_frame(with_host(|h| h.async_frame.clone()));
let trigger = args
.get(1)
.and_then(|o| {
with_host(|h| match h.get(o) {
Some(crate::host::JsObj::Object(p)) => p
.get("triggerAsyncId")
.filter(|v| !matches!(v, Value::Undef))
.map(|v| h.to_number(v)),
_ => None,
})
})
.unwrap_or_else(execution_async_id);
with_host(|h| {
if let Some(crate::host::JsObj::Object(p)) = h.get_mut(&r) {
p.insert("@@asyncId".into(), Value::Float(fresh_async_id()));
p.insert("@@triggerAsyncId".into(), Value::Float(trigger));
p.insert("@@frame".into(), Value::Float(frame_id));
}
});
Some(Ok(r))
}
_ => None,
}
}
fn new_native(tag: &'static str) -> Value {
with_host(|h| {
let mut m = IndexMap::new();
m.insert("@@native".into(), h.new_str(tag));
h.new_object(m)
})
}
fn hidden_num(recv: &Value, key: &str, fallback: f64) -> f64 {
with_host(|h| match h.get(recv) {
Some(crate::host::JsObj::Object(p)) => {
p.get(key).map(|v| h.to_number(v)).unwrap_or(fallback)
}
_ => fallback,
})
}
fn new_hook() -> Value {
new_native("AsyncHook")
}
pub fn instance_call(
tag: &str,
recv: &Value,
method: &str,
args: Vec<Value>,
) -> Result<Value, String> {
match tag {
"AsyncHook" => match method {
"enable" | "disable" => Ok(recv.clone()),
_ => Err(crate::host::type_error(&format!(
"{method} is not a function"
))),
},
"AsyncLocalStorage" => als_call(recv, method, args),
"AsyncResource" => resource_call(recv, method, args),
_ => Err(crate::host::type_error(&format!(
"{method} is not a function"
))),
}
}
fn resource_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
match method {
"runInAsyncScope" => {
let f = args.first().cloned().unwrap_or(Value::Undef);
let this = args.get(1).cloned();
let rest = args.get(2..).map(|s| s.to_vec()).unwrap_or_default();
let id = hidden_num(recv, "@@asyncId", 1.0);
let trigger = hidden_num(recv, "@@triggerAsyncId", 0.0);
let frame = resource_frame(recv);
in_async_scope(id, trigger, || {
crate::host::in_frame(frame, || invoke(&f, rest, this))
})
}
"bind" => {
let f = args.first().cloned().unwrap_or(Value::Undef);
let bound = bind_to(f, args.get(1).cloned());
frame_runner(resource_frame(recv), Some(bound))
}
"emitDestroy" => Ok(recv.clone()),
"asyncId" => Ok(Value::Float(hidden_num(recv, "@@asyncId", 1.0))),
"triggerAsyncId" => Ok(Value::Float(hidden_num(recv, "@@triggerAsyncId", 0.0))),
_ => Err(crate::host::type_error(&format!(
"{method} is not a function"
))),
}
}
fn key(recv: &Value) -> u32 {
match recv {
Value::Obj(i) => *i,
_ => 0,
}
}
fn als_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
let id = key(recv);
match method {
"getStore" => Ok(with_host(|h| {
h.async_frame
.iter()
.find(|(k, _)| *k == id)
.map(|(_, v)| v.clone())
.unwrap_or(Value::Undef)
})),
"run" => {
let store = args.first().cloned().unwrap_or(Value::Undef);
let cb = args.get(1).cloned().unwrap_or(Value::Undef);
let rest = args.get(2..).map(|s| s.to_vec()).unwrap_or_default();
let frame = crate::host::frame_with(id, Some(store));
crate::host::in_frame(frame, || invoke(&cb, rest, None))
}
"exit" => {
let cb = args.first().cloned().unwrap_or(Value::Undef);
let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
let frame = crate::host::frame_with(id, None);
crate::host::in_frame(frame, || invoke(&cb, rest, None))
}
"enterWith" | "disable" => {
let store =
(method == "enterWith").then(|| args.first().cloned().unwrap_or(Value::Undef));
let frame = crate::host::frame_with(id, store);
with_host(|h| h.async_frame = frame);
Ok(Value::Undef)
}
_ => Err(crate::host::type_error(&format!(
"{method} is not a function"
))),
}
}
fn resource_frame(recv: &Value) -> crate::host::AsyncFrame {
let id = hidden_num(recv, "@@frame", -1.0);
if id < 0.0 {
return with_host(|h| h.async_frame.clone());
}
HELD_FRAMES
.with(|f| f.borrow().get(id as usize).cloned())
.unwrap_or_default()
}
pub const ALS_STATIC_METHODS: &[&str] = &["bind", "snapshot"];
pub fn als_static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
let frame = with_host(|h| h.async_frame.clone());
Some(match method {
"snapshot" => frame_runner(frame, None),
"bind" => frame_runner(frame, Some(args.first().cloned().unwrap_or(Value::Undef))),
_ => return None,
})
}
thread_local! {
static HELD_FRAMES: RefCell<Vec<crate::host::AsyncFrame>> = const { RefCell::new(Vec::new()) };
}
fn hold_frame(frame: crate::host::AsyncFrame) -> f64 {
HELD_FRAMES.with(|f| {
let mut f = f.borrow_mut();
f.push(frame);
(f.len() - 1) as f64
})
}
fn frame_runner(frame: crate::host::AsyncFrame, target: Option<Value>) -> Result<Value, String> {
thread_local! {
static FACTORY: RefCell<Option<Value>> = const { RefCell::new(None) };
}
let factory = match FACTORY.with(|f| f.borrow().clone()) {
Some(f) => f,
None => {
let f = crate::eval_internal(
"(function (runner, id, target) {\n\
if (target === undefined) return function runInAsyncScope(fn, ...args) { return runner(id, fn, undefined, ...args); };\n\
return function (...args) { return runner(id, target, this, ...args); };\n\
})",
)?;
FACTORY.with(|c| *c.borrow_mut() = Some(f.clone()));
f
}
};
let id = Value::Float(hold_frame(frame));
let runner = with_host(|h| {
h.alloc(crate::host::JsObj::Builtin(
"async_hooks.@@runInFrame".into(),
))
});
invoke(
&factory,
vec![runner, id, target.unwrap_or(Value::Undef)],
None,
)
}
pub fn run_in_frame(args: &[Value]) -> Result<Value, String> {
let id = with_host(|h| h.to_number(args.first().unwrap_or(&Value::Undef))) as usize;
let frame = HELD_FRAMES
.with(|f| f.borrow().get(id).cloned())
.unwrap_or_default();
let f = args.get(1).cloned().unwrap_or(Value::Undef);
let this = args.get(2).cloned().filter(|t| !matches!(t, Value::Undef));
let rest = args.get(3..).map(|s| s.to_vec()).unwrap_or_default();
crate::host::in_frame(frame, || invoke(&f, rest, this))
}