cdk-rsx-executor 0.1.0

Async executor for CDK RSX canisters
//! Transient TLS that can release its complete backing at a quiescent boundary.
pub use crate::root_control::{HotRoot, RootKey};
use std::{
    cell::{Cell, Ref, RefCell, RefMut},
    thread::LocalKey,
};

/// A library's transient roots, released after application, timer and executor
/// teardown. Declare this in TLS and register its static key from cache setup.
/// Callbacks must run at a quiescent boundary; inspection is pure and allocation-free.
pub struct CleanupProvider {
    name: &'static str,
    clear: fn(),
    is_clear: fn() -> bool,
    next: Cell<Option<&'static LocalKey<CleanupProvider>>>,
    registered: Cell<bool>,
}
thread_local! {
    // Only static keys and old-code callbacks: no owned backing or retained state.
    static PROVIDERS: Cell<Option<&'static LocalKey<CleanupProvider>>> = const { Cell::new(None) };
}
impl CleanupProvider {
    /// Construct an allocation-free provider. Each thread has its own links.
    pub const fn new(name: &'static str, clear: fn(), is_clear: fn() -> bool) -> Self {
        Self {
            name,
            clear,
            is_clear,
            next: Cell::new(None),
            registered: Cell::new(false),
        }
    }

    /// Register once per thread, without scanning or allocating. Keep registration
    /// for the executable's lifetime: an initialized cache can refill after reset.
    pub fn register(key: &'static LocalKey<Self>) {
        key.with(|provider| {
            if !provider.registered.replace(true) {
                provider.next.set(PROVIDERS.replace(Some(key)));
            }
        });
    }
}

/// Release all registered library roots, then inspect every provider. Callbacks
/// run outside TLS access closures, so another owner's Drop may use the registry.
pub fn clear_providers() {
    let head = PROVIDERS.get();
    let mut current = head;
    while let Some(key) = current {
        let (clear, next) = key.with(|provider| (provider.clear, provider.next.get()));
        clear();
        current = next;
    }
    assert_providers_unchanged(head);
    assert_providers_drained();
}

/// Recheck immediately before the final allocator gate; never clear a root here.
pub fn assert_providers_drained() {
    let head = PROVIDERS.get();
    let mut current = head;
    while let Some(key) = current {
        let (name, is_clear, next) =
            key.with(|provider| (provider.name, provider.is_clear, provider.next.get()));
        assert!(is_clear(), "library root recreated during teardown: {name}");
        current = next;
    }
    assert_providers_unchanged(head);
}

fn assert_providers_unchanged(head: Option<&'static LocalKey<CleanupProvider>>) {
    assert!(
        match (PROVIDERS.get(), head) {
            (Some(actual), Some(expected)) => std::ptr::eq(actual, expected),
            (None, None) => true,
            _ => false,
        },
        "library provider registered during teardown"
    );
}

/// An ordinary lazily initialized process value; `take` leaves no backing value.
/// This does not trace unregistered statics or repair forgotten reference counts.
pub struct Reclaimable<T>(RefCell<Option<T>>);
impl<T> Reclaimable<T> {
    /// Construct an allocation-free empty TLS slot.
    pub const fn new() -> Self {
        Self(RefCell::new(None))
    }
    /// Inspect without creating the default value.
    pub fn inspect<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R {
        f(self.0.borrow().as_ref())
    }
    /// Detach before dropping, so destructors run without a TLS borrow.
    pub fn take(&self) -> Option<T> {
        self.0.borrow_mut().take()
    }
    /// Try to borrow existing backing without recreating a released value.
    pub fn try_borrow_mut_if_initialized(
        &self,
    ) -> Result<Option<RefMut<'_, T>>, std::cell::BorrowMutError> {
        Ok(
            match RefMut::filter_map(self.0.try_borrow_mut()?, Option::as_mut) {
                Ok(value) => Some(value),
                Err(_) => None,
            },
        )
    }
}
impl<T> Default for Reclaimable<T> {
    fn default() -> Self {
        Self::new()
    }
}
impl<T: Default> Reclaimable<T> {
    /// Borrow the process value, initializing it on first use.
    pub fn borrow(&self) -> Ref<'_, T> {
        match Ref::filter_map(self.0.borrow(), Option::as_ref) {
            Ok(value) => value,
            Err(empty) => {
                drop(empty);
                self.0.borrow_mut().get_or_insert_with(T::default);
                Ref::map(self.0.borrow(), |value| value.as_ref().unwrap())
            }
        }
    }
    /// Mutably borrow the process value, initializing it on first use.
    pub fn borrow_mut(&self) -> RefMut<'_, T> {
        RefMut::map(self.0.borrow_mut(), |value| {
            value.get_or_insert_with(T::default)
        })
    }
    /// Preserve the executor's nonpanicking cancellation probe during Drop.
    pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, std::cell::BorrowMutError> {
        self.0
            .try_borrow_mut()
            .map(|value| RefMut::map(value, |value| value.get_or_insert_with(T::default)))
    }
}

