panoramic_courier/
address.rs1use std::{fmt, path::PathBuf, str::FromStr};
2
3use crate::{Error, InvalidAddressSnafu};
4
5#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct HostPort {
8 pub host: String,
10
11 pub port: u16,
13}
14
15impl fmt::Display for HostPort {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 if self.host.contains(':') {
18 write!(f, "[{}]:{}", self.host, self.port)
19 } else {
20 write!(f, "{}:{}", self.host, self.port)
21 }
22 }
23}
24
25impl FromStr for HostPort {
26 type Err = &'static str;
27
28 fn from_str(s: &str) -> Result<Self, Self::Err> {
29 let (host, port) = s.rsplit_once(':').ok_or("expected <host>:<port>")?;
30 let host = match host.strip_prefix('[') {
31 Some(rest) => rest.strip_suffix(']').ok_or("an IPv6 host must be in brackets")?,
32 None if host.contains(':') => return Err("an IPv6 host must be in brackets"),
33 None => host,
34 };
35 if host.is_empty() {
36 return Err("the host is empty");
37 }
38 if host.contains(['/', '?', '#']) {
39 return Err("only <host>:<port> may follow the scheme");
40 }
41 let port = port.parse().map_err(|_| "the port is not a number from 0 to 65535")?;
42 Ok(Self {
43 host: host.to_string(),
44 port,
45 })
46 }
47}
48
49#[derive(Clone, Debug, Eq, PartialEq)]
53pub enum Address {
54 Tcp(HostPort),
56
57 Udp(HostPort),
59
60 Http(HostPort),
62
63 Grpc(HostPort),
65
66 UnixStream(PathBuf),
68
69 UnixDatagram(PathBuf),
71
72 NamedPipe(String),
74}
75
76impl fmt::Display for Address {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 match self {
79 Self::Tcp(host_port) => write!(f, "tcp://{host_port}"),
80 Self::Udp(host_port) => write!(f, "udp://{host_port}"),
81 Self::Http(host_port) => write!(f, "http://{host_port}"),
82 Self::Grpc(host_port) => write!(f, "grpc://{host_port}"),
83 Self::UnixStream(path) => write!(f, "unix://{}", path.display()),
84 Self::UnixDatagram(path) => write!(f, "unixgram://{}", path.display()),
85 Self::NamedPipe(name) => write!(f, "pipe://{name}"),
86 }
87 }
88}
89
90impl FromStr for Address {
91 type Err = Error;
92
93 fn from_str(s: &str) -> Result<Self, Self::Err> {
94 let invalid = |reason| InvalidAddressSnafu { address: s, reason }.build();
95 let (scheme, rest) = s.split_once("://").ok_or_else(|| invalid("expected <scheme>://"))?;
96 let host_port = || rest.parse::<HostPort>().map_err(invalid);
97 let path = || {
98 if rest.is_empty() {
99 Err(invalid("the socket path is empty"))
100 } else {
101 Ok(PathBuf::from(rest))
102 }
103 };
104 match scheme {
105 "tcp" => Ok(Self::Tcp(host_port()?)),
106 "udp" => Ok(Self::Udp(host_port()?)),
107 "http" => Ok(Self::Http(host_port()?)),
108 "grpc" => Ok(Self::Grpc(host_port()?)),
109 "https" => Err(invalid("the courier does not speak TLS")),
110 "unix" => Ok(Self::UnixStream(path()?)),
111 "unixgram" => Ok(Self::UnixDatagram(path()?)),
112 "pipe" if rest.is_empty() || rest.contains(['/', '\\']) => {
113 Err(invalid("a pipe name is not empty and holds no '/' or '\\'"))
114 }
115 "pipe" => Ok(Self::NamedPipe(rest.to_string())),
116 _ => Err(invalid(
117 "the scheme is not one of tcp, udp, http, grpc, unix, unixgram or pipe",
118 )),
119 }
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::Fault;
127
128 #[test]
129 fn rejects_bad_addresses_as_a_harness_fault() {
130 for text in [
131 "adp:9126",
132 "https://adp:443",
133 "ftp://adp:21",
134 "tcp://adp",
135 "tcp://adp:65536",
136 "tcp://:80",
137 "tcp://::1:80",
138 "http://adp:80/ready",
139 "unix://",
140 "pipe://a\\b",
141 ] {
142 let error = text.parse::<Address>().unwrap_err();
143 assert!(matches!(error, Error::InvalidAddress { .. }), "{text}: {error}");
144 assert_eq!(error.fault(), Fault::Harness, "{text}");
145 }
146 }
147}