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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Simplified configuration manager for the Rialo CDK.
//!
//! This module provides a clean interface to the layered configuration system
//! using schema-generated types directly, eliminating the need for complex
//! conversion layers.
use std::{
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
use anyhow::{anyhow, Result};
#[cfg(feature = "file-storage")]
use dirs;
#[cfg(feature = "file-storage")]
use rialo_modular_config::FileLayer;
use rialo_modular_config::{
ConfigLayer, ConfigLayerSource, ConfigValue, InMemoryLayer, LayeredConfig, LayeredConfigBuilder,
};
use serde_json::Value;
use crate::config::generated::RialoCdkConfigurationSchema;
/// Embedded JSON schema for CDK configuration
#[cfg(feature = "schema-validation")]
const CDK_CONFIG_SCHEMA: &str = include_str!("../../schemas/cdk-config.json");
/// Embedded default TOML configuration for CDK
const CDK_DEFAULTS_TOML: &str = include_str!("../../config/defaults.toml");
/// Simplified configuration manager that wraps LayeredConfig with schema-aware operations.
///
/// This manager provides a clean interface for loading and saving configuration
/// using the schema-generated types directly, eliminating complex conversion layers.
pub struct ConfigManager {
layered_config: Arc<RwLock<LayeredConfig>>,
user_config_path: PathBuf,
#[allow(dead_code)]
overrides: Option<std::collections::HashMap<String, String>>,
}
impl ConfigManager {
/// Create a new configuration manager with the specified user config path.
///
/// # Arguments
///
/// * `user_config_path` - Path to the user's configuration file
///
/// # Returns
///
/// A configured ConfigManager or an error if initialization fails
pub fn new(user_config_path: impl Into<PathBuf>) -> Result<Self> {
let user_config_path = user_config_path.into();
// Create minimal layer stack: Default -> User
let default_layer = Self::create_default_layer()?;
let layered_config = LayeredConfigBuilder::new().with_layer(default_layer);
#[cfg(feature = "file-storage")]
let layered_config = layered_config.with_layer(
FileLayer::new(&user_config_path)
.with_source(ConfigLayerSource::User(user_config_path.clone()))
.required(false) // File might not exist initially
.build()?,
);
#[cfg(feature = "schema-validation")]
let layered_config = layered_config.with_schema(Self::load_schema()?).build()?;
#[cfg(not(feature = "schema-validation"))]
let layered_config = layered_config.build()?;
Ok(Self {
layered_config: Arc::new(RwLock::new(layered_config)),
user_config_path,
overrides: None,
})
}
/// Create a new configuration manager with overrides.
///
/// # Arguments
///
/// * `user_config_path` - Path to the user's configuration file
/// * `overrides` - argument overrides as key-value pairs
///
/// # Returns
///
/// A configured ConfigManager with overrides applied
pub fn with_overrides(
user_config_path: impl Into<PathBuf>,
overrides: std::collections::HashMap<String, String>,
) -> Result<Self> {
let user_config_path = user_config_path.into();
// Create layer stack: Default -> [User] -> Overrides
let default_layer = Self::create_default_layer()?;
#[cfg(feature = "file-storage")]
let mut layered_config = LayeredConfigBuilder::new().with_layer(default_layer);
#[cfg(not(feature = "file-storage"))]
let layered_config = LayeredConfigBuilder::new().with_layer(default_layer);
// Add user file layer only if file-storage is enabled
#[cfg(feature = "file-storage")]
{
let user_layer = FileLayer::new(&user_config_path)
.with_source(ConfigLayerSource::User(user_config_path.clone()))
.required(false)
.build()?;
layered_config = layered_config.with_layer(user_layer);
}
// Add overrides layer
let overrides_layer = Self::create_overrides_layer(&overrides)?;
let layered_config = layered_config.with_layer(overrides_layer);
#[cfg(feature = "schema-validation")]
let layered_config = layered_config.with_schema(Self::load_schema()?).build()?;
#[cfg(not(feature = "schema-validation"))]
let layered_config = layered_config.build()?;
Ok(Self {
layered_config: Arc::new(RwLock::new(layered_config)),
user_config_path,
overrides: Some(overrides),
})
}
/// Load the complete configuration as a schema type.
///
/// # Returns
///
/// The resolved configuration as a RialoCdkConfigurationSchema
pub fn load(&self) -> Result<RialoCdkConfigurationSchema> {
let layered_config = self
.layered_config
.read()
.map_err(|e| anyhow!("Failed to acquire read lock on layered config: {}", e))?;
let resolved = layered_config.get_resolved_values();
// Convert flat keys to nested structure and then to JSON
let nested_config = ConfigValue::from_flat_map(resolved);
let json_value = nested_config.to_json_value();
serde_json::from_value(json_value)
.map_err(|e| anyhow!("Failed to deserialize configuration to schema type: {}", e))
}
/// Save the complete configuration to the user layer.
///
/// This will write all configuration values to the user's config file,
/// overwriting any existing values but preserving the layered structure.
///
/// **Note**: This method is only available with the `file-storage` feature.
///
/// # Arguments
///
/// * `config` - The configuration to save
///
/// # Returns
///
/// Success or an error if saving fails
#[cfg(feature = "file-storage")]
pub fn save(&self, config: &RialoCdkConfigurationSchema) -> Result<()> {
let layered_config = self
.layered_config
.read()
.map_err(|e| anyhow!("Failed to acquire read lock on layered config: {}", e))?;
let user_layer = layered_config
.find_user_layer()
.ok_or_else(|| anyhow!("No user layer available for saving"))?;
// Convert config to JSON (already has cdk structure)
let json_value = serde_json::to_value(config)?;
Self::save_json_to_layer(&layered_config, &json_value, user_layer, None)?;
// Drop the borrow before reloading
drop(layered_config);
// Reload to pick up the saved changes
self.reload()?;
Ok(())
}
/// Get a specific configuration value by key.
///
/// # Arguments
///
/// * `key` - The configuration key (supports dot notation)
///
/// # Returns
///
/// The configuration value if found
pub fn get<T>(&self, key: &str) -> Option<T>
where
T: serde::de::DeserializeOwned,
{
// Namespace the key under "cdk"
let namespaced_key = format!("cdk.{}", key);
self.layered_config
.read()
.map_err(|e| anyhow!("Failed to acquire read lock on layered config: {}", e))
.ok()?
.get(&namespaced_key)
}
/// Set a specific configuration value.
///
/// With `file-storage` enabled: Saves to the user's config file and persists between sessions.
/// Without `file-storage`: Returns an error - use overrides or modify defaults at startup instead.
///
/// # Arguments
///
/// * `key` - The configuration key (supports dot notation)
/// * `value` - The value to set
///
/// # Returns
///
/// Success or an error if setting fails (includes validation errors)
#[cfg(feature = "file-storage")]
pub fn set<T>(&self, key: &str, value: T) -> Result<()>
where
T: serde::Serialize,
{
let layered_config = self
.layered_config
.write()
.map_err(|e| anyhow!("Failed to acquire write lock on layered config: {}", e))?;
let user_layer = layered_config
.find_user_layer()
.ok_or_else(|| anyhow!("No user layer available for setting values"))?;
// Namespace the key under "cdk"
let namespaced_key = format!("cdk.{}", key);
layered_config.set_in_layer(&namespaced_key, value, user_layer)?;
// Drop the borrow before reloading
drop(layered_config);
// Reload to ensure the changes are reflected immediately
self.reload()?;
Ok(())
}
#[cfg(not(feature = "file-storage"))]
pub fn set<T>(&self, _key: &str, _value: T) -> Result<()>
where
T: serde::Serialize,
{
Err(anyhow!(
"Configuration setting is not available without the 'file-storage' feature. \
Use overrides when creating the ConfigManager instead."
))
}
/// Get direct access to the underlying LayeredConfig for advanced use cases.
///
/// Note: This returns a borrowed reference through RwLock. Be careful not to
/// cause panics by borrowing mutably while this reference is active.
///
/// # Returns
///
/// Reference to the underlying LayeredConfig
pub fn with_layered_config<F, R>(&self, f: F) -> Result<R>
where
F: FnOnce(&LayeredConfig) -> R,
{
let layered_config = self
.layered_config
.read()
.map_err(|e| anyhow!("Failed to acquire read lock on layered config: {}", e))?;
Ok(f(&layered_config))
}
/// Reload the configuration by reconstructing the LayeredConfig.
///
/// This picks up any changes made to the underlying files and preserves
/// overrides if they were originally provided.
///
/// # Returns
///
/// Success or an error if reloading fails
#[cfg(feature = "file-storage")]
fn reload(&self) -> Result<()> {
// Reconstruct the layered config with the same structure as new()
let default_layer = Self::create_default_layer()?;
let mut builder = LayeredConfigBuilder::new().with_layer(default_layer);
// Add user file layer only if file-storage is enabled
#[cfg(feature = "file-storage")]
{
let user_layer = FileLayer::new(&self.user_config_path)
.with_source(ConfigLayerSource::User(self.user_config_path.clone()))
.required(false)
.build()?;
builder = builder.with_layer(user_layer);
}
// Re-add overrides if they exist
if let Some(ref overrides) = self.overrides {
let overrides_layer = Self::create_overrides_layer(overrides)?;
builder = builder.with_layer(overrides_layer);
}
#[cfg(feature = "schema-validation")]
let new_layered_config = builder.with_schema(Self::load_schema()?).build()?;
#[cfg(not(feature = "schema-validation"))]
let new_layered_config = builder.build()?;
// Replace the current layered config
*self
.layered_config
.write()
.map_err(|e| anyhow!("Failed to acquire write lock on layered config: {}", e))? =
new_layered_config;
Ok(())
}
/// Get the path to the user configuration file.
///
/// # Returns
///
/// Path to the user's configuration file
pub fn user_config_path(&self) -> &Path {
&self.user_config_path
}
/// Create a overrides layer from the provided overrides.
fn create_overrides_layer(
overrides: &std::collections::HashMap<String, String>,
) -> Result<ConfigLayer> {
let mut overrides_layer_builder = InMemoryLayer::new(ConfigLayerSource::CommandLineArgs);
for (key, value) in overrides {
// Namespace the key under "cdk"
let namespaced_key = format!("cdk.{}", key);
// Convert string values to appropriate types based on key
match key.as_str() {
"verbose_mode" => {
let bool_value: bool = value
.parse()
.map_err(|_| anyhow!("Invalid boolean value for {}: {}", key, value))?;
overrides_layer_builder =
overrides_layer_builder.with_value(&namespaced_key, bool_value);
}
_ => {
// For other values, keep as strings
overrides_layer_builder =
overrides_layer_builder.with_value(&namespaced_key, value.as_str());
}
}
}
Ok(overrides_layer_builder.build())
}
/// Create the default configuration layer from embedded TOML.
fn create_default_layer() -> Result<ConfigLayer> {
let toml_value: toml::Value = toml::from_str(CDK_DEFAULTS_TOML)
.map_err(|e| anyhow!("Failed to parse embedded CDK defaults: {}", e))?;
let config_value = ConfigValue::from_toml_value(toml_value);
let values = if let ConfigValue::Object(map) = config_value {
map
} else {
return Err(anyhow!("CDK defaults must be a TOML table"));
};
Ok(InMemoryLayer::new(ConfigLayerSource::Default)
.with_config_values(values)
.build())
}
/// Load the JSON schema for validation.
/// Since the CDK should only validate the "cdk" section, we extract that schema portion.
#[cfg(feature = "schema-validation")]
fn load_schema() -> Result<Value> {
let full_schema: Value = serde_json::from_str(CDK_CONFIG_SCHEMA)
.map_err(|e| anyhow!("Failed to parse embedded CDK schema: {}", e))?;
// Use the full schema since we validate the complete nested structure
Ok(full_schema)
}
/// Get the embedded CDK JSON schema for external use (e.g., CLI merging).
///
/// # Returns
///
/// The CDK configuration JSON schema as a serde_json::Value
#[cfg(feature = "schema-validation")]
pub fn get_cdk_schema() -> Result<Value> {
Self::load_schema()
}
/// Get the embedded CDK JSON schema for external use (no-op when schema-validation is disabled)
#[cfg(not(feature = "schema-validation"))]
pub fn get_cdk_schema() -> Result<Value> {
Err(anyhow!(
"Schema validation is not available when 'schema-validation' feature is disabled"
))
}
/// Get the embedded CDK defaults TOML as a string for external use (e.g., CLI merging).
///
/// # Returns
///
/// The CDK defaults TOML content as a string
pub fn get_cdk_defaults_toml() -> &'static str {
CDK_DEFAULTS_TOML
}
/// Recursively save a JSON value to a configuration layer.
#[cfg(feature = "file-storage")]
fn save_json_to_layer(
layered_config: &LayeredConfig,
json_value: &Value,
layer: &ConfigLayer,
prefix: Option<&str>,
) -> Result<()> {
match json_value {
Value::Object(obj) => {
for (key, value) in obj {
let full_key = match prefix {
Some(p) => format!("{}.{}", p, key),
None => key.clone(),
};
match value {
Value::Object(_) => {
// Recursively handle nested objects
Self::save_json_to_layer(
layered_config,
value,
layer,
Some(&full_key),
)?;
}
_ => {
// Save primitive values directly
layered_config.set_in_layer(&full_key, value, layer)?;
}
}
}
}
_ => {
// If we have a non-object at the root, save it directly
let key = prefix.unwrap_or("root");
layered_config.set_in_layer(key, json_value, layer)?;
}
}
Ok(())
}
}
/// Utility functions for common configuration operations.
pub struct ConfigUtils;
impl ConfigUtils {
/// Get the default user configuration directory.
///
/// # Returns
///
/// Path to the default configuration directory
#[cfg(feature = "file-storage")]
pub fn default_config_dir() -> Result<PathBuf> {
// Preferred OS-specific config directory (`<os-specific-config-dir>/rialo`).
let preferred = dirs::config_dir()
.map(|config_dir| config_dir.join("rialo"))
.ok_or_else(|| anyhow!("Cannot determine config directory"))?;
// Legacy directory (~/.rialo).
let legacy = dirs::home_dir()
.map(|home| home.join(".rialo"))
.ok_or_else(|| anyhow!("Cannot determine home directory"))?;
// Use legacy if it exists AND preferred does not exist.
// Otherwise, use preferred.
let dir = if legacy.exists() && !preferred.exists() {
legacy
} else {
preferred
};
Ok(dir)
}
/// Get the default user configuration file path.
///
/// # Returns
///
/// Path to the default configuration file
#[cfg(feature = "file-storage")]
pub fn default_config_file() -> Result<PathBuf> {
Ok(Self::default_config_dir()?.join("config.toml"))
}
/// Create a configuration manager with default paths.
///
/// # Returns
///
/// A ConfigManager using the default configuration file location
#[cfg(feature = "file-storage")]
pub fn create_default_manager() -> Result<ConfigManager> {
ConfigManager::new(Self::default_config_file()?)
}
/// Create a configuration manager (in-memory only when file-storage is disabled).
///
/// # Returns
///
/// A ConfigManager using only default configuration
#[cfg(not(feature = "file-storage"))]
pub fn create_default_manager() -> Result<ConfigManager> {
ConfigManager::new(PathBuf::new()) // Path is ignored without file-storage
}
/// Get RPC URL for the specified network from a configuration.
///
/// # Arguments
///
/// * `config` - The configuration to query
/// * `network` - The network name (if None, uses current network)
///
/// # Returns
///
/// The RPC URL for the network
pub fn get_rpc_url(
config: &RialoCdkConfigurationSchema,
network: Option<&str>,
) -> Result<String> {
let cdk_config = config
.cdk
.as_ref()
.ok_or_else(|| anyhow!("CDK configuration section is missing"))?;
let current_network_str = cdk_config.network.to_string();
let target_network = network.unwrap_or(¤t_network_str);
cdk_config
.rpc_urls
.get(target_network)
.cloned()
.ok_or_else(|| anyhow!("No RPC URL configured for network: {}", target_network))
}
}
#[cfg(test)]
mod tests {
use tempfile::TempDir;
use super::*;
#[test]
fn test_config_manager_creation() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test_config.toml");
let manager = ConfigManager::new(&config_path).unwrap();
// Should be able to load default configuration
let config = manager.load().unwrap();
assert_eq!(config.cdk.as_ref().unwrap().network.to_string(), "localnet");
assert_eq!(
config
.cdk
.as_ref()
.unwrap()
.default_balance_unit
.to_string(),
"rlo"
);
assert!(!config.cdk.as_ref().unwrap().verbose_mode);
}
#[test]
fn test_config_save_and_load() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test_save.toml");
let manager = ConfigManager::new(&config_path).unwrap();
// Load default config and modify it
let mut config = manager.load().unwrap();
if let Some(cdk_config) = &mut config.cdk {
cdk_config.verbose_mode = true;
}
// Save and reload (should now work automatically with interior mutability)
manager.save(&config).unwrap();
let reloaded_config = manager.load().unwrap();
assert!(reloaded_config.cdk.as_ref().unwrap().verbose_mode);
assert_eq!(
reloaded_config.cdk.as_ref().unwrap().network.to_string(),
"localnet"
); // Should preserve other values
}
#[test]
fn test_individual_set_and_get() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test_individual.toml");
let manager = ConfigManager::new(&config_path).unwrap();
// Set individual value
manager.set("verbose_mode", true).unwrap();
// Get individual value (should work with interior mutability)
let verbose: bool = manager.get("verbose_mode").unwrap();
assert!(verbose);
// Load complete config to verify
let config = manager.load().unwrap();
assert!(config.cdk.as_ref().unwrap().verbose_mode);
}
#[test]
fn test_overrides() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test_overrides.toml");
let mut overrides = std::collections::HashMap::new();
overrides.insert("verbose_mode".to_string(), "true".to_string());
overrides.insert("network".to_string(), "testnet".to_string());
let manager = ConfigManager::with_overrides(&config_path, overrides).unwrap();
let config = manager.load().unwrap();
assert!(config.cdk.as_ref().unwrap().verbose_mode); // From overrides
assert_eq!(config.cdk.as_ref().unwrap().network.to_string(), "testnet");
// From overrides
}
#[test]
fn test_schema_validation() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("test_validation.toml");
let manager = ConfigManager::new(&config_path).unwrap();
// Try to set an invalid network (should fail validation)
let result = manager.set("network", "invalid_network");
assert!(result.is_err());
// Try to set a valid network (should succeed)
let result = manager.set("network", "testnet");
assert!(result.is_ok());
// Verify the change (should work with interior mutability)
let network: String = manager.get("network").unwrap();
assert_eq!(network, "testnet");
}
#[cfg(not(feature = "file-storage"))]
#[test]
fn test_no_file_storage_behavior() {
use std::path::PathBuf;
// Should create manager successfully even without file-storage
let manager = ConfigManager::new(PathBuf::from("/nonexistent/path")).unwrap();
// Should be able to load defaults
let config = manager.load().unwrap();
assert_eq!(config.cdk.as_ref().unwrap().network.to_string(), "localnet");
// Should NOT be able to set individual values (no file-storage)
let result = manager.set("verbose_mode", true);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("file-storage"));
// Should be able to get values from defaults
let verbose: bool = manager.get("verbose_mode").unwrap();
assert!(!verbose); // Default is false
}
#[cfg(not(feature = "file-storage"))]
#[test]
fn test_no_file_storage_with_overrides() {
use std::{collections::HashMap, path::PathBuf};
// Create overrides
let mut overrides = HashMap::new();
overrides.insert("verbose_mode".to_string(), "true".to_string());
overrides.insert("network".to_string(), "testnet".to_string());
// Should work with overrides even without file-storage
let manager = ConfigManager::with_overrides(PathBuf::from("/ignored"), overrides).unwrap();
let config = manager.load().unwrap();
assert!(config.cdk.as_ref().unwrap().verbose_mode); // From overrides
assert_eq!(config.cdk.as_ref().unwrap().network.to_string(), "testnet"); // From overrides
// Default config manager should also work
let default_manager = ConfigUtils::create_default_manager().unwrap();
let default_config = default_manager.load().unwrap();
assert_eq!(
default_config.cdk.as_ref().unwrap().network.to_string(),
"localnet"
);
}
}