lib.rs

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

1//! Direct typed module tree over Nyxus, with optional Hylix records.2//! Store owns module lifetimes, not each value stored in a native collection.3//!4//! Only data receives a mutable Rust reference. Child ownership lives behind5//! private, accounted attachment slots/maps. Services hold nonowning identities.6#![feature(allocator_ext, btreemap_alloc, rustc_attrs)]7#![allow(internal_features)]8#![deny(unsafe_op_in_unsafe_fn)]910mod backend;11pub mod binding;12mod catalog;13mod children;14pub mod hylix;15mod module_memory;16mod scope;1718pub use backend::{PhysicalDirectory, Store};19pub use catalog::{Catalog, catalog};20pub use cdk_rsx_engine_nyxus::{Nyxus, NyxusData};21/// Generate one owner-private frozen memory version.22///23/// `#[memory(owner = crate::inventory)] pub struct Memory;` uses Nyxus and local Data,24/// no children, module path plus marker name as identity, and the declaration's25/// source file.26/// Add `children = Children` for owning attachments, `data = ()` for a root,27/// or `hylix` to store Data through the Hylix engine record adapter.28/// Additional interpretation sources and compiled configuration dependencies29/// use `sources = [include_str!(...)]` and `dependencies = [digest, ...]`.30/// Source capture does not infer arbitrary Ord/Drop/codec equivalence or active31/// cfg values. Those remain explicit semantic authoring obligations.32/// Generic unit markers support type/const parameters, defaults and where33/// clauses, and require nonempty explicit semantic dependencies. Their KEY is34/// an owner-private associated constant (`Memory::<T>::KEY`). Concrete markers35/// can select `key = NAME` or `key = associated` when a version has several36/// owners. Scope/view lifetimes remain outside static memory declarations.37pub use cdk_rsx_store_derive::memory;38pub use children::{ChildMap, ChildSlot, ModuleChildren};3940/// Implementation details used by generated memory declarations.41#[doc(hidden)]42pub mod __private {43    pub use crate::module_memory::MODULE_MEMORY_POLICY;44    pub use cdk_rsx_engine_hylix::{Codec, HYLIX_POLICY};45    pub use cdk_rsx_memory_abi::{46        CatalogGroup, CatalogSpec, Declaration, Physical, physical, semantic_contract,47    };48    #[cfg(target_family = "wasm")]49    pub use cdk_rsx_memory_abi::{read_saved_digest, write_saved_digest};50}51pub use scope::{Access, Detached, Loan, ReadScope, Scope, Upgrade, loan};5253use std::{54    cell::{Ref, RefCell, RefMut},55    marker::PhantomData,56    ops::{Deref, DerefMut},57};5859pub type Result<T> = std::result::Result<T, Error>;60#[derive(Clone, Copy, Debug, PartialEq, Eq)]61pub enum Error {62    Arena,63    AlreadyInstalled,64    NotInstalled,65    Poisoned,66    ActiveScope,67    WrongNamespace,68    Stale,69    WrongContract,70    WrongPhysical,71    Borrowed,72    NotDetached,73    WrongOwner,74    Cycle,75    GenerationExhausted,76    TooManyModules,77    Conversion,78    UnboundChildren,79    Hylix,80}8182/// The complete owner-private version contract. Implement through a version file.83///84/// # Safety85/// Data must be a recursively admitted retained representation. Children must86/// contain all owning module attachments, with no aliases or hidden owners.87/// `physical_contract` must certify the complete `PhysicalModule<Self>` layout,88/// including private container structures, for this exact target/compiler ABI.89pub unsafe trait ModuleMemory: Sized + 'static {90    type Data: NyxusData;91    type Children: ModuleChildren;92    const CONTRACT: [u8; 32];93    fn physical_contract() -> [u8; 32];94}9596/// A module owner's unforgeable-in-safe-code permission to view its records.97/// This zero-sized key stays private inside the owner's memory folder.98/// ```compile_fail99/// use cdk_rsx_store::{MemoryKey, ModuleMemory};100/// fn steal_owner_key<M: ModuleMemory>() -> MemoryKey<M> { MemoryKey::new() }101/// ```102pub struct MemoryKey<M: ModuleMemory>(PhantomData<fn() -> M>);103impl<M: ModuleMemory> MemoryKey<M> {104    /// # Safety105    /// Only the memory owner may construct or expose this key. Keep it private;106    /// exposing it delegates access to the owner's otherwise opaque record.107    pub const unsafe fn new() -> Self {108        Self(PhantomData)109    }110}111112/// Opaque stable identity. It carries no ownership and cannot be deserialized.113#[repr(C)]114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]115pub struct Identity {116    namespace: u64,117    slot: u64,118    generation: u64,119}120impl Identity {121    const NONE: Self = Self {122        namespace: 0,123        slot: 0,124        generation: 0,125    };126    fn is_none(self) -> bool {127        self.generation == 0128    }129}130131/// Reflection root for a module's physical retained representation. Fields stay132/// private so neither a parent nor a service can move an ownership container out.133#[repr(C)]134pub struct PhysicalCell<D: NyxusData, C: ModuleChildren> {135    data: RefCell<D>,136    children: C,137}138/// This alias names the actual allocated cell. The concrete carrier avoids139/// unresolved associated projections in the compiler's private-layout evidence.140pub type PhysicalModule<M> = PhysicalCell<<M as ModuleMemory>::Data, <M as ModuleMemory>::Children>;141142/// A nonowning process-local service binding. Binding checks the full physical143/// contract once; each scoped access checks identity/generation/current pointer.144/// Cloning this capability never pins persistent state.145pub struct ModuleRef<M: ModuleMemory> {146    identity: Identity,147    pointer: usize,148    binding_epoch: u64,149    marker: PhantomData<fn() -> M>,150}151impl<M: ModuleMemory> Copy for ModuleRef<M> {}152impl<M: ModuleMemory> Clone for ModuleRef<M> {153    fn clone(&self) -> Self {154        *self155    }156}157impl<M: ModuleMemory> ModuleRef<M> {158    pub fn identity(&self) -> Identity {159        self.identity160    }161    pub fn read<'a>(162        &self,163        access: &'a impl Access,164        _key: &MemoryKey<M>,165    ) -> Result<Data<'a, M::Data>> {166        let cx = scope::context(access);167        let cell = cx.resolve::<M>(*self)?;168        // SAFETY: resolve checks the live slot before constructing this pointer;169        // retirement waits until the shared frame ends, and the guard cannot escape.170        let cell = unsafe { &*(std::ptr::with_exposed_provenance::<PhysicalModule<M>>(cell)) };171        let value = if cx.read_only() {172            // SAFETY: this Context exposes only ReadScope, and Active rejects173            // every nested root frame, including those of another Store. No174            // Scope or conversion can coexist with these shared references.175            // The ordinary live-loan fence still prevents frame completion176            // with a forgotten Data guard. Check the existing RefCell state so177            // even a preexisting mutable loan rejects before exposing Data.178            DataValue::ReadOnly(179                unsafe { cell.data.try_borrow_unguarded() }.map_err(|_| Error::Borrowed)?,180            )181        } else {182            // Read access in a write frame must exclude later writes through183            // another service binding, so it retains the dynamic borrow.184            DataValue::Borrowed(cell.data.try_borrow().map_err(|_| Error::Borrowed)?)185        };186        cx.loan();187        Ok(Data { value, cx })188    }189    pub fn write<'a>(190        &self,191        access: &'a Scope<'_>,192        _key: &MemoryKey<M>,193    ) -> Result<DataMut<'a, M::Data>> {194        let cx = access.cx;195        let cell = cx.resolve::<M>(*self)?;196        // SAFETY: same frame/lifetime invariant as read. Scope is write-only.197        let cell = unsafe { &*(std::ptr::with_exposed_provenance::<PhysicalModule<M>>(cell)) };198        let value = cell.data.try_borrow_mut().map_err(|_| Error::Borrowed)?;199        cx.loan();200        Ok(DataMut { value, cx })201    }202    pub fn children<'a>(203        &self,204        access: &'a impl Access,205        _key: &MemoryKey<M>,206    ) -> Result<Children<'a, M::Children>> {207        let cx = scope::context(access);208        let cell = cx.resolve::<M>(*self)?;209        // SAFETY: the cell lives to frame end. Only an immutable projection is210        // exposed; every ownership mutation additionally needs a Scope.211        let value =212            unsafe { &(*(std::ptr::with_exposed_provenance::<PhysicalModule<M>>(cell))).children };213        cx.loan();214        Ok(Children { value, cx })215    }216}217218pub struct Data<'a, T> {219    value: DataValue<'a, T>,220    cx: &'a scope::Context<'a>,221}222enum DataValue<'a, T> {223    ReadOnly(&'a T),224    Borrowed(Ref<'a, T>),225}226impl<T> Deref for Data<'_, T> {227    type Target = T;228    fn deref(&self) -> &T {229        match &self.value {230            DataValue::ReadOnly(value) => value,231            DataValue::Borrowed(value) => value,232        }233    }234}235impl<T> Drop for Data<'_, T> {236    fn drop(&mut self) {237        self.cx.unloan();238    }239}240pub struct DataMut<'a, T> {241    value: RefMut<'a, T>,242    cx: &'a scope::Context<'a>,243}244impl<T> Deref for DataMut<'_, T> {245    type Target = T;246    fn deref(&self) -> &T {247        &self.value248    }249}250impl<T> DerefMut for DataMut<'_, T> {251    fn deref_mut(&mut self) -> &mut T {252        &mut self.value253    }254}255impl<T> Drop for DataMut<'_, T> {256    fn drop(&mut self) {257        self.cx.unloan();258    }259}260/// Owning groups have no mutable projection, even in an update:261/// ```compile_fail262/// use cdk_rsx_store::*;263/// fn move_owners<M: ModuleMemory>(actor: &Actor<M>, key: &MemoryKey<M>) {264///     actor.with(|cx,root| {265///         let mut children = root.children(cx,key)?;266///         let _stolen = std::mem::take(&mut *children);267///         Ok(())268///     }).unwrap();269/// }270/// ```271pub struct Children<'a, T> {272    value: &'a T,273    cx: &'a scope::Context<'a>,274}275impl<T> Deref for Children<'_, T> {276    type Target = T;277    fn deref(&self) -> &T {278        self.value279    }280}281impl<T> Drop for Children<'_, T> {282    fn drop(&mut self) {283        self.cx.unloan();284    }285}286287/// A typed active-root service owner; the retained store owns the actual root.288/// Dropping/rebuilding Actor changes no persistent reference counts.289/// Read-only access cannot mutate Data or child ownership, and typed guards290/// cannot leave the shared root frame:291/// ```compile_fail292/// use cdk_rsx_store::*;293/// fn mutate_query<M: ModuleMemory>(actor: &Actor<M>, key: &MemoryKey<M>) {294///     actor.read(|cx,root| {295///         let mut data = root.read(cx,key)?;296///         let _write = &mut *data;297///         Ok(())298///     }).unwrap();299/// }300/// ```301/// ```compile_fail302/// use cdk_rsx_store::*;303/// fn query_detach<M: ModuleMemory>(slot: &ChildSlot<M>, cx: &ReadScope<'_>) {304///     slot.clear(cx).unwrap();305/// }306/// ```307/// ```compile_fail308/// use cdk_rsx_store::*;309/// fn escape<M: ModuleMemory>(actor: &Actor<M>, key: &MemoryKey<M>) {310///     let _escaped = actor.read(|cx,root| root.read(cx,key));311/// }312/// ```313/// ```compile_fail314/// use cdk_rsx_store::*;315/// fn delayed_access<M: ModuleMemory>(actor: &Actor<M>, key: &MemoryKey<M>) {316///     let _future = actor.read(|cx,root| Ok(async move {317///         let data = root.read(cx,key).unwrap();318///         std::future::pending::<()>().await;319///         drop(data);320///     }));321/// }322/// ```323pub struct Actor<M: ModuleMemory> {324    store: Store,325    root: ModuleRef<M>,326}327impl<M: ModuleMemory> Actor<M> {328    pub fn root(&self) -> ModuleRef<M> {329        self.root330    }331    pub fn store(&self) -> &Store {332        &self.store333    }334    pub fn read<R>(335        &self,336        f: impl for<'s> FnOnce(&ReadScope<'s>, ModuleRef<M>) -> Result<R>,337    ) -> Result<R> {338        self.store.read(|cx| f(cx, self.root))339    }340    pub fn with<R>(341        &self,342        f: impl for<'s> FnOnce(&Scope<'s>, ModuleRef<M>) -> Result<R>,343    ) -> Result<R> {344        self.store.with(|cx| f(cx, self.root))345    }346    pub fn upgrade<N: ModuleMemory>(347        self,348        old_key: &MemoryKey<M>,349        new_key: &MemoryKey<N>,350        data: impl for<'s> FnOnce(&Upgrade<'s>, M::Data) -> Result<N::Data>,351        children: impl for<'s> FnOnce(&Upgrade<'s>, &M::Children, &N::Children) -> Result<()>,352    ) -> Result<Actor<N>> {353        let root = self354            .store355            .upgrade_root(self.root, old_key, new_key, data, children)?;356        Ok(Actor {357            store: self.store,358            root,359        })360    }361}362363/// No live root frame or typed view may cross a reset boundary.364pub fn assert_quiescent() {365    scope::assert_quiescent();366}367368pub(crate) fn fatal(error: Error) -> ! {369    panic!("Store invariant: {error:?}")370}371372/// Concise named ownership fields without giving callers mutable projections.373/// Individual fields may be ChildSlot, ChildMap, (), or another generated group.374#[macro_export]375macro_rules! module_children {376    ($(#[$attr:meta])* $vis:vis struct $name:ident { $($fvis:vis $field:ident : $ty:ty),* $(,)? }) => {377        $(#[$attr])* $vis struct $name { $($fvis $field: $ty),* }378        impl Default for $name { fn default() -> Self { Self { $($field: Default::default()),* } } }379        // SAFETY: the generated group delegates every attachment to its closed380        // field container; it exposes no mutable ownership projection.381        unsafe impl $crate::ModuleChildren for $name {382            unsafe fn bind_owner(&self, owner: $crate::Identity) -> $crate::Result<()> {383                $(unsafe { $crate::ModuleChildren::bind_owner(&self.$field, owner)?; })* Ok(())384            }385        }386        unsafe impl $crate::__private::CatalogGroup for $name {}387    }388}389390#[cfg(test)]391mod tests;392393pub const MODULE_POLICY: [u8; 32] = cdk_rsx_memory_abi::semantic_contract(394    "cdk-rsx-store-module-policy-v3",395    &[],396    &[397        cdk_rsx_store_derive::__package_policy!(),398        cdk_rsx_source_policy::source_policy!(399            "../Cargo.toml",400            "lib.rs",401            "backend.rs",402            "scope.rs",403            "children.rs",404            "catalog.rs",405            "binding.rs",406            "hylix.rs"407        ),408        cdk_rsx_platform::profile::__PROFILE_POLICY,409        // Native Store does not bind the executor's Wasm root control.410        #[cfg(target_family = "wasm")]411        cdk_rsx_executor::__ROOT_POLICY,412    ],413);