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