cdk-rsx-executor 0.1.0

Async executor for CDK RSX canisters
//! An async executor for [`cdk-rsx`](https://docs.rs/ic-cdk). Most users should not use this crate directly. It is useful
//! primarily for those who are writing their own CDK or a runtime host for non-Rust languages.
//!
//! ## Contexts
//!
//! The expected boilerplate for a canister method or other entrypoint (*not* including callbacks) looks like this:
//!
//! ```
//! # use cdk_rsx_executor::*;
//! pub extern "C" fn function() {
//!     in_tracking_executor_context(|| {
//!         // method goes here
//!     });
//! }
//! ```
//!
//! The [`in_tracking_executor_context`] function permits you to call `spawn_*` functions. As little code as possible
//! should exist outside the block, because [`in_tracking_executor_context`] additionally sets up the panic handler.
//!
//! The above applies to update contexts. Query contexts, including `canister_inspect_message`, should use
//! [`in_tracking_query_executor_context`].
//!
//! The expected boilerplate for an inter-canister call callback looks like this:
//!
//! ```
//! # use cdk_rsx_executor::*;
//! # fn unpack_env(env: usize) -> MethodHandle { unimplemented!() }
//! unsafe extern "C" fn callback(env: usize) {
//!     let method = unpack_env(env);
//!     in_callback_executor_context_for(method, || {
//!        // wake the call future
//!     });
//! }
//! unsafe extern "C" fn cleanup(env: usize) {
//!     let method = unpack_env(env);
//!     in_trap_recovery_context_for(method, || {
//!         cancel_all_tasks_attached_to_current_method();
//!     });
//! }
//! ```
//!
//! In async contexts, all scheduled tasks are run *after* the closure passed to the context function
//! returns, but *before* the context function itself returns.
//!
//! The `method` parameter must be retrieved *before* making inter-canister calls via the [`extend_current_method_context`]
//! function. Calling this function from the callback instead will trap.
//!
//! ## Protection
//!
//! Tasks can be either *protected* or *migratory*. Protected tasks are attached to the method that spawned them,
//! when awoken will not resume until that method continues, and will be canceled if the method returns before they complete.
//! Migratory tasks are not attached to any method, and will resume in whatever method wakes them.
#[doc(hidden)]
pub mod dispatch;
#[cfg(target_family = "wasm")]
mod hot_control;
#[doc(hidden)]
pub mod lifecycle;
mod machinery;
mod method_registry;
mod root_control;
use lifecycle::ReclaimableKey as _;

/// Executor code that interprets the Wasm root and transient control headers.
#[doc(hidden)]
#[cfg(target_family = "wasm")]
pub const __ROOT_POLICY: [u8; 32] =
    cdk_rsx_source_policy::source_policy!("root_control.rs", "hot_control.rs", "lifecycle.rs");

/// Whether all executor tasks and callback-owned method contexts have drained.
/// Invoke outside an executor context, at the upgrade boundary.
pub fn is_idle() -> bool {
    machinery::METHODS.inspect(|m| m.is_none_or(|m| m.is_empty()))
        && machinery::TASKS.inspect(|t| t.is_none_or(|t| t.is_empty()))
}

/// Release all empty executor backing after callbacks and tasks have drained.
/// Invoke outside an executor context, after dropping application runtime roots.
#[doc(hidden)]
pub fn shutdown() -> Result<(), &'static str> {
    if !is_idle()
        || machinery::CURRENT_METHOD.get().is_some()
        || machinery::CURRENT_TASK_ID.get().is_some()
        || machinery::RECOVERING.get()
        || machinery::QUERY_EXECUTION.get()
    {
        return Err("executor shutdown requires drained tasks and no active context");
    }
    drop(machinery::MIGRATORY_WAKEUPS.take());
    drop(machinery::TASKS.take());
    drop(machinery::METHODS.take());
    Ok(())
}

#[cfg(test)]
mod shutdown_tests {
    use super::*;
    use std::{cell::Cell, rc::Rc};
    #[test]
    fn shutdown_frees_empty_backing_and_executor_can_restart() {
        let calls = Rc::new(Cell::new(0));
        for _ in 0..3 {
            let next = calls.clone();
            in_tracking_executor_context(|| {
                spawn_protected(async move {
                    next.set(next.get() + 1);
                })
            });
            assert!(is_idle());
            shutdown().unwrap();
            assert!(machinery::METHODS.inspect(|value| value.is_none()));
            assert!(machinery::TASKS.inspect(|value| value.is_none()));
            assert!(machinery::MIGRATORY_WAKEUPS.inspect(|value| value.is_none()));
            assert!(is_idle()); // An idle check must not recreate the SlotMap dummy allocation.
            assert!(machinery::METHODS.inspect(|value| value.is_none()));
        }
        assert_eq!(calls.get(), 3);
        assert_eq!(Rc::strong_count(&calls), 1);
    }
    #[test]
    fn shutdown_refuses_an_active_context_without_cancelling_it() {
        in_tracking_executor_context(|| {
            assert!(shutdown().is_err());
            assert!(!is_idle());
        });
        assert!(is_idle());
        shutdown().unwrap();
    }
}

#[doc(inline)]
pub use machinery::{
    MethodHandle, TaskHandle, cancel_all_tasks_attached_to_current_method, cancel_task,
    extend_current_method_context, in_callback_executor_context_for, in_tracking_executor_context,
    in_tracking_query_executor_context, in_trap_recovery_context_for, is_recovering_from_trap,
    spawn_migratory, spawn_protected,
};

#[doc(hidden)]
pub use machinery::in_tracking_executor_context_without_poll;

/// The active endpoint/callback is a query, including replicated queries.
#[doc(hidden)]
pub fn is_query_context() -> bool {
    machinery::QUERY_EXECUTION.get()
}

#[cfg(test)]
mod memory_capability_tests {
    use super::*;
    use std::{
        cell::Cell,
        future::Future,
        pin::Pin,
        rc::Rc,
        task::{Context, Poll},
    };
    struct PendingProbe(Rc<Cell<Option<bool>>>);
    impl Future for PendingProbe {
        type Output = ();
        fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
            Poll::Pending
        }
    }
    impl Drop for PendingProbe {
        fn drop(&mut self) {
            self.0.set(Some(is_query_context()));
        }
    }
    #[test]
    fn query_fence_covers_cancellation_and_callbacks() {
        let observed = Rc::new(Cell::new(None));
        in_tracking_query_executor_context(|| {
            spawn_protected(PendingProbe(observed.clone()));
        });
        assert_eq!(observed.get(), Some(true));
        assert!(!is_query_context());
        let callback = in_tracking_query_executor_context(extend_current_method_context);
        in_callback_executor_context_for(callback, || assert!(is_query_context()));
        assert!(!is_query_context());
        in_tracking_executor_context(|| {
            spawn_protected(PendingProbe(observed.clone()));
        });
        assert_eq!(observed.get(), Some(false));
    }
}

/// SDK-private bridge for Store's existing synchronous frame controls.
///
/// # Safety
/// The caller must preserve Store's Context liveness, frame loan and disposal
/// invariants. No control borrow may escape; no active pointer may outlive its
/// Context. This is not an application state/access API.
#[cfg(target_family = "wasm")]
#[doc(hidden)]
pub unsafe fn __with_store_controls<R>(
    f: impl FnOnce(&std::cell::Cell<*const ()>, &std::cell::Cell<bool>) -> R,
) -> R {
    unsafe { hot_control::with_store_controls(f) }
}