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
#![feature(async_await, specialization)]
#![recursion_limit = "512"]

mod api_client;
pub mod errors;
pub mod models;
mod subscription_client;

pub use crate::api_client::{DeribitAPICallRawResult, DeribitAPICallResult, DeribitAPIClient};
pub use crate::subscription_client::DeribitSubscriptionClient;

use crate::errors::DeribitError;
use crate::models::{Either, HeartbeatMessage, JSONRPCResponse, SubscriptionMessage, WSMessage};
use derive_builder::Builder;
use failure::Fallible;
use futures::channel::{mpsc, oneshot};
use futures::compat::{Future01CompatExt, Sink01CompatExt, Stream01CompatExt};
use futures::{select, FutureExt, SinkExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
use futures01::Stream as Stream01;
use log::warn;
use log::{error, info, trace};
use serde_json::from_str;
use std::collections::HashMap;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::timer::Timeout;
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
use tungstenite::Message;
use url::Url;

type WSStream = WebSocketStream<MaybeTlsStream<TcpStream>>;

pub const WS_URL: &'static str = "wss://www.deribit.com/ws/api/v2";
pub const WS_URL_TESTNET: &'static str = "wss://test.deribit.com/ws/api/v2";

#[derive(Default, Builder, Debug)]
#[builder(setter(into))]
pub struct Deribit {
    #[builder(default)]
    testnet: bool,
    #[builder(default = "10")]
    subscription_buffer_size: usize,
}

impl Deribit {
    pub fn new() -> Deribit {
        DeribitBuilder::default().build().unwrap()
    }

    pub async fn connect(self) -> Fallible<(DeribitAPIClient, DeribitSubscriptionClient)> {
        let ws_url = if self.testnet { WS_URL_TESTNET } else { WS_URL };
        info!("Connecting");
        let (ws, _) = connect_async(Url::parse(ws_url)?).compat().await?;

        let (wstx, wsrx) = ws.split();
        let (stx, srx) = mpsc::channel(self.subscription_buffer_size);
        let (waiter_tx, waiter_rx) = mpsc::channel(10);
        let background = Self::servo(wsrx.compat().err_into(), waiter_rx, stx).map_err(|e| {
            warn!("[Servo] Exiting because of '{}'", e);
        });

        tokio::spawn(background.boxed().compat());

        Ok((
            DeribitAPIClient::new(wstx.sink_compat(), waiter_tx),
            DeribitSubscriptionClient::new(srx),
        ))
    }

    async fn servo(
        ws: impl Stream<Item = Fallible<Message>> + Unpin,
        mut waiter_rx: mpsc::Receiver<(i64, oneshot::Sender<Fallible<JSONRPCResponse>>)>,
        mut stx: mpsc::Sender<Either<SubscriptionMessage, HeartbeatMessage>>,
    ) -> Fallible<()> {
        let mut ws = ws.fuse();
        let mut waiters: HashMap<i64, oneshot::Sender<Fallible<JSONRPCResponse>>> = HashMap::new();

        let mut orphan_messages = HashMap::new();

        let (mut sdropped, mut cdropped) = (false, false);
        while !sdropped && !cdropped {
            select! {
                msg = ws.next() => {
                    trace!("[Servo] Message: {:?}", msg);
                    if sdropped { continue; }
                    let msg = if let Some(msg) = msg { msg } else { Err(DeribitError::WebsocketDisconnected)? };

                    match msg? {
                        Message::Text(msg) => {
                            let resp: WSMessage = match from_str(&msg) {
                                Ok(msg) => msg,
                                Err(e) => {
                                    error!("[Servo] Cannot decode rpc message {:?}", e);
                                    Err(e)?
                                }
                            };

                            match resp {
                                WSMessage::RPC(msg) => {
                                    let id = msg.id;
                                    let waiter = match waiters.remove(&msg.id) {
                                        Some(waiter) => waiter,
                                        None => {
                                            orphan_messages.insert(msg.id, msg);
                                            continue;
                                        }
                                    };

                                    if let Err(msg) = waiter.send(msg.to_result()) {
                                        info!("[Servo] The client for request {} is dropped, response is {:?}", id, msg);
                                    }
                                }
                                WSMessage::Subscription(event) => {
                                    let fut = stx.send(Either::Left(event)).compat();
                                    let fut = Timeout::new(fut, Duration::from_millis(1)).compat();
                                    match fut.await.map_err(|e| e.into_inner()) {
                                        Ok(_) => {}
                                        Err(Some(ref e)) if e.is_disconnected() => sdropped = true,
                                        Err(Some(e)) => { unreachable!("[Servo] futures::mpsc won't complain channel is full") },
                                        Err(None) => { warn!("[Servo] Subscription channel is full") }
                                    }

                                }
                                WSMessage::Heartbeat(event) => {
                                    let fut = stx.send(Either::Right(event)).compat();
                                    let fut = Timeout::new(fut, Duration::from_millis(1)).compat();
                                    match fut.await.map_err(|e| e.into_inner()) {
                                        Ok(_) => {}
                                        Err(Some(ref e)) if e.is_disconnected() => sdropped = true,
                                        Err(Some(e)) => { unreachable!("[Servo] futures::mpsc won't complain channel is full") },
                                        Err(None) => { warn!("[Servo] Subscription channel is full") }
                                    }
                                }
                            };
                        }
                        Message::Ping(_) => {
                            trace!("[Servo] Received Ping");
                        }
                        Message::Pong(_) => {
                            trace!("[Servo] Received Ping");
                        }
                        Message::Binary(_) => {
                            trace!("[Servo] Received Binary");
                        }
                    }
                }
                waiter = waiter_rx.next() => {
                    if let Some((id, waiter)) = waiter {
                        if orphan_messages.contains_key(&id) {
                            info!("[Servo] Message come before waiter");
                            let msg = orphan_messages.remove(&id).unwrap();
                            if let Err(msg) = waiter.send(msg.to_result()) {
                                info!("[Servo] The client for request {} is dropped, response is {:?}", id, msg);
                            }
                        } else {
                            waiters.insert(id, waiter);
                        }
                    } else {
                        cdropped = true;
                        info!("[Servo] API Client dropped");
                    }
                }
            };
        }

        Ok(()) // Exit with all receiver dropped
    }
}