1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
mod builder;
mod manager;
mod task;
#[cfg(test)]
mod tests;

use std::{
    pin::Pin,
    task::{Context, Poll},
    time::Duration,
};

use futures::{
    channel::{mpsc, oneshot},
    future,
    sink::SinkExt,
    stream::{Stream, StreamExt},
};
use jsonrpc_types::*;

pub use self::builder::WsClientBuilder;
use crate::{
    error::WsClientError,
    transport::{BatchTransport, PubsubTransport, Transport},
};

/// Message that the client can send to the background task.
pub(crate) enum ToBackTaskMessage {
    Request {
        method: String,
        params: Option<Params>,
        /// One-shot channel where to send back the response of the request.
        send_back: oneshot::Sender<Result<Output, WsClientError>>,
    },
    BatchRequest {
        batch: Vec<(String, Option<Params>)>,
        /// One-shot channel where to send back the response of the batch request.
        send_back: oneshot::Sender<Result<Vec<Output>, WsClientError>>,
    },
    Subscribe {
        subscribe_method: String,
        params: Option<Params>,
        /// One-shot channel where to send back the response (subscription id) and a `Receiver`
        /// that will receive subscription notification when we get a response (subscription id)
        /// from the server about the subscription.
        send_back: oneshot::Sender<Result<(Id, mpsc::Receiver<SubscriptionNotification>), WsClientError>>,
    },
    Unsubscribe {
        unsubscribe_method: String,
        subscription_id: Id,
        /// One-shot channel where to send back the response of the unsubscribe request.
        send_back: oneshot::Sender<Result<bool, WsClientError>>,
    },
}

/// WebSocket JSON-RPC client
#[derive(Clone)]
pub struct WsClient {
    to_back: mpsc::Sender<ToBackTaskMessage>,
    /// Request timeout.
    timeout: Option<Duration>,
}

impl WsClient {
    /// Creates a new WebSocket JSON-RPC client.
    pub async fn new(url: impl Into<String>) -> Result<Self, WsClientError> {
        WsClientBuilder::new()
            .build(url)
            .await
            .map_err(WsClientError::WebSocket)
    }

    /// Creates a `WsClientBuilder` to configure a `WsClient`.
    ///
    /// This is the same as `WsClientBuilder::new()`.
    pub fn builder() -> WsClientBuilder {
        WsClientBuilder::new()
    }

    /// Sends a `method call` request to the server.
    async fn send_request(&self, method: impl Into<String>, params: Option<Params>) -> Result<Output, WsClientError> {
        let method = method.into();
        log::debug!("[frontend] Send request: method={}, params={:?}", method, params);

        let (tx, rx) = oneshot::channel();
        self.to_back
            .clone()
            .send(ToBackTaskMessage::Request {
                method,
                params,
                send_back: tx,
            })
            .await
            .map_err(|_| WsClientError::InternalChannel)?;

        let res = if let Some(duration) = self.timeout {
            #[cfg(feature = "ws-async-std")]
            let timeout = async_std::task::sleep(duration);
            #[cfg(feature = "ws-tokio")]
            let timeout = tokio::time::sleep(duration);
            futures::pin_mut!(rx, timeout);
            match future::select(rx, timeout).await {
                future::Either::Left((response, _)) => response,
                future::Either::Right((_, _)) => return Err(WsClientError::RequestTimeout),
            }
        } else {
            rx.await
        };
        match res {
            Ok(Ok(output)) => Ok(output),
            Ok(Err(err)) => Err(err),
            Err(_) => Err(WsClientError::InternalChannel),
        }
    }

    /// Sends a batch of `method call` requests to the server.
    async fn send_request_batch<I, M>(&self, batch: I) -> Result<Vec<Output>, WsClientError>
    where
        I: IntoIterator<Item = (M, Option<Params>)>,
        M: Into<String>,
    {
        let batch = batch
            .into_iter()
            .map(|(method, params)| (method.into(), params))
            .collect::<Vec<_>>();
        log::debug!("[frontend] Send a batch of requests: {:?}", batch);

        let (tx, rx) = oneshot::channel();
        self.to_back
            .clone()
            .send(ToBackTaskMessage::BatchRequest { batch, send_back: tx })
            .await
            .map_err(|_| WsClientError::InternalChannel)?;

        let res = if let Some(duration) = self.timeout {
            #[cfg(feature = "ws-async-std")]
            let timeout = async_std::task::sleep(duration);
            #[cfg(feature = "ws-tokio")]
            let timeout = tokio::time::sleep(duration);
            futures::pin_mut!(rx, timeout);
            match future::select(rx, timeout).await {
                future::Either::Left((response, _)) => response,
                future::Either::Right((_, _)) => return Err(WsClientError::RequestTimeout),
            }
        } else {
            rx.await
        };
        match res {
            Ok(Ok(outputs)) => Ok(outputs),
            Ok(Err(err)) => Err(err),
            Err(_) => Err(WsClientError::InternalChannel),
        }
    }

    /// Sends a subscribe request to the server.
    ///
    /// `subscribe_method` and `params` are used to ask for the subscription towards the server.
    /// `unsubscribe_method` is used to close the subscription.
    async fn send_subscribe(
        &self,
        subscribe_method: impl Into<String>,
        params: Option<Params>,
    ) -> Result<WsSubscription<SubscriptionNotification>, WsClientError> {
        let subscribe_method = subscribe_method.into();
        log::debug!("[frontend] Subscribe: method={}, params={:?}", subscribe_method, params);
        let (tx, rx) = oneshot::channel();
        self.to_back
            .clone()
            .send(ToBackTaskMessage::Subscribe {
                subscribe_method,
                params,
                send_back: tx,
            })
            .await
            .map_err(|_| WsClientError::InternalChannel)?;

        let res = if let Some(duration) = self.timeout {
            #[cfg(feature = "ws-async-std")]
            let timeout = async_std::task::sleep(duration);
            #[cfg(feature = "ws-tokio")]
            let timeout = tokio::time::sleep(duration);
            futures::pin_mut!(rx, timeout);
            match future::select(rx, timeout).await {
                future::Either::Left((response, _)) => response,
                future::Either::Right((_, _)) => return Err(WsClientError::RequestTimeout),
            }
        } else {
            rx.await
        };
        match res {
            Ok(Ok((id, notification_rx))) => Ok(WsSubscription { id, notification_rx }),
            Ok(Err(err)) => Err(err),
            Err(_) => Err(WsClientError::InternalChannel),
        }
    }

    /// Sends an unsubscribe request to the server.
    async fn send_unsubscribe(
        &self,
        unsubscribe_method: impl Into<String>,
        subscription_id: Id,
    ) -> Result<bool, WsClientError> {
        let unsubscribe_method = unsubscribe_method.into();
        log::debug!(
            "[frontend] unsubscribe: method={}, id={:?}",
            unsubscribe_method,
            subscription_id
        );
        let (tx, rx) = oneshot::channel();
        self.to_back
            .clone()
            .send(ToBackTaskMessage::Unsubscribe {
                unsubscribe_method,
                subscription_id,
                send_back: tx,
            })
            .await
            .map_err(|_| WsClientError::InternalChannel)?;

        let res = if let Some(duration) = self.timeout {
            #[cfg(feature = "ws-async-std")]
            let timeout = async_std::task::sleep(duration);
            #[cfg(feature = "ws-tokio")]
            let timeout = tokio::time::sleep(duration);
            futures::pin_mut!(rx, timeout);
            match future::select(rx, timeout).await {
                future::Either::Left((response, _)) => response,
                future::Either::Right((_, _)) => return Err(WsClientError::RequestTimeout),
            }
        } else {
            rx.await
        };

        match res {
            Ok(Ok(res)) => Ok(res),
            Ok(Err(err)) => Err(err),
            Err(_) => Err(WsClientError::InternalChannel),
        }
    }
}

/// Active subscription on a websocket client.
pub struct WsSubscription<Notif> {
    /// Subscription ID.
    pub id: Id,
    /// Channel from which we receive notifications from the server.
    notification_rx: mpsc::Receiver<Notif>,
}

impl<Notif> WsSubscription<Notif> {
    /// Returns the next notification from the websocket stream.
    ///
    /// Ignore any malformed packet.
    pub async fn next(&mut self) -> Option<Notif> {
        self.notification_rx.next().await
    }
}

impl<Notif> Stream for WsSubscription<Notif> {
    type Item = Notif;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        mpsc::Receiver::<Notif>::poll_next(Pin::new(&mut self.notification_rx), cx)
    }
}

#[async_trait::async_trait]
impl Transport for WsClient {
    type Error = WsClientError;

    async fn request<M>(&self, method: M, params: Option<Params>) -> Result<Output, Self::Error>
    where
        M: Into<String> + Send,
    {
        self.send_request(method, params).await
    }
}

#[async_trait::async_trait]
impl BatchTransport for WsClient {
    async fn request_batch<I, M>(&self, batch: I) -> Result<Vec<Output>, <Self as Transport>::Error>
    where
        I: IntoIterator<Item = (M, Option<Params>)> + Send,
        I::IntoIter: Send,
        M: Into<String>,
    {
        self.send_request_batch(batch).await
    }
}

#[async_trait::async_trait]
impl PubsubTransport for WsClient {
    type NotificationStream = WsSubscription<SubscriptionNotification>;

    async fn subscribe<M>(
        &self,
        subscribe_method: M,
        params: Option<Params>,
    ) -> Result<(Id, Self::NotificationStream), <Self as Transport>::Error>
    where
        M: Into<String> + Send,
    {
        let notification_stream = self.send_subscribe(subscribe_method, params).await?;
        Ok((notification_stream.id.clone(), notification_stream))
    }

    async fn unsubscribe<M>(
        &self,
        unsubscribe_method: M,
        subscription_id: Id,
    ) -> Result<bool, <Self as Transport>::Error>
    where
        M: Into<String> + Send,
    {
        self.send_unsubscribe(unsubscribe_method, subscription_id).await
    }
}