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        journal.validate_pending_mutation(
96            &self.authority,
97            self.mutation_attempt,
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;