Skip to main content

macfly_core/
journal.rs

1use std::fs::{self, OpenOptions};
2use std::io::Write;
3use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6
7use crate::config::data_dir;
8use crate::error::MacflyError;
9use crate::plan::{ensure_private_dir, now_unix};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct JournalEntry {
13    pub timestamp_unix: u64,
14    pub plan_id: String,
15    pub profile: String,
16    pub plan_hash: String,
17    pub status: String,
18    pub operations_count: usize,
19    pub details: Vec<String>,
20}
21
22pub struct AuditJournal {
23    path: PathBuf,
24}
25
26impl AuditJournal {
27    pub fn default_journal() -> Self {
28        Self {
29            path: data_dir().join("journal.jsonl"),
30        }
31    }
32
33    pub fn append(&self, entry: &JournalEntry) -> Result<(), MacflyError> {
34        if let Some(parent) = self.path.parent() {
35            ensure_private_dir(parent)?;
36        }
37        let mut file = OpenOptions::new()
38            .create(true)
39            .append(true)
40            .open(&self.path)?;
41        let line = serde_json::to_string(entry)?;
42        writeln!(file, "{line}")?;
43        #[cfg(unix)]
44        {
45            use std::os::unix::fs::PermissionsExt;
46            let _ = fs::set_permissions(&self.path, fs::Permissions::from_mode(0o600));
47        }
48        Ok(())
49    }
50
51    pub fn recent(&self, limit: usize) -> Result<Vec<JournalEntry>, MacflyError> {
52        if !self.path.exists() {
53            return Ok(Vec::new());
54        }
55        let raw = fs::read_to_string(&self.path)?;
56        let mut entries: Vec<JournalEntry> = raw
57            .lines()
58            .filter_map(|l| serde_json::from_str::<JournalEntry>(l).ok())
59            .collect();
60        entries.reverse();
61        entries.truncate(limit);
62        Ok(entries)
63    }
64
65    pub fn record_apply(
66        &self,
67        plan_id: &str,
68        profile: &str,
69        plan_hash: &str,
70        ok: bool,
71        details: Vec<String>,
72    ) -> Result<(), MacflyError> {
73        self.append(&JournalEntry {
74            timestamp_unix: now_unix(),
75            plan_id: plan_id.to_string(),
76            profile: profile.to_string(),
77            plan_hash: plan_hash.to_string(),
78            status: if ok {
79                "applied".to_string()
80            } else {
81                "failed".to_string()
82            },
83            operations_count: details.len(),
84            details,
85        })
86    }
87}