mod.rs

cdk-rsx/crates/cdk-rsx-rechain/src/idempotency/mod.rs

1//! Scoped Nyxus replay index; BLAKE3 field framing and 24-hour rules.2pub mod memory;3use crate::{Commit, CommitToken, Prepare};4use cdk_rsx::Principal;5use cdk_rsx_reactor::Result;6use cdk_rsx_store::{7    Access, ModuleRef, Scope,8    binding::{Memory as Binding, MemoryView},9};10use memory::v1::{ExpiryKey, Record};11use serde::Serialize;12use std::rc::Rc;13pub const WINDOW_NANOS: u64 = 86_400_000_000_000;14pub const MAX_PRUNE: usize = 1000;15mod identity;16pub use identity::{FINGERPRINT_FORMAT, fingerprint};17#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, Serialize, serde::Deserialize)]18pub struct Metadata {19    #[serde(with = "cdk_rsx::wire::bytes")]20    pub memo: Option<Vec<u8>>,21    pub created_at_time: Option<u64>,22    #[serde(rename = "expireAt")]23    pub expire_at: Option<u64>,24}25/// Scoped replay metadata. Exact memo bytes stay with the admitted request owner.26#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]27pub struct MetadataRef<'a> {28    #[serde(with = "cdk_rsx::wire::bytes")]29    pub memo: Option<&'a [u8]>,30    pub created_at_time: Option<u64>,31    #[serde(rename = "expireAt")]32    pub expire_at: Option<u64>,33}34impl Metadata {35    pub fn as_ref(&self) -> MetadataRef<'_> {36        MetadataRef {37            memo: self.memo.as_deref(),38            created_at_time: self.created_at_time,39            expire_at: self.expire_at,40        }41    }42}43#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, Serialize, serde::Deserialize)]44pub enum Error {45    DuplicateOf(u64),46    TooOld,47    CreatedInFuture { ledger_time: u64 },48    TransactionExpired { ledger_time: u64 },49    CreatedAtTimeRequired,50    Capacity { max_records: u64 },51}52#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, Serialize, serde::Deserialize)]53pub enum ReplayError<E> {54    Idempotency(Error),55    App(E),56}5758/// Scoped action fields; never includes receipt time in the fingerprint.59pub struct Request<'a> {60    pub caller: Principal,61    pub now: u64,62    pub metadata: Option<MetadataRef<'a>>,63    pub identity: &'a [u8],64}65pub trait Identify {66    fn request(&self) -> Request<'_>;67}6869pub struct Plan {70    now: u64,71    identity: Option<([u8; 32], u64)>,72}7374pub struct Idempotency {75    chain: u8,76    max_records: u64,77    state: Binding<memory::Memory>,78}79/// A read projection cannot construct a dispatch commit reducer:80/// ```compile_fail81/// use cdk_rsx_rechain::idempotency::Idempotency;82/// fn query(replay: &Idempotency, scope: &cdk_rsx_store::ReadScope<'_>) {83///     let _ = replay.view(scope).with(());84/// }85/// ```86pub struct View<'a, A: Access> {87    owner: &'a Idempotency,88    state: MemoryView<'a, A, memory::Memory>,89}90impl<A: Access> Copy for View<'_, A> {}91impl<A: Access> Clone for View<'_, A> {92    fn clone(&self) -> Self {93        *self94    }95}96impl Idempotency {97    pub fn bind(98        access: &impl Access,99        state: ModuleRef<memory::Memory>,100        chain: u8,101        max_records: u64,102    ) -> Result<Rc<Self>> {103        let state = memory::bind(state);104        {105            let view = state.view(access);106            let saved = view.read()?;107            if saved.chain != chain || saved.max_records != max_records {108                return Err(cdk_rsx_reactor::Error::InvalidInput(109                    "replay configuration differs from saved contract",110                ));111            }112        }113        Ok(Rc::new(Self {114            chain,115            max_records,116            state,117        }))118    }119    pub fn view<'a, A: Access>(&'a self, access: &'a A) -> View<'a, A> {120        View {121            owner: self,122            state: self.state.view(access),123        }124    }125}126impl<'a, 's> View<'a, Scope<'s>> {127    pub fn with<R>(&self, reducer: R) -> WithReplay<'a, 's, R> {128        WithReplay {129            view: *self,130            reducer,131        }132    }133    fn commit_plan(&self, plan: Plan, block: u64, authority: &CommitToken) -> Result<()> {134        if plan.identity.is_some() && self.owner.chain != authority.chain() {135            return Err(cdk_rsx_reactor::Error::InvalidInput(136                "idempotency belongs to another chain",137            ));138        }139        let mut state = self.state.write()?;140        for _ in 0..MAX_PRUNE {141            let Some(key) = state142                .expiration143                .first()144                .filter(|key| key.until <= plan.now)145                .copied()146            else {147                break;148            };149            state.expiration.pop_first();150            state.records.remove(&key.identity);151        }152        if let Some((identity, until)) = plan.identity {153            state.expiration.insert(ExpiryKey { identity, until });154            state.records.insert(identity, Record { block, until });155        }156        Ok(())157    }158}159impl<A: Access> View<'_, A> {160    pub fn retained_count(&self) -> Result<u64> {161        Ok(self.state.read()?.records.len() as u64)162    }163    pub fn next_expiry(&self) -> Result<Option<u64>> {164        Ok(self.state.read()?.expiration.first().map(|key| key.until))165    }166    pub fn prepare_request(167        &self,168        request: Request<'_>,169    ) -> Result<core::result::Result<Plan, Error>> {170        let now = request.now;171        let Some(metadata) = request.metadata else {172            return Ok(Ok(Plan {173                now,174                identity: None,175            }));176        };177        let state = self.state.read()?;178        let identity = if let Some(created) = metadata.created_at_time {179            if now as u128 >= created as u128 + WINDOW_NANOS as u128 {180                return Ok(Err(Error::TooOld));181            }182            if created > now {183                return Ok(Err(Error::CreatedInFuture { ledger_time: now }));184            }185            let identity = fingerprint(request.caller, metadata, request.identity);186            if let Some(record) = state.records.get(&identity) {187                if now < record.until {188                    return Ok(Err(Error::DuplicateOf(record.block)));189                }190            }191            Some((192                identity,193                created194                    .checked_add(WINDOW_NANOS)195                    .ok_or(cdk_rsx_reactor::Error::Overflow)?,196            ))197        } else {198            if metadata.memo.is_some() {199                return Ok(Err(Error::CreatedAtTimeRequired));200            }201            None202        };203        if metadata.expire_at.is_some_and(|until| until <= now) {204            return Ok(Err(Error::TransactionExpired { ledger_time: now }));205        }206        if identity.is_some() {207            let max = self.owner.max_records;208            let count = state.records.len() as u64;209            if max == 0 {210                return Ok(Err(Error::Capacity { max_records: max }));211            }212            if count >= max {213                let needed = count - max + 1;214                if needed > MAX_PRUNE as u64 {215                    return Ok(Err(Error::Capacity { max_records: max }));216                }217                let through = ExpiryKey {218                    until: now,219                    identity: [u8::MAX; 32],220                };221                let available = state222                    .expiration223                    .range(..=through)224                    .take(needed as usize)225                    .count() as u64;226                if available < needed {227                    return Ok(Err(Error::Capacity { max_records: max }));228                }229            }230        }231        Ok(Ok(Plan { now, identity }))232    }233}234pub struct WithReplay<'a, 's, R> {235    view: View<'a, Scope<'s>>,236    reducer: R,237}238impl<T: Identify, R: Prepare<T>> Prepare<T> for WithReplay<'_, '_, R> {239    type Error = ReplayError<R::Error>;240    type Plan = (Plan, R::Plan);241    fn prepare(&self, action: &T) -> Result<core::result::Result<Self::Plan, Self::Error>> {242        let replay = match self.view.prepare_request(action.request())? {243            Ok(plan) => plan,244            Err(error) => return Ok(Err(ReplayError::Idempotency(error))),245        };246        Ok(match self.reducer.prepare(action)? {247            Ok(plan) => Ok((replay, plan)),248            Err(error) => Err(ReplayError::App(error)),249        })250    }251}252impl<T: Identify, R: Commit<T>> Commit<T> for WithReplay<'_, '_, R> {253    fn commit(&self, plan: Self::Plan, block: u64, authority: &CommitToken) -> Result<()> {254        self.view.commit_plan(plan.0, block, authority)?;255        self.reducer.commit(plan.1, block, authority)256    }257}