cdk-rsx-executor 0.1.0

Async executor for CDK RSX canisters
//! The generated actor root's transient header. Application allocations retain
//! their ordinary allocator; large or over-aligned App values use an ordinary Box.
use crate::lifecycle::{Reclaimable, ReclaimableKey};
use std::thread::LocalKey;

/// Private generated-root operations. Every callback retains the root's RefCell
/// loan; clear detaches its value before invoking any application destructor.
#[doc(hidden)]
pub trait RootKey<T: 'static> {
    fn install(&'static self, app: T);
    fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R;
    fn clear(&'static self);
    fn is_empty(&'static self) -> bool;
}
impl<T: 'static> RootKey<T> for LocalKey<Reclaimable<Option<T>>> {
    fn install(&'static self, app: T) {
        self.with_borrow_mut(|slot| {
            assert!(slot.is_none(), "root already bound");
            *slot = Some(app);
        });
    }
    fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
        self.with_borrow(|slot| f(slot.as_ref().expect("root missing")))
    }
    fn clear(&'static self) {
        drop(self.take());
    }
    fn is_empty(&'static self) -> bool {
        self.inspect(|slot| slot.is_none_or(Option::is_none))
    }
}

/// The App type is invariant: a key may not be safely coerced into another
/// function-pointer subtype and then reinterpret the same fixed storage.
///
/// ```
/// use cdk_rsx_executor::lifecycle::HotRoot;
/// fn identity(key: &'static HotRoot<for<'a> fn(&'a u8)>)
///     -> &'static HotRoot<for<'a> fn(&'a u8)> { key }
/// ```
/// ```compile_fail
/// use cdk_rsx_executor::lifecycle::HotRoot;
/// fn change_type(key: &'static HotRoot<for<'a> fn(&'a u8)>)
///     -> &'static HotRoot<fn(&'static u8)> { key }
/// ```
#[doc(hidden)]
pub struct HotRoot<T>(std::marker::PhantomData<fn(T) -> T>);
#[cfg(target_family = "wasm")]
impl<T: 'static> HotRoot<T> {
    /// Construct only the private key emitted by the generated actor root.
    ///
    /// # Safety
    /// Exactly one key and one fixed App type may project this actor's root
    /// interval for its whole executable lifetime. The root macro's unique
    /// canister_init and memory-admission exports enforce one generated root.
    /// Canonical startup must reset the full gap before first use; old-code
    /// teardown must clear the value before KEEP. Do not construct another key.
    pub const unsafe fn new() -> Self {
        Self(std::marker::PhantomData)
    }
    fn storage(&self) -> &'static storage::Storage<T, PAYLOAD_BYTES> {
        // SAFETY: the private generated key fixes T for this whole lifetime.
        // Platform partitions are disjoint and prepare zeros this range before
        // Rust runs. Storage's flag and MaybeUninit payload are valid in zeros.
        // Wasm has no threads; its RefCell guards enforce all dynamic loans.
        unsafe { &*(cdk_rsx_platform::profile::HOT_ROOT_BASE as *const _) }
    }
}
#[cfg(target_family = "wasm")]
const PAYLOAD_BYTES: usize = cdk_rsx_platform::profile::HOT_ROOT_BYTES - storage::HEADER_BYTES;
#[cfg(target_family = "wasm")]
const _: () = {
    use cdk_rsx_platform::profile;
    use std::mem::{align_of, size_of};
    assert!(size_of::<storage::Storage<(), PAYLOAD_BYTES>>() <= profile::HOT_ROOT_BYTES);
    assert!(align_of::<storage::Storage<(), PAYLOAD_BYTES>>() <= profile::HOT_CONTROL_ALIGNMENT);
    assert!(
        profile::HOT_ROOT_BASE.is_multiple_of(align_of::<storage::Storage<(), PAYLOAD_BYTES>>())
    );
};
#[cfg(target_family = "wasm")]
impl<T: 'static> RootKey<T> for HotRoot<T> {
    fn install(&'static self, app: T) {
        self.storage().install(app);
    }
    fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
        self.storage().with(f)
    }
    fn clear(&'static self) {
        self.storage().clear();
    }
    fn is_empty(&'static self) -> bool {
        self.storage().is_empty()
    }
}

