reducer.rs
cdk-rsx/crates/cdk-rsx-rechain/src/reducer.rs
1//! Pure preparation followed by dispatch-authorized mutation.2use cdk_rsx_reactor::Result;34/// Only Rechain dispatch can construct this authority. Reducer implementations5/// require it for their commit method; application code exposes selectors and6/// dispatch, never its concrete reducers or prepared plans.7///8/// ```compile_fail9/// let token = cdk_rsx_rechain::CommitToken { chain: 0 };10/// ```11pub struct CommitToken {12 pub(crate) chain: u8,13}14impl CommitToken {15 pub fn chain(&self) -> u8 {16 self.chain17 }18}1920/// Implement on a service view with `A: Access`, so preparation has no write21/// capability. Read only its own memory, the action and immutable configuration.22pub trait Prepare<Action> {23 type Error;24 type Plan;25 fn prepare(&self, action: &Action) -> Result<core::result::Result<Self::Plan, Self::Error>>;26}27/// Implement separately with `A: MutAccess`. Expected rejections belong to28/// `prepare`; a storage/invariant failure here must abort the IC execution.29pub trait Commit<Action>: Prepare<Action> {30 fn commit(&self, plan: Self::Plan, block: u64, authority: &CommitToken) -> Result<()>;31}32impl<T> Prepare<T> for () {33 type Error = core::convert::Infallible;34 type Plan = ();35 fn prepare(&self, _: &T) -> Result<core::result::Result<(), Self::Error>> {36 Ok(Ok(()))37 }38}39impl<T> Commit<T> for () {40 fn commit(&self, _: (), _: u64, _: &CommitToken) -> Result<()> {41 Ok(())42 }43}44macro_rules! reducers {45 ($($name:ident:$index:tt),+) => {46 impl<Action,E,$($name),+> Prepare<Action> for ($($name,)+)47 where $($name: Prepare<Action,Error=E>,)+ {48 type Error=E; type Plan=($($name::Plan,)+);49 fn prepare(&self,action:&Action)->Result<core::result::Result<Self::Plan,E>> {50 $(let $name=match self.$index.prepare(action)? {Ok(plan)=>plan,Err(error)=>return Ok(Err(error))};)+51 Ok(Ok(($($name,)+)))52 }53 }54 impl<Action,E,$($name),+> Commit<Action> for ($($name,)+)55 where $($name: Commit<Action,Error=E>,)+ {56 fn commit(&self,plan:Self::Plan,block:u64,authority:&CommitToken)->Result<()> {57 $(self.$index.commit(plan.$index,block,authority)?;)+ Ok(())58 }59 }60 };61}62#[allow(non_snake_case)]63mod tuples {64 use super::*;65 reducers!(A:0,B:1);66 reducers!(A:0,B:1,C:2);67 reducers!(A:0,B:1,C:2,D:3);68 reducers!(A:0,B:1,C:2,D:3,Ee:4);69 reducers!(A:0,B:1,C:2,D:3,Ee:4,F:5);70}7172impl<Action, R: Prepare<Action> + ?Sized> Prepare<Action> for &R {73 type Error = R::Error;74 type Plan = R::Plan;75 fn prepare(&self, a: &Action) -> Result<core::result::Result<Self::Plan, Self::Error>> {76 (**self).prepare(a)77 }78}79impl<Action, R: Commit<Action> + ?Sized> Commit<Action> for &R {80 fn commit(&self, p: Self::Plan, b: u64, t: &CommitToken) -> Result<()> {81 (**self).commit(p, b, t)82 }83}