fedimint_client/client/
handle.rs1use std::ops;
2use std::sync::Arc;
3use std::time::Duration;
4
5use anyhow::format_err;
6use fedimint_core::runtime;
7use fedimint_core::util::FmtCompactAnyhow as _;
8use fedimint_logging::LOG_CLIENT;
9#[cfg(not(target_family = "wasm"))]
10use tokio::runtime::{Handle as RuntimeHandle, RuntimeFlavor};
11use tracing::{debug, error, trace, warn};
12
13use super::Client;
14use crate::ClientBuilder;
15
16#[derive(Debug)]
26pub struct ClientHandle {
27 inner: Option<Arc<Client>>,
28}
29
30pub type ClientHandleArc = Arc<ClientHandle>;
32
33impl ClientHandle {
34 pub(crate) fn new(inner: Arc<Client>) -> Self {
36 ClientHandle {
37 inner: inner.into(),
38 }
39 }
40
41 pub(crate) fn as_inner(&self) -> &Arc<Client> {
42 self.inner.as_ref().expect("Inner always set")
43 }
44
45 pub fn start_executor(&self) {
46 self.as_inner().start_executor();
47 }
48
49 pub async fn shutdown(mut self) {
51 self.shutdown_inner().await;
52 }
53
54 async fn shutdown_inner(&mut self) {
55 let Some(inner) = self.inner.take() else {
56 error!(
57 target: LOG_CLIENT,
58 "ClientHandleShared::shutdown called twice"
59 );
60 return;
61 };
62 inner.executor.stop_executor();
63 let db = inner.db.clone();
64 debug!(target: LOG_CLIENT, "Waiting for client task group to shut down");
65 if let Err(err) = inner
66 .task_group
67 .clone()
68 .shutdown_join_all(Some(Duration::from_secs(30)))
69 .await
70 {
71 warn!(target: LOG_CLIENT, err = %err.fmt_compact_anyhow(), "Error waiting for client task group to shut down");
72 }
73
74 let client_strong_count = Arc::strong_count(&inner);
75 debug!(target: LOG_CLIENT, "Dropping last handle to Client");
76 drop(inner);
79
80 if client_strong_count != 1 {
81 debug!(target: LOG_CLIENT, count = client_strong_count - 1, LOG_CLIENT, "External Client references remaining after last handle dropped");
82 }
83
84 let db_strong_count = db.strong_count();
85 if db_strong_count != 1 {
86 debug!(target: LOG_CLIENT, count = db_strong_count - 1, "External DB references remaining after last handle dropped");
87 }
88 trace!(target: LOG_CLIENT, "Dropped last handle to Client");
89 }
90
91 pub async fn restart(self) -> anyhow::Result<ClientHandle> {
99 let (builder, config, api_secret, root_secret, db, endpoints) = {
100 let client = self
101 .inner
102 .as_ref()
103 .ok_or_else(|| format_err!("Already stopped"))?;
104 let builder = ClientBuilder::from_existing(client);
105 let config = client.config().await;
106 let api_secret = client.api_secret.clone();
107 let root_secret = client.root_secret.clone();
108 let db = client.db().clone();
109 let endpoints = client.endpoints().clone();
110
111 (builder, config, api_secret, root_secret, db, endpoints)
112 };
113 self.shutdown().await;
114
115 builder
116 .build(
117 endpoints,
118 db,
119 root_secret,
120 config,
121 api_secret,
122 false,
123 None,
124 None,
125 None, )
127 .await
128 }
129}
130
131impl ops::Deref for ClientHandle {
132 type Target = Client;
133
134 fn deref(&self) -> &Self::Target {
135 self.inner.as_ref().expect("Must have inner client set")
136 }
137}
138
139impl Drop for ClientHandle {
145 fn drop(&mut self) {
146 if self.inner.is_none() {
147 return;
148 }
149
150 #[cfg(target_family = "wasm")]
152 let can_block = false;
153 #[cfg(not(target_family = "wasm"))]
154 let can_block = RuntimeHandle::current().runtime_flavor() != RuntimeFlavor::CurrentThread;
156 if !can_block {
157 let inner = self.inner.take().expect("Must have inner client set");
158 inner.executor.stop_executor();
159 if cfg!(target_family = "wasm") {
160 error!(target: LOG_CLIENT, "Automatic client shutdown is not possible on wasm, call ClientHandle::shutdown manually.");
161 } else {
162 error!(target: LOG_CLIENT, "Automatic client shutdown is not possible on current thread runtime, call ClientHandle::shutdown manually.");
163 }
164 return;
165 }
166
167 debug!(target: LOG_CLIENT, "Shutting down the Client on last handle drop");
168 #[cfg(not(target_family = "wasm"))]
169 runtime::block_in_place(|| {
170 runtime::block_on(self.shutdown_inner());
171 });
172 }
173}