DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: 59fec95b232dd0b1b8348e52c2f31062459a2cba canwa/src/config.rs -rw-r--r-- 3.5 KiB
59fec95bJonni Liljamo feat: optionally render commonmark to html for matrix a month 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
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
/*
 * Copyright (C) 2025 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-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;
}

pub fn deserialize_token<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let token_or_path: String = serde::de::Deserialize::deserialize(deserializer)?;
    // If the value exists as a path and we can read it, read the file.
    let path = std::path::Path::new(&token_or_path);
    if path.exists() {
        match std::fs::read_to_string(path) {
            Ok(token) => return Ok(token.trim().into()),
            Err(err) => {
                tracing::warn!(msg="token exists as a filesystem path, but could not be read, assuming raw token", %err)
            }
        }
    }
    // Assume raw token.
    Ok(token_or_path)
}

#[derive(Clone, Deserialize)]
pub struct NotifierConfig {
    #[serde(deserialize_with = "deserialize_token")]
    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

            [services.m]
            type = "matrix"
            instance = ""
            token = ""
            room = ""

            [notifiers.a]
            token = "42"
            services = ["m"]
        "#
            )
            .await
            .is_ok()
        );
    }

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