distributed-config 0.1.0

A robust configuration management library for Rust applications running in distributed environments
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
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
//! Configuration validation using JSON Schema

use crate::error::{ConfigError, Result};
use crate::value::ConfigValue;
use jsonschema::{Draft, JSONSchema};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use tracing::{debug, info};

/// Schema validator for configuration values
pub struct SchemaValidator {
    schemas: HashMap<String, JSONSchema>,
}

impl SchemaValidator {
    /// Create a new schema validator
    pub fn new() -> Self {
        Self {
            schemas: HashMap::new(),
        }
    }

    /// Add a schema for a specific configuration path
    pub fn add_schema<T>(mut self, path: &str) -> Self
    where
        T: serde::Serialize + for<'de> serde::Deserialize<'de>,
    {
        // Generate JSON schema from the type
        if let Ok(schema) = generate_schema_for_type::<T>() {
            if let Ok(compiled) = JSONSchema::compile(&schema) {
                self.schemas.insert(path.to_string(), compiled);
                info!("Added schema for configuration path: {}", path);
            }
        }
        self
    }

    /// Add a schema from a JSON schema object
    pub fn add_schema_from_json(mut self, path: &str, schema: JsonValue) -> Result<Self> {
        let compiled = JSONSchema::options()
            .with_draft(Draft::Draft7)
            .compile(&schema)
            .map_err(|e| ConfigError::ValidationError(format!("Invalid schema: {e}")))?;

        self.schemas.insert(path.to_string(), compiled);
        info!("Added JSON schema for configuration path: {}", path);
        Ok(self)
    }

    /// Add a schema from a JSON schema string
    pub fn add_schema_from_string(self, path: &str, schema_str: &str) -> Result<Self> {
        let schema: JsonValue = serde_json::from_str(schema_str)
            .map_err(|e| ConfigError::ValidationError(format!("Invalid schema JSON: {e}")))?;

        self.add_schema_from_json(path, schema)
    }

    /// Validate a configuration value against all applicable schemas
    pub fn validate(&self, config: &ConfigValue) -> Result<()> {
        // Convert ConfigValue to JSON for validation
        let json_value = config_value_to_json(config)?;

        let mut validation_errors = Vec::new();

        // Validate against each schema
        for (path, schema) in &self.schemas {
            if let Some(value_to_validate) = get_value_at_path(&json_value, path) {
                if let Err(errors) = schema.validate(&value_to_validate) {
                    for error in errors {
                        validation_errors.push(format!("Path '{path}': {error}"));
                    }
                }
            } else {
                debug!("No value found at path '{}' for validation", path);
            }
        }

        if !validation_errors.is_empty() {
            return Err(ConfigError::ValidationError(validation_errors.join("; ")));
        }

        debug!(
            "Configuration validation passed for {} schemas",
            self.schemas.len()
        );
        Ok(())
    }

    /// Validate a specific configuration value at a path
    pub fn validate_path(&self, path: &str, value: &ConfigValue) -> Result<()> {
        if let Some(schema) = self.schemas.get(path) {
            let json_value = config_value_to_json(value)?;

            let result = schema.validate(&json_value);
            if let Err(errors) = result {
                let error_messages: Vec<String> = errors.map(|e| e.to_string()).collect();
                return Err(ConfigError::ValidationError(error_messages.join("; ")));
            }
        }

        Ok(())
    }

    /// Get the list of schema paths
    pub fn schema_paths(&self) -> Vec<String> {
        self.schemas.keys().cloned().collect()
    }

    /// Check if a schema exists for a given path
    pub fn has_schema(&self, path: &str) -> bool {
        self.schemas.contains_key(path)
    }

    /// Remove a schema for a path
    pub fn remove_schema(&mut self, path: &str) -> bool {
        self.schemas.remove(path).is_some()
    }
}

