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
use crate::backoff::{millis_sleep, Backoff};
use crate::worker::{Context, InnerMessage, WsInfo, WsPayload};
use anyhow::{Error, Result};
use async_channel::{unbounded, Receiver, Sender};
use futures_util::{SinkExt, StreamExt};
use serde::Serialize;
use serde_json::{to_value, Value};
use slog::{debug, error, info, warn};
use std::time::{Duration, Instant};
use tokio::io;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message, WebSocketStream};

/// Websocket consumer
///
/// Listen for new messages from websocket and write new commands into it
#[derive(Clone)]
pub struct WsConsumer {
    pub context: Context<InnerMessage>,
    pub sender: Sender<Value>,
    receiver: Receiver<Value>,
    heartbeat_sender: Sender<()>,
    heartbeat_receiver: Receiver<()>,
    heartbeat: Duration,
    ws_url: String,
}

impl WsConsumer {
    /// Create a new websocket consumer
    pub fn new(context: &Context<InnerMessage>, ws_url: &str) -> Self {
        let (sender, receiver) = unbounded();
        let (heartbeat_sender, heartbeat_receiver) = unbounded();
        let heartbeat_millis: u64 = context
            .get_or("websocket_heartbeat", 5000)
            .expect("websocket heartbeat");
        WsConsumer {
            context: context.clone(),
            sender,
            receiver,
            heartbeat_sender,
            heartbeat_receiver,
            ws_url: ws_url.to_string(),
            heartbeat: Duration::from_millis(heartbeat_millis),
        }
    }

    pub fn info(&self) -> WsInfo {
        WsInfo {
            name: self.context.name.clone(),
            url: self.ws_url.clone(),
        }
    }

    /// schedule a write into the websocket
    pub fn write<T: Serialize>(&self, message: T) {
        self.sender.try_send(to_value(message).unwrap()).unwrap();
    }

    fn payload(&self, value: Value) -> WsPayload {
        WsPayload {
            name: self.context.name.clone(),
            url: self.ws_url.clone(),
            value,
        }
    }

    pub fn get_url(&self) -> &str {
        &self.ws_url
    }

    fn create_ws_request(&self) -> &str {
        &self.ws_url
    }

    // coroutine for consuming and writing messages into a websocket
    pub async fn run(&self) -> Result<()> {
        let mut backoff = Backoff::new(10, 1, 20, 2);
        let logger = self.context.logger.clone();

        // heartbeat to check health of connection
        let heartbeat_sender = self.heartbeat_sender.clone();
        let heartbeat = self.heartbeat;
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(heartbeat).await;
                heartbeat_sender.send(()).await.unwrap();
            }
        });

        // main loop with backoff-reconnection
        loop {
            match backoff.next() {
                Some(delay) => {
                    if delay > 0 {
                        info!(
                            logger,
                            "attempt {} to reconnect to websocket in {} seconds",
                            backoff.count(),
                            delay
                        );
                        millis_sleep(1000 * delay as u64).await;
                    }
                }
                None => {
                    return Err(Error::msg(format!(
                        "failed to reconnect to websocket after {} attempts",
                        backoff.count()
                    )));
                }
            }

            info!(logger, "connecting with websocket {}", &self.ws_url);
            let ws_stream = match connect_async(self.create_ws_request()).await {
                Ok((ws_stream, _)) => {
                    warn!(logger, "connected with websocket {}", &self.ws_url);
                    backoff.reset();
                    ws_stream
                }
                Err(err) => {
                    warn!(
                        logger,
                        "failed to connect with websocket {}: {}", &self.ws_url, err
                    );
                    continue;
                }
            };

            self.stream(ws_stream).await.unwrap_or_else(|err| {
                error!(logger, "{}", err);
            });

            self.context
                .send(InnerMessage::WsDisconnected(self.info()))
                .await;
        }
    }

    async fn stream<S>(&self, mut ws_stream: WebSocketStream<S>) -> Result<()>
    where
        S: io::AsyncRead + io::AsyncWrite + Unpin,
    {
        let logger = &self.context.logger;
        let url = &self.ws_url;
        let mut last_frame_instant = Instant::now();
        let mut num_messages_since_last_heartbeat = 0;
        // send connected message to the main application
        self.context
            .send(InnerMessage::WsConnected(self.info()))
            .await;
        loop {
            tokio::select! {
                // Handle stream of messages from exchange
                Some(frame) = ws_stream.next() => {
                    last_frame_instant = Instant::now();
                    num_messages_since_last_heartbeat += 1;
                    match frame {
                        Ok(Message::Text(ref text)) => {
                            let value: Value = match serde_json::from_str(text.as_ref()) {
                                Ok(value) => value,
                                Err(err) => {
                                    let mut context = String::from("malformed json message: ");
                                    context.push_str(text);
                                    return Err(Error::new(err).context(context));
                                }
                            };
                            // send websocket message to the main task
                            self.context.send(InnerMessage::WsPayload(self.payload(value))).await;
                        }
                        Ok(Message::Close(_)) =>{
                            warn!(logger, "received a close frame, stop streaming and reconnect");
                            return Ok(());
                        }
                        Ok(Message::Ping(msg)) =>{
                            info!(logger, "send a pong message after receiving a server ping");
                            ws_stream.send(Message::Pong(msg)).await?;
                        }
                        Ok(Message::Pong(_)) =>{
                            info!(logger, "got a pong message from server");
                        }
                        Ok(Message::Binary(_)) =>{
                            warn!(logger, "got a binary message from server - skip it");
                        }
                        Ok(Message::Frame(_)) =>{
                            warn!(logger, "got a raw frame message from server - skip it");
                        }
                        Err(err) => {
                            return Err(Error::msg(format!("error while streaming websocket: {}", err)));
                        }
                    };
                }
                // write new messages
                Ok(message) = self.receiver.recv() => {
                    debug!(logger, "write new message into websocket: {}", message);
                    ws_stream.send(Message::Text(message.to_string())).await?;
                }
                // heartbeat
                Ok(_) = self.heartbeat_receiver.recv() => {
                    if Instant::now() - last_frame_instant > self.heartbeat && num_messages_since_last_heartbeat == 0 {
                        warn!(logger, "{} no messages received since last heartbeat, exit receiving loop and reconnect", self.context.name);
                        return Ok(());
                    } else {
                        debug!(logger, "{} received {} messages since last heartbeat", url, num_messages_since_last_heartbeat);
                        num_messages_since_last_heartbeat = 0;
                    }
                }
            }
        }
    }
}