wsio_client/
lib.rs

1use std::{
2    fmt::Display,
3    sync::Arc,
4};
5
6use anyhow::Result;
7use serde::{
8    Serialize,
9    de::DeserializeOwned,
10};
11use tokio_util::sync::CancellationToken;
12use url::Url;
13pub use wsio_core as core;
14
15mod builder;
16mod config;
17pub mod connection;
18mod runtime;
19
20use crate::{
21    builder::WsIoClientBuilder,
22    connection::WsIoClientConnection,
23    core::traits::task::spawner::TaskSpawner,
24    runtime::WsIoClientRuntime,
25};
26
27// Structs
28#[derive(Clone)]
29pub struct WsIoClient(Arc<WsIoClientRuntime>);
30
31impl WsIoClient {
32    // Public methods
33    pub fn builder<U>(url: U) -> Result<WsIoClientBuilder>
34    where
35        U: TryInto<Url>,
36        U::Error: Display,
37    {
38        let url = match url.try_into() {
39            Ok(url) => url,
40            Err(e) => panic!("Invalid URL: {e}"),
41        };
42
43        WsIoClientBuilder::new(url)
44    }
45
46    pub fn cancel_token(&self) -> Arc<CancellationToken> {
47        self.0.cancel_token()
48    }
49
50    pub async fn connect(&self) {
51        self.0.connect().await
52    }
53
54    pub async fn disconnect(&self) {
55        self.0.disconnect().await
56    }
57
58    pub async fn emit<D: Serialize>(&self, event: impl AsRef<str>, data: Option<&D>) -> Result<()> {
59        self.0.emit(event.as_ref(), data).await
60    }
61
62    #[inline]
63    pub fn off(&self, event: impl AsRef<str>) {
64        self.0.off(event.as_ref());
65    }
66
67    #[inline]
68    pub fn off_by_handler_id(&self, event: impl AsRef<str>, handler_id: u32) {
69        self.0.off_by_handler_id(event.as_ref(), handler_id);
70    }
71
72    #[inline]
73    pub fn on<H, Fut, D>(&self, event: impl AsRef<str>, handler: H) -> u32
74    where
75        H: Fn(Arc<WsIoClientConnection>, Arc<D>) -> Fut + Send + Sync + 'static,
76        Fut: Future<Output = Result<()>> + Send + 'static,
77        D: DeserializeOwned + Send + Sync + 'static,
78    {
79        self.0.on(event.as_ref(), handler)
80    }
81
82    #[inline]
83    pub fn spawn_task<F: Future<Output = Result<()>> + Send + 'static>(&self, future: F) {
84        self.0.spawn_task(future);
85    }
86}