Skip to main content

memd/
config.rs

1//! Configuration module for memd
2//!
3//! Handles loading configuration from TOML files with fallback to defaults.
4//! Supports path expansion (~/) and XDG config directory conventions.
5
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::{MemdError, Result};
12
13/// Main configuration for memd
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Config {
16    /// Directory for tenant data storage
17    #[serde(default = "default_data_dir")]
18    pub data_dir: PathBuf,
19
20    /// Logging level: trace, debug, info, warn, error
21    #[serde(default = "default_log_level")]
22    pub log_level: String,
23
24    /// Log format: json (structured) or pretty (human-readable)
25    #[serde(default = "default_log_format")]
26    pub log_format: String,
27
28    /// Compatibility routing configuration.
29    #[serde(default)]
30    pub server: ServerConfig,
31}
32
33fn default_data_dir() -> PathBuf {
34    PathBuf::from("~/.memd/data")
35}
36
37fn default_log_level() -> String {
38    "info".to_string()
39}
40
41fn default_log_format() -> String {
42    "json".to_string()
43}
44
45/// Compatibility routing configuration.
46///
47/// The TOML table name remains `[server]` for existing config files, but the
48/// executable no longer exposes a network or stdio server mode.
49#[derive(Debug, Clone, Default, Serialize, Deserialize)]
50pub struct ServerConfig {
51    /// Opt-in to the legacy cross-tenant `project_id` fallback.
52    ///
53    /// When true, any retrieval that carries a `project_id` widens its
54    /// search across all tenants on the daemon that contain that project
55    /// string. This is a compatibility shim for older fragmented history
56    /// — it silently leaks data across tenant boundaries and should stay
57    /// off unless you are deliberately consolidating writes that were
58    /// misrouted. `tenant_id` is a logical partition only and not an
59    /// authentication boundary; put HTTP behind a reverse proxy with real
60    /// auth if you need multi-user isolation.
61    #[serde(default)]
62    pub allow_cross_tenant_project_fallback: bool,
63    /// Explicit project aliases for intentional cross-scope retrieval.
64    ///
65    /// Each rule says: when the requested `(tenant_id, project_id)` matches,
66    /// also search the listed alias scopes. An alias may point at another
67    /// tenant and/or another project ID. Unlike the legacy fallback, this does
68    /// not widen to every tenant that happens to share the project name.
69    #[serde(default)]
70    pub project_aliases: Vec<ProjectAliasConfig>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74pub struct ProjectAliasConfig {
75    pub tenant_id: String,
76    pub project_id: String,
77    #[serde(default)]
78    pub aliases: Vec<ProjectAliasScopeConfig>,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
82pub struct ProjectAliasScopeConfig {
83    pub tenant_id: String,
84    #[serde(default)]
85    pub project_id: Option<String>,
86    #[serde(default)]
87    pub reason: Option<String>,
88}
89
90impl Default for Config {
91    fn default() -> Self {
92        Self {
93            data_dir: default_data_dir(),
94            log_level: default_log_level(),
95            log_format: default_log_format(),
96            server: ServerConfig::default(),
97        }
98    }
99}
100
101impl Config {
102    /// Expand tilde (~) in paths to the user's home directory
103    pub fn expand_paths(&mut self) -> Result<()> {
104        self.data_dir = expand_tilde(&self.data_dir)?;
105        Ok(())
106    }
107
108    /// Get the data directory with tilde expansion applied
109    pub fn data_dir_expanded(&self) -> Result<PathBuf> {
110        expand_tilde(&self.data_dir)
111    }
112
113    /// Validate the configuration values
114    pub fn validate(&self) -> Result<()> {
115        // Validate log_level
116        let valid_levels = ["trace", "debug", "info", "warn", "error"];
117        if !valid_levels.contains(&self.log_level.to_lowercase().as_str()) {
118            return Err(MemdError::ConfigError(format!(
119                "invalid log_level '{}', must be one of: {}",
120                self.log_level,
121                valid_levels.join(", ")
122            )));
123        }
124
125        // Validate log_format
126        let valid_formats = ["json", "pretty"];
127        if !valid_formats.contains(&self.log_format.to_lowercase().as_str()) {
128            return Err(MemdError::ConfigError(format!(
129                "invalid log_format '{}', must be one of: {}",
130                self.log_format,
131                valid_formats.join(", ")
132            )));
133        }
134
135        for rule in &self.server.project_aliases {
136            if rule.tenant_id.trim().is_empty() || rule.project_id.trim().is_empty() {
137                return Err(MemdError::ConfigError(
138                    "server.project_aliases entries require tenant_id and project_id".to_string(),
139                ));
140            }
141            for alias in &rule.aliases {
142                if alias.tenant_id.trim().is_empty() {
143                    return Err(MemdError::ConfigError(
144                        "server.project_aliases aliases require tenant_id".to_string(),
145                    ));
146                }
147                if alias
148                    .project_id
149                    .as_deref()
150                    .is_some_and(|project_id| project_id.trim().is_empty())
151                {
152                    return Err(MemdError::ConfigError(
153                        "server.project_aliases aliases cannot use an empty project_id".to_string(),
154                    ));
155                }
156            }
157        }
158
159        Ok(())
160    }
161}
162
163/// Expand tilde (~) in a path to the user's home directory
164fn expand_tilde(path: &Path) -> Result<PathBuf> {
165    let path_str = path.to_string_lossy();
166
167    if let Some(relative) = path_str.strip_prefix("~/") {
168        let home = std::env::var("HOME")
169            .map_err(|_| MemdError::ConfigError("HOME environment variable not set".to_string()))?;
170        Ok(PathBuf::from(home).join(relative))
171    } else if path_str == "~" {
172        let home = std::env::var("HOME")
173            .map_err(|_| MemdError::ConfigError("HOME environment variable not set".to_string()))?;
174        Ok(PathBuf::from(home))
175    } else {
176        Ok(path.to_path_buf())
177    }
178}
179
180/// Load configuration from a file path or default locations
181///
182/// Search order:
183/// 1. Explicit path if provided
184/// 2. XDG config: ~/.config/memd/config.toml
185/// 3. Fall back to defaults
186pub fn load_config(path: Option<&Path>) -> Result<Config> {
187    // If explicit path provided, load from there
188    if let Some(p) = path {
189        return load_from_file(p);
190    }
191
192    // Check XDG config location
193    if let Ok(home) = std::env::var("HOME") {
194        let xdg_config = PathBuf::from(&home)
195            .join(".config")
196            .join("memd")
197            .join("config.toml");
198
199        if xdg_config.exists() {
200            return load_from_file(&xdg_config);
201        }
202    }
203
204    // Fall back to defaults
205    Ok(Config::default())
206}
207
208/// Load configuration from a specific file
209fn load_from_file(path: &Path) -> Result<Config> {
210    let content = fs::read_to_string(path)?;
211    let config: Config = toml::from_str(&content)?;
212
213    // Validate after loading
214    config.validate()?;
215
216    Ok(config)
217}
218
219/// Load configuration from a TOML string (useful for testing)
220pub fn load_from_str(content: &str) -> Result<Config> {
221    let config: Config = toml::from_str(content)?;
222    config.validate()?;
223    Ok(config)
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn default_config_is_valid() {
232        let config = Config::default();
233        assert!(config.validate().is_ok());
234    }
235
236    #[test]
237    fn load_from_toml_string() {
238        let toml = r#"
239            data_dir = "/custom/path"
240            log_level = "debug"
241            log_format = "pretty"
242
243            [server]
244            allow_cross_tenant_project_fallback = true
245        "#;
246
247        let config = load_from_str(toml).unwrap();
248        assert_eq!(config.data_dir, PathBuf::from("/custom/path"));
249        assert_eq!(config.log_level, "debug");
250        assert_eq!(config.log_format, "pretty");
251        assert!(config.server.allow_cross_tenant_project_fallback);
252    }
253
254    #[test]
255    fn partial_toml_uses_defaults() {
256        let toml = r#"
257            log_level = "warn"
258        "#;
259
260        let config = load_from_str(toml).unwrap();
261        assert_eq!(config.log_level, "warn");
262        // Other fields should use defaults
263        assert_eq!(config.log_format, "json");
264        assert!(!config.server.allow_cross_tenant_project_fallback);
265    }
266
267    #[test]
268    fn empty_toml_uses_all_defaults() {
269        let config = load_from_str("").unwrap();
270        assert_eq!(config.log_level, "info");
271        assert_eq!(config.log_format, "json");
272        assert_eq!(config.data_dir, PathBuf::from("~/.memd/data"));
273    }
274
275    #[test]
276    fn expand_tilde_works() {
277        std::env::set_var("HOME", "/home/testuser");
278        let path = PathBuf::from("~/.memd/data");
279        let expanded = expand_tilde(&path).unwrap();
280        assert_eq!(expanded, PathBuf::from("/home/testuser/.memd/data"));
281    }
282
283    #[test]
284    fn expand_tilde_absolute_path_unchanged() {
285        let path = PathBuf::from("/absolute/path");
286        let expanded = expand_tilde(&path).unwrap();
287        assert_eq!(expanded, PathBuf::from("/absolute/path"));
288    }
289
290    #[test]
291    fn invalid_log_level_rejected() {
292        let toml = r#"log_level = "invalid""#;
293        let result = load_from_str(toml);
294        assert!(result.is_err());
295        assert!(result
296            .unwrap_err()
297            .to_string()
298            .contains("invalid log_level"));
299    }
300
301    #[test]
302    fn invalid_log_format_rejected() {
303        let toml = r#"log_format = "xml""#;
304        let result = load_from_str(toml);
305        assert!(result.is_err());
306        assert!(result
307            .unwrap_err()
308            .to_string()
309            .contains("invalid log_format"));
310    }
311
312    #[test]
313    fn config_serializes_to_toml() {
314        let config = Config::default();
315        let toml_str = toml::to_string_pretty(&config).unwrap();
316        assert!(toml_str.contains("data_dir"));
317        assert!(toml_str.contains("log_level"));
318    }
319
320    #[test]
321    fn load_config_returns_default_when_no_file() {
322        // When no path provided and no XDG config exists, should return defaults
323        let config = load_config(None).unwrap();
324        assert_eq!(config.log_level, "info");
325    }
326
327    #[test]
328    fn legacy_transport_keys_are_ignored() {
329        let toml = r#"
330            [server]
331            transport = "http"
332            bind = "127.0.0.1:8787"
333            path = "/legacy"
334        "#;
335
336        let config = load_from_str(toml).unwrap();
337        assert!(!config.server.allow_cross_tenant_project_fallback);
338    }
339
340    #[test]
341    fn project_aliases_load_from_toml() {
342        let toml = r#"
343            [server]
344
345            [[server.project_aliases]]
346            tenant_id = "memd"
347            project_id = "memd"
348
349            [[server.project_aliases.aliases]]
350            tenant_id = "default"
351            reason = "historical writes"
352        "#;
353
354        let config = load_from_str(toml).unwrap();
355        assert_eq!(config.server.project_aliases.len(), 1);
356        assert_eq!(config.server.project_aliases[0].aliases.len(), 1);
357        assert_eq!(
358            config.server.project_aliases[0].aliases[0]
359                .reason
360                .as_deref(),
361            Some("historical writes")
362        );
363    }
364
365    #[test]
366    fn project_aliases_allow_project_renames() {
367        let toml = r#"
368            [server]
369
370            [[server.project_aliases]]
371            tenant_id = "memd"
372            project_id = "memd"
373
374            [[server.project_aliases.aliases]]
375            tenant_id = "default"
376            project_id = "old_memd"
377        "#;
378
379        let config = load_from_str(toml).unwrap();
380        assert_eq!(
381            config.server.project_aliases[0].aliases[0]
382                .project_id
383                .as_deref(),
384            Some("old_memd")
385        );
386    }
387
388    #[test]
389    fn legacy_server_path_is_ignored() {
390        let toml = r#"
391            [server]
392            path = "legacy"
393        "#;
394
395        let config = load_from_str(toml).unwrap();
396        assert!(config.server.project_aliases.is_empty());
397    }
398}