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
38pub 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 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
84type ConnectorInitFn = Arc<
86 dyn Fn() -> Pin<Box<dyn Future<Output = Result<DynConnector, ConnectorError>> + Send>>
87 + Send
88 + Sync,
89>;
90
91#[derive(Debug, Clone)]
96#[allow(clippy::struct_excessive_bools)] pub struct ConnectorRegistryBuilder {
98 connection_overrides: BTreeMap<SafeUrl, SafeUrl>,
103
104 iroh_enable: bool,
106 iroh_dns: Option<SafeUrl>,
108 iroh_pkarr_dht: bool,
110 iroh_next: bool,
112 iroh_p2p: bool,
115
116 ws_enable: bool,
118 ws_force_tor: bool,
119
120 http_enable: bool,
122}
123
124impl ConnectorRegistryBuilder {
125 #[allow(clippy::unused_async)] pub async fn bind(self) -> ConnectorRegistry {
127 let iroh_next = self.iroh_next && self.iroh_enable;
128
129 let mut connectors_lazy: BTreeMap<String, (ConnectorInitFn, OnceCell<DynConnector>)> =
131 BTreeMap::new();
132
133 let path_change = Arc::new(watch::channel(0u64).0);
137
138 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 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 pub fn iroh_next(self, enable: bool) -> Self {
249 Self {
250 iroh_next: enable,
251 ..self
252 }
253 }
254
255 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 pub fn with_env_var_overrides(mut self) -> Self {
295 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 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
320struct ConnectorRegistryInner {
322 connectors_lazy: BTreeMap<String, (ConnectorInitFn, OnceCell<DynConnector>)>,
324 connection_overrides: BTreeMap<SafeUrl, SafeUrl>,
326 initialized: tokio::sync::SetOnce<()>,
331 path_change: Arc<watch::Sender<u64>>,
334 iroh_next: bool,
337}
338
339#[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 pub fn iroh_next_enabled(&self) -> bool {
370 self.inner.iroh_next
371 }
372
373 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 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 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 pub fn build_from_client_env() -> ConnectorRegistryBuilder {
429 Self::build_from_client_defaults().with_env_var_overrides()
430 }
431
432 pub fn build_from_server_env() -> ConnectorRegistryBuilder {
435 Self::build_from_server_defaults().with_env_var_overrides()
436 }
437
438 pub fn build_from_testing_env() -> ConnectorRegistryBuilder {
441 Self::build_from_testing_defaults().with_env_var_overrides()
442 }
443
444 pub async fn wait_for_initialized_connections(&self) {
446 self.inner.initialized.wait().await;
447 }
448
449 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 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 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 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 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 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 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 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 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 fn connectivity(&self, url: &SafeUrl) -> Connectivity;
678
679 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
698pub enum Connectivity {
699 Direct,
700 Relay,
701 Mixed,
702 Tor,
703 Unknown,
704}
705
706#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
713pub enum PeerStatus {
714 Disconnected,
715 Connected(Connectivity),
716}
717
718#[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#[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
737pub type DynGuaridianConnection = Arc<dyn IGuardianConnection>;
739
740#[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
753pub type DynGatewayConnection = Arc<dyn IGatewayConnection>;
755
756#[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 connectors: ConnectorRegistry,
779
780 active_connections: watch::Sender<BTreeSet<SafeUrl>>,
781
782 #[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 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 break leader_tx;
863 }
864
865 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 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 conn.await_disconnection().await;
921 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 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 pub fn connectivity(&self, url: &SafeUrl) -> Connectivity {
948 self.connectors.connectivity(url)
949 }
950
951 pub fn connectivity_change_notifier(&self) -> watch::Receiver<u64> {
954 self.connectors.connectivity_change_notifier()
955 }
956}
957
958#[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 pub connection: tokio::sync::OnceCell<Arc<T>>,
971
972 merge_connection_attempts_chan:
976 std::sync::Mutex<broadcast::Receiver<std::result::Result<Arc<T>, String>>>,
977
978 inner: std::sync::Mutex<ConnectionStateInner>,
982}
983
984impl<T: ?Sized> ConnectionState<T> {
985 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 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 pub fn new_reconnecting() -> Self {
1006 Self {
1007 connection: OnceCell::new(),
1008 inner: std::sync::Mutex::new(ConnectionStateInner {
1009 fresh: false,
1011 retry_at: None,
1012 backoff: custom_backoff(
1013 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 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;