cdk-rsx-executor 0.1.0

Async executor for CDK RSX canisters
//! SDK-private transient controls in the prepare-admitted stack/static gap.
//! Wasm targets use this placement; native hosts retain ordinary thread locals.
use crate::{
    lifecycle::{Reclaimable, ReclaimableKey},
    machinery::{Task, TaskId},
    method_registry::{MethodId, MethodRegistry},
};
use cdk_rsx_platform::profile;
use slotmap::SlotMap;
use std::{
    cell::{Cell, UnsafeCell},
    collections::VecDeque,
    marker::PhantomData,
    mem::{MaybeUninit, align_of, size_of},
    sync::Once,
};

/// This aggregate owns only the same transient headers previously held in TLS.
/// Overflow, task futures and queue payloads keep their ordinary allocations.
pub(crate) struct Control {
    setup: Once,
    methods: Reclaimable<MethodRegistry>,
    tasks: Reclaimable<SlotMap<TaskId, Task>>,
    migratory_wakeups: Reclaimable<VecDeque<TaskId>>,
    query_execution: Cell<bool>,
    current_method: Cell<Option<MethodId>>,
    recovering: Cell<bool>,
    current_task_id: Cell<Option<TaskId>>,
    store_active: Cell<*const ()>,
    store_disposing: Cell<bool>,
}
impl Control {
    const fn new() -> Self {
        Self {
            setup: Once::new(),
            methods: Reclaimable::new(),
            tasks: Reclaimable::new(),
            migratory_wakeups: Reclaimable::new(),
            query_execution: Cell::new(false),
            current_method: Cell::new(None),
            recovering: Cell::new(false),
            current_task_id: Cell::new(None),
            store_active: Cell::new(std::ptr::null()),
            store_disposing: Cell::new(false),
        }
    }
}

#[repr(C)]
struct Storage {
    initialized: Cell<u8>,
    value: UnsafeCell<MaybeUninit<Control>>,
}
const _: () = {
    assert!(size_of::<Storage>() <= profile::HOT_EXECUTOR_BYTES);
    assert!(align_of::<Storage>() <= profile::HOT_CONTROL_ALIGNMENT);
    assert!(profile::HOT_EXECUTOR_BASE.is_multiple_of(align_of::<Storage>()));
};

fn control() -> &'static Control {
    // SAFETY: canonical prepare excludes all active initializers from this
    // reserved range and zeros it before any Rust startup/admission code. The
    // full downward-growing stack ends at HOT_CONTROL_BASE and cannot overlap
    // the range above it. Storage is valid in zero bytes: u8 accepts every bit
    // pattern and MaybeUninit requires no initialized Control representation.
    // Wasm is single-threaded. This pure const constructor cannot reenter and
    // publishes the initialized flag only after every field has been written.
    // The control never moves or resets during an actor lifetime. Existing
    // executor shutdown drains/takes all owned backing before KEEP; raw startup
    // resets the complete gap before the new program can access it again.
    let storage = unsafe { &*(profile::HOT_EXECUTOR_BASE as *const Storage) };
    if storage.initialized.get() == 0 {
        unsafe { (*storage.value.get()).write(Control::new()) };
        storage.initialized.set(1);
    }
    unsafe { (&*storage.value.get()).assume_init_ref() }
}

/// Zero-sized projections carry no function pointer or separately placed data.
pub(crate) trait Field: 'static {
    type Value: 'static;
    fn get(control: &Control) -> &Self::Value;
}
pub(crate) struct Key<F>(PhantomData<fn() -> F>);
impl<F: Field> Key<F> {
    pub(crate) fn with<R>(&'static self, f: impl FnOnce(&F::Value) -> R) -> R {
        f(F::get(control()))
    }
}
impl<F, T: Copy + 'static> Key<F>
where
    F: Field<Value = Cell<T>>,
{
    pub(crate) fn get(&'static self) -> T {
        self.with(Cell::get)
    }
    pub(crate) fn set(&'static self, value: T) {
        self.with(|cell| cell.set(value));
    }
    pub(crate) fn replace(&'static self, value: T) -> T {
        self.with(|cell| cell.replace(value))
    }
}
impl<F: Field<Value = Once>> Key<F> {
    pub(crate) fn call_once(&'static self, f: impl FnOnce()) {
        self.with(|once| once.call_once(f));
    }
}
impl<F, T: Default + 'static> ReclaimableKey<T> for Key<F>
where
    F: Field<Value = Reclaimable<T>>,
{
    fn with_borrow<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
        self.with(|slot| f(&slot.borrow()))
    }
    fn with_borrow_mut<R>(&'static self, f: impl FnOnce(&mut T) -> R) -> R {
        self.with(|slot| f(&mut slot.borrow_mut()))
    }
    fn inspect<R>(&'static self, f: impl FnOnce(Option<&T>) -> R) -> R {
        self.with(|slot| slot.inspect(f))
    }
    fn take(&'static self) -> Option<T> {
        self.with(Reclaimable::take)
    }
}
macro_rules! key {
    ($name:ident, $projection:ident, $field:ident, $value:ty) => {
        pub(crate) struct $projection;
        impl Field for $projection {
            type Value = $value;
            fn get(control: &Control) -> &Self::Value {
                &control.$field
            }
        }
        pub(crate) static $name: Key<$projection> = Key(PhantomData);
    };
}
key!(SETUP, Setup, setup, Once);
key!(METHODS, Methods, methods, Reclaimable<MethodRegistry>);
key!(TASKS, Tasks, tasks, Reclaimable<SlotMap<TaskId, Task>>);
key!(
    MIGRATORY_WAKEUPS,
    MigratoryWakeups,
    migratory_wakeups,
    Reclaimable<VecDeque<TaskId>>
);
key!(QUERY_EXECUTION, QueryExecution, query_execution, Cell<bool>);
key!(
    CURRENT_METHOD,
    CurrentMethod,
    current_method,
    Cell<Option<MethodId>>
);
key!(RECOVERING, Recovering, recovering, Cell<bool>);
key!(
    CURRENT_TASK_ID,
    CurrentTaskId,
    current_task_id,
    Cell<Option<TaskId>>
);

/// Only the owning Store implementation may mutate this frame protocol.
///
/// # Safety
/// Every non-null active pointer must refer to the live Store Context for the
/// current synchronous frame. Maintain all existing frame/loan/disposal fences;
/// restore/clear the controls before that Context ends. Never expose these
/// mutable controls or references to application code.
pub(crate) unsafe fn with_store_controls<R>(
    f: impl FnOnce(&Cell<*const ()>, &Cell<bool>) -> R,
) -> R {
    let control = control();
    f(&control.store_active, &control.store_disposing)
}