use crate::lifecycle::{Reclaimable, ReclaimableKey as _};
use crate::method_registry::{MethodId, MethodRegistry};
use std::{
collections::VecDeque,
future::Future,
mem::take,
pin::Pin,
sync::Arc,
task::{Context, Poll, Wake, Waker},
};
use slotmap::{SlotMap, new_key_type};
use smallvec::SmallVec;
#[cfg(not(target_family = "wasm"))]
use std::cell::Cell;
#[derive(Clone, Debug)]
pub(crate) struct MethodContext {
pub(crate) kind: ContextKind,
pub(crate) handles: usize,
pub(crate) tasks: SmallVec<[TaskId; 4]>,
wakeups: VecDeque<TaskId>,
}
impl MethodContext {
pub(crate) fn new_update() -> Self {
Self {
kind: ContextKind::Update,
handles: 0,
tasks: SmallVec::new(),
wakeups: VecDeque::new(),
}
}
pub(crate) fn new_query() -> Self {
Self {
kind: ContextKind::Query,
handles: 0,
tasks: SmallVec::new(),
wakeups: VecDeque::new(),
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) enum ContextKind {
Update,
Query,
}
new_key_type! {
pub(crate) struct TaskId;
}
#[cfg(not(target_family = "wasm"))]
thread_local! {
pub(crate) static METHODS: Reclaimable<MethodRegistry> = const { Reclaimable::new() };
pub(crate) static TASKS: Reclaimable<SlotMap<TaskId, Task>> = const { Reclaimable::new() };
pub(crate) static MIGRATORY_WAKEUPS: Reclaimable<VecDeque<TaskId>> = const { Reclaimable::new() };
pub(crate) static QUERY_EXECUTION: Cell<bool> = const { Cell::new(false) };
pub(crate) static CURRENT_METHOD: Cell<Option<MethodId>> = const { Cell::new(None) };
pub(crate) static RECOVERING: Cell<bool> = const { Cell::new(false) };
pub(crate) static CURRENT_TASK_ID: Cell<Option<TaskId>> = const { Cell::new(None) };
}
#[cfg(target_family = "wasm")]
pub(crate) use crate::hot_control::{
CURRENT_METHOD, CURRENT_TASK_ID, METHODS, MIGRATORY_WAKEUPS, QUERY_EXECUTION, RECOVERING, TASKS,
};
pub(crate) struct Task {
future: Option<Pin<Box<dyn Future<Output = ()>>>>,
method_binding: MethodId,
}
pub fn in_tracking_executor_context<R>(f: impl FnOnce() -> R) -> R {
in_tracking_executor_context_without_poll(|| {
let res = f();
poll_all();
res
})
}
#[doc(hidden)]
pub fn in_tracking_executor_context_without_poll<R>(f: impl FnOnce() -> R) -> R {
setup_panic_hook();
let method = METHODS.with_borrow_mut(|methods| methods.insert(MethodContext::new_update()));
enter_current_method(MethodHandle::for_method(method), f)
}
#[expect(dead_code)] pub(crate) fn in_null_context<R>(f: impl FnOnce() -> R) -> R {
setup_panic_hook();
let guard = MethodHandle::for_method(MethodId::null());
enter_current_method(guard, || {
let res = f();
poll_all();
res
})
}
pub fn in_tracking_query_executor_context<R>(f: impl FnOnce() -> R) -> R {
setup_panic_hook();
let method = METHODS.with_borrow_mut(|methods| methods.insert(MethodContext::new_query()));
let guard = MethodHandle::for_method(method);
enter_current_method(guard, || {
let res = f();
poll_all();
res
})
}
pub fn in_callback_executor_context_for<R>(
method_handle: MethodHandle,
f: impl FnOnce() -> R,
) -> R {
setup_panic_hook();
enter_current_method(method_handle, || {
let res = f();
poll_all();
res
})
}
pub fn in_trap_recovery_context_for<R>(method: MethodHandle, f: impl FnOnce() -> R) -> R {
setup_panic_hook();
enter_current_method(method, || {
RECOVERING.set(true);
let res = f();
RECOVERING.set(false);
res
})
}
pub fn cancel_all_tasks_attached_to_current_method() {
let Some(method_id) = CURRENT_METHOD.get() else {
panic!(
"`cancel_all_tasks_attached_to_current_method` can only be called within a method context"
);
};
cancel_all_tasks_attached_to_method(method_id);
}
fn cancel_all_tasks_attached_to_method(method_id: MethodId) {
let Some(to_cancel) = METHODS.with_borrow_mut(|methods| {
methods
.get_mut(method_id)
.map(|method| take(&mut method.tasks))
}) else {
return; };
let _tasks = TASKS.with(|tasks| {
let Ok(mut tasks) = tasks.try_borrow_mut() else {
panic!(
"`cancel_all_tasks_attached_to_current_method` cannot be called from an async task"
);
};
let mut canceled = Vec::with_capacity(to_cancel.len());
for task_id in to_cancel {
canceled.push(tasks.remove(task_id));
}
canceled
});
drop(_tasks); }
pub(crate) fn delete_task(task_id: TaskId) {
let _task = TASKS.with_borrow_mut(|tasks| tasks.remove(task_id));
drop(_task); }
pub fn cancel_task(task_handle: &TaskHandle) {
delete_task(task_handle.task_id);
}
pub fn is_recovering_from_trap() -> bool {
RECOVERING.get()
}
pub fn extend_current_method_context() -> MethodHandle {
setup_panic_hook();
let Some(method_id) = CURRENT_METHOD.get() else {
panic!("`extend_method_context` can only be called within a tracking executor context");
};
MethodHandle::for_method(method_id)
}
pub(crate) fn poll_all() {
let Some(method_id) = CURRENT_METHOD.get() else {
panic!("tasks can only be polled within an executor context");
};
let kind = METHODS
.with_borrow(|methods| methods.get(method_id).map(|m| m.kind))
.unwrap_or(ContextKind::Update);
fn pop_wakeup(method_id: MethodId, update: bool) -> Option<TaskId> {
if let Some(task_id) = METHODS.with_borrow_mut(|methods| {
methods
.get_mut(method_id)
.and_then(|method| method.wakeups.pop_front())
}) {
Some(task_id)
} else if update {
MIGRATORY_WAKEUPS.with_borrow_mut(|unattached| unattached.pop_front())
} else {
None
}
}
while let Some(task_id) = pop_wakeup(method_id, kind == ContextKind::Update) {
let Some((mut future, binding)) = TASKS.with_borrow_mut(|tasks| {
let task = tasks.get_mut(task_id)?;
Some((task.future.take()?, task.method_binding))
}) else {
continue;
};
let waker = Waker::from(Arc::new(TaskWaker { task_id }));
let prev_current_method_var = CURRENT_METHOD.replace(Some(binding));
CURRENT_TASK_ID.set(Some(task_id));
let poll = future.as_mut().poll(&mut Context::from_waker(&waker));
CURRENT_TASK_ID.set(None);
CURRENT_METHOD.set(prev_current_method_var);
match poll {
Poll::Pending => {
let discarded = TASKS.with_borrow_mut(|tasks| match tasks.get_mut(task_id) {
Some(task) => task.future.replace(future),
None => Some(future),
});
drop(discarded);
}
Poll::Ready(()) => {
delete_task(task_id);
}
}
}
}
struct QueryExecutionGuard(bool);
impl Drop for QueryExecutionGuard {
fn drop(&mut self) {
QUERY_EXECUTION.set(self.0);
}
}
pub(crate) fn enter_current_method<R>(method_guard: MethodHandle, f: impl FnOnce() -> R) -> R {
CURRENT_METHOD.with(|context_var| {
assert!(
context_var.get().is_none(),
"in_*_context called within an existing async context"
);
context_var.set(Some(method_guard.method_id));
});
let query = METHODS.with_borrow(|methods| {
methods
.get(method_guard.method_id)
.is_some_and(|m| m.kind == ContextKind::Query)
});
let _query_guard = QueryExecutionGuard(QUERY_EXECUTION.replace(QUERY_EXECUTION.get() || query));
let r = f();
drop(method_guard); let method_id = CURRENT_METHOD.replace(None);
if let Some(method_id) = method_id {
let handles = METHODS.with_borrow_mut(|methods| methods.get(method_id).map(|m| m.handles));
if handles == Some(0) {
cancel_all_tasks_attached_to_method(method_id);
METHODS.with_borrow_mut(|methods| methods.remove(method_id));
}
}
r
}
#[derive(Debug)]
pub struct MethodHandle {
method_id: MethodId,
}
impl MethodHandle {
pub(crate) fn for_method(method_id: MethodId) -> Self {
if method_id.is_null() {
return Self { method_id };
}
METHODS.with_borrow_mut(|methods| {
let Some(method) = methods.get_mut(method_id) else {
panic!("internal error: method context deleted while in use (for_method)");
};
method.handles += 1;
});
Self { method_id }
}
}
impl Drop for MethodHandle {
fn drop(&mut self) {
METHODS.with_borrow_mut(|methods| {
if let Some(method) = methods.get_mut(self.method_id) {
method.handles -= 1;
}
})
}
}
#[derive(Debug)]
pub struct TaskHandle {
task_id: TaskId,
}
impl TaskHandle {
pub fn current() -> Option<Self> {
let task_id = CURRENT_TASK_ID.get()?;
Some(Self { task_id })
}
}
pub(crate) struct TaskWaker {
pub(crate) task_id: TaskId,
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
TASKS.with_borrow_mut(|tasks| {
if let Some(task) = tasks.get(self.task_id) {
let method_id = task.method_binding;
if !method_id.is_null() {
METHODS.with_borrow_mut(|methods| {
if let Some(method) = methods.get_mut(method_id) {
method.wakeups.push_back(self.task_id);
}
});
} else {
MIGRATORY_WAKEUPS.with_borrow_mut(|unattached| {
unattached.push_back(self.task_id);
});
}
}
})
}
}
pub fn spawn_migratory(f: impl Future<Output = ()> + 'static) -> TaskHandle {
setup_panic_hook();
let Some(method_id) = CURRENT_METHOD.get() else {
panic!("`spawn_*` can only be called within an executor context");
};
if is_recovering_from_trap() {
panic!("tasks cannot be spawned while recovering from a trap");
}
let kind = METHODS
.with_borrow(|methods| methods.get(method_id).map(|m| m.kind))
.unwrap_or(ContextKind::Update);
if kind == ContextKind::Query {
panic!("unprotected spawns cannot be made within a query context");
}
let task = Task {
future: Some(Box::pin(f)),
method_binding: MethodId::null(),
};
let task_id = TASKS.with_borrow_mut(|tasks| tasks.insert(task));
MIGRATORY_WAKEUPS.with_borrow_mut(|unattached| {
unattached.push_back(task_id);
});
TaskHandle { task_id }
}
pub fn spawn_protected(f: impl Future<Output = ()> + 'static) -> TaskHandle {
setup_panic_hook();
if is_recovering_from_trap() {
panic!("tasks cannot be spawned while recovering from a trap");
}
let Some(method_id) = CURRENT_METHOD.get() else {
panic!("`spawn_*` can only be called within an executor context");
};
if method_id.is_null() {
panic!("`spawn_protected` cannot be called outside of a tracked method context");
}
let task = Task {
future: Some(Box::pin(f)),
method_binding: method_id,
};
let task_id = TASKS.with_borrow_mut(|tasks| tasks.insert(task));
METHODS.with_borrow_mut(|methods| {
let Some(method) = methods.get_mut(method_id) else {
panic!("internal error: method context deleted while in use (spawn_protected)");
};
method.tasks.push(task_id);
method.wakeups.push_back(task_id);
});
TaskHandle { task_id }
}
#[cfg(target_family = "wasm")]
fn setup_panic_hook() {
use crate::hot_control::SETUP;
SETUP.call_once(|| {
std::panic::set_hook(Box::new(|info| {
let file = info.location().unwrap().file();
let line = info.location().unwrap().line();
let col = info.location().unwrap().column();
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match info.payload().downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
},
};
let err_info = format!("Panicked at '{msg}', {file}:{line}:{col}");
cdk_rsx_sys::debug_print(err_info.as_bytes());
cdk_rsx_sys::trap(err_info.as_bytes());
}));
});
}
#[cfg(not(target_family = "wasm"))]
fn setup_panic_hook() {}
#[cfg(test)]
mod tests {
use super::*;
use std::{cell::RefCell, rc::Rc};
#[cfg(not(target_family = "wasm"))]
#[test]
fn native_contexts_leave_expected_panics_catchable() {
in_tracking_executor_context(|| {});
let failure = std::panic::catch_unwind(|| panic!("expected native panic")).unwrap_err();
assert_eq!(
failure.downcast_ref::<&str>(),
Some(&"expected native panic")
);
assert!(crate::is_idle());
crate::shutdown().unwrap();
}
#[derive(Clone, Default)]
struct Signal {
ready: Rc<Cell<bool>>,
waker: Rc<RefCell<Option<Waker>>>,
polls: Rc<Cell<usize>>,
drops: Rc<RefCell<Vec<(bool, bool)>>>,
}
impl Signal {
fn wake(&self) {
self.waker.borrow().as_ref().unwrap().wake_by_ref();
}
}
struct Wait(Signal);
impl Future for Wait {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
assert!(TaskHandle::current().is_some());
self.0.polls.set(self.0.polls.get() + 1);
*self.0.waker.borrow_mut() = Some(cx.waker().clone());
if self.0.ready.get() {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl Drop for Wait {
fn drop(&mut self) {
let handle = CURRENT_METHOD
.get()
.map(|_| extend_current_method_context());
assert!(METHODS.with(|methods| methods.try_borrow_mut().is_ok()));
assert!(TASKS.with(|tasks| tasks.try_borrow_mut().is_ok()));
self.0
.drops
.borrow_mut()
.push((QUERY_EXECUTION.get(), is_recovering_from_trap()));
drop(handle);
}
}
#[test]
fn callbacks_retain_their_context_across_overflow_growth_and_reuse() {
let signals: Vec<_> = (0..12).map(|_| Signal::default()).collect();
let callbacks: Vec<_> = signals
.iter()
.map(|signal| {
in_tracking_executor_context(|| {
spawn_protected(Wait(signal.clone()));
extend_current_method_context()
})
})
.collect();
assert!(crate::shutdown().is_err());
for (signal, callback) in signals.iter().zip(callbacks).rev() {
signal.ready.set(true);
signal.wake();
in_tracking_query_executor_context(|| {});
assert_eq!(signal.polls.get(), 1);
in_callback_executor_context_for(callback, || {
assert!(!QUERY_EXECUTION.get());
let alias = extend_current_method_context();
assert_eq!(alias.method_id, CURRENT_METHOD.get().unwrap());
});
assert_eq!(signal.polls.get(), 2);
assert_eq!(*signal.drops.borrow(), [(false, false)]);
}
assert!(crate::is_idle());
for signal in &signals {
signal.wake();
}
let fresh = Signal::default();
in_tracking_executor_context(|| {
spawn_protected(Wait(fresh.clone()));
});
assert_eq!(fresh.polls.get(), 1);
assert_eq!(*fresh.drops.borrow(), [(false, false)]);
assert!(crate::is_idle());
crate::shutdown().unwrap();
assert!(METHODS.inspect(|value| value.is_none()));
}
#[test]
fn protected_wakes_wait_for_owner_while_migratory_wakes_skip_queries() {
let protected = Signal::default();
let migratory = Signal::default();
let callback = in_tracking_executor_context(|| {
spawn_protected(Wait(protected.clone()));
spawn_migratory(Wait(migratory.clone()));
extend_current_method_context()
});
assert_eq!(protected.polls.get(), 1);
assert_eq!(migratory.polls.get(), 1);
protected.ready.set(true);
migratory.ready.set(true);
protected.wake();
migratory.wake();
in_tracking_query_executor_context(|| {});
assert_eq!(protected.polls.get(), 1);
assert_eq!(migratory.polls.get(), 1);
in_tracking_executor_context(|| {});
assert_eq!(protected.polls.get(), 1);
assert_eq!(migratory.polls.get(), 2);
in_callback_executor_context_for(callback, || {});
assert_eq!(protected.polls.get(), 2);
assert!(crate::is_idle());
crate::shutdown().unwrap();
}
#[test]
fn protected_query_self_wakes_are_polled_in_the_current_entry() {
let signal = Signal::default();
let callback = in_tracking_query_executor_context(|| {
let signal = signal.clone();
spawn_protected(std::future::poll_fn(move |cx| {
assert!(QUERY_EXECUTION.get());
let polls = signal.polls.get();
signal.polls.set(polls + 1);
match polls {
0 | 2 => {
cx.waker().wake_by_ref();
Poll::Pending
}
1 => {
*signal.waker.borrow_mut() = Some(cx.waker().clone());
Poll::Pending
}
3 => Poll::Ready(()),
_ => panic!("polled after completion"),
}
}));
extend_current_method_context()
});
assert_eq!(signal.polls.get(), 2);
in_callback_executor_context_for(callback, || signal.wake());
assert_eq!(signal.polls.get(), 4);
assert!(MIGRATORY_WAKEUPS.inspect(|wakes| wakes.is_none_or(VecDeque::is_empty)));
assert!(crate::is_idle());
crate::shutdown().unwrap();
}
#[test]
fn recovery_cancels_query_tasks_with_fence_and_retains_other_callback_handles() {
let update = in_tracking_executor_context(extend_current_method_context);
let signal = Signal::default();
let (cleanup, late_callback) = in_tracking_query_executor_context(|| {
spawn_protected(Wait(signal.clone()));
(
extend_current_method_context(),
extend_current_method_context(),
)
});
in_trap_recovery_context_for(cleanup, || {
assert!(QUERY_EXECUTION.get());
assert!(is_recovering_from_trap());
cancel_all_tasks_attached_to_current_method();
});
assert!(!QUERY_EXECUTION.get());
assert!(!is_recovering_from_trap());
assert_eq!(*signal.drops.borrow(), [(true, true)]);
assert!(!crate::is_idle());
signal.wake();
in_callback_executor_context_for(late_callback, || {
assert!(QUERY_EXECUTION.get());
});
assert_eq!(signal.polls.get(), 1);
assert!(!crate::is_idle());
in_callback_executor_context_for(update, || {
assert!(!QUERY_EXECUTION.get());
});
assert!(crate::is_idle());
crate::shutdown().unwrap();
}
#[test]
fn protected_tasks_can_spawn_during_poll_and_reenter_method_during_drop() {
let child = Signal::default();
let child_task = Rc::new(RefCell::new(None));
in_tracking_executor_context(|| {
let task = child_task.clone();
let signal = child.clone();
spawn_protected(async move {
*task.borrow_mut() = Some(spawn_protected(Wait(signal)));
});
});
assert_eq!(child.polls.get(), 1);
assert_eq!(*child.drops.borrow(), [(false, false)]);
let stale = child_task.borrow_mut().take().unwrap();
let fresh = Signal::default();
in_tracking_executor_context(|| {
spawn_protected(Wait(fresh.clone()));
cancel_task(&stale);
});
assert_eq!(fresh.polls.get(), 1);
assert!(crate::is_idle());
crate::shutdown().unwrap();
}
}