Skip to main content

ic_backup/workflow/ic_snapshot_upload/data/
mod.rs

1//! Complete finite original data uploads with explicit integration-qualified receipts.
2
3use super::{IcSnapshotUploadExecutionError, upload_snapshot_with};
4use crate::{
5    model::{
6        attempt_journal::MutationReceiptRequest,
7        evidence_digest::EvidenceDigest,
8        execution_workflow::ExecutionStagePredecessorRecord,
9        ic_mutation::IcMutationAcknowledgement,
10        ic_snapshot_upload::{
11            IcSnapshotDataUploadPlan, IcSnapshotDataUploadPlanningError, IcSnapshotUploadAttempt,
12        },
13    },
14    ops::persistence::{
15        AttemptJournalError, DownloadJournalGuard, ExecutionProgressPersistenceError,
16        ExecutionStageCheckpointError, ExecutionStageGuard, ExecutionWorkflowPersistenceError,
17        IcSnapshotUploadArtifactError, read_execution_progress,
18    },
19    ports::ic_snapshot_upload::IcSnapshotUploadProvider,
20};
21use thiserror::Error;
22
23/// Upload every exact original data operation, then checkpoint qualified reply evidence.
24///
25/// Prepare the source-derived data plan, allocation predecessor, retained stage and
26/// complete original journals first; hold no attempt guards. Empty plans and any prior
27/// consumption reject before dispatch: this is a fresh stage, never partial upload
28/// resume. Original source and destination/command custody remain integration-owned.
29/// Fresh guarded preparation buffers one payload and rechecks its immutable binding
30/// before existing single-upload reservation, mandatory fresh `admit` and one call.
31///
32/// `qualify` must independently authenticate exact original data-write attribution and
33/// durably retain original request/reply bytes before returning its explicit Applied
34/// receipt under the selected journal lock. An empty reply never supplies a receipt.
35/// Account remote qualification separately before its calls. Record through the sole
36/// attempt owner before the next dependency can dispatch; failures stop immediately.
37/// Admission, submission and qualification are async under their selected journal
38/// guards. Retain each exact reply before awaiting cancellable qualification work.
39/// Cancellation preserves source bytes/references, earlier Applied receipts and
40/// the current pending reservation, denying whole-stage or single-call reentry.
41///
42/// After all exact receipts, release journal locks and checkpoint the full original plan
43/// and ordered canonical request/raw-reply evidence through the existing stage owner.
44/// This is declared stage settlement, not authenticated whole-backend completeness,
45/// same-release load/start admission, terminal proof or fence/source-reference release.
46/// No hidden observation, reissue, refund, default provider or journal is added.
47/// # Errors
48/// Rejects changed originals, consumed attempts, source/preparation failures, spending,
49/// admission/provider/reply/qualification/receipt or checkpoint failure. Bounded returned
50/// replies survive post-reply rejection; spending, recorded receipts and source remain.
51pub async fn upload_snapshot_data<E: std::error::Error + 'static>(
52    stage: &ExecutionStageGuard<'_>,
53    upload: &IcSnapshotDataUploadPlan<'_, '_, '_>,
54    source: &DownloadJournalGuard<'_>,
55    snapshot: &str,
56    provider: &mut impl IcSnapshotUploadProvider,
57    mut admit: impl AsyncFnMut(&IcSnapshotUploadAttempt<'_, '_>) -> Result<(), E>,
58    mut qualify: impl AsyncFnMut(
59        &IcSnapshotUploadAttempt<'_, '_>,
60        &IcMutationAcknowledgement,
61    ) -> Result<MutationReceiptRequest, E>,
62) -> Result<ExecutionStagePredecessorRecord, IcSnapshotDataUploadExecutionError<E>> {
63    upload.validate_binding(stage.binding())?;
64    let plan = upload
65        .plan()
66        .ok_or(IcSnapshotDataUploadPlanningError::NoDataWrites)?;
67    if stage.plan() != plan {
68        return Err(IcSnapshotDataUploadPlanningError::OriginalMismatch.into());
69    }
70    let progress = read_execution_progress(stage.layout()?, &plan.digest())?;
71    if progress.attempts.mutations_used != 0 || progress.attempts.observations_used != 0 {
72        return Err(IcSnapshotDataUploadExecutionError::AlreadyAttempted);
73    }
74    let mut evidence = EvidenceDigest::new(b"ic-backup/ic-snapshot-data-upload/v1\0");
75    evidence.append(plan.digest().hash().as_bytes());
76    let session = source.upload_session(snapshot, upload)?;
77    for (index, kind) in upload.kinds().iter().enumerate() {
78        let sequence =
79            u64::try_from(index).map_err(|_| IcSnapshotDataUploadPlanningError::CountOverflow)?;
80        let payload = session.prepare(sequence, kind.clone())?;
81        // The single-call owner rechecks the exact full source/context/request before spending.
82        let (acknowledgement, settlement) = upload_snapshot_with(
83            stage,
84            sequence,
85            &payload,
86            provider,
87            &mut admit,
88            async |journal, request, admitted| {
89                let receipt = qualify(request, admitted.acknowledgement())
90                    .await
91                    .map_err(IcSnapshotDataUploadReplyError::Qualification)?;
92                let receipt = super::super::qualified_receipt::admit_applied(
93                    receipt,
94                    request.mutation_attempt(),
95                    payload.binding_digest().hash(),
96                )
97                .ok_or(IcSnapshotDataUploadReplyError::ReceiptRequired)?;
98                stage.layout()?;
99                journal.record_mutation(receipt)?;
100                stage.layout()?;
101                Ok::<_, IcSnapshotDataUploadReplyError<E>>(admitted.reply().digest())
102            },
103        )
104        .await?;
105        let digest =
106            settlement.map_err(|source| IcSnapshotDataUploadExecutionError::AfterReply {
107                operation_sequence: sequence,
108                source,
109                acknowledgement: Box::new(acknowledgement),
110            })?;
111        evidence.append(digest.hash().as_bytes());
112    }
113    session.finish()?;
114    let progress = read_execution_progress(stage.layout()?, &plan.digest())?;
115    if progress.applied_operations != upload.kinds().len() {
116        return Err(IcSnapshotDataUploadExecutionError::AlreadyAttempted);
117    }
118    Ok(stage.reconcile_checkpoint(evidence.finish())?)
119}
120
121/// Data-stage failure preserves source, original spending and returned acknowledgement bytes.
122#[derive(Debug, Error)]
123pub enum IcSnapshotDataUploadExecutionError<E: std::error::Error + 'static> {
124    /// Fresh-only entrypoint rejects any original consumed mutation or observation.
125    #[error("snapshot data upload original stage was already attempted")]
126    AlreadyAttempted,
127    /// Existing exact original data-plan/binding admission.
128    #[error(transparent)]
129    Planning(#[from] IcSnapshotDataUploadPlanningError),
130    /// Existing retained workflow/stage/ancestor admission.
131    #[error(transparent)]
132    Stage(#[from] ExecutionWorkflowPersistenceError),
133    /// Complete original progress admission.
134    #[error(transparent)]
135    Progress(#[from] ExecutionProgressPersistenceError),
136    /// Fresh exact source preparation failed before the selected operation reserves.
137    #[error(transparent)]
138    Source(#[from] IcSnapshotUploadArtifactError),
139    /// One exact original upload failed; its owner retains bounded returned evidence.
140    #[error(transparent)]
141    Upload(#[from] IcSnapshotUploadExecutionError<E>),
142    /// Receipt settlement failed after a bounded returned acknowledgement.
143    #[error("snapshot data upload reply rejected for operation {operation_sequence}: {source}")]
144    AfterReply {
145        /// Exact original failed operation sequence.
146        operation_sequence: u64,
147        /// Original qualification or persistence rejection.
148        source: IcSnapshotDataUploadReplyError<E>,
149        /// Exact bounded reply, without an inferred outcome.
150        acknowledgement: Box<IcMutationAcknowledgement>,
151    },
152    /// Existing all-Applied stage checkpoint failed; receipts and occupied evidence remain.
153    #[error(transparent)]
154    Checkpoint(#[from] ExecutionStageCheckpointError),
155}
156
157/// Post-reply data-write rejection, without a second outcome/accounting owner.
158#[derive(Debug, Error)]
159pub enum IcSnapshotDataUploadReplyError<E: std::error::Error + 'static> {
160    /// Independent attribution/authentication or durable original-byte retention failed.
161    #[error("snapshot data upload qualification failed: {0}")]
162    Qualification(#[source] E),
163    /// Require the explicit exact original Applied receipt.
164    #[error("snapshot data upload requires an explicit original Applied receipt")]
165    ReceiptRequired,
166    /// Original workflow/stage/ancestor admission failed.
167    #[error(transparent)]
168    Stage(#[from] ExecutionWorkflowPersistenceError),
169    /// Existing selected journal/receipt persistence failed.
170    #[error(transparent)]
171    Journal(#[from] AttemptJournalError),
172}