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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/* -------------------------------------------------------------------------- *\
 *        Apache 2.0 License Copyright © 2022-2023 The Aurae Authors          *
 *                                                                            *
 *                +--------------------------------------------+              *
 *                |   █████╗ ██╗   ██╗██████╗  █████╗ ███████╗ |              *
 *                |  ██╔══██╗██║   ██║██╔══██╗██╔══██╗██╔════╝ |              *
 *                |  ███████║██║   ██║██████╔╝███████║█████╗   |              *
 *                |  ██╔══██║██║   ██║██╔══██╗██╔══██║██╔══╝   |              *
 *                |  ██║  ██║╚██████╔╝██║  ██║██║  ██║███████╗ |              *
 *                |  ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝ |              *
 *                +--------------------------------------------+              *
 *                                                                            *
 *                         Distributed Systems Runtime                        *
 *                                                                            *
 * -------------------------------------------------------------------------- *
 *                                                                            *
 *   Licensed under the Apache License, Version 2.0 (the "License");          *
 *   you may not use this file except in compliance with the License.         *
 *   You may obtain a copy of the License at                                  *
 *                                                                            *
 *       http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                            *
 *   Unless required by applicable law or agreed to in writing, software      *
 *   distributed under the License is distributed on an "AS IS" BASIS,        *
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 *   See the License for the specific language governing permissions and      *
 *   limitations under the License.                                           *
 *                                                                            *
\* -------------------------------------------------------------------------- */

use serde::de::{Error, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt::Formatter;
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
use std::path::PathBuf;

/// The system configuration for AuraeScript.
///
/// Used to define settings for AuraeScript at runtime.
#[derive(Debug, Clone, Deserialize)]
pub struct SystemConfig {
    /// Socket to connect the client to.  Can be a path (unix socket) or a network socket address.
    ///
    /// When deserializing from a string, the deserializer will try to parse a valid value in the following order:
    /// - IpV6 with scope id (e.g., "[fe80::2%4]:8080")
    /// - IpV6 without scope id (e.g., "[fe80::2]:8080")
    /// - IpV4 (e.g., "127.0.0.1:8080")
    /// - Otherwise a path
    ///
    /// scope id must be a valid u32, otherwise it will be assumed a path
    pub socket: AuraeSocket,
}

#[derive(Debug, Clone)]
pub enum AuraeSocket {
    Path(PathBuf),
    Addr(SocketAddr),
}

impl<'de> Deserialize<'de> for AuraeSocket {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_string(AuraeSocketVisitor)
    }
}

struct AuraeSocketVisitor;

impl<'de> Visitor<'de> for AuraeSocketVisitor {
    type Value = AuraeSocket;

    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
        formatter.write_str("a path (unix socket) or a network socket address")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        self.visit_string(v.to_string())
    }

    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        self.visit_string(v.to_string())
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: Error,
    {
        if let Ok(addr) = v.parse::<SocketAddrV6>() {
            Ok(AuraeSocket::Addr(addr.into()))
        } else if let Ok(addr) = v.parse::<SocketAddrV4>() {
            Ok(AuraeSocket::Addr(addr.into()))
        } else {
            Ok(AuraeSocket::Path(v.into()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr};
    use std::str::FromStr;

    #[test]
    fn can_parse_aurae_socket_path() {
        let visitor = AuraeSocketVisitor {};

        let res = visitor
            .visit_str::<toml::de::Error>("/var/run/aurae/aurae.sock")
            .unwrap();

        assert!(
            matches!(res, AuraeSocket::Path(path) if Some("/var/run/aurae/aurae.sock") == path.to_str())
        );
    }

    #[test]
    fn can_parse_aurae_socket_ipv6() {
        let visitor = AuraeSocketVisitor {};

        let res =
            visitor.visit_str::<toml::de::Error>("[fe80::2]:8080").unwrap();

        let AuraeSocket::Addr (addr) = res else {
            panic!("expected AuraeSocket::Addr");
        };

        let SocketAddr::V6(addr) = addr else {
            panic!("expected v6 addr");
        };

        assert_eq!(*addr.ip(), Ipv6Addr::from_str("fe80::2").unwrap());
        assert_eq!(addr.port(), 8080);
        assert_eq!(addr.scope_id(), 0);
    }

    #[test]
    fn can_parse_aurae_socket_ipv6_with_scope_id() {
        let visitor = AuraeSocketVisitor {};

        let res =
            visitor.visit_str::<toml::de::Error>("[fe80::2%4]:8080").unwrap();

        let AuraeSocket::Addr (addr) = res else {
            panic!("expected AuraeSocket::Addr");
        };

        let SocketAddr::V6(addr) = addr else {
            panic!("expected v6 addr");
        };

        assert_eq!(*addr.ip(), Ipv6Addr::from_str("fe80::2").unwrap());
        assert_eq!(addr.port(), 8080);
        assert_eq!(addr.scope_id(), 4);
    }

    #[test]
    fn can_parse_aurae_socket_ipv4() {
        let visitor = AuraeSocketVisitor {};

        let res =
            visitor.visit_str::<toml::de::Error>("127.0.0.1:8081").unwrap();

        let AuraeSocket::Addr (addr) = res else {
            panic!("expected AuraeSocket::Addr");
        };

        let SocketAddr::V4(addr) = addr else {
            panic!("expected v4 addr");
        };

        assert_eq!(*addr.ip(), Ipv4Addr::from_str("127.0.0.1").unwrap());
        assert_eq!(addr.port(), 8081);
    }
}