1use std::fmt;
24use std::sync::Arc;
25use std::time::Duration;
26
27use serde_json::Value;
28use tokio::runtime::{Handle, Runtime};
29
30#[cfg(any(feature = "rustls", feature = "native-tls"))]
31use crate::engineio::TlsConfig;
32use crate::handler::ListenerId;
33use crate::{
34 ConnectionState, Direction, Event, LinkInfo, Payload, Result, TransportType, protocol,
35};
36
37struct RuntimeOwner(Option<Runtime>);
39
40impl Drop for RuntimeOwner {
41 fn drop(&mut self) {
42 if let Some(runtime) = self.0.take() {
43 runtime.shutdown_background();
44 }
45 }
46}
47
48pub struct ClientBuilder {
50 inner: crate::ClientBuilder,
51 runtime: Arc<RuntimeOwner>,
52 handle: Handle,
53}
54
55impl fmt::Debug for ClientBuilder {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 f.debug_struct("ClientBuilder")
58 .field("inner", &self.inner)
59 .finish_non_exhaustive()
60 }
61}
62
63macro_rules! delegate {
64 ($($(#[$meta:meta])* fn $name:ident($($arg:ident: $ty:ty),*);)*) => {$(
65 $(#[$meta])*
66 pub fn $name(self, $($arg: $ty),*) -> Self {
67 ClientBuilder { inner: self.inner.$name($($arg),*), ..self }
68 }
69 )*};
70}
71
72impl ClientBuilder {
73 pub fn new(address: impl Into<String>) -> Self {
78 let runtime = tokio::runtime::Builder::new_multi_thread()
79 .worker_threads(1)
80 .thread_name("socketio-next")
81 .enable_all()
82 .build()
83 .expect("start the socketio-next runtime");
84 let handle = runtime.handle().clone();
85 ClientBuilder {
86 inner: crate::ClientBuilder::new(address),
87 runtime: Arc::new(RuntimeOwner(Some(runtime))),
88 handle,
89 }
90 }
91
92 delegate! {
93 fn namespace(namespace: impl Into<String>);
95 fn path(path: impl Into<String>);
97 fn query(key: impl Into<String>, value: impl Into<String>);
99 fn header(key: impl Into<String>, value: impl Into<String>);
101 fn auth(auth: impl Into<Value>);
103 fn transport_type(transport: TransportType);
105 fn timeout(timeout: Duration);
107 fn reconnection(reconnection: bool);
109 fn reconnection_attempts(attempts: u32);
111 fn reconnection_delay(delay: Duration);
113 fn reconnection_delay_max(delay: Duration);
115 fn randomization_factor(factor: f64);
117 fn reconnect_on_disconnect(reconnect: bool);
119 fn buffer_while_disconnected(buffer: bool);
121 fn redact_query(redact: bool);
123 }
124
125 #[cfg(any(feature = "rustls", feature = "native-tls"))]
127 pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self {
128 ClientBuilder {
129 inner: self.inner.tls_config(tls_config),
130 ..self
131 }
132 }
133
134 pub fn auth_with<F>(self, auth: F) -> Self
136 where
137 F: Fn() -> Value + Send + Sync + 'static,
138 {
139 let auth = Arc::new(auth);
140 let inner = self.inner.auth_with(move || {
141 let auth = Arc::clone(&auth);
142 async move {
143 tokio::task::spawn_blocking(move || auth())
144 .await
145 .unwrap_or(Value::Null)
146 }
147 });
148 ClientBuilder { inner, ..self }
149 }
150
151 pub fn inspect_packets<F>(self, inspector: F) -> Self
153 where
154 F: Fn(Direction, &protocol::socketio::Packet) + Send + Sync + 'static,
155 {
156 ClientBuilder {
157 inner: self.inner.inspect_packets(inspector),
158 ..self
159 }
160 }
161
162 pub fn on<F>(self, event: impl Into<String>, handler: F) -> Self
164 where
165 F: Fn(Event, Client) + Send + Sync + 'static,
166 {
167 let handle = self.handle.clone();
168 ClientBuilder {
169 inner: self.inner.on(event, wrap(handle, handler)),
170 ..self
171 }
172 }
173
174 pub fn once<F>(self, event: impl Into<String>, handler: F) -> Self
176 where
177 F: Fn(Event, Client) + Send + Sync + 'static,
178 {
179 let handle = self.handle.clone();
180 ClientBuilder {
181 inner: self.inner.once(event, wrap(handle, handler)),
182 ..self
183 }
184 }
185
186 pub fn on_any<F>(self, handler: F) -> Self
188 where
189 F: Fn(Event, Client) + Send + Sync + 'static,
190 {
191 let handle = self.handle.clone();
192 ClientBuilder {
193 inner: self.inner.on_any(wrap(handle, handler)),
194 ..self
195 }
196 }
197
198 pub fn on_state_change<F>(self, handler: F) -> Self
200 where
201 F: Fn(ConnectionState, Client) + Send + Sync + 'static,
202 {
203 let handle = self.handle.clone();
204 ClientBuilder {
205 inner: self.inner.on_state_change(wrap(handle, handler)),
206 ..self
207 }
208 }
209
210 pub fn connect(self) -> Result<Client> {
212 let inner = self.handle.block_on(self.inner.connect())?;
213 Ok(Client {
214 inner,
215 handle: self.handle,
216 _runtime: Some(self.runtime),
217 })
218 }
219}
220
221fn wrap<A, F>(handle: Handle, handler: F) -> impl Fn(A, crate::Client) + Send + Sync + 'static
222where
223 A: Send + 'static,
224 F: Fn(A, Client) + Send + Sync + 'static,
225{
226 move |arg, inner| {
227 handler(
228 arg,
229 Client {
230 inner,
231 handle: handle.clone(),
232 _runtime: None,
233 },
234 )
235 }
236}
237
238#[derive(Clone)]
242pub struct Client {
243 inner: crate::Client,
244 handle: Handle,
245 _runtime: Option<Arc<RuntimeOwner>>,
246}
247
248impl fmt::Debug for Client {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.debug_tuple("Client").field(&self.inner).finish()
251 }
252}
253
254impl Drop for Client {
255 fn drop(&mut self) {
256 let last = self
259 ._runtime
260 .as_ref()
261 .is_some_and(|runtime| Arc::strong_count(runtime) == 1);
262 if last && Handle::try_current().is_err() && !self.inner.state().is_closed() {
263 let inner = self.inner.clone();
264 self.handle.block_on(async move {
265 let _ = tokio::time::timeout(Duration::from_secs(3), inner.disconnect()).await;
266 });
267 }
268 }
269}
270
271impl Client {
272 pub fn as_async(&self) -> &crate::Client {
274 &self.inner
275 }
276
277 pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
279 self.inner.emit(event, data)
280 }
281
282 pub fn emit_with_ack(
284 &self,
285 event: impl AsRef<str>,
286 data: impl Into<Payload>,
287 timeout: Duration,
288 ) -> Result<Payload> {
289 self.handle
290 .block_on(self.inner.emit_with_ack(event, data, timeout))
291 }
292
293 pub fn disconnect(&self) -> Result<()> {
295 self.handle.block_on(self.inner.disconnect())
296 }
297
298 pub fn reconnect(&self) -> Result<()> {
300 self.handle.block_on(self.inner.reconnect())
301 }
302
303 pub fn on<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
305 where
306 F: Fn(Event, Client) + Send + Sync + 'static,
307 {
308 self.inner.on(event, wrap(self.handle.clone(), handler))
309 }
310
311 pub fn once<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
313 where
314 F: Fn(Event, Client) + Send + Sync + 'static,
315 {
316 self.inner.once(event, wrap(self.handle.clone(), handler))
317 }
318
319 pub fn off(&self, event: &str) -> usize {
321 self.inner.off(event)
322 }
323
324 pub fn off_listener(&self, id: ListenerId) -> bool {
326 self.inner.off_listener(id)
327 }
328
329 pub fn listener_count(&self, event: &str) -> usize {
331 self.inner.listener_count(event)
332 }
333
334 pub fn state(&self) -> ConnectionState {
336 self.inner.state()
337 }
338
339 pub fn wait_for(
342 &self,
343 predicate: impl Fn(&ConnectionState) -> bool,
344 timeout: Duration,
345 ) -> ConnectionState {
346 self.handle.block_on(async {
347 tokio::time::timeout(timeout, self.inner.wait_for(predicate))
348 .await
349 .unwrap_or_else(|_| self.inner.state())
350 })
351 }
352
353 pub fn connected(&self) -> bool {
355 self.inner.connected()
356 }
357
358 pub fn id(&self) -> Option<String> {
360 self.inner.id()
361 }
362
363 pub fn namespace(&self) -> &str {
365 self.inner.namespace()
366 }
367
368 pub fn link_info(&self) -> LinkInfo {
370 self.inner.link_info()
371 }
372}