infotainer 0.0.1-alpha.1

building blocks for simple pubsub services
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use std::time::{Duration, Instant};

use actix::prelude::{Actor, ActorContext, Addr, AsyncContext, Handler, Running, StreamHandler};
use actix_web::{error, web};
use actix_web_actors::ws;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::data_log::LogIndexPut;
use crate::pubsub::ManageSession;
use crate::{
    data_log::{DataLogError, DataLogPull, DataLogPut, DataLogger, LogIndexPull},
    pubsub::{
        Issue, ManageSubscription, PubSubService, Publication, PublicationError, SubmitCommand,
    }
};


/// Represents a message sent by the server to a connected client
#[derive(Debug, Serialize, Deserialize)]
pub enum ServerMessage {
    Issue(Issue),
    LogIndex(LogIndexPut),
    LogEntry(Vec<Publication>),
}

const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);

/// Represents errors caused during client interaction
#[derive(Debug, Fail, PartialEq, Clone, Serialize, Deserialize)]
pub enum ClientError {
    #[fail(display = "Invalid Input: {}", _0)]
    InvalidInput(String),
}

impl From<serde_cbor::Error> for ClientError {
    fn from(e: serde_cbor::Error) -> ClientError {
        ClientError::InvalidInput(format!("{}", e))
    }
}

impl From<uuid::Error> for ClientError {
    fn from(e: uuid::Error) -> ClientError {
        ClientError::InvalidInput(format!("{}", e))
    }
}

/// Start a new WebSocketSession for the requesting client and start the actor.
pub async fn websocket_handler(
    req: web::HttpRequest,
    stream: web::Payload,
    session_id: web::Path<Uuid>,
    pubsub: web::Data<Addr<PubSubService>>,
    datalog: web::Data<Addr<DataLogger>>,
) -> Result<web::HttpResponse, error::Error> {
    let websocket_session = WebSocketSession::new(
        pubsub.get_ref(),
        datalog.get_ref(),
        &session_id,
    );
    ws::start(websocket_session, &req, stream)
}

/// The actor responsible handling client-server communication.
#[derive(Debug, Clone)]
pub struct WebSocketSession {
    id: Uuid,
    hb: Instant,
    pubsub: Addr<PubSubService>,
    datalog: Addr<DataLogger>,
}

impl WebSocketSession {
    fn new(
        pubsub: &Addr<PubSubService>,
        datalog: &Addr<DataLogger>,
        client_id: &Uuid,
    ) -> WebSocketSession {
        WebSocketSession {
            id: *client_id,
            hb: Instant::now(),
            pubsub: pubsub.clone(),
            datalog: datalog.clone(),
        }
    }

    fn beat(&self, ctx: &mut <Self as Actor>::Context) {
        ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
            if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
                warn!("Connection for {} timed out. Closing.", act.id);
                ctx.stop();
                return;
            }
            ctx.ping(b"");
        });
    }
}

impl Actor for WebSocketSession {
    type Context = ws::WebsocketContext<Self>;

    // On start of actor begin monitoring heartbeat and create
    // a session on the `PubSubServer`
    fn started(&mut self, ctx: &mut Self::Context) {
        info!("Starting WebSocketSession for {}", self.id);
        self.beat(ctx);
        if let Err(e) = self.pubsub.try_send(ManageSession::Add {
            client_id: self.id,
            addr: ctx.address(),
        }) {
            error!("{}", e);
            ctx.stop()
        }
    }

    // Unregister with SessionService when stopping the actor
    fn stopping(&mut self, _: &mut Self::Context) -> Running {
        info!("Stopping WebSocketSession for {}", self.id);
        self.pubsub
            .do_send(ManageSession::Remove { client_id: self.id });
        Running::Stop
    }
}

// Handles publication messages sent by the server
impl Handler<Issue> for WebSocketSession {
    type Result = Result<(), PublicationError>;

    fn handle(&mut self, msg: Issue, ctx: &mut Self::Context) -> Self::Result {
        debug!("Received {:?} for {}", msg, self.id);
        let msg = ServerMessage::Issue(msg);
        Ok(ctx.binary(
            serde_cbor::to_vec(&msg).map_err(|e| PublicationError::Publishing(e.to_string()))?,
        ))
    }
}

// Handles log indices sent by the server
impl Handler<LogIndexPut> for WebSocketSession {
    type Result = Result<(), DataLogError>;

    fn handle(&mut self, msg: LogIndexPut, ctx: &mut Self::Context) -> Self::Result {
        let msg = ServerMessage::LogIndex(msg);
        Ok(ctx.binary(serde_cbor::to_vec(&msg).map_err(|e| DataLogError::WriteError(e))?))
    }
}

// Handles DataLogEntries sent by the server
impl Handler<DataLogPut<Publication>> for WebSocketSession {
    type Result = Result<(), DataLogError>;

    fn handle(&mut self, msg: DataLogPut<Publication>, ctx: &mut Self::Context) -> Self::Result {
        let msg = ServerMessage::LogEntry(msg.0);
        Ok(ctx.binary(serde_cbor::to_vec(&msg).map_err(|e| DataLogError::PutDataLogEntry(e))?))
    }
}

// Handles incoming websocket messages sent by clients
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WebSocketSession {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        trace!("Message received: {:#?}", &msg);
        match msg {
            Ok(ws::Message::Text(_)) => {
                self.hb = Instant::now();
                info!("Received Text Message from {}", self.id);
                ctx.text(format!("Text messages not implemented"))
            }
            Ok(ws::Message::Binary(msg)) => {
                self.hb = Instant::now();
                info!("Received Binary Message from {}", self.id);
                match serde_cbor::from_slice::<ClientCommand>(&msg) {
                    Ok(ClientCommand::GetLogEntries { log_id, entries }) => {
                        if let Err(e) = self.datalog.try_send(DataLogPull {
                            client: ctx.address().recipient(),
                            data_log_id: log_id,
                            selection: entries,
                        }) {
                            error!("Error while requesting DataLogEntries");
                            ctx.binary(format!("{}", e));
                        }
                    }
                    Ok(ClientCommand::GetLogIndex { log_id }) => {
                        if let Err(e) = self.datalog.try_send(LogIndexPull {
                            client: ctx.address().recipient(),
                            data_log_id: log_id,
                        }) {
                            error!("Error while requesting DataLogIndex");
                            ctx.binary(format!("{}", e));
                        }
                    }
                    Ok(ClientCommand::SubmitPublication {
                        subscription_id,
                        submission,
                    }) => {
                        if let Err(e) = self.pubsub.try_send(SubmitCommand::new(
                            &self.id,
                            &subscription_id,
                            &submission,
                        )) {
                            error!("Error during publication: {}", e);
                            ctx.binary(format!("{}", e));
                        }
                    }
                    Ok(ClientCommand::Subscribe { subscription_id }) => {
                        if let Err(e) = self.pubsub.try_send(ManageSubscription::Add {
                            client_id: self.id,
                            subscription_id,
                        }) {
                            error!("Error while attempting to subscribe client to subscription");
                            ctx.binary(format!("{}", e))
                        }
                    }
                    Ok(ClientCommand::Unsubscribe { subscription_id }) => {
                        if let Err(e) = self.pubsub.try_send(ManageSubscription::Remove {
                            client_id: self.id,
                            subscription_id,
                        }) {
                            error!(
                                "Error while attempting to unsubscribe client from subscription"
                            );
                            ctx.binary(format!("{}", e))
                        }
                    }
                    Err(e) => {
                        error!("{}", &e);
                        ctx.binary(format!("{}", &e))
                    }
                };
            }
            Ok(ws::Message::Ping(msg)) => {
                self.hb = Instant::now();
                ctx.pong(&msg);
            }
            Ok(ws::Message::Pong(_)) => {
                self.hb = Instant::now();
            }
            Ok(ws::Message::Close(reason)) => {
                info!("Received CLOSE from client.");
                ctx.close(reason);
                ctx.stop();
            }
            _ => {
                info!("Unable to handle message");
                ctx.stop()
            }
        }
    }
}

/// Represents a message from a client sent to the websocket.
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub enum ClientCommand {
    /// Retrieve a Subscriptions log index
    GetLogIndex { log_id: Uuid },
    /// Fetch one or more entries from the datalog
    GetLogEntries { log_id: Uuid, entries: Vec<Uuid> },
    /// Add client to a Subscription, creating it it if doesn't exist
    Subscribe { subscription_id: Uuid },
    /// Remove client from a Subscription, deleting it, if client was last subscriber
    Unsubscribe { subscription_id: Uuid },
    /// Submit new data for publication
    SubmitPublication {
        subscription_id: Uuid,
        submission: Vec<u8>,
    },
}

#[cfg(test)]
pub mod tests {
    use super::*;

    use std::collections::HashSet;
    use std::convert::TryInto;
    use std::env::temp_dir;
    use std::path::{Path, PathBuf};
    use std::str::FromStr;

    use actix_web::{test, web, App};
    use futures_util::{sink::SinkExt, stream::StreamExt};

    use crate::data_log::DataLogger;

    fn create_test_directory() -> PathBuf {
        let mut p = temp_dir();
        p.push(format!("infotainer-{}", Uuid::new_v4().to_hyphenated()));
        std::fs::create_dir(&p).unwrap();
        p
    }

    fn remove_test_directory(p: &Path) {
        std::fs::remove_dir_all(p).unwrap();
    }

    #[actix_rt::test]
    async fn test_websocket_pubsub_datalog_integration() {
        let test_dir = create_test_directory();
        let data_log = DataLogger::new(&test_dir).unwrap().start();
        let pubsub_server = PubSubService::new(&data_log).start();
        let session_id = Uuid::new_v4();
        let subscription_id = Uuid::new_v4();
        let test_data_text = "Milton Beats <Giver of Beatings>";
        let mut srv = test::start(move || {
            App::new()
                .data(pubsub_server.clone())
                .data(data_log.clone())
                .route("/{session_id}", web::get().to(websocket_handler))
        });
        let mut conn = srv
            .ws_at(&format!("/{}", session_id))
            .await
            .expect("Could not start ws connection");
        assert!(&conn.is_write_ready());
        let sub_message = ClientCommand::Subscribe {
            subscription_id: subscription_id,
        };
        &conn
            .send(ws::Message::Binary(
                serde_cbor::to_vec(&sub_message)
                    .unwrap()
                    .try_into()
                    .unwrap(),
            ))
            .await
            .unwrap();
        let pub_message = ClientCommand::SubmitPublication {
            subscription_id: subscription_id,
            submission: test_data_text.into(),
        };
        &conn
            .send(ws::Message::Binary(
                serde_cbor::to_vec(&pub_message)
                    .unwrap()
                    .try_into()
                    .unwrap(),
            ))
            .await
            .unwrap();
        let issue_server_message = match conn.next().await.unwrap().unwrap() {
            ws::Frame::Binary(a) => serde_cbor::from_slice::<ServerMessage>(&a[..]).unwrap(),
            _ => panic!("Could not parse response"),
        };
        let published_issue = match issue_server_message {
            ServerMessage::Issue(i) => {
                assert_eq!(i.0, subscription_id);
                i
            }
            _ => panic!("Received unexpected response: {:?}", issue_server_message),
        };
        let log_message = ClientCommand::GetLogIndex {
            log_id: subscription_id,
        };
        &conn
            .send(ws::Message::Binary(
                serde_cbor::to_vec(&log_message)
                    .unwrap()
                    .try_into()
                    .unwrap(),
            ))
            .await
            .unwrap();
        let mut log_response = HashSet::new();
        match conn.next().await.unwrap().unwrap() {
            ws::Frame::Binary(a) => {
                match serde_cbor::from_slice::<ServerMessage>(&a[..]).unwrap() {
                    ServerMessage::LogIndex(i) => log_response = i.1,
                    _ => panic!("Received invalid response from server"),
                }
            }
            _ => (),
        };
        assert!(!&log_response.is_empty());
        assert!(&log_response.contains(&published_issue.1));
        let entry_message = ClientCommand::GetLogEntries {
            log_id: subscription_id,
            entries: log_response.drain().collect(),
        };
        &conn
            .send(ws::Message::Binary(
                serde_cbor::to_vec(&entry_message)
                    .unwrap()
                    .try_into()
                    .unwrap(),
            ))
            .await
            .unwrap();
        let entry_response = match conn.next().await.unwrap().unwrap() {
            ws::Frame::Binary(a) => serde_cbor::from_slice::<ServerMessage>(&a[..]).unwrap(),
            _ => panic!("Received invalid server response"),
        };
        let data_log_entry = match entry_response {
            ServerMessage::LogEntry(e) => e[0].clone(),
            _ => panic!("Unexpected server message"),
        };
        assert_eq!(
            String::from_utf8(data_log_entry.data).unwrap(),
            test_data_text
        );
        let unsub_message = ClientCommand::Unsubscribe {
            subscription_id: subscription_id,
        };
        &conn
            .send(ws::Message::Binary(
                serde_cbor::to_vec(&unsub_message)
                    .unwrap()
                    .try_into()
                    .unwrap(),
            ))
            .await
            .unwrap();
        let unsub_response = match conn.next().await.unwrap().unwrap() {
            ws::Frame::Binary(a) => Some(serde_cbor::from_slice::<String>(&a[..]).unwrap()),
            _ => None,
        };
        assert_eq!(unsub_response, None);
        remove_test_directory(&test_dir);
    }

    #[test]
    fn test_client_error() {
        let err = ClientError::InvalidInput(String::from("Test"));
        let err_display = format!("{}", err);
        assert_eq!("Invalid Input: Test", &err_display);
    }

    #[test]
    fn test_wrapping_cbor_errors() {
        if let Err(e) = serde_cbor::from_slice::<String>(&[23]) {
            let err = ClientError::from(e);
            assert_eq!(
                "Invalid Input: invalid type: integer `23`, expected a string",
                format!("{}", err)
            )
        }
    }

    #[test]
    fn test_wrapping_uuid_errors() {
        if let Err(e) = Uuid::from_str("notauuidstring") {
            let err = ClientError::from(e);
            assert_eq!(
                "Invalid Input: invalid length: expected one of [36, 32], found 14",
                format!("{}", err)
            )
        }
    }
}