iroh_base/
relay_url.rs

1use std::{fmt, ops::Deref, str::FromStr, sync::Arc};
2
3use n0_error::stack_error;
4use serde::{Deserialize, Serialize};
5use url::Url;
6
7/// A URL identifying a relay server.
8///
9/// It is cheaply clonable, as the underlying type is wrapped into an `Arc`.  The main type
10/// under the hood though is [`Url`].
11///
12/// To create a [`RelayUrl`] use the `From<Url>` implementation.  It adds a trailing `/` to
13/// a path that lacks one, so the relay's own paths are joined under it: `https://example.com/prefix`
14/// becomes `https://example.com/prefix/`.  Deserialising goes through it too.
15///
16/// It is encouraged to use a fully-qualified DNS domain name in the URL.  Meaning a DNS
17/// name which ends in a `.`, e.g, in `relay.example.com.`.  Otherwise the DNS resolution of
18/// your local host or network could interpret the DNS name as relative and in some
19/// configurations might cause additional delays or even connection problems.
20#[derive(
21    Clone, derive_more::Display, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
22)]
23#[serde(from = "Url")]
24pub struct RelayUrl(Arc<Url>);
25
26impl From<Url> for RelayUrl {
27    fn from(mut url: Url) -> Self {
28        if !url.cannot_be_a_base() && !url.path().ends_with('/') {
29            let path = format!("{}/", url.path());
30            url.set_path(&path);
31            tracing::info!(%url, "Added a trailing slash to the relay URL's path");
32        }
33        Self(Arc::new(url))
34    }
35}
36
37/// Can occur when parsing a string into a [`RelayUrl`].
38#[stack_error(derive, add_meta)]
39#[error("Failed to parse relay URL")]
40pub struct RelayUrlParseError(#[error(std_err)] url::ParseError);
41
42/// Support for parsing strings directly.
43///
44/// If you need more control over the error first create a [`Url`] and use [`RelayUrl::from`]
45/// instead.
46impl FromStr for RelayUrl {
47    type Err = RelayUrlParseError;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        let inner = Url::from_str(s).map_err(RelayUrlParseError::new)?;
51        Ok(RelayUrl::from(inner))
52    }
53}
54
55impl From<RelayUrl> for Url {
56    fn from(value: RelayUrl) -> Self {
57        Arc::unwrap_or_clone(value.0)
58    }
59}
60
61/// Dereferences to the wrapped [`Url`].
62///
63/// Note that [`DerefMut`] is not implemented on purpose, so this type has more flexibility
64/// to change the inner later.
65///
66/// [`DerefMut`]: std::ops::DerefMut
67impl Deref for RelayUrl {
68    type Target = Url;
69
70    fn deref(&self) -> &Self::Target {
71        &self.0
72    }
73}
74
75impl fmt::Debug for RelayUrl {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.debug_tuple("RelayUrl")
78            .field(&DbgStr(self.0.as_str()))
79            .finish()
80    }
81}
82
83/// Helper struct to format a &str without allocating a String.
84///
85/// Maybe this is entirely unneeded and the compiler would be smart enough to never allocate
86/// the String anyway.  Who knows.  Writing this was faster than checking the assembler
87/// output.
88struct DbgStr<'a>(&'a str);
89
90impl fmt::Debug for DbgStr<'_> {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, r#""{}""#, self.0)
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn test_relay_url_debug_display() {
102        let url = RelayUrl::from(Url::parse("https://example.com").unwrap());
103
104        assert_eq!(format!("{url:?}"), r#"RelayUrl("https://example.com/")"#);
105
106        assert_eq!(format!("{url}"), "https://example.com/");
107    }
108
109    #[test]
110    fn test_relay_url_absolute() {
111        let url = RelayUrl::from(Url::parse("https://example.com").unwrap());
112
113        assert_eq!(url.domain(), Some("example.com"));
114
115        let url1 = RelayUrl::from(Url::parse("https://example.com.").unwrap());
116        assert_eq!(url1.domain(), Some("example.com."));
117
118        let url2 = RelayUrl::from(Url::parse("https://example.com./").unwrap());
119        assert_eq!(url2.domain(), Some("example.com."));
120
121        let url3 = RelayUrl::from(Url::parse("https://example.com/").unwrap());
122        assert_eq!(url3.domain(), Some("example.com"));
123    }
124
125    #[test]
126    fn test_relay_url_path_trailing_slash() {
127        let url = RelayUrl::from(Url::parse("https://example.com/prefix").unwrap());
128        assert_eq!(url.as_str(), "https://example.com/prefix/");
129
130        let url: RelayUrl = "https://example.com/a/b?x=1".parse().unwrap();
131        assert_eq!(url.as_str(), "https://example.com/a/b/?x=1");
132
133        let url = RelayUrl::from(Url::parse("https://example.com/prefix/").unwrap());
134        assert_eq!(url.as_str(), "https://example.com/prefix/");
135
136        let url = RelayUrl::from(Url::parse("https://example.com").unwrap());
137        assert_eq!(url.as_str(), "https://example.com/");
138    }
139
140    #[test]
141    fn test_relay_url_deserialize_trailing_slash() {
142        let url: RelayUrl = serde_json::from_str(r#""https://example.com/prefix""#).unwrap();
143        assert_eq!(url.as_str(), "https://example.com/prefix/");
144
145        let url = RelayUrl::from(Url::parse("https://example.com/prefix/").unwrap());
146        let bytes = postcard::to_stdvec(&url).unwrap();
147        let back: RelayUrl = postcard::from_bytes(&bytes).unwrap();
148        assert_eq!(back, url);
149    }
150}