Skip to main content

ic_backup/model/ic_mutation/
mod.rs

1//! Exact reserved IC mutation identity and bounded passive reply association.
2
3use crate::model::attempt_journal::MutationReservation;
4use crate::model::ic_update_response::IcUpdateResponseInput;
5use crate::model::{
6    attempt_journal::{AttemptAuthorityRecord, AttemptJournalRecord},
7    ic_lifecycle_reply::MAX_IC_LIFECYCLE_REPLY_BYTES,
8    ic_request::{IcManagementRequestRecord, IcRequestError},
9    ic_snapshot_reply::MAX_IC_SNAPSHOT_REPLY_BYTES,
10    operation_plan::{OperationPlanError, OperationPlanRecord},
11};
12use std::fmt;
13use thiserror::Error;
14
15/// Maximum owned raw reply bytes, derived from both existing finite codec owners.
16pub const MAX_IC_MUTATION_REPLY_BYTES: usize =
17    if MAX_IC_SNAPSHOT_REPLY_BYTES < MAX_IC_LIFECYCLE_REPLY_BYTES {
18        MAX_IC_SNAPSHOT_REPLY_BYTES
19    } else {
20        MAX_IC_LIFECYCLE_REPLY_BYTES
21    };
22
23/// Structural request for one already reserved original host-ingress mutation.
24///
25/// Retained identity does not prove fresh permissions, prerequisites, application
26/// safety or exclusive custody. A pending reservation does not prove it was never
27/// dispatched. This request is not a dispatch permit or an interruption retry.
28#[derive(Debug)]
29pub struct IcMutationRequest<'a> {
30    plan: &'a OperationPlanRecord,
31    payload: &'a IcManagementRequestRecord,
32    reservation: MutationReservation,
33}
34
35impl<'a> IcMutationRequest<'a> {
36    /// Bind exact original plan, allowances and IC bytes after mutation reservation.
37    ///
38    /// Accepts only capture, load, start and stop; observations have separate
39    /// reservations. Derivation never creates a journal, spends or resets allowance.
40    /// # Errors
41    /// Rejects unknown operations, changed authority/bytes, absent pending mutation
42    /// or an observation already reserved for recovery.
43    pub fn new(
44        plan: &'a OperationPlanRecord,
45        operation_sequence: u64,
46        journal: &AttemptJournalRecord,
47        payload: &'a IcManagementRequestRecord,
48    ) -> Result<Self, IcMutationRequestError> {
49        let authority = plan.attempt_authority(operation_sequence)?;
50        if journal.authority() != &authority {
51            return Err(IcMutationRequestError::AuthorityMismatch);
52        }
53        payload.validate_mutation_binding(authority.binding())?;
54        let reservation = MutationReservation::new(
55            authority,
56            journal,
57            IcMutationRequestError::NoPendingMutation,
58            IcMutationRequestError::AuthorityMismatch,
59            IcMutationRequestError::MutationMismatch,
60            IcMutationRequestError::ObservationPending,
61        )?;
62        Ok(Self {
63            plan,
64            payload,
65            reservation,
66        })
67    }
68
69    /// Read original full context, inventory, selection and dependency declarations.
70    #[must_use]
71    pub const fn plan(&self) -> &OperationPlanRecord {
72        self.plan
73    }
74    /// Read exact management receiver, routing target, method and Candid argument bytes.
75    #[must_use]
76    pub const fn payload(&self) -> &'a IcManagementRequestRecord {
77        self.payload
78    }
79    /// Read canonical original identity and immutable mutation/observation limits.
80    #[must_use]
81    pub const fn authority(&self) -> &AttemptAuthorityRecord {
82        &self.reservation.authority
83    }
84    /// Read the original already consumed mutation attempt number.
85    #[must_use]
86    pub const fn mutation_attempt(&self) -> u32 {
87        self.reservation.mutation_attempt
88    }
89    /// Recheck the exact current pending reservation without IO or effect admission.
90    /// # Errors
91    /// Rejects different authority, replaced/settled mutation or observation recovery.
92    pub fn validate_journal(
93        &self,
94        journal: &AttemptJournalRecord,
95    ) -> Result<(), IcMutationRequestError> {
96        self.reservation.validate(
97            journal,
98            IcMutationRequestError::AuthorityMismatch,
99            IcMutationRequestError::MutationMismatch,
100            IcMutationRequestError::ObservationPending,
101        )
102    }
103}
104
105/// Immutable bounded passive acknowledgement; not a receipt or authenticated outcome.
106///
107/// No Serde or default admission exists. Raw bytes are hidden from Debug; explicit
108/// access retains exact evidence. Decoding happens in the existing method-specific
109/// reply owners during pure association, never in a second codec.
110#[derive(Clone)]
111pub struct IcMutationAcknowledgement {
112    input: IcUpdateResponseInput,
113}
114
115impl IcMutationAcknowledgement {
116    /// Admit finite attempt/raw-byte bounds and normalize the actual target identity.
117    /// # Errors
118    /// Rejects zero/excessive attempts, oversized raw replies and invalid principals.
119    pub fn new(mut input: IcUpdateResponseInput) -> Result<Self, IcMutationAcknowledgementError> {
120        input.admit(
121            MAX_IC_MUTATION_REPLY_BYTES,
122            IcMutationAcknowledgementError::InvalidAttempt,
123            IcMutationAcknowledgementError::ReplyTooLarge,
124            IcMutationAcknowledgementError::InvalidTarget,
125        )?;
126        Ok(Self { input })
127    }
128    /// Read canonical passive association fields and exact raw reply, without mutation access.
129    #[must_use]
130    pub const fn input(&self) -> &IcUpdateResponseInput {
131        &self.input
132    }
133}
134
135impl fmt::Debug for IcMutationAcknowledgement {
136    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137        self.input
138            .fmt_redacted(formatter, "IcMutationAcknowledgement")
139    }
140}
141
142/// Original reservation denial; no variant consumes, refunds or grants call authority.
143#[derive(Debug, Error)]
144pub enum IcMutationRequestError {
145    /// Journal differs from full original plan/context/operation/request/allowance identity.
146    #[error("IC mutation original authority mismatch")]
147    AuthorityMismatch,
148    /// There is no unresolved original mutation reservation.
149    #[error("IC mutation requires a pending original mutation")]
150    NoPendingMutation,
151    /// Current pending mutation changed or was settled after binding.
152    #[error("IC mutation original attempt mismatch")]
153    MutationMismatch,
154    /// Recovery observation is pending; association cannot bypass its original owner.
155    #[error("IC mutation has a pending recovery observation")]
156    ObservationPending,
157    /// Exact closed method, target or original Candid payload digest differs.
158    #[error(transparent)]
159    Payload(#[from] IcRequestError),
160    /// Original plan cannot derive the requested operation authority.
161    #[error(transparent)]
162    Plan(#[from] OperationPlanError),
163}
164
165/// Passive reply boundary denial with no raw payload in diagnostics.
166#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
167pub enum IcMutationAcknowledgementError {
168    /// Original attempt must be within the existing 1..=1,024 total-attempt bound.
169    #[error("invalid IC mutation acknowledgement attempt")]
170    InvalidAttempt,
171    /// Raw reply exceeded the existing finite codec byte bounds.
172    #[error("IC mutation acknowledgement reply too large")]
173    ReplyTooLarge,
174    /// Actual provider target is not a principal.
175    #[error("invalid IC mutation acknowledgement target")]
176    InvalidTarget,
177}
178
179#[cfg(test)]
180mod tests;