iroh/address_lookup/
memory.rs

1//! An in-memory address lookup system to manually add endpoint addressing information.
2//!
3//! Often an application might get endpoint addressing information out-of-band in an
4//! application-specific way.  [`EndpointTicket`]'s are one common way used to achieve this.
5//! This addressing information is often only usable for a limited time so needs to
6//! be able to be removed again once you know it is no longer useful.
7//!
8//! This is where the [`MemoryLookup`] is useful: it allows applications to add and
9//! retract endpoint addressing information that is otherwise out-of-band to iroh.
10//!
11//! [`EndpointTicket`]: https://docs.rs/iroh-tickets/latest/iroh_tickets/endpoint/struct.EndpointTicket.html
12
13use std::{
14    collections::{BTreeMap, btree_map::Entry},
15    sync::{Arc, RwLock},
16};
17
18use iroh_base::EndpointId;
19use n0_future::{
20    boxed::BoxStream,
21    stream::{self, StreamExt},
22    time::SystemTime,
23};
24
25use super::{AddressLookup, EndpointData, EndpointInfo, Error, Item};
26
27/// An in-memory address lookup system to manually add endpoint addressing information.
28///
29/// Often an application might get endpoint addressing information out-of-band in an
30/// application-specific way.  [`EndpointTicket`]'s are one common way used to achieve this.
31/// This addressing information is often only usable for a limited time so needs to
32/// be able to be removed again once you know it is no longer useful.
33///
34/// This is where the [`MemoryLookup`] is useful: it allows applications to add and
35/// retract endpoint addressing information that is otherwise out-of-band to iroh.
36///
37/// # Examples
38///
39/// ```no_run
40/// # #[cfg(with_crypto_provider)] // Endpoint::bind needs a crypto provider
41/// # {
42/// use iroh::{
43///     Endpoint, EndpointAddr, TransportAddr, address_lookup::memory::MemoryLookup,
44///     endpoint::presets,
45/// };
46/// use iroh_base::SecretKey;
47///
48/// # #[tokio::main]
49/// # async fn wrapper() -> n0_error::Result<()> {
50/// // Create the Address Lookup and endpoint.
51/// let address_lookup = MemoryLookup::new();
52///
53/// let _ep = Endpoint::builder(presets::N0)
54///     .address_lookup(address_lookup.clone())
55///     .bind()
56///     .await?;
57///
58/// // Sometime later add a RelayUrl for our endpoint.
59/// let id = SecretKey::generate().public();
60/// // You can pass either `EndpointInfo` or `EndpointAddr` to `add_endpoint_info`.
61/// address_lookup.add_endpoint_info(EndpointAddr {
62///     id,
63///     addrs: [TransportAddr::Relay("https://example.com".parse()?)]
64///         .into_iter()
65///         .collect(),
66/// });
67///
68/// # Ok(())
69/// # }
70/// # }
71/// ```
72///
73/// [`EndpointTicket`]: https://docs.rs/iroh-tickets/latest/iroh_tickets/endpoint/struct.EndpointTicket.html
74#[derive(Debug, Clone)]
75pub struct MemoryLookup {
76    endpoints: Arc<RwLock<BTreeMap<EndpointId, StoredEndpointInfo>>>,
77    provenance: &'static str,
78}
79
80impl Default for MemoryLookup {
81    fn default() -> Self {
82        Self {
83            endpoints: Default::default(),
84            provenance: Self::PROVENANCE,
85        }
86    }
87}
88
89#[derive(Debug)]
90struct StoredEndpointInfo {
91    data: EndpointData,
92    last_updated: SystemTime,
93}
94
95impl MemoryLookup {
96    /// The provenance string for this Address Lookup implementation.
97    ///
98    /// This is mostly used for debugging information and allows understanding the origin of
99    /// addressing information used by an iroh [`Endpoint`].
100    ///
101    /// [`Endpoint`]: crate::Endpoint
102    pub const PROVENANCE: &'static str = "memory_lookup";
103
104    /// Creates a new empty Memory Lookup instance.
105    pub fn new() -> Self {
106        Self::default()
107    }
108
109    /// Creates a new Memory Lookup instance with the provided `provenance`.
110    ///
111    /// The provenance is part of [`address_lookup::Item`]s returned from [`Self::resolve`].
112    /// It is mostly used for debugging information and allows understanding the origin of
113    /// addressing information used by an iroh [`Endpoint`].
114    ///
115    /// [`Endpoint`]: crate::Endpoint
116    /// [`address_lookup::Item`]: crate::address_lookup::Item
117    pub fn with_provenance(provenance: &'static str) -> Self {
118        Self {
119            endpoints: Default::default(),
120            provenance,
121        }
122    }
123
124    /// Creates a Memory Lookup instance from endpoint addresses.
125    ///
126    /// # Examples
127    ///
128    /// ```no_run
129    /// # #[cfg(with_crypto_provider)] // Endpoint::bind needs a crypto provider
130    /// # {
131    /// use std::{net::SocketAddr, str::FromStr};
132    ///
133    /// use iroh::{Endpoint, EndpointAddr, address_lookup::memory::MemoryLookup, endpoint::presets};
134    ///
135    /// # fn get_addrs() -> Vec<EndpointAddr> {
136    /// #     Vec::new()
137    /// # }
138    /// # #[tokio::main]
139    /// # async fn wrapper() -> n0_error::Result<()> {
140    /// // get addrs from somewhere
141    /// let addrs = get_addrs();
142    ///
143    /// // create a MemoryLookup from the list of addrs.
144    /// let address_lookup = MemoryLookup::from_endpoint_info(addrs);
145    /// // create an endpoint with the memory lookup address_lookup
146    /// let endpoint = Endpoint::builder(presets::N0)
147    ///     .address_lookup(address_lookup)
148    ///     .bind()
149    ///     .await?;
150    /// # Ok(())
151    /// # }
152    /// # }
153    /// ```
154    pub fn from_endpoint_info(infos: impl IntoIterator<Item = impl Into<EndpointInfo>>) -> Self {
155        let res = Self::default();
156        for info in infos {
157            res.add_endpoint_info(info);
158        }
159        res
160    }
161
162    /// Sets endpoint addressing information for the given endpoint ID.
163    ///
164    /// This will completely overwrite any existing info for the endpoint.
165    ///
166    /// Returns the [`EndpointData`] of the previous entry, or `None` if there was no previous
167    /// entry for this endpoint ID.
168    pub fn set_endpoint_info(
169        &self,
170        endpoint_info: impl Into<EndpointInfo>,
171    ) -> Option<EndpointData> {
172        let last_updated = SystemTime::now();
173        let EndpointInfo { endpoint_id, data } = endpoint_info.into();
174        let mut guard = self.endpoints.write().expect("poisoned");
175        let previous = guard.insert(endpoint_id, StoredEndpointInfo { data, last_updated });
176        previous.map(|x| x.data)
177    }
178
179    /// Augments endpoint addressing information for the given endpoint ID.
180    ///
181    /// The provided addressing information is combined with the existing info in the memory
182    /// lookup.  Any new direct addresses are added to those already present while the
183    /// relay URL is overwritten.
184    pub fn add_endpoint_info(&self, endpoint_info: impl Into<EndpointInfo>) {
185        let last_updated = SystemTime::now();
186        let EndpointInfo { endpoint_id, data } = endpoint_info.into();
187        let mut guard = self.endpoints.write().expect("poisoned");
188        match guard.entry(endpoint_id) {
189            Entry::Occupied(mut entry) => {
190                let existing = entry.get_mut();
191                existing.data.add_addrs(data.addrs().cloned());
192                existing.data.set_user_data(data.user_data().cloned());
193                existing.last_updated = last_updated;
194            }
195            Entry::Vacant(entry) => {
196                entry.insert(StoredEndpointInfo { data, last_updated });
197            }
198        }
199    }
200
201    /// Returns endpoint addressing information for the given endpoint ID.
202    pub fn get_endpoint_info(&self, endpoint_id: EndpointId) -> Option<EndpointInfo> {
203        let guard = self.endpoints.read().expect("poisoned");
204        let info = guard.get(&endpoint_id)?;
205        Some(EndpointInfo::from_parts(endpoint_id, info.data.clone()))
206    }
207
208    /// Removes all endpoint addressing information for the given endpoint ID.
209    ///
210    /// Any removed information is returned.
211    pub fn remove_endpoint_info(&self, endpoint_id: EndpointId) -> Option<EndpointInfo> {
212        let mut guard = self.endpoints.write().expect("poisoned");
213        let info = guard.remove(&endpoint_id)?;
214        Some(EndpointInfo::from_parts(endpoint_id, info.data))
215    }
216}
217
218impl AddressLookup for MemoryLookup {
219    fn publish(&self, _data: &EndpointData) {}
220
221    fn resolve(&self, endpoint_id: EndpointId) -> Option<BoxStream<Result<super::Item, Error>>> {
222        let guard = self.endpoints.read().expect("poisoned");
223        let info = guard.get(&endpoint_id);
224        match info {
225            Some(endpoint_info) => {
226                let last_updated = endpoint_info
227                    .last_updated
228                    .duration_since(SystemTime::UNIX_EPOCH)
229                    .expect("time drift")
230                    .as_micros() as u64;
231                let item = Item::new(
232                    EndpointInfo::from_parts(endpoint_id, endpoint_info.data.clone()),
233                    self.provenance,
234                    Some(last_updated),
235                );
236                Some(stream::iter(Some(Ok(item))).boxed())
237            }
238            None => None,
239        }
240    }
241}
242
243#[cfg(all(test, with_crypto_provider))]
244mod tests {
245    use iroh_base::{EndpointAddr, SecretKey, TransportAddr};
246    use n0_error::{Result, StackResultExt};
247
248    use super::*;
249    use crate::{Endpoint, endpoint::presets};
250
251    #[tokio::test]
252    async fn test_basic() -> Result {
253        let address_lookup = MemoryLookup::new();
254
255        let _ep = Endpoint::builder(presets::Minimal)
256            .address_lookup(address_lookup.clone())
257            .bind()
258            .await?;
259
260        let key = SecretKey::from_bytes(&[0u8; 32]);
261        let addr = EndpointAddr::from_parts(
262            key.public(),
263            [TransportAddr::Relay("https://example.com".parse()?)],
264        );
265        let user_data = Some("foobar".parse().unwrap());
266        let endpoint_info = EndpointInfo::from(addr.clone()).with_user_data(user_data.clone());
267        address_lookup.add_endpoint_info(endpoint_info.clone());
268
269        let back = address_lookup
270            .get_endpoint_info(key.public())
271            .context("no addr")?;
272
273        assert_eq!(back, endpoint_info);
274        assert_eq!(back.user_data(), user_data.as_ref());
275        assert_eq!(back.into_endpoint_addr(), addr);
276
277        let removed = address_lookup
278            .remove_endpoint_info(key.public())
279            .context("nothing removed")?;
280        assert_eq!(removed, endpoint_info);
281        let res = address_lookup.get_endpoint_info(key.public());
282        assert!(res.is_none());
283
284        Ok(())
285    }
286
287    #[tokio::test]
288    async fn test_provenance() -> Result {
289        let address_lookup = MemoryLookup::with_provenance("foo");
290        let key = SecretKey::from_bytes(&[0u8; 32]);
291        let addr = EndpointAddr::from_parts(
292            key.public(),
293            [TransportAddr::Relay("https://example.com".parse()?)],
294        );
295        address_lookup.add_endpoint_info(addr);
296        let mut stream = address_lookup.resolve(key.public()).unwrap();
297        let item = stream.next().await.unwrap()?;
298        assert_eq!(item.provenance(), "foo");
299        assert_eq!(
300            item.relay_urls().next(),
301            Some(&("https://example.com".parse()?))
302        );
303
304        Ok(())
305    }
306}