Skip to content

Commit

Permalink
Add resume_gateway_url support (serenity-rs#2832)
Browse files Browse the repository at this point in the history
This announcement was missed (around August 2022) and probably the cause
of a lot of the disconnections.
  • Loading branch information
GnomedDev committed Oct 20, 2024
1 parent 2d8c572 commit 15ea78f
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/gateway/shard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ pub struct Shard {
pub started: Instant,
token: Secret<Token>,
ws_url: Arc<str>,
resume_ws_url: Option<FixedString>,
pub intents: GatewayIntents,
}

Expand Down Expand Up @@ -154,6 +155,7 @@ impl Shard {
session_id,
shard_info,
ws_url,
resume_ws_url: None,
intents,
})
}
Expand Down Expand Up @@ -284,6 +286,7 @@ impl Shard {
Event::Ready(ready) => {
debug!("[{:?}] Received Ready", self.shard_info);

self.resume_ws_url = Some(ready.ready.resume_gateway_url.clone());
self.session_id = Some(ready.ready.session_id.clone());
self.stage = ConnectionStage::Connected;

Expand Down Expand Up @@ -685,16 +688,20 @@ impl Shard {
Ok(())
}

/// Initializes a new WebSocket client.
/// Reinitializes an existing WebSocket client, replacing it.
///
/// This will set the stage of the shard before and after instantiation of the client.
///
/// # Errors
///
/// Errors if unable to establish a websocket connection.
#[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))]
pub async fn initialize(&mut self) -> Result<WsClient> {
pub async fn reinitialize(&mut self) -> Result<WsClient> {
debug!("[{:?}] Initializing.", self.shard_info);

// Reconnect to the resume URL if possible, otherwise use the generic URL.
let ws_url = self.resume_ws_url.as_deref().unwrap_or(&self.ws_url);

// We need to do two, sort of three things here:
// - set the stage of the shard as opening the websocket connection
// - open the websocket connection
Expand All @@ -704,7 +711,7 @@ impl Shard {
// Hello is received.
self.stage = ConnectionStage::Connecting;
self.started = Instant::now();
let client = connect(&self.ws_url).await?;
let client = connect(ws_url).await?;
self.stage = ConnectionStage::Handshake;

Ok(client)
Expand All @@ -728,7 +735,7 @@ impl Shard {
pub async fn resume(&mut self) -> Result<()> {
debug!("[{:?}] Attempting to resume", self.shard_info);

self.client = self.initialize().await?;
self.client = self.reinitialize().await?;
self.stage = ConnectionStage::Resuming;

match &self.session_id {
Expand All @@ -749,7 +756,7 @@ impl Shard {
info!("[{:?}] Attempting to reconnect", self.shard_info());

self.reset();
self.client = self.initialize().await?;
self.client = self.reinitialize().await?;

Ok(())
}
Expand Down

0 comments on commit 15ea78f

Please sign in to comment.