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 fn proxy(proxy: impl Into<String>);
125 fn no_proxy();
127 }
128
129 pub fn engine_url(&self) -> Result<url::Url> {
131 self.inner.engine_url()
132 }
133
134 pub fn connect_params_with<F>(self, params: F) -> Self
137 where
138 F: Fn() -> crate::ConnectParams + Send + Sync + 'static,
139 {
140 let params = Arc::new(params);
141 let inner = self.inner.connect_params_with(move || {
142 let params = Arc::clone(¶ms);
143 async move {
144 match tokio::task::spawn_blocking(move || params()).await {
146 Ok(value) => value,
147 Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
148 Err(_) => {
149 std::panic::resume_unwind(Box::new("connect_params_with was cancelled"))
150 }
151 }
152 }
153 });
154 ClientBuilder { inner, ..self }
155 }
156
157 #[cfg(any(feature = "rustls", feature = "native-tls"))]
159 pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self {
160 ClientBuilder {
161 inner: self.inner.tls_config(tls_config),
162 ..self
163 }
164 }
165
166 pub fn auth_with<F>(self, auth: F) -> Self
168 where
169 F: Fn() -> Value + Send + Sync + 'static,
170 {
171 let auth = Arc::new(auth);
172 let inner = self.inner.auth_with(move || {
173 let auth = Arc::clone(&auth);
174 async move {
175 match tokio::task::spawn_blocking(move || auth()).await {
177 Ok(value) => value,
178 Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
179 Err(_) => std::panic::resume_unwind(Box::new("auth_with was cancelled")),
180 }
181 }
182 });
183 ClientBuilder { inner, ..self }
184 }
185
186 pub fn inspect_packets<F>(self, inspector: F) -> Self
188 where
189 F: Fn(Direction, &protocol::socketio::Packet) + Send + Sync + 'static,
190 {
191 ClientBuilder {
192 inner: self.inner.inspect_packets(inspector),
193 ..self
194 }
195 }
196
197 pub fn on<F>(self, event: impl Into<String>, handler: F) -> Self
199 where
200 F: Fn(Event, Client) + Send + Sync + 'static,
201 {
202 let handle = self.handle.clone();
203 ClientBuilder {
204 inner: self.inner.on(event, wrap(handle, handler)),
205 ..self
206 }
207 }
208
209 pub fn once<F>(self, event: impl Into<String>, handler: F) -> Self
211 where
212 F: Fn(Event, Client) + Send + Sync + 'static,
213 {
214 let handle = self.handle.clone();
215 ClientBuilder {
216 inner: self.inner.once(event, wrap(handle, handler)),
217 ..self
218 }
219 }
220
221 pub fn on_any<F>(self, handler: F) -> Self
223 where
224 F: Fn(Event, Client) + Send + Sync + 'static,
225 {
226 let handle = self.handle.clone();
227 ClientBuilder {
228 inner: self.inner.on_any(wrap(handle, handler)),
229 ..self
230 }
231 }
232
233 pub fn on_state_change<F>(self, handler: F) -> Self
235 where
236 F: Fn(ConnectionState, Client) + Send + Sync + 'static,
237 {
238 let handle = self.handle.clone();
239 ClientBuilder {
240 inner: self.inner.on_state_change(wrap(handle, handler)),
241 ..self
242 }
243 }
244
245 pub fn connect(self) -> Result<Client> {
247 let inner = self.handle.block_on(self.inner.connect())?;
248 Ok(Client {
249 inner,
250 handle: self.handle,
251 _runtime: Some(self.runtime),
252 })
253 }
254}
255
256fn wrap<A, F>(handle: Handle, handler: F) -> impl Fn(A, crate::Client) + Send + Sync + 'static
257where
258 A: Send + 'static,
259 F: Fn(A, Client) + Send + Sync + 'static,
260{
261 move |arg, inner| {
262 handler(
263 arg,
264 Client {
265 inner,
266 handle: handle.clone(),
267 _runtime: None,
268 },
269 )
270 }
271}
272
273#[derive(Clone)]
277pub struct Client {
278 inner: crate::Client,
279 handle: Handle,
280 _runtime: Option<Arc<RuntimeOwner>>,
281}
282
283impl fmt::Debug for Client {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.debug_tuple("Client").field(&self.inner).finish()
286 }
287}
288
289impl Drop for Client {
290 fn drop(&mut self) {
291 let last = self
294 ._runtime
295 .as_ref()
296 .is_some_and(|runtime| Arc::strong_count(runtime) == 1);
297 if last && Handle::try_current().is_err() && !self.inner.state().is_closed() {
298 let inner = self.inner.clone();
299 self.handle.block_on(async move {
300 let _ = tokio::time::timeout(Duration::from_secs(3), inner.disconnect()).await;
301 });
302 }
303 }
304}
305
306impl Client {
307 pub fn as_async(&self) -> &crate::Client {
309 &self.inner
310 }
311
312 pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
314 self.inner.emit(event, data)
315 }
316
317 pub fn emit_with_ack(
319 &self,
320 event: impl AsRef<str>,
321 data: impl Into<Payload>,
322 timeout: Duration,
323 ) -> Result<Payload> {
324 self.handle
325 .block_on(self.inner.emit_with_ack(event, data, timeout))
326 }
327
328 pub fn disconnect(&self) -> Result<()> {
330 self.handle.block_on(self.inner.disconnect())
331 }
332
333 pub fn reconnect(&self) -> Result<()> {
335 self.handle.block_on(self.inner.reconnect())
336 }
337
338 pub fn on<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
340 where
341 F: Fn(Event, Client) + Send + Sync + 'static,
342 {
343 self.inner.on(event, wrap(self.handle.clone(), handler))
344 }
345
346 pub fn once<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
348 where
349 F: Fn(Event, Client) + Send + Sync + 'static,
350 {
351 self.inner.once(event, wrap(self.handle.clone(), handler))
352 }
353
354 pub fn on_any<F>(&self, handler: F) -> ListenerId
356 where
357 F: Fn(Event, Client) + Send + Sync + 'static,
358 {
359 self.inner.on_any(wrap(self.handle.clone(), handler))
360 }
361
362 pub fn on_state_change<F>(&self, handler: F) -> ListenerId
364 where
365 F: Fn(ConnectionState, Client) + Send + Sync + 'static,
366 {
367 self.inner
368 .on_state_change(wrap(self.handle.clone(), handler))
369 }
370
371 pub fn off(&self, event: &str) -> usize {
373 self.inner.off(event)
374 }
375
376 pub fn off_any(&self) -> usize {
378 self.inner.off_any()
379 }
380
381 pub fn off_listener(&self, id: ListenerId) -> bool {
383 self.inner.off_listener(id)
384 }
385
386 pub fn listener_count(&self, event: &str) -> usize {
388 self.inner.listener_count(event)
389 }
390
391 pub fn state(&self) -> ConnectionState {
393 self.inner.state()
394 }
395
396 pub fn wait_for(
399 &self,
400 predicate: impl Fn(&ConnectionState) -> bool,
401 timeout: Duration,
402 ) -> ConnectionState {
403 self.handle.block_on(async {
404 tokio::time::timeout(timeout, self.inner.wait_for(predicate))
405 .await
406 .unwrap_or_else(|_| self.inner.state())
407 })
408 }
409
410 pub fn connected(&self) -> bool {
412 self.inner.connected()
413 }
414
415 pub fn id(&self) -> Option<String> {
417 self.inner.id()
418 }
419
420 pub fn recovered(&self) -> bool {
422 self.inner.recovered()
423 }
424
425 pub fn namespace(&self) -> &str {
427 self.inner.namespace()
428 }
429
430 pub fn link_info(&self) -> LinkInfo {
432 self.inner.link_info()
433 }
434}