1use crate::model::evidence_digest::EvidenceDigest;
4mod authority;
5mod history;
6pub use authority::{
7 AttemptAuthorityRecord, AttemptBudgetRecord, MAX_OPERATION_ATTEMPTS, OperationBindingRecord,
8 OperationBindingRequest,
9};
10
11use crate::model::{
12 artifacts::{ArtifactChecksumRecord, ChecksumError, canonical_hash},
13 bounded_sequence,
14};
15use history::{AttemptEventRecord, Projection};
16use serde::{Deserialize, Deserializer, Serialize};
17use thiserror::Error;
18
19pub const MAX_ATTEMPT_EVENTS: usize = 2048;
21pub const MAX_ATTEMPT_JOURNAL_BYTES: u64 = 1024 * 1024;
23
24#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
26#[serde(rename_all = "snake_case")]
27pub enum MutationOutcomeRecord {
28 Applied,
30 NotApplied,
32}
33
34#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
36#[serde(rename_all = "snake_case")]
37pub enum ObservationOutcomeRecord {
38 Applied,
40 NotApplied,
42 Uncertain,
44}
45
46#[derive(Clone, Debug)]
48pub struct MutationReceiptRequest {
49 pub attempt: u32,
51 pub request: String,
53 pub outcome: MutationOutcomeRecord,
55 pub evidence: String,
57}
58
59#[derive(Clone, Debug)]
65pub struct ObservationReceiptRequest {
66 pub attempt: u32,
68 pub request: String,
70 pub outcome: ObservationOutcomeRecord,
72 pub evidence: String,
74}
75
76#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
78pub struct AttemptJournalView {
79 pub authority: ArtifactChecksumRecord,
81 pub mutations_used: u32,
83 pub observations_used: u32,
85 pub mutations_remaining: u32,
87 pub observations_remaining: u32,
89 pub pending_mutation: Option<u32>,
91 pub pending_observation: Option<u32>,
93 pub applied: bool,
95 pub history_len: usize,
97}
98
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104pub enum AppliedReceiptEvidence<'a> {
105 Mutation {
107 attempt: u32,
109 evidence: &'a str,
111 },
112 Observation {
114 attempt: u32,
116 request: &'a str,
118 evidence: &'a str,
120 },
121}
122
123#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
125#[serde(try_from = "JournalFields")]
126pub struct AttemptJournalRecord {
127 version: u16,
128 authority: AttemptAuthorityRecord,
129 events: Vec<AttemptEventRecord>,
130 #[serde(skip)]
131 projection: Projection,
132}
133
134#[derive(Deserialize)]
135#[serde(deny_unknown_fields)]
136struct JournalFields {
137 version: u16,
138 authority: AttemptAuthorityRecord,
139 #[serde(deserialize_with = "bounded_events")]
140 events: Vec<AttemptEventRecord>,
141}
142
143impl TryFrom<JournalFields> for AttemptJournalRecord {
144 type Error = AttemptJournalRecordError;
145 fn try_from(mut fields: JournalFields) -> Result<Self, Self::Error> {
146 if fields.version != 1 {
147 return Err(AttemptJournalRecordError::UnsupportedVersion(
148 fields.version,
149 ));
150 }
151 let mut projection = Projection::empty();
152 for event in &mut fields.events {
153 event.normalize()?;
154 projection.apply(event, fields.authority.budget())?;
155 }
156 Ok(Self {
157 version: 1,
158 authority: fields.authority,
159 events: fields.events,
160 projection,
161 })
162 }
163}
164
165impl AttemptJournalRecord {
166 #[must_use]
168 pub const fn new(authority: AttemptAuthorityRecord) -> Self {
169 Self {
170 version: 1,
171 authority,
172 events: Vec::new(),
173 projection: Projection::empty(),
174 }
175 }
176 #[must_use]
178 pub const fn authority(&self) -> &AttemptAuthorityRecord {
179 &self.authority
180 }
181 pub(crate) fn validate_pending_mutation<E>(
184 &self,
185 authority: &AttemptAuthorityRecord,
186 mutation_attempt: u32,
187 authority_mismatch: E,
188 mutation_mismatch: E,
189 observation_pending: E,
190 ) -> Result<(), E> {
191 if self.authority() != authority {
192 return Err(authority_mismatch);
193 }
194 let current = self.view();
195 if current.pending_mutation != Some(mutation_attempt) {
196 return Err(mutation_mismatch);
197 }
198 if current.pending_observation.is_some() {
199 return Err(observation_pending);
200 }
201 Ok(())
202 }
203 #[must_use]
208 pub fn pending_observation_request(&self) -> Option<&str> {
209 self.projection
210 .pending_observation
211 .as_ref()
212 .map(|pending| pending.request.as_str())
213 }
214 #[must_use]
218 pub fn applied_receipt(&self) -> Option<AppliedReceiptEvidence<'_>> {
219 match self.events.last()? {
220 AttemptEventRecord::MutationResolved {
221 mutation,
222 outcome: MutationOutcomeRecord::Applied,
223 evidence,
224 } => Some(AppliedReceiptEvidence::Mutation {
225 attempt: *mutation,
226 evidence,
227 }),
228 AttemptEventRecord::ObservationRecorded {
229 observation,
230 request,
231 outcome: ObservationOutcomeRecord::Applied,
232 evidence,
233 } => Some(AppliedReceiptEvidence::Observation {
234 attempt: *observation,
235 request,
236 evidence,
237 }),
238 _ => None,
239 }
240 }
241 #[must_use]
246 pub fn view(&self) -> AttemptJournalView {
247 AttemptJournalView {
248 authority: self.authority.digest(),
249 mutations_used: self.projection.mutations_used,
250 observations_used: self.projection.observations_used,
251 mutations_remaining: self.authority.budget().mutations()
252 - self.projection.mutations_used,
253 observations_remaining: self.authority.budget().observations()
254 - self.projection.observations_used,
255 pending_mutation: self.projection.pending_mutation,
256 pending_observation: self
257 .projection
258 .pending_observation
259 .as_ref()
260 .map(|pending| pending.attempt),
261 applied: self.projection.applied,
262 history_len: self.events.len(),
263 }
264 }
265 #[must_use]
271 pub fn digest(&self) -> ArtifactChecksumRecord {
272 let mut bytes = EvidenceDigest::new(b"ic-backup/attempt-journal-history/v1\0");
273 bytes.append(self.authority.digest().hash().as_bytes());
274 bytes.append(&(self.events.len() as u64).to_be_bytes());
275 for event in &self.events {
276 event.append_digest_bytes(&mut bytes);
277 }
278 bytes.finish()
279 }
280 pub(crate) fn reserve_mutation(&mut self) -> Result<u32, AttemptJournalRecordError> {
281 let attempt = self.projection.next_attempt;
282 self.append(AttemptEventRecord::MutationReserved { attempt })?;
283 Ok(attempt)
284 }
285 pub(crate) fn reserve_observation(
286 &mut self,
287 mutation: u32,
288 request: &str,
289 ) -> Result<u32, AttemptJournalRecordError> {
290 let attempt = self.projection.next_attempt;
291 self.append(AttemptEventRecord::ObservationReserved {
292 attempt,
293 mutation,
294 request: request.to_owned(),
295 })?;
296 Ok(attempt)
297 }
298 pub(crate) fn record_mutation(
299 &mut self,
300 receipt: MutationReceiptRequest,
301 ) -> Result<(), AttemptJournalRecordError> {
302 if canonical_hash(&receipt.request)? != self.authority.binding().request() {
303 return Err(AttemptJournalRecordError::RequestMismatch);
304 }
305 self.append(AttemptEventRecord::MutationResolved {
306 mutation: receipt.attempt,
307 outcome: receipt.outcome,
308 evidence: receipt.evidence,
309 })
310 }
311 pub(crate) fn record_observation(
312 &mut self,
313 receipt: ObservationReceiptRequest,
314 ) -> Result<(), AttemptJournalRecordError> {
315 self.append(AttemptEventRecord::ObservationRecorded {
316 observation: receipt.attempt,
317 request: receipt.request,
318 outcome: receipt.outcome,
319 evidence: receipt.evidence,
320 })
321 }
322 fn append(&mut self, mut event: AttemptEventRecord) -> Result<(), AttemptJournalRecordError> {
323 if self.events.len() == MAX_ATTEMPT_EVENTS {
324 return Err(AttemptJournalRecordError::HistoryTooLarge);
325 }
326 event.normalize()?;
327 let mut projection = self.projection.clone();
328 projection.apply(&event, self.authority.budget())?;
329 self.events.push(event);
330 self.projection = projection;
331 Ok(())
332 }
333}
334
335fn bounded_events<'de, D: Deserializer<'de>>(
336 deserializer: D,
337) -> Result<Vec<AttemptEventRecord>, D::Error> {
338 bounded_sequence::deserialize::<_, _, MAX_ATTEMPT_EVENTS>(
339 deserializer,
340 "a bounded chronological attempt event list",
341 AttemptJournalRecordError::HistoryTooLarge,
342 )
343}
344
345#[derive(Debug, Error)]
347pub enum AttemptJournalRecordError {
348 #[error("unsupported attempt journal version {0}")]
350 UnsupportedVersion(u16),
351 #[error("attempt allowance exceeds {MAX_OPERATION_ATTEMPTS}")]
353 BudgetTooLarge,
354 #[error("attempt history exceeds {MAX_ATTEMPT_EVENTS} events")]
356 HistoryTooLarge,
357 #[error("invalid attempt operation principal")]
359 InvalidPrincipal,
360 #[error(transparent)]
362 Checksum(#[from] ChecksumError),
363 #[error("mutation attempt {attempt} remains unresolved")]
365 MutationPending {
366 attempt: u32,
368 },
369 #[error("observation attempt {attempt} remains unresolved")]
371 ObservationPending {
372 attempt: u32,
374 },
375 #[error("no pending mutation attempt")]
377 NoPendingMutation,
378 #[error("no pending observation attempt")]
380 NoPendingObservation,
381 #[error("attempt identity mismatch: expected {expected}, actual {actual}")]
383 AttemptMismatch {
384 expected: u32,
386 actual: u32,
388 },
389 #[error("attempt request digest mismatch")]
391 RequestMismatch,
392 #[error("mutation attempt allowance exhausted")]
394 MutationBudgetExhausted,
395 #[error("observation attempt allowance exhausted")]
397 ObservationBudgetExhausted,
398 #[error("operation application already retained")]
400 AlreadyApplied,
401}
402
403#[cfg(test)]
404mod tests;