Skip to main content

canic_backup/runner/
types.rs

1use crate::{
2    execution::{BackupExecutionJournalOperation, BackupExecutionResumeSummary},
3    plan::{BackupExecutionPreflightReceipts, BackupPlan},
4};
5use serde::Serialize;
6use std::{error::Error as StdError, fmt, path::Path, path::PathBuf};
7use thiserror::Error as ThisError;
8
9use crate::persistence::JournalLockError;
10
11///
12/// BackupRunnerConfig
13///
14
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct BackupRunnerConfig {
17    pub out: PathBuf,
18    pub max_steps: Option<usize>,
19    pub updated_at: Option<String>,
20    pub tool_name: String,
21    pub tool_version: String,
22}
23
24///
25/// BackupRunnerExecutor
26///
27
28pub trait BackupRunnerExecutor {
29    /// Prove execution preflights before any mutating operation runs.
30    fn preflight_receipts(
31        &mut self,
32        plan: &BackupPlan,
33        preflight_id: &str,
34        validated_at: &str,
35        expires_at: &str,
36    ) -> Result<BackupExecutionPreflightReceipts, BackupRunnerCommandError>;
37
38    /// Stop one selected canister.
39    fn stop_canister(&mut self, canister_id: &str) -> Result<(), BackupRunnerCommandError>;
40
41    /// Start one selected canister.
42    fn start_canister(&mut self, canister_id: &str) -> Result<(), BackupRunnerCommandError>;
43
44    /// Create one selected canister snapshot and return the typed snapshot receipt.
45    fn create_snapshot(
46        &mut self,
47        canister_id: &str,
48    ) -> Result<BackupRunnerSnapshotReceipt, BackupRunnerCommandError>;
49
50    /// Download one selected snapshot into a temporary artifact directory.
51    fn download_snapshot(
52        &mut self,
53        canister_id: &str,
54        snapshot_id: &str,
55        artifact_path: &Path,
56    ) -> Result<(), BackupRunnerCommandError>;
57}
58
59///
60/// BackupRunnerSnapshotReceipt
61///
62
63#[derive(Clone, Debug, Eq, PartialEq)]
64pub struct BackupRunnerSnapshotReceipt {
65    pub snapshot_id: String,
66    pub taken_at_timestamp: Option<u64>,
67    pub total_size_bytes: Option<u64>,
68}
69
70///
71/// BackupRunnerCommandError
72///
73
74#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct BackupRunnerCommandError {
76    pub status: String,
77    pub message: String,
78}
79
80impl BackupRunnerCommandError {
81    #[must_use]
82    pub fn failed(status: impl Into<String>, message: impl Into<String>) -> Self {
83        Self {
84            status: status.into(),
85            message: message.into(),
86        }
87    }
88}
89
90impl fmt::Display for BackupRunnerCommandError {
91    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(formatter, "{}: {}", self.status, self.message)
93    }
94}
95
96impl StdError for BackupRunnerCommandError {}
97
98///
99/// BackupRunnerError
100///
101
102#[derive(Debug, ThisError)]
103pub enum BackupRunnerError {
104    #[error("backup execution journal is locked: {lock_path}")]
105    JournalLocked { lock_path: String },
106
107    #[error("backup operation {sequence} has no target canister")]
108    MissingOperationTarget { sequence: usize },
109
110    #[error("backup operation {sequence} has no snapshot id for target {target_canister_id}")]
111    MissingSnapshotId {
112        sequence: usize,
113        target_canister_id: String,
114    },
115
116    #[error(
117        "backup operation {sequence} has no artifact journal entry for target {target_canister_id}"
118    )]
119    MissingArtifactEntry {
120        sequence: usize,
121        target_canister_id: String,
122    },
123
124    #[error(
125        "backup operation {sequence} artifact temp path for target {target_canister_id} does not match expected runner path: journal={journal_path}, expected={expected_path}"
126    )]
127    ArtifactTempPathMismatch {
128        sequence: usize,
129        target_canister_id: String,
130        journal_path: String,
131        expected_path: String,
132    },
133
134    #[error("backup operation {sequence} failed: {status}: {message}")]
135    CommandFailed {
136        sequence: usize,
137        status: String,
138        message: String,
139    },
140
141    #[error("backup preflight failed: {status}: {message}")]
142    PreflightFailed { status: String, message: String },
143
144    #[error("backup execution has no operation ready to run")]
145    NoReadyOperation,
146
147    #[error("backup execution is blocked: {reasons:?}")]
148    Blocked { reasons: Vec<String> },
149
150    #[error(transparent)]
151    Io(#[from] std::io::Error),
152
153    #[error(transparent)]
154    Json(#[from] serde_json::Error),
155
156    #[error(transparent)]
157    Persistence(#[from] crate::persistence::PersistenceError),
158
159    #[error(transparent)]
160    BackupPlan(#[from] crate::plan::BackupPlanError),
161
162    #[error(transparent)]
163    ExecutionJournal(#[from] crate::execution::BackupExecutionJournalError),
164
165    #[error(transparent)]
166    Journal(#[from] crate::journal::JournalValidationError),
167
168    #[error(transparent)]
169    Checksum(#[from] crate::artifacts::ArtifactChecksumError),
170
171    #[error(transparent)]
172    Manifest(#[from] crate::manifest::ManifestValidationError),
173}
174
175impl From<JournalLockError> for BackupRunnerError {
176    fn from(error: JournalLockError) -> Self {
177        match error {
178            JournalLockError::Locked { lock_path } => Self::JournalLocked { lock_path },
179            JournalLockError::Io(error) => Self::Io(error),
180        }
181    }
182}
183
184///
185/// BackupRunResponse
186///
187
188#[derive(Clone, Debug, Serialize)]
189pub struct BackupRunResponse {
190    pub run_id: String,
191    pub plan_id: String,
192    pub backup_id: String,
193    pub complete: bool,
194    pub max_steps_reached: bool,
195    pub executed_operation_count: usize,
196    pub executed_operations: Vec<BackupRunExecutedOperation>,
197    pub execution: BackupExecutionResumeSummary,
198}
199
200///
201/// BackupRunExecutedOperation
202///
203
204#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
205pub struct BackupRunExecutedOperation {
206    pub sequence: usize,
207    pub operation_id: String,
208    pub kind: String,
209    pub target_canister_id: Option<String>,
210    pub outcome: String,
211}
212
213impl BackupRunExecutedOperation {
214    pub(super) fn completed(operation: &BackupExecutionJournalOperation) -> Self {
215        Self::from_operation(operation, "completed")
216    }
217
218    pub(super) fn failed(operation: &BackupExecutionJournalOperation) -> Self {
219        Self::from_operation(operation, "failed")
220    }
221
222    fn from_operation(operation: &BackupExecutionJournalOperation, outcome: &str) -> Self {
223        Self {
224            sequence: operation.sequence,
225            operation_id: operation.operation_id.clone(),
226            kind: format!("{:?}", operation.kind),
227            target_canister_id: operation.target_canister_id.clone(),
228            outcome: outcome.to_string(),
229        }
230    }
231}