forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_binding.rs
More file actions
194 lines (164 loc) · 6.59 KB
/
service_binding.rs
File metadata and controls
194 lines (164 loc) · 6.59 KB
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
184
185
186
187
188
189
190
191
192
193
194
use std::fmt;
use std::net::SocketAddr;
use serde::{Deserialize, Serialize};
use url::Url;
/// Represents the supported network protocols.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum Protocol {
UDP,
HTTP,
HTTPS,
}
impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let proto_str = match self {
Protocol::UDP => "udp",
Protocol::HTTP => "http",
Protocol::HTTPS => "https",
};
write!(f, "{proto_str}")
}
}
#[derive(thiserror::Error, Debug, Clone)]
pub enum Error {
#[error("The port number cannot be zero. It must be an assigned valid port.")]
PortZeroNotAllowed,
}
/// Represents a network service binding, encapsulating protocol and socket
/// address.
///
/// This struct is used to define how a service binds to a network interface and
/// port.
///
/// It's an URL without path and some restrictions:
///
/// - Only some schemes are accepted: `udp`, `http`, `https`.
/// - The port number must be greater than zero. The service should be already
/// listening on that port.
/// - The authority part of the URL must be a valid socket address (wildcard is
/// accepted).
///
/// Besides it accepts some non well-formed URLs, like:<http://127.0.0.1:7070>
/// or <https://127.0.0.1:7070>. Those URLs are not valid because they use non
/// standard ports (80 and 443).
///
/// NOTICE: It does not represent a public valid URL clients can connect to. It
/// represents the service's internal URL configuration after assigning a port.
/// If the port in the configuration is not zero, it's basically the same
/// information you get from the configuration (binding address + protocol).
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
/// use torrust_tracker_primitives::service_binding::{ServiceBinding, Protocol};
///
/// let service_binding = ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap();
///
/// assert_eq!(service_binding.url().to_string(), "http://127.0.0.1:7070/".to_string());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct ServiceBinding {
/// The network protocol used by the service (UDP, HTTP, HTTPS).
protocol: Protocol,
/// The socket address (IP and port) to which the service binds.
bind_address: SocketAddr,
}
impl ServiceBinding {
/// # Errors
///
/// This function will return an error if the port number is zero.
pub fn new(protocol: Protocol, bind_address: SocketAddr) -> Result<Self, Error> {
if bind_address.port() == 0 {
return Err(Error::PortZeroNotAllowed);
}
Ok(Self { protocol, bind_address })
}
/// Returns the protocol used by the service.
#[must_use]
pub fn protocol(&self) -> Protocol {
self.protocol.clone()
}
#[must_use]
pub fn bind_address(&self) -> SocketAddr {
self.bind_address
}
/// # Panics
///
/// It never panics because the URL is always valid.
#[must_use]
pub fn url(&self) -> Url {
Url::parse(&format!("{}://{}", self.protocol, self.bind_address))
.expect("Service binding can always be parsed into a URL")
}
}
impl From<ServiceBinding> for Url {
fn from(service_binding: ServiceBinding) -> Self {
service_binding.url()
}
}
impl fmt::Display for ServiceBinding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.url())
}
}
#[cfg(test)]
mod tests {
mod the_service_binding {
use std::net::SocketAddr;
use std::str::FromStr;
use rstest::rstest;
use url::Url;
use crate::service_binding::{Error, Protocol, ServiceBinding};
#[rstest]
#[case("wildcard_ip", Protocol::UDP, SocketAddr::from_str("0.0.0.0:6969").unwrap())]
#[case("udp_service", Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap())]
#[case("http_service", Protocol::HTTP, SocketAddr::from_str("127.0.0.1:7070").unwrap())]
#[case("https_service", Protocol::HTTPS, SocketAddr::from_str("127.0.0.1:7070").unwrap())]
fn should_allow_a_subset_of_urls(#[case] case: &str, #[case] protocol: Protocol, #[case] bind_address: SocketAddr) {
let service_binding = ServiceBinding::new(protocol.clone(), bind_address);
assert!(service_binding.is_ok(), "{}", format!("{case} failed: {service_binding:?}"));
}
#[test]
fn should_not_allow_undefined_port_zero() {
let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:0").unwrap());
assert!(matches!(service_binding, Err(Error::PortZeroNotAllowed)));
}
#[test]
fn should_return_the_bind_address() {
let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap();
assert_eq!(
service_binding.bind_address(),
SocketAddr::from_str("127.0.0.1:6969").unwrap()
);
}
#[test]
fn should_return_the_corresponding_url() {
let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap();
assert_eq!(service_binding.url(), Url::parse("udp://127.0.0.1:6969").unwrap());
}
#[test]
fn should_be_converted_into_an_url() {
let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap();
let url: Url = service_binding.clone().into();
assert_eq!(url, Url::parse("udp://127.0.0.1:6969").unwrap());
}
#[rstest]
#[case("udp_service", Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap(), "udp://127.0.0.1:6969")]
#[case("http_service", Protocol::HTTP, SocketAddr::from_str("127.0.0.1:7070").unwrap(), "http://127.0.0.1:7070/")]
#[case("https_service", Protocol::HTTPS, SocketAddr::from_str("127.0.0.1:7070").unwrap(), "https://127.0.0.1:7070/")]
fn should_always_have_a_corresponding_unique_url(
#[case] case: &str,
#[case] protocol: Protocol,
#[case] bind_address: SocketAddr,
#[case] expected_url: String,
) {
let service_binding = ServiceBinding::new(protocol.clone(), bind_address).unwrap();
assert_eq!(
service_binding.url().to_string(),
expected_url,
"{case} failed: {service_binding:?}",
);
}
}
}