Skip to main content

fedimint_connectors/
lib.rs

1pub mod error;
2pub mod http;
3pub mod iroh;
4pub mod metrics;
5#[cfg(all(feature = "tor", not(target_family = "wasm")))]
6pub mod tor;
7pub mod ws;
8
9use std::collections::{BTreeMap, BTreeSet, HashMap};
10use std::fmt::{self, Debug};
11use std::net::SocketAddr;
12use std::pin::Pin;
13use std::str::FromStr as _;
14use std::sync::Arc;
15use std::time::Duration;
16
17use async_trait::async_trait;
18use fedimint_core::envs::{
19    FM_WS_API_CONNECT_OVERRIDES_ENV, is_running_in_test_env, parse_kv_list_from_env,
20};
21use fedimint_core::module::{ApiMethod, ApiRequestErased};
22use fedimint_core::util::backoff_util::{FibonacciBackoff, custom_backoff};
23use fedimint_core::util::{FmtCompact, SafeUrl};
24use fedimint_core::{apply, async_trait_maybe_send};
25use fedimint_logging::{LOG_CLIENT_NET_API, LOG_NET};
26use fedimint_metrics::HistogramExt as _;
27use reqwest::Method;
28use serde_json::Value;
29use tokio::sync::{OnceCell, SetOnce, broadcast, watch};
30use tracing::trace;
31
32use crate::error::{ConnectorError, ServerError};
33use crate::metrics::{CONNECTION_ATTEMPTS_TOTAL, CONNECTION_DURATION_SECONDS};
34use crate::ws::WebsocketConnector;
35
36const IROH_NEXT_PATH: &str = "/v1";
37
38/// Parse an advertised Iroh 1.0 endpoint ID into its API URL.
39///
40/// The `/v1` path is an internal transport-selection marker. It prevents the
41/// connector from attempting Iroh 0.35 against an Iroh 1.0-only identity,
42/// avoiding both an inappropriate connection attempt and its overhead.
43pub fn iroh_next_endpoint_url(endpoint: &str) -> Result<SafeUrl, ConnectorError> {
44    let endpoint_id = iroh_next::EndpointId::from_str(endpoint).map_err(|source| {
45        ConnectorError::InvalidNodeId {
46            host: endpoint.to_owned(),
47            source: Box::new(source),
48        }
49    })?;
50    let url = format!("iroh://{endpoint_id}{IROH_NEXT_PATH}");
51    SafeUrl::parse(&url).map_err(|source| ConnectorError::InvalidUrl {
52        url,
53        source: Box::new(source),
54    })
55}
56
57fn is_iroh_next_endpoint_url(url: &SafeUrl) -> Result<bool, ConnectorError> {
58    match url.path() {
59        "" | "/" => Ok(false),
60        IROH_NEXT_PATH => Ok(true),
61        path => Err(ConnectorError::UnsupportedUrlPath {
62            path: path.to_owned(),
63        }),
64    }
65}
66
67fn preserve_iroh_next_marker(original: &SafeUrl, replacement: &SafeUrl) -> SafeUrl {
68    // An Iroh-to-Iroh override changes the destination, not the selected wire
69    // version. Cross-protocol overrides deliberately replace the whole route.
70    if original.scheme() == "iroh"
71        && original.path() == IROH_NEXT_PATH
72        && replacement.scheme() == "iroh"
73    {
74        let mut replacement = replacement.clone().to_unsafe();
75        replacement.set_path(IROH_NEXT_PATH);
76        replacement.into()
77    } else {
78        replacement.clone()
79    }
80}
81
82pub type ServerResult<T> = Result<T, ServerError>;
83
84/// Type for connector initialization functions
85type ConnectorInitFn = Arc<
86    dyn Fn() -> Pin<Box<dyn Future<Output = Result<DynConnector, ConnectorError>> + Send>>
87        + Send
88        + Sync,
89>;
90
91/// Builder for [`ConnectorRegistry`]
92///
93/// See [`ConnectorRegistry::build_from_client_env`] and similar
94/// to create.
95#[derive(Debug, Clone)]
96#[allow(clippy::struct_excessive_bools)] // Shut up, Clippy
97pub struct ConnectorRegistryBuilder {
98    /// List of overrides to use when attempting to connect to given url
99    ///
100    /// This is useful for testing, or forcing non-default network
101    /// connectivity.
102    connection_overrides: BTreeMap<SafeUrl, SafeUrl>,
103
104    /// Enable Iroh endpoints at all?
105    iroh_enable: bool,
106    /// Override the Iroh DNS server to use
107    iroh_dns: Option<SafeUrl>,
108    /// Enable Pkarr DHT discovery
109    iroh_pkarr_dht: bool,
110    /// Enable compatible iroh-next endpoint preference from guardian metadata
111    iroh_next: bool,
112    /// Allow direct (peer-to-peer) IP connections on iroh 1.x, not only
113    /// relayed ones
114    iroh_p2p: bool,
115
116    /// Enable Websocket API handling at all?
117    ws_enable: bool,
118    ws_force_tor: bool,
119
120    // Enable HTTP
121    http_enable: bool,
122}
123
124impl ConnectorRegistryBuilder {
125    #[allow(clippy::unused_async)] // Leave room for async in the future
126    pub async fn bind(self) -> ConnectorRegistry {
127        let iroh_next = self.iroh_next && self.iroh_enable;
128
129        // Create initialization functions for each connector type
130        let mut connectors_lazy: BTreeMap<String, (ConnectorInitFn, OnceCell<DynConnector>)> =
131            BTreeMap::new();
132
133        // Eagerly created so consumers can subscribe before the Iroh
134        // connector is lazily initialized. Only Iroh bumps it today
135        // (on transport-level path changes like relay → direct).
136        let path_change = Arc::new(watch::channel(0u64).0);
137
138        // WS connector init function
139        let builder_ws = self.clone();
140        let ws_connector_init = Arc::new(move || {
141            let builder = builder_ws.clone();
142            Box::pin(async move { builder.build_ws_connector().await })
143                as Pin<Box<dyn Future<Output = Result<DynConnector, ConnectorError>> + Send>>
144        });
145        connectors_lazy.insert("ws".into(), (ws_connector_init.clone(), OnceCell::new()));
146        connectors_lazy.insert("wss".into(), (ws_connector_init.clone(), OnceCell::new()));
147
148        // Iroh connector init function
149        let builder_iroh = self.clone();
150        let path_change_iroh = path_change.clone();
151        connectors_lazy.insert(
152            "iroh".into(),
153            (
154                Arc::new(move || {
155                    let builder = builder_iroh.clone();
156                    let path_change = path_change_iroh.clone();
157                    Box::pin(async move { builder.build_iroh_connector(path_change).await })
158                        as Pin<
159                            Box<dyn Future<Output = Result<DynConnector, ConnectorError>> + Send>,
160                        >
161                }),
162                OnceCell::new(),
163            ),
164        );
165
166        let builder_http = self.clone();
167        let http_connector_init = Arc::new(move || {
168            let builder = builder_http.clone();
169            Box::pin(async move { builder.build_http_connector() })
170                as Pin<Box<dyn Future<Output = Result<DynConnector, ConnectorError>> + Send>>
171        });
172
173        connectors_lazy.insert(
174            "http".into(),
175            (http_connector_init.clone(), OnceCell::new()),
176        );
177        connectors_lazy.insert(
178            "https".into(),
179            (http_connector_init.clone(), OnceCell::new()),
180        );
181
182        ConnectorRegistry {
183            inner: ConnectorRegistryInner {
184                connectors_lazy,
185                connection_overrides: self.connection_overrides,
186                initialized: SetOnce::new(),
187                path_change,
188                iroh_next,
189            }
190            .into(),
191        }
192    }
193
194    pub async fn build_iroh_connector(
195        &self,
196        path_change: Arc<watch::Sender<u64>>,
197    ) -> Result<DynConnector, ConnectorError> {
198        if !self.iroh_enable {
199            return Err(ConnectorError::NotEnabled { scheme: "iroh" });
200        }
201        let connector = iroh::IrohConnector::new(
202            self.iroh_dns.clone(),
203            self.iroh_pkarr_dht,
204            self.iroh_p2p,
205            path_change,
206        )
207        .await?;
208
209        Ok(Arc::new(connector) as DynConnector)
210    }
211
212    pub async fn build_ws_connector(&self) -> Result<DynConnector, ConnectorError> {
213        if !self.ws_enable {
214            return Err(ConnectorError::NotEnabled { scheme: "ws" });
215        }
216
217        match self.ws_force_tor {
218            #[cfg(all(feature = "tor", not(target_family = "wasm")))]
219            true => {
220                use crate::tor::TorConnector;
221
222                Ok(Arc::new(TorConnector::bootstrap().await?) as DynConnector)
223            }
224
225            false => Ok(Arc::new(WebsocketConnector::new()) as DynConnector),
226            #[allow(unreachable_patterns)]
227            _ => Err(ConnectorError::TorNotCompiledIn),
228        }
229    }
230
231    pub fn build_http_connector(&self) -> Result<DynConnector, ConnectorError> {
232        if !self.http_enable {
233            return Err(ConnectorError::NotEnabled { scheme: "http" });
234        }
235
236        Ok(Arc::new(crate::http::HttpConnector::default()) as DynConnector)
237    }
238
239    pub fn iroh_pkarr_dht(self, enable: bool) -> Self {
240        Self {
241            iroh_pkarr_dht: enable,
242            ..self
243        }
244    }
245
246    /// Enable use of compatible iroh-next endpoints advertised in guardian
247    /// metadata.
248    pub fn iroh_next(self, enable: bool) -> Self {
249        Self {
250            iroh_next: enable,
251            ..self
252        }
253    }
254
255    /// Allow Iroh to reach guardians directly over IP, not only through
256    /// relays.
257    ///
258    /// When disabled, the iroh 1.x endpoint binds no IP sockets and sends
259    /// only through relays: guardians never learn the client's IP address,
260    /// and the client never probes the direct addresses guardians advertise.
261    /// On iOS those can include addresses on the user's own network, which
262    /// raises the Local Network permission prompt. Connection overrides that
263    /// carry a direct address stop working. The iroh 0.35 endpoint has no
264    /// runtime switch for this and is not affected.
265    pub fn iroh_p2p(self, enable: bool) -> Self {
266        Self {
267            iroh_p2p: enable,
268            ..self
269        }
270    }
271
272    pub fn ws_force_tor(self, enable: bool) -> Self {
273        Self {
274            ws_force_tor: enable,
275            ..self
276        }
277    }
278
279    pub fn http(self, enable: bool) -> Self {
280        Self {
281            http_enable: enable,
282            ..self
283        }
284    }
285
286    pub fn set_iroh_dns(self, url: SafeUrl) -> Self {
287        Self {
288            iroh_dns: Some(url),
289            ..self
290        }
291    }
292
293    /// Apply overrides from env variables
294    pub fn with_env_var_overrides(mut self) -> Self {
295        // TODO: read rest of the env
296        for (k, v) in parse_kv_list_from_env::<_, SafeUrl>(FM_WS_API_CONNECT_OVERRIDES_ENV) {
297            self = self.with_connection_override(k, v);
298        }
299
300        // Disable iroh-next endpoint preference in test/devimint environments
301        // where iroh-next server endpoints are not running.
302        if is_running_in_test_env!() {
303            self.iroh_next = false;
304        }
305
306        self
307    }
308
309    pub fn with_connection_override(
310        mut self,
311        original_url: SafeUrl,
312        replacement_url: SafeUrl,
313    ) -> Self {
314        self.connection_overrides
315            .insert(original_url, replacement_url);
316        self
317    }
318}
319
320/// Actual data shared between copies of [`ConnectorRegistry`] handle
321struct ConnectorRegistryInner {
322    /// Lazily initialized [`Connector`]s per protocol supported
323    connectors_lazy: BTreeMap<String, (ConnectorInitFn, OnceCell<DynConnector>)>,
324    /// Connection URL overrides for testing/custom routing
325    connection_overrides: BTreeMap<SafeUrl, SafeUrl>,
326    /// Set on first connection attempt
327    ///
328    /// This is used for functionality that wants to avoid making
329    /// network connections if nothing else did network request.
330    initialized: tokio::sync::SetOnce<()>,
331    /// Ticks whenever a connector observes a transport-level path change
332    /// (e.g. iroh relay → direct). Only Iroh bumps this today.
333    path_change: Arc<watch::Sender<u64>>,
334    /// Whether compatible iroh-next endpoints advertised in guardian metadata
335    /// are used.
336    iroh_next: bool,
337}
338
339/// A set of available connectivity protocols a client can use to make
340/// network API requests (typically to federation).
341///
342/// Maps from connection URL schema to [`Connector`] to use to connect to it.
343///
344/// See [`ConnectorRegistry::build_from_client_env`] and similar
345/// to create.
346///
347/// [`ConnectorRegistry::connect_guardian`] is the main entry point for making
348/// mixed-networking stack connection.
349///
350/// Responsibilities:
351#[derive(Clone)]
352pub struct ConnectorRegistry {
353    inner: Arc<ConnectorRegistryInner>,
354}
355
356impl fmt::Debug for ConnectorRegistry {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        f.debug_struct("ConnectorRegistry")
359            .field("connectors_lazy", &self.inner.connectors_lazy.len())
360            .field("connection_overrides", &self.inner.connection_overrides)
361            .field("iroh_next", &self.inner.iroh_next)
362            .finish()
363    }
364}
365
366impl ConnectorRegistry {
367    /// Whether compatible iroh-next endpoints advertised in guardian metadata
368    /// are used.
369    pub fn iroh_next_enabled(&self) -> bool {
370        self.inner.iroh_next
371    }
372
373    /// Create a builder with recommended defaults intended for client-side
374    /// usage
375    ///
376    /// In particular mobile devices are considered.
377    pub fn build_from_client_defaults() -> ConnectorRegistryBuilder {
378        ConnectorRegistryBuilder {
379            iroh_enable: true,
380            iroh_dns: None,
381            iroh_pkarr_dht: false,
382            iroh_next: true,
383            iroh_p2p: true,
384            ws_enable: true,
385            ws_force_tor: false,
386            http_enable: true,
387
388            connection_overrides: BTreeMap::default(),
389        }
390    }
391
392    /// Create a builder with recommended defaults intended for the server-side
393    /// usage
394    pub fn build_from_server_defaults() -> ConnectorRegistryBuilder {
395        ConnectorRegistryBuilder {
396            iroh_enable: true,
397            iroh_dns: None,
398            iroh_pkarr_dht: true,
399            iroh_next: true,
400            iroh_p2p: true,
401            ws_enable: true,
402            ws_force_tor: false,
403            http_enable: false,
404
405            connection_overrides: BTreeMap::default(),
406        }
407    }
408
409    /// Create a builder with recommended defaults intended for testing
410    /// usage
411    pub fn build_from_testing_defaults() -> ConnectorRegistryBuilder {
412        ConnectorRegistryBuilder {
413            iroh_enable: true,
414            iroh_dns: None,
415            iroh_pkarr_dht: false,
416            iroh_next: false,
417            iroh_p2p: true,
418            ws_enable: true,
419            ws_force_tor: false,
420            http_enable: true,
421
422            connection_overrides: BTreeMap::default(),
423        }
424    }
425
426    /// Like [`Self::build_from_client_defaults`] build will apply
427    /// environment-provided overrides.
428    pub fn build_from_client_env() -> ConnectorRegistryBuilder {
429        Self::build_from_client_defaults().with_env_var_overrides()
430    }
431
432    /// Like [`Self::build_from_server_defaults`] build will apply
433    /// environment-provided overrides.
434    pub fn build_from_server_env() -> ConnectorRegistryBuilder {
435        Self::build_from_server_defaults().with_env_var_overrides()
436    }
437
438    /// Like [`Self::build_from_testing_defaults`] build will apply
439    /// environment-provided overrides.
440    pub fn build_from_testing_env() -> ConnectorRegistryBuilder {
441        Self::build_from_testing_defaults().with_env_var_overrides()
442    }
443
444    /// Wait until some connections have been made
445    pub async fn wait_for_initialized_connections(&self) {
446        self.inner.initialized.wait().await;
447    }
448
449    /// Connect to a given `url` using matching [`Connector`]
450    ///
451    /// This is the main function consumed by the downstream use for making
452    /// connection.
453    pub async fn connect_guardian(
454        &self,
455        url: &SafeUrl,
456        api_secret: Option<&str>,
457    ) -> ServerResult<DynGuaridianConnection> {
458        trace!(
459            target: LOG_NET,
460            %url,
461            "Connection requested to guardian"
462        );
463        let _ = self.inner.initialized.set(());
464
465        let replacement = self
466            .inner
467            .connection_overrides
468            .get(url)
469            .map(|replacement| preserve_iroh_next_marker(url, replacement));
470        let url = match replacement.as_ref() {
471            Some(replacement) => {
472                trace!(
473                    target: LOG_NET,
474                    original_url = %url,
475                    replacement_url = %replacement,
476                    "Using a connectivity override for connection"
477                );
478
479                replacement
480            }
481            None => url,
482        };
483
484        let scheme = url.scheme().to_string();
485
486        let Some(connector_lazy) = self.inner.connectors_lazy.get(&scheme) else {
487            return Err(ServerError::InvalidEndpoint(
488                format!(
489                    "Unsupported scheme: {}; missing endpoint handler",
490                    url.scheme()
491                )
492                .into(),
493            ));
494        };
495
496        // Clone the init function to use in the async block
497        let init_fn = connector_lazy.0.clone();
498
499        let timer = CONNECTION_DURATION_SECONDS
500            .with_label_values(&[&scheme])
501            .start_timer_ext();
502
503        let result = connector_lazy
504            .1
505            .get_or_try_init(|| async move { init_fn().await })
506            .await
507            .map_err(|e| {
508                // `Transport` is printed, not walked, by its consumers, so the whole chain
509                // goes into the text on purpose.
510                ServerError::Transport(
511                    format!("Connector failed to initialize: {}", e.fmt_compact()).into(),
512                )
513            })?
514            .connect_guardian(url, api_secret)
515            .await;
516
517        timer.observe_duration();
518
519        let result_label = if result.is_ok() { "success" } else { "error" }.to_string();
520        CONNECTION_ATTEMPTS_TOTAL
521            .with_label_values(&[&scheme, &result_label])
522            .inc();
523
524        let conn = result.inspect_err(|err| {
525            trace!(
526                target: LOG_NET,
527                %url,
528                err = %err.fmt_compact(),
529                "Connection failed"
530            );
531        })?;
532
533        trace!(
534            target: LOG_NET,
535            %url,
536            "Connection returned"
537        );
538        Ok(conn)
539    }
540
541    /// Connect to a given `url` using matching [`Connector`] to a gateway
542    ///
543    /// This is the main function consumed by the downstream use for making
544    /// connection.
545    pub async fn connect_gateway(
546        &self,
547        url: &SafeUrl,
548    ) -> Result<DynGatewayConnection, ConnectorError> {
549        trace!(
550            target: LOG_NET,
551            %url,
552            "Connection requested to gateway"
553        );
554        let _ = self.inner.initialized.set(());
555
556        let url = match self.inner.connection_overrides.get(url) {
557            Some(replacement) => {
558                trace!(
559                    target: LOG_NET,
560                    original_url = %url,
561                    replacement_url = %replacement,
562                    "Using a connectivity override for connection"
563                );
564
565                replacement
566            }
567            None => url,
568        };
569
570        let scheme = url.scheme().to_string();
571
572        let Some(connector_lazy) = self.inner.connectors_lazy.get(&scheme) else {
573            return Err(ConnectorError::UnsupportedScheme { scheme });
574        };
575
576        // Clone the init function to use in the async block
577        let init_fn = connector_lazy.0.clone();
578
579        let timer = CONNECTION_DURATION_SECONDS
580            .with_label_values(&[&scheme])
581            .start_timer_ext();
582
583        let result = connector_lazy
584            .1
585            .get_or_try_init(|| async move { init_fn().await })
586            .await?
587            .connect_gateway(url)
588            .await;
589
590        timer.observe_duration();
591
592        let result_label = if result.is_ok() { "success" } else { "error" }.to_string();
593        CONNECTION_ATTEMPTS_TOTAL
594            .with_label_values(&[&scheme, &result_label])
595            .inc();
596
597        result
598    }
599
600    /// Report how a connection to `url` is currently reaching its peer.
601    ///
602    /// Returns [`Connectivity::Unknown`] if no connector for the url's scheme
603    /// is registered, or if the matching connector has not been initialized
604    /// yet (i.e. no connection attempt has been made).
605    pub fn connectivity(&self, url: &SafeUrl) -> Connectivity {
606        let url = match self.inner.connection_overrides.get(url) {
607            Some(replacement) => replacement,
608            None => url,
609        };
610
611        let Some((_, connector_cell)) = self.inner.connectors_lazy.get(url.scheme()) else {
612            return Connectivity::Unknown;
613        };
614
615        match connector_cell.get() {
616            Some(connector) => connector.connectivity(url),
617            None => Connectivity::Unknown,
618        }
619    }
620
621    /// Return iroh-specific peer details if `url` is handled by the iroh
622    /// connector.
623    pub async fn iroh_peer_info(
624        &self,
625        url: &SafeUrl,
626        path_timeout: Duration,
627    ) -> ServerResult<Option<IrohPeerInfo>> {
628        let url = match self.inner.connection_overrides.get(url) {
629            Some(replacement) => replacement,
630            None => url,
631        };
632
633        let Some((init_fn, connector_cell)) = self.inner.connectors_lazy.get(url.scheme()) else {
634            return Ok(None);
635        };
636
637        let init_fn = init_fn.clone();
638        connector_cell
639            .get_or_try_init(|| async move { init_fn().await })
640            .await
641            .map_err(|e| {
642                // `Transport` is printed, not walked, by its consumers, so the whole chain
643                // goes into the text on purpose.
644                ServerError::Transport(
645                    format!("Connector failed to initialize: {}", e.fmt_compact()).into(),
646                )
647            })?
648            .iroh_peer_info(url, path_timeout)
649            .await
650    }
651
652    /// Subscribe to transport-level connectivity changes across all
653    /// connectors managed by this registry.
654    ///
655    /// The receiver ticks whenever a connector observes a path change on
656    /// an existing connection (for example an iroh connection upgrading
657    /// from relay to direct). The carried `u64` is an opaque counter —
658    /// consumers should treat each update as a "re-read connectivity"
659    /// signal.
660    pub fn connectivity_change_notifier(&self) -> watch::Receiver<u64> {
661        self.inner.path_change.subscribe()
662    }
663}
664pub type DynConnector = Arc<dyn Connector>;
665
666#[async_trait]
667pub trait Connector: Send + Sync + 'static + Debug {
668    async fn connect_guardian(
669        &self,
670        url: &SafeUrl,
671        api_secret: Option<&str>,
672    ) -> ServerResult<DynGuaridianConnection>;
673
674    async fn connect_gateway(&self, url: &SafeUrl) -> Result<DynGatewayConnection, ConnectorError>;
675
676    /// Report how a connection to `url` is currently reaching its peer.
677    fn connectivity(&self, url: &SafeUrl) -> Connectivity;
678
679    /// Return iroh-specific peer details if this connector supports them.
680    async fn iroh_peer_info(
681        &self,
682        _url: &SafeUrl,
683        _path_timeout: Duration,
684    ) -> ServerResult<Option<IrohPeerInfo>> {
685        Ok(None)
686    }
687}
688
689/// How a connection is currently reaching its peer.
690///
691/// Transports without a relay concept (WS, HTTP) are always
692/// [`Connectivity::Direct`]. Tor-routed connections report
693/// [`Connectivity::Tor`]. Iroh connections may be [`Connectivity::Direct`]
694/// (peer-to-peer), [`Connectivity::Relay`] (routed through a relay
695/// server), or [`Connectivity::Mixed`] (both paths active); for Iroh this
696/// can change at runtime as hole-punching succeeds or falls back.
697#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
698pub enum Connectivity {
699    Direct,
700    Relay,
701    Mixed,
702    Tor,
703    Unknown,
704}
705
706/// Per-peer connection state reported by the federation API.
707///
708/// [`PeerStatus::Connected`] carries the current [`Connectivity`] of the
709/// active connection; for Iroh this reflects the path at the moment of the
710/// emission and may be stale until the next pool-level change (relay→direct
711/// upgrades on an existing connection are not yet streamed).
712#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
713pub enum PeerStatus {
714    Disconnected,
715    Connected(Connectivity),
716}
717
718/// Iroh-specific reachability details for a guardian endpoint.
719#[derive(Debug, Clone, PartialEq, Eq)]
720pub struct IrohPeerInfo {
721    pub node_id: String,
722    pub connectivity: Connectivity,
723    pub direct_addr: Option<SocketAddr>,
724    pub known_direct_addrs: Vec<SocketAddr>,
725    pub relay_url: Option<String>,
726}
727
728/// Generic connection trait shared between [`IGuardianConnection`] and
729/// [`IGatewayConnection`]
730#[apply(async_trait_maybe_send!)]
731pub trait IConnection: Debug + Send + Sync + 'static {
732    fn is_connected(&self) -> bool;
733
734    async fn await_disconnection(&self);
735}
736
737/// A connection from api client to a federation guardian (type erased)
738pub type DynGuaridianConnection = Arc<dyn IGuardianConnection>;
739
740/// A connection from api client to a federation guardian
741#[async_trait]
742pub trait IGuardianConnection: IConnection + Debug + Send + Sync + 'static {
743    async fn request(&self, method: ApiMethod, request: ApiRequestErased) -> ServerResult<Value>;
744
745    fn into_dyn(self) -> DynGuaridianConnection
746    where
747        Self: Sized,
748    {
749        Arc::new(self)
750    }
751}
752
753/// A connection from api client to a gateway (type erased)
754pub type DynGatewayConnection = Arc<dyn IGatewayConnection>;
755
756/// A connection from a client to a gateway
757#[apply(async_trait_maybe_send!)]
758pub trait IGatewayConnection: IConnection + Debug + Send + Sync + 'static {
759    async fn request(
760        &self,
761        password: Option<String>,
762        method: Method,
763        route: &str,
764        payload: Option<Value>,
765    ) -> ServerResult<Value>;
766
767    fn into_dyn(self) -> DynGatewayConnection
768    where
769        Self: Sized,
770    {
771        Arc::new(self)
772    }
773}
774
775#[derive(Debug)]
776pub struct ConnectionPool<T: IConnection + ?Sized> {
777    /// Available connectors which we can make connections
778    connectors: ConnectorRegistry,
779
780    active_connections: watch::Sender<BTreeSet<SafeUrl>>,
781
782    /// Connection pool
783    ///
784    /// Every entry in this map will be created on demand and correspond to a
785    /// single outgoing connection to a certain URL that is in the process
786    /// of being established, or we already established.
787    #[allow(clippy::type_complexity)]
788    connections: Arc<tokio::sync::Mutex<HashMap<SafeUrl, Arc<ConnectionState<T>>>>>,
789}
790
791impl<T: IConnection + ?Sized> Clone for ConnectionPool<T> {
792    fn clone(&self) -> Self {
793        Self {
794            connectors: self.connectors.clone(),
795            connections: self.connections.clone(),
796            active_connections: self.active_connections.clone(),
797        }
798    }
799}
800
801impl<T: IConnection + ?Sized> ConnectionPool<T> {
802    pub fn new(connectors: ConnectorRegistry) -> Self {
803        Self {
804            connectors,
805            connections: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
806            active_connections: watch::channel(BTreeSet::new()).0,
807        }
808    }
809
810    async fn get_or_init_pool_entry(&self, url: &SafeUrl) -> Arc<ConnectionState<T>> {
811        let mut pool_locked = self.connections.lock().await;
812        pool_locked
813            .entry(url.to_owned())
814            .and_modify(|entry_arc| {
815                // Check if existing connection is disconnected and reset the whole entry.
816                //
817                // This resets the state (like connectivity backoff), which is what we want.
818                // Since the (`OnceCell`) was already initialized, it means connection was
819                // successfully before, and disconnected afterwards.
820                if let Some(existing_conn) = entry_arc.connection.get()
821                    && !existing_conn.is_connected()
822                {
823                    trace!(
824                        target: LOG_CLIENT_NET_API,
825                        %url,
826                        "Existing connection is disconnected, removing from pool"
827                    );
828                    self.active_connections.send_modify(|v| {
829                        v.remove(url);
830                    });
831                    *entry_arc = Arc::new(ConnectionState::new_reconnecting());
832                }
833            })
834            .or_insert_with(|| Arc::new(ConnectionState::new_initial()))
835            .clone()
836    }
837
838    pub async fn get_or_create_connection<F, Fut>(
839        &self,
840        url: &SafeUrl,
841        api_secret: Option<&str>,
842        create_connection: F,
843    ) -> ServerResult<Arc<T>>
844    where
845        F: Fn(SafeUrl, Option<String>, ConnectorRegistry) -> Fut + Clone + Send + Sync + 'static,
846        Fut: Future<Output = ServerResult<Arc<T>>> + Send + 'static,
847    {
848        let pool_entry_arc = self.get_or_init_pool_entry(url).await;
849
850        let leader_tx = loop {
851            let mut leader_rx = {
852                let mut chan_locked = pool_entry_arc
853                    .merge_connection_attempts_chan
854                    .lock()
855                    .expect("locking error");
856
857                if chan_locked.is_closed() {
858                    let (leader_tx, leader_rx) = broadcast::channel(1);
859                    *chan_locked = leader_rx;
860                    // whoever was trying to connect last time is gone
861                    // we're out of this lame loop for followers
862                    break leader_tx;
863                }
864
865                // lets piggyback on the existing leader
866                chan_locked.resubscribe()
867            };
868
869            if let Ok(res) = leader_rx.recv().await {
870                match res {
871                    Ok(o) => return Ok(o),
872                    Err(err) => {
873                        return Err(ServerError::Connection(err.into()));
874                    }
875                }
876            }
877        };
878
879        let conn = pool_entry_arc
880            .connection
881            .get_or_try_init(|| async {
882                let retry_delay = pool_entry_arc.pre_reconnect_delay();
883                fedimint_core::runtime::sleep(retry_delay).await;
884                pool_entry_arc
885                    .inner
886                    .lock()
887                    .expect("Locking failed")
888                    .retry_at = None;
889
890                trace!(target: LOG_CLIENT_NET_API, %url, "Attempting to create a new connection");
891                let res = create_connection(
892                    url.clone(),
893                    api_secret.map(std::string::ToString::to_string),
894                    self.connectors.clone(),
895                )
896                .await;
897
898                // If any other task was also waiting to connect, send them the connection
899                // result.
900                //
901                // Note: we want to send both Ok or Err, so `res?` is used only afterwards.
902                let _ = leader_tx.send(
903                    res.as_ref()
904                        .map(|o| o.clone())
905                        .map_err(|err| err.fmt_compact().to_string()),
906                );
907
908                let conn = res?;
909
910                self.active_connections.send_modify(|v| {
911                    v.insert(url.clone());
912                });
913
914                fedimint_core::runtime::spawn("connection disconnect watch", {
915                    let conn = conn.clone();
916                    let s = self.clone();
917                    let url = url.clone();
918                    async move {
919                        // wait for this connection to disconnect
920                        conn.await_disconnection().await;
921                        // And afterwards, update `active_connections`.
922                        //
923                        // This will update the `active_connections` just like calling
924                        // `get_or_create_connection` normally do, but we will
925                        // not attempt to do anything with the result (i.e. try to connect).
926                        s.get_or_init_pool_entry(&url).await;
927                    }
928                });
929
930                Ok(conn)
931            })
932            .await?;
933
934        trace!(target: LOG_CLIENT_NET_API, %url, "Connection ready");
935        Ok(conn.clone())
936    }
937    /// Get receiver for changes in the active connections
938    pub fn get_active_connection_receiver(&self) -> watch::Receiver<BTreeSet<SafeUrl>> {
939        self.active_connections.subscribe()
940    }
941
942    pub async fn wait_for_initialized_connections(&self) {
943        self.connectors.wait_for_initialized_connections().await
944    }
945
946    /// Report how a connection to `url` is currently reaching its peer.
947    pub fn connectivity(&self, url: &SafeUrl) -> Connectivity {
948        self.connectors.connectivity(url)
949    }
950
951    /// Subscribe to transport-level connectivity changes observed by
952    /// the connectors underlying this pool.
953    pub fn connectivity_change_notifier(&self) -> watch::Receiver<u64> {
954        self.connectors.connectivity_change_notifier()
955    }
956}
957
958/// Inner part of [`ConnectionState`] preserving state between attempts to
959/// initialize [`ConnectionState::connection`]
960#[derive(Debug)]
961struct ConnectionStateInner {
962    fresh: bool,
963    backoff: FibonacciBackoff,
964    retry_at: Option<fedimint_core::runtime::Instant>,
965}
966
967#[derive(Debug)]
968pub struct ConnectionState<T: ?Sized> {
969    /// Connection we are trying to or already established
970    pub connection: tokio::sync::OnceCell<Arc<T>>,
971
972    /// When tasks attempt to connect at the same time,
973    /// this is the receiving end of the channel where
974    /// the "leader" sends a result.
975    merge_connection_attempts_chan:
976        std::sync::Mutex<broadcast::Receiver<std::result::Result<Arc<T>, String>>>,
977
978    /// State that technically is protected every time by
979    /// the serialization of `OnceCell::get_or_try_init`, but
980    /// for Rust purposes needs to be locked.
981    inner: std::sync::Mutex<ConnectionStateInner>,
982}
983
984impl<T: ?Sized> ConnectionState<T> {
985    /// Create a new connection state for a first time connection
986    pub fn new_initial() -> Self {
987        Self {
988            connection: OnceCell::new(),
989            inner: std::sync::Mutex::new(ConnectionStateInner {
990                fresh: true,
991                retry_at: None,
992                backoff: custom_backoff(
993                    // First time connections start quick
994                    Duration::from_millis(5),
995                    Duration::from_secs(30),
996                    None,
997                ),
998            }),
999            merge_connection_attempts_chan: std::sync::Mutex::new(broadcast::channel(1).1),
1000        }
1001    }
1002
1003    /// Create a new connection state for a connection that already failed, and
1004    /// is being reset
1005    pub fn new_reconnecting() -> Self {
1006        Self {
1007            connection: OnceCell::new(),
1008            inner: std::sync::Mutex::new(ConnectionStateInner {
1009                // set the attempts to 1, indicating that
1010                fresh: false,
1011                retry_at: None,
1012                backoff: custom_backoff(
1013                    // Connections after a disconnect start with some minimum delay
1014                    Duration::from_millis(500),
1015                    Duration::from_secs(30),
1016                    None,
1017                ),
1018            }),
1019            merge_connection_attempts_chan: std::sync::Mutex::new(broadcast::channel(1).1),
1020        }
1021    }
1022
1023    /// Return the remaining wait, preserving its deadline across cancellation.
1024    pub fn pre_reconnect_delay(&self) -> Duration {
1025        let mut backoff_locked = self.inner.lock().expect("Locking failed");
1026        let now = fedimint_core::runtime::Instant::now();
1027        if let Some(retry_at) = backoff_locked.retry_at {
1028            return retry_at.saturating_duration_since(now);
1029        }
1030        let fresh = backoff_locked.fresh;
1031
1032        backoff_locked.fresh = false;
1033
1034        let delay = if fresh {
1035            Duration::default()
1036        } else {
1037            backoff_locked.backoff.next().expect("Keeps retrying")
1038        };
1039        backoff_locked.retry_at = Some(now + delay);
1040        delay
1041    }
1042}
1043
1044#[cfg(test)]
1045mod reconnect_tests;