// The exact typed backing is also exercised by native tests. Production native
// roots above retain ordinary TLS; they never use a fixed Wasm address.
#[cfg(any(target_family = "wasm", test))]
mod storage {
    use std::{
        cell::{Cell, RefCell, UnsafeCell},
        marker::PhantomData,
        mem::{MaybeUninit, align_of, size_of},
    };
    #[repr(C, align(16))]
    struct Bytes<const N: usize>(UnsafeCell<MaybeUninit<[u8; N]>>);
    #[repr(C)]
    pub(super) struct Storage<T, const N: usize> {
        initialized: Cell<bool>,
        bytes: Bytes<N>,
        ty: PhantomData<fn(T) -> T>,
    }
    pub(super) const HEADER_BYTES: usize = size_of::<Storage<(), 0>>();
    enum Backing<'a, T> {
        Inline(&'a RefCell<Option<T>>),
        Boxed(&'a RefCell<Option<Box<T>>>),
    }
    impl<T, const N: usize> Storage<T, N> {
        pub(super) const INLINE: bool = size_of::<RefCell<Option<T>>>() <= N
            && align_of::<RefCell<Option<T>>>() <= align_of::<Bytes<N>>();
        #[cfg(test)]
        pub(super) const fn new() -> Self {
            Self {
                initialized: Cell::new(false),
                bytes: Bytes(UnsafeCell::new(MaybeUninit::uninit())),
                ty: PhantomData,
            }
        }
        /// S must be the one representation selected by INLINE for this T/N.
        unsafe fn cell<S>(&self) -> &RefCell<Option<S>> {
            let pointer = self.bytes.0.get().cast::<RefCell<Option<S>>>();
            if !self.initialized.get() {
                // SAFETY: backing proves size/alignment and fixes S for every
                // access. The pure empty constructor cannot call user code or
                // reenter. Publish only after the complete cell is initialized.
                unsafe { pointer.write(RefCell::new(None)) };
                self.initialized.set(true);
            }
            // SAFETY: this storage never moves in Wasm; native references pin
            // their owner. The same selected S was initialized above, and only
            // RefCell operations mutate its value or dynamic borrow state.
            unsafe { &*pointer }
        }
        fn backing(&self) -> Backing<'_, T> {
            const {
                assert!(size_of::<RefCell<Option<Box<T>>>>() <= N);
                assert!(align_of::<RefCell<Option<Box<T>>>>() <= align_of::<Bytes<N>>());
            }
            if Self::INLINE {
                // SAFETY: INLINE establishes this exact cell's size/alignment.
                Backing::Inline(unsafe { self.cell::<T>() })
            } else {
                // SAFETY: the const bounds above cover the only fallback type.
                Backing::Boxed(unsafe { self.cell::<Box<T>>() })
            }
        }
        pub(super) fn install(&self, app: T) {
            match self.backing() {
                Backing::Inline(cell) => {
                    let mut slot = cell.borrow_mut();
                    assert!(slot.is_none(), "root already bound");
                    *slot = Some(app);
                }
                Backing::Boxed(cell) => {
                    let mut slot = cell.borrow_mut();
                    assert!(slot.is_none(), "root already bound");
                    *slot = Some(Box::new(app));
                }
            }
        }
        pub(super) fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
            match self.backing() {
                Backing::Inline(cell) => f(cell.borrow().as_ref().expect("root missing")),
                Backing::Boxed(cell) => f(cell.borrow().as_deref().expect("root missing")),
            }
        }
        pub(super) fn is_empty(&self) -> bool {
            if !self.initialized.get() {
                return true;
            }
            match self.backing() {
                Backing::Inline(cell) => cell.borrow().is_none(),
                Backing::Boxed(cell) => cell.borrow().is_none(),
            }
        }
        pub(super) fn clear(&self) {
            if !self.initialized.get() {
                return;
            }
            // Release the dynamic loan before Drop. Keeping the branches
            // separate also avoids moving an oversized App out of its Box.
            match self.backing() {
                Backing::Inline(cell) => {
                    let value = cell.borrow_mut().take();
                    drop(value);
                }
                Backing::Boxed(cell) => {
                    let value = cell.borrow_mut().take();
                    drop(value);
                }
            }
        }
    }
    impl<T, const N: usize> Drop for Storage<T, N> {
        fn drop(&mut self) {
            self.clear();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{RootKey, storage::Storage};
    use crate::lifecycle::Reclaimable;
    use std::{cell::Cell, rc::Rc};
    fn aliases_and_unwind<const N: usize>() {
        let root = Storage::<String, N>::new();
        assert!(root.is_empty());
        root.install("root".to_owned());
        root.with(|a| root.with(|b| assert!(std::ptr::eq(a, b))));
        for mutate in [false, true] {
            let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                root.with(|_| {
                    if mutate {
                        root.install("duplicate".to_owned());
                    } else {
                        root.clear();
                    }
                });
            }));
            assert!(failed.is_err());
            root.with(|value| assert_eq!(value, "root"));
        }
        assert!(
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(
                || root.with(|_| panic!("body"))
            ))
            .is_err()
        );
        assert!(
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(
                || root.install("duplicate".to_owned())
            ))
            .is_err()
        );
        root.clear();
        assert!(root.is_empty());
        root.install("rebound".to_owned());
        root.with(|value| assert_eq!(value, "rebound"));
    }
    #[test]
    fn inline_and_boxed_headers_preserve_loans_unwind_and_rebinding() {
        assert!(Storage::<String, 128>::INLINE);
        assert!(!Storage::<String, 16>::INLINE);
        aliases_and_unwind::<128>();
        aliases_and_unwind::<16>();
    }
    #[test]
    fn large_and_overaligned_apps_use_the_ordinary_box_fallback() {
        struct Large {
            value: [u8; 8192],
            drops: Rc<Cell<u32>>,
        }
        impl Drop for Large {
            fn drop(&mut self) {
                self.drops.set(self.drops.get() + 1);
            }
        }
        #[repr(align(64))]
        struct Aligned([u8; 3]);
        let drops = Rc::new(Cell::new(0));
        let large = Storage::<Large, 128>::new();
        let aligned = Storage::<Aligned, 128>::new();
        assert!(!Storage::<Large, 128>::INLINE);
        assert_eq!(
            std::mem::size_of_val(&large),
            super::storage::HEADER_BYTES + 128
        );
        assert!(!Storage::<Aligned, 128>::INLINE);
        large.install(Large {
            value: [7; 8192],
            drops: drops.clone(),
        });
        aligned.install(Aligned([3, 4, 5]));
        large.with(|value| assert!(value.value.iter().all(|byte| *byte == 7)));
        large.clear();
        assert_eq!(drops.get(), 1);
        aligned.with(|value| {
            assert!((value as *const Aligned as usize).is_multiple_of(64));
            assert_eq!(value.0, [3, 4, 5]);
        });
    }
    thread_local! {
        static DROPS: Storage<Probe, 128> = const { Storage::new() };
        static NATIVE: Reclaimable<Option<u64>> = const { Reclaimable::new() };
    }
    struct Probe {
        count: Rc<Cell<u32>>,
        recreate: bool,
        fail: bool,
    }
    impl Drop for Probe {
        fn drop(&mut self) {
            self.count.set(self.count.get() + 1);
            DROPS.with(|root| {
                assert!(
                    root.is_empty(),
                    "drop must run after detaching and releasing the loan"
                );
                if self.recreate {
                    root.install(Probe {
                        count: self.count.clone(),
                        recreate: false,
                        fail: false,
                    });
                }
            });
            assert!(!self.fail, "destructor failure");
        }
    }
    #[test]
    fn clearing_drops_outside_the_loan_and_leaves_recreation_visible() {
        let count = Rc::new(Cell::new(0));
        DROPS.with(|root| {
            root.install(Probe {
                count: count.clone(),
                recreate: true,
                fail: false,
            });
            root.clear();
            assert!(!root.is_empty());
            root.clear();
            assert_eq!(count.get(), 2);
            root.install(Probe {
                count: count.clone(),
                recreate: false,
                fail: true,
            });
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| root.clear())).is_err()
            );
            assert!(root.is_empty());
            assert_eq!(count.get(), 3);
        });
    }
    #[test]
    fn native_generated_key_retains_thread_local_reclamation() {
        assert!(RootKey::is_empty(&NATIVE));
        RootKey::install(&NATIVE, 17);
        RootKey::with(&NATIVE, |a| {
            RootKey::with(&NATIVE, |b| assert_eq!((*a, *b), (17, 17)))
        });
        assert!(
            std::panic::catch_unwind(|| RootKey::with(&NATIVE, |_| RootKey::clear(&NATIVE)))
                .is_err()
        );
        RootKey::clear(&NATIVE);
        assert!(RootKey::is_empty(&NATIVE));
        std::thread::spawn(|| assert!(RootKey::is_empty(&NATIVE)))
            .join()
            .unwrap();
    }
}