Skip to main content

ic_backup/workflow/ic_snapshot_download/
mod.rs

1//! Complete original planned data transfer with explicit integration-qualified receipts.
2
3use crate::model::data_stage_plan::SnapshotDataPlanningError;
4use crate::{
5    model::{
6        artifacts::ArtifactChecksumRecord,
7        attempt_journal::MutationReceiptRequest,
8        ic_snapshot_download::IcSnapshotDownloadPlan,
9        ic_snapshot_transfer_read::{
10            IcSnapshotTransferReadPayload, IcSnapshotTransferReadRequest,
11            IcSnapshotTransferReadResponse,
12        },
13    },
14    ops::persistence::{
15        AttemptJournalError, AttemptJournalGuard, ExecutionProgressPersistenceError,
16        ExecutionStageGuard, ExecutionWorkflowPersistenceError, IcSnapshotArtifactError,
17        IcSnapshotArtifactWriter, read_execution_progress,
18    },
19    policy::ic_snapshot_transfer_read::{IcSnapshotTransferReadReply, IcSnapshotTransferReadView},
20    ports::ic_snapshot_transfer_read::IcSnapshotTransferReadProvider,
21    workflow::ic_snapshot_transfer_read::{
22        IcSnapshotTransferReadExecutionError, read_snapshot_with,
23    },
24};
25use thiserror::Error;
26
27/// Stream every original data request into an existing private writer and publish it.
28///
29/// The metadata read and its independently qualified receipt/checkpoint must already
30/// exist. Prepare the metadata-derived data stage and its complete original journals,
31/// retain exact token/raw-ID association, then create the writer with exact raw metadata.
32/// Hold no attempt guards on entry. Read-free plans and any consumed original attempt
33/// reject; this is a fresh transfer, never partial-read resume or artifact recovery.
34///
35/// For every request, `admit` qualifies fresh access, metadata/command custody and
36/// application requirements under the existing single-read coordinator. `qualify`
37/// must independently authenticate exact original response attribution and return an
38/// explicit original Applied receipt. Wire shape alone cannot qualify that receipt.
39/// It runs under the same original journal lock held through dispatch and reuses
40/// that read's decoded reply. Append exact decoded bytes before
41/// the sole journal owner records that receipt; only then may the next dependent read
42/// run. Failed qualification, append or persistence stops without another provider call.
43/// Admission, submission and qualification are awaited under their selected journal
44/// guards. Retain each reply durably before cancellable qualification work. Dropping
45/// this future consumes the writer, retaining partial bytes, earlier receipts and
46/// the current pending reservation; it grants no resume or repeat-call authority.
47///
48/// All original limits/records remain unchanged. Errors consume the writer and preserve
49/// partial bytes, pending spending and every recorded receipt. Returned bounded replies
50/// survive post-read rejection. Success uses the existing fresh checksum/durable
51/// publisher, but supplies no immutable manifest/checkpoint, complete product backup,
52/// terminal proof, default provider, refund or fence/reference release. Stable bytes,
53/// complete authenticated backend transfer and application safety stay integration-owned.
54/// # Errors
55/// Rejects changed stage/plan/metadata/writer, prior consumption, spending, admission,
56/// provider or receipt failures, malformed replies and local IO/publication failure.
57pub async fn download_snapshot<E: std::error::Error + 'static>(
58    stage: &ExecutionStageGuard<'_>,
59    download: &IcSnapshotDownloadPlan<'_, '_>,
60    mut writer: IcSnapshotArtifactWriter<'_, '_, '_>,
61    provider: &mut impl IcSnapshotTransferReadProvider,
62    mut admit: impl AsyncFnMut(&IcSnapshotTransferReadRequest<'_, '_>) -> Result<(), E>,
63    mut qualify: impl AsyncFnMut(
64        &IcSnapshotTransferReadRequest<'_, '_>,
65        &IcSnapshotTransferReadResponse,
66    ) -> Result<MutationReceiptRequest, E>,
67) -> Result<ArtifactChecksumRecord, IcSnapshotDownloadExecutionError<E>> {
68    download.validate_binding(stage.binding())?;
69    let plan = download
70        .plan()
71        .ok_or(SnapshotDataPlanningError::NoDataOperations)?;
72    if stage.plan() != plan
73        || !download.matches_metadata(writer.coverage().metadata())
74        || writer.coverage().covered_region_bytes() != [0; 3]
75        || writer.coverage().covered_chunks() != 0
76    {
77        return Err(IcSnapshotDownloadExecutionError::OriginalMismatch);
78    }
79    writer.validate_transfer_origin(stage.layout()?.root(), plan.digest().hash())?;
80    let progress = read_execution_progress(stage.layout()?, &plan.digest())?;
81    if !progress.is_unattempted() {
82        return Err(IcSnapshotDownloadExecutionError::AlreadyAttempted);
83    }
84    // The plan constructor pairs each request with one ordered operation.
85    for (operation, payload) in plan.operations().iter().zip(download.requests()) {
86        let sequence = operation.operation_sequence();
87        let (response, result) = read_snapshot_with(
88            stage,
89            sequence,
90            IcSnapshotTransferReadPayload::Data(payload),
91            provider,
92            &mut admit,
93            async |journal, request, admitted| {
94                append_qualified(stage, journal, request, admitted, writer, &mut qualify).await
95            },
96        )
97        .await?;
98        writer = result.map_err(|source| IcSnapshotDownloadExecutionError::AfterReply {
99            operation_sequence: sequence,
100            source,
101            response: Box::new(response),
102        })?;
103    }
104    let progress = read_execution_progress(stage.layout()?, &plan.digest())?;
105    if !progress.all_applied() {
106        return Err(IcSnapshotDownloadExecutionError::AlreadyAttempted);
107    }
108    writer.validate_transfer_origin(stage.layout()?.root(), plan.digest().hash())?;
109    let checksum = writer.finish()?;
110    if let Err(source) = stage.layout() {
111        return Err(IcSnapshotDownloadExecutionError::AfterPublication { source, checksum });
112    }
113    Ok(checksum)
114}
115
116async fn append_qualified<'journal, 'layout, 'metadata, E: std::error::Error + 'static>(
117    stage: &ExecutionStageGuard<'_>,
118    journal: &mut AttemptJournalGuard<'_>,
119    request: &IcSnapshotTransferReadRequest<'_, '_>,
120    admitted: &IcSnapshotTransferReadView<'_, '_>,
121    writer: IcSnapshotArtifactWriter<'journal, 'layout, 'metadata>,
122    qualify: &mut impl AsyncFnMut(
123        &IcSnapshotTransferReadRequest<'_, '_>,
124        &IcSnapshotTransferReadResponse,
125    ) -> Result<MutationReceiptRequest, E>,
126) -> Result<IcSnapshotArtifactWriter<'journal, 'layout, 'metadata>, IcSnapshotDownloadReplyError<E>>
127{
128    let plan = stage.plan();
129    let receipt = qualify(request, admitted.response())
130        .await
131        .map_err(IcSnapshotDownloadReplyError::Qualification)?;
132    let writer = super::qualified_receipt::record_applied(
133        journal,
134        receipt,
135        request.mutation_attempt(),
136        request.payload().digest().hash(),
137        IcSnapshotDownloadReplyError::ReceiptRequired,
138        || {
139            writer.validate_transfer_origin(stage.layout()?.root(), plan.digest().hash())?;
140            let IcSnapshotTransferReadReply::Data(reply) = admitted.reply() else {
141                return Err(IcSnapshotDownloadReplyError::ReceiptRequired);
142            };
143            Ok(writer.append(reply)?)
144        },
145    )?;
146    stage.layout()?;
147    Ok(writer)
148}
149
150/// Failures preserve original spending and partial/published artifact evidence.
151#[derive(Debug, Error)]
152pub enum IcSnapshotDownloadExecutionError<E: std::error::Error + 'static> {
153    /// Exact retained writer, stage or metadata differs.
154    #[error("snapshot download originals differ")]
155    OriginalMismatch,
156    /// A prior attempt cannot be replayed by this fresh transfer entrypoint.
157    #[error("snapshot download original data stage was already attempted")]
158    AlreadyAttempted,
159    /// Existing original download plan/binding admission.
160    #[error(transparent)]
161    Planning(#[from] SnapshotDataPlanningError),
162    /// Existing retained stage/ancestor admission.
163    #[error(transparent)]
164    Stage(#[from] ExecutionWorkflowPersistenceError),
165    /// Complete original progress admission.
166    #[error(transparent)]
167    Progress(#[from] ExecutionProgressPersistenceError),
168    /// One original read failed; its owner retains any returned bounded reply.
169    #[error(transparent)]
170    Read(#[from] IcSnapshotTransferReadExecutionError<E>),
171    /// Canonical writer/checksum/durable publication failure.
172    #[error(transparent)]
173    Artifact(#[from] IcSnapshotArtifactError),
174    /// Rejection after a returned read retains the exact bounded response.
175    #[error("snapshot download reply rejected for operation {operation_sequence}: {source}")]
176    AfterReply {
177        /// Exact original data operation.
178        operation_sequence: u64,
179        /// Original rejection without undoing receipt or spending.
180        source: IcSnapshotDownloadReplyError<E>,
181        /// Exact bounded returned bytes and passive claims.
182        response: Box<IcSnapshotTransferReadResponse>,
183    },
184    /// Publication succeeded but stage re-admission failed; retain the published checksum.
185    #[error("snapshot download stage changed after publication: {source}")]
186    AfterPublication {
187        /// Retained stage/ancestor admission failure.
188        source: ExecutionWorkflowPersistenceError,
189        /// Existing durable publisher's returned checksum.
190        checksum: ArtifactChecksumRecord,
191    },
192}
193
194/// Rejection of a returned data reply while retaining its original attempt.
195#[derive(Debug, Error)]
196pub enum IcSnapshotDownloadReplyError<E: std::error::Error + 'static> {
197    /// Fresh authenticated exact attribution was not qualified by the integration.
198    #[error("snapshot download reply qualification failed: {0}")]
199    Qualification(#[source] E),
200    /// Require the explicit exact original Applied receipt, without outcome inference.
201    #[error("snapshot download requires an explicit original Applied receipt")]
202    ReceiptRequired,
203    /// Existing original stage admission.
204    #[error(transparent)]
205    Stage(#[from] ExecutionWorkflowPersistenceError),
206    /// Original selected journal/spending/receipt admission.
207    #[error(transparent)]
208    Journal(#[from] AttemptJournalError),
209    /// Exact local bytes/custody admission failed.
210    #[error(transparent)]
211    Artifact(#[from] IcSnapshotArtifactError),
212}
213
214#[cfg(test)]
215mod tests;