-
Notifications
You must be signed in to change notification settings - Fork 51
/
tungstenite_wss_client.rs
520 lines (480 loc) · 20.9 KB
/
tungstenite_wss_client.rs
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
use crate::api::SlackApiAppsConnectionOpenRequest;
use crate::errors::*;
use crate::listener::SlackClientEventsListenerEnvironment;
use crate::*;
use futures::{SinkExt, StreamExt};
use rvstruct::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::SystemTime;
use tokio::net::TcpStream;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio::sync::RwLock;
use tokio_tungstenite::*;
use tracing::*;
#[derive(Clone)]
pub struct SlackTungsteniteWssClientIdentity {
pub id: SlackSocketModeWssClientId,
pub token: SlackApiToken,
pub client_listener: Arc<dyn SlackSocketModeClientListener + Sync + Send>,
pub config: SlackClientSocketModeConfig,
}
#[derive(Clone)]
pub struct SlackTungsteniteWssClient<SCHC>
where
SCHC: SlackClientHttpConnector + Send + Sync,
{
pub identity: SlackTungsteniteWssClientIdentity,
command_writer: Arc<RwLock<UnboundedSender<SlackTungsteniteWssClientCommand>>>,
command_reader: Arc<RwLock<Option<UnboundedReceiver<SlackTungsteniteWssClientCommand>>>>,
destroyed: Arc<AtomicBool>,
listener_environment: Arc<SlackClientEventsListenerEnvironment<SCHC>>,
}
#[derive(Clone, Debug)]
enum SlackTungsteniteWssClientCommand {
Message(String),
Ping,
Pong(Vec<u8>),
Exit,
}
impl<SCHC> SlackTungsteniteWssClient<SCHC>
where
SCHC: SlackClientHttpConnector + Send + Sync + 'static,
{
pub fn new(
id: SlackSocketModeWssClientId,
client_listener: Arc<dyn SlackSocketModeClientListener + Sync + Send>,
token: &SlackApiToken,
config: &SlackClientSocketModeConfig,
listener_environment: Arc<SlackClientEventsListenerEnvironment<SCHC>>,
) -> Self {
let identity = SlackTungsteniteWssClientIdentity {
id,
client_listener,
token: token.clone(),
config: config.clone(),
};
let (tx, rx): (
UnboundedSender<SlackTungsteniteWssClientCommand>,
UnboundedReceiver<SlackTungsteniteWssClientCommand>,
) = tokio::sync::mpsc::unbounded_channel();
SlackTungsteniteWssClient {
identity,
command_writer: Arc::new(RwLock::new(tx)),
command_reader: Arc::new(RwLock::new(Some(rx))),
destroyed: Arc::new(AtomicBool::new(false)),
listener_environment,
}
}
async fn try_to_connect(
identity: &SlackTungsteniteWssClientIdentity,
listener_environment: Arc<SlackClientEventsListenerEnvironment<SCHC>>,
) -> Option<WebSocketStream<MaybeTlsStream<TcpStream>>> {
let session = listener_environment.client.open_session(&identity.token);
trace!(
"[{}] Receiving WSS URL to connect through Slack app.connections.open()",
identity.id.to_string()
);
match session
.apps_connections_open(&SlackApiAppsConnectionOpenRequest::new())
.await
{
Ok(open_connection_res) => {
let open_connection_res_url = if identity.config.debug_connections {
open_connection_res.url.to_debug_url()
} else {
open_connection_res.url
};
trace!(
"[{}] Connecting to: {}",
identity.id.to_string(),
open_connection_res_url.value()
);
let url_to_connect = open_connection_res_url.value().to_string();
match connect_async(&url_to_connect).await {
Ok((_, response))
if !response.status().is_success()
&& !response.status().is_informational() =>
{
error!(
slack_wss_client_id = identity.id.to_string().as_str(),
"[{}] Unable to connect {}: {}",
identity.id.to_string(),
url_to_connect,
response.status()
);
None
}
Err(err) => {
error!(
slack_wss_client_id = identity.id.to_string().as_str(),
"[{}] Unable to connect {}: {:?}",
identity.id.to_string(),
url_to_connect,
err
);
None
}
Ok((wss_stream, _)) => {
debug!(
slack_wss_client_id = identity.id.to_string().as_str(),
"[{}] Connected to {}",
identity.id.to_string(),
url_to_connect
);
Some(wss_stream)
}
}
}
Err(err) => {
error!(
"[{}] Unable to create WSS url: {}",
identity.id.to_string(),
err
);
None
}
}
}
async fn connect_with_reconnections(
identity: &SlackTungsteniteWssClientIdentity,
listener_environment: Arc<SlackClientEventsListenerEnvironment<SCHC>>,
destroyed: Arc<AtomicBool>,
) -> ClientResult<WebSocketStream<MaybeTlsStream<TcpStream>>> {
let mut maybe_stream = Self::try_to_connect(identity, listener_environment.clone()).await;
loop {
if let Some(wss_stream) = maybe_stream {
return Ok(wss_stream);
} else if !destroyed.load(Ordering::Relaxed) {
trace!(
slack_wss_client_id = identity.id.to_string().as_str(),
"[{}] Reconnecting after {} seconds...",
identity.id.to_string(),
identity.config.reconnect_timeout_in_seconds
);
let mut interval = tokio::time::interval(std::time::Duration::from_secs(
identity.config.reconnect_timeout_in_seconds,
));
interval.tick().await;
interval.tick().await;
maybe_stream = Self::try_to_connect(identity, listener_environment.clone()).await;
} else {
return Err(SlackClientError::EndOfStream(
SlackClientEndOfStreamError::new(),
));
}
}
}
async fn connect_spawn(
mut rx: UnboundedReceiver<SlackTungsteniteWssClientCommand>,
tx: UnboundedSender<SlackTungsteniteWssClientCommand>,
identity: SlackTungsteniteWssClientIdentity,
listener_environment: Arc<SlackClientEventsListenerEnvironment<SCHC>>,
destroyed: Arc<AtomicBool>,
initial_wait_timeout: u64,
) -> ClientResult<()> {
if initial_wait_timeout > 0 {
trace!(
slack_wss_client_id = identity.id.to_string().as_str(),
"[{}] Postponed connection for {} seconds (backoff timeout for multiple connections)",
identity.id.to_string(),
initial_wait_timeout
);
let mut interval =
tokio::time::interval(std::time::Duration::from_secs(initial_wait_timeout));
interval.tick().await;
interval.tick().await;
}
let wss_stream =
Self::connect_with_reconnections(&identity, listener_environment, destroyed.clone())
.await?;
let (mut writer, mut reader) = wss_stream.split();
struct PongState {
time: SystemTime,
}
let last_time_pong_received: Arc<RwLock<PongState>> = Arc::new(RwLock::new(PongState {
time: SystemTime::now(),
}));
{
let thread_identity = identity.clone();
let thread_last_time_pong_received = last_time_pong_received.clone();
let thread_destroyed = destroyed.clone();
tokio::spawn(async move {
while let Some(message) = rx.recv().await {
if thread_destroyed.load(Ordering::Relaxed) {
break;
}
match message {
SlackTungsteniteWssClientCommand::Message(body) => {
if writer
.send(tokio_tungstenite::tungstenite::Message::Text(body))
.await
.is_err()
{
rx.close()
}
}
SlackTungsteniteWssClientCommand::Pong(body) => {
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Pong to Slack: {:?}",
thread_identity.id.to_string(),
body
);
if writer
.send(tokio_tungstenite::tungstenite::Message::Pong(body))
.await
.is_err()
{
rx.close()
}
}
SlackTungsteniteWssClientCommand::Ping => {
let body: [u8; 5] = rand::random();
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Ping to Slack: {:?}",
thread_identity.id.to_string(),
body
);
let seen_pong_time_in_secs = {
let last_pong = thread_last_time_pong_received.read().await;
SystemTime::now()
.duration_since(last_pong.time)
.unwrap()
.as_secs()
};
if seen_pong_time_in_secs
> thread_identity.config.ping_interval_in_seconds
* thread_identity.config.ping_failure_threshold_times
{
warn!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Haven't seen any pong from Slack since {} seconds ago",
thread_identity.id.to_string(),
seen_pong_time_in_secs
);
rx.close()
} else if let Err(err) = writer
.send(tokio_tungstenite::tungstenite::Message::Ping(body.to_vec()))
.await
{
warn!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Ping slack failed with: {:?}",
thread_identity.id.to_string(),
err
);
rx.close()
}
}
SlackTungsteniteWssClientCommand::Exit => {
writer.close().await.unwrap_or(());
rx.close();
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] WSS client command channel has been closed",
thread_identity.id.to_string()
);
break;
}
}
}
});
}
{
let thread_identity = identity.clone();
let ping_tx = tx.clone();
let thread_destroyed = destroyed.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(
thread_identity.config.ping_interval_in_seconds,
));
loop {
if thread_destroyed.load(Ordering::Relaxed) {
break;
}
interval.tick().await;
if !ping_tx.is_closed() {
if ping_tx
.send(SlackTungsteniteWssClientCommand::Ping)
.is_err()
{
break;
}
} else {
thread_identity
.client_listener
.on_disconnect(&thread_identity.id)
.await;
break;
}
}
});
}
{
let thread_identity = identity.clone();
let thread_last_time_pong_received = last_time_pong_received;
let thread_destroyed = destroyed.clone();
tokio::spawn(async move {
while let Some(message) = reader.next().await {
if thread_destroyed.load(Ordering::Relaxed) {
break;
}
match message {
Ok(tokio_tungstenite::tungstenite::Message::Text(body)) => {
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Received from Slack: {}",
thread_identity.id.to_string(),
body
);
if let Some(reply) = thread_identity
.client_listener
.on_message(&thread_identity.id, body)
.await
{
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Sending reply to Slack: {:?}",
thread_identity.id.to_string(),
reply
);
tx.send(SlackTungsteniteWssClientCommand::Message(reply))
.unwrap_or(());
}
}
Ok(tokio_tungstenite::tungstenite::Message::Ping(body)) => {
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Ping from Slack: {:?}",
thread_identity.id.to_string(),
body
);
tx.send(SlackTungsteniteWssClientCommand::Pong(body))
.unwrap_or(());
}
Ok(tokio_tungstenite::tungstenite::Message::Pong(body)) => {
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Pong from Slack: {:?}",
thread_identity.id.to_string(),
body
);
let mut last_pong = thread_last_time_pong_received.write().await;
last_pong.time = SystemTime::now();
}
Ok(tokio_tungstenite::tungstenite::Message::Binary(body)) => {
warn!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Unexpected binary received from Slack: {:?}",
thread_identity.id.to_string(),
body
);
thread_identity
.client_listener
.on_error(Box::new(SlackClientError::SocketModeProtocolError(
SlackClientSocketModeProtocolError::new(format!(
"Unexpected binary received from Slack: {body:?}"
)),
)))
.await;
}
Ok(tokio_tungstenite::tungstenite::Message::Close(body)) => {
debug!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Shutting down WSS channel: {:?}",
thread_identity.id.to_string(),
body
);
thread_identity
.client_listener
.on_disconnect(&thread_identity.id)
.await;
break;
}
Ok(tokio_tungstenite::tungstenite::Message::Frame(frame)) => {
trace!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Ignored frame/incomplete message from Slack: {:?}",
thread_identity.id.to_string(),
frame
);
}
Err(err) => {
error!(
slack_wss_client_id = thread_identity.id.to_string().as_str(),
"[{}] Slack WSS error: {:?}",
thread_identity.id.to_string(),
err
);
thread_identity
.client_listener
.on_error(Box::new(SlackClientError::SocketModeProtocolError(
SlackClientSocketModeProtocolError::new(format!(
"Slack WSS error: {err:?}"
)),
)))
.await;
thread_identity
.client_listener
.on_disconnect(&thread_identity.id)
.await;
break;
}
}
}
});
}
Ok(())
}
pub async fn connect(&self, initial_wait_timeout: u64) -> ClientResult<()> {
let maybe_rx = {
let mut rx_writer = self.command_reader.write().await;
rx_writer.take()
};
match maybe_rx {
Some(rx) => {
let tx = {
let tx_writer = self.command_writer.write().await;
(*tx_writer).clone()
};
tokio::spawn(Self::connect_spawn(
rx,
tx,
self.identity.clone(),
self.listener_environment.clone(),
self.destroyed.clone(),
initial_wait_timeout,
));
Ok(())
}
None => Err(SlackClientError::EndOfStream(
SlackClientEndOfStreamError::new(),
)),
}
}
pub async fn shutdown_channel(&mut self) {
debug!(
slack_wss_client_id = self.identity.id.to_string().as_str(),
"[{}] Destroying WSS client",
self.identity.id.to_string()
);
self.destroyed.store(true, Ordering::Relaxed);
let sender = {
let commands_writer = self.command_writer.write().await;
(*commands_writer).clone()
};
sender
.send(SlackTungsteniteWssClientCommand::Exit)
.unwrap_or(());
debug!(
slack_wss_client_id = self.identity.id.to_string().as_str(),
"[{}] WSS client has been destroyed",
self.identity.id.to_string()
);
}
pub async fn start(&self, initial_wait_timeout: u64) {
self.connect(initial_wait_timeout).await.unwrap_or(());
}
}