Skip to main content

fyi_core/
config.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3use std::time::Duration;
4use thiserror::Error;
5
6use crate::EventType;
7
8#[derive(Error, Debug)]
9pub enum ConfigError {
10    #[error("failed to read config file: {0}")]
11    ReadError(#[from] std::io::Error),
12    #[error("failed to parse config file: {0}")]
13    ParseError(#[from] toml::de::Error),
14    #[error("failed to determine home directory")]
15    NoHomeDir,
16}
17
18/// Error parsing a TTL string
19#[derive(Error, Debug, PartialEq, Eq)]
20pub enum TtlParseError {
21    #[error("invalid TTL format: {0}")]
22    InvalidFormat(String),
23    #[error("invalid TTL number: {0}")]
24    InvalidNumber(String),
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Config {
29    /// Explicit database path. If None, uses default (~/.fyi/events.db).
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub db_path: Option<String>,
32
33    /// Explicit machine identifier. If None, uses hostname.
34    /// Resolution order: FYI_MACHINE_ID env var > config > hostname > "unknown"
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub machine_id: Option<String>,
37
38    #[serde(default)]
39    pub hooks: HooksConfig,
40
41    /// Data retention period for all events. Default: 365 days.
42    /// Supports suffixes: 'd' (days), 'h' (hours), 'm' (minutes), 's' (seconds), or raw seconds.
43    #[serde(default = "default_retention")]
44    pub retention: String,
45
46    /// Where the config was loaded from (not serialized)
47    #[serde(skip)]
48    source: ConfigSource,
49}
50
51/// Macro to define HooksConfig with automatic snake_case to PascalCase mapping.
52///
53/// This macro generates the struct, Default impl, and enabled_hooks() method
54/// from a single definition, ensuring the field names and EventType variants
55/// are always in sync.
56macro_rules! define_hooks_config {
57    ($($field:ident => $variant:ident),* $(,)?) => {
58        #[derive(Debug, Clone, Serialize, Deserialize)]
59        #[serde(rename_all = "PascalCase")]
60        pub struct HooksConfig {
61            $(
62                #[serde(default = "default_true")]
63                pub $field: bool,
64            )*
65        }
66
67        impl Default for HooksConfig {
68            fn default() -> Self {
69                Self {
70                    $($field: true,)*
71                }
72            }
73        }
74
75        impl HooksConfig {
76            /// Returns enabled hooks as EventType values for type-safe handling.
77            pub fn enabled_hooks(&self) -> Vec<EventType> {
78                let mut hooks = Vec::new();
79                $(
80                    if self.$field {
81                        hooks.push(EventType::$variant);
82                    }
83                )*
84                hooks
85            }
86        }
87    };
88}
89
90define_hooks_config! {
91    session_start => SessionStart,
92    session_end => SessionEnd,
93    user_prompt_submit => UserPromptSubmit,
94    stop => Stop,
95    subagent_stop => SubagentStop,
96    notification => Notification,
97    permission_request => PermissionRequest,
98    pre_compact => PreCompact,
99    pre_tool_use => PreToolUse,
100    post_tool_use => PostToolUse,
101}
102
103fn default_true() -> bool {
104    true
105}
106
107/// Default retention period: 365 days
108pub const DEFAULT_RETENTION: Duration = Duration::from_secs(365 * 24 * 60 * 60);
109
110fn default_retention() -> String {
111    "365d".to_string()
112}
113
114/// Parse a retention/TTL string like "7d", "30d", "1h" into a Duration.
115///
116/// Supports suffixes:
117/// - 'd' for days (e.g., "7d" = 7 days)
118/// - 'h' for hours (e.g., "24h" = 24 hours)
119/// - 'm' for minutes (e.g., "30m" = 30 minutes)
120/// - 's' for seconds (e.g., "3600s" = 1 hour)
121/// - Raw seconds if no suffix (e.g., "86400" = 1 day)
122pub fn parse_retention(s: &str) -> Result<Duration, TtlParseError> {
123    let s = s.trim();
124    if let Some(stripped) = s.strip_suffix('d') {
125        let days: u64 = stripped
126            .parse()
127            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
128        Ok(Duration::from_secs(days * 24 * 60 * 60))
129    } else if let Some(stripped) = s.strip_suffix('h') {
130        let hours: u64 = stripped
131            .parse()
132            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
133        Ok(Duration::from_secs(hours * 60 * 60))
134    } else if let Some(stripped) = s.strip_suffix('m') {
135        let minutes: u64 = stripped
136            .parse()
137            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
138        Ok(Duration::from_secs(minutes * 60))
139    } else if let Some(stripped) = s.strip_suffix('s') {
140        let secs: u64 = stripped
141            .parse()
142            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
143        Ok(Duration::from_secs(secs))
144    } else {
145        // Assume seconds (raw number)
146        let secs: u64 = s
147            .parse()
148            .map_err(|_| TtlParseError::InvalidFormat(s.to_string()))?;
149        Ok(Duration::from_secs(secs))
150    }
151}
152
153impl Default for Config {
154    fn default() -> Self {
155        Self {
156            db_path: None,
157            machine_id: None,
158            hooks: HooksConfig::default(),
159            retention: default_retention(),
160            source: ConfigSource::Default,
161        }
162    }
163}
164
165/// Where the config was loaded from
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum ConfigSource {
168    /// Environment variable (FYI_CONFIG)
169    EnvVar,
170    /// User global ~/.fyi/config.toml
171    UserGlobal,
172    /// No config file found, using defaults
173    #[default]
174    Default,
175}
176
177impl Config {
178    /// Load config with source information.
179    ///
180    /// Config resolution order:
181    /// 1. `FYI_CONFIG` env var (if set and file exists)
182    /// 2. `~/.fyi/config.toml` (user global)
183    /// 3. Built-in defaults
184    ///
185    /// For per-project database paths, use the `FYI_DB_PATH` env var.
186    pub fn load_with_source() -> Result<(Self, ConfigSource), ConfigError> {
187        // 1. Check environment variable
188        if let Ok(path) = std::env::var("FYI_CONFIG") {
189            let path = PathBuf::from(path);
190            if path.exists() {
191                let contents = std::fs::read_to_string(&path)?;
192                let mut config: Config = toml::from_str(&contents)?;
193                config.source = ConfigSource::EnvVar;
194                return Ok((config, ConfigSource::EnvVar));
195            }
196        }
197
198        // 2. Check user global ~/.fyi/config.toml
199        if let Some(home) = dirs::home_dir() {
200            let global_config = home.join(".fyi/config.toml");
201            if global_config.exists() {
202                let contents = std::fs::read_to_string(&global_config)?;
203                let mut config: Config = toml::from_str(&contents)?;
204                config.source = ConfigSource::UserGlobal;
205                return Ok((config, ConfigSource::UserGlobal));
206            }
207        }
208
209        // 3. Use defaults
210        Ok((Config::default(), ConfigSource::Default))
211    }
212
213    /// Load config (convenience method that discards source)
214    pub fn load() -> Result<Self, ConfigError> {
215        Ok(Self::load_with_source()?.0)
216    }
217
218    /// Get the database path.
219    ///
220    /// Resolution order:
221    /// 1. `FYI_DB_PATH` env var (if set)
222    /// 2. `db_path` from config file (if set)
223    /// 3. Default: `~/.fyi/events.db`
224    pub fn db_path(&self) -> Result<PathBuf, ConfigError> {
225        // Environment variable always takes precedence
226        if let Ok(path) = std::env::var("FYI_DB_PATH") {
227            return Ok(PathBuf::from(path));
228        }
229
230        // If db_path is explicitly set in config, use it
231        if let Some(ref db_path) = self.db_path {
232            return Self::expand_path(db_path);
233        }
234
235        // Default to global database location
236        let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
237        Ok(home.join(".fyi/events.db"))
238    }
239
240    /// Get the source from which this config was loaded.
241    pub fn source(&self) -> ConfigSource {
242        self.source
243    }
244
245    /// Expand a path, handling ~ for home directory
246    fn expand_path(path: &str) -> Result<PathBuf, ConfigError> {
247        if let Some(stripped) = path.strip_prefix("~/") {
248            let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
249            Ok(home.join(stripped))
250        } else {
251            Ok(PathBuf::from(path))
252        }
253    }
254
255    /// Get the user global config directory
256    pub fn user_global_dir() -> Result<PathBuf, ConfigError> {
257        let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
258        Ok(home.join(".fyi"))
259    }
260
261    /// Get the machine ID.
262    ///
263    /// Resolution order:
264    /// 1. `FYI_MACHINE_ID` env var (if set)
265    /// 2. `machine_id` from config file (if set)
266    /// 3. Hostname (current behavior)
267    /// 4. "unknown" fallback
268    pub fn machine_id(&self) -> String {
269        // 1. Environment variable takes precedence
270        if let Ok(id) = std::env::var("FYI_MACHINE_ID")
271            && !id.is_empty()
272        {
273            return id;
274        }
275
276        // 2. Config file setting
277        if let Some(ref id) = self.machine_id
278            && !id.is_empty()
279        {
280            return id.clone();
281        }
282
283        // 3. Hostname
284        if let Some(hostname) = hostname::get().ok().and_then(|h| h.into_string().ok())
285            && !hostname.is_empty()
286        {
287            return hostname;
288        }
289
290        // 4. Fallback
291        "unknown".to_string()
292    }
293
294    /// Get the retention period as a Duration.
295    ///
296    /// Falls back to default if the retention string is invalid.
297    pub fn retention_duration(&self) -> Duration {
298        match parse_retention(&self.retention) {
299            Ok(duration) => duration,
300            Err(e) => {
301                eprintln!(
302                    "fyi: warning: failed to parse retention '{}': {}. Using default.",
303                    self.retention, e
304                );
305                DEFAULT_RETENTION
306            }
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn test_parse_retention() {
317        // Days
318        assert_eq!(
319            parse_retention("7d"),
320            Ok(Duration::from_secs(7 * 24 * 60 * 60))
321        );
322        assert_eq!(
323            parse_retention("30d"),
324            Ok(Duration::from_secs(30 * 24 * 60 * 60))
325        );
326
327        // Hours
328        assert_eq!(parse_retention("1h"), Ok(Duration::from_secs(60 * 60)));
329        assert_eq!(
330            parse_retention("24h"),
331            Ok(Duration::from_secs(24 * 60 * 60))
332        );
333
334        // Minutes
335        assert_eq!(parse_retention("30m"), Ok(Duration::from_secs(30 * 60)));
336        assert_eq!(parse_retention("60m"), Ok(Duration::from_secs(60 * 60)));
337
338        // Seconds (raw number)
339        assert_eq!(parse_retention("1000"), Ok(Duration::from_secs(1000)));
340
341        // Explicit seconds suffix
342        assert_eq!(parse_retention("3600s"), Ok(Duration::from_secs(3600)));
343
344        // Invalid
345        assert_eq!(
346            parse_retention("abc"),
347            Err(TtlParseError::InvalidFormat("abc".to_string()))
348        );
349        assert_eq!(
350            parse_retention("d"),
351            Err(TtlParseError::InvalidNumber("d".to_string()))
352        );
353    }
354
355    #[test]
356    fn test_config_default_retention() {
357        let config = Config::default();
358        assert_eq!(config.retention, "365d");
359        assert_eq!(config.retention_duration(), DEFAULT_RETENTION);
360    }
361
362    #[test]
363    fn test_config_custom_retention() -> Result<(), String> {
364        let toml_str = r#"
365            retention = "30d"
366        "#;
367
368        let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
369        assert_eq!(config.retention, "30d");
370        assert_eq!(
371            config.retention_duration(),
372            std::time::Duration::from_secs(30 * 24 * 60 * 60)
373        );
374        Ok(())
375    }
376
377    #[test]
378    fn test_config_retention_fallback_on_invalid() {
379        let config = Config {
380            retention: "invalid".to_string(),
381            ..Default::default()
382        };
383        // Should fall back to DEFAULT_RETENTION
384        assert_eq!(config.retention_duration(), DEFAULT_RETENTION);
385    }
386
387    #[test]
388    fn test_config_default_source() {
389        let config = Config::default();
390        assert_eq!(config.source(), ConfigSource::Default);
391    }
392
393    #[test]
394    fn test_config_source_cached_from_load() -> Result<(), String> {
395        // When loading config, the source should be cached in the struct
396        let (config, source) = Config::load_with_source().map_err(|e| e.to_string())?;
397        assert_eq!(config.source(), source);
398        Ok(())
399    }
400
401    #[test]
402    fn test_db_path_consistent() -> Result<(), String> {
403        // Calling db_path() multiple times should return consistent results
404        let config = Config::default();
405        let path1 = config.db_path().map_err(|e| e.to_string())?;
406        let path2 = config.db_path().map_err(|e| e.to_string())?;
407        assert_eq!(path1, path2);
408        Ok(())
409    }
410
411    #[test]
412    fn test_config_source_default_is_default() {
413        // Verify ConfigSource::Default is the default variant
414        assert_eq!(ConfigSource::default(), ConfigSource::Default);
415    }
416
417    #[test]
418    fn test_enabled_hooks_returns_all_event_types() {
419        let config = HooksConfig::default();
420        let hooks = config.enabled_hooks();
421
422        // Verify all expected hooks are present as EventType variants
423        assert!(hooks.contains(&EventType::SessionStart));
424        assert!(hooks.contains(&EventType::SessionEnd));
425        assert!(hooks.contains(&EventType::UserPromptSubmit));
426        assert!(hooks.contains(&EventType::Stop));
427        assert!(hooks.contains(&EventType::SubagentStop));
428        assert!(hooks.contains(&EventType::Notification));
429        assert!(hooks.contains(&EventType::PermissionRequest));
430        assert!(hooks.contains(&EventType::PreCompact));
431        assert!(hooks.contains(&EventType::PreToolUse));
432        assert!(hooks.contains(&EventType::PostToolUse));
433
434        // Verify we have exactly 10 hooks
435        assert_eq!(hooks.len(), 10);
436    }
437
438    #[test]
439    fn test_enabled_hooks_respects_disabled_hooks() {
440        let config = HooksConfig {
441            session_start: false,
442            pre_tool_use: false,
443            ..Default::default()
444        };
445
446        let hooks = config.enabled_hooks();
447        assert_eq!(hooks.len(), 8);
448        assert!(!hooks.contains(&EventType::SessionStart));
449        assert!(!hooks.contains(&EventType::PreToolUse));
450        assert!(hooks.contains(&EventType::SessionEnd));
451    }
452
453    #[test]
454    fn test_machine_id_returns_nonempty() {
455        // machine_id() should always return a non-empty string
456        let config = Config::default();
457        let machine_id = config.machine_id();
458        // Should be non-empty (env var, config, hostname, or "unknown")
459        assert!(!machine_id.is_empty());
460    }
461
462    #[test]
463    fn test_config_machine_id_from_toml() -> Result<(), String> {
464        let toml_str = r#"
465            machine_id = "test-machine"
466        "#;
467
468        let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
469        assert_eq!(config.machine_id, Some("test-machine".to_string()));
470        Ok(())
471    }
472
473    #[test]
474    fn test_config_machine_id_optional_in_toml() -> Result<(), String> {
475        // machine_id should be optional in TOML
476        let toml_str = r#"
477            retention = "30d"
478        "#;
479
480        let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
481        assert_eq!(config.machine_id, None);
482        Ok(())
483    }
484
485    #[test]
486    fn test_machine_id_default_is_none() {
487        // Default config should have machine_id as None
488        let config = Config::default();
489        assert!(config.machine_id.is_none());
490    }
491}