v1.rs

cdk-rsx/crates/cdk-rsx-takt/src/memory/v1.rs

1//! Fresh complete Nyxus Takt state. No historical layout reader is kept.2//!3//! Every owned allocation uses Nyxus. Explicit tags avoid relying on Rust's4//! Option/enum niche choices in the physical certificate. Shared byte/child5//! arrays use the source-owned SharedSlice<T> allocation recipe; elements and6//! immutable sharing remain direct, without a separate Vec header allocation.7use cdk_rsx::Principal;8use cdk_rsx_collections::nyxus::{Map, NyxusData, Queue, Rc, Set, SharedSlice, String, Vec};9use std::cell::RefCell;1011/// Frozen application payload interpretation, separate from executable graph12/// behavior. Implement in the application memory version with every declaration,13/// key/hash/drop interpretation dependency included in the source digest.14///15/// # Safety16/// CONTRACT must change when those saved declarations/interpretations change;17/// unchanged physical layouts alone do not establish semantic compatibility.18pub unsafe trait PayloadContract: NyxusData {19    const CONTRACT: [u8; 32];20}21macro_rules! scalar_contract {22    ($($ty:ty),* $(,)?) => {$ (23        // SAFETY: fixed primitive value interpretation has no hidden dependencies.24        unsafe impl PayloadContract for $ty {25            const CONTRACT:[u8;32] = cdk_rsx_memory_abi::semantic_source(concat!("takt/scalar/",stringify!($ty)), &[]);26        }27    )*};28}29scalar_contract!(30    (),31    bool,32    char,33    u8,34    u16,35    u32,36    u64,37    u128,38    usize,39    i8,40    i16,41    i32,42    i64,43    i128,44    isize,45    f32,46    f6447);4849/// Opaque owner contract for one complete typed workflow memory.50#[cdk_rsx_store::memory(owner = crate::memory, data = State<D, E>, sources = [include_str!("cell.rs"), include_str!("node_table.rs")], dependencies = [D::CONTRACT, E::CONTRACT, cdk_rsx::wire::WIRE_POLICY])]51pub struct Workflow<D: PayloadContract, E: PayloadContract>;52impl<D: PayloadContract, E: PayloadContract> Workflow<D, E> {53    pub fn create<'s>(54        scope: &cdk_rsx_store::Scope<'s>,55    ) -> cdk_rsx_store::Result<cdk_rsx_store::Detached<'s, Self>> {56        scope.create(&Self::KEY, State::default())57    }58    pub(crate) fn bind(59        reference: cdk_rsx_store::ModuleRef<Self>,60    ) -> cdk_rsx_store::binding::Memory<Self> {61        cdk_rsx_store::binding::Memory::bind(reference, &Self::KEY)62    }63}6465/// Private versioned cell layout. Capability-gated borrow methods and guards66/// live in `memory::cell`; the complete saved carrier stays in this version.67#[repr(transparent)]68pub(crate) struct Cell<T: NyxusData> {69    pub(super) value: RefCell<T>,70}71// SAFETY: admitted T is the only payload. The private raw cell is reachable only72// by the memory implementation, whose read/write guards require Access/Scope and73// retain the shared frame's counted Loan. No public DTO exposes Cell or guards.74// RefCell's actual borrow-flag/value layout is a physical certificate root.75unsafe impl<T: NyxusData> NyxusData for Cell<T> {76    const __NYXUS_POLICY: [u8; 32] = cdk_rsx_memory_abi::semantic_source(77        "takt-owner-cell-v1",78        &[include_str!("v1.rs"), include_str!("cell.rs")],79    );80}8182/// Persisted optional data with a source-controlled tag. Borrowed projections83/// return ordinary transient Options; they never reinterpret this enum's bytes.84#[repr(C, u8)]85#[derive(86    Clone,87    Copy,88    Debug,89    Default,90    PartialEq,91    Eq,92    PartialOrd,93    Ord,94    NyxusData,95    cdk_rsx_memory_abi::Tagged,96)]97pub(crate) enum StoredOption<T> {98    #[default]99    None = 0,100    Some(T) = 1,101}102impl<T> StoredOption<T> {103    pub(crate) const fn is_some(&self) -> bool {104        matches!(self, Self::Some(_))105    }106    pub(crate) const fn is_none(&self) -> bool {107        !self.is_some()108    }109    pub(crate) const fn as_ref(&self) -> Option<&T> {110        match self {111            Self::None => None,112            Self::Some(value) => Some(value),113        }114    }115    pub(crate) const fn as_mut(&mut self) -> Option<&mut T> {116        match self {117            Self::None => None,118            Self::Some(value) => Some(value),119        }120    }121    pub(crate) fn as_deref(&self) -> Option<&T::Target>122    where123        T: std::ops::Deref,124    {125        self.as_ref().map(std::ops::Deref::deref)126    }127    pub(crate) fn into_option(self) -> Option<T> {128        match self {129            Self::None => None,130            Self::Some(value) => Some(value),131        }132    }133    pub(crate) fn map<U>(self, f: impl FnOnce(T) -> U) -> Option<U> {134        self.into_option().map(f)135    }136    pub(crate) fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool {137        self.into_option().is_none_or(f)138    }139    pub(crate) fn expect(self, message: &str) -> T {140        self.into_option().expect(message)141    }142    pub(crate) fn ok_or<E>(self, error: E) -> Result<T, E> {143        self.into_option().ok_or(error)144    }145    pub(crate) fn take(&mut self) -> Option<T> {146        std::mem::replace(self, Self::None).into_option()147    }148}149impl<T> From<Option<T>> for StoredOption<T> {150    fn from(value: Option<T>) -> Self {151        match value {152            None => Self::None,153            Some(value) => Self::Some(value),154        }155    }156}157impl<T> From<StoredOption<T>> for Option<T> {158    fn from(value: StoredOption<T>) -> Self {159        value.into_option()160    }161}162163#[repr(C)]164#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, NyxusData)]165pub struct Key {166    pub namespace: u64,167    pub execution: u64,168    pub node: u32,169    pub visit: u64,170    pub version: u32,171}172#[repr(u8)]173#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]174pub enum Safety {175    ReadOnly = 0,176    Idempotent = 1,177    Reconcile = 2,178}179#[repr(C, u8)]180#[derive(Clone, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]181pub enum Failure<E> {182    App(E) = 0,183    Unknown = 1,184    Timeout = 2,185    Capacity = 3,186}187#[repr(u8)]188#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]189pub enum BlockReason {190    Unknown = 0,191    Timeout = 1,192    RetryExhausted = 2,193    StorageLimit = 3,194}195#[repr(C, u8)]196#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]197pub enum Phase {198    Ready = 0,199    QueuedCall = 1,200    Calling = 2,201    Received = 3,202    RetryWait = 4,203    Waiting = 5,204    Awaiting = 6,205    Joining = 7,206    Blocked(BlockReason) = 8,207}208#[repr(u8)]209#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]210pub enum Transport {211    Reactor = 0,212    NativeUpdate = 1,213    NativeQuery = 2,214}215#[repr(u8)]216#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]217pub enum Priority {218    Interactive = 0,219    Maintenance = 1,220}221#[repr(C)]222#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData)]223pub struct ExternalAddress {224    pub canister: Principal,225    pub id: u64,226}227#[repr(u8)]228#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData, cdk_rsx_memory_abi::Tagged)]229pub enum EventKind {230    Entered = 0,231    AttemptStarted = 1,232    Received = 2,233    RetryScheduled = 3,234    Waiting = 4,235    Blocked = 5,236    Completed = 6,237    Failed = 7,238    Restored = 8,239}240#[repr(C)]241#[derive(Clone, Copy, Debug, PartialEq, Eq, NyxusData)]242pub struct TraceEvent {243    pub sequence: u64,244    pub at: u64,245    pub key: Key,246    pub kind: EventKind,247    pub attempt: u32,248}249250/// The exact prepared remote request, captured once before effect publication.251#[repr(C)]252#[derive(Clone, Debug, PartialEq, Eq, NyxusData)]253pub(crate) struct SavedRequest {254    pub canister: Principal,255    pub caller: Principal,256    pub route: String,257    pub reader_version: u32,258    pub args: SharedSlice<u8>,259    pub expires_at: StoredOption<u64>,260    pub transport: Transport,261    pub priority: Priority,262}263#[repr(C)]264#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, NyxusData)]265pub(crate) struct Work {266    pub execution: u64,267    pub node: u32,268    pub visit: u64,269}270#[repr(C)]271#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, NyxusData)]272pub(crate) struct WakeKey {273    pub at: u64,274    pub ticket: u64,275}276#[repr(C, u8)]277#[derive(Clone, Copy, Debug, NyxusData, cdk_rsx_memory_abi::Tagged)]278pub(crate) enum Wake {279    Node(Work) = 0,280    Expire(u64) = 1,281}282#[repr(C)]283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, NyxusData)]284pub(crate) struct CallIdentity {285    pub key: Key,286    pub attempt: u32,287}288#[repr(C)]289#[derive(Clone, Copy, NyxusData)]290pub(crate) struct Parent {291    pub node: u32,292    pub branch: u32,293}294#[repr(C, u8)]295#[derive(Clone, NyxusData, cdk_rsx_memory_abi::Tagged)]296pub(crate) enum SharedOutcome<D: NyxusData, E: NyxusData> {297    Ok(Rc<D>) = 0,298    Err(Failure<Rc<E>>) = 1,299}300#[repr(C, u8)]301#[derive(Clone, NyxusData, cdk_rsx_memory_abi::Tagged)]302pub(crate) enum SharedStatus<D: NyxusData, E: NyxusData> {303    Running = 0,304    Succeeded(Rc<D>) = 1,305    Failed(Failure<Rc<E>>) = 2,306}307#[repr(C)]308#[derive(Clone, NyxusData)]309pub(crate) struct Task<D: NyxusData, E: NyxusData> {310    pub key: Key,311    pub input: Rc<D>,312    pub safety: Safety,313    pub safe_until: StoredOption<u64>,314    pub retries: [u32; 16],315    pub attempt: u32,316    pub uncertain: bool,317    pub reply: StoredOption<SharedOutcome<D, E>>,318    pub request: StoredOption<Rc<SavedRequest>>,319    pub handler: bool,320    pub external: StoredOption<ExternalAddress>,321    pub next: StoredOption<u32>,322    pub resolved_through: u32,323}324#[repr(C)]325#[derive(Clone, NyxusData)]326pub(crate) struct Node<D: NyxusData, E: NyxusData> {327    pub id: u32,328    pub parent: StoredOption<Parent>,329    pub step: u32,330    pub data: Rc<D>,331    pub visit: u64,332    pub visit_finished: bool,333    pub phase: Phase,334    pub task: StoredOption<Task<D, E>>,335    pub wake: StoredOption<WakeKey>,336    pub queued: bool,337    pub continuation: StoredOption<u32>,338    pub producer: StoredOption<Principal>,339    pub children: StoredOption<SharedSlice<u32>>,340    pub results: StoredOption<Rc<Cell<Map<u32, SharedOutcome<D, E>>>>>,341    pub remaining: u32,342}343/// Sorted live nodes only. IDs remain the full monotonic execution-local u32;344/// neither their magnitude nor removed IDs determine allocation size.345#[repr(C)]346#[derive(NyxusData)]347pub(crate) struct NodeTable<D: NyxusData, E: NyxusData> {348    pub(super) entries: Vec<Node<D, E>>,349}350pub(crate) type Nodes<D, E> = Rc<Cell<NodeTable<D, E>>>;351#[repr(C)]352#[derive(Clone, NyxusData)]353pub(crate) struct Execution<D: NyxusData, E: NyxusData> {354    pub id: u64,355    pub version: u32,356    pub signature: StoredOption<[u8; 32]>,357    pub input: Rc<D>,358    pub created_at: u64,359    pub nodes: Nodes<D, E>,360    pub status: SharedStatus<D, E>,361    pub finished_at: StoredOption<u64>,362    pub expiry: StoredOption<WakeKey>,363    pub next_node: u32,364    pub history: StoredOption<Rc<Cell<Queue<TraceEvent>>>>,365    pub history_capacity: usize,366    pub trace_sequence: u64,367    pub trace_generation: u64,368}369#[repr(C)]370#[derive(NyxusData)]371pub struct State<D: NyxusData, E: NyxusData> {372    pub(crate) executions: Map<u64, Execution<D, E>>,373    pub(crate) results: Set<u64>,374    pub(crate) ready: Queue<Work>,375    pub(crate) calls: Queue<Work>,376    pub(crate) coordinated: Queue<Work>,377    pub(crate) wakes: Map<WakeKey, Wake>,378    pub(crate) physical: Set<CallIdentity>,379    pub(crate) prefer_coordinated: bool,380    pub(crate) next_id: u64,381    pub(crate) next_wake: u64,382    pub(crate) pending: u32,383    pub(crate) logical_calls: u32,384    pub(crate) active_calls: u32,385}386impl<D: NyxusData, E: NyxusData> Default for State<D, E> {387    fn default() -> Self {388        Self {389            executions: Map::new(),390            results: Set::new(),391            ready: Queue::new(),392            calls: Queue::new(),393            coordinated: Queue::new(),394            wakes: Map::new(),395            physical: Set::new(),396            prefer_coordinated: true,397            next_id: 0,398            next_wake: 0,399            pending: 0,400            logical_calls: 0,401            active_calls: 0,402        }403    }404}405406/// Persisted shared accounting and diagnostic totals; callbacks/leases stay407/// transient in the Runtime service and are reconstructed after binding.408#[repr(C)]409#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, NyxusData)]410pub struct RuntimeStats {411    pub pending: u32,412    pub logical_calls: u32,413    pub physical_calls: u32,414}415#[repr(C)]416#[derive(417    Clone, Copy, Debug, Default, PartialEq, Eq, NyxusData, cdk_rsx::WireType, serde::Serialize,418)]419pub struct WorkflowMetrics {420    pub entered: u64,421    pub completed: u64,422    pub failed: u64,423    pub attempts: u64,424    pub admitted: u64,425    pub succeeded: u64,426    pub failed_executions: u64,427}428#[repr(C)]429#[derive(NyxusData)]430pub struct RuntimeState {431    pub(crate) counts: RuntimeStats,432    pub(crate) metrics: WorkflowMetrics,433    pub(crate) tracing: Map<u64, bool>,434}435impl Default for RuntimeState {436    fn default() -> Self {437        Self {438            counts: Default::default(),439            metrics: Default::default(),440            tracing: Map::new(),441        }442    }443}444/// Opaque owner contract for the one shared canister-wide Takt Runtime.445#[cdk_rsx_store::memory(owner = crate::memory, data = RuntimeState, key = associated, sources = [include_str!("cell.rs"), include_str!("node_table.rs")])]446pub struct RuntimeMemory;447impl RuntimeMemory {448    pub fn create<'s>(449        scope: &cdk_rsx_store::Scope<'s>,450    ) -> cdk_rsx_store::Result<cdk_rsx_store::Detached<'s, Self>> {451        scope.create(&Self::KEY, RuntimeState::default())452    }453    pub(crate) fn bind(454        reference: cdk_rsx_store::ModuleRef<Self>,455    ) -> cdk_rsx_store::binding::Memory<Self> {456        cdk_rsx_store::binding::Memory::bind(reference, &Self::KEY)457    }458}