Skip to main content

ic_backup/workflow/ic_snapshot_transfer_read/
mod.rs

1//! One freshly reserved metadata/data update; no automatic receipt or retry.
2
3use crate::{
4    model::{
5        ic_snapshot_transfer_read::{
6            IcSnapshotTransferReadError, IcSnapshotTransferReadPayload,
7            IcSnapshotTransferReadRequest, IcSnapshotTransferReadResponse,
8        },
9        operation_plan::OperationPlanError,
10    },
11    ops::persistence::{
12        AttemptJournalError, AttemptJournalGuard, ExecutionProgressPersistenceError,
13        ExecutionStageGuard, ExecutionWorkflowPersistenceError,
14    },
15    policy::ic_snapshot_transfer_read::{
16        IcSnapshotTransferReadAssociationError, IcSnapshotTransferReadView, validate_response,
17    },
18    ports::{
19        ic_observation::IcObservationProviderError,
20        ic_snapshot_transfer_read::IcSnapshotTransferReadProvider,
21    },
22};
23use thiserror::Error;
24
25/// Durably reserve one original planned read, freshly admit it and invoke its provider once.
26///
27/// Hold no attempt guards on entry. The selected original journal remains locked
28/// through admission, dispatch and passive response association. Missing originals,
29/// pending attempts and unfulfilled prerequisites reject before provider invocation.
30/// This only accepts a newly reserved attempt; reconstructed pending requests are
31/// never dispatched. Every failure after reservation retains its consumed allowance.
32/// Admission and provider submission are awaited under that same selected guard.
33/// Dropping the future releases the guard without refunding or granting reentry.
34///
35/// `admit` must qualify actual fresh method-specific access, original metadata/raw-ID
36/// custody, current application requirements and exclusive never-dispatched command
37/// custody for this exact request. There is no default admission. Any remote preflight
38/// calls require their own prior accounting. The provider retains its existing
39/// authenticated single-update contract, without retries or hidden observations.
40///
41/// The returned bounded reply has only structural association. Integrations must
42/// independently authenticate it and explicitly use the existing journal receipt
43/// owner to record a qualified outcome. Even success leaves the attempt pending.
44/// No artifact, complete-transfer, fence or terminal/reference-release proof follows.
45/// # Errors
46/// Rejects changed originals, payloads, spending, fresh admission, provider failure
47/// or malformed/mismatched replies. Replies returned before a later rejection are
48/// retained in the error. No failure grants a repeat call, refund or cleanup.
49pub async fn read_snapshot<E: std::error::Error + 'static>(
50    stage: &ExecutionStageGuard<'_>,
51    operation_sequence: u64,
52    payload: IcSnapshotTransferReadPayload<'_, '_>,
53    provider: &mut impl IcSnapshotTransferReadProvider,
54    admit: impl AsyncFnOnce(&IcSnapshotTransferReadRequest<'_, '_>) -> Result<(), E>,
55) -> Result<IcSnapshotTransferReadResponse, IcSnapshotTransferReadExecutionError<E>> {
56    let (response, ()) = read_snapshot_with(
57        stage,
58        operation_sequence,
59        payload,
60        provider,
61        admit,
62        async |_, _, _| (),
63    )
64    .await?;
65    Ok(response)
66}
67
68// Complete a compound read while its original guard and decoded reply remain alive.
69// The continuation owns qualification and append/receipt ordering; checkpointing
70// happens only after this function has released the selected journal guard.
71pub(super) async fn read_snapshot_with<E: std::error::Error + 'static, T>(
72    stage: &ExecutionStageGuard<'_>,
73    operation_sequence: u64,
74    payload: IcSnapshotTransferReadPayload<'_, '_>,
75    provider: &mut impl IcSnapshotTransferReadProvider,
76    admit: impl AsyncFnOnce(&IcSnapshotTransferReadRequest<'_, '_>) -> Result<(), E>,
77    complete: impl AsyncFnOnce(
78        &mut AttemptJournalGuard<'_>,
79        &IcSnapshotTransferReadRequest<'_, '_>,
80        &IcSnapshotTransferReadView<'_, '_>,
81    ) -> T,
82) -> Result<(IcSnapshotTransferReadResponse, T), IcSnapshotTransferReadExecutionError<E>> {
83    let plan = stage.plan();
84    let authority = plan.attempt_authority(operation_sequence)?;
85    payload.validate_binding(&authority)?;
86    let mut journal = AttemptJournalGuard::open(stage.layout()?, &authority)?;
87    journal.reserve_planned_mutation(&plan.digest())?;
88    let request =
89        IcSnapshotTransferReadRequest::new(plan, operation_sequence, journal.record()?, payload)?;
90    admit(&request)
91        .await
92        .map_err(IcSnapshotTransferReadExecutionError::Admission)?;
93    stage.layout()?;
94    let response = provider.read_snapshot(&request, journal.record()?).await?;
95    let record = match journal.record() {
96        Ok(record) => record,
97        Err(source) => {
98            return Err(IcSnapshotTransferReadExecutionError::AfterReplyJournal {
99                source,
100                response: Box::new(response),
101            });
102        }
103    };
104    let admitted = match validate_response(&request, record, &response) {
105        Ok(admitted) => admitted,
106        Err(source) => {
107            return Err(IcSnapshotTransferReadExecutionError::Association {
108                source,
109                response: Box::new(response),
110            });
111        }
112    };
113    if let Err(source) = stage.layout() {
114        return Err(IcSnapshotTransferReadExecutionError::AfterReplyStage {
115            source,
116            response: Box::new(response),
117        });
118    }
119    let result = complete(&mut journal, &request, &admitted).await;
120    Ok((response, result))
121}
122
123/// Typed step failures retain original spending; returned raw replies remain available.
124#[derive(Debug, Error)]
125pub enum IcSnapshotTransferReadExecutionError<E: std::error::Error + 'static> {
126    /// The original operation cannot be derived.
127    #[error(transparent)]
128    Plan(#[from] OperationPlanError),
129    /// Retained workflow, stage or ancestors changed before dispatch.
130    #[error(transparent)]
131    Stage(#[from] ExecutionWorkflowPersistenceError),
132    /// Original journal admission or durable reservation failed.
133    #[error(transparent)]
134    Journal(#[from] AttemptJournalError),
135    /// Complete original progress, prerequisites or reservation failed.
136    #[error(transparent)]
137    Progress(#[from] ExecutionProgressPersistenceError),
138    /// Exact original payload/reservation admission failed.
139    #[error(transparent)]
140    Request(#[from] IcSnapshotTransferReadError),
141    /// Integration-owned fresh admission failed after durable reservation.
142    #[error("fresh snapshot read admission failed: {0}")]
143    Admission(#[source] E),
144    /// The single provider call failed; its reservation stays pending.
145    #[error(transparent)]
146    Provider(#[from] IcObservationProviderError),
147    /// Passive association rejected a bounded returned reply.
148    #[error("snapshot read response association failed: {source}")]
149    Association {
150        /// Canonical structural rejection.
151        source: IcSnapshotTransferReadAssociationError,
152        /// Exact bounded returned response, without authentication or outcome.
153        response: Box<IcSnapshotTransferReadResponse>,
154    },
155    /// Journal re-admission failed after a reply; retain the reply.
156    #[error("snapshot read journal changed after reply: {source}")]
157    AfterReplyJournal {
158        /// Original journal rejection.
159        source: AttemptJournalError,
160        /// Exact bounded returned response.
161        response: Box<IcSnapshotTransferReadResponse>,
162    },
163    /// Stage/ancestor re-admission failed after a reply; retain the reply.
164    #[error("snapshot read stage changed after reply: {source}")]
165    AfterReplyStage {
166        /// Original stage or ancestor rejection.
167        source: ExecutionWorkflowPersistenceError,
168        /// Exact bounded returned response.
169        response: Box<IcSnapshotTransferReadResponse>,
170    },
171}
172
173#[cfg(all(test, unix))]
174mod tests;