hylix.rs

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

hylix.rs491 lines← SDK documentation
1//! Hylix records in the ordinary Store ownership tree.2//!3//! A module's retained cell contains only `Record`'s fixed allocation identity.4//! Scalar fields and fixed-size collection handles are encoded in stable memory.5//! The existing directory and child attachments remain retained kernel metadata;6//! this is not a heap-independent root or a second persistence system.7//!8//! One actor frame decodes each accessed module record once and publishes dirty9//! records before the frame ends. Guards retain the ordinary module borrow.10//! Collection handles have inert normal Drop: replacing a field must11//! explicitly retire the displaced owner or move it into another durable owner.12//! `HylixValue::retire` runs only when the actual module record is retired.1314use crate::{Access, Data, DataMut, Detached, Error, MemoryKey, ModuleRef, Result, Scope};15use cdk_rsx_engine_hylix::{16    Block, Codec, Field, HylixValue, Storage, with_storage, with_storage_read,17};18use std::{19    any::{Any, TypeId},20    cell::{Cell, Ref, RefCell, RefMut},21    marker::PhantomData,22    mem::ManuallyDrop,23    ops::{Deref, DerefMut},24};2526fn failure(_: cdk_rsx_engine_hylix::Error) -> Error {27    Error::Hylix28}2930/// Transient decoded records belonging to exactly one Store Context. The31/// private Record owns each allocation, and every guard acquires its existing32/// native module loan before looking here. A frame epoch alone is not a pin.33#[derive(Default)]34pub(crate) struct FrameRecords {35    entries: RefCell<Vec<FrameEntry>>,36}37struct FrameEntry {38    block: Block,39    ty: TypeId,40    value: Box<dyn BufferedValue>,41}42trait BufferedValue {43    fn as_any(&self) -> &dyn Any;44    fn into_any(self: Box<Self>) -> Box<dyn Any>;45    fn unborrowed(&self) -> bool;46    fn flush(&self, block: Block) -> Result<()>;47}48struct Buffered<T: HylixValue> {49    value: RefCell<T>,50    dirty: Cell<bool>,51}52impl<T: HylixValue> BufferedValue for Buffered<T> {53    fn as_any(&self) -> &dyn Any {54        self55    }56    fn into_any(self: Box<Self>) -> Box<dyn Any> {57        self58    }59    fn unborrowed(&self) -> bool {60        self.value.try_borrow_mut().is_ok()61    }62    fn flush(&self, block: Block) -> Result<()> {63        if self.dirty.get() {64            let value = self.value.try_borrow().map_err(|_| Error::Borrowed)?;65            cdk_rsx_engine_hylix::with_encoded(&*value, |bytes| {66                with_storage(|storage| storage.write(block, 0, bytes))67            })68            .map_err(failure)?;69            self.dirty.set(false);70        }71        Ok(())72    }73}74impl FrameRecords {75    /// Call only while retaining the native Data/DataMut<Record<T>> loan. Its76    /// module cannot be retired, converted or replaced until that guard ends.77    fn get<T: HylixValue>(&self, block: Block) -> Result<&Buffered<T>> {78        let pointer = {79            let entries = self.entries.try_borrow().map_err(|_| Error::Borrowed)?;80            entries81                .iter()82                .find(|entry| entry.block == block && entry.ty == TypeId::of::<T>())83                .map(|entry| {84                    entry85                        .value86                        .as_any()87                        .downcast_ref::<Buffered<T>>()88                        .expect("record cache type matches its key")89                        as *const Buffered<T>90                })91        };92        if let Some(pointer) = pointer {93            // SAFETY: Vec growth moves Boxes, never this pointee. Removal first94            // proves no cached borrow exists. The caller's native module loan95            // excludes retirement, conversion and replacement of this Record.96            return Ok(unsafe { &*pointer });97        }98        let value = with_storage_read(|storage| load(storage, block)).map_err(failure)?;99        let value = Box::new(Buffered::<T> {100            value: RefCell::new(value),101            dirty: Cell::new(false),102        });103        let pointer = &*value as *const Buffered<T>;104        self.entries105            .try_borrow_mut()106            .map_err(|_| Error::Borrowed)?107            .push(FrameEntry {108                block,109                ty: TypeId::of::<T>(),110                value,111            });112        // SAFETY: same boxed-address and native module loan invariant as above.113        Ok(unsafe { &*pointer })114    }115116    /// Remove before freeing/reusing a Record allocation. Conversion and117    /// destruction own the native Record and cannot coexist with its guards.118    fn take<T: HylixValue>(&self, block: Block) -> Result<Option<T>> {119        let entry = {120            let mut entries = self.entries.try_borrow_mut().map_err(|_| Error::Borrowed)?;121            let Some(index) = entries122                .iter()123                .position(|entry| entry.block == block && entry.ty == TypeId::of::<T>())124            else {125                return Ok(None);126            };127            if !entries[index].value.unborrowed() {128                return Err(Error::Borrowed);129            }130            entries.swap_remove(index)131        };132        let value = entry133            .value134            .into_any()135            .downcast::<Buffered<T>>()136            .unwrap_or_else(|_| crate::fatal(Error::Hylix));137        Ok(Some(value.value.into_inner()))138    }139140    pub(crate) fn finish(&self) -> Result<()> {141        {142            let entries = self.entries.try_borrow().map_err(|_| Error::Borrowed)?;143            for entry in entries.iter() {144                entry.value.flush(entry.block)?;145            }146        }147        // Drop transient snapshots outside the table loan, before Active ends.148        let entries =149            core::mem::take(&mut *self.entries.try_borrow_mut().map_err(|_| Error::Borrowed)?);150        drop(entries);151        Ok(())152    }153}154155fn take_buffered<T: HylixValue>(block: Block) -> Result<Option<T>> {156    crate::scope::with_current(|cx| cx.records.take::<T>(block)).unwrap_or(Ok(None))157}158159/// A versioned owner-private Hylix record with a fixed native descriptor.160/// This descriptor participates in Store's existing module ownership, borrowing161/// and upgrade rules. It must not be cloned or placed in transient services.162#[repr(C)]163pub struct Record<T: HylixValue> {164    block: Block,165    marker: PhantomData<fn() -> T>,166}167// SAFETY: the descriptor is inline data. It has no pointer or transient owner;168// its one stable allocation is controlled by the containing Store module cell.169// HylixValue already requires 'static. Repeating it here prevents the pinned170// reflection MVP from selecting this proof for the compiled interpretation walk.171unsafe impl<T: HylixValue> crate::NyxusData for Record<T> {172    const __NYXUS_POLICY: [u8; 32] = cdk_rsx_memory_abi::semantic_contract(173        "hylix-record-v1",174        &[],175        &[crate::MODULE_POLICY, cdk_rsx_engine_hylix::HYLIX_POLICY],176    );177}178// SAFETY: the descriptor has one logical argument T, the complete fixed Codec179// value stored in its stable allocation. Its native proof owns the lifecycle.180unsafe impl<T: HylixValue> cdk_rsx_engine_hylix::CodecCarrier for Record<T> {}181182impl<T: HylixValue> Record<T> {183    /// Construct inside a write scope of a Store with an attached Hylix arena.184    pub fn new(value: T) -> Result<Self> {185        let block = cdk_rsx_engine_hylix::with_encoded(&value, |bytes| {186            with_storage(|storage| {187                // Empty codecs still need an independent allocation identity188                // for frame borrowing, conversion and retirement.189                let block = storage.allocate(T::SIZE.max(1) as u64)?;190                storage.write(block, 0, if T::SIZE == 0 { &[0] } else { bytes })?;191                Ok(block)192            })193        })194        .map_err(failure)?;195        // HylixValue snapshots do not own by Drop. The bytes now own exactly196        // the values passed to this constructor, without per-entry bookkeeping.197        drop(value);198        Ok(Self {199            block,200            marker: PhantomData,201        })202    }203204    /// Transfer a source version's owned value during an explicit conversion.205    /// Only this small record allocation is freed; nested allocations move with206    /// the returned handles and must be saved or explicitly retired by the owner.207    pub fn into_value(self) -> Result<T> {208        let record = ManuallyDrop::new(self);209        let value = take_buffered::<T>(record.block)?;210        with_storage(|storage| {211            let value = match value {212                Some(value) => value,213                None => load::<T>(storage, record.block)?,214            };215            storage.deallocate(record.block)?;216            Ok(value)217        })218        .map_err(failure)219    }220}221222impl<T: HylixValue> Drop for Record<T> {223    fn drop(&mut self) {224        let value = take_buffered::<T>(self.block).unwrap_or_else(|e| crate::fatal(e));225        with_storage(|storage| {226            let value = match value {227                Some(value) => value,228                None => load::<T>(storage, self.block)?,229            };230            value.retire(storage)?;231            storage.deallocate(self.block)232        })233        .unwrap_or_else(|_| crate::fatal(Error::Hylix));234    }235}236237fn load<T: Codec>(storage: &dyn Storage, block: Block) -> cdk_rsx_engine_hylix::Result<T> {238    cdk_rsx_engine_hylix::read_value(storage, block, 0)239}240241/// A statically selected Hylix module. Its ordinary native ModuleMemory242/// implementation uses `type Data = Record<Self::HylixData>` and declares the243/// same private key, opaque Children and physical contract as a native module.244///245/// # Safety246/// HylixData must be the exact frozen codec saved by this version. Its normal247/// Drop is inert; retire visits every owned stable allocation exactly once.248pub unsafe trait ModuleMemory:249    crate::ModuleMemory<Data = Record<<Self as ModuleMemory>::HylixData>>250{251    type HylixData: HylixValue + 'static;252}253254/// Create a Hylix module using the same detached ticket and attachment rules.255pub fn create<'s, M: ModuleMemory>(256    scope: &Scope<'s>,257    key: &MemoryKey<M>,258    value: M::HylixData,259) -> Result<Detached<'s, M>> {260    scope.create(key, Record::new(value)?)261}262263/// Borrow the frame's current decoded record under its native module binding.264pub fn read<'a, M: ModuleMemory>(265    reference: ModuleRef<M>,266    access: &'a impl Access,267    key: &MemoryKey<M>,268) -> Result<Read<'a, M::HylixData>> {269    let record = reference.read(access, key)?;270    let value = crate::scope::context(access)271        .records272        .get::<M::HylixData>(record.block)?273        .value274        .try_borrow()275        .map_err(|_| Error::Borrowed)?;276    Ok(Read {277        value,278        _record: record,279    })280}281282/// Edit the frame's current decoded record. Dirty module records publish at283/// frame end; nested collection operations still publish their own rows.284pub fn write<'a, M: ModuleMemory>(285    reference: ModuleRef<M>,286    access: &'a Scope<'_>,287    key: &MemoryKey<M>,288) -> Result<Write<'a, M::HylixData>> {289    let record = reference.write(access, key)?;290    let entry = access.cx.records.get::<M::HylixData>(record.block)?;291    let value = entry.value.try_borrow_mut().map_err(|_| Error::Borrowed)?;292    entry.dirty.set(true);293    Ok(Write {294        value,295        _record: record,296    })297}298299/// Borrow one compile-selected native field of the frame's current record,300/// retaining the whole module's read borrow.301pub fn read_field<'a, M: ModuleMemory, T: HylixValue>(302    reference: ModuleRef<M>,303    access: &'a impl Access,304    key: &MemoryKey<M>,305    field: Field<M::HylixData, T>,306) -> Result<Read<'a, T, M::HylixData>> {307    let record = reference.read(access, key)?;308    let value = crate::scope::context(access)309        .records310        .get::<M::HylixData>(record.block)?311        .value312        .try_borrow()313        .map_err(|_| Error::Borrowed)?;314    let value = Ref::map(value, |value| field.get(value));315    Ok(Read {316        value,317        _record: record,318    })319}320321/// Edit one complete field of the frame's current record. Replacing an owning322/// field still requires explicit retirement323/// or transfer of its displaced value, exactly as whole-record editing does.324pub fn write_field<'a, M: ModuleMemory, T: HylixValue>(325    reference: ModuleRef<M>,326    access: &'a Scope<'_>,327    key: &MemoryKey<M>,328    field: Field<M::HylixData, T>,329) -> Result<Write<'a, T, M::HylixData>> {330    let record = reference.write(access, key)?;331    let entry = access.cx.records.get::<M::HylixData>(record.block)?;332    let value = entry.value.try_borrow_mut().map_err(|_| Error::Borrowed)?;333    entry.dirty.set(true);334    let value = RefMut::map(value, |value| field.get_mut(value));335    Ok(Write {336        value,337        _record: record,338    })339}340341pub struct Read<'a, T: HylixValue, RecordValue: HylixValue = T> {342    value: Ref<'a, T>,343    _record: Data<'a, Record<RecordValue>>,344}345impl<T: HylixValue, RecordValue: HylixValue> Deref for Read<'_, T, RecordValue> {346    type Target = T;347    fn deref(&self) -> &T {348        &self.value349    }350}351352pub struct Write<'a, T: HylixValue, RecordValue: HylixValue = T> {353    value: RefMut<'a, T>,354    _record: DataMut<'a, Record<RecordValue>>,355}356impl<T: HylixValue, RecordValue: HylixValue> Deref for Write<'_, T, RecordValue> {357    type Target = T;358    fn deref(&self) -> &T {359        &self.value360    }361}362impl<T: HylixValue, RecordValue: HylixValue> DerefMut for Write<'_, T, RecordValue> {363    fn deref_mut(&mut self) -> &mut T {364        &mut self.value365    }366}367368/// Service bindings use the same actor frame and private owner key as native369/// bindings. Only the final read/write projection selects the Hylix engine.370pub mod binding {371    use super::*;372    use crate::Children;373374    pub struct Memory<M: ModuleMemory> {375        reference: ModuleRef<M>,376        key: &'static MemoryKey<M>,377    }378    impl<M: ModuleMemory> Memory<M> {379        pub const fn bind(reference: ModuleRef<M>, key: &'static MemoryKey<M>) -> Self {380            Self { reference, key }381        }382        #[inline]383        pub fn view<'a, A: Access>(&'a self, access: &'a A) -> MemoryView<'a, A, M> {384            MemoryView {385                memory: self,386                access,387            }388        }389    }390    pub struct MemoryView<'a, A: Access, M: ModuleMemory> {391        memory: &'a Memory<M>,392        access: &'a A,393    }394    impl<A: Access, M: ModuleMemory> Copy for MemoryView<'_, A, M> {}395    impl<A: Access, M: ModuleMemory> Clone for MemoryView<'_, A, M> {396        fn clone(&self) -> Self {397            *self398        }399    }400    impl<'a, A: Access, M: ModuleMemory> MemoryView<'a, A, M> {401        #[inline]402        pub fn access(&self) -> &'a A {403            self.access404        }405        #[inline]406        pub fn read(&self) -> Result<Read<'a, M::HylixData>> {407            read(self.memory.reference, self.access, self.memory.key)408        }409        /// Select a private typed field without reading the enclosing record.410        #[inline]411        pub fn field<T: HylixValue>(412            &self,413            field: Field<M::HylixData, T>,414        ) -> FieldView<'a, A, M, T> {415            FieldView {416                memory: *self,417                field,418            }419        }420        #[inline]421        pub fn children(&self) -> Result<Children<'a, M::Children>> {422            self.memory.reference.children(self.access, self.memory.key)423        }424        #[inline]425        pub fn project<N: ModuleMemory>(&self, memory: &'a Memory<N>) -> MemoryView<'a, A, N> {426            memory.view(self.access)427        }428    }429    impl<'a, 's, M: ModuleMemory> MemoryView<'a, Scope<'s>, M> {430        #[inline]431        pub fn write(&self) -> Result<Write<'a, M::HylixData>> {432            write(self.memory.reference, self.access, self.memory.key)433        }434        #[inline]435        pub fn scope(&self) -> &'a Scope<'s> {436            self.access437        }438    }439440    /// A typed field projection keeps the module's key and actor frame private.441    /// Query projections cannot acquire a writer.442    ///443    /// ```compile_fail444    /// use cdk_rsx_engine_hylix::{Field, HylixValue};445    /// use cdk_rsx_store::{ReadScope, hylix::{ModuleMemory, binding::Memory}};446    /// fn query<M: ModuleMemory, T: HylixValue>(447    ///     memory: &Memory<M>, scope: &ReadScope<'_>, field: Field<M::HylixData, T>,448    /// ) {449    ///     let writer = memory.view(scope).field(field).write();450    /// }451    /// ```452    pub struct FieldView<'a, A: Access, M: ModuleMemory, T: HylixValue> {453        memory: MemoryView<'a, A, M>,454        field: Field<M::HylixData, T>,455    }456    impl<A: Access, M: ModuleMemory, T: HylixValue> Copy for FieldView<'_, A, M, T> {}457    impl<A: Access, M: ModuleMemory, T: HylixValue> Clone for FieldView<'_, A, M, T> {458        fn clone(&self) -> Self {459            *self460        }461    }462    impl<'a, A: Access, M: ModuleMemory, T: HylixValue> FieldView<'a, A, M, T> {463        #[inline]464        pub fn read(&self) -> Result<Read<'a, T, M::HylixData>> {465            read_field(466                self.memory.memory.reference,467                self.memory.access,468                self.memory.memory.key,469                self.field,470            )471        }472        #[inline]473        pub fn field<Nested: HylixValue>(474            &self,475            field: Field<T, Nested>,476        ) -> FieldView<'a, A, M, Nested> {477            self.memory.field(self.field.then(field))478        }479    }480    impl<'a, 's, M: ModuleMemory, T: HylixValue> FieldView<'a, Scope<'s>, M, T> {481        #[inline]482        pub fn write(&self) -> Result<Write<'a, T, M::HylixData>> {483            write_field(484                self.memory.memory.reference,485                self.memory.access,486                self.memory.memory.key,487                self.field,488            )489        }490    }491}