mod.rs

benches/rrt/canister/src/ledger/mod.rs

mod.rs374 lines← Benchmarks
1//! Source fourcans work reducer and its one bound dispatch composition.2use cdk_rsx_rechain::cleanup;3pub mod memory;4use cdk_rsx_store::{5    Access, ModuleRef, Scope,6    binding::{Memory as Binding, MemoryView},7};8pub mod selectors;9use crate::wire;10use cdk_rsx::Principal;11use cdk_rsx_reactor::Result;12use cdk_rsx_rechain::{13    Commit, CommitToken, Prepare,14    idempotency::{Idempotency, Identify, ReplayError, Request},15};16use std::rc::Rc;17pub struct Business<'a>(std::marker::PhantomData<&'a ()>);18impl<'a> cdk_rsx_rechain::Chain for Business<'a> {19    const ID: u8 = 0;20    type Action = Envelope<'a>;21    #[cfg(feature = "tripwire-workload")]22    fn record(23        action: &Envelope<'a>,24        _: &cdk_rsx_rechain::RecordContext,25        _: &[u8],26    ) -> core::result::Result<cdk_rsx_rechain::RecordedPayload, String> {27        crate::protocol::encode_prepared_action(&action.action, &action.identity)28            .map(cdk_rsx_rechain::RecordedPayload::new)29            .map_err(|error| error.to_string())30    }31}32struct Maintenance;33impl cdk_rsx_rechain::Chain for Maintenance {34    const ID: u8 = 1;35    type Action = MaintenanceAction;36}37#[derive(serde::Serialize)]38struct MaintenanceAction {39    caller: Principal,40    now: u64,41}42impl Identify for MaintenanceAction {43    fn request(&self) -> Request<'_> {44        Request {45            caller: self.caller,46            now: self.now,47            metadata: None,48            identity: &[],49        }50    }51}52/// Prepared transport identity is transient and absent from canonical payload.53pub struct Envelope<'a> {54    action: wire::ActionRef<'a>,55    now: u64,56    identity: Vec<u8>,57}58// Only the action is canonical; receipt time and prepared transport identity59// remain transient, exactly as the source dispatch contract requires.60impl serde::Serialize for Envelope<'_> {61    fn serialize<S: serde::Serializer>(62        &self,63        serializer: S,64    ) -> core::result::Result<S::Ok, S::Error> {65        serde::Serialize::serialize(&self.action, serializer)66    }67}68impl Identify for Envelope<'_> {69    fn request(&self) -> Request<'_> {70        Request {71            caller: self.action.caller,72            now: self.now,73            metadata: self.action.command.as_ref().map(|c| c.metadata),74            identity: &self.identity,75        }76    }77}78pub struct Work {79    state: Binding<memory::Memory>,80}81pub struct WorkView<'a, A: Access> {82    state: MemoryView<'a, A, memory::Memory>,83}84impl Work {85    pub fn bind(access: &impl Access, reference: ModuleRef<memory::Memory>) -> Result<Rc<Self>> {86        let state = memory::bind(reference);87        {88            let view = state.view(access);89            drop(view.read()?);90        }91        Ok(Rc::new(Self { state }))92    }93    pub fn view<'a, A: Access>(&'a self, access: &'a A) -> WorkView<'a, A> {94        WorkView {95            state: self.state.view(access),96        }97    }98}99pub struct Plan {100    counts: [u64; 5],101    total: u64,102    caller: Principal,103}104impl<A: Access> Prepare<Envelope<'_>> for WorkView<'_, A> {105    type Error = wire::BusinessError;106    type Plan = Plan;107    fn prepare(&self, e: &Envelope<'_>) -> Result<core::result::Result<Plan, Self::Error>> {108        use wire::BusinessError as Error;109        let state = self.state.read()?;110        if e.action.caller != state.owner {111            return Ok(Err(Error::Unauthorized));112        }113        let Some(command) = &e.action.command else {114            return Ok(Err(Error::Unauthorized));115        };116        let Some(units) = command.units.try_to_u64() else {117            return Ok(Err(Error::InvalidUnits));118        };119        if !(1..=1_000_000).contains(&units) {120            return Ok(Err(Error::InvalidUnits));121        }122        let Some(total) = state.total.checked_add(units) else {123            return Ok(Err(Error::InvalidUnits));124        };125        let mut counts = state.counts;126        let index = match command.kind {127            wire::Kind::Open => 0,128            wire::Kind::Reserve => 1,129            wire::Kind::Deliver => 2,130            wire::Kind::Close => 3,131            wire::Kind::Audit => 4,132        };133        let Some(next) = counts[index].checked_add(1) else {134            return Ok(Err(Error::InvalidUnits));135        };136        counts[index] = next;137        Ok(Ok(Plan {138            counts,139            total,140            caller: e.action.caller,141        }))142    }143}144impl Commit<Envelope<'_>> for WorkView<'_, Scope<'_>> {145    fn commit(&self, plan: Plan, _: u64, _: &CommitToken) -> Result<()> {146        let mut state = self.state.write()?;147        state.counts = plan.counts;148        state.total = plan.total;149        state.has_last_caller = true;150        state.last_caller = plan.caller;151        Ok(())152    }153}154pub struct Commands {155    chain: Rc<cdk_rsx_rechain::Runtime>,156    replay: Rc<Idempotency>,157    work: Rc<Work>,158    coordinator: Rc<cdk_rsx_takt::coordination::Coordinator>,159    cleanup: Rc<cleanup::Cleanup>,160    canister: Principal,161}162impl Commands {163    pub fn new(164        chain: Rc<cdk_rsx_rechain::Runtime>,165        replay: Rc<Idempotency>,166        work: Rc<Work>,167        coordinator: Rc<cdk_rsx_takt::coordination::Coordinator>,168        cleanup: Rc<cleanup::Cleanup>,169        canister: Principal,170    ) -> Self {171        Self {172            chain,173            replay,174            work,175            coordinator,176            cleanup,177            canister,178        }179    }180}181pub struct CommandsView<'a, A: Access> {182    commands: &'a Commands,183    access: &'a A,184}185impl Commands {186    pub fn view<'a, A: Access>(&'a self, access: &'a A) -> CommandsView<'a, A> {187        CommandsView {188            commands: self,189            access,190        }191    }192    pub fn cleanup_handle(&self) -> Rc<cleanup::Cleanup> {193        self.cleanup.clone()194    }195}196impl<A: Access> CommandsView<'_, A> {197    pub fn retained(&self) -> Result<cdk_rsx::wire::Nat> {198        Ok(self199            .commands200            .replay201            .view(self.access)202            .retained_count()?203            .into())204    }205    pub fn next_expiry(&self) -> Result<Option<u64>> {206        self.commands.replay.view(self.access).next_expiry()207    }208    pub fn cleanup_handle(&self) -> Rc<cleanup::Cleanup> {209        self.commands.cleanup.clone()210    }211}212impl CommandsView<'_, Scope<'_>> {213    pub fn dispatch(214        &self,215        caller: Principal,216        now: u64,217        command: wire::CommandRef<'_>,218    ) -> Result<wire::DispatchResult> {219        let timestamp = wire::NatBytes::new(now);220        let action = wire::ActionRef {221            caller,222            timestamp: wire::IntRef(false, timestamp.as_ref()),223            command: Some(command),224        };225        #[cfg(feature = "tripwire-workload")]226        let identity = crate::protocol::encode_command_option(&action.command)227            .map_err(|_| cdk_rsx_reactor::Error::InvalidInput("encode replay identity"))?;228        #[cfg(not(feature = "tripwire-workload"))]229        let identity = cdk_rsx_takt::encode_message(&action.command)230            .map_err(|_| cdk_rsx_reactor::Error::InvalidInput("encode replay identity"))?;231        let envelope = Envelope {232            action,233            now,234            identity,235        };236        let result = self237            .commands238            .chain239            .view(self.access)240            .dispatch::<Business, _>(241                &envelope,242                &self243                    .commands244                    .replay245                    .view(self.access)246                    .with(self.commands.work.view(self.access)),247                now,248                |envelope, block| {249                    let command = envelope.action.command.as_ref().expect("business action");250                    if command.kind == wire::Kind::Audit && !command.topic.is_empty() {251                        let payload = cdk_rsx_takt::encode_message(&command.job).map_err(|_| {252                            cdk_rsx_reactor::Error::InvalidInput("encode audit notice")253                        })?;254                        self.commands.coordinator.view(self.access).publish(255                            0,256                            block,257                            [cdk_rsx_takt::coordination::Publication {258                                key: command.topic.to_vec(),259                                payload,260                            }],261                        )?;262                    }263                    Ok(())264                },265            )?;266        self.commands267            .cleanup268            .changed(self.commands.replay.view(self.access).next_expiry()?);269        Ok(convert(result))270    }271    pub fn collect(272        &self,273        now: u64,274    ) -> Result<cdk_rsx_rechain::DispatchResult<ReplayError<wire::BusinessError>>> {275        let envelope = MaintenanceAction {276            caller: self.commands.canister,277            now,278        };279        let guard = PruneOnly {280            canister: self.commands.canister,281        };282        self.commands283            .chain284            .view(self.access)285            .dispatch::<Maintenance, _>(286                &envelope,287                &self.commands.replay.view(self.access).with(guard),288                now,289                |_, _| Ok(()),290            )291    }292}293struct PruneOnly {294    canister: Principal,295}296impl Prepare<MaintenanceAction> for PruneOnly {297    type Error = wire::BusinessError;298    type Plan = ();299    fn prepare(&self, e: &MaintenanceAction) -> Result<core::result::Result<(), Self::Error>> {300        Ok(if e.caller == self.canister {301            Ok(())302        } else {303            Err(wire::BusinessError::Unauthorized)304        })305    }306}307impl Commit<MaintenanceAction> for PruneOnly {308    fn commit(&self, _: (), _: u64, _: &CommitToken) -> Result<()> {309        Ok(())310    }311}312fn convert(313    value: cdk_rsx_rechain::DispatchResult<ReplayError<wire::BusinessError>>,314) -> wire::DispatchResult {315    use cdk_rsx_rechain::{DispatchError as D, LibraryError as L, idempotency::Error as I};316    use wire::{DispatchError as E, LibraryError as W, TransactionError as T};317    match value {318        Ok(id) => Ok(id.into()),319        Err(D::App(ReplayError::Idempotency(I::DuplicateOf(id)))) => Ok(id.into()),320        Err(D::App(ReplayError::App(e))) => Err(E::App(e)),321        Err(D::App(ReplayError::Idempotency(e))) => {322            Err(E::App(wire::BusinessError::Transaction(match e {323                I::DuplicateOf(id) => T::DuplicateOf(id.into()),324                I::TooOld => T::TooOld,325                I::CreatedInFuture { ledger_time } => T::CreatedInFuture(wire::LedgerTime {326                    ledger_time: ledger_time.into(),327                }),328                I::TransactionExpired { ledger_time } => T::TransactionExpired(wire::LedgerTime {329                    ledger_time: ledger_time.into(),330                }),331                I::CreatedAtTimeRequired => T::CreatedAtTimeRequired,332                I::Capacity { max_records } => T::IdempotencyCapacityExceeded(wire::ReplayCapacity {333                    max_records: max_records.into(),334                }),335            })))336        }337        Err(D::Rechain(e)) => Err(E::Rechain(match e {338            L::UnknownChain(_) => W::StorageUnavailable,339            L::StorageFull => W::StorageFull,340            L::PayloadEncodingFailed(e) => W::PayloadEncodingFailed(e),341            L::RecordTransformFailed(e) => W::RecordTransformFailed(e),342            L::ReadTransformFailed(e) => W::ReadTransformFailed(e),343            L::BlindingKeyUnavailable => W::BlindingKeyUnavailable,344            L::TransactionTooLarge {345                actual_bytes,346                max_bytes,347            } => W::TransactionTooLarge(wire::TransactionSize {348                actual_bytes: actual_bytes.into(),349                max_bytes: max_bytes.into(),350            }),351        })),352    }353}354pub fn chains() -> [cdk_rsx_rechain::ChainConfig<'static>; 2] {355    use cdk_rsx_rechain::{ChainConfig, Limits};356    [357        ChainConfig::of::<Business>(358            "work",359            "Five benchmark actions, committed once",360            Limits::default(),361        ),362        ChainConfig::of::<Maintenance>(363            "maintenance",364            "Bounded fingerprint pruning",365            Limits {366                record: false,367                ..Default::default()368            },369        ),370    ]371}372373#[cfg(test)]374mod tests;