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
use std::{
    collections::BTreeMap,
    convert::TryFrom,
    path::{Path, PathBuf},
};

use async_trait::async_trait;

use super::ConfigBackend;
use crate::models::*;

pub trait ConfigExt {
    fn to_string(&self) -> Result<String, toml::ser::Error>;
}

impl ConfigExt for Config {
    fn to_string(&self) -> Result<String, toml::ser::Error> {
        toml::to_string_pretty(&SerializableConfig::from(self))
    }
}

pub struct FileBackend {
    path: PathBuf,
}

impl FileBackend {
    pub fn new(path: &Path) -> Self {
        Self {
            path: path.to_owned(),
        }
    }
}

#[async_trait]
impl ConfigBackend for FileBackend {
    async fn load(&mut self) -> Result<Config, ConfigError> {
        use tokio::io::AsyncReadExt;

        let mut file = tokio::fs::File::open(&self.path).await?;
        let mut full = String::new();
        file.read_to_string(&mut full).await?;

        let config: DeserializableConfig = toml::from_str(&full)?;
        Ok(config.try_into()?)
    }
}

#[derive(Serialize)]
struct SerializableConfig<'c> {
    instances: BTreeMap<String, &'c InstanceConfig>,
    #[serde(flatten)]
    global: &'c GlobalConfig,
    meta: &'c Vec<Meta>,
    users: &'c Vec<User>,
}

impl<'c> From<&'c Config> for SerializableConfig<'c> {
    fn from(config: &'c Config) -> Self {
        Self {
            instances: config
                .instances
                .iter()
                .map(|(k, v)| (k.to_string(), v))
                .collect(),
            global: &config.global,
            meta: &config.meta,
            users: &config.users,
        }
    }
}

fn default_meta() -> Vec<Meta> {
    vec![Meta::new()]
}

fn default_users() -> Vec<User> {
    vec![User::hyperion()]
}

#[derive(Deserialize)]
struct DeserializableConfig {
    instances: BTreeMap<String, InstanceConfig>,
    #[serde(default, flatten)]
    global: GlobalConfig,
    #[serde(default = "default_meta")]
    meta: Vec<Meta>,
    #[serde(default = "default_users")]
    users: Vec<User>,
}

impl TryFrom<DeserializableConfig> for Config {
    type Error = ConfigError;

    fn try_from(value: DeserializableConfig) -> Result<Self, Self::Error> {
        Ok(Self {
            instances: value
                .instances
                .into_iter()
                .map(|(k, v)| {
                    k.parse()
                        .map_err(|_| ConfigError::InvalidId(k.clone()))
                        .map(|k| (k, v))
                })
                .collect::<Result<_, _>>()?,
            global: value.global,
            meta: value.meta,
            users: value.users,
        })
    }
}