1use 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#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct RelayMap {
13 nodes: Arc<BTreeMap<RelayUrl, Arc<RelayNode>>>,
15}
16
17impl RelayMap {
18 pub fn urls(&self) -> impl Iterator<Item = &RelayUrl> {
20 self.nodes.keys()
21 }
22
23 pub fn empty() -> Self {
25 Self {
26 nodes: Default::default(),
27 }
28 }
29
30 pub fn nodes(&self) -> impl Iterator<Item = &Arc<RelayNode>> {
32 self.nodes.values()
33 }
34
35 pub fn contains_node(&self, url: &RelayUrl) -> bool {
37 self.nodes.contains_key(url)
38 }
39
40 pub fn get_node(&self, url: &RelayUrl) -> Option<&Arc<RelayNode>> {
42 self.nodes.get(url)
43 }
44
45 pub fn len(&self) -> usize {
47 self.nodes.len()
48 }
49
50 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
116pub struct RelayNode {
117 pub url: RelayUrl,
119 #[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#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq, PartialOrd, Ord)]
143pub struct RelayQuicConfig {
144 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}