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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub db_path: Option<String>,
32
33 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub machine_id: Option<String>,
37
38 #[serde(default)]
39 pub hooks: HooksConfig,
40
41 #[serde(default = "default_retention")]
44 pub retention: String,
45
46 #[serde(skip)]
48 source: ConfigSource,
49}
50
51macro_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 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
107pub const DEFAULT_RETENTION: Duration = Duration::from_secs(365 * 24 * 60 * 60);
109
110fn default_retention() -> String {
111 "365d".to_string()
112}
113
114pub 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum ConfigSource {
168 EnvVar,
170 UserGlobal,
172 #[default]
174 Default,
175}
176
177impl Config {
178 pub fn load_with_source() -> Result<(Self, ConfigSource), ConfigError> {
187 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 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 Ok((Config::default(), ConfigSource::Default))
211 }
212
213 pub fn load() -> Result<Self, ConfigError> {
215 Ok(Self::load_with_source()?.0)
216 }
217
218 pub fn db_path(&self) -> Result<PathBuf, ConfigError> {
225 if let Ok(path) = std::env::var("FYI_DB_PATH") {
227 return Ok(PathBuf::from(path));
228 }
229
230 if let Some(ref db_path) = self.db_path {
232 return Self::expand_path(db_path);
233 }
234
235 let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
237 Ok(home.join(".fyi/events.db"))
238 }
239
240 pub fn source(&self) -> ConfigSource {
242 self.source
243 }
244
245 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 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 pub fn machine_id(&self) -> String {
269 if let Ok(id) = std::env::var("FYI_MACHINE_ID")
271 && !id.is_empty()
272 {
273 return id;
274 }
275
276 if let Some(ref id) = self.machine_id
278 && !id.is_empty()
279 {
280 return id.clone();
281 }
282
283 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 "unknown".to_string()
292 }
293
294 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 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 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 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 assert_eq!(parse_retention("1000"), Ok(Duration::from_secs(1000)));
340
341 assert_eq!(parse_retention("3600s"), Ok(Duration::from_secs(3600)));
343
344 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 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 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 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 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 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 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 let config = Config::default();
457 let machine_id = config.machine_id();
458 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 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 let config = Config::default();
489 assert!(config.machine_id.is_none());
490 }
491}