zng_ext_config/
json.rs

1use zng_ext_fs_watcher::{WatchFile, WriteFile};
2
3use super::*;
4
5impl ConfigMap for indexmap::IndexMap<ConfigKey, serde_json::Value> {
6    fn empty() -> Self {
7        Self::new()
8    }
9
10    fn read(mut file: WatchFile) -> io::Result<Self> {
11        file.json().map_err(Into::into)
12    }
13
14    fn write(self, file: &mut WriteFile) -> io::Result<()> {
15        file.write_json(&self, true)
16    }
17
18    fn get_raw(&self, key: &ConfigKey) -> Result<Option<RawConfigValue>, Arc<dyn std::error::Error + Send + Sync>> {
19        Ok(self.get(key).map(|v| RawConfigValue(v.clone())))
20    }
21
22    fn set_raw(map: &mut VarModify<Self>, key: ConfigKey, value: RawConfigValue) -> Result<(), Arc<dyn std::error::Error + Send + Sync>> {
23        let value = value.0;
24        if map.get(&key) != Some(&value) {
25            map.to_mut().insert(key, value);
26        }
27        Ok(())
28    }
29
30    fn contains_key(&self, key: &ConfigKey) -> bool {
31        self.contains_key(key)
32    }
33
34    fn get<O: ConfigValue>(&self, key: &ConfigKey) -> Result<Option<O>, Arc<dyn std::error::Error + Send + Sync>> {
35        if let Some(value) = self.get(key) {
36            match serde_json::from_value(value.clone()) {
37                Ok(s) => Ok(Some(s)),
38                Err(e) => Err(Arc::new(e)),
39            }
40        } else {
41            Ok(None)
42        }
43    }
44
45    fn set<O: ConfigValue>(map: &mut VarModify<Self>, key: ConfigKey, value: O) -> Result<(), Arc<dyn std::error::Error + Send + Sync>> {
46        match serde_json::to_value(value) {
47            Ok(value) => {
48                if map.get(&key) != Some(&value) {
49                    map.to_mut().insert(key, value);
50                }
51                Ok(())
52            }
53            Err(e) => Err(Arc::new(e)),
54        }
55    }
56
57    fn remove(map: &mut VarModify<Self>, key: &ConfigKey) {
58        if map.contains_key(key) {
59            map.to_mut().shift_remove(key);
60        }
61    }
62}
63
64/// Represents a config source that synchronizes with a JSON file.
65pub type JsonConfig = SyncConfig<indexmap::IndexMap<ConfigKey, serde_json::Value>>;