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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use super::{
    super::{config::ShardConfig, stage::Stage},
    connect, emit,
    error::{Error, Result},
    inflater::Inflater,
    session::Session,
    socket_forwarder::SocketForwarder,
};

use crate::listener::Listeners;
use twilight_model::gateway::{
    event::{
        shard::{Connected, Connecting, Disconnected, Identifying, Reconnecting, Resuming},
        DispatchEvent, Event, GatewayEvent,
    },
    payload::{
        identify::{Identify, IdentifyInfo, IdentifyProperties},
        resume::Resume,
    },
};

use async_tungstenite::tungstenite::{
    protocol::{frame::coding::CloseCode, CloseFrame},
    Message,
};
use futures_channel::mpsc::UnboundedReceiver;
use futures_util::stream::StreamExt;
use serde::Serialize;
use std::{env::consts::OS, ops::Deref, str, sync::Arc};
use tokio::sync::watch::{
    channel as watch_channel, Receiver as WatchReceiver, Sender as WatchSender,
};
#[allow(unused_imports)]
use tracing::{debug, info, trace, warn};

use std::borrow::Cow;

#[cfg(feature = "metrics")]
use metrics::counter;

use std::error::Error as StdError;
use std::sync::atomic::Ordering;

/// Runs in the background and processes incoming events, and then broadcasts
/// to all listeners.
#[derive(Debug)]
pub struct ShardProcessor {
    pub config: Arc<ShardConfig>,
    pub listeners: Listeners<Event>,
    pub properties: IdentifyProperties,
    pub rx: UnboundedReceiver<Message>,
    pub session: Arc<Session>,
    inflater: Inflater,
    url: String,
    resume: Option<(u64, String)>,
    wtx: WatchSender<Arc<Session>>,
}

impl ShardProcessor {
    pub async fn new(
        config: Arc<ShardConfig>,
        mut url: String,
        listeners: Listeners<Event>,
    ) -> Result<(Self, WatchReceiver<Arc<Session>>)> {
        //if we got resume info we don't need to wait
        let shard_id = config.shard();
        let resumable = config.sequence.is_some() && config.session_id.is_some();
        if !resumable {
            debug!("Shard {:?} is not resumable", shard_id);
            debug!("[ShardProcessor {:?}] Queueing", shard_id);
            config.queue.request(shard_id).await;
            debug!("[ShardProcessor {:?}] Finished queue", config.shard());
        }

        let properties = IdentifyProperties::new("twilight.rs", "twilight.rs", OS, "", "");

        url.push_str("?v=6&compress=zlib-stream");

        emit::event(
            &listeners,
            Event::ShardConnecting(Connecting {
                gateway: url.clone(),
                shard_id: config.shard()[0],
            }),
        );
        let stream = connect::connect(&url).await?;
        let (forwarder, rx, tx) = SocketForwarder::new(stream);
        tokio::spawn(async move {
            forwarder.run().await;
        });

        let session = Arc::new(Session::new(tx));
        if resumable {
            session
                .id
                .lock()
                .await
                .replace(config.session_id.clone().unwrap());
            session
                .seq
                .store(config.sequence.unwrap(), Ordering::Relaxed)
        }

        let (wtx, wrx) = watch_channel(Arc::clone(&session));

        let mut processor = Self {
            config,
            listeners,
            properties,
            rx,
            session,
            inflater: Inflater::new(shard_id),
            url,
            resume: None,
            wtx,
        };

        if resumable {
            debug!("Shard {:?} resuming", shard_id);
            processor.resume().await?;
        }

        Ok((processor, wrx))
    }

    pub async fn run(mut self) {
        loop {
            let gateway_event = match self.next_event().await {
                Ok(ev) => ev,
                // The authorization is invalid, so we should just quit.
                Err(Error::AuthorizationInvalid { shard_id, .. }) => {
                    warn!(
                        "The authorization for shard {} is invalid, quitting",
                        shard_id
                    );
                    self.listeners.remove_all();

                    return;
                }
                // Reconnect as this error is often fatal!
                Err(Error::Decompressing { source }) => {
                    warn!(
                        "[gateway] Decompressing error, clears buffers and reconnect! {:?}",
                        source
                    );

                    // Inflater gets reset in the reconnect call.
                    self.reconnect(true).await;
                    continue;
                }
                Err(Error::IntentsDisallowed { shard_id, .. }) => {
                    warn!(
                        "At least one of the provided intents for shard {} are disallowed",
                        shard_id
                    );
                    self.listeners.remove_all();
                    return;
                }
                Err(Error::IntentsInvalid { shard_id, .. }) => {
                    warn!(
                        "At least one of the provided intents for shard {} are invalid",
                        shard_id
                    );
                    self.listeners.remove_all();
                    return;
                }
                Err(err) => {
                    warn!("Error receiving gateway event: {:?}", err.source());
                    continue;
                }
            };

            // The only reason for an error is if the sender couldn't send a
            // message or if the session didn't exist when it should, so do a
            // reconnect if this fails.
            if self.process(&gateway_event).await.is_err() {
                debug!("Error processing event; reconnecting");

                self.reconnect(true).await;

                continue;
            }

            emit::event(&self.listeners, Event::from(gateway_event));
        }
    }

    /// Identifies with the gateway to create a new session.
    async fn identify(&mut self) -> Result<()> {
        self.session.set_stage(Stage::Identifying);

        let intents = self.config.intents().copied();

        let identify = Identify::new(IdentifyInfo {
            compression: false,
            intents,
            large_threshold: 250,
            properties: self.properties.clone(),
            shard: Some(self.config.shard()),
            presence: self.config.presence().cloned(),
            token: self.config.token().to_owned(),
            v: 6,
        });
        emit::event(
            &self.listeners,
            Event::ShardIdentifying(Identifying {
                shard_id: self.config.shard()[0],
                shard_total: self.config.shard()[1],
            }),
        );

        self.send(identify).await
    }

    async fn process(&mut self, event: &GatewayEvent) -> Result<()> {
        use GatewayEvent::{
            Dispatch, Heartbeat, HeartbeatAck, Hello, InvalidateSession, Reconnect,
        };

        match event {
            Dispatch(seq, dispatch) => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "Dispatch");
                self.session.set_seq(*seq);

                // this lint is wrong and generates invalid code
                #[allow(clippy::explicit_deref_methods)]
                match dispatch.deref() {
                    DispatchEvent::Ready(ready) => {
                        self.session.set_stage(Stage::Connected);
                        self.session.set_id(&ready.session_id).await;

                        emit::event(
                            &self.listeners,
                            Event::ShardConnected(Connected {
                                heartbeat_interval: self.session.heartbeat_interval(),
                                shard_id: self.config.shard()[0],
                            }),
                        );
                    }
                    DispatchEvent::Resumed => {
                        self.session.set_stage(Stage::Connected);
                        emit::event(
                            &self.listeners,
                            Event::ShardConnected(Connected {
                                heartbeat_interval: self.session.heartbeat_interval(),
                                shard_id: self.config.shard()[0],
                            }),
                        );
                        self.session.heartbeats.receive().await;
                    }
                    _ => {}
                }
            }
            Heartbeat(seq) => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "Heartbeat");
                if *seq > self.session.seq() + 1 {
                    self.resume().await?;
                }

                if let Err(err) = self.session.heartbeat() {
                    warn!("Error sending heartbeat; reconnecting: {}", err);

                    self.reconnect(true).await;
                }
            }
            Hello(interval) => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "Hello");
                debug!("[EVENT] Hello({})", interval);

                if self.session.stage() == Stage::Resuming && self.resume.is_some() {
                    // Safe to unwrap so here as we have just checked that
                    // it is some.
                    let (seq, id) = self.resume.take().unwrap();
                    warn!("Resuming with ({}, {})!", seq, id);
                    let payload = Resume::new(seq, &id, self.config.token());

                    // Set id so it is correct for next resume.
                    self.session.set_id(id).await;

                    if *interval > 0 {
                        self.session.set_heartbeat_interval(*interval);
                        self.session.start_heartbeater().await;
                    }

                    self.send(payload).await?;
                } else {
                    self.session.set_stage(Stage::Identifying);

                    if *interval > 0 {
                        self.session.set_heartbeat_interval(*interval);
                        self.session.start_heartbeater().await;
                    }

                    self.identify().await?;
                }
            }
            HeartbeatAck => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "HeartbeatAck");
                self.session.heartbeats.receive().await;
            }
            InvalidateSession(true) => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "InvalidateSessionTrue");
                debug!("[EVENT] InvalidateSession(true)");
                self.resume().await?;
            }
            InvalidateSession(false) => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "InvalidateSessionFalse");
                debug!("[EVENT] InvalidateSession(false)");
                self.reconnect(true).await;
            }
            Reconnect => {
                #[cfg(feature = "metrics")]
                counter!("GatewayEvent", 1, "GatewayEvent" => "Reconnect");
                debug!("[EVENT] Reconnect");
                let frame = CloseFrame {
                    code: CloseCode::Restart,
                    reason: Cow::Borrowed("Reconnecting"),
                };
                self.close(Some(frame)).await?;
                self.resume().await?;
            }
        }

        Ok(())
    }

    async fn reconnect(&mut self, full_reconnect: bool) {
        info!("[reconnect] Reconnection started!");
        loop {
            // Await allowance if doing a full reconnect
            if full_reconnect {
                let shard = self.config.shard();
                self.config.queue.request(shard).await;
            }

            if full_reconnect {
                emit::event(
                    &self.listeners,
                    Event::ShardReconnecting(Reconnecting {
                        shard_id: self.config.shard()[0],
                    }),
                );
            } else {
                emit::event(
                    &self.listeners,
                    Event::ShardResuming(Resuming {
                        seq: self.session.seq(),
                        shard_id: self.config.shard()[0],
                    }),
                );
            }

            let new_stream = match connect::connect(&self.url).await {
                Ok(s) => s,
                Err(why) => {
                    warn!("Error reconnecting: {:?}", why);
                    continue;
                }
            };

            let (new_forwarder, new_rx, new_tx) = SocketForwarder::new(new_stream);
            tokio::spawn(async move {
                new_forwarder.run().await;
            });

            self.rx = new_rx;
            self.session = Arc::new(Session::new(new_tx));
            match self.wtx.broadcast(Arc::clone(&self.session)) {
                Ok(_) => (),
                Err(why) => {
                    warn!(
                        "Broadcast of new session failed, \
                         This should not happen, please open \
                         a issue on the repo. {}",
                        why
                    );
                    warn!(
                        "After this many of the commands on the \
                         shard will no longer work."
                    );
                }
            };

            if !full_reconnect {
                self.session.set_stage(Stage::Resuming);
            }

            self.inflater.reset();

            break;
        }

        emit::event(
            &self.listeners,
            Event::ShardConnecting(Connecting {
                gateway: self.url.clone(),
                shard_id: self.config.shard()[0],
            }),
        );
    }

    async fn resume(&mut self) -> Result<()> {
        info!("[resume] Resume started!");
        self.session.set_stage(Stage::Resuming);
        self.session.stop_heartbeater().await;

        let seq = self.session.seq();

        let id = if let Some(id) = self.session.id().await {
            id
        } else {
            warn!("Was not able to get the id, reconnecting.");
            self.reconnect(true).await;
            return Ok(());
        };

        self.resume = Some((seq, id));

        self.reconnect(false).await;

        Ok(())
    }

    pub async fn send(&mut self, payload: impl Serialize) -> Result<()> {
        match self.session.send(payload) {
            Ok(()) => Ok(()),
            Err(Error::PayloadSerialization { source }) => {
                warn!("Failed to serialize message to send: {:?}", source);

                Err(Error::PayloadSerialization { source })
            }
            Err(Error::SendingMessage { source }) => {
                warn!("Failed to send message: {:?}", source);
                info!("Reconnecting");

                self.reconnect(true).await;

                Ok(())
            }
            Err(other) => Err(other),
        }
    }

    async fn close(&mut self, close_frame: Option<CloseFrame<'static>>) -> Result<()> {
        self.session.close(close_frame)?;
        Ok(())
    }

    /// # Errors
    ///
    /// Returns [`Error::AuthorizationInvalid`] if the provided authorization
    /// is invalid.
    ///
    /// [`Error::AuthorizationInvalid`]: ../../error/enum.Error.html#variant.AuthorizationInvalid
    #[allow(unsafe_code)]
    async fn next_event(&mut self) -> Result<GatewayEvent> {
        loop {
            // Returns None when the socket forwarder has ended, meaning the
            // connection was dropped.
            let msg = if let Some(msg) = self.rx.next().await {
                msg
            } else {
                if let Err(why) = self.resume().await {
                    warn!("Resume failed with {}, reconnecting", why);
                    self.reconnect(true).await;
                }
                continue;
            };

            match msg {
                Message::Binary(bin) => {
                    self.inflater.extend(&bin[..]);
                    let decompressed_msg = self
                        .inflater
                        .msg()
                        .map_err(|source| Error::Decompressing { source })?;
                    let msg_or_error = match decompressed_msg {
                        Some(json) => {
                            emit::bytes(self.listeners.clone(), json).await;

                            let mut text = str::from_utf8_mut(json)
                                .map_err(|source| Error::PayloadNotUtf8 { source })?;

                            // Safety: the buffer isn't used again after parsing.
                            unsafe { Self::parse_gateway_event(&mut text) }
                        }
                        None => continue,
                    };
                    self.inflater.clear();
                    break msg_or_error;
                }
                Message::Close(close_frame) => {
                    tracing::warn!("Got close code: {:?}.", close_frame);
                    emit::event(
                        &self.listeners,
                        Event::ShardDisconnected(Disconnected {
                            code: close_frame.as_ref().map(|frame| frame.code.into()),
                            reason: close_frame
                                .as_ref()
                                .map(|frame| frame.reason.clone().into()),
                            shard_id: self.config.shard()[0],
                        }),
                    );

                    if let Some(close_frame) = close_frame {
                        match close_frame.code {
                            CloseCode::Library(4004) => {
                                return Err(Error::AuthorizationInvalid {
                                    shard_id: self.config.shard()[0],
                                    token: self.config.token().to_owned(),
                                });
                            }
                            CloseCode::Library(4013) => {
                                return Err(Error::IntentsInvalid {
                                    intents: self.config.intents().copied(),
                                    shard_id: self.config.shard()[0],
                                });
                            }
                            CloseCode::Library(4014) => {
                                return Err(Error::IntentsDisallowed {
                                    intents: self.config.intents().copied(),
                                    shard_id: self.config.shard()[0],
                                });
                            }
                            _ => {}
                        }
                    }

                    self.resume().await?;
                }
                Message::Ping(_) | Message::Pong(_) => {}
                Message::Text(mut text) => {
                    trace!("Text payload: {}", text);

                    emit::bytes(self.listeners.clone(), text.as_bytes()).await;

                    // Safety: the buffer isn't used again after parsing.
                    break unsafe { Self::parse_gateway_event(&mut text) };
                }
            }
        }
    }

    /// Parse a gateway event from a string using `serde_json`.
    ///
    /// # Safety
    ///
    /// This function is actually safe, though it is marked unsafe to have a
    /// compatible signature with the simd-json variant of this function.
    ///
    /// # Errors
    ///
    /// Returns [`Error::PayloadInvalid`] if the payload wasn't a valid
    /// `GatewayEvent` data structure.
    ///
    /// Returns [`Error::PayloadSerialization`] if the payload failed to
    /// deserialize.
    ///
    /// [`Error::PayloadInvalid`]: ../enum.Error.html#variant.PayloadInvalid
    /// [`Error::PayloadSerialization`]: ../enum.Error.html#variant.PayloadSerialization
    #[allow(unsafe_code)]
    #[cfg(all(feature = "serde_json", not(feature = "simd-json")))]
    unsafe fn parse_gateway_event(json: &mut str) -> Result<GatewayEvent> {
        use serde::de::DeserializeSeed;
        use serde_json::Deserializer;
        use twilight_model::gateway::event::GatewayEventDeserializer;

        let gateway_deserializer =
            GatewayEventDeserializer::from_json(json).ok_or_else(|| Error::PayloadInvalid)?;
        let mut json_deserializer = Deserializer::from_str(json);

        gateway_deserializer
            .deserialize(&mut json_deserializer)
            .map_err(|source| {
                tracing::debug!("Broken JSON: {}", json);

                Error::PayloadSerialization { source }
            })
    }

    /// Parse a gateway event from a string using `simd-json`.
    ///
    /// # Safety
    ///
    /// This is unsafe because it calls `std::str::as_bytes_mut`. The provided
    /// string must not be used again because the value may be changed in ways
    /// that aren't UTF-8 valid.
    ///
    /// # Errors
    ///
    /// Returns [`Error::PayloadInvalid`] if the payload wasn't a valid
    /// `GatewayEvent` data structure.
    ///
    /// Returns [`Error::PayloadSerialization`] if the payload failed to
    /// deserialize.
    ///
    /// [`Error::PayloadInvalid`]: ../enum.Error.html#variant.PayloadInvalid
    /// [`Error::PayloadSerialization`]: ../enum.Error.html#variant.PayloadSerialization
    #[allow(unsafe_code)]
    #[cfg(feature = "simd-json")]
    unsafe fn parse_gateway_event(json: &mut str) -> Result<GatewayEvent> {
        use serde::de::DeserializeSeed;
        use simd_json::Deserializer;
        use twilight_model::gateway::event::gateway::GatewayEventDeserializerOwned;

        let gateway_deserializer =
            GatewayEventDeserializerOwned::from_json(json).map_err(|_| Error::PayloadInvalid)?;
        let mut json_deserializer = Deserializer::from_slice(unsafe { json.as_bytes_mut() })
            .map_err(|_| Error::PayloadInvalid)?;

        gateway_deserializer
            .deserialize(&mut json_deserializer)
            .map_err(|source| {
                tracing::debug!("Broken JSON: {}", json);

                Error::PayloadSerialization { source }
            })
    }
}