Skip to main content

metalcraft_flows/
log.rs

1//! Flow execution log entries.
2//!
3//! Enabled by the `log` feature.
4
5use serde::{Deserialize, Serialize};
6use std::io;
7use std::path::Path;
8
9/// The maximum number of entries retained on disk before old entries are
10/// rotated out by [`append_flow_log`].
11pub const DEFAULT_LOG_RETENTION: usize = 2000;
12
13/// A single line in a flow's execution log.
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
15pub struct FlowLogEntry {
16    /// ISO-8601 / RFC-3339 timestamp of when the entry was recorded.
17    pub timestamp: String,
18    /// Id of the flow this entry belongs to.
19    pub flow_id: String,
20    /// Human-readable name of the flow at the time the entry was recorded.
21    pub flow_name: String,
22    /// Short verb describing what happened (e.g. `"started"`, `"node_ran"`,
23    /// `"failed"`). The spec does not constrain the value set.
24    pub action: String,
25    /// Longer free-form detail about the action.
26    pub detail: String,
27    /// Optional run identifier to correlate entries from a single execution.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub run_id: Option<String>,
30}
31
32/// Append `entry` to `log_path` (a JSON-array file), trimming to the most
33/// recent [`DEFAULT_LOG_RETENTION`] entries.
34///
35/// Creates the file if it doesn't exist.
36pub fn append_flow_log(log_path: &Path, entry: &FlowLogEntry) -> io::Result<()> {
37    let mut entries = load_flow_logs(log_path);
38    entries.push(entry.clone());
39    if entries.len() > DEFAULT_LOG_RETENTION {
40        let drop = entries.len() - DEFAULT_LOG_RETENTION;
41        entries.drain(0..drop);
42    }
43    let json = serde_json::to_string_pretty(&entries).map_err(io::Error::other)?;
44    std::fs::write(log_path, json)
45}
46
47/// Read all log entries from `log_path`.
48///
49/// Returns an empty vec if the file is missing or unparseable.
50pub fn load_flow_logs(log_path: &Path) -> Vec<FlowLogEntry> {
51    if !log_path.exists() {
52        return vec![];
53    }
54    std::fs::read_to_string(log_path)
55        .ok()
56        .and_then(|s| serde_json::from_str(&s).ok())
57        .unwrap_or_default()
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63    use tempfile::tempdir;
64
65    fn entry(action: &str) -> FlowLogEntry {
66        FlowLogEntry {
67            timestamp: "2026-01-01T00:00:00Z".into(),
68            flow_id: "f1".into(),
69            flow_name: "F1".into(),
70            action: action.into(),
71            detail: "stuff".into(),
72            run_id: Some("r1".into()),
73        }
74    }
75
76    #[test]
77    fn append_then_load_round_trip() {
78        let dir = tempdir().unwrap();
79        let path = dir.path().join("log.json");
80        append_flow_log(&path, &entry("started")).unwrap();
81        append_flow_log(&path, &entry("finished")).unwrap();
82        let loaded = load_flow_logs(&path);
83        assert_eq!(loaded.len(), 2);
84        assert_eq!(loaded[0].action, "started");
85        assert_eq!(loaded[1].action, "finished");
86    }
87
88    #[test]
89    fn missing_log_returns_empty() {
90        let dir = tempdir().unwrap();
91        assert!(load_flow_logs(&dir.path().join("nope.json")).is_empty());
92    }
93
94    #[test]
95    fn retention_drops_oldest() {
96        let dir = tempdir().unwrap();
97        let path = dir.path().join("log.json");
98        for i in 0..(DEFAULT_LOG_RETENTION + 50) {
99            let mut e = entry("tick");
100            e.detail = format!("{i}");
101            append_flow_log(&path, &e).unwrap();
102        }
103        let loaded = load_flow_logs(&path);
104        assert_eq!(loaded.len(), DEFAULT_LOG_RETENTION);
105        // First retained entry should be the 50th appended (0-indexed).
106        assert_eq!(loaded.first().unwrap().detail, "50");
107        assert_eq!(
108            loaded.last().unwrap().detail,
109            format!("{}", DEFAULT_LOG_RETENTION + 49)
110        );
111    }
112}