tc_telemetry/
endpoints.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2021 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use tetsy_libp2p::Multiaddr;
20use serde::{Deserialize, Deserializer, Serialize};
21
22/// List of telemetry servers we want to talk to. Contains the URL of the server, and the
23/// maximum verbosity level.
24///
25/// The URL string can be either a URL or a multiaddress.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
27pub struct TelemetryEndpoints(
28	#[serde(deserialize_with = "url_or_multiaddr_deser")]
29	pub(crate) Vec<(Multiaddr, u8)>,
30);
31
32/// Custom deserializer for TelemetryEndpoints, used to convert urls or multiaddr to multiaddr.
33fn url_or_multiaddr_deser<'de, D>(deserializer: D) -> Result<Vec<(Multiaddr, u8)>, D::Error>
34where
35	D: Deserializer<'de>,
36{
37	Vec::<(String, u8)>::deserialize(deserializer)?
38		.iter()
39		.map(|e| {
40			url_to_multiaddr(&e.0)
41				.map_err(serde::de::Error::custom)
42				.map(|m| (m, e.1))
43		})
44		.collect()
45}
46
47impl TelemetryEndpoints {
48	/// Create a `TelemetryEndpoints` based on a list of `(String, u8)`.
49	pub fn new(endpoints: Vec<(String, u8)>) -> Result<Self, tetsy_libp2p::multiaddr::Error> {
50		let endpoints: Result<Vec<(Multiaddr, u8)>, tetsy_libp2p::multiaddr::Error> = endpoints
51			.iter()
52			.map(|e| Ok((url_to_multiaddr(&e.0)?, e.1)))
53			.collect();
54		endpoints.map(Self)
55	}
56}
57
58impl TelemetryEndpoints {
59	/// Return `true` if there are no telemetry endpoints, `false` otherwise.
60	pub fn is_empty(&self) -> bool {
61		self.0.is_empty()
62	}
63}
64
65/// Parses a WebSocket URL into a libp2p `Multiaddr`.
66fn url_to_multiaddr(url: &str) -> Result<Multiaddr, tetsy_libp2p::multiaddr::Error> {
67	// First, assume that we have a `Multiaddr`.
68	let parse_error = match url.parse() {
69		Ok(ma) => return Ok(ma),
70		Err(err) => err,
71	};
72
73	// If not, try the `ws://path/url` format.
74	if let Ok(ma) = tetsy_libp2p::multiaddr::from_url(url) {
75		return Ok(ma);
76	}
77
78	// If we have no clue about the format of that string, assume that we were expecting a
79	// `Multiaddr`.
80	Err(parse_error)
81}
82
83#[cfg(test)]
84mod tests {
85	use super::url_to_multiaddr;
86	use super::TelemetryEndpoints;
87	use tetsy_libp2p::Multiaddr;
88
89	#[test]
90	fn valid_endpoints() {
91		let endp = vec![
92			("wss://telemetry.polkadot.io/submit/".into(), 3),
93			("/ip4/80.123.90.4/tcp/5432".into(), 4),
94		];
95		let telem =
96			TelemetryEndpoints::new(endp.clone()).expect("Telemetry endpoint should be valid");
97		let mut res: Vec<(Multiaddr, u8)> = vec![];
98		for (a, b) in endp.iter() {
99			res.push((
100				url_to_multiaddr(a).expect("provided url should be valid"),
101				*b,
102			))
103		}
104		assert_eq!(telem.0, res);
105	}
106
107	#[test]
108	fn invalid_endpoints() {
109		let endp = vec![
110			("/ip4/...80.123.90.4/tcp/5432".into(), 3),
111			("/ip4/no:!?;rlkqre;;::::///tcp/5432".into(), 4),
112		];
113		let telem = TelemetryEndpoints::new(endp);
114		assert!(telem.is_err());
115	}
116
117	#[test]
118	fn valid_and_invalid_endpoints() {
119		let endp = vec![
120			("/ip4/80.123.90.4/tcp/5432".into(), 3),
121			("/ip4/no:!?;rlkqre;;::::///tcp/5432".into(), 4),
122		];
123		let telem = TelemetryEndpoints::new(endp);
124		assert!(telem.is_err());
125	}
126}