Skip to main content

ic_backup/workflow/ic_snapshot_capture/
mod.rs

1//! One freshly reserved capture update under exact original stage evidence.
2
3use crate::{
4    model::{
5        ic_mutation::{IcMutationAcknowledgement, IcMutationRequest, IcMutationRequestError},
6        ic_request::{IcManagementMethodRecord, IcManagementRequestRecord},
7        operation_plan::OperationPlanError,
8    },
9    ops::persistence::{
10        AttemptJournalError, AttemptJournalGuard, ExecutionProgressPersistenceError,
11        ExecutionStageGuard, ExecutionWorkflowPersistenceError,
12    },
13    policy::ic_mutation::{IcMutationAssociationError, validate_acknowledgement},
14    ports::ic_mutation::{IcMutationProvider, IcMutationProviderError},
15};
16use thiserror::Error;
17
18/// Durably reserve an original capture, freshly admit it and submit one exact update.
19///
20/// Hold no attempt guards on entry. Only `TakeCanisterSnapshot` is accepted, with
21/// canonical original target/wire binding checked before spending. The existing
22/// journal is opened, never created, and complete original-plan admission owns its
23/// durable reservation. Keep the selected journal locked through fresh admission,
24/// one provider invocation and bounded passive acknowledgement association.
25/// Retained stage/ancestor checks bracket dispatch. Pending or Applied attempts
26/// cannot invoke admission or dispatch again; reopening grants no recapture.
27///
28/// The mandatory fallible `admit` callback must qualify fresh actual context/control,
29/// original capture consistency, quiescence/fence obligations and exclusive
30/// never-dispatched command custody. Any remote preflight calls need their own prior
31/// accounting. There is no default permission, provider or application consistency
32/// lane. The existing provider retains its authenticated single-update contract.
33/// Admission and submission are awaited while the selected journal stays locked.
34/// Cancellation releases that lock while retaining its pending reservation;
35/// even cancellation before dispatch grants no repeat callback or submission.
36///
37/// Success returns a bounded passive acknowledgement and leaves spending pending.
38/// Integrations authenticate exact original attribution and explicitly record any
39/// qualified receipt using the existing journal owner. An ID or matching wire reply
40/// supplies no automatic outcome, complete capture/download, terminal or fence release.
41/// # Errors
42/// Rejects noncapture/changed payloads, original evidence, spending, fresh admission,
43/// provider failures or malformed/mismatched replies. All post-reservation failures
44/// retain consumption; returned acknowledgements survive later rejection in typed
45/// errors. No failure permits retry, recapture, refund, cleanup or automatic uncertainty.
46pub async fn capture_snapshot<E: std::error::Error + 'static>(
47    stage: &ExecutionStageGuard<'_>,
48    operation_sequence: u64,
49    payload: &IcManagementRequestRecord,
50    provider: &mut impl IcMutationProvider,
51    admit: impl AsyncFnOnce(&IcMutationRequest<'_>) -> Result<(), E>,
52) -> Result<IcMutationAcknowledgement, IcSnapshotCaptureExecutionError<E>> {
53    if payload.method() != IcManagementMethodRecord::TakeCanisterSnapshot {
54        return Err(IcSnapshotCaptureExecutionError::CaptureRequired);
55    }
56    let plan = stage.plan();
57    let authority = plan.attempt_authority(operation_sequence)?;
58    payload
59        .validate_mutation_binding(authority.binding())
60        .map_err(IcMutationRequestError::from)?;
61    let mut journal = AttemptJournalGuard::open(stage.layout()?, &authority)?;
62    journal.reserve_planned_mutation(&plan.digest())?;
63    let request = IcMutationRequest::new(plan, operation_sequence, journal.record()?, payload)?;
64    admit(&request)
65        .await
66        .map_err(IcSnapshotCaptureExecutionError::Admission)?;
67    stage.layout()?;
68    let acknowledgement = provider
69        .submit_mutation(&request, journal.record()?)
70        .await?;
71    let admit_reply = || -> Result<(), IcSnapshotCaptureReplyError> {
72        validate_acknowledgement(&request, journal.record()?, &acknowledgement)?;
73        stage.layout()?;
74        Ok(())
75    };
76    match admit_reply() {
77        Ok(()) => Ok(acknowledgement),
78        Err(source) => Err(IcSnapshotCaptureExecutionError::AfterReply {
79            source,
80            acknowledgement: Box::new(acknowledgement),
81        }),
82    }
83}
84
85/// Capture-step failures retain original spending and any bounded returned acknowledgement.
86#[derive(Debug, Error)]
87pub enum IcSnapshotCaptureExecutionError<E: std::error::Error + 'static> {
88    /// Only the original capture method may enter this coordinator.
89    #[error("snapshot capture requires take_canister_snapshot")]
90    CaptureRequired,
91    /// Original operation authority cannot be derived.
92    #[error(transparent)]
93    Plan(#[from] OperationPlanError),
94    /// Workflow, stage or original ancestor evidence failed admission.
95    #[error(transparent)]
96    Stage(#[from] ExecutionWorkflowPersistenceError),
97    /// Original selected journal admission failed.
98    #[error(transparent)]
99    Journal(#[from] AttemptJournalError),
100    /// Complete original progress, prerequisites or durable reservation failed.
101    #[error(transparent)]
102    Progress(#[from] ExecutionProgressPersistenceError),
103    /// Canonical original mutation binding or current reservation differs.
104    #[error(transparent)]
105    Request(#[from] IcMutationRequestError),
106    /// Fresh integration-owned admission rejected after reservation.
107    #[error("fresh snapshot capture admission failed: {0}")]
108    Admission(#[source] E),
109    /// The single provider call failed; spending remains pending.
110    #[error(transparent)]
111    Provider(#[from] IcMutationProviderError),
112    /// Admission after a reply failed, retaining its complete bounded evidence.
113    #[error("snapshot capture reply rejected: {source}")]
114    AfterReply {
115        /// Typed original admission failure.
116        source: IcSnapshotCaptureReplyError,
117        /// Complete returned passive evidence, without settlement authority.
118        acknowledgement: Box<IcMutationAcknowledgement>,
119    },
120}
121
122/// Admission failure after a returned snapshot capture reply.
123#[derive(Debug, Error)]
124pub enum IcSnapshotCaptureReplyError {
125    /// Original selected journal cannot be re-admitted.
126    #[error(transparent)]
127    Journal(#[from] AttemptJournalError),
128    /// Passive exact reply association failed.
129    #[error(transparent)]
130    Association(#[from] IcMutationAssociationError),
131    /// Original stage or ancestor evidence cannot be re-admitted.
132    #[error(transparent)]
133    Stage(#[from] ExecutionWorkflowPersistenceError),
134}
135
136#[cfg(all(test, unix))]
137mod tests;