ownership.rs

cdk-rsx/crates/cdk-rsx-collections/src/hylix/ownership.rs

ownership.rs466 lines← SDK documentation
1//! Scoped temporary owners above the fixed, inert persisted carriers.2//!3//! Construct, remove or take an actual edge here. An unused `Owned` retires it;4//! replacement/insertion moves it without a retain, ownership directory or5//! record scan. Persisted snapshots keep their ordinary inert Drop. Raw carrier6//! APIs and Codec remain trusted storage infrastructure: this module cannot7//! infer ownership of an arbitrary decoded `T`, and provides no generic adopt.8//!9//! Inside a module's active write frame, with its actual mutable field:10//! ```11//! use cdk_rsx_collections::hylix::{Blob, Queue, ownership};12//! fn replace_backlog(backlog: &mut Queue<Blob>, input: &[u8]) {13//!     ownership::scope(|owners| {14//!         let mut next = owners.queue();15//!         next.push_back(owners.blob(input));16//!         next.replace(backlog); // displaced backlog is automatically retired17//!     });18//! }19//! ```20//! The field handoff has the same contract as existing raw carrier APIs: its21//! enclosing actual record must be published, moved or retired. Passing a raw22//! decoded alias, or abandoning that enclosing raw record, is not repaired by23//! this temporary-owner layer.24//!25//! Named records derive `OwnedRecord` alongside their fieldwise codecs and26//! ownership contract. The generated `NameFields<'scope>` contains an `Owned`27//! for each field, with the original field's visibility. It has no Codec,28//! HylixValue or Clone. Splitting and rebuilding move the existing child edges;29//! they perform no stable I/O or retain/release. Discarding a field retires it.30//! The FieldwiseValue marker proves that the record's owning edges are exactly31//! its fields' HylixValue edges. Derived HylixValue emits it for structs;32//! manual implementations require an explicit unsafe structural certificate.33//! A custom aliasing/external-edge contract is rejected without that proof.34//! ```compile_fail35//! use cdk_rsx_collections::hylix::{Blob, OwnedRecord, Shared};36//! #[derive(cdk_rsx_engine_hylix::Codec, OwnedRecord)]37//! struct Aliased { child: Shared<Blob> }38//! // This manual contract deliberately does not own the aliased child.39//! unsafe impl cdk_rsx_engine_hylix::HylixValue for Aliased {40//!     fn retire(self, _: &mut dyn cdk_rsx_engine_hylix::Storage) -> cdk_rsx_engine_hylix::Result<()> { Ok(()) }41//! }42//! ```43//! A genuinely fieldwise manual implementation can certify that contract.44//! ```45//! use cdk_rsx_collections::hylix::{Blob, OwnedRecord, ownership::{Owned, Owners}};46//! #[derive(cdk_rsx_engine_hylix::Codec, OwnedRecord)]47//! struct Manual { child: Blob }48//! // SAFETY: exactly the single field's ownership.49//! unsafe impl cdk_rsx_engine_hylix::HylixValue for Manual {50//!     fn retain(&self, storage: &mut dyn cdk_rsx_engine_hylix::Storage) -> cdk_rsx_engine_hylix::Result<()> {51//!         cdk_rsx_engine_hylix::HylixValue::retain(&self.child, storage)52//!     }53//!     fn retire(self, storage: &mut dyn cdk_rsx_engine_hylix::Storage) -> cdk_rsx_engine_hylix::Result<()> {54//!         cdk_rsx_engine_hylix::HylixValue::retire(self.child, storage)55//!     }56//! }57//! // SAFETY: the complete contract above is exactly the field contract.58//! unsafe impl cdk_rsx_engine_hylix::FieldwiseValue for Manual {}59//! fn roundtrip<'s>(owners: &'s Owners, row: Owned<'s, Manual>) -> Owned<'s, Manual> {60//!     Manual::from_owned_fields(owners, Manual::split_owned(row))61//! }62//! ```63//!64//! ```65//! use cdk_rsx_collections::hylix::{Blob, Map, OwnedRecord, Shared, ownership, transform};66//! #[derive(cdk_rsx_engine_hylix::Codec, cdk_rsx_engine_hylix::HylixValue, OwnedRecord)]67//! struct Old { count: u64, child: Shared<Blob>, obsolete: Blob }68//! #[derive(cdk_rsx_engine_hylix::Codec, cdk_rsx_engine_hylix::HylixValue, OwnedRecord)]69//! struct New { count: u64, child: Shared<Blob>, added: bool }70//! fn convert(source: &mut Map<u64, Old>, target: &mut Map<u64, New>) {71//!     ownership::scope(|owners| {72//!         transform::values(owners, owners.take(source), |row| {73//!             let OldFields { count, child, obsolete } = Old::split_owned(row);74//!             drop(obsolete);75//!             New::from_owned_fields(owners, NewFields {76//!                 count: owners.plain(count.into_plain() + 1),77//!                 child,78//!                 added: owners.plain(true),79//!             })80//!         }).replace(target);81//!     });82//! }83//! ```84//! Field visibility remains the schema owner's boundary.85//! ```compile_fail86//! mod owner {87//!     use cdk_rsx_collections::hylix::{Blob, OwnedRecord};88//!     #[derive(cdk_rsx_engine_hylix::Codec, cdk_rsx_engine_hylix::HylixValue, OwnedRecord)]89//!     pub struct Row { child: Blob }90//! }91//! fn steal(fields: owner::RowFields<'_>) { let _ = fields.child; }92//! ```93//! A field view cannot become a persisted record or leave its owning scope.94//! ```compile_fail95//! use cdk_rsx_collections::hylix::{Blob, OwnedRecord};96//! #[derive(cdk_rsx_engine_hylix::Codec, cdk_rsx_engine_hylix::HylixValue, OwnedRecord)]97//! struct Row { child: Blob }98//! fn persist(fields: &RowFields<'_>) { cdk_rsx_engine_hylix::encode(fields); }99//! ```100//! ```compile_fail101//! use cdk_rsx_collections::hylix::{Blob, OwnedRecord, ownership};102//! #[derive(cdk_rsx_engine_hylix::Codec, cdk_rsx_engine_hylix::HylixValue, OwnedRecord)]103//! struct Row { child: Blob }104//! let escaped = ownership::scope(|owners| {105//!     Row::split_owned(Row::from_owned_fields(owners, RowFields { child: owners.blob(b"child") }))106//! });107//! ```108//! Generated structural hooks cannot be called as safe raw adoption APIs.109//! ```compile_fail110//! use cdk_rsx_collections::hylix::{Blob, ownership::Owners};111//! fn adopt(owners: &Owners, raw: Blob) { owners.__produce(|| raw); }112//! ```113//!114//! A temporary cannot escape this lexical scope or be encoded as a carrier.115//! ```compile_fail116//! use cdk_rsx_collections::hylix::ownership;117//! let escaped = ownership::scope(|owners| owners.blob(b"temporary"));118//! ```119//! ```compile_fail120//! use cdk_rsx_collections::hylix::{Blob, ownership::Owned};121//! fn persist(owner: &Owned<'_, Blob>) { cdk_rsx_engine_hylix::encode(owner); }122//! ```123//! `Owned` has no mutable dereference or generic consuming extraction. Use its124//! collection operations and explicit field transfer helpers.125//! ```compile_fail126//! use cdk_rsx_collections::hylix::{Map, ownership::Owned};127//! fn steal(owner: &mut Owned<'_, Map<u64,u64>>) {128//!     let raw = core::mem::take(&mut **owner);129//! }130//! ```131132use super::{Blob, Cell, HylixValue, Key, Map, Queue, Set, Shared, String, Vec, must};133use cdk_rsx_engine_hylix::{ContextLoan, Error, context_id, with_storage};134use core::ops::Deref;135136#[cfg(not(all(target_family = "wasm", panic = "abort")))]137use std::thread::panicking as unwinding;138139// An aborting IC invocation cannot resume after a panic, including an explicit140// drop in its panic hook: retirement is rolled back with that invocation.141// Native/unwinding hosts retain their existing quarantine behavior.142#[cfg(all(target_family = "wasm", panic = "abort"))]143#[inline]144fn unwinding() -> bool {145    false146}147148mod sealed {149    pub trait Plain {}150}151152/// Resource-free fixed values accepted without an ownership assertion.153/// This is sealed: an arbitrary Copy codec can still contain owning offsets.154pub trait Plain: HylixValue + Copy + sealed::Plain {}155macro_rules! plain {156    ($($ty:ty),* $(,)?) => { $(157        impl sealed::Plain for $ty {}158        impl Plain for $ty {}159    )* };160}161plain!(162    (),163    bool,164    u8,165    u16,166    u32,167    u64,168    u128,169    usize,170    i8,171    i16,172    i32,173    i64,174    i128,175    isize,176    f32,177    f64178);179impl<T: Plain, const N: usize> sealed::Plain for [T; N] {}180impl<T: Plain, const N: usize> Plain for [T; N] {}181impl<T: Plain> sealed::Plain for Option<T> {}182impl<T: Plain> Plain for Option<T> {}183184/// The lexical brand for temporary owners in the active write frame.185pub struct Owners {186    epoch: u64,187    loan: Option<ContextLoan>,188}189190/// Execute owner construction and moves inside the current Store write frame.191/// Read contexts reject this before any allocation. No stable bytes or native192/// registry are allocated for the lexical scope itself.193pub fn scope<R>(run: impl for<'s> FnOnce(&'s Owners) -> R) -> R {194    let epoch = must(with_storage(|_| context_id()));195    run(&Owners {196        epoch,197        loan: Some(must(ContextLoan::new())),198    })199}200impl Drop for Owners {201    fn drop(&mut self) {202        if unwinding() {203            core::mem::forget(self.loan.take());204        }205    }206}207208/// An actual temporary owning edge. Its carrier is never persisted directly.209///210/// One transient ContextLoan rejects forgotten owners at frame finalization.211/// Drop in an unwinding frame leaves that loan outstanding and performs no212/// disposal: a caught native panic cannot turn an abandoned owner into a213/// successful frame. The IC supplies rollback; native hosts must restore their214/// whole image before clearing foundation quarantine.215pub struct Owned<'s, T: HylixValue> {216    value: Option<T>,217    owners: &'s Owners,218    loan: Option<ContextLoan>,219}220struct Disposal<'a>(&'a mut Option<ContextLoan>);221impl Drop for Disposal<'_> {222    fn drop(&mut self) {223        if unwinding() {224            core::mem::forget(self.0.take());225        }226    }227}228impl<T: HylixValue> Deref for Owned<'_, T> {229    type Target = T;230    fn deref(&self) -> &T {231        self.check();232        self.value.as_ref().expect("live temporary owner")233    }234}235impl<'s, T: HylixValue> Owned<'s, T> {236    fn check(&self) {237        must(self.loan.as_ref().expect("temporary owner loan").check());238    }239    // Retain the token throughout the operation. If publication traps, the240    // partially consumed temporary forces context failure, never success.241    pub(super) fn transfer<R>(mut self, apply: impl FnOnce(T) -> R) -> R {242        self.check();243        let value = self.value.take().expect("live temporary owner");244        apply(value)245    }246    /// Structural transfer hook used only by `OwnedRecord` generated code.247    ///248    /// # Safety249    /// Move every owning field exactly once into protected field owners or a250    /// complete target carrier. Never return a raw owning alias or abandon an251    /// unprotected raw field. The source loan remains live throughout `apply`.252    #[doc(hidden)]253    pub unsafe fn __transfer<R>(self, apply: impl FnOnce(T, &'s Owners) -> R) -> R {254        let owners = self.owners;255        self.transfer(|value| apply(value, owners))256    }257    /// Replace an actual owner field. The displaced owner is also temporary,258    /// so ignoring the result retires it rather than leaking it.259    pub fn replace(self, slot: &mut T) -> Self {260        let owners = self.owners;261        self.transfer(|value| owners.owned(core::mem::replace(slot, value)))262    }263    pub fn cell(self) -> Owned<'s, Cell<T>> {264        let owners = self.owners;265        self.transfer(|value| owners.owned(Cell::new(value)))266    }267    pub fn shared(self) -> Owned<'s, Shared<T>> {268        let owners = self.owners;269        self.transfer(|value| owners.owned(Shared::new(value)))270    }271    pub fn some(self) -> Owned<'s, Option<T>> {272        let owners = self.owners;273        self.transfer(|value| owners.owned(Some(value)))274    }275    pub fn pair<U: HylixValue>(self, other: Owned<'s, U>) -> Owned<'s, (T, U)> {276        let owners = self.owners;277        self.transfer(|a| other.transfer(|b| owners.owned((a, b))))278    }279}280impl<T: HylixValue> Drop for Owned<'_, T> {281    fn drop(&mut self) {282        let loan = self.loan.as_ref().expect("temporary owner loan");283        if let Err(error) = loan.check() {284            if !unwinding() {285                must::<()>(Err(error));286            }287            return;288        }289        if unwinding() {290            core::mem::forget(self.loan.take());291            return;292        }293        if let Some(value) = self.value.take() {294            let _disposal = Disposal(&mut self.loan);295            must(with_storage(|storage| value.retire(storage)));296        }297    }298}299impl<'s, T: Plain> Owned<'s, T> {300    /// Materialize a resource-free value as an ordinary transient DTO.301    pub fn into_plain(self) -> T {302        self.transfer(core::convert::identity)303    }304}305impl<'s, A: HylixValue, B: HylixValue> Owned<'s, (A, B)> {306    pub fn split(self) -> (Owned<'s, A>, Owned<'s, B>) {307        let owners = self.owners;308        self.transfer(|(a, b)| (owners.owned(a), owners.owned(b)))309    }310}311312impl Owners {313    fn check(&self) {314        if must(context_id()) != self.epoch {315            must::<()>(Err(Error::InvalidInput("stale stable ownership scope")));316        }317    }318    pub(super) fn owned<T: HylixValue>(&self, value: T) -> Owned<'_, T> {319        self.produce(|| value)320    }321    pub(super) fn produce<T: HylixValue>(&self, create: impl FnOnce() -> T) -> Owned<'_, T> {322        let mut pending = self.pending();323        pending.value = Some(create());324        pending325    }326    /// Structural construction hook used only by `OwnedRecord` generated code.327    ///328    /// # Safety329    /// `create` must move actual owning fields exactly once into the returned330    /// carrier, never adopt decoded snapshots or duplicate raw owning handles.331    /// A pending target loan exists before `create` consumes any input fields.332    #[doc(hidden)]333    pub unsafe fn __produce<T: HylixValue>(&self, create: impl FnOnce() -> T) -> Owned<'_, T> {334        self.produce(create)335    }336    fn optional<T: HylixValue>(&self, create: impl FnOnce() -> Option<T>) -> Option<Owned<'_, T>> {337        let mut pending = self.pending();338        pending.value = create();339        pending.value.is_some().then_some(pending)340    }341    fn pending<T: HylixValue>(&self) -> Owned<'_, T> {342        self.check();343        Owned {344            value: None,345            owners: self,346            loan: Some(must(ContextLoan::new())),347        }348    }349    pub fn plain<T: Plain>(&self, value: T) -> Owned<'_, T> {350        self.owned(value)351    }352    pub fn map<K: HylixValue, V: HylixValue>(&self) -> Owned<'_, Map<K, V>> {353        self.owned(Map::new())354    }355    pub fn queue<T: HylixValue>(&self) -> Owned<'_, Queue<T>> {356        self.owned(Queue::new())357    }358    pub fn vector<T: HylixValue>(&self) -> Owned<'_, Vec<T>> {359        self.owned(Vec::new())360    }361    pub fn set<T: HylixValue>(&self) -> Owned<'_, Set<T>> {362        self.owned(Set::new())363    }364    pub fn blob(&self, bytes: &[u8]) -> Owned<'_, Blob> {365        self.produce(|| Blob::from_slice(bytes))366    }367    pub fn string(&self, text: &str) -> Owned<'_, String> {368        self.produce(|| String::from_str(text))369    }370    /// A counted additional durable edge, acquired explicitly rather than on read.371    pub fn share<T: HylixValue>(&self, value: &Shared<T>) -> Owned<'_, Shared<T>> {372        self.produce(|| value.share())373    }374    /// Move an actual mutable owner field, leaving its empty default carrier.375    /// A borrowed Read snapshot cannot supply this mutable reference.376    pub fn take<T: HylixValue + Default>(&self, slot: &mut T) -> Owned<'_, T> {377        self.produce(|| core::mem::take(slot))378    }379    pub fn insert<'s, K: Key, V: HylixValue>(380        &'s self,381        map: &mut Map<K, V>,382        key: Owned<'s, K>,383        value: Owned<'s, V>,384    ) -> Option<Owned<'s, V>> {385        self.check();386        key.transfer(|key| {387            value.transfer(|value| map.insert(key, value).map(|old| self.owned(old)))388        })389    }390    pub fn remove<K, V, Q: ?Sized>(&self, map: &mut Map<K, V>, key: &Q) -> Option<Owned<'_, V>>391    where392        K: Key + Key<Q>,393        V: HylixValue,394    {395        self.optional(|| map.remove(key))396    }397    pub fn pop_first<K: Key, V: HylixValue>(398        &self,399        map: &mut Map<K, V>,400    ) -> Option<Owned<'_, (K, V)>> {401        self.optional(|| map.pop_first())402    }403    pub fn push_back<'s, T: HylixValue>(&'s self, queue: &mut Queue<T>, value: Owned<'s, T>) {404        self.check();405        value.transfer(|value| queue.push_back(value));406    }407    pub fn pop_front<T: HylixValue>(&self, queue: &mut Queue<T>) -> Option<Owned<'_, T>> {408        self.optional(|| queue.pop_front())409    }410    pub fn pop_back<T: HylixValue>(&self, queue: &mut Queue<T>) -> Option<Owned<'_, T>> {411        self.optional(|| queue.pop_back())412    }413}414415impl<'s, K: Key, V: HylixValue> Owned<'s, Map<K, V>> {416    pub fn insert(&mut self, key: Owned<'s, K>, value: Owned<'s, V>) -> Option<Owned<'s, V>> {417        self.check();418        self.owners.insert(self.value.as_mut().unwrap(), key, value)419    }420    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Owned<'s, V>>421    where422        K: Key<Q>,423    {424        self.check();425        self.owners.remove(self.value.as_mut().unwrap(), key)426    }427    pub fn pop_first(&mut self) -> Option<Owned<'s, (K, V)>> {428        self.check();429        self.owners.pop_first(self.value.as_mut().unwrap())430    }431}432impl<'s, T: HylixValue> Owned<'s, Queue<T>> {433    pub fn push_back(&mut self, value: Owned<'s, T>) {434        self.check();435        self.owners.push_back(self.value.as_mut().unwrap(), value);436    }437    pub fn pop_front(&mut self) -> Option<Owned<'s, T>> {438        self.check();439        self.owners.pop_front(self.value.as_mut().unwrap())440    }441    pub fn pop_back(&mut self) -> Option<Owned<'s, T>> {442        self.check();443        self.owners.pop_back(self.value.as_mut().unwrap())444    }445}446impl<'s, T: HylixValue> Owned<'s, Vec<T>> {447    pub fn push(&mut self, value: Owned<'s, T>) {448        self.check();449        value.transfer(|value| self.value.as_mut().unwrap().push(value));450    }451    pub fn pop(&mut self) -> Option<Owned<'s, T>> {452        self.check();453        self.owners.optional(|| self.value.as_mut().unwrap().pop())454    }455}456impl<'s, T: Key> Owned<'s, Set<T>> {457    pub fn insert(&mut self, value: Owned<'s, T>) -> bool {458        self.check();459        value.transfer(|value| self.value.as_mut().unwrap().insert(value))460    }461    pub fn pop_first(&mut self) -> Option<Owned<'s, T>> {462        self.check();463        self.owners464            .optional(|| self.value.as_mut().unwrap().pop_first())465    }466}