Skip to main content

arpy_reqwasm/
websocket.rs

1//! Websocket Client.
2//!
3//! See [`Connection`] for an example.
4use arpy::{ConcurrentRpcClient, FnRemote, FnSubscription, RpcClient};
5use arpy_client::websocket::{Call, SubscriptionStream};
6use async_trait::async_trait;
7use futures::{SinkExt, Stream, StreamExt, TryStreamExt};
8use reqwasm::websocket::{futures::WebSocket, Message};
9use serde::de::DeserializeOwned;
10
11use crate::{Error, LocalSpawner};
12
13/// A connection to the server.
14///
15/// # Example
16///
17/// ```
18#[doc = include_doc::function_body!("tests/doc.rs", websocket_client, [my_app, MyAdd])]
19/// ```
20#[derive(Clone)]
21pub struct Connection(arpy_client::websocket::Connection<LocalSpawner>);
22
23impl Connection {
24    /// Constructor.
25    pub fn new(ws: WebSocket) -> Self {
26        let (ws_sink, ws_stream) = ws.split();
27        let ws_sink = ws_sink
28            .sink_map_err(Error::send)
29            .with(|msg| async { Ok(Message::Bytes(msg)) });
30        let ws_stream = ws_stream.map_err(Error::receive).map(|msg| match msg? {
31            Message::Text(_) => Err(Error::receive("Text messages are unsupported")),
32            Message::Bytes(message) => Ok(message),
33        });
34
35        Self(arpy_client::websocket::Connection::new(
36            LocalSpawner,
37            ws_sink,
38            ws_stream,
39        ))
40    }
41
42    pub async fn close(self) {
43        self.0.close().await
44    }
45}
46
47#[async_trait(?Send)]
48impl ConcurrentRpcClient for Connection {
49    type Call<Output: DeserializeOwned> = Call<Output>;
50    type Error = Error;
51    type SubscriptionStream<Item: DeserializeOwned> = SubscriptionStream<Item>;
52
53    async fn begin_call<F>(&self, function: F) -> Result<Self::Call<F::Output>, Self::Error>
54    where
55        F: FnRemote,
56    {
57        self.0.begin_call(function).await
58    }
59
60    async fn subscribe<S>(
61        &self,
62        service: S,
63        updates: impl Stream<Item = S::Update> + 'static,
64    ) -> Result<(S::InitialReply, SubscriptionStream<S::Item>), Error>
65    where
66        S: FnSubscription + 'static,
67    {
68        self.0.subscribe(service, updates).await
69    }
70}
71
72#[async_trait(?Send)]
73impl RpcClient for Connection {
74    type Error = Error;
75
76    async fn call<Args>(&self, args: Args) -> Result<Args::Output, Self::Error>
77    where
78        Args: FnRemote,
79    {
80        self.0.call(args).await
81    }
82}