impl Default for SchemaValidator {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert ConfigValue to JSON Value for validation
fn config_value_to_json(config: &ConfigValue) -> Result<JsonValue> {
    match config {
        ConfigValue::Null => Ok(JsonValue::Null),
        ConfigValue::Bool(b) => Ok(JsonValue::Bool(*b)),
        ConfigValue::Integer(i) => Ok(JsonValue::Number((*i).into())),
        ConfigValue::Float(f) => {
            if let Some(num) = serde_json::Number::from_f64(*f) {
                Ok(JsonValue::Number(num))
            } else {
                Ok(JsonValue::Null)
            }
        }
        ConfigValue::String(s) => Ok(JsonValue::String(s.clone())),
        ConfigValue::Array(arr) => {
            let json_arr: Result<Vec<JsonValue>> = arr.iter().map(config_value_to_json).collect();
            Ok(JsonValue::Array(json_arr?))
        }
        ConfigValue::Object(obj) => {
            let json_obj: Result<serde_json::Map<String, JsonValue>> = obj
                .iter()
                .map(|(k, v)| config_value_to_json(v).map(|json_v| (k.clone(), json_v)))
                .collect();
            Ok(JsonValue::Object(json_obj?))
        }
        ConfigValue::Duration(d) => Ok(JsonValue::Number(d.as_secs().into())),
    }
}

/// Get a value at a specific path in a JSON object
fn get_value_at_path(json: &JsonValue, path: &str) -> Option<JsonValue> {
    if path.is_empty() {
        return Some(json.clone());
    }

    let parts: Vec<&str> = path.split('.').collect();
    let mut current = json;

    for part in parts {
        match current {
            JsonValue::Object(obj) => {
                current = obj.get(part)?;
            }
            _ => return None,
        }
    }

    Some(current.clone())
}

/// Generate a JSON schema for a Rust type
fn generate_schema_for_type<T>() -> Result<JsonValue>
where
    T: serde::Serialize + for<'de> serde::Deserialize<'de>,
{
    // This is a simplified schema generator
    // In a real implementation, you might want to use a crate like `schemars`

    // For now, we'll create a basic schema structure
    let schema = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {},
        "additionalProperties": true
    });

    Ok(schema)
}

/// Common validation schemas
pub mod schemas {
    use super::*;

    /// Database configuration schema
    pub fn database_config() -> JsonValue {
        serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "host": {
                    "type": "string",
                    "format": "hostname"
                },
                "port": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 65535
                },
                "username": {
                    "type": "string",
                    "minLength": 1
                },
                "password": {
                    "type": "string",
                    "minLength": 1
                },
                "database": {
                    "type": "string",
                    "minLength": 1
                },
                "max_connections": {
                    "type": "integer",
                    "minimum": 1
                },
                "timeout": {
                    "type": "integer",
                    "minimum": 0
                }
            },
            "required": ["host", "port", "username", "password", "database"],
            "additionalProperties": false
        })
    }

    /// Server configuration schema
    pub fn server_config() -> JsonValue {
        serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "host": {
                    "type": "string",
                    "default": "0.0.0.0"
                },
                "port": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 65535
                },
                "workers": {
                    "type": "integer",
                    "minimum": 1
                },
                "debug": {
                    "type": "boolean",
                    "default": false
                },
                "log_level": {
                    "type": "string",
                    "enum": ["trace", "debug", "info", "warn", "error"]
                }
            },
            "required": ["port"],
            "additionalProperties": false
        })
    }

    /// Feature flags schema
    pub fn feature_flags() -> JsonValue {
        serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "patternProperties": {
                "^[a-zA-Z][a-zA-Z0-9_-]*$": {
                    "type": "boolean"
                }
            },
            "additionalProperties": false
        })
    }

    /// API configuration schema
    pub fn api_config() -> JsonValue {
        serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "base_url": {
                    "type": "string",
                    "format": "uri"
                },
                "timeout": {
                    "type": "integer",
                    "minimum": 0
                },
                "retries": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 10
                },
                "rate_limit": {
                    "type": "object",
                    "properties": {
                        "requests_per_second": {
                            "type": "integer",
                            "minimum": 1
                        },
                        "burst_size": {
                            "type": "integer",
                            "minimum": 1
                        }
                    },
                    "additionalProperties": false
                }
            },
            "required": ["base_url"],
            "additionalProperties": false
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_schema_validator_basic() {
        let mut validator = SchemaValidator::new();

        // Add a simple schema
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer", "minimum": 0}
            },
            "required": ["name"]
        });

        validator = validator.add_schema_from_json("person", schema).unwrap();

        // Valid configuration
        let mut config = HashMap::new();
        config.insert("name".to_string(), ConfigValue::String("John".to_string()));
        config.insert("age".to_string(), ConfigValue::Integer(25));
        let valid_config = ConfigValue::Object(config);

        assert!(validator.validate_path("person", &valid_config).is_ok());

        // Invalid configuration (missing required field)
        let mut invalid_config = HashMap::new();
        invalid_config.insert("age".to_string(), ConfigValue::Integer(25));
        let invalid_config = ConfigValue::Object(invalid_config);

        assert!(validator.validate_path("person", &invalid_config).is_err());
    }

    #[test]
    fn test_database_schema() {
        let mut validator = SchemaValidator::new();
        validator = validator
            .add_schema_from_json("database", schemas::database_config())
            .unwrap();

        // Valid database config
        let mut config = HashMap::new();
        config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        config.insert("port".to_string(), ConfigValue::Integer(5432));
        config.insert(
            "username".to_string(),
            ConfigValue::String("user".to_string()),
        );
        config.insert(
            "password".to_string(),
            ConfigValue::String("pass".to_string()),
        );
        config.insert(
            "database".to_string(),
            ConfigValue::String("mydb".to_string()),
        );
        let valid_config = ConfigValue::Object(config);

        assert!(validator.validate_path("database", &valid_config).is_ok());

        // Invalid database config (invalid port)
        let mut invalid_config = HashMap::new();
        invalid_config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        invalid_config.insert("port".to_string(), ConfigValue::Integer(70000)); // Invalid port
        invalid_config.insert(
            "username".to_string(),
            ConfigValue::String("user".to_string()),
        );
        invalid_config.insert(
            "password".to_string(),
            ConfigValue::String("pass".to_string()),
        );
        invalid_config.insert(
            "database".to_string(),
            ConfigValue::String("mydb".to_string()),
        );
        let invalid_config = ConfigValue::Object(invalid_config);

        assert!(validator
            .validate_path("database", &invalid_config)
            .is_err());
    }

    #[test]
    fn test_feature_flags_schema() {
        let mut validator = SchemaValidator::new();
        validator = validator
            .add_schema_from_json("feature_flags", schemas::feature_flags())
            .unwrap();

        // Valid feature flags
        let mut config = HashMap::new();
        config.insert("new_ui".to_string(), ConfigValue::Bool(true));
        config.insert("beta_feature".to_string(), ConfigValue::Bool(false));
        let valid_config = ConfigValue::Object(config);

        assert!(validator
            .validate_path("feature_flags", &valid_config)
            .is_ok());

        // Invalid feature flags (non-boolean value)
        let mut invalid_config = HashMap::new();
        invalid_config.insert(
            "new_ui".to_string(),
            ConfigValue::String("true".to_string()),
        );
        let invalid_config = ConfigValue::Object(invalid_config);

        assert!(validator
            .validate_path("feature_flags", &invalid_config)
            .is_err());
    }

    #[test]
    fn test_get_value_at_path() {
        let json = serde_json::json!({
            "app": {
                "database": {
                    "host": "localhost",
                    "port": 5432
                }
            }
        });

        assert_eq!(
            get_value_at_path(&json, "app.database.host"),
            Some(serde_json::json!("localhost"))
        );

        assert_eq!(
            get_value_at_path(&json, "app.database.port"),
            Some(serde_json::json!(5432))
        );

        assert_eq!(get_value_at_path(&json, "app.nonexistent"), None);
    }
}