scope.rs

cdk-rsx/crates/cdk-rsx-store/src/scope.rs

scope.rs548 lines← SDK documentation
1use crate::{backend, *};2use std::{3    cell::{Cell, RefCell},4    marker::PhantomData,5};67#[cfg(not(target_family = "wasm"))]8thread_local! {9    static ACTIVE: Cell<*const ()> = const { Cell::new(std::ptr::null()) };10    static DISPOSING: Cell<bool> = const { Cell::new(false) };11}12// The typed values stay owned by Store's frame protocol; wasm only changes13// their physical carrier. Native hosts retain their ordinary per-thread TLS.14#[cfg(target_family = "wasm")]15struct ActiveKey;16#[cfg(target_family = "wasm")]17static ACTIVE: ActiveKey = ActiveKey;18#[cfg(target_family = "wasm")]19impl ActiveKey {20    fn with<R>(&self, f: impl FnOnce(&Cell<*const ()>) -> R) -> R {21        // SAFETY: this private adapter is used only by the unchanged Store22        // frame/liveness checks and Context cleanup below.23        unsafe { cdk_rsx_executor::__with_store_controls(|active, _| f(active)) }24    }25    fn get(&self) -> *const () {26        self.with(Cell::get)27    }28    fn set(&self, value: *const ()) {29        self.with(|active| active.set(value));30    }31}32#[cfg(target_family = "wasm")]33struct DisposingKey;34#[cfg(target_family = "wasm")]35static DISPOSING: DisposingKey = DisposingKey;36#[cfg(target_family = "wasm")]37impl DisposingKey {38    fn get(&self) -> bool {39        // SAFETY: read-only inspection of Store's private disposal flag.40        unsafe { cdk_rsx_executor::__with_store_controls(|_, disposing| disposing.get()) }41    }42    fn set(&self, value: bool) {43        // SAFETY: only Disposing's existing guard restores this flag.44        unsafe { cdk_rsx_executor::__with_store_controls(|_, disposing| disposing.set(value)) }45    }46    fn replace(&self, value: bool) -> bool {47        // SAFETY: only Disposing's existing guard enters disposal.48        unsafe { cdk_rsx_executor::__with_store_controls(|_, disposing| disposing.replace(value)) }49    }50}51pub(crate) struct Disposing(bool);52impl Disposing {53    pub(crate) fn enter() -> Self {54        Self(DISPOSING.replace(true))55    }56}57impl Drop for Disposing {58    fn drop(&mut self) {59        DISPOSING.set(self.0);60    }61}6263pub struct Context<'i> {64    pub store: &'i Store,65    read_only: bool,66    loans: Cell<usize>,67    pending: RefCell<Vec<Pending>>,68    pub(crate) records: hylix::FrameRecords,69}70struct Pending {71    identity: Identity,72    destroy: fn(&Context<'_>, Identity) -> Result<()>,73}74impl<'i> Context<'i> {75    fn new(store: &'i Store, read_only: bool) -> Self {76        Self {77            store,78            read_only,79            loans: Cell::new(0),80            pending: RefCell::new(Vec::new()),81            records: hylix::FrameRecords::default(),82        }83    }84    pub(crate) fn read_only(&self) -> bool {85        self.read_only86    }87    pub(crate) fn loan(&self) {88        self.loans89            .set(self.loans.get().checked_add(1).expect("borrow counter"));90    }91    pub(crate) fn unloan(&self) {92        self.loans93            .set(self.loans.get().checked_sub(1).expect("borrow counter"));94    }95    fn no_loans(&self) -> Result<()> {96        if self.loans.get() == 0 {97            Ok(())98        } else {99            Err(Error::Borrowed)100        }101    }102    #[inline]103    pub(crate) fn resolve<M: ModuleMemory>(&self, reference: ModuleRef<M>) -> Result<usize> {104        self.store.resolve_bound(105            reference.identity,106            reference.pointer,107            reference.binding_epoch,108        )109    }110    fn same_scope<M: ModuleMemory>(&self, ticket: &Detached<'_, M>) -> Result<()> {111        if ticket.scope == (self as *const Self).cast::<()>() {112            Ok(())113        } else {114            Err(Error::WrongOwner)115        }116    }117    pub(crate) fn attach<M: ModuleMemory>(118        &self,119        owner: Identity,120        ticket: Detached<'_, M>,121    ) -> Result<Identity> {122        self.same_scope(&ticket)?;123        self.resolve(ticket.reference)?;124        let id = ticket.reference.identity;125        let slot = self.store.slot(id)?;126        if slot.state != backend::DETACHED {127            return Err(Error::NotDetached);128        }129        self.store.slot(owner)?;130        // Brands prevent escape, not cycles: a descendant ID may still be live131        // after detaching its ancestor. Check only a module-ownership operation.132        let mut ancestor = owner;133        let mut steps = 0usize;134        let budget = self.store.slots_len();135        while !ancestor.is_none() {136            if ancestor == id {137                return Err(Error::Cycle);138            }139            ancestor = self.store.slot(ancestor)?.parent;140            steps += 1;141            if steps > budget {142                return Err(Error::Cycle);143            }144        }145        if !self.pending.borrow().iter().any(|p| p.identity == id) {146            return Err(Error::NotDetached);147        }148        self.store.update(id, |s| {149            s.parent = owner;150            s.state = backend::ATTACHED;151        })?;152        self.pending.borrow_mut().retain(|p| p.identity != id);153        Ok(id)154    }155    pub(crate) fn detach<M: ModuleMemory>(156        &self,157        owner: Identity,158        id: Identity,159    ) -> Result<Detached<'_, M>> {160        let slot = self.store.slot(id)?;161        if slot.parent != owner || slot.state != backend::ATTACHED {162            return Err(Error::WrongOwner);163        }164        let reference = self.store.bind::<M>(id)?;165        self.store.update(id, |s| {166            s.parent = Identity::NONE;167            s.state = backend::DETACHED;168        })?;169        self.pending.borrow_mut().push(Pending {170            identity: id,171            destroy: release::<M>,172        });173        Ok(Detached {174            reference,175            scope: (self as *const Self).cast(),176            marker: PhantomData,177        })178    }179    pub(crate) fn retire_owner<M: ModuleMemory>(180        &self,181        owner: Identity,182        id: Identity,183    ) -> Result<()> {184        self.detach::<M>(owner, id).map(|_| ())185    }186    fn finish(&self) {187        self.no_loans().unwrap_or_else(|e| fatal(e));188        cdk_rsx_engine_hylix::check_no_loans().unwrap_or_else(|_| fatal(Error::Hylix));189        loop {190            let entry = self.pending.borrow_mut().pop();191            let Some(entry) = entry else { break };192            // Drop may enqueue child roots. Never hold the pending/directory193            // borrow across typed user data destruction.194            (entry.destroy)(self, entry.identity).unwrap_or_else(|e| fatal(e));195        }196        self.records.finish().unwrap_or_else(|e| fatal(e));197    }198    pub(crate) fn make_root<M: ModuleMemory>(&self, ticket: Detached<'_, M>) -> Result<()> {199        self.same_scope(&ticket)?;200        let id = ticket.reference.identity;201        self.resolve(ticket.reference)?;202        if self.store.slot(id)?.state != backend::DETACHED {203            return Err(Error::NotDetached);204        }205        if !self.store.root().is_none() {206            return Err(Error::AlreadyInstalled);207        }208        self.store.update(id, |s| {209            s.state = backend::ROOT;210        })?;211        self.pending.borrow_mut().retain(|p| p.identity != id);212        self.store.set_root(id);213        Ok(())214    }215    fn convert<M: ModuleMemory, N: ModuleMemory>(216        &self,217        reference: ModuleRef<M>,218        root: bool,219        _old_key: &MemoryKey<M>,220        _new_key: &MemoryKey<N>,221        data_convert: impl for<'s> FnOnce(&Upgrade<'s>, M::Data) -> Result<N::Data>,222        child_convert: impl for<'s> FnOnce(&Upgrade<'s>, &M::Children, &N::Children) -> Result<()>,223    ) -> Result<ModuleRef<N>> {224        self.no_loans()?;225        let pointer = self.resolve(reference)?;226        let slot = self.store.slot(reference.identity)?;227        let binding_epoch = slot228            .binding_epoch229            .checked_add(1)230            .ok_or(Error::GenerationExhausted)?;231        let expected = if root {232            backend::ROOT233        } else {234            backend::DETACHED235        };236        if slot.state != expected {237            return Err(Error::NotDetached);238        }239        let mut guard = self.store.conversion_guard();240        self.store.update(reference.identity, |s| {241            s.state = backend::CONVERTING;242            s.pointer = 0;243        })?;244        // SAFETY: exact old physical type was admitted at binding, with no loans.245        let owned = unsafe {246            std::boxed::Box::from_raw_in(247                std::ptr::with_exposed_provenance_mut::<PhysicalModule<M>>(pointer),248                Nyxus,249            )250        };251        let PhysicalCell {252            data,253            children: old_children,254        } = *owned;255        let upgrade = Upgrade {256            scope: Scope {257                cx: self,258                marker: PhantomData,259            },260        };261        let data = data_convert(&upgrade, data.into_inner()).unwrap_or_else(|error| fatal(error));262        let children = N::Children::default();263        let cell = std::boxed::Box::new_in(264            PhysicalModule::<N> {265                data: RefCell::new(data),266                children,267            },268            Nyxus,269        );270        let (pointer, _) = std::boxed::Box::into_raw_with_allocator(cell);271        // SAFETY: only the kernel binds a closed group, inside its already272        // allocated retained cell. No public bound owner value can escape.273        unsafe { (&(*pointer).children).bind_owner(reference.identity) }274            .unwrap_or_else(|e| fatal(e));275        let physical = N::physical_contract();276        self.store277            .update(reference.identity, |s| {278                s.pointer = pointer.expose_provenance();279                s.binding_epoch = binding_epoch;280                s.semantic = N::CONTRACT;281                s.physical = physical;282            })283            .unwrap_or_else(|e| fatal(e));284        self.store.register_destructor::<N>(reference.identity);285        // Only immutable projections cross application code. Ownership changes286        // use accounted APIs; forgetting a reference cannot strand an owner.287        child_convert(&upgrade, &old_children, unsafe { &(*pointer).children })288            .unwrap_or_else(|error| fatal(error));289        drop(old_children); // all nonadopted owners enter this frame's orphan list290        self.store291            .update(reference.identity, |s| s.state = expected)292            .unwrap_or_else(|e| fatal(e));293        if !root {294            let mut pending = self.pending.borrow_mut();295            let p = pending296                .iter_mut()297                .find(|p| p.identity == reference.identity)298                .unwrap_or_else(|| fatal(Error::NotDetached));299            p.destroy = release::<N>;300        }301        guard.committed = true;302        Ok(ModuleRef {303            identity: reference.identity,304            pointer: pointer.expose_provenance(),305            binding_epoch,306            marker: PhantomData,307        })308    }309    pub(crate) fn convert_root<M: ModuleMemory, N: ModuleMemory>(310        &self,311        root: ModuleRef<M>,312        old_key: &MemoryKey<M>,313        new_key: &MemoryKey<N>,314        data: impl for<'s> FnOnce(&Upgrade<'s>, M::Data) -> Result<N::Data>,315        children: impl for<'s> FnOnce(&Upgrade<'s>, &M::Children, &N::Children) -> Result<()>,316    ) -> Result<ModuleRef<N>> {317        self.convert(root, true, old_key, new_key, data, children)318    }319}320fn release<M: ModuleMemory>(cx: &Context<'_>, id: Identity) -> Result<()> {321    cx.no_loans()?;322    let slot = cx.store.slot(id)?;323    if slot.state != backend::DETACHED || slot.semantic != M::CONTRACT {324        return Err(Error::WrongOwner);325    }326    let old = cx.store.remove(id)?;327    // SAFETY: all scoped views ended; this was admitted as exactly M. The cell328    // drops its ownership fields, enqueuing descendants through the same frame.329    unsafe { backend::destroy::<M>(old.pointer) };330    Ok(())331}332333struct Active;334impl Active {335    fn enter(cx: &Context<'_>) -> Result<Self> {336        ACTIVE.with(|active| {337            if !active.get().is_null() {338                return Err(Error::ActiveScope);339            }340            active.set((cx as *const Context<'_>).cast());341            Ok(Self)342        })343    }344}345impl Drop for Active {346    fn drop(&mut self) {347        ACTIVE.set(std::ptr::null());348    }349}350pub(crate) fn retiring<M: ModuleMemory>(owner: Identity, id: Identity) {351    if id.is_none() || DISPOSING.get() {352        return;353    }354    ACTIVE.with(|active| {355        let pointer = active.get();356        assert!(357            !pointer.is_null(),358            "owning child destroyed outside its root frame"359        );360        // SAFETY: Active pins this stack Context until frame finalization. This361        // callback cannot return a reference or run after Active is dropped.362        let cx = unsafe { &*pointer.cast::<Context<'_>>() };363        // A nested converter may already have poisoned this native store. Its364        // outer source owners now drop during unwind; quarantine them without365        // a second panic or any raw destructor dispatch.366        if cx.store.healthy() == Err(Error::Poisoned) {367            return;368        }369        cx.retire_owner::<M>(owner, id).unwrap_or_else(|e| fatal(e));370    });371}372pub fn assert_quiescent() {373    assert!(ACTIVE.get().is_null(), "live retained root frame");374}375376/// Only synchronous record retirement/conversion uses this callback. No377/// reference into this Context may escape its already-active execution frame.378pub(crate) fn with_current<R>(f: impl for<'a> FnOnce(&'a Context<'a>) -> R) -> Option<R> {379    let pointer = ACTIVE.get();380    if pointer.is_null() {381        return None;382    }383    // SAFETY: Active owns this stack Context until its callback/frame ends.384    Some(f(unsafe { &*pointer.cast::<Context<'_>>() }))385}386387mod sealed {388    pub trait Sealed {389        fn cx(&self) -> &super::Context<'_>;390    }391}392/// Read access is sealed; only the actor can create an execution capability.393pub trait Access: sealed::Sealed {}394pub(crate) fn context<'a>(access: &'a impl Access) -> &'a Context<'a> {395    sealed::Sealed::cx(access)396}397/// Shared-frame loan for trusted capability-checked retained interior cells.398/// Keep this token private beside the actual Ref/RefMut; never expose that guard399/// separately. Forgetting the complete wrapper traps frame finalization.400pub struct Loan<'a> {401    cx: &'a Context<'a>,402}403impl Drop for Loan<'_> {404    fn drop(&mut self) {405        self.cx.unloan();406    }407}408#[doc(hidden)]409pub fn loan(access: &impl Access) -> Loan<'_> {410    let cx = context(access);411    cx.loan();412    Loan { cx }413}414pub struct ReadScope<'s> {415    cx: &'s Context<'s>,416    marker: PhantomData<&'s mut &'s ()>,417}418pub struct Scope<'s> {419    pub(crate) cx: &'s Context<'s>,420    marker: PhantomData<&'s mut &'s ()>,421}422impl sealed::Sealed for ReadScope<'_> {423    fn cx(&self) -> &Context<'_> {424        self.cx425    }426}427impl sealed::Sealed for Scope<'_> {428    fn cx(&self) -> &Context<'_> {429        self.cx430    }431}432impl Access for ReadScope<'_> {}433impl Access for Scope<'_> {}434impl<'s> Scope<'s> {435    /// Lend read access within this execution frame. This does not open a436    /// nested frame or permit mutation through the returned capability.437    pub fn read_only(&self) -> ReadScope<'_> {438        ReadScope {439            cx: self.cx,440            marker: PhantomData,441        }442    }443    pub fn create<M: ModuleMemory>(444        &self,445        _key: &MemoryKey<M>,446        data: M::Data,447    ) -> Result<Detached<'s, M>> {448        let children = M::Children::default();449        let mut cell = std::boxed::Box::new_in(450            PhysicalModule::<M> {451                data: RefCell::new(data),452                children,453            },454            Nyxus,455        );456        let address = (&mut *cell as *mut PhysicalModule<M>).expose_provenance();457        // Keep typed ownership on every recoverable registration error.458        let id = self.cx.store.insert::<M>(address)?;459        let (pointer, _) = std::boxed::Box::into_raw_with_allocator(cell);460        self.cx.pending.borrow_mut().push(Pending {461            identity: id,462            destroy: release::<M>,463        });464        // SAFETY: freshly allocated cell is exclusively constructed here. Any465        // postregistration invariant failure traps rather than returning Err.466        unsafe { (&(*pointer).children).bind_owner(id) }.unwrap_or_else(|e| fatal(e));467        Ok(Detached {468            reference: ModuleRef {469                identity: id,470                pointer: pointer.expose_provenance(),471                binding_epoch: 1,472                marker: PhantomData,473            },474            scope: (self.cx as *const Context<'_>).cast(),475            marker: PhantomData,476        })477    }478}479480/// A scope-owned orphan ticket. It is not an owning Rc or a durable owner. The481/// frame retires an unconsumed identity even if this ticket is deliberately forgotten.482pub struct Detached<'s, M: ModuleMemory> {483    pub(crate) reference: ModuleRef<M>,484    scope: *const (),485    marker: PhantomData<&'s mut &'s ()>,486}487impl<M: ModuleMemory> Detached<'_, M> {488    pub fn reference(&self) -> ModuleRef<M> {489        self.reference490    }491}492493pub struct Upgrade<'s> {494    scope: Scope<'s>,495}496impl<'s> Upgrade<'s> {497    pub fn scope(&self) -> &Scope<'s> {498        &self.scope499    }500    pub fn convert<M: ModuleMemory, N: ModuleMemory>(501        &self,502        ticket: Detached<'s, M>,503        old_key: &MemoryKey<M>,504        new_key: &MemoryKey<N>,505        data: impl for<'a> FnOnce(&Upgrade<'a>, M::Data) -> Result<N::Data>,506        children: impl for<'a> FnOnce(&Upgrade<'a>, &M::Children, &N::Children) -> Result<()>,507    ) -> Result<Detached<'s, N>> {508        self.scope.cx.same_scope(&ticket)?;509        let reference =510            self.scope511                .cx512                .convert(ticket.reference, false, old_key, new_key, data, children)?;513        Ok(Detached {514            reference,515            scope: ticket.scope,516            marker: PhantomData,517        })518    }519}520521pub(crate) fn execute_read<R>(522    store: &Store,523    f: impl for<'s> FnOnce(&ReadScope<'s>) -> Result<R>,524) -> Result<R> {525    let cx = Context::new(store, true);526    let active = Active::enter(&cx)?;527    let result = f(&ReadScope {528        cx: &cx,529        marker: PhantomData,530    });531    cx.no_loans().unwrap_or_else(|e| fatal(e));532    drop(active);533    result534}535pub(crate) fn execute_write<R>(536    store: &Store,537    f: impl for<'s> FnOnce(&Scope<'s>) -> Result<R>,538) -> Result<R> {539    let cx = Context::new(store, false);540    let active = Active::enter(&cx)?;541    let result = f(&Scope {542        cx: &cx,543        marker: PhantomData,544    });545    cx.finish();546    drop(active);547    result548}