/// Scoped access to a reclaimable thread-local value.
pub trait ReclaimableKey<T: Default + 'static> {
    /// Borrow the initialized value for one synchronous operation.
    fn with_borrow<R>(&'static self, f: impl FnOnce(&T) -> R) -> R;
    /// Mutably borrow the initialized value for one synchronous operation.
    fn with_borrow_mut<R>(&'static self, f: impl FnOnce(&mut T) -> R) -> R;
    /// Inspect without initializing a value or allocating its backing.
    fn inspect<R>(&'static self, f: impl FnOnce(Option<&T>) -> R) -> R;
    /// Take the value, releasing its borrow before any destructor runs.
    fn take(&'static self) -> Option<T>;
}
impl<T: Default + 'static> ReclaimableKey<T> for LocalKey<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)
    }
}

#[cfg(test)]
mod provider_tests {
    use super::*;
    thread_local! {
        static VALUE: Cell<bool> = const { Cell::new(false) };
        static CLEARS: Cell<usize> = const { Cell::new(0) };
        static CACHE: CleanupProvider = const { CleanupProvider::new("cache", clear, is_clear) };
        static LATE: CleanupProvider = const { CleanupProvider::new("late", || {}, || true) };
        static REGISTRAR: CleanupProvider = const {
            CleanupProvider::new("registrar", || CleanupProvider::register(&LATE), || true)
        };
        static RECREATOR: CleanupProvider = const {
            CleanupProvider::new("recreator", || VALUE.set(true), || true)
        };
    }
    fn clear() {
        VALUE.set(false);
        CLEARS.set(CLEARS.get() + 1);
    }
    fn is_clear() -> bool {
        !VALUE.get()
    }
    #[test]
    fn deduplication_and_registration_survive_repeated_cleanup() {
        for expected in 1..=3 {
            CleanupProvider::register(&CACHE);
            CleanupProvider::register(&CACHE);
            VALUE.set(true);
            clear_providers();
            assert_providers_drained();
            assert_eq!(CLEARS.get(), expected);
        }
    }
    #[test]
    fn registration_during_a_callback_is_safe_but_rejected() {
        CleanupProvider::register(&REGISTRAR);
        let failure = std::panic::catch_unwind(clear_providers).unwrap_err();
        assert!(
            failure.downcast_ref::<String>().is_some_and(|message| {
                message.contains("library provider registered during teardown")
            }) || failure.downcast_ref::<&str>().is_some_and(|message| {
                message.contains("library provider registered during teardown")
            })
        );
        // No registry borrow escaped into the callback, and the new link remains valid.
        clear_providers();
    }
    #[test]
    fn every_provider_is_checked_after_all_destructors_and_again_at_the_final_gate() {
        CleanupProvider::register(&RECREATOR);
        CleanupProvider::register(&CACHE);
        assert!(std::panic::catch_unwind(clear_providers).is_err());
        VALUE.set(false);
        assert_providers_drained();
        VALUE.set(true);
        assert!(std::panic::catch_unwind(assert_providers_drained).is_err());
        VALUE.set(false);
    }
    #[test]
    fn registrations_and_links_are_local_to_each_native_thread() {
        let workers: Vec<_> = (0..2)
            .map(|_| {
                std::thread::spawn(|| {
                    CleanupProvider::register(&CACHE);
                    VALUE.set(true);
                    clear_providers();
                    assert_eq!(CLEARS.get(), 1);
                    assert_providers_drained();
                })
            })
            .collect();
        for worker in workers {
            worker.join().unwrap();
        }
        assert_eq!(CLEARS.get(), 0);
    }
}