1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::sync::Arc;
4use parking_lot::RwLock;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct ConfigValue {
8 pub key: String,
9 pub value: serde_json::Value,
10 pub version: u64,
11 pub metadata: ConfigMetadata,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct ConfigMetadata {
16 pub created_at: chrono::DateTime<chrono::Utc>,
17 pub updated_at: chrono::DateTime<chrono::Utc>,
18 pub created_by: Option<String>,
19 pub description: Option<String>,
20 pub tags: Vec<String>,
21}
22
23impl ConfigMetadata {
24 pub fn new() -> Self {
25 let now = chrono::Utc::now();
26 Self {
27 created_at: now,
28 updated_at: now,
29 created_by: None,
30 description: None,
31 tags: Vec::new(),
32 }
33 }
34}
35
36#[derive(Debug, Clone)]
37pub struct ConfigChange {
38 pub key: String,
39 pub old_value: Option<serde_json::Value>,
40 pub new_value: Option<serde_json::Value>,
41 pub change_type: ChangeType,
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub enum ChangeType {
46 Created,
47 Updated,
48 Deleted,
49}
50
51pub type ConfigChangeCallback = Arc<dyn Fn(ConfigChange) + Send + Sync>;
52
53#[derive(Clone)]
54pub struct ConfigOptions {
55 pub namespace: Option<String>,
56 pub environment: Option<String>,
57 pub cache_ttl: Option<std::time::Duration>,
58 pub watch_interval: std::time::Duration,
59}
60
61impl Default for ConfigOptions {
62 fn default() -> Self {
63 Self {
64 namespace: None,
65 environment: None,
66 cache_ttl: Some(std::time::Duration::from_secs(60)),
67 watch_interval: std::time::Duration::from_secs(5),
68 }
69 }
70}
71
72#[derive(Debug, Clone)]
73pub struct ConfigCache {
74 data: Arc<RwLock<HashMap<String, ConfigValue>>>,
75}
76
77impl ConfigCache {
78 pub fn new() -> Self {
79 Self {
80 data: Arc::new(RwLock::new(HashMap::new())),
81 }
82 }
83
84 pub fn get(&self, key: &str) -> Option<ConfigValue> {
85 self.data.read().get(key).cloned()
86 }
87
88 pub fn set(&self, key: String, value: ConfigValue) {
89 self.data.write().insert(key, value);
90 }
91
92 pub fn remove(&self, key: &str) -> Option<ConfigValue> {
93 self.data.write().remove(key)
94 }
95
96 pub fn clear(&self) {
97 self.data.write().clear();
98 }
99
100 pub fn keys(&self) -> Vec<String> {
101 self.data.read().keys().cloned().collect()
102 }
103}