use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Duration;
use thiserror::Error;
use crate::EventType;
#[derive(Error, Debug)]
pub enum ConfigError {
#[error("failed to read config file: {0}")]
ReadError(#[from] std::io::Error),
#[error("failed to parse config file: {0}")]
ParseError(#[from] toml::de::Error),
#[error("failed to determine home directory")]
NoHomeDir,
}
#[derive(Error, Debug, PartialEq, Eq)]
pub enum TtlParseError {
#[error("invalid TTL format: {0}")]
InvalidFormat(String),
#[error("invalid TTL number: {0}")]
InvalidNumber(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub db_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub machine_id: Option<String>,
#[serde(default)]
pub hooks: HooksConfig,
#[serde(default = "default_retention")]
pub retention: String,
#[serde(skip)]
source: ConfigSource,
}
macro_rules! define_hooks_config {
($($field:ident => $variant:ident),* $(,)?) => {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct HooksConfig {
$(
#[serde(default = "default_true")]
pub $field: bool,
)*
}
impl Default for HooksConfig {
fn default() -> Self {
Self {
$($field: true,)*
}
}
}
impl HooksConfig {
pub fn enabled_hooks(&self) -> Vec<EventType> {
let mut hooks = Vec::new();
$(
if self.$field {
hooks.push(EventType::$variant);
}
)*
hooks
}
}
};
}
define_hooks_config! {
session_start => SessionStart,
session_end => SessionEnd,
user_prompt_submit => UserPromptSubmit,
stop => Stop,
subagent_stop => SubagentStop,
notification => Notification,
permission_request => PermissionRequest,
pre_compact => PreCompact,
pre_tool_use => PreToolUse,
post_tool_use => PostToolUse,
}
fn default_true() -> bool {
true
}
pub const DEFAULT_RETENTION: Duration = Duration::from_secs(365 * 24 * 60 * 60);
fn default_retention() -> String {
"365d".to_string()
}
pub fn parse_retention(s: &str) -> Result<Duration, TtlParseError> {
let s = s.trim();
if let Some(stripped) = s.strip_suffix('d') {
let days: u64 = stripped
.parse()
.map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
Ok(Duration::from_secs(days * 24 * 60 * 60))
} else if let Some(stripped) = s.strip_suffix('h') {
let hours: u64 = stripped
.parse()
.map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
Ok(Duration::from_secs(hours * 60 * 60))
} else if let Some(stripped) = s.strip_suffix('m') {
let minutes: u64 = stripped
.parse()
.map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
Ok(Duration::from_secs(minutes * 60))
} else if let Some(stripped) = s.strip_suffix('s') {
let secs: u64 = stripped
.parse()
.map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
Ok(Duration::from_secs(secs))
} else {
let secs: u64 = s
.parse()
.map_err(|_| TtlParseError::InvalidFormat(s.to_string()))?;
Ok(Duration::from_secs(secs))
}
}
impl Default for Config {
fn default() -> Self {
Self {
db_path: None,
machine_id: None,
hooks: HooksConfig::default(),
retention: default_retention(),
source: ConfigSource::Default,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfigSource {
EnvVar,
UserGlobal,
#[default]
Default,
}
impl Config {
pub fn load_with_source() -> Result<(Self, ConfigSource), ConfigError> {
if let Ok(path) = std::env::var("FYI_CONFIG") {
let path = PathBuf::from(path);
if path.exists() {
let contents = std::fs::read_to_string(&path)?;
let mut config: Config = toml::from_str(&contents)?;
config.source = ConfigSource::EnvVar;
return Ok((config, ConfigSource::EnvVar));
}
}
if let Some(home) = dirs::home_dir() {
let global_config = home.join(".fyi/config.toml");
if global_config.exists() {
let contents = std::fs::read_to_string(&global_config)?;
let mut config: Config = toml::from_str(&contents)?;
config.source = ConfigSource::UserGlobal;
return Ok((config, ConfigSource::UserGlobal));
}
}
Ok((Config::default(), ConfigSource::Default))
}
pub fn load() -> Result<Self, ConfigError> {
Ok(Self::load_with_source()?.0)
}
pub fn db_path(&self) -> Result<PathBuf, ConfigError> {
if let Ok(path) = std::env::var("FYI_DB_PATH") {
return Ok(PathBuf::from(path));
}
if let Some(ref db_path) = self.db_path {
return Self::expand_path(db_path);
}
let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
Ok(home.join(".fyi/events.db"))
}
pub fn source(&self) -> ConfigSource {
self.source
}
fn expand_path(path: &str) -> Result<PathBuf, ConfigError> {
if let Some(stripped) = path.strip_prefix("~/") {
let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
Ok(home.join(stripped))
} else {
Ok(PathBuf::from(path))
}
}
pub fn user_global_dir() -> Result<PathBuf, ConfigError> {
let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
Ok(home.join(".fyi"))
}
pub fn machine_id(&self) -> String {
if let Ok(id) = std::env::var("FYI_MACHINE_ID")
&& !id.is_empty()
{
return id;
}
if let Some(ref id) = self.machine_id
&& !id.is_empty()
{
return id.clone();
}
if let Some(hostname) = hostname::get().ok().and_then(|h| h.into_string().ok())
&& !hostname.is_empty()
{
return hostname;
}
"unknown".to_string()
}
pub fn retention_duration(&self) -> Duration {
match parse_retention(&self.retention) {
Ok(duration) => duration,
Err(e) => {
eprintln!(
"fyi: warning: failed to parse retention '{}': {}. Using default.",
self.retention, e
);
DEFAULT_RETENTION
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_retention() {
assert_eq!(
parse_retention("7d"),
Ok(Duration::from_secs(7 * 24 * 60 * 60))
);
assert_eq!(
parse_retention("30d"),
Ok(Duration::from_secs(30 * 24 * 60 * 60))
);
assert_eq!(parse_retention("1h"), Ok(Duration::from_secs(60 * 60)));
assert_eq!(
parse_retention("24h"),
Ok(Duration::from_secs(24 * 60 * 60))
);
assert_eq!(parse_retention("30m"), Ok(Duration::from_secs(30 * 60)));
assert_eq!(parse_retention("60m"), Ok(Duration::from_secs(60 * 60)));
assert_eq!(parse_retention("1000"), Ok(Duration::from_secs(1000)));
assert_eq!(parse_retention("3600s"), Ok(Duration::from_secs(3600)));
assert_eq!(
parse_retention("abc"),
Err(TtlParseError::InvalidFormat("abc".to_string()))
);
assert_eq!(
parse_retention("d"),
Err(TtlParseError::InvalidNumber("d".to_string()))
);
}
#[test]
fn test_config_default_retention() {
let config = Config::default();
assert_eq!(config.retention, "365d");
assert_eq!(config.retention_duration(), DEFAULT_RETENTION);
}
#[test]
fn test_config_custom_retention() -> Result<(), String> {
let toml_str = r#"
retention = "30d"
"#;
let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
assert_eq!(config.retention, "30d");
assert_eq!(
config.retention_duration(),
std::time::Duration::from_secs(30 * 24 * 60 * 60)
);
Ok(())
}
#[test]
fn test_config_retention_fallback_on_invalid() {
let config = Config {
retention: "invalid".to_string(),
..Default::default()
};
assert_eq!(config.retention_duration(), DEFAULT_RETENTION);
}
#[test]
fn test_config_default_source() {
let config = Config::default();
assert_eq!(config.source(), ConfigSource::Default);
}
#[test]
fn test_config_source_cached_from_load() -> Result<(), String> {
let (config, source) = Config::load_with_source().map_err(|e| e.to_string())?;
assert_eq!(config.source(), source);
Ok(())
}
#[test]
fn test_db_path_consistent() -> Result<(), String> {
let config = Config::default();
let path1 = config.db_path().map_err(|e| e.to_string())?;
let path2 = config.db_path().map_err(|e| e.to_string())?;
assert_eq!(path1, path2);
Ok(())
}
#[test]
fn test_config_source_default_is_default() {
assert_eq!(ConfigSource::default(), ConfigSource::Default);
}
#[test]
fn test_enabled_hooks_returns_all_event_types() {
let config = HooksConfig::default();
let hooks = config.enabled_hooks();
assert!(hooks.contains(&EventType::SessionStart));
assert!(hooks.contains(&EventType::SessionEnd));
assert!(hooks.contains(&EventType::UserPromptSubmit));
assert!(hooks.contains(&EventType::Stop));
assert!(hooks.contains(&EventType::SubagentStop));
assert!(hooks.contains(&EventType::Notification));
assert!(hooks.contains(&EventType::PermissionRequest));
assert!(hooks.contains(&EventType::PreCompact));
assert!(hooks.contains(&EventType::PreToolUse));
assert!(hooks.contains(&EventType::PostToolUse));
assert_eq!(hooks.len(), 10);
}
#[test]
fn test_enabled_hooks_respects_disabled_hooks() {
let config = HooksConfig {
session_start: false,
pre_tool_use: false,
..Default::default()
};
let hooks = config.enabled_hooks();
assert_eq!(hooks.len(), 8);
assert!(!hooks.contains(&EventType::SessionStart));
assert!(!hooks.contains(&EventType::PreToolUse));
assert!(hooks.contains(&EventType::SessionEnd));
}
#[test]
fn test_machine_id_returns_nonempty() {
let config = Config::default();
let machine_id = config.machine_id();
assert!(!machine_id.is_empty());
}
#[test]
fn test_config_machine_id_from_toml() -> Result<(), String> {
let toml_str = r#"
machine_id = "test-machine"
"#;
let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
assert_eq!(config.machine_id, Some("test-machine".to_string()));
Ok(())
}
#[test]
fn test_config_machine_id_optional_in_toml() -> Result<(), String> {
let toml_str = r#"
retention = "30d"
"#;
let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
assert_eq!(config.machine_id, None);
Ok(())
}
#[test]
fn test_machine_id_default_is_none() {
let config = Config::default();
assert!(config.machine_id.is_none());
}
}