Skip to main content

oxirs_cluster/backup/
executor.rs

1//! Backup policy executor with structured audit log.
2//!
3//! `BackupExecutor` consumes a `BackupPolicy` and writes backup artefacts to
4//! the configured `DestinationConfig`.  Every operation (start, complete,
5//! fail, prune) is appended to an in-memory audit log that callers can query.
6
7use std::path::Path;
8use std::sync::{Mutex, MutexGuard};
9use std::time::{Duration, SystemTime};
10
11use thiserror::Error;
12
13use super::policy::BackupPolicy;
14
15// ---------------------------------------------------------------------------
16// Audit types
17// ---------------------------------------------------------------------------
18
19/// A single entry in the backup audit log.
20#[derive(Debug)]
21pub struct BackupAuditEntry {
22    /// When this entry was recorded.
23    pub timestamp: SystemTime,
24    /// Name of the policy that triggered this action.
25    pub policy_name: String,
26    /// What happened.
27    pub action: AuditAction,
28    /// Bytes written (only set for `BackupCompleted`).
29    pub size_bytes: Option<u64>,
30    /// Error message (only set for `BackupFailed`).
31    pub error: Option<String>,
32}
33
34/// Discriminant for audit log entries.
35#[derive(Debug)]
36pub enum AuditAction {
37    /// A backup has been initiated.
38    BackupStarted,
39    /// A backup completed successfully.
40    BackupCompleted,
41    /// A backup failed.
42    BackupFailed,
43    /// An old backup artefact was removed during retention enforcement.
44    RetentionPruned {
45        /// Identifier of the backup that was pruned.
46        backup_id: u64,
47    },
48}
49
50impl AuditAction {
51    fn label(&self) -> &'static str {
52        match self {
53            AuditAction::BackupStarted => "Started",
54            AuditAction::BackupCompleted => "Completed",
55            AuditAction::BackupFailed => "Failed",
56            AuditAction::RetentionPruned { .. } => "Pruned",
57        }
58    }
59}
60
61// ---------------------------------------------------------------------------
62// Errors
63// ---------------------------------------------------------------------------
64
65/// Errors produced by `BackupExecutor`.
66#[derive(Debug, Error)]
67pub enum BackupError {
68    /// A filesystem I/O error.
69    #[error("IO error: {0}")]
70    IoError(String),
71    /// The backup was written but post-write verification failed.
72    #[error("Verification failed: {0}")]
73    VerificationFailed(String),
74}
75
76// ---------------------------------------------------------------------------
77// Executor
78// ---------------------------------------------------------------------------
79
80/// Policy-driven backup executor with an append-only audit log.
81pub struct BackupExecutor {
82    /// Thread-safe append-only audit log.
83    audit_log: Mutex<Vec<BackupAuditEntry>>,
84}
85
86impl BackupExecutor {
87    /// Create a new executor with an empty audit log.
88    pub fn new() -> Self {
89        BackupExecutor {
90            audit_log: Mutex::new(Vec::new()),
91        }
92    }
93
94    /// Execute a backup according to `policy`.
95    ///
96    /// Writes `data` as a single flat file under `destination`.  The file
97    /// name embeds the current Unix timestamp to prevent collisions.
98    ///
99    /// Returns the number of bytes written on success.
100    pub fn execute_backup(
101        &self,
102        policy: &BackupPolicy,
103        data: &[u8],
104        destination: &Path,
105    ) -> Result<u64, BackupError> {
106        self.append_audit(policy.name.clone(), AuditAction::BackupStarted, None, None);
107
108        // Build a unique file name based on current timestamp
109        let ts_secs = SystemTime::now()
110            .duration_since(SystemTime::UNIX_EPOCH)
111            .unwrap_or(Duration::ZERO)
112            .as_secs();
113        let dest_file = destination.join(format!("backup_{}.bin", ts_secs));
114
115        // Ensure the destination directory exists
116        if let Err(e) = std::fs::create_dir_all(destination) {
117            let msg = format!("create_dir_all failed: {e}");
118            self.append_audit(
119                policy.name.clone(),
120                AuditAction::BackupFailed,
121                None,
122                Some(msg.clone()),
123            );
124            return Err(BackupError::IoError(msg));
125        }
126
127        // Write the backup artefact
128        if let Err(e) = std::fs::write(&dest_file, data) {
129            let msg = format!("write failed: {e}");
130            self.append_audit(
131                policy.name.clone(),
132                AuditAction::BackupFailed,
133                None,
134                Some(msg.clone()),
135            );
136            return Err(BackupError::IoError(msg));
137        }
138
139        let size = data.len() as u64;
140        self.append_audit(
141            policy.name.clone(),
142            AuditAction::BackupCompleted,
143            Some(size),
144            None,
145        );
146
147        Ok(size)
148    }
149
150    /// Record that a backup artefact was pruned by retention enforcement.
151    pub fn record_prune(&self, policy_name: &str, backup_id: u64) {
152        self.append_audit(
153            policy_name.to_owned(),
154            AuditAction::RetentionPruned { backup_id },
155            None,
156            None,
157        );
158    }
159
160    /// Return a human-readable snapshot of the audit log.
161    ///
162    /// Format: `"<policy>: <unix_ts> — <action>"`
163    pub fn audit_entries(&self) -> Vec<String> {
164        self.lock_log()
165            .iter()
166            .map(|e| {
167                let ts = e
168                    .timestamp
169                    .duration_since(SystemTime::UNIX_EPOCH)
170                    .unwrap_or(Duration::ZERO)
171                    .as_secs();
172                format!("{}: {} — {}", e.policy_name, ts, e.action.label())
173            })
174            .collect()
175    }
176
177    /// Raw access to the audit log entries (useful for tests).
178    pub fn raw_audit_log(&self) -> Vec<String> {
179        self.audit_entries()
180    }
181
182    /// Number of entries in the audit log.
183    pub fn audit_len(&self) -> usize {
184        self.lock_log().len()
185    }
186
187    // Internal helpers
188
189    fn append_audit(
190        &self,
191        policy_name: String,
192        action: AuditAction,
193        size_bytes: Option<u64>,
194        error: Option<String>,
195    ) {
196        let entry = BackupAuditEntry {
197            timestamp: SystemTime::now(),
198            policy_name,
199            action,
200            size_bytes,
201            error,
202        };
203        self.lock_log().push(entry);
204    }
205
206    fn lock_log(&self) -> MutexGuard<'_, Vec<BackupAuditEntry>> {
207        self.audit_log
208            .lock()
209            .unwrap_or_else(|poisoned| poisoned.into_inner())
210    }
211}
212
213// ---------------------------------------------------------------------------
214// Tests
215// ---------------------------------------------------------------------------
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::backup::{
221        destination::DestinationConfig,
222        gfs::GfsRotation,
223        policy::{BackupPolicy, CronSchedule, EncryptionConfig},
224        retention::RetentionTier,
225    };
226    use std::env;
227
228    fn make_policy(dir: &Path) -> BackupPolicy {
229        BackupPolicy {
230            name: "test-policy".into(),
231            schedule: CronSchedule::daily(),
232            retention: RetentionTier::minimal(),
233            gfs: Some(GfsRotation::default()),
234            encryption: EncryptionConfig::none(),
235            destination: DestinationConfig::Filesystem {
236                path: dir.to_owned(),
237            },
238        }
239    }
240
241    #[test]
242    fn execute_backup_writes_file_and_returns_size() {
243        let dir = env::temp_dir().join(format!(
244            "oxirs_executor_test_{}",
245            SystemTime::now()
246                .duration_since(SystemTime::UNIX_EPOCH)
247                .unwrap_or(Duration::ZERO)
248                .as_nanos()
249        ));
250
251        let executor = BackupExecutor::new();
252        let policy = make_policy(&dir);
253        let data = b"backup payload data 1234567890";
254
255        let size = executor
256            .execute_backup(&policy, data, &dir)
257            .expect("backup should succeed");
258
259        assert_eq!(size, data.len() as u64);
260
261        let _ = std::fs::remove_dir_all(&dir);
262    }
263
264    #[test]
265    fn audit_log_contains_started_and_completed() {
266        let dir = env::temp_dir().join(format!(
267            "oxirs_audit_test_{}",
268            SystemTime::now()
269                .duration_since(SystemTime::UNIX_EPOCH)
270                .unwrap_or(Duration::ZERO)
271                .as_nanos()
272        ));
273
274        let executor = BackupExecutor::new();
275        let policy = make_policy(&dir);
276
277        executor
278            .execute_backup(&policy, b"data", &dir)
279            .expect("backup should succeed");
280
281        let entries = executor.audit_entries();
282        assert!(
283            entries.len() >= 2,
284            "expected ≥2 audit entries; got {}",
285            entries.len()
286        );
287
288        let has_started = entries.iter().any(|e| e.contains("Started"));
289        let has_completed = entries.iter().any(|e| e.contains("Completed"));
290        assert!(has_started, "missing 'Started' entry: {entries:?}");
291        assert!(has_completed, "missing 'Completed' entry: {entries:?}");
292
293        let _ = std::fs::remove_dir_all(&dir);
294    }
295
296    #[test]
297    fn record_prune_adds_pruned_entry() {
298        let executor = BackupExecutor::new();
299        executor.record_prune("my-policy", 42);
300        let entries = executor.audit_entries();
301        assert!(entries.iter().any(|e| e.contains("Pruned")));
302    }
303
304    #[test]
305    fn audit_len_increases_with_operations() {
306        let dir = env::temp_dir().join(format!(
307            "oxirs_len_test_{}",
308            SystemTime::now()
309                .duration_since(SystemTime::UNIX_EPOCH)
310                .unwrap_or(Duration::ZERO)
311                .as_nanos()
312        ));
313
314        let executor = BackupExecutor::new();
315        assert_eq!(executor.audit_len(), 0);
316
317        let policy = make_policy(&dir);
318        executor.execute_backup(&policy, b"x", &dir).ok();
319
320        assert!(executor.audit_len() >= 2);
321        let _ = std::fs::remove_dir_all(&dir);
322    }
323
324    #[test]
325    fn backup_to_invalid_path_returns_error_and_logs_failed() {
326        let executor = BackupExecutor::new();
327
328        // Create a temp file to use as destination (files can't be used as dirs)
329        let temp_file = env::temp_dir().join(format!(
330            "oxirs_invalid_{}",
331            SystemTime::now()
332                .duration_since(SystemTime::UNIX_EPOCH)
333                .unwrap_or(Duration::ZERO)
334                .as_nanos()
335        ));
336        std::fs::write(&temp_file, b"block").ok();
337
338        // Try to create a file *inside* another file — guaranteed to fail
339        let bad_dest = temp_file.join("subdir");
340
341        let policy = BackupPolicy {
342            name: "fail-test".into(),
343            schedule: CronSchedule::daily(),
344            retention: RetentionTier::minimal(),
345            gfs: None,
346            encryption: EncryptionConfig::none(),
347            destination: DestinationConfig::Filesystem {
348                path: bad_dest.clone(),
349            },
350        };
351
352        let result = executor.execute_backup(&policy, b"data", &bad_dest);
353        assert!(result.is_err(), "Expected Err for invalid destination");
354
355        let entries = executor.audit_entries();
356        assert!(
357            entries.iter().any(|e| e.contains("Failed")),
358            "Expected 'Failed' audit entry"
359        );
360
361        let _ = std::fs::remove_file(&temp_file);
362    }
363}