rcman 0.1.9

Framework-agnostic settings management with schema, backup/restore, secrets and derive macro support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#[cfg(any(feature = "keychain", feature = "encrypted-file"))]
use crate::config::SettingMetadata;
use crate::config::SettingsSchema;
use crate::error::{Error, Result};
use crate::manager::cache::CachedSettings;
use crate::manager::core::SettingsManager;
use crate::storage::StorageBackend;
use crate::utils::sync::RwLockExt;

use log::{debug, info};
use serde_json::{Value, json};

impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema> {
    #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
    fn save_secret_setting(
        &self,
        full_key: &str,
        value: &Value,
        metadata: &SettingMetadata,
    ) -> Result<()> {
        let default_value = metadata.default.clone();

        let old_value = if self.credentials.is_some() {
            match self.get_credential_with_profile(full_key) {
                Ok(Some(secret_value)) => Value::String(secret_value),
                Ok(None) => default_value.clone(),
                Err(err) => {
                    debug!("Failed to read current secret value for {full_key} before save: {err}");
                    default_value.clone()
                }
            }
        } else {
            default_value.clone()
        };

        if *value == default_value {
            if self.credentials.is_some() {
                self.remove_credential_with_profile(full_key)?;
            }
            info!("Secret {full_key} set to default, removed from keychain");

            if old_value != *value {
                self.events.notify(full_key, &old_value, value);
            }

            return Ok(());
        }

        let value_str = match value {
            Value::String(s) => s.clone(),
            _ => value.to_string(),
        };
        self.store_credential_with_profile(full_key, &value_str)?;
        info!("Secret setting {full_key} stored in keychain");

        if old_value != *value {
            self.events.notify(full_key, &old_value, value);
        }

        Ok(())
    }

    /// Get the current settings file path
    ///
    /// This returns the path where settings.json is stored.
    /// If profiles are enabled, this points to the active profile's directory.
    pub(crate) fn settings_path(&self) -> Result<std::path::PathBuf> {
        let dir = self.settings_dir.read_recovered()?;
        Ok(dir.join(&self.config.settings_file))
    }

    /// Get the credential manager, potentially with profile context
    #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
    pub(crate) fn get_credential_with_profile(&self, key: &str) -> Result<Option<String>> {
        let creds = self
            .credentials
            .as_ref()
            .ok_or(Error::Credential("Credentials not enabled".to_string()))?;

        #[cfg(feature = "profiles")]
        let profile = self
            .profile_manager
            .as_ref()
            .and_then(|pm| pm.active().ok());

        #[cfg(not(feature = "profiles"))]
        let profile: Option<String> = None;

        creds.get_with_profile(key, profile.as_deref())
    }

    /// Store credential with profile context
    #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
    pub(crate) fn store_credential_with_profile(&self, key: &str, value: &str) -> Result<()> {
        let creds = self
            .credentials
            .as_ref()
            .ok_or(Error::Credential("Credentials not enabled".to_string()))?;

        #[cfg(feature = "profiles")]
        let profile = self
            .profile_manager
            .as_ref()
            .and_then(|pm| pm.active().ok());

        #[cfg(not(feature = "profiles"))]
        let profile: Option<String> = None;

        creds.store_with_profile(key, value, profile.as_deref())
    }

    /// Remove credential with profile context
    #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
    pub(crate) fn remove_credential_with_profile(&self, key: &str) -> Result<()> {
        let creds = self
            .credentials
            .as_ref()
            .ok_or(Error::Credential("Credentials not enabled".to_string()))?;

        #[cfg(feature = "profiles")]
        let profile = self
            .profile_manager
            .as_ref()
            .and_then(|pm| pm.active().ok());

        #[cfg(not(feature = "profiles"))]
        let profile: Option<String> = None;

        creds.remove_with_profile(key, profile.as_deref())
    }

    /// Invalidate the settings cache
    ///
    /// Call this if the settings file was modified externally.
    pub fn invalidate_cache(&self) {
        self.settings_cache.invalidate();

        #[cfg(feature = "profiles")]
        if let Some(pm) = &self.profile_manager {
            pm.invalidate_manifest();
        }

        if let Ok(sub_settings) = self.sub_settings.read_recovered() {
            for sub in sub_settings.values() {
                sub.invalidate_cache();
            }
        } else {
            debug!("Failed to invalidate sub-settings cache due to lock recovery error");
        }

        debug!("Settings cache invalidated");
    }

    /// Save a single setting value.
    ///
    /// This method validates the value, updates the cache, and writes to disk.
    /// If the setting is marked as `secret: true` and credentials are enabled,
    /// the value will be stored in the OS keychain instead of the settings file.
    /// If the value equals the default, it will be removed from storage.
    /// If the value is unchanged, no I/O occurs.
    ///
    /// # Arguments
    ///
    /// * `category` - Category name (e.g., "ui", "general")
    /// * `key` - Setting key within the category (e.g., "theme", "language")
    /// * `value` - New value as JSON
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * Validation fails
    /// * Saving to storage fails
    /// * Parsing the existing settings fails
    ///
    pub fn save_setting(&self, category: &str, key: &str, value: &Value) -> Result<()> {
        let path = self.settings_path()?;
        let full_key = format!("{category}.{key}");

        // Run user-registered validators
        self.events
            .validate(&full_key, value)
            .map_err(|msg| Error::InvalidSettingValue {
                key: full_key.clone(),
                reason: msg,
            })?;

        let metadata = &self.schema_metadata;

        // Route secret settings to the credential backend
        #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
        if let Some(setting_meta) = metadata.get(&full_key).filter(|m| m.is_secret()) {
            self.save_secret_setting(&full_key, value, setting_meta)?;
            return Ok(());
        }

        let _write_guard = self
            .settings_write_lock
            .lock()
            .map_err(|_| Error::Config("Settings write lock poisoned".into()))?;

        self.ensure_cache_populated()?;

        let mut stored = self
            .settings_cache
            .get_stored()?
            .unwrap_or_else(|| json!({}));

        // Validate against schema and get metadata
        let setting_meta = metadata
            .get(&full_key)
            .ok_or_else(|| Error::SettingNotFound(full_key.clone()))?;

        if let Err(e) = setting_meta.validate(value) {
            return Err(Error::Config(format!(
                "Validation failed for {full_key}: {e}"
            )));
        }

        let default_value = setting_meta.default.clone();

        let old_value = stored
            .get(category)
            .and_then(|cat| cat.get(key))
            .cloned()
            .unwrap_or_else(|| default_value.clone());

        if old_value == *value {
            debug!("Setting {full_key} unchanged, skipping save");
            return Ok(());
        }

        let stored_obj = stored
            .as_object_mut()
            .ok_or_else(|| Error::Parse("Settings root is not an object".into()))?;

        {
            let category_obj = stored_obj
                .entry(category.to_string())
                .or_insert_with(|| json!({}))
                .as_object_mut()
                .ok_or_else(|| Error::Parse(format!("Category {category} is not an object")))?;

            // If value equals default, remove it to keep the file minimal
            if *value == default_value {
                category_obj.remove(key);
                debug!("Setting {full_key} set to default, removed from store");
            } else {
                category_obj.insert(key.to_string(), value.clone());
                debug!("Saved setting {full_key}");
            }
        } // category_obj borrow ends

        // Remove empty categories
        if stored_obj
            .get(category)
            .and_then(|v| v.as_object())
            .is_some_and(serde_json::Map::is_empty)
        {
            stored_obj.remove(category);
        }

        self.storage.write(&path, &stored)?;
        self.settings_cache.update_stored(stored)?;

        info!("Setting {full_key} saved");
        self.events.notify(&full_key, &old_value, value);

        Ok(())
    }

    /// Reset a single setting to default
    ///
    /// # Arguments
    ///
    /// * `category` - Category of the setting
    /// * `key` - Key of the setting
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The setting doesn't exist
    /// - Writing to storage fails
    pub fn reset_setting(&self, category: &str, key: &str) -> Result<Value> {
        let metadata_key = format!("{category}.{key}");
        let default_value = self
            .schema_metadata
            .get(&metadata_key)
            .map(|m| m.default.clone())
            .ok_or_else(|| Error::SettingNotFound(format!("{category}.{key}")))?;

        self.save_setting(category, key, &default_value)?;

        info!("Setting {category}.{key} reset to default");
        Ok(default_value)
    }

    /// Reset all settings to defaults
    /// # Errors
    ///
    /// Returns an error if writing to storage fails or credential clearing fails.
    pub fn reset_all(&self) -> Result<()> {
        let path = self.settings_path()?;

        self.ensure_cache_populated()?;

        let stored = self
            .settings_cache
            .get_stored()?
            .unwrap_or_else(|| json!({}));

        let mut changed_events = Vec::new();
        for (full_key, metadata) in self.schema_metadata.iter() {
            let mut key_parts = full_key.split('.');
            let (Some(category), Some(setting), None) =
                (key_parts.next(), key_parts.next(), key_parts.next())
            else {
                debug!("Skipping invalid schema key format during reset_all: {full_key}");
                continue;
            };

            let default_value = metadata.default.clone();

            #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
            let old_value = if metadata.is_secret() && self.credentials.is_some() {
                match self.get_credential_with_profile(full_key) {
                    Ok(Some(secret_value)) => Value::String(secret_value),
                    Ok(None) => default_value.clone(),
                    Err(err) => {
                        debug!(
                            "Failed to read secret value for {full_key} during reset_all: {err}"
                        );
                        default_value.clone()
                    }
                }
            } else {
                stored
                    .get(category)
                    .and_then(|cat| cat.get(setting))
                    .cloned()
                    .unwrap_or_else(|| default_value.clone())
            };

            #[cfg(not(any(feature = "keychain", feature = "encrypted-file")))]
            let old_value = stored
                .get(category)
                .and_then(|cat| cat.get(setting))
                .cloned()
                .unwrap_or_else(|| default_value.clone());

            if old_value != default_value {
                changed_events.push((full_key.clone(), old_value, default_value));
            }
        }

        // Write empty object
        self.storage.write(&path, &json!({}))?;

        #[cfg(any(feature = "keychain", feature = "encrypted-file"))]
        if let Some(ref creds) = self.credentials {
            creds.clear()?;
            info!("All credentials cleared");
        }

        info!("All settings reset to defaults");

        self.invalidate_cache();

        for (full_key, old_value, new_value) in changed_events {
            self.events.notify(&full_key, &old_value, &new_value);
        }

        Ok(())
    }

    /// Load settings from disk, applying migrations if needed
    pub(crate) fn load_from_disk(&self) -> Result<CachedSettings> {
        let settings_path = self.settings_path()?;
        let mut value: Value = match self.storage.read(&settings_path) {
            Ok(v) => v,
            Err(Error::FileRead { .. } | Error::PathNotFound(_) | Error::Parse(_)) => {
                // Start empty if not found or corrupted/invalid JSON
                json!({})
            }
            Err(e) => return Err(e),
        };

        // Apply migrations
        if let Some(migrator) = &self.config.migrator {
            let original = value.clone();
            value = migrator(value);
            if value != original {
                info!("Migrated settings file");
                self.storage.write(&settings_path, &value)?;
            }
        }

        // Strip null values: null in a settings file is a legacy artifact from
        // older code that used Option<T> fields (serialized as null when None).
        // rcman never writes null — it removes keys equal to the default instead.
        // Stripping here keeps deep_merge a pure function and prevents null from
        // clobbering schema defaults.
        crate::utils::value::strip_nulls(&mut value);

        Ok(CachedSettings {
            stored: value,
            merged: std::sync::OnceLock::new(),
            defaults: self.schema_defaults.clone(),
            generation: 0,
        })
    }

    /// Ensure the settings cache is populated
    ///
    /// This method is thread-safe and safe to call multiple times.
    /// It uses double-checked locking to avoid unnecessary locks.
    ///
    /// # Errors
    ///
    /// Returns an error if the settings cannot be loaded from disk.
    pub fn ensure_cache_populated(&self) -> Result<()> {
        if self.settings_cache.is_populated() {
            return Ok(());
        }

        self.settings_cache.populate(|| self.load_from_disk())?;

        Ok(())
    }
}