backend.rs

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

backend.rs554 lines← SDK documentation
1use crate::*;2use std::boxed::Box as NativeBox;3use std::cell::{OnceCell, RefCell as HylixCell};4#[cfg(target_family = "wasm")]5use std::rc::Rc as HylixRc;6// Publish once for every alias; an absent provider needs no dynamic loan.7type HylixStorage = OnceCell<HylixCell<NativeBox<dyn cdk_rsx_engine_hylix::Storage>>>;8#[cfg(target_family = "wasm")]9use std::ptr::NonNull;10#[cfg(not(target_family = "wasm"))]11use std::{12    cell::{Cell, RefCell},13    collections::BTreeMap,14    rc::Rc,15};1617pub(crate) const VACANT: u64 = 0;18pub(crate) const DETACHED: u64 = 1;19pub(crate) const ATTACHED: u64 = 2;20pub(crate) const ROOT: u64 = 3;21pub(crate) const CONVERTING: u64 = 4;2223#[repr(C)]24#[derive(Clone, Copy)]25#[cfg_attr(test, derive(Debug, PartialEq, Eq))]26pub(crate) struct Slot {27    pub generation: u64,28    // A live module address, or the next one-based free index while VACANT.29    pub pointer: usize,30    pub binding_epoch: u64,31    pub semantic: [u8; 32],32    pub physical: [u8; 32],33    pub parent: Identity,34    pub state: u64,35}3637/// Allocator-backed directory metadata. This index does not own each module;38/// only the one root and accounted child containers do. It stores no code.39#[repr(C)]40pub struct PhysicalDirectory {41    namespace: u64,42    next_generation: u64,43    // Zero ends the list. The u32 slot-count bound leaves slot+1 representable44    // on every target, including when its links occupy a vacant pointer word.45    free_head: u32,46    // make_root resolves its same-scope ticket before publishing the root, so47    // its namespace is always this directory's. Keep its exact slot/generation.48    root_slot: u64,49    root_generation: u64,50    slots: std::vec::Vec<Slot, Nyxus>,51}52// Keep the directory within its original 64-byte Nyxus allocation budget.53#[cfg(target_pointer_width = "64")]54const _: () = assert!(std::mem::size_of::<PhysicalDirectory>() <= 64);5556impl PhysicalDirectory {57    fn empty(namespace: u64) -> Self {58        Self {59            namespace,60            next_generation: 0,61            free_head: 0,62            root_slot: 0,63            root_generation: 0,64            slots: std::vec::Vec::new_in(Nyxus),65        }66    }67    fn root(&self) -> Identity {68        if self.root_generation == 0 {69            Identity::NONE70        } else {71            Identity {72                namespace: self.namespace,73                slot: self.root_slot,74                generation: self.root_generation,75            }76        }77    }78}7980#[cfg(not(target_family = "wasm"))]81struct Core {82    poisoned: Cell<bool>,83    directory: RefCell<PhysicalDirectory>,84    // Native test-host dispatch only. Never persisted or present in Wasm.85    destructors: RefCell<BTreeMap<u64, unsafe fn(usize)>>,86    // Transient byte-provider authority. Only module Block descriptors persist.87    hylix: HylixStorage,88}89#[cfg(not(target_family = "wasm"))]90impl Drop for Core {91    fn drop(&mut self) {92        // Native has no IC rollback. A partial converter is quarantined and its93        // raw cells deliberately leak rather than dispatch a guessed destructor.94        if self.poisoned.get() {95            return;96        }97        let directory = self.directory.get_mut();98        let destructors = self.destructors.get_mut();99        let hylix = self.hylix.get_mut();100        let dispose = || {101            let _dispose = scope::Disposing::enter();102            for (slot, destroy) in destructors.iter() {103                let entry = directory.slots[*slot as usize];104                if entry.state != VACANT && entry.pointer != 0 {105                    // SAFETY: each native dispatch was registered by that cell's106                    // actual type, and ordinary retirement removes it exactly once.107                    unsafe { destroy(entry.pointer) };108                }109            }110        };111        if let Some(storage) = hylix {112            cdk_rsx_engine_hylix::using(storage.get_mut().as_mut(), || {113                dispose();114                Ok(())115            })116            .unwrap_or_else(|_| fatal(Error::Hylix));117        } else {118            dispose();119        }120    }121}122123/// Native tests own an store through Rc. Wasm has one guarded retained store;124/// its transient Store value owns no retained cell and can be discarded freely.125#[derive(Clone)]126pub struct Store {127    #[cfg(not(target_family = "wasm"))]128    core: Rc<Core>,129    // Admission fixes this address for the opening. The Directory Box never130    // moves or retires; growing its slots Vec replaces only that Vec's buffer.131    #[cfg(target_family = "wasm")]132    directory: NonNull<PhysicalDirectory>,133    #[cfg(target_family = "wasm")]134    hylix: HylixRc<HylixStorage>,135}136impl Default for Store {137    fn default() -> Self {138        #[cfg(not(target_family = "wasm"))]139        {140            use std::sync::atomic::{AtomicU64, Ordering};141            static NEXT: AtomicU64 = AtomicU64::new(1);142            let namespace = NEXT.fetch_add(1, Ordering::Relaxed);143            assert_ne!(namespace, 0, "native store namespace exhausted");144            Self {145                core: Rc::new(Core {146                    poisoned: Cell::new(false),147                    directory: RefCell::new(PhysicalDirectory::empty(namespace)),148                    destructors: RefCell::new(BTreeMap::new()),149                    hylix: OnceCell::new(),150                }),151            }152        }153        #[cfg(target_family = "wasm")]154        {155            panic!("use guarded Store::initialize/reopen on Wasm")156        }157    }158}159impl Store {160    #[cfg(target_family = "wasm")]161    pub fn initialize() -> Result<Self> {162        cdk_rsx_engine_nyxus::initialize().map_err(|_| Error::Arena)?;163        let directory = wasm::initialize()?;164        Ok(Self {165            directory,166            hylix: HylixRc::new(OnceCell::new()),167        })168    }169    /// # Safety170    /// The canonical startup guard must already have accepted platform, arena,171    /// directory and admitted native data ABIs before reset or allocation.172    #[cfg(target_family = "wasm")]173    pub unsafe fn reopen() -> Result<Self> {174        unsafe { cdk_rsx_engine_nyxus::reopen() }.map_err(|_| Error::Arena)?;175        let directory = unsafe { wasm::reopen() }?;176        Ok(Self {177            directory,178            hylix: HylixRc::new(OnceCell::new()),179        })180    }181    /// Attach this Store's exclusive Hylix byte-provider authority before182    /// opening/installing services. Recreate it explicitly after an upgrade;183    /// only fixed module allocation descriptors are retained across teardown.184    pub fn with_hylix<S: cdk_rsx_engine_hylix::Storage + 'static>(185        self,186        storage: S,187    ) -> Result<Self> {188        self.healthy()?;189        scope::assert_quiescent();190        self.hylix()191            .set(HylixCell::new(NativeBox::new(storage)))192            .map_err(|_| Error::AlreadyInstalled)?;193        Ok(self)194    }195    fn hylix(&self) -> &HylixStorage {196        #[cfg(not(target_family = "wasm"))]197        {198            &self.core.hylix199        }200        #[cfg(target_family = "wasm")]201        {202            &self.hylix203        }204    }205    fn hylix_read<R>(&self, f: impl FnOnce() -> Result<R>) -> Result<R> {206        let Some(storage) = self.hylix().get() else {207            return f();208        };209        let storage = storage.try_borrow().map_err(|_| Error::Borrowed)?;210        cdk_rsx_engine_hylix::using_read(storage.as_ref(), || Ok(f())).map_err(|_| Error::Hylix)?211    }212    fn hylix_write<R>(&self, f: impl FnOnce() -> Result<R>) -> Result<R> {213        let Some(storage) = self.hylix().get() else {214            return f();215        };216        let mut storage = storage.try_borrow_mut().map_err(|_| Error::Borrowed)?;217        cdk_rsx_engine_hylix::using(storage.as_mut(), || Ok(f())).map_err(|_| Error::Hylix)?218    }219    pub(crate) fn healthy(&self) -> Result<()> {220        #[cfg(not(target_family = "wasm"))]221        if self.core.poisoned.get() {222            return Err(Error::Poisoned);223        }224        Ok(())225    }226    pub(crate) fn conversion_guard(&self) -> ConversionGuard<'_> {227        ConversionGuard {228            store: self,229            committed: false,230        }231    }232    #[cfg(test)]233    pub(crate) fn exhaust_generation(&self) {234        self.directory(|d| d.next_generation = u64::MAX);235    }236    #[cfg(test)]237    pub(crate) fn directory_snapshot(&self) -> (u64, u64, Identity, std::vec::Vec<Slot>, u32) {238        self.directory(|d| {239            (240                d.namespace,241                d.next_generation,242                d.root(),243                d.slots.to_vec(),244                d.free_head,245            )246        })247    }248    pub(crate) fn slots_len(&self) -> usize {249        self.directory(|d| d.slots.len())250    }251    pub(crate) fn directory<R>(&self, f: impl FnOnce(&mut PhysicalDirectory) -> R) -> R {252        #[cfg(not(target_family = "wasm"))]253        {254            f(&mut self.core.directory.borrow_mut())255        }256        #[cfg(target_family = "wasm")]257        {258            // SAFETY: only internal short closures use this mutable reference;259            // none invoke user code or preserve a directory reference across it.260            // The private Store field exists only after guarded admission and261            // stays pinned even when individual module cells are converted.262            unsafe { f(&mut *self.directory.as_ptr()) }263        }264    }265    pub(crate) fn root(&self) -> Identity {266        self.directory(|d| d.root())267    }268    pub fn root_contract(&self) -> Result<[u8; 32]> {269        self.healthy()?;270        let root = self.root();271        if root.is_none() {272            return Err(Error::NotInstalled);273        }274        Ok(self.slot(root)?.semantic)275    }276    pub(crate) fn set_root(&self, identity: Identity) {277        self.directory(|d| {278            d.root_slot = identity.slot;279            d.root_generation = identity.generation;280        });281    }282    pub(crate) fn slot(&self, id: Identity) -> Result<Slot> {283        self.healthy()?;284        self.directory(|d| {285            if id.namespace != d.namespace {286                return Err(Error::WrongNamespace);287            }288            let slot = d.slots.get(id.slot as usize).copied().ok_or(Error::Stale)?;289            if slot.generation != id.generation || slot.state == VACANT {290                return Err(Error::Stale);291            }292            Ok(slot)293        })294    }295    /// Resolve a previously admitted binding without copying its cold contracts296    /// and ownership metadata out of the directory. No slot reference escapes.297    #[inline]298    pub(crate) fn resolve_bound(299        &self,300        id: Identity,301        pointer: usize,302        binding_epoch: u64,303    ) -> Result<usize> {304        self.healthy()?;305        self.directory(|d| {306            if id.namespace != d.namespace {307                return Err(Error::WrongNamespace);308            }309            let slot = d.slots.get(id.slot as usize).ok_or(Error::Stale)?;310            if slot.generation != id.generation || slot.state == VACANT {311                return Err(Error::Stale);312            }313            if slot.state == CONVERTING {314                return Err(Error::Borrowed);315            }316            if slot.pointer != pointer || slot.binding_epoch != binding_epoch {317                return Err(Error::Stale);318            }319            Ok(slot.pointer)320        })321    }322    pub(crate) fn update(&self, id: Identity, f: impl FnOnce(&mut Slot)) -> Result<()> {323        self.healthy()?;324        self.directory(|d| {325            if id.namespace != d.namespace {326                return Err(Error::WrongNamespace);327            }328            let slot = d.slots.get_mut(id.slot as usize).ok_or(Error::Stale)?;329            if slot.generation != id.generation || slot.state == VACANT {330                return Err(Error::Stale);331            }332            f(slot);333            Ok(())334        })335    }336    pub(crate) fn insert<M: ModuleMemory>(&self, pointer: usize) -> Result<Identity> {337        self.healthy()?;338        let physical = M::physical_contract();339        let id = self.directory(|d| {340            let generation = d341                .next_generation342                .checked_add(1)343                .ok_or(Error::GenerationExhausted)?;344            let entry = Slot {345                generation,346                pointer,347                binding_epoch: 1,348                semantic: M::CONTRACT,349                physical,350                parent: Identity::NONE,351                state: DETACHED,352            };353            let slot = if d.free_head != 0 {354                let index = d.free_head as usize - 1;355                d.free_head = d.slots[index].pointer as u32;356                d.slots[index] = entry;357                index358            } else {359                if d.slots.len() == u32::MAX as usize {360                    return Err(Error::TooManyModules);361                }362                let index = d.slots.len();363                d.slots.push(entry);364                index365            };366            d.next_generation = generation;367            Ok(Identity {368                namespace: d.namespace,369                slot: slot as u64,370                generation,371            })372        })?;373        self.register_destructor::<M>(id);374        Ok(id)375    }376    pub(crate) fn register_destructor<M: ModuleMemory>(&self, id: Identity) {377        #[cfg(not(target_family = "wasm"))]378        self.core379            .destructors380            .borrow_mut()381            .insert(id.slot, destroy::<M>);382        #[cfg(target_family = "wasm")]383        let _ = id;384    }385    pub(crate) fn remove(&self, id: Identity) -> Result<Slot> {386        self.healthy()?;387        let old = self.directory(|d| {388            if id.namespace != d.namespace {389                return Err(Error::WrongNamespace);390            }391            let slot = d.slots.get_mut(id.slot as usize).ok_or(Error::Stale)?;392            if slot.generation != id.generation || slot.state == VACANT {393                return Err(Error::Stale);394            }395            let old = *slot;396            slot.pointer = d.free_head as usize;397            slot.parent = Identity::NONE;398            slot.state = VACANT;399            d.free_head = id.slot as u32 + 1;400            Ok(old)401        })?;402        #[cfg(not(target_family = "wasm"))]403        self.core.destructors.borrow_mut().remove(&id.slot);404        Ok(old)405    }406    pub(crate) fn bind<M: ModuleMemory>(&self, id: Identity) -> Result<ModuleRef<M>> {407        let slot = self.slot(id)?;408        if slot.semantic != M::CONTRACT {409            return Err(Error::WrongContract);410        }411        if slot.physical != M::physical_contract() {412            return Err(Error::WrongPhysical);413        }414        if slot.state == CONVERTING {415            return Err(Error::Borrowed);416        }417        let end = slot418            .pointer419            .checked_add(std::mem::size_of::<PhysicalModule<M>>())420            .ok_or(Error::WrongPhysical)?;421        if !slot422            .pointer423            .is_multiple_of(std::mem::align_of::<PhysicalModule<M>>())424            || !cdk_rsx_engine_nyxus::contains(slot.pointer..end)425        {426            return Err(Error::WrongPhysical);427        }428        Ok(ModuleRef {429            identity: id,430            pointer: slot.pointer,431            binding_epoch: slot.binding_epoch,432            marker: PhantomData,433        })434    }435    pub fn open<M: ModuleMemory>(&self, _key: &MemoryKey<M>) -> Result<Actor<M>> {436        self.healthy()?;437        let id = self.root();438        if id.is_none() {439            return Err(Error::NotInstalled);440        }441        let root = self.bind::<M>(id)?;442        Ok(Actor {443            store: self.clone(),444            root,445        })446    }447    pub fn install<M: ModuleMemory>(448        &self,449        _key: &MemoryKey<M>,450        construct: impl for<'s> FnOnce(&Scope<'s>) -> Result<Detached<'s, M>>,451    ) -> Result<Actor<M>> {452        self.healthy()?;453        if !self.root().is_none() {454            return Err(Error::AlreadyInstalled);455        }456        let root = self.with(|cx| {457            let ticket = construct(cx)?;458            let reference = ticket.reference();459            cx.cx.make_root(ticket)?;460            Ok(reference)461        })?;462        Ok(Actor {463            store: self.clone(),464            root,465        })466    }467    pub fn read<R>(&self, f: impl for<'s> FnOnce(&ReadScope<'s>) -> Result<R>) -> Result<R> {468        self.healthy()?;469        self.hylix_read(|| scope::execute_read(self, f))470    }471    pub fn with<R>(&self, f: impl for<'s> FnOnce(&Scope<'s>) -> Result<R>) -> Result<R> {472        #[cfg(target_family = "wasm")]473        assert!(474            !cdk_rsx_executor::is_query_context(),475            "query cannot enter retained write frame"476        );477        self.healthy()?;478        self.hylix_write(|| scope::execute_write(self, f))479    }480    pub(crate) fn upgrade_root<M: ModuleMemory, N: ModuleMemory>(481        &self,482        root: ModuleRef<M>,483        old_key: &MemoryKey<M>,484        new_key: &MemoryKey<N>,485        data: impl for<'s> FnOnce(&Upgrade<'s>, M::Data) -> Result<N::Data>,486        children: impl for<'s> FnOnce(&Upgrade<'s>, &M::Children, &N::Children) -> Result<()>,487    ) -> Result<ModuleRef<N>> {488        if self.root() != root.identity {489            return Err(Error::WrongOwner);490        }491        self.with(|cx| cx.cx.convert_root(root, old_key, new_key, data, children))492    }493}494495pub(crate) struct ConversionGuard<'a> {496    store: &'a Store,497    pub committed: bool,498}499impl Drop for ConversionGuard<'_> {500    fn drop(&mut self) {501        if !self.committed {502            #[cfg(not(target_family = "wasm"))]503            self.store.core.poisoned.set(true);504        }505    }506}507508pub(crate) unsafe fn destroy<M: ModuleMemory>(pointer: usize) {509    // SAFETY: caller removed the exact matching slot with no live loans. The510    // retained allocator matches the original typed allocation.511    unsafe {512        drop(NativeBox::from_raw_in(513            std::ptr::with_exposed_provenance_mut::<PhysicalModule<M>>(pointer),514            Nyxus,515        ));516    }517}518519#[cfg(target_family = "wasm")]520mod wasm {521    use super::*;522    const BASE: usize = cdk_rsx_platform::profile::BOOTSTRAP_BASE + 4096;523    const MAGIC: u64 = u64::from_le_bytes(*b"SRTMOD02");524    pub(super) fn initialize() -> Result<NonNull<PhysicalDirectory>> {525        if unsafe { (BASE as *const u64).read() } != 0 {526            return Err(Error::AlreadyInstalled);527        }528        let directory = NativeBox::new_in(PhysicalDirectory::empty(1), Nyxus);529        let (pointer, _) = NativeBox::into_raw_with_allocator(directory);530        unsafe {531            (BASE as *mut u64).write(MAGIC);532            ((BASE + 8) as *mut usize).write(pointer.expose_provenance());533        }534        Ok(NonNull::new(pointer).expect("allocated directory is nonnull"))535    }536    pub(super) unsafe fn reopen() -> Result<NonNull<PhysicalDirectory>> {537        if unsafe { (BASE as *const u64).read() } != MAGIC {538            return Err(Error::WrongPhysical);539        }540        let pointer = unsafe { ((BASE + 8) as *const usize).read() };541        let end = pointer542            .checked_add(std::mem::size_of::<PhysicalDirectory>())543            .ok_or(Error::WrongPhysical)?;544        if !pointer.is_multiple_of(std::mem::align_of::<PhysicalDirectory>())545            || !cdk_rsx_engine_nyxus::contains(pointer..end)546        {547            return Err(Error::WrongPhysical);548        }549        NonNull::new(std::ptr::with_exposed_provenance_mut::<PhysicalDirectory>(550            pointer,551        ))552        .ok_or(Error::WrongPhysical)553    }554}