ic_backup/workflow/ic_snapshot_upload/allocation/mod.rs
1//! Original metadata allocation with independently qualified receipt and learned checkpoint.
2
3use super::{IcSnapshotUploadExecutionError, upload_snapshot_with};
4use crate::{
5 model::{
6 attempt_journal::MutationReceiptRequest,
7 execution_workflow::ExecutionStagePredecessorRecord,
8 ic_mutation::IcMutationAcknowledgement,
9 ic_snapshot_upload::{
10 IcSnapshotUploadAttempt, IcSnapshotUploadKind, IcSnapshotUploadRequest,
11 },
12 },
13 ops::persistence::{
14 AttemptJournalError, ExecutionStageCheckpointError, ExecutionStageGuard,
15 ExecutionWorkflowPersistenceError,
16 },
17 ports::ic_snapshot_upload::IcSnapshotUploadProvider,
18};
19use thiserror::Error;
20
21/// Allocate one new snapshot through an exact singleton original metadata stage.
22///
23/// Prepare the retained workflow/stage and complete original journals first; hold no
24/// attempt guards. Reuse [`super::upload_snapshot`] for exact source/payload binding, durable
25/// spending, mandatory fresh `admit` and one provider invocation. A pending or Applied
26/// allocation never dispatches again, including after failed checkpoint publication.
27///
28/// The mandatory `qualify` callback runs under the original journal lock. It must
29/// independently authenticate exclusive allocation attribution and durably retain the
30/// original request/reply bytes before returning its exact Applied receipt. Neither a
31/// decoded destination ID nor provider evidence supplies that qualification. Account
32/// any remote qualification independently before its calls; no default is installed.
33/// Admission, submission and qualification are async under their selected journal
34/// guards. Retain exact replies before cancellable qualification work. Cancellation
35/// keeps pending/Applied spending and denies allocation reentry; no runtime or `Send`
36/// bound is imposed by the core.
37///
38/// Record only that exact qualified receipt through the sole attempt owner, release
39/// the journal lock, then checkpoint the canonical allocation request/raw-reply digest.
40/// Return the bounded acknowledgement and original predecessor for explicit data-stage
41/// binding within the original workflow ceiling. Original source/metadata custody,
42/// destination attribution and data planning remain integration-owned. No data call,
43/// replacement, complete transfer, load/start, terminal or fence/reference release
44/// follows. Recovery reopens retained evidence and never repeats this allocation.
45/// # Errors
46/// Rejects non-metadata/non-singleton originals, spending/admission/provider/reply,
47/// qualification, receipt and checkpoint failures. Post-reply failures retain bounded
48/// acknowledgement bytes; spending, recorded outcomes and occupied evidence remain.
49pub async fn allocate_snapshot<E: std::error::Error + 'static>(
50 stage: &ExecutionStageGuard<'_>,
51 operation_sequence: u64,
52 payload: &IcSnapshotUploadRequest<'_>,
53 provider: &mut impl IcSnapshotUploadProvider,
54 admit: impl AsyncFnOnce(&IcSnapshotUploadAttempt<'_, '_>) -> Result<(), E>,
55 qualify: impl AsyncFnOnce(
56 &IcSnapshotUploadAttempt<'_, '_>,
57 &IcMutationAcknowledgement,
58 ) -> Result<MutationReceiptRequest, E>,
59) -> Result<
60 (IcMutationAcknowledgement, ExecutionStagePredecessorRecord),
61 IcSnapshotAllocationExecutionError<E>,
62> {
63 let operations = stage.plan().operations();
64 if !matches!(payload.kind(), IcSnapshotUploadKind::Metadata)
65 || operations.len() != 1
66 || operations[0].operation_sequence() != operation_sequence
67 || operations[0].request() != payload.binding_digest().hash()
68 {
69 return Err(IcSnapshotAllocationExecutionError::OriginalMismatch);
70 }
71 let (acknowledgement, settlement) = upload_snapshot_with(
72 stage,
73 operation_sequence,
74 payload,
75 provider,
76 admit,
77 async |journal, request, admitted| {
78 let receipt = qualify(request, admitted.acknowledgement())
79 .await
80 .map_err(IcSnapshotAllocationSettlementError::Qualification)?;
81 super::super::qualified_receipt::record_applied(
82 journal,
83 receipt,
84 request.mutation_attempt(),
85 payload.binding_digest().hash(),
86 IcSnapshotAllocationSettlementError::ReceiptRequired,
87 || {
88 stage.layout()?;
89 Ok(admitted.reply().digest())
90 },
91 )
92 },
93 )
94 .await?;
95 // The upload owner releases its journal before checkpoint admission locks it again.
96 super::super::qualified_receipt::checkpoint_reply(
97 stage,
98 acknowledgement,
99 settlement,
100 |source, acknowledgement| IcSnapshotAllocationExecutionError::AfterReply {
101 source,
102 acknowledgement,
103 },
104 )
105}
106
107/// Allocation coordination failures retain original spending and bounded returned bytes.
108#[derive(Debug, Error)]
109pub enum IcSnapshotAllocationExecutionError<E: std::error::Error + 'static> {
110 /// Original plan is not exactly this singleton metadata allocation.
111 #[error("snapshot allocation requires an exact singleton original metadata stage")]
112 OriginalMismatch,
113 /// Canonical single-upload failure, including bounded returned acknowledgements.
114 #[error(transparent)]
115 Upload(#[from] IcSnapshotUploadExecutionError<E>),
116 /// Receipt or checkpoint failed after reply; all originals remain retained.
117 #[error("snapshot allocation reply settlement failed: {source}")]
118 AfterReply {
119 /// Exact settlement rejection; no retry or refund follows.
120 source: IcSnapshotAllocationSettlementError<E>,
121 /// Original bounded reply and passive claims.
122 acknowledgement: Box<IcMutationAcknowledgement>,
123 },
124}
125
126/// Post-reply allocation rejection; no second accounting or outcome owner.
127#[derive(Debug, Error)]
128pub enum IcSnapshotAllocationSettlementError<E: std::error::Error + 'static> {
129 /// Independent authentication, attribution or durable original-byte retention failed.
130 #[error("snapshot allocation qualification failed: {0}")]
131 Qualification(#[source] E),
132 /// Require an independently qualified exact original Applied receipt.
133 #[error("snapshot allocation requires an explicit original Applied receipt")]
134 ReceiptRequired,
135 /// Original stage or ancestor admission failed.
136 #[error(transparent)]
137 Stage(#[from] ExecutionWorkflowPersistenceError),
138 /// Selected journal or receipt admission failed.
139 #[error(transparent)]
140 Journal(#[from] AttemptJournalError),
141 /// Canonical all-Applied checkpoint publication/re-admission failed.
142 #[error(transparent)]
143 Checkpoint(#[from] ExecutionStageCheckpointError),
144}
145
146#[cfg(all(test, unix))]
147mod tests;