#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
use crate::inflater::Inflater;
use crate::{
channel::{MessageChannel, MessageSender},
command::{self, Command},
connection::{self, Connection},
error::{
ProcessError, ProcessErrorType, ReceiveMessageError, ReceiveMessageErrorType, SendError,
SendErrorType,
},
future::{self, NextMessageFuture, NextMessageFutureOutput},
json,
latency::Latency,
ratelimiter::CommandRatelimiter,
session::Session,
Config, Message, ShardId,
};
use futures_util::{SinkExt, StreamExt};
use serde::{de::DeserializeOwned, Deserialize};
#[cfg(any(feature = "rustls-native-roots", feature = "rustls-webpki-roots"))]
use std::io::ErrorKind as IoErrorKind;
use std::{env::consts::OS, str};
use tokio::time::{self, Duration, Instant, Interval, MissedTickBehavior};
#[cfg(any(feature = "rustls-native-roots", feature = "rustls-webpki-roots"))]
use tokio_tungstenite::tungstenite::Error as TungsteniteError;
#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
use tokio_tungstenite::tungstenite::Message as TungsteniteMessage;
use twilight_model::gateway::{
event::{Event, GatewayEventDeserializer},
payload::{
incoming::Hello,
outgoing::{
identify::{IdentifyInfo, IdentifyProperties},
Heartbeat, Identify, Resume,
},
},
CloseCode, CloseFrame, Intents, OpCode,
};
#[derive(Clone, Copy, Debug)]
enum CloseInitiator {
Gateway(Option<u16>),
Shard(u16),
None,
}
impl CloseInitiator {
const fn close_code(self) -> Option<u16> {
match self {
CloseInitiator::Gateway(close_code) => close_code,
CloseInitiator::Shard(close_code) => Some(close_code),
CloseInitiator::None => None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ConnectionStatus {
Connected,
Disconnected {
close_code: Option<u16>,
reconnect_attempts: u8,
},
FatallyClosed {
close_code: CloseCode,
},
Identifying,
Resuming,
}
impl ConnectionStatus {
fn from_close_code(close_code: Option<u16>) -> Self {
match close_code.map(CloseCode::try_from) {
Some(Ok(close_code)) if !close_code.can_reconnect() => {
Self::FatallyClosed { close_code }
}
_ => Self::Disconnected {
close_code,
reconnect_attempts: 0,
},
}
}
pub const fn is_connected(&self) -> bool {
matches!(self, Self::Connected)
}
pub const fn is_disconnected(&self) -> bool {
matches!(self, Self::Disconnected { .. })
}
pub const fn is_fatally_closed(&self) -> bool {
matches!(self, Self::FatallyClosed { .. })
}
pub const fn is_identified(&self) -> bool {
self.is_connected() || self.is_resuming()
}
pub const fn is_identifying(&self) -> bool {
matches!(self, Self::Identifying)
}
pub const fn is_resuming(&self) -> bool {
matches!(self, Self::Resuming)
}
}
#[derive(Deserialize)]
struct MinimalEvent<T> {
#[serde(rename = "d")]
data: T,
}
#[derive(Deserialize)]
struct MinimalReady {
resume_gateway_url: String,
session_id: String,
}
#[derive(Debug)]
pub struct Shard {
config: Config,
connection: Option<Connection>,
heartbeat_interval: Option<Interval>,
heartbeat_interval_event: bool,
id: ShardId,
#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
inflater: Inflater,
latency: Latency,
ratelimiter: Option<CommandRatelimiter>,
resume_gateway_url: Option<String>,
session: Option<Session>,
status: ConnectionStatus,
user_channel: MessageChannel,
}
impl Shard {
pub fn new(id: ShardId, token: String, intents: Intents) -> Self {
let config = Config::builder(token, intents).build();
Self::with_config(id, config)
}
pub fn with_config(shard_id: ShardId, mut config: Config) -> Self {
let session = config.take_session();
Self {
config,
connection: None,
heartbeat_interval: None,
heartbeat_interval_event: false,
id: shard_id,
#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
inflater: Inflater::new(),
latency: Latency::new(),
ratelimiter: None,
resume_gateway_url: None,
session,
status: ConnectionStatus::Disconnected {
close_code: None,
reconnect_attempts: 0,
},
user_channel: MessageChannel::new(),
}
}
pub const fn config(&self) -> &Config {
&self.config
}
pub const fn id(&self) -> ShardId {
self.id
}
#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
pub const fn inflater(&self) -> &Inflater {
&self.inflater
}
pub const fn status(&self) -> &ConnectionStatus {
&self.status
}
pub const fn latency(&self) -> &Latency {
&self.latency
}
pub const fn ratelimiter(&self) -> Option<&CommandRatelimiter> {
self.ratelimiter.as_ref()
}
pub const fn session(&self) -> Option<&Session> {
self.session.as_ref()
}
pub async fn next_event(&mut self) -> Result<Event, ReceiveMessageError> {
loop {
match self.next_message().await? {
Message::Close(frame) => return Ok(Event::GatewayClose(frame)),
Message::Text(event) => {
if let Some(event) = json::parse(event, self.config.event_types())? {
return Ok(event.into());
}
}
}
}
}
#[tracing::instrument(fields(id = %self.id()), name = "shard", skip(self))]
pub async fn next_message(&mut self) -> Result<Message, ReceiveMessageError> {
match self.status {
ConnectionStatus::Disconnected {
close_code,
reconnect_attempts,
} => {
if self.connection.is_none() {
self.reconnect(close_code, reconnect_attempts).await?;
}
}
ConnectionStatus::FatallyClosed { close_code } if self.connection.is_none() => {
return Err(ReceiveMessageError::from_fatally_closed(close_code));
}
_ => {}
}
let message = loop {
let future = NextMessageFuture::new(
self.user_channel.rx_mut(),
self.connection.as_mut().expect("connected").next(),
self.ratelimiter.as_mut(),
self.heartbeat_interval.as_mut(),
);
let tungstenite_message = match future.await {
NextMessageFutureOutput::Message(Some(Ok(message))) => message,
#[cfg(any(feature = "rustls-native-roots", feature = "rustls-webpki-roots"))]
NextMessageFutureOutput::Message(Some(Err(TungsteniteError::Io(e))))
if self.status.is_disconnected() && e.kind() == IoErrorKind::UnexpectedEof =>
{
continue
}
NextMessageFutureOutput::Message(Some(Err(source))) => {
self.disconnect(CloseInitiator::None);
return Err(ReceiveMessageError {
kind: ReceiveMessageErrorType::Io,
source: Some(Box::new(source)),
});
}
NextMessageFutureOutput::Message(None) => {
tracing::debug!("gateway connection closed");
self.connection = None;
match self.status {
ConnectionStatus::Disconnected {
close_code,
reconnect_attempts,
} => self.reconnect(close_code, reconnect_attempts).await?,
ConnectionStatus::FatallyClosed { close_code } => {
return Err(ReceiveMessageError::from_fatally_closed(close_code))
}
_ => unreachable!(
"stream ended because websocket is closed (received close frame sets \
status to disconnected or fatally closed) or because it errored (which \
also sets status to disconnected)"
),
};
continue;
}
NextMessageFutureOutput::SendHeartbeat => {
let is_first_heartbeat =
self.heartbeat_interval.is_some() && self.latency.sent().is_none();
if !is_first_heartbeat && !self.heartbeat_interval_event {
tracing::info!("connection is failed or \"zombied\"");
self.session = self
.close(CloseFrame::RESUME)
.await
.map_err(ReceiveMessageError::from_send)?;
} else {
self.heartbeat()
.await
.map_err(ReceiveMessageError::from_send)?;
self.heartbeat_interval_event = false;
}
continue;
}
NextMessageFutureOutput::UserChannelMessage(message) => {
tracing::debug!("sending message from user channel");
self.send(message)
.await
.map_err(ReceiveMessageError::from_send)?;
continue;
}
};
#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
if let TungsteniteMessage::Binary(bytes) = &tungstenite_message {
if let Some(decompressed) = self
.inflater
.inflate(bytes)
.map_err(ReceiveMessageError::from_compression)?
{
tracing::trace!(%decompressed);
break Message::Text(decompressed);
};
}
if let Some(message) = Message::from_tungstenite(tungstenite_message) {
break message;
}
};
match &message {
Message::Close(frame) => {
tracing::debug!(?frame, "received websocket close message");
if !self.status.is_disconnected() {
self.disconnect(CloseInitiator::Gateway(
frame.as_ref().map(|frame| frame.code),
));
}
}
Message::Text(event) => {
self.process(event)
.await
.map_err(|source| ReceiveMessageError {
kind: ReceiveMessageErrorType::Process,
source: Some(Box::new(source)),
})?;
}
}
Ok(message)
}
pub async fn command(&mut self, command: &impl Command) -> Result<(), SendError> {
let message = command::prepare(command)?;
self.send(message).await
}
pub async fn send(&mut self, message: Message) -> Result<(), SendError> {
if !matches!(message, Message::Close(_)) {
if let Some(ratelimiter) = &mut self.ratelimiter {
ratelimiter.acquire().await;
}
}
self.send_unratelimited(message).await
}
async fn send_unratelimited(&mut self, message: Message) -> Result<(), SendError> {
self.connection
.as_mut()
.ok_or(SendError {
kind: SendErrorType::Sending,
source: None,
})?
.send(message.into_tungstenite())
.await
.map_err(|source| SendError {
kind: SendErrorType::Sending,
source: Some(Box::new(source)),
})
}
pub fn sender(&self) -> MessageSender {
self.user_channel.sender()
}
pub async fn close(
&mut self,
close_frame: CloseFrame<'static>,
) -> Result<Option<Session>, SendError> {
let close_code = close_frame.code;
tracing::debug!(frame = ?close_frame, "sending websocket close message");
let message = Message::Close(Some(close_frame));
self.send(message).await?;
self.disconnect(CloseInitiator::Shard(close_code));
Ok(self.session.take())
}
fn disconnect(&mut self, initiator: CloseInitiator) {
self.heartbeat_interval = None;
self.ratelimiter = None;
if matches!(initiator, CloseInitiator::Shard(1000 | 1001)) {
self.resume_gateway_url = None;
self.session = None;
}
self.status = match initiator {
CloseInitiator::Gateway(close_code) => ConnectionStatus::from_close_code(close_code),
_ => ConnectionStatus::Disconnected {
close_code: initiator.close_code(),
reconnect_attempts: 0,
},
};
}
async fn heartbeat(&mut self) -> Result<(), SendError> {
let sequence = self.session().map(Session::sequence);
tracing::debug!(?sequence, "sending heartbeat");
let message = command::prepare(&Heartbeat::new(sequence))?;
self.send_unratelimited(message).await?;
self.latency.track_sent();
Ok(())
}
fn identify(&self) {
tokio::spawn({
let sender = self.sender();
let shard_id = self.id();
let span = tracing::Span::current();
let queue = self.config().queue().clone();
let properties = self
.config()
.identify_properties()
.cloned()
.unwrap_or_else(default_identify_properties);
let identify = Identify::new(IdentifyInfo {
compress: false,
large_threshold: self.config.large_threshold(),
intents: self.config.intents(),
properties,
shard: Some([self.id().number(), self.id().total()]),
presence: self.config.presence().cloned(),
token: self.config.token().to_owned(),
});
async move {
queue.request([shard_id.number(), shard_id.total()]).await;
let _span = span.entered();
tracing::debug!("sending identify");
#[allow(clippy::let_underscore_drop)]
let _ = sender.command(&identify);
}
});
}
#[allow(clippy::too_many_lines)]
async fn process(&mut self, event: &str) -> Result<(), ProcessError> {
let (raw_opcode, maybe_sequence, maybe_event_type) =
GatewayEventDeserializer::from_json(event)
.ok_or(ProcessError {
kind: ProcessErrorType::Deserializing {
event: event.to_owned(),
},
source: Some("missing opcode".into()),
})?
.into_parts();
if self.latency.sent().is_some() {
self.heartbeat_interval_event = true;
}
match OpCode::from(raw_opcode) {
Some(OpCode::Dispatch) => {
let event_type = maybe_event_type.ok_or(ProcessError {
kind: ProcessErrorType::Deserializing {
event: event.to_owned(),
},
source: Some("missing dispatch event type".into()),
})?;
let sequence = maybe_sequence.ok_or(ProcessError {
kind: ProcessErrorType::Deserializing {
event: event.to_owned(),
},
source: Some("missing sequence".into()),
})?;
tracing::debug!(%event_type, %sequence, "received dispatch");
match event_type.as_ref() {
"READY" => {
let event = Self::parse_event::<MinimalReady>(event)?;
self.resume_gateway_url = Some(event.data.resume_gateway_url);
self.session = Some(Session::new(sequence, event.data.session_id));
self.status = ConnectionStatus::Connected;
}
"RESUMED" => self.status = ConnectionStatus::Connected,
_ => {}
}
if let Some(session) = self.session.as_mut() {
let last_sequence = session.set_sequence(sequence);
if sequence > last_sequence + 1 {
tracing::info!(
missed_events = sequence - (last_sequence + 1),
"dispatch events have been missed",
);
self.session = self
.close(CloseFrame::RESUME)
.await
.map_err(ProcessError::from_send)?;
}
} else {
tracing::info!("unable to store sequence");
}
}
Some(OpCode::Heartbeat) => {
tracing::debug!("received heartbeat");
self.heartbeat().await.map_err(ProcessError::from_send)?;
}
Some(OpCode::HeartbeatAck) => {
let requested = self.latency.received().is_none() && self.latency.sent().is_some();
if requested {
tracing::debug!("received heartbeat ack");
self.latency.track_received();
} else {
tracing::info!("received unrequested heartbeat ack");
}
}
Some(OpCode::Hello) => {
let event = Self::parse_event::<Hello>(event)?;
let heartbeat_interval = Duration::from_millis(event.data.heartbeat_interval);
let jitter = heartbeat_interval.mul_f64(rand::random());
tracing::debug!(?heartbeat_interval, ?jitter, "received hello");
if self.config().ratelimit_messages() {
self.ratelimiter = Some(CommandRatelimiter::new(heartbeat_interval));
}
let mut interval = time::interval_at(Instant::now() + jitter, heartbeat_interval);
interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
self.heartbeat_interval = Some(interval);
self.latency = Latency::new();
match self.session() {
Some(session) => {
tracing::debug!(sequence = session.sequence(), "sending resume");
let resume =
Resume::new(session.sequence(), session.id(), self.config().token());
self.command(&resume)
.await
.map_err(ProcessError::from_send)?;
}
None => self.identify(),
}
}
Some(OpCode::InvalidSession) => {
let resumable = Self::parse_event(event)?.data;
tracing::debug!(resumable, "received invalid session");
if resumable {
self.session = self
.close(CloseFrame::RESUME)
.await
.map_err(ProcessError::from_send)?;
} else {
self.close(CloseFrame::NORMAL)
.await
.map_err(ProcessError::from_send)?;
}
}
Some(OpCode::Reconnect) => {
tracing::debug!("received reconnect");
self.session = self
.close(CloseFrame::RESUME)
.await
.map_err(ProcessError::from_send)?;
}
_ => tracing::info!("received an unknown opcode: {raw_opcode}"),
}
Ok(())
}
async fn reconnect(
&mut self,
close_code: Option<u16>,
reconnect_attempts: u8,
) -> Result<(), ReceiveMessageError> {
future::reconnect_delay(reconnect_attempts).await;
let maybe_gateway_url = self
.config
.gateway_url()
.or(self.resume_gateway_url.as_deref());
self.connection = Some(
connection::connect(maybe_gateway_url, self.config.tls())
.await
.map_err(|source| {
self.resume_gateway_url = None;
self.status = ConnectionStatus::Disconnected {
close_code,
reconnect_attempts: reconnect_attempts + 1,
};
source
})?,
);
if self.session().is_some() {
self.status = ConnectionStatus::Resuming;
} else {
self.status = ConnectionStatus::Identifying;
}
#[cfg(any(feature = "zlib-stock", feature = "zlib-simd"))]
self.inflater.reset();
Ok(())
}
fn parse_event<T: DeserializeOwned>(json: &str) -> Result<MinimalEvent<T>, ProcessError> {
json::from_str::<MinimalEvent<T>>(json).map_err(|source| ProcessError {
kind: ProcessErrorType::Deserializing {
event: json.to_owned(),
},
source: Some(Box::new(source)),
})
}
}
fn default_identify_properties() -> IdentifyProperties {
IdentifyProperties::new("twilight.rs", "twilight.rs", OS)
}
#[cfg(test)]
mod tests {
use super::{ConnectionStatus, Shard};
use static_assertions::{assert_fields, assert_impl_all};
use std::fmt::Debug;
use twilight_model::gateway::CloseCode;
assert_fields!(
ConnectionStatus::Disconnected: close_code,
reconnect_attempts
);
assert_fields!(ConnectionStatus::FatallyClosed: close_code);
assert_impl_all!(ConnectionStatus: Clone, Debug, Eq, PartialEq, Send, Sync);
assert_impl_all!(Shard: Debug, Send, Sync);
#[test]
fn connection_status_from_close_frame() {
let empty = ConnectionStatus::from_close_code(None);
assert_eq!(
empty,
ConnectionStatus::Disconnected {
close_code: None,
reconnect_attempts: 0
}
);
let non_fatal_code = CloseCode::SessionTimedOut as u16;
let non_fatal_status = ConnectionStatus::from_close_code(Some(non_fatal_code));
assert_eq!(
non_fatal_status,
ConnectionStatus::Disconnected {
close_code: Some(non_fatal_code),
reconnect_attempts: 0
}
);
let fatal_code = CloseCode::AuthenticationFailed;
let fatal_status = ConnectionStatus::from_close_code(Some(fatal_code as u16));
assert_eq!(
fatal_status,
ConnectionStatus::FatallyClosed {
close_code: fatal_code
}
);
let unknown_code = u16::MAX;
let non_fatal_status = ConnectionStatus::from_close_code(Some(unknown_code));
assert_eq!(
non_fatal_status,
ConnectionStatus::Disconnected {
close_code: Some(unknown_code),
reconnect_attempts: 0
}
);
}
}