DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: 45439cc45439d0050fb8dd130f48993bba82574f canwa/src/config.rs -rw-r--r-- 2.5 KiB
45439cc4Jonni Liljamo feat: initial version 27 days ago
                                                                                
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
/*
 * Copyright (C) 2025 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

use std::{collections::HashMap, net::IpAddr, str::FromStr};

use serde::Deserialize;
use tokio::{fs::File, io::AsyncReadExt};

#[derive(Debug)]
pub enum ConfigError {
    InvalidInterface,
    NonExistentService(String),
}

impl std::error::Error for ConfigError {}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidInterface => write!(f, "invalid interface"),
            Self::NonExistentService(s) => write!(f, "service '{}' does not exist", s),
        }
    }
}

#[typetag::serde(tag = "type")]
pub trait ServiceConfig {
    fn as_any(&self) -> &dyn std::any::Any;
}

#[derive(Clone, Deserialize)]
pub struct NotifierConfig {
    pub token: String,
    pub services: Vec<String>,
}

#[derive(Deserialize)]
pub struct Config {
    pub interface: String,
    pub port: u16,
    pub services: HashMap<String, Box<dyn ServiceConfig>>,
    pub notifiers: HashMap<String, NotifierConfig>,
}

impl Config {
    pub async fn from_str(s: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let config: Config = toml::from_str(s)?;

        // Verify interface
        if IpAddr::from_str(&config.interface).is_err() {
            return Err(Box::new(ConfigError::InvalidInterface));
        }

        // Verify notifiers target services that exist
        for notifier in config.notifiers.values() {
            for service in &notifier.services {
                if !config.services.contains_key(service) {
                    return Err(Box::new(ConfigError::NonExistentService(service.into())));
                }
            }
        }

        Ok(config)
    }

    pub async fn from_path(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let mut content: String = String::new();
        File::open(path).await?.read_to_string(&mut content).await?;
        Self::from_str(&content).await
    }
}

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

    #[tokio::test]
    async fn basic_ok() {
        assert!(Config::from_str(
            r#"
            interface = "0.0.0.0"
            port = 8080
        "#
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn invalid_interface() {
        assert!(Config::from_str(
            r#"
            interface = "0.0.0.a"
            port = 8080
        "#
        )
        .await
        .is_err());
    }
}