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 admit_reply = || {
96        let admitted = validate_response(&request, journal.record()?, &response)?;
97        stage.layout()?;
98        Ok::<_, IcSnapshotTransferReadReplyError>(admitted)
99    };
100    let admitted = match admit_reply() {
101        Ok(admitted) => admitted,
102        Err(source) => {
103            return Err(IcSnapshotTransferReadExecutionError::AfterReply {
104                source,
105                response: Box::new(response),
106            });
107        }
108    };
109    let result = complete(&mut journal, &request, &admitted).await;
110    Ok((response, result))
111}
112
113/// Typed step failures retain original spending; returned raw replies remain available.
114#[derive(Debug, Error)]
115pub enum IcSnapshotTransferReadExecutionError<E: std::error::Error + 'static> {
116    /// The original operation cannot be derived.
117    #[error(transparent)]
118    Plan(#[from] OperationPlanError),
119    /// Retained workflow, stage or ancestors changed before dispatch.
120    #[error(transparent)]
121    Stage(#[from] ExecutionWorkflowPersistenceError),
122    /// Original journal admission or durable reservation failed.
123    #[error(transparent)]
124    Journal(#[from] AttemptJournalError),
125    /// Complete original progress, prerequisites or reservation failed.
126    #[error(transparent)]
127    Progress(#[from] ExecutionProgressPersistenceError),
128    /// Exact original payload/reservation admission failed.
129    #[error(transparent)]
130    Request(#[from] IcSnapshotTransferReadError),
131    /// Integration-owned fresh admission failed after durable reservation.
132    #[error("fresh snapshot read admission failed: {0}")]
133    Admission(#[source] E),
134    /// The single provider call failed; its reservation stays pending.
135    #[error(transparent)]
136    Provider(#[from] IcObservationProviderError),
137    /// Admission after a reply failed, retaining its complete bounded evidence.
138    #[error("snapshot transfer read reply rejected: {source}")]
139    AfterReply {
140        /// Typed original admission failure.
141        source: IcSnapshotTransferReadReplyError,
142        /// Complete returned passive evidence, without settlement authority.
143        response: Box<IcSnapshotTransferReadResponse>,
144    },
145}
146
147/// Admission failure after a returned snapshot transfer read reply.
148#[derive(Debug, Error)]
149pub enum IcSnapshotTransferReadReplyError {
150    /// Original selected journal cannot be re-admitted.
151    #[error(transparent)]
152    Journal(#[from] AttemptJournalError),
153    /// Passive exact reply association failed.
154    #[error(transparent)]
155    Association(#[from] IcSnapshotTransferReadAssociationError),
156    /// Original stage or ancestor evidence cannot be re-admitted.
157    #[error(transparent)]
158    Stage(#[from] ExecutionWorkflowPersistenceError),
159}
160
161#[cfg(all(test, unix))]
162mod tests;