diff --git a/Cargo.toml b/Cargo.toml index 13511bc9c98..ca29245b795 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -129,6 +129,9 @@ temp_cache = ["cache", "mini-moka", "typesize?/mini_moka"] typesize = ["dep:typesize", "small-fixed-array/typesize", "bool_to_bitflags/typesize"] +# Enables compile-time heavy instrument macros from tracing +tracing_instrument = ["tracing/attributes"] + # Removed feature (https://github.com/serenity-rs/serenity/pull/2246) absolute_ratelimits = [] diff --git a/src/cache/mod.rs b/src/cache/mod.rs index 36ca9ec3ebe..824f522a026 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -36,7 +36,6 @@ use dashmap::DashMap; #[cfg(feature = "temp_cache")] use mini_moka::sync::Cache as MokaCache; use parking_lot::RwLock; -use tracing::instrument; pub use self::cache_update::CacheUpdate; pub use self::settings::Settings; @@ -234,7 +233,7 @@ impl Cache { /// /// let cache = Cache::new_with_settings(settings); /// ``` - #[instrument] + #[cfg_attr(feature = "tracing_instrument", instrument)] pub fn new_with_settings(settings: Settings) -> Self { #[cfg(feature = "temp_cache")] fn temp_cache(ttl: Duration) -> MokaCache @@ -673,7 +672,7 @@ impl Cache { /// Refer to the [`CacheUpdate` examples]. /// /// [`CacheUpdate` examples]: CacheUpdate#examples - #[instrument(skip(self, e))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self, e)))] pub fn update(&self, e: &mut E) -> Option { e.update(self) } diff --git a/src/client/context.rs b/src/client/context.rs index 40a84683e91..04f73b9da8c 100644 --- a/src/client/context.rs +++ b/src/client/context.rs @@ -41,7 +41,8 @@ pub struct Context { pub cache: Arc, } -// Used by the #[instrument] macro on client::dispatch::handle_event +// Used by the #[cfg_attr(feature = "tracing_instrument", instrument)] macro on +// client::dispatch::handle_event impl fmt::Debug for Context { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Context") diff --git a/src/client/mod.rs b/src/client/mod.rs index 0850cb57060..a09048c0ff7 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -32,7 +32,7 @@ use futures::channel::mpsc::UnboundedReceiver as Receiver; use futures::future::BoxFuture; use futures::StreamExt as _; use tokio::sync::RwLock; -use tracing::{debug, error, info, instrument}; +use tracing::debug; use typemap_rev::{TypeMap, TypeMapKey}; pub use self::context::Context; @@ -304,7 +304,7 @@ impl IntoFuture for ClientBuilder { type IntoFuture = BoxFuture<'static, Result>; - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] fn into_future(self) -> Self::IntoFuture { let data = Arc::new(RwLock::new(self.data)); #[cfg(feature = "framework")] @@ -631,8 +631,12 @@ impl Client { /// # } /// ``` /// + /// # Errors + /// + /// Returns a [`ClientError::Shutdown`] when all shards have shutdown due to an error. + /// /// [gateway docs]: crate::gateway#sharding - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn start(&mut self) -> Result<()> { self.start_connection(0, 0, NonZeroU16::MIN).await } @@ -673,7 +677,7 @@ impl Client { /// Returns a [`ClientError::Shutdown`] when all shards have shutdown due to an error. /// /// [gateway docs]: crate::gateway#sharding - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn start_autosharded(&mut self) -> Result<()> { let (end, total) = { let res = self.http.get_bot_gateway().await?; @@ -737,7 +741,7 @@ impl Client { /// Returns a [`ClientError::Shutdown`] when all shards have shutdown due to an error. /// /// [gateway docs]: crate::gateway#sharding - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn start_shard(&mut self, shard: u16, shards: u16) -> Result<()> { self.start_connection(shard, shard, check_shard_total(shards)).await } @@ -778,7 +782,7 @@ impl Client { /// Returns a [`ClientError::Shutdown`] when all shards have shutdown due to an error. /// /// [Gateway docs]: crate::gateway#sharding - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn start_shards(&mut self, total_shards: u16) -> Result<()> { self.start_connection(0, total_shards - 1, check_shard_total(total_shards)).await } @@ -819,12 +823,12 @@ impl Client { /// Returns a [`ClientError::Shutdown`] when all shards have shutdown due to an error. /// /// [Gateway docs]: crate::gateway#sharding - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn start_shard_range(&mut self, range: Range, total_shards: u16) -> Result<()> { self.start_connection(range.start, range.end, check_shard_total(total_shards)).await } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn start_connection( &mut self, start_shard: u16, @@ -842,15 +846,7 @@ impl Client { debug!("Initializing shard info: {} - {}/{}", start_shard, init, total_shards); - if let Err(why) = self.shard_manager.initialize(start_shard, init, total_shards) { - error!("Failed to boot a shard: {:?}", why); - info!("Shutting down all shards"); - - self.shard_manager.shutdown_all().await; - - return Err(Error::Client(ClientError::ShardBootFailure)); - } - + self.shard_manager.initialize(start_shard, init, total_shards); if let Some(Err(err)) = self.shard_manager_return_value.next().await { return Err(Error::Gateway(err)); } diff --git a/src/error.rs b/src/error.rs index dc449c3af91..fbbac135063 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,7 +6,6 @@ use std::io::Error as IoError; use reqwest::{header::InvalidHeaderValue, Error as ReqwestError}; #[cfg(feature = "gateway")] use tokio_tungstenite::tungstenite::error::Error as TungsteniteError; -use tracing::instrument; #[cfg(feature = "client")] use crate::client::ClientError; @@ -171,7 +170,7 @@ impl fmt::Display for Error { } impl StdError for Error { - #[instrument] + #[cfg_attr(feature = "tracing_instrument", instrument)] fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { Self::Format(inner) => Some(inner), diff --git a/src/framework/standard/mod.rs b/src/framework/standard/mod.rs index f14102232b1..3780efb14bb 100644 --- a/src/framework/standard/mod.rs +++ b/src/framework/standard/mod.rs @@ -22,7 +22,6 @@ use structures::buckets::{Bucket, RateLimitAction}; pub use structures::*; use tokio::sync::Mutex; use tokio::time::sleep; -use tracing::instrument; use uwl::Stream; use self::buckets::{RateLimitInfo, RevertBucket}; @@ -602,7 +601,7 @@ impl StandardFramework { #[async_trait] impl Framework for StandardFramework { - #[instrument(skip(self, event))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self, event)))] async fn dispatch(&self, mut ctx: Context, event: FullEvent) { let FullEvent::Message { new_message: msg, diff --git a/src/gateway/bridge/shard_manager.rs b/src/gateway/bridge/shard_manager.rs index 9dfa67f06cf..0ba18141452 100644 --- a/src/gateway/bridge/shard_manager.rs +++ b/src/gateway/bridge/shard_manager.rs @@ -9,7 +9,7 @@ use futures::channel::mpsc::{self, UnboundedReceiver as Receiver, UnboundedSende use futures::{SinkExt, StreamExt}; use tokio::sync::{Mutex, RwLock}; use tokio::time::timeout; -use tracing::{info, instrument, warn}; +use tracing::{info, warn}; use typemap_rev::TypeMap; #[cfg(feature = "voice")] @@ -170,21 +170,14 @@ impl ShardManager { /// /// This will communicate shard boots with the [`ShardQueuer`] so that they are properly /// queued. - #[instrument(skip(self))] - pub fn initialize( - &self, - shard_index: u16, - shard_init: u16, - shard_total: NonZeroU16, - ) -> Result<()> { + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] + pub fn initialize(&self, shard_index: u16, shard_init: u16, shard_total: NonZeroU16) { let shard_to = shard_index + shard_init; self.set_shard_total(shard_total); for shard_id in shard_index..shard_to { self.boot(ShardId(shard_id)); } - - Ok(()) } /// Restarts a shard runner. @@ -207,7 +200,7 @@ impl ShardManager { /// ``` /// /// [`ShardRunner`]: super::ShardRunner - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn restart(&self, shard_id: ShardId) { info!("Restarting shard {shard_id}"); self.shutdown(shard_id, 4000).await; @@ -218,7 +211,7 @@ impl ShardManager { /// valid [`ShardRunner`]. /// /// [`ShardRunner`]: super::ShardRunner - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn shards_instantiated(&self) -> Vec { self.runners.lock().await.keys().copied().collect() } @@ -231,7 +224,7 @@ impl ShardManager { /// **Note**: If the receiving end of an mpsc channel - theoretically owned by the shard runner /// - no longer exists, then the shard runner will not know it should shut down. This _should /// never happen_. It may already be stopped. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn shutdown(&self, shard_id: ShardId, code: u16) { const TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(5); @@ -273,7 +266,7 @@ impl ShardManager { /// /// If you only need to shutdown a select number of shards, prefer looping over the /// [`Self::shutdown`] method. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn shutdown_all(&self) { let keys = { let runners = self.runners.lock().await; @@ -305,7 +298,7 @@ impl ShardManager { drop(self.shard_queuer.unbounded_send(msg)); } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] fn boot(&self, shard_id: ShardId) { info!("Telling shard queuer to start shard {shard_id}"); diff --git a/src/gateway/bridge/shard_queuer.rs b/src/gateway/bridge/shard_queuer.rs index cc72dd0faf6..7d3b6829113 100644 --- a/src/gateway/bridge/shard_queuer.rs +++ b/src/gateway/bridge/shard_queuer.rs @@ -8,7 +8,7 @@ use futures::channel::mpsc::UnboundedReceiver as Receiver; use futures::StreamExt; use tokio::sync::{Mutex, RwLock}; use tokio::time::{sleep, timeout, Duration, Instant}; -use tracing::{debug, info, instrument, warn}; +use tracing::{debug, info, warn}; use typemap_rev::TypeMap; #[cfg(feature = "voice")] @@ -100,7 +100,7 @@ impl ShardQueuer { /// over. /// /// **Note**: This should be run in its own thread due to the blocking nature of the loop. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn run(&mut self) { // The duration to timeout from reads over the Rx channel. This can be done in a loop, and // if the read times out then a shard can be started if one is presently waiting in the @@ -135,7 +135,7 @@ impl ShardQueuer { } } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn check_last_start(&mut self) { let Some(instant) = self.last_start else { return }; @@ -152,7 +152,7 @@ impl ShardQueuer { sleep(to_sleep).await; } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn checked_start(&mut self, shard_id: ShardId) { debug!("[Shard Queuer] Checked start for shard {shard_id}"); @@ -167,7 +167,7 @@ impl ShardQueuer { self.last_start = Some(Instant::now()); } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn start(&mut self, shard_id: ShardId) -> Result<()> { let mut shard = Shard::new( Arc::clone(&self.ws_url), @@ -212,7 +212,7 @@ impl ShardQueuer { Ok(()) } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn shutdown_runners(&mut self) { let keys = { let runners = self.runners.lock().await; @@ -236,7 +236,7 @@ impl ShardQueuer { /// **Note**: If the receiving end of an mpsc channel - theoretically owned by the shard runner /// - no longer exists, then the shard runner will not know it should shut down. This _should /// never happen_. It may already be stopped. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn shutdown(&mut self, shard_id: ShardId, code: u16) { info!("Shutting down shard {}", shard_id); diff --git a/src/gateway/bridge/shard_runner.rs b/src/gateway/bridge/shard_runner.rs index 26d5dddb8b6..b69e49e453a 100644 --- a/src/gateway/bridge/shard_runner.rs +++ b/src/gateway/bridge/shard_runner.rs @@ -6,7 +6,7 @@ use tokio::sync::RwLock; use tokio_tungstenite::tungstenite; use tokio_tungstenite::tungstenite::error::Error as TungsteniteError; use tokio_tungstenite::tungstenite::protocol::frame::CloseFrame; -use tracing::{debug, error, info, instrument, trace, warn}; +use tracing::{debug, error, info, trace, warn}; use typemap_rev::TypeMap; use super::event::ShardStageUpdateEvent; @@ -93,14 +93,17 @@ impl ShardRunner { /// /// 6. Go back to 1. /// + /// # Errors + /// Returns errors if the internal WS connection drops in a non-recoverable way. + /// /// [`ShardManager`]: super::ShardManager - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn run(&mut self) -> Result<()> { info!("[ShardRunner {:?}] Running", self.shard.shard_info()); loop { trace!("[ShardRunner {:?}] loop iteration started.", self.shard.shard_info()); - if !self.recv().await? { + if !self.recv().await { return Ok(()); } @@ -108,7 +111,8 @@ impl ShardRunner { if !self.shard.do_heartbeat().await { warn!("[ShardRunner {:?}] Error heartbeating", self.shard.shard_info(),); - return self.request_restart().await; + self.request_restart().await; + return Ok(()); } let pre = self.shard.stage(); @@ -133,7 +137,8 @@ impl ShardRunner { match action { Some(ShardAction::Reconnect(ReconnectType::Reidentify)) => { - return self.request_restart().await; + self.request_restart().await; + return Ok(()); }, Some(other) => { if let Err(e) = self.action(&other).await { @@ -144,7 +149,10 @@ impl ShardRunner { e ); match self.shard.reconnection_type() { - ReconnectType::Reidentify => return self.request_restart().await, + ReconnectType::Reidentify => { + self.request_restart().await; + return Ok(()); + }, ReconnectType::Resume => { if let Err(why) = self.shard.resume().await { warn!( @@ -153,7 +161,8 @@ impl ShardRunner { why ); - return self.request_restart().await; + self.request_restart().await; + return Ok(()); } }, }; @@ -177,7 +186,8 @@ impl ShardRunner { } if !successful && !self.shard.stage().is_connecting() { - return self.request_restart().await; + self.request_restart().await; + return Ok(()); } trace!("[ShardRunner {:?}] loop iteration reached the end.", self.shard.shard_info()); } @@ -196,10 +206,13 @@ impl ShardRunner { /// # Errors /// /// Returns - #[instrument(skip(self, action))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self, action)))] async fn action(&mut self, action: &ShardAction) -> Result<()> { match *action { - ShardAction::Reconnect(ReconnectType::Reidentify) => self.request_restart().await, + ShardAction::Reconnect(ReconnectType::Reidentify) => { + self.request_restart().await; + Ok(()) + }, ShardAction::Reconnect(ReconnectType::Resume) => self.shard.resume().await, ShardAction::Heartbeat => self.shard.heartbeat().await, ShardAction::Identify => self.shard.identify().await, @@ -212,7 +225,7 @@ impl ShardRunner { // Returns whether the WebSocket client is still active. // // If true, the WebSocket client was _not_ shutdown. If false, it was. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn checked_shutdown(&mut self, id: ShardId, close_code: u16) -> bool { // First verify the ID so we know for certain this runner is to shutdown. if id != self.shard.shard_info().id { @@ -269,7 +282,7 @@ impl ShardRunner { // // This always returns true, except in the case that the shard manager asked the runner to // shutdown. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn handle_rx_value(&mut self, msg: ShardRunnerMessage) -> bool { match msg { ShardRunnerMessage::Restart(id) => self.checked_shutdown(id, 4000).await, @@ -320,7 +333,7 @@ impl ShardRunner { } #[cfg(feature = "voice")] - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn handle_voice_event(&self, event: &Event) { if let Some(voice_manager) = &self.voice_manager { match event { @@ -353,13 +366,13 @@ impl ShardRunner { // Requests a restart if the sending half of the channel disconnects. This should _never_ // happen, as the sending half is kept on the runner. // Returns whether the shard runner is in a state that can continue. - #[instrument(skip(self))] - async fn recv(&mut self) -> Result { + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] + async fn recv(&mut self) -> bool { loop { match self.runner_rx.try_next() { Ok(Some(value)) => { if !self.handle_rx_value(value).await { - return Ok(false); + return false; } }, Ok(None) => { @@ -368,21 +381,20 @@ impl ShardRunner { self.shard.shard_info(), ); - drop(self.request_restart().await); - return Ok(false); + self.request_restart().await; + return false; }, Err(_) => break, } } // There are no longer any values available. - - Ok(true) + true } /// Returns a received event, as well as whether reading the potentially present event was /// successful. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn recv_event(&mut self) -> Result<(Option, Option, bool)> { let gw_event = match self.shard.client.recv_json().await { Ok(inner) => Ok(inner), @@ -454,8 +466,8 @@ impl ShardRunner { Ok((event, action, true)) } - #[instrument(skip(self))] - async fn request_restart(&mut self) -> Result<()> { + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] + async fn request_restart(&mut self) { debug!("[ShardRunner {:?}] Requesting restart", self.shard.shard_info()); self.update_manager().await; @@ -467,11 +479,9 @@ impl ShardRunner { if let Some(voice_manager) = &self.voice_manager { voice_manager.deregister_shard(shard_id.0).await; } - - Ok(()) } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] async fn update_manager(&self) { self.manager .update_shard_latency_and_stage( diff --git a/src/gateway/shard.rs b/src/gateway/shard.rs index 760dedc1033..2237eb30707 100644 --- a/src/gateway/shard.rs +++ b/src/gateway/shard.rs @@ -3,7 +3,7 @@ use std::time::{Duration as StdDuration, Instant}; use tokio_tungstenite::tungstenite::error::Error as TungsteniteError; use tokio_tungstenite::tungstenite::protocol::frame::CloseFrame; -use tracing::{debug, error, info, instrument, trace, warn}; +use tracing::{debug, error, info, trace, warn}; use url::Url; use super::{ @@ -191,7 +191,7 @@ impl Shard { /// # Errors /// /// Returns [`GatewayError::HeartbeatFailed`] if there was an error sending a heartbeat. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn heartbeat(&mut self) -> Result<()> { match self.client.send_heartbeat(&self.shard_info, Some(self.seq)).await { Ok(()) => { @@ -239,20 +239,20 @@ impl Shard { } #[inline] - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub fn set_activity(&mut self, activity: Option) { self.presence.activity = activity; } #[inline] - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub fn set_presence(&mut self, activity: Option, status: OnlineStatus) { self.set_activity(activity); self.set_status(status); } #[inline] - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub fn set_status(&mut self, mut status: OnlineStatus) { if status == OnlineStatus::Offline { status = OnlineStatus::Invisible; @@ -274,7 +274,7 @@ impl Shard { self.stage } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] fn handle_gateway_dispatch(&mut self, seq: u64, event: &Event) -> Option { if seq > self.seq + 1 { warn!("[{:?}] Sequence off; them: {}, us: {}", self.shard_info, seq, self.seq); @@ -307,7 +307,7 @@ impl Shard { None } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] fn handle_heartbeat_event(&mut self, s: u64) -> ShardAction { info!("[{:?}] Received shard heartbeat", self.shard_info); @@ -331,7 +331,7 @@ impl Shard { ShardAction::Heartbeat } - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] fn handle_gateway_closed( &mut self, data: Option<&CloseFrame<'static>>, @@ -436,7 +436,7 @@ impl Shard { /// /// Returns a [`GatewayError::OverloadedShard`] if the shard would have too many guilds /// assigned to it. - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub fn handle_event(&mut self, event: &Result) -> Result> { match event { Ok(GatewayEvent::Dispatch(seq, event)) => Ok(self.handle_gateway_dispatch(*seq, event)), @@ -504,7 +504,7 @@ impl Shard { /// `false` is returned under one of the following conditions: /// - a heartbeat acknowledgement was not received in time /// - an error occurred while heartbeating - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn do_heartbeat(&mut self) -> bool { let Some(heartbeat_interval) = self.heartbeat_interval else { // No Hello received yet @@ -541,7 +541,7 @@ impl Shard { /// Calculates the heartbeat latency between the shard and the gateway. // Shamelessly stolen from brayzure's commit in eris: // - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub fn latency(&self) -> Option { if let (Some(sent), Some(received)) = (self.last_heartbeat_sent, self.last_heartbeat_ack) { if received > sent { @@ -632,10 +632,13 @@ impl Shard { /// # } /// ``` /// + /// # Errors + /// Errors if there is a problem with the WS connection. + /// /// [`Event::GuildMembersChunk`]: crate::model::event::Event::GuildMembersChunk /// [`Guild`]: crate::model::guild::Guild /// [`Member`]: crate::model::guild::Member - #[instrument(skip(self))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn chunk_guild( &mut self, guild_id: GuildId, @@ -654,7 +657,10 @@ impl Shard { /// Sets the shard as going into identifying stage, which sets: /// - the time that the last heartbeat sent as being now /// - the `stage` to [`ConnectionStage::Identifying`] - #[instrument(skip(self))] + /// + /// # Errors + /// Errors if there is a problem with the WS connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn identify(&mut self) -> Result<()> { self.client .send_identify(&self.shard_info, &self.token, self.intents, &self.presence) @@ -669,7 +675,10 @@ impl Shard { /// Initializes a new WebSocket client. /// /// This will set the stage of the shard before and after instantiation of the client. - #[instrument(skip(self))] + /// # Errors + /// + /// Errors if unable to establish a websocket connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn initialize(&mut self) -> Result { debug!("[{:?}] Initializing.", self.shard_info); @@ -688,8 +697,8 @@ impl Shard { Ok(client) } - #[instrument(skip(self))] - pub async fn reset(&mut self) { + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] + pub fn reset(&mut self) { self.last_heartbeat_sent = Some(Instant::now()); self.last_heartbeat_ack = None; self.heartbeat_interval = None; @@ -699,7 +708,10 @@ impl Shard { self.seq = 0; } - #[instrument(skip(self))] + /// # Errors + /// + /// Errors if unable to re-establish a websocket connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn resume(&mut self) -> Result<()> { debug!("[{:?}] Attempting to resume", self.shard_info); @@ -714,17 +726,23 @@ impl Shard { } } - #[instrument(skip(self))] + /// # Errors + /// + /// Errors if unable to re-establish a websocket connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn reconnect(&mut self) -> Result<()> { info!("[{:?}] Attempting to reconnect", self.shard_info()); - self.reset().await; + self.reset(); self.client = self.initialize().await?; Ok(()) } - #[instrument(skip(self))] + /// # Errors + /// + /// Errors if there is a problem with the WS connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn update_presence(&mut self) -> Result<()> { self.client.send_presence_update(&self.shard_info, &self.presence).await } diff --git a/src/gateway/ws.rs b/src/gateway/ws.rs index 3f378dd367a..2e70a6bc517 100644 --- a/src/gateway/ws.rs +++ b/src/gateway/ws.rs @@ -20,7 +20,7 @@ use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::{connect_async_with_config, MaybeTlsStream, WebSocketStream}; #[cfg(feature = "client")] use tracing::warn; -use tracing::{debug, instrument, trace}; +use tracing::{debug, trace}; use url::Url; use super::{ActivityData, ChunkGuildFilter, PresenceData}; @@ -212,7 +212,10 @@ impl WsClient { .await } - #[instrument(skip(self))] + /// # Errors + /// + /// Errors if there is a problem with the WS connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn send_heartbeat(&mut self, shard_info: &ShardInfo, seq: Option) -> Result<()> { trace!("[{:?}] Sending heartbeat d: {:?}", shard_info, seq); @@ -223,7 +226,10 @@ impl WsClient { .await } - #[instrument(skip(self, token))] + /// # Errors + /// + /// Errors if there is a problem with the WS connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self, token)))] pub async fn send_identify( &mut self, shard: &ShardInfo, @@ -261,7 +267,10 @@ impl WsClient { self.send_json(&msg).await } - #[instrument(skip(self))] + /// # Errors + /// + /// Errors if there is a problem with the WS connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self)))] pub async fn send_presence_update( &mut self, shard_info: &ShardInfo, @@ -284,7 +293,10 @@ impl WsClient { .await } - #[instrument(skip(self, token))] + /// # Errors + /// + /// Errors if there is a problem with the WS connection. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(self, token)))] pub async fn send_resume( &mut self, shard_info: &ShardInfo, diff --git a/src/http/client.rs b/src/http/client.rs index 797082e014a..f9200435ccc 100644 --- a/src/http/client.rs +++ b/src/http/client.rs @@ -13,7 +13,7 @@ use reqwest::Url; use reqwest::{Client, ClientBuilder, Response as ReqwestResponse, StatusCode}; use secrecy::{ExposeSecret, SecretString}; use serde::de::DeserializeOwned; -use tracing::{debug, instrument, trace}; +use tracing::{debug, trace}; use super::multipart::{Multipart, MultipartUpload}; use super::ratelimiting::Ratelimiter; @@ -4633,7 +4633,7 @@ impl Http { /// # Ok(()) /// # } /// ``` - #[instrument] + #[cfg_attr(feature = "tracing_instrument", instrument)] pub async fn request(&self, req: Request<'_>) -> Result { let method = req.method.reqwest_method(); let response = if let Some(ratelimiter) = &self.ratelimiter { diff --git a/src/http/ratelimiting.rs b/src/http/ratelimiting.rs index cb6904394c5..ebfffcda5cd 100644 --- a/src/http/ratelimiting.rs +++ b/src/http/ratelimiting.rs @@ -46,7 +46,7 @@ use reqwest::{Client, Response, StatusCode}; use secrecy::{ExposeSecret, SecretString}; use tokio::sync::{Mutex, RwLock}; use tokio::time::{sleep, Duration}; -use tracing::{debug, instrument}; +use tracing::debug; pub use super::routing::RatelimitingBucket; use super::{HttpError, LightMethod, Request}; @@ -178,7 +178,7 @@ impl Ratelimiter { /// # Errors /// /// Only error kind that may be returned is [`Error::Http`]. - #[instrument] + #[cfg_attr(feature = "tracing_instrument", instrument)] pub async fn perform(&self, req: Request<'_>) -> Result { loop { // This will block if another thread hit the global ratelimit. @@ -277,7 +277,7 @@ pub struct Ratelimit { } impl Ratelimit { - #[instrument(skip(ratelimit_callback))] + #[cfg_attr(feature = "tracing_instrument", instrument(skip(ratelimit_callback)))] pub async fn pre_hook( &mut self, req: &Request<'_>, @@ -323,7 +323,10 @@ impl Ratelimit { self.remaining -= 1; } - #[instrument(skip(ratelimit_callback))] + /// # Errors + /// + /// Errors if unable to parse response headers. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(ratelimit_callback)))] pub async fn post_hook( &mut self, response: &Response, diff --git a/src/http/request.rs b/src/http/request.rs index b5541670306..dcbef521326 100644 --- a/src/http/request.rs +++ b/src/http/request.rs @@ -9,7 +9,6 @@ use reqwest::header::{ USER_AGENT, }; use reqwest::{Client, RequestBuilder as ReqwestRequestBuilder, Url}; -use tracing::instrument; use super::multipart::Multipart; use super::routing::Route; @@ -64,7 +63,10 @@ impl<'a> Request<'a> { self } - #[instrument(skip(token))] + /// # Errors + /// + /// Errors if the given proxy URL is invalid, or the token cannot be parsed into a HTTP header. + #[cfg_attr(feature = "tracing_instrument", instrument(skip(token)))] pub fn build( self, client: &Client,