Skip to main content

trusty_code/log_drain/
config.rs

1//! The `~/.trusty-code/log_drain.yaml` config file (#6537).
2//!
3//! Why: `tcode` has no crate-wide settings file today, so the drain gets its
4//! own small one rather than inventing a general config system this ticket
5//! does not need. Field names match trusty-mpm's `log_drain:` section
6//! (`trusty_mpm::core::trusty_tools_config::log_drain::LogDrainConfig`) so an
7//! operator who already knows that shape needs nothing new. [`LogDrainConfig`]
8//! is now a bare alias onto
9//! [`trusty_common::log_drain::SingleSourceSection`] — the shared shape
10//! trusty-agents' own TOML section also aliases (#6537 code-review fix
11//! round) — since YAML and TOML serialize the same eight fields with no
12//! mapping needed.
13//! What: [`LogDrainConfig`] is the on-disk shape; [`load_config`] reads it,
14//! defaulting to a disabled section when the file is absent. A present but
15//! malformed file is an error, never a silent default — matching trusty-mpm's
16//! "malformed is an error" convention (`resolve::resolve_log_drain` applies
17//! the same rule to the section's CONTENT).
18//! Test: `tests`.
19
20use std::path::{Path, PathBuf};
21
22/// The `log_drain.yaml` schema. Every field optional, same names as
23/// trusty-mpm's `log_drain:` section.
24pub type LogDrainConfig = trusty_common::log_drain::SingleSourceSection;
25
26/// Path of the config file: `~/.trusty-code/log_drain.yaml`.
27pub fn config_path() -> PathBuf {
28    crate::paths::private_state::private_state_dir().join("log_drain.yaml")
29}
30
31/// Load the config file, defaulting to a disabled section when absent.
32///
33/// # Errors
34/// A present file that fails to parse, formatted with its path so the
35/// operator can find the typo.
36pub fn load_config() -> Result<LogDrainConfig, String> {
37    load_from_path(&config_path())
38}
39
40/// The read-and-parse logic, over an explicit path — the test seam.
41fn load_from_path(path: &Path) -> Result<LogDrainConfig, String> {
42    match std::fs::read_to_string(path) {
43        Ok(raw) => serde_yaml::from_str(&raw).map_err(|e| format!("{}: {e}", path.display())),
44        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(LogDrainConfig::default()),
45        Err(e) => Err(format!("{}: {e}", path.display())),
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    /// No file at all reads as a valid, disabled config — not an error.
54    ///
55    /// Why: a fresh `tcode` install must never fail to start because it has
56    /// never seen this file.
57    #[test]
58    fn missing_file_defaults_to_disabled() {
59        let dir = tempfile::tempdir().expect("tempdir");
60        let missing = dir.path().join("log_drain.yaml");
61        assert_eq!(load_from_path(&missing), Ok(LogDrainConfig::default()));
62    }
63
64    /// A present, malformed file is an error naming its own path.
65    #[test]
66    fn present_malformed_file_is_an_error() {
67        let dir = tempfile::tempdir().expect("tempdir");
68        let path = dir.path().join("log_drain.yaml");
69        std::fs::write(&path, "enabled: [this is not a bool").expect("write");
70        let result = load_from_path(&path);
71        assert!(result.is_err());
72        assert!(result.unwrap_err().contains("log_drain.yaml"));
73    }
74
75    /// A present, well-formed file loads its fields.
76    #[test]
77    fn present_valid_file_loads() {
78        let dir = tempfile::tempdir().expect("tempdir");
79        let path = dir.path().join("log_drain.yaml");
80        std::fs::write(&path, "enabled: true\ndestination: s3://bucket/prefix\n").expect("write");
81        let cfg = load_from_path(&path).expect("load");
82        assert_eq!(cfg.enabled, Some(true));
83        assert_eq!(cfg.destination.as_deref(), Some("s3://bucket/prefix"));
84    }
85
86    /// A well-formed file round-trips every field.
87    #[test]
88    fn yaml_round_trips_every_field() {
89        let cfg = LogDrainConfig {
90            enabled: Some(true),
91            destination: Some("s3://bucket/prefix".to_string()),
92            interval_secs: Some(300),
93            max_file_bytes: Some(1024),
94            max_wire_bytes: Some(2048),
95            secrets: vec!["shh".to_string()],
96            owner: Some("acme".to_string()),
97            project: Some("widgets".to_string()),
98        };
99        let yaml = serde_yaml::to_string(&cfg).expect("serialize");
100        let back: LogDrainConfig = serde_yaml::from_str(&yaml).expect("deserialize");
101        assert_eq!(cfg, back);
102    }
103
104    /// Malformed YAML is a hard error, never a silent default.
105    #[test]
106    fn malformed_yaml_is_an_error() {
107        let malformed = "enabled: [this is not a bool";
108        let result: Result<LogDrainConfig, _> = serde_yaml::from_str(malformed);
109        assert!(result.is_err());
110    }
111
112    /// An empty document parses to every field defaulted (absent section
113    /// content, same as `LogDrainConfig::default()`).
114    #[test]
115    fn empty_document_defaults_every_field() {
116        let cfg: LogDrainConfig = serde_yaml::from_str("{}").expect("empty doc parses");
117        assert_eq!(cfg, LogDrainConfig::default());
118    }
119}