iroh_relay/
relay_map.rs

1//! based on tailscale/tailcfg/derpmap.go
2
3use std::{collections::BTreeMap, fmt, sync::Arc};
4
5use iroh_base::RelayUrl;
6use serde::{Deserialize, Serialize};
7
8use crate::defaults::DEFAULT_RELAY_QUIC_PORT;
9
10/// Configuration of all the relay servers that can be used.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct RelayMap {
13    /// A map of the different relay IDs to the [`RelayNode`] information
14    nodes: Arc<BTreeMap<RelayUrl, Arc<RelayNode>>>,
15}
16
17impl RelayMap {
18    /// Returns the sorted relay URLs.
19    pub fn urls(&self) -> impl Iterator<Item = &RelayUrl> {
20        self.nodes.keys()
21    }
22
23    /// Create an empty relay map.
24    pub fn empty() -> Self {
25        Self {
26            nodes: Default::default(),
27        }
28    }
29
30    /// Returns an `Iterator` over all known nodes.
31    pub fn nodes(&self) -> impl Iterator<Item = &Arc<RelayNode>> {
32        self.nodes.values()
33    }
34
35    /// Is this a known node?
36    pub fn contains_node(&self, url: &RelayUrl) -> bool {
37        self.nodes.contains_key(url)
38    }
39
40    /// Get the given node.
41    pub fn get_node(&self, url: &RelayUrl) -> Option<&Arc<RelayNode>> {
42        self.nodes.get(url)
43    }
44
45    /// How many nodes are known?
46    pub fn len(&self) -> usize {
47        self.nodes.len()
48    }
49
50    /// Are there any nodes in this map?
51    pub fn is_empty(&self) -> bool {
52        self.nodes.is_empty()
53    }
54}
55
56impl FromIterator<RelayNode> for RelayMap {
57    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self {
58        Self {
59            nodes: Arc::new(
60                iter.into_iter()
61                    .map(|node| (node.url.clone(), Arc::new(node)))
62                    .collect(),
63            ),
64        }
65    }
66}
67
68impl From<RelayUrl> for RelayMap {
69    /// Creates a [`RelayMap`] from a [`RelayUrl`].
70    ///
71    /// The [`RelayNode`]s in the [`RelayMap`] will have the default QUIC address
72    /// discovery ports.
73    fn from(value: RelayUrl) -> Self {
74        Self {
75            nodes: Arc::new([(value.clone(), Arc::new(value.into()))].into()),
76        }
77    }
78}
79
80impl From<RelayNode> for RelayMap {
81    fn from(value: RelayNode) -> Self {
82        Self {
83            nodes: Arc::new([(value.url.clone(), Arc::new(value))].into()),
84        }
85    }
86}
87
88impl FromIterator<RelayUrl> for RelayMap {
89    /// Creates a [`RelayMap`] from an iterator of [`RelayUrl`].
90    ///
91    /// The [`RelayNode`]s in the [`RelayMap`] will have the default QUIC address
92    /// discovery ports.
93    fn from_iter<T: IntoIterator<Item = RelayUrl>>(iter: T) -> Self {
94        Self {
95            nodes: Arc::new(
96                iter.into_iter()
97                    .map(|url| (url.clone(), Arc::new(url.into())))
98                    .collect(),
99            ),
100        }
101    }
102}
103
104impl fmt::Display for RelayMap {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        fmt::Debug::fmt(&self, f)
107    }
108}
109
110/// Information on a specific relay server.
111///
112/// Includes the Url where it can be dialed.
113// Please note that this is documented in the `iroh.computer` repository under
114// `src/app/docs/reference/config/page.mdx`.  Any changes to this need to be updated there.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
116pub struct RelayNode {
117    /// The [`RelayUrl`] where this relay server can be dialed.
118    pub url: RelayUrl,
119    /// Configuration to speak to the QUIC endpoint on the relay server.
120    ///
121    /// When `None`, we will not attempt to do QUIC address discovery
122    /// with this relay server.
123    #[serde(default = "quic_config")]
124    pub quic: Option<RelayQuicConfig>,
125}
126
127impl From<RelayUrl> for RelayNode {
128    fn from(value: RelayUrl) -> Self {
129        Self {
130            url: value,
131            quic: quic_config(),
132        }
133    }
134}
135
136fn quic_config() -> Option<RelayQuicConfig> {
137    Some(RelayQuicConfig::default())
138}
139
140/// Configuration for speaking to the QUIC endpoint on the relay
141/// server to do QUIC address discovery.
142#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq, PartialOrd, Ord)]
143pub struct RelayQuicConfig {
144    /// The port on which the connection should be bound to.
145    pub port: u16,
146}
147
148impl Default for RelayQuicConfig {
149    fn default() -> Self {
150        Self {
151            port: DEFAULT_RELAY_QUIC_PORT,
152        }
153    }
154}
155
156impl fmt::Display for RelayNode {
157    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158        write!(f, "{}", self.url)
159    }
160}