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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
use std::{
borrow::Cow,
};
use reqwest::{
header::{
AUTHORIZATION, SEC_WEBSOCKET_PROTOCOL,
HeaderValue,
},
};
use tokio_tungstenite::{
tungstenite::{
self,
Message,
protocol::{
frame::coding::CloseCode,
CloseFrame,
},
client::{
IntoClientRequest,
},
},
};
use futures_util::{
SinkExt, StreamExt,
};
use tokio::{
task::{
JoinHandle,
},
sync::{
mpsc::{
self,
error::TryRecvError,
}
},
};
use crate::{
api::{
NotificationEvent,
},
Result, Error, X_BCOT_TIMESTAMP,
error::GenericError,
notification::*,
async_impl::{
client::CatenisClient,
}
};
/// Represents an asynchronous Catenis WebSocket notification channel.
///
/// This is used to receive notifications from the Catenis system, in an asynchronous way.
///
/// An instance of this object should be obtained from an asynchronous [`CatenisClient`](crate::async_impl::CatenisClient)
/// object via its [`new_ws_notify_channel`](crate::async_impl::CatenisClient::new_ws_notify_channel)
/// method.
#[derive(Debug, Clone)]
pub struct WsNotifyChannel{
pub(crate) api_client: CatenisClient,
pub(crate) event: NotificationEvent,
pub(crate) tx: Option<mpsc::Sender<WsNotifyChannelCommand>>,
}
impl WsNotifyChannel {
pub(crate) fn new(api_client: &CatenisClient, event: NotificationEvent) -> Self {
WsNotifyChannel {
api_client: api_client.clone(),
event,
tx: None,
}
}
/// Open the WebSocket notification channel setting up a handler to monitor the activity on
/// that channel.
///
/// # Example
///
/// ```no_run
/// use std::sync::{Arc, Mutex};
/// use catenis_api_client::{
/// async_impl,
/// ClientOptions, Environment, Result,
/// api::NotificationEvent,
/// notification::WsNotifyChannelEvent,
/// };
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let ctn_client = async_impl::CatenisClient::new_with_options(
/// Some((
/// "drc3XdxNtzoucpw9xiRp",
/// concat!(
/// "4c1749c8e86f65e0a73e5fb19f2aa9e74a716bc22d7956bf3072b4bc3fbfe2a0",
/// "d138ad0d4bcfee251e4e5f54d6e92b8fd4eb36958a7aeaeeb51e8d2fcc4552c3"
/// ),
/// ).into()),
/// &[
/// ClientOptions::Environment(Environment::Sandbox),
/// ],
/// )?;
///
/// // Instantiate asynchronous WebSocket notification channel object for New Message Received
/// // notification event
/// let notify_channel = Arc::new(Mutex::new(
/// ctn_client.new_ws_notify_channel(NotificationEvent::NewMsgReceived)
/// ));
/// let notify_channel_2 = notify_channel.clone();
///
/// let notify_task;
///
/// {
/// notify_task = notify_channel.lock().unwrap()
/// // Open WebSocket notification channel and monitor events on it
/// .open(move |event: WsNotifyChannelEvent| {
/// let mut notify_channel = (&*notify_channel_2.lock().unwrap()).clone();
///
/// tokio::spawn(async move {
/// match event {
/// WsNotifyChannelEvent::Error(err) => {
/// println!(
/// "WebSocket notification channel error: {:?}",
/// err
/// );
/// },
/// WsNotifyChannelEvent::Open => {
/// println!("WebSocket notification channel open");
/// },
/// WsNotifyChannelEvent::Close(close_info) => {
/// println!(
/// "WebSocket notification channel closed: {:?}",
/// close_info
/// );
/// },
/// WsNotifyChannelEvent::Notify(notify_msg) => {
/// println!(
/// "Received notification (new message read): {:?}",
/// notify_msg
/// );
/// notify_channel.close().await;
/// },
/// }
/// });
/// }).await?;
/// }
/// # Ok(())
/// # }
/// ```
pub async fn open<F>(&mut self, notify_event_handler: F) -> Result<JoinHandle<()>>
where
F: Fn(WsNotifyChannelEvent) + Send + 'static
{
// Prepare to connect to Catenis WebSocket notification service
// Note: this request is only used to assemble the URL for the notification service
// and generate the required data for authentication with the notification service.
// The actual request used to open a WebSocket connection is created below
// (from this request's URL).
let mut auth_req = self.api_client.get_ws_request(
"notify/ws/:event_name",
Some(&[("event_name", self.event.to_string().as_str())])
)?;
self.api_client.sign_request(&mut auth_req)?;
let ws_notify_auth_msg_json = serde_json::to_string(
&WsNotifyChannelAuthentication {
x_bcot_timestamp: auth_req.headers()
.get(X_BCOT_TIMESTAMP)
.unwrap_or(&HeaderValue::from_static(""))
.to_str()?
.into(),
authorization: auth_req.headers()
.get(AUTHORIZATION)
.unwrap_or(&HeaderValue::from_static(""))
.to_str()?
.into()
}
)?;
// Create request to open WebSocket connection
let mut req = auth_req.url().as_str().into_client_request()?;
// Add HTTP header specifying the expected WebSocket subprotocol
req.headers_mut().insert(SEC_WEBSOCKET_PROTOCOL, HeaderValue::from_static(NOTIFY_WS_PROTOCOL));
// Try to establish WebSocket connection
let (mut ws, _) = tokio_tungstenite::connect_async(req)
.await
.map_err(|err| Error::new_client_error(
Some("Failed to establish WebSocket connection"),
Some(err)
))?;
// Prepare to async task to run WebSocket connection
let (tx, mut rx) = mpsc::channel(128);
// Save communication channel with WebSocket async task
self.tx = Some(tx);
Ok(tokio::spawn(async move {
// Create notification event handler async task
let (h_tx, mut h_rx) = mpsc::channel(1024);
tokio::spawn(async move {
loop {
match h_rx.recv().await {
Some(msg) => {
match msg {
NotifyEventHandlerMessage::Drop => {
// Request to exit async task. So just do it
break;
},
NotifyEventHandlerMessage::NotifyEvent(event) => {
// Call handler passing notification event
notify_event_handler(event);
}
}
},
None => {
// Lost communication with parent async task. End this task
break;
},
}
}
});
// Send authentication message
if let Err(err) = ws.send(Message::Text(ws_notify_auth_msg_json)).await {
let ctn_error = if let tungstenite::error::Error::ConnectionClosed = err {
// WebSocket connection has been closed
Error::new_client_error(
Some("Failed to send WebSocket notification channel authentication message; WebSocket connection closed unexpectedly"),
None::<GenericError>
)
} else {
// Any other error
Error::new_client_error(
Some("Failed to send WebSocket notification channel authentication message"),
Some(err)
)
};
// Send error message to notification event handler async task...
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Error(ctn_error)
)
).await.unwrap_or(());
// and exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
}
loop {
// Receive data from WebSocket connection
match tokio::time::timeout(std::time::Duration::from_millis(500),ws.next()).await {
Ok(next_result) => {
match next_result {
Some(result) => {
match result {
Ok(msg) => {
match msg {
Message::Text(text) => {
// A text message was received
if text == NOTIFY_WS_CHANNEL_OPEN {
// WebSocket notification channel open and ready to send
// notification. Send open message to notification event
// handler async task
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Open
)
).await.unwrap_or(());
} else {
// Parse received message
match serde_json::from_str(text.as_str()) {
Ok(notify_message) => {
// Send notify message to notification event handler
// async task
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Notify(notify_message)
)
).await.unwrap_or(());
},
Err(_) => {
// Unexpected notification message. Force closing of
// WebSocket notification channel reporting error
// condition
if let Err(err) = ws.close(Some(CloseFrame {
code: CloseCode::Library(4000),
reason: Cow::from(format!("Unexpected notification message received: {}", text))
})).await {
if let tungstenite::error::Error::ConnectionClosed = err {
// WebSocket connection has already been closed. Just exit
// current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
} else {
// Any other error. Send error message to notification
// event handler async task...
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Error(
Error::new_client_error(
Some("Failed to close WebSocket connection"),
Some(err)
)
)
)
).await.unwrap_or(());
// and exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
}
}
},
}
}
},
Message::Binary(bin) => {
// A binary message was received. This is unexpected, so
// force closing of WebSocket notification channel reporting
// the error condition
if let Err(err) = ws.close(Some(CloseFrame {
code: CloseCode::Unsupported,
reason: Cow::from(format!("Unexpected binary message received: {}", format_vec_limit(bin, 20)))
})).await {
if let tungstenite::error::Error::ConnectionClosed = err {
// WebSocket connection has already been closed. Just exit
// current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
} else {
// Any other error. Send error message to notification
// event handler async task...
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Error(
Error::new_client_error(
Some("Failed to close WebSocket connection"),
Some(err)
)
)
)
).await.unwrap_or(());
// and exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
}
}
},
Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => (),
Message::Close(close_info) => {
// WebSocket connection is being closed. Send close message
// to notification event handler async task...
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Close(close_info)
)
).await.unwrap_or(());
// and continue precessing normally until receiving confirmation
// (via Error::ConnectionClosed) that WebSocket connection has
// been closed
}
}
},
Err(err) => {
if let tungstenite::error::Error::ConnectionClosed = err {
// WebSocket connection has been closed
} else {
// Any other error. Send error message to notification event
// handler async task
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Error(
Error::new_client_error(
Some("Failed to send WebSocket notification channel authentication message"),
Some(err)
)
)
)
).await.unwrap_or(());
};
// Exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
}
}
},
None => {
// Assume that WebSocket connection has been closed, and
// just exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
},
}
},
Err(_) => {
// Timeout reading data from WebSocket connection. Just
// continue processing
},
}
// Check for command from parent thread
match rx.try_recv() {
Ok(msg) => {
match msg {
WsNotifyChannelCommand::Drop => {
// Exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
},
WsNotifyChannelCommand::Close => {
// Close WebSocket connection
if let Err(err) = ws.close(Some(CloseFrame {
code: CloseCode::Normal,
reason: Cow::from("")
})).await {
if let tungstenite::error::Error::ConnectionClosed = err {
// WebSocket connection has already been closed. Just exit
// current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
} else {
// Any other error. Send error message to notification
// event handler async task...
h_tx.send(
NotifyEventHandlerMessage::NotifyEvent(
WsNotifyChannelEvent::Error(
Error::new_client_error(
Some("Failed to close WebSocket connection"),
Some(err)
)
)
)
).await.unwrap_or(());
// and exit current async task (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
}
}
},
}
},
Err(err) => {
match err {
TryRecvError::Disconnected => {
// Lost communication with main thread. Exit current async task
// (requesting child async task to exit too)
h_tx.send(NotifyEventHandlerMessage::Drop).await.unwrap_or(());
return;
},
TryRecvError::Empty => {
// No data to be received now. Just continue processing
},
}
},
}
}
}))
}
/// Close the WebSocket notification channel.
pub async fn close(&mut self) {
if let Some(tx) = &mut self.tx {
// Send command to notification event handler async task to close
// WebSocket notification channel
tx.send(WsNotifyChannelCommand::Close).await.unwrap_or(());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn it_process_ws_notify_channel_events() {
use std::sync::{Arc, Mutex};
use crate::{
async_impl::CatenisClient,
ClientOptions,
};
let ctn_client = CatenisClient::new_with_options(
Some((
"drc3XdxNtzoucpw9xiRp",
"4c1749c8e86f65e0a73e5fb19f2aa9e74a716bc22d7956bf3072b4bc3fbfe2a0d138ad0d4bcfee251e4e5f54d6e92b8fd4eb36958a7aeaeeb51e8d2fcc4552c3",
).into()),
&[
ClientOptions::Host("localhost:3000"),
ClientOptions::Secure(false),
ClientOptions::UseCompression(false)
],
).unwrap();
// Open WebSocket notification channel closing it after first notify message is received
let notify_channel = Arc::new(Mutex::new(
ctn_client.new_ws_notify_channel(NotificationEvent::NewMsgReceived)
));
let notify_channel_2 = notify_channel.clone();
let notify_task;
{
notify_task = notify_channel.lock().unwrap()
// Note: we need to access a reference of notify_channel inside the notify_event_handler
// closure. That's why we need to wrap it around Arc<Mutex<>> (see above)
.open(move |event: WsNotifyChannelEvent| {
// Note: clone (the dereferenced) notify_channel so it can be moved into
// spawned async task
let mut notify_channel = (&*notify_channel_2.lock().unwrap()).clone();
tokio::spawn(async move {
match event {
WsNotifyChannelEvent::Error(err) => {
println!(">>>>>> WebSocket Notification Channel: Error event: {:?}", err);
},
WsNotifyChannelEvent::Open => {
println!(">>>>>> WebSocket Notification Channel: Open event");
},
WsNotifyChannelEvent::Close(close_info) => {
println!(">>>>>> WebSocket Notification Channel: Close event: {:?}", close_info);
},
WsNotifyChannelEvent::Notify(notify_msg) => {
println!(">>>>>> WebSocket Notification Channel: Notify event: {:?}", notify_msg);
notify_channel.close().await;
},
}
});
}).await.unwrap();
}
// Set up timeout to close WebSocket notification channel if no notify message
// is received within a given period of time
// Note: clone (a new dereferenced reference of) notify_channel so it can be moved
// into spawned thread
let mut notify_channel_3 = (&*notify_channel.clone().lock().unwrap()).clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
notify_channel_3.close().await;
});
// Wait for notification task to end
notify_task.await.unwrap();
}
}