Skip to main content

djs_gateway/
shard.rs

1//! The [`Shard`]: one gateway connection.
2
3use core::{fmt::Write as _, future::Future, pin::Pin, time::Duration};
4use std::sync::{Arc, Mutex, PoisonError};
5
6use djs_model::gateway::{
7    API_VERSION, CloseCode, DispatchEvent, GatewayEvent, GatewayEventDeserializer, OpCode, ShardId,
8    payload::{
9        CommandPayload, GatewayCapabilities, GatewayCommand, Heartbeat, Identify, Resume,
10        UpdatePresence,
11    },
12};
13use futures_util::{SinkExt, StreamExt};
14use serde::de::DeserializeSeed;
15use tokio::{
16    net::TcpStream,
17    sync::mpsc,
18    time::{Instant, Sleep, sleep, sleep_until},
19};
20use tokio_websockets::{ClientBuilder, Limits, MaybeTlsStream, Message, WebSocketStream};
21
22use crate::{
23    Config,
24    compression::Decompressor,
25    error::{ReceiveError, ReceiveErrorKind, SendError},
26    send_limit::SendLimit,
27};
28
29type Connection = WebSocketStream<MaybeTlsStream<TcpStream>>;
30
31/// A shard's turn in the IDENTIFY queue.
32///
33/// Kept in a [`Mutex`] only so that [`Shard`] stays `Sync` (the future is only `Send`); it is
34/// never locked — polling goes through [`Mutex::get_mut`], which is free.
35type IdentifyTurn = Mutex<Pin<Box<dyn Future<Output = ()> + Send>>>;
36
37/// Upper bound of the reconnect backoff.
38const MAX_BACKOFF: Duration = Duration::from_secs(60);
39/// How long to wait for our close frame to be written before dropping the connection.
40const CLOSE_TIMEOUT: Duration = Duration::from_secs(2);
41/// The close code used when *we* close a connection we want to resume later. Codes 1000 and
42/// 1001 would invalidate the session.
43const RESUMABLE_CLOSE_CODE: u16 = 4000;
44
45/// The connection state of a [`Shard`].
46///
47/// discord.js counterpart: `WebSocketShardStatus` (`@discordjs/ws`).
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum ShardState {
51    /// Not connected. The next call to [`Shard::next_event`] connects (after a backoff delay if
52    /// the previous attempt failed).
53    Disconnected,
54    /// Connected and identifying; waiting for `READY`.
55    Identifying,
56    /// Connected and resuming; waiting for `RESUMED`.
57    Resuming,
58    /// The session is established and events are flowing.
59    Active,
60    /// Discord closed the connection with a code that forbids reconnecting.
61    FatallyClosed(CloseCode),
62    /// Closed by [`Shard::close`].
63    Closed,
64}
65
66/// A single connection to the Discord gateway.
67///
68/// A shard is **poll-driven** (D-037): calling [`next_event`](Self::next_event) is what drives
69/// the connection — it connects, identifies or resumes, sends heartbeats, detects zombied
70/// connections and reconnects, all while waiting for the next event. Nothing happens while no
71/// one is polling, and there are no background tasks or internal event channels.
72///
73/// Before identifying, a shard waits for its turn in the [`IdentifyQueue`] of its
74/// [`Config`]; shards created from clones of one configuration (as [`create_shards`] does)
75/// share it. Resuming does not identify and does not wait.
76///
77/// Commands (presence updates, member requests, …) can be sent from other tasks through a
78/// [`MessageSender`]; they are delivered once the session is active, paced to stay under
79/// Discord's send limit.
80///
81/// [`IdentifyQueue`]: crate::IdentifyQueue
82/// [`create_shards`]: crate::create_shards
83///
84/// discord.js counterpart: `WebSocketShard` from `@discordjs/ws`.
85///
86/// # Examples
87///
88/// ```no_run
89/// use djs_gateway::Shard;
90/// use djs_model::gateway::{DispatchEvent, GatewayEvent, Intents, ShardId};
91///
92/// # async fn run() {
93/// let token = std::env::var("DISCORD_TOKEN").unwrap();
94/// let mut shard = Shard::new(ShardId::ONE, token, Intents::GUILDS | Intents::GUILD_MESSAGES);
95///
96/// while let Some(event) = shard.next_event().await {
97///     match event {
98///         Ok(GatewayEvent::Dispatch(_, DispatchEvent::Ready(ready))) => {
99///             println!("logged in as {}", ready.user.username);
100///         }
101///         Ok(_) => {}
102///         Err(error) if error.is_fatal() => {
103///             eprintln!("fatal: {error}");
104///             break;
105///         }
106///         Err(error) => eprintln!("recoverable: {error}"),
107///     }
108/// }
109/// # }
110/// ```
111pub struct Shard {
112    id: ShardId,
113    config: Config,
114    state: ShardState,
115    connection: Option<Connection>,
116    decompressor: Option<Decompressor>,
117    heartbeat: Option<Heartbeater>,
118    hello_deadline: Option<Pin<Box<Sleep>>>,
119    /// The shard's turn in the IDENTIFY queue, while it waits for it.
120    identify_turn: Option<IdentifyTurn>,
121    session: Option<Session>,
122    sequence: Option<u64>,
123    latency: Option<Duration>,
124    reconnect_attempts: u32,
125    connect_after: Option<Instant>,
126    commands_tx: mpsc::UnboundedSender<String>,
127    commands_rx: mpsc::UnboundedReceiver<String>,
128    send_limit: SendLimit,
129    held: Option<HeldCommand>,
130    /// The presence to identify with, shared with every [`MessageSender`].
131    presence: SharedPresence,
132}
133
134/// The presence a shard identifies with: the configured one until
135/// [`MessageSender::update_presence`] replaces it.
136type SharedPresence = Arc<Mutex<Option<UpdatePresence>>>;
137
138struct Session {
139    id: Box<str>,
140    resume_url: Box<str>,
141}
142
143struct Heartbeater {
144    interval: Duration,
145    sleep: Pin<Box<Sleep>>,
146    last_sent: Option<Instant>,
147    acked: bool,
148}
149
150/// A command taken from the queue but held back by the send limit.
151struct HeldCommand {
152    json: String,
153    /// Fires once the send limit has room for it.
154    until: Pin<Box<Sleep>>,
155}
156
157/// What woke the shard up.
158enum Wake {
159    Heartbeat,
160    HelloTimeout,
161    Identify,
162    Command(String),
163    HeldCommandAllowed,
164    Message(Option<Result<Message, tokio_websockets::Error>>),
165}
166
167impl core::fmt::Debug for Shard {
168    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
169        f.debug_struct("Shard")
170            .field("id", &self.id)
171            .field("state", &self.state)
172            .field(
173                "session_id",
174                &self.session.as_ref().map(|session| &session.id),
175            )
176            .field("sequence", &self.sequence)
177            .field("latency", &self.latency)
178            .finish_non_exhaustive()
179    }
180}
181
182impl Shard {
183    /// Creates a shard with the default [`Config`]. It does not connect until
184    /// [`next_event`](Self::next_event) is called.
185    ///
186    /// Pass the raw token, without the `Bot ` prefix.
187    ///
188    /// discord.js counterpart: `new WebSocketShard(strategy, id)` (`@discordjs/ws`).
189    #[must_use]
190    pub fn new(
191        id: ShardId,
192        token: impl Into<String>,
193        intents: djs_model::gateway::Intents,
194    ) -> Self {
195        Self::with_config(id, Config::new(token, intents))
196    }
197
198    /// Creates a shard with a custom [`Config`].
199    ///
200    /// discord.js counterpart: `new WebSocketShard(strategy, id)` (`@discordjs/ws`).
201    #[must_use]
202    pub fn with_config(id: ShardId, config: Config) -> Self {
203        let (commands_tx, commands_rx) = mpsc::unbounded_channel();
204        let presence = Arc::new(Mutex::new(config.presence.clone()));
205        Self {
206            id,
207            config,
208            state: ShardState::Disconnected,
209            connection: None,
210            decompressor: None,
211            heartbeat: None,
212            hello_deadline: None,
213            identify_turn: None,
214            session: None,
215            sequence: None,
216            latency: None,
217            reconnect_attempts: 0,
218            connect_after: None,
219            commands_tx,
220            commands_rx,
221            send_limit: SendLimit::default(),
222            held: None,
223            presence,
224        }
225    }
226
227    /// Returns the shard's ID.
228    ///
229    /// discord.js counterpart: `WebSocketShard#id` (`@discordjs/ws`).
230    #[must_use]
231    pub const fn id(&self) -> ShardId {
232        self.id
233    }
234
235    /// Returns the shard's configuration.
236    ///
237    /// discord.js counterpart: the options of `WebSocketManager` (`@discordjs/ws`).
238    #[must_use]
239    pub const fn config(&self) -> &Config {
240        &self.config
241    }
242
243    /// Returns the current connection state.
244    ///
245    /// discord.js counterpart: `WebSocketShard#status` (`@discordjs/ws`).
246    #[must_use]
247    pub const fn state(&self) -> ShardState {
248        self.state
249    }
250
251    /// Returns the round-trip time of the last acknowledged heartbeat.
252    ///
253    /// discord.js counterpart: `WebSocketShard#ping` / `client.ws.ping`.
254    #[must_use]
255    pub const fn latency(&self) -> Option<Duration> {
256        self.latency
257    }
258
259    /// Returns the current session ID, if a session is established.
260    ///
261    /// discord.js counterpart: the `sessionId` of `SessionInfo` (`@discordjs/ws`).
262    #[must_use]
263    pub fn session_id(&self) -> Option<&str> {
264        self.session.as_ref().map(|session| &*session.id)
265    }
266
267    /// Returns the sequence number of the last dispatch received.
268    ///
269    /// discord.js counterpart: the `sequence` of `SessionInfo` (`@discordjs/ws`).
270    #[must_use]
271    pub const fn sequence(&self) -> Option<u64> {
272        self.sequence
273    }
274
275    /// Returns a handle to send commands to this shard from anywhere.
276    ///
277    /// Commands are queued and sent once the session is [active](ShardState::Active), in
278    /// order, paced to stay under Discord's send limit (see [`MessageSender`]).
279    ///
280    /// discord.js counterpart: `WebSocketShard#send` (`@discordjs/ws`).
281    #[must_use]
282    pub fn sender(&self) -> MessageSender {
283        MessageSender {
284            tx: self.commands_tx.clone(),
285            presence: Arc::clone(&self.presence),
286        }
287    }
288
289    /// Waits for the next event, driving the connection meanwhile.
290    ///
291    /// Returns `None` once the shard has been [closed](Self::close) or fatally closed by Discord.
292    /// Every gateway payload is returned, including control payloads such as
293    /// [`GatewayEvent::Hello`], which the shard has already acted upon.
294    ///
295    /// discord.js counterpart: `WebSocketShard#connect` and its `dispatch` event (`@discordjs/ws`).
296    ///
297    /// # Cancel safety
298    ///
299    /// This method is cancel safe in the sense that cancelling it never corrupts the shard: it
300    /// can be used in `tokio::select!`. An event being processed at the moment of cancellation
301    /// may be lost.
302    pub async fn next_event(&mut self) -> Option<Result<GatewayEvent, ReceiveError>> {
303        loop {
304            if matches!(
305                self.state,
306                ShardState::FatallyClosed(_) | ShardState::Closed
307            ) {
308                return None;
309            }
310            if self.connection.is_none() {
311                if let Some(at) = self.connect_after.take() {
312                    sleep_until(at).await;
313                }
314                if let Err(error) = self.connect().await {
315                    self.schedule_reconnect();
316                    return Some(Err(error));
317                }
318            }
319            if let Some(result) = self.step().await {
320                return Some(result);
321            }
322        }
323    }
324
325    /// Closes the connection and invalidates the session (the bot appears offline). Afterwards
326    /// [`next_event`](Self::next_event) returns `None`.
327    ///
328    /// discord.js counterpart: `WebSocketShard#destroy`.
329    pub async fn close(&mut self) {
330        if let Some(mut connection) = self.connection.take() {
331            let frame = Message::close(Some(tokio_websockets::CloseCode::NORMAL_CLOSURE), "");
332            let _ = tokio::time::timeout(CLOSE_TIMEOUT, connection.send(frame)).await;
333        }
334        self.reset_connection();
335        self.session = None;
336        self.sequence = None;
337        self.state = ShardState::Closed;
338        tracing::info!(shard = %self.id, "shard closed");
339    }
340
341    /// Waits for one wake-up source and handles it. Returns an item for the caller, if any.
342    async fn step(&mut self) -> Option<Result<GatewayEvent, ReceiveError>> {
343        let active = self.state == ShardState::Active;
344        // A held command goes out first; the queue waits behind it.
345        let receive_commands = active && self.held.is_none();
346        let connection = self.connection.as_mut()?;
347        let heartbeat = self
348            .heartbeat
349            .as_mut()
350            .map(|heartbeat| heartbeat.sleep.as_mut());
351        let hello = self.hello_deadline.as_mut().map(Pin::as_mut);
352        let identify = self.identify_turn.as_mut().map(|turn| {
353            turn.get_mut()
354                .unwrap_or_else(PoisonError::into_inner)
355                .as_mut()
356        });
357        let held = self
358            .held
359            .as_mut()
360            .filter(|_| active)
361            .map(|held| held.until.as_mut());
362
363        let wake = tokio::select! {
364            biased;
365            () = optional(heartbeat) => Wake::Heartbeat,
366            () = optional(hello) => Wake::HelloTimeout,
367            () = optional(identify) => Wake::Identify,
368            () = optional(held) => Wake::HeldCommandAllowed,
369            Some(command) = self.commands_rx.recv(), if receive_commands => Wake::Command(command),
370            message = connection.next() => Wake::Message(message),
371        };
372
373        match wake {
374            Wake::Heartbeat => self.heartbeat_due().await.err().map(Err),
375            Wake::HelloTimeout => {
376                tracing::warn!(shard = %self.id, "no Hello received in time, reconnecting");
377                self.disconnect(true).await;
378                None
379            }
380            Wake::Identify => {
381                self.identify_turn = None;
382                self.identify().await.err().map(Err)
383            }
384            Wake::Command(json) => self.send_limited(json).await.err().map(Err),
385            Wake::HeldCommandAllowed => match self.held.take() {
386                Some(held) => self.send_limited(held.json).await.err().map(Err),
387                None => None,
388            },
389            Wake::Message(None) => {
390                tracing::info!(shard = %self.id, "connection ended without a close frame, reconnecting");
391                self.disconnect(true).await;
392                None
393            }
394            Wake::Message(Some(Err(error))) => {
395                self.disconnect(true).await;
396                Some(Err(ReceiveError::with_source(
397                    ReceiveErrorKind::Connection,
398                    error,
399                )))
400            }
401            Wake::Message(Some(Ok(message))) => self.handle_message(&message).await,
402        }
403    }
404
405    async fn handle_message(
406        &mut self,
407        message: &Message,
408    ) -> Option<Result<GatewayEvent, ReceiveError>> {
409        if let Some((code, reason)) = message.as_close() {
410            let code = u16::from(code);
411            let reason = reason.to_owned();
412            return self.handle_close(Some(code), &reason);
413        }
414        if message.is_close() {
415            return self.handle_close(None, "");
416        }
417
418        let (sequence, parsed) = if let Some(json) = message.as_text() {
419            parse(json)
420        } else if message.is_binary() {
421            let Some(decompressor) = self.decompressor.as_mut() else {
422                tracing::warn!(shard = %self.id, "binary message received without compression, ignoring");
423                return None;
424            };
425            match decompressor.decompress(message.as_payload()) {
426                // The start of a payload split over several messages.
427                Ok(None) => return None,
428                Ok(Some(bytes)) => match core::str::from_utf8(bytes) {
429                    Ok(json) => parse(json),
430                    Err(error) => (
431                        None,
432                        Err(ReceiveError::with_source(
433                            ReceiveErrorKind::Deserialize,
434                            error,
435                        )),
436                    ),
437                },
438                Err(error) => {
439                    let error = ReceiveError::with_source(ReceiveErrorKind::Decompress, error);
440                    self.disconnect(true).await;
441                    return Some(Err(error));
442                }
443            }
444        } else {
445            // Ping/pong frames are answered by the WebSocket library.
446            return None;
447        };
448
449        if let Some(sequence) = sequence {
450            self.sequence = Some(sequence);
451        }
452        match parsed {
453            Ok(event) => match self.process(&event).await {
454                Ok(()) => Some(Ok(event)),
455                Err(error) => Some(Err(error)),
456            },
457            Err(error) => {
458                tracing::warn!(shard = %self.id, %error, "skipping a gateway payload that failed to parse");
459                Some(Err(error))
460            }
461        }
462    }
463
464    /// Updates the shard state for an event and performs the required actions.
465    async fn process(&mut self, event: &GatewayEvent) -> Result<(), ReceiveError> {
466        match event {
467            GatewayEvent::Hello(hello) => {
468                self.hello_deadline = None;
469                let interval = Duration::from_millis(hello.heartbeat_interval);
470                // The first heartbeat is sent after `interval * jitter` (jitter in [0, 1)).
471                let first = interval.mul_f64(fastrand::f64());
472                self.heartbeat = Some(Heartbeater {
473                    interval,
474                    sleep: Box::pin(sleep(first)),
475                    last_sent: None,
476                    acked: true,
477                });
478                if self.session.is_some() && self.sequence.is_some() {
479                    self.resume().await?;
480                } else {
481                    self.schedule_identify();
482                }
483            }
484            GatewayEvent::HeartbeatAck => {
485                if let Some(heartbeat) = self.heartbeat.as_mut() {
486                    heartbeat.acked = true;
487                    if let Some(sent) = heartbeat.last_sent {
488                        self.latency = Some(sent.elapsed());
489                    }
490                }
491            }
492            GatewayEvent::Heartbeat => self.send_heartbeat().await?,
493            GatewayEvent::Reconnect => {
494                tracing::info!(shard = %self.id, "Discord requested a reconnect");
495                self.disconnect(true).await;
496            }
497            GatewayEvent::InvalidSession(resumable) => {
498                tracing::info!(shard = %self.id, resumable, "session invalidated");
499                self.disconnect(*resumable).await;
500                // Discord recommends waiting a random 1–5 seconds before reconnecting.
501                self.connect_after =
502                    Some(Instant::now() + Duration::from_millis(fastrand::u64(1_000..=5_000)));
503            }
504            GatewayEvent::Dispatch(_, DispatchEvent::Ready(ready)) => {
505                self.session = Some(Session {
506                    id: ready.session_id.as_str().into(),
507                    resume_url: ready.resume_gateway_url.as_str().into(),
508                });
509                self.state = ShardState::Active;
510                self.reconnect_attempts = 0;
511                tracing::info!(shard = %self.id, user = %ready.user.username, guilds = ready.guilds.len(), "session ready");
512            }
513            GatewayEvent::Dispatch(_, DispatchEvent::Resumed) => {
514                self.state = ShardState::Active;
515                self.reconnect_attempts = 0;
516                tracing::info!(shard = %self.id, "session resumed");
517            }
518            _ => {}
519        }
520        Ok(())
521    }
522
523    fn handle_close(
524        &mut self,
525        code: Option<u16>,
526        reason: &str,
527    ) -> Option<Result<GatewayEvent, ReceiveError>> {
528        tracing::info!(shard = %self.id, code, reason, "gateway closed the connection");
529        self.connection = None;
530        self.reset_connection();
531
532        if let Some(code) = code.filter(|code| (4000..5000).contains(code)) {
533            let code = CloseCode::from(code);
534            if !code.can_reconnect() {
535                tracing::error!(shard = %self.id, ?code, "fatal close code, the shard will stop");
536                self.state = ShardState::FatallyClosed(code);
537                return Some(Err(ReceiveError::new(ReceiveErrorKind::FatallyClosed {
538                    code,
539                })));
540            }
541            if matches!(
542                code,
543                CloseCode::InvalidSequence | CloseCode::SessionTimedOut
544            ) {
545                self.session = None;
546                self.sequence = None;
547            }
548        }
549        None
550    }
551
552    async fn connect(&mut self) -> Result<(), ReceiveError> {
553        let base = match (&self.session, self.sequence) {
554            (Some(session), Some(_)) => &*session.resume_url,
555            _ => &*self.config.gateway_url,
556        };
557        let mut url = String::with_capacity(base.len() + 48);
558        url.push_str(base.trim_end_matches('/'));
559        let _ = write!(url, "/?v={API_VERSION}&encoding=json");
560        if let Some(compression) = self.config.compression.query_value() {
561            let _ = write!(url, "&compress={compression}");
562        }
563
564        tracing::debug!(shard = %self.id, %url, "connecting to the gateway");
565        let builder = ClientBuilder::new()
566            .uri(&url)
567            .map_err(|error| ReceiveError::with_source(ReceiveErrorKind::Connect, error))?
568            .connector(&self.config.tls)
569            .limits(Limits::unlimited());
570        let (connection, _) = tokio::time::timeout(self.config.connect_timeout, builder.connect())
571            .await
572            .map_err(|_| {
573                ReceiveError::with_source(ReceiveErrorKind::Connect, "connection timed out")
574            })?
575            .map_err(|error| ReceiveError::with_source(ReceiveErrorKind::Connect, error))?;
576
577        self.decompressor = Decompressor::new(self.config.compression)
578            .map_err(|error| ReceiveError::with_source(ReceiveErrorKind::Connect, error))?;
579        self.connection = Some(connection);
580        self.hello_deadline = Some(Box::pin(sleep(self.config.hello_timeout)));
581        tracing::info!(shard = %self.id, "connected to the gateway");
582        Ok(())
583    }
584
585    /// Schedules the next connection attempt with exponential backoff and jitter.
586    fn schedule_reconnect(&mut self) {
587        self.reconnect_attempts = self.reconnect_attempts.saturating_add(1);
588        let exponent = self.reconnect_attempts.saturating_sub(1).min(6);
589        let delay = Duration::from_secs(1 << exponent).min(MAX_BACKOFF);
590        let delay = delay.mul_f64(0.5 + fastrand::f64() / 2.0);
591        tracing::warn!(
592            shard = %self.id,
593            attempt = self.reconnect_attempts,
594            delay_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
595            "connecting failed, retrying after a delay"
596        );
597        self.connect_after = Some(Instant::now() + delay);
598    }
599
600    /// Queues for an IDENTIFY turn; the shard identifies when the queue lets it.
601    fn schedule_identify(&mut self) {
602        self.identify_turn = Some(Mutex::new(self.config.identify_queue.wait_turn(self.id)));
603        self.state = ShardState::Identifying;
604    }
605
606    async fn identify(&mut self) -> Result<(), ReceiveError> {
607        let identify = Identify {
608            token: (*self.config.token).into(),
609            properties: self.config.properties.clone(),
610            large_threshold: self.config.large_threshold,
611            shard: Some(self.id),
612            intents: self.config.intents,
613            presence: self
614                .presence
615                .lock()
616                .unwrap_or_else(PoisonError::into_inner)
617                .clone(),
618            capabilities: GatewayCapabilities::empty(),
619        };
620        self.state = ShardState::Identifying;
621        tracing::debug!(shard = %self.id, "identifying");
622        self.send_command(&identify).await
623    }
624
625    async fn resume(&mut self) -> Result<(), ReceiveError> {
626        let (Some(session), Some(seq)) = (&self.session, self.sequence) else {
627            return Ok(());
628        };
629        let resume = Resume {
630            token: (*self.config.token).into(),
631            session_id: (*session.id).into(),
632            seq,
633        };
634        self.state = ShardState::Resuming;
635        tracing::debug!(shard = %self.id, seq, "resuming");
636        self.send_command(&resume).await
637    }
638
639    async fn heartbeat_due(&mut self) -> Result<(), ReceiveError> {
640        if self
641            .heartbeat
642            .as_ref()
643            .is_some_and(|heartbeat| !heartbeat.acked)
644        {
645            tracing::warn!(shard = %self.id, "no heartbeat ACK received (zombied connection), reconnecting");
646            self.disconnect(true).await;
647            return Ok(());
648        }
649        self.send_heartbeat().await
650    }
651
652    async fn send_heartbeat(&mut self) -> Result<(), ReceiveError> {
653        let sequence = self.sequence;
654        if let Some(heartbeat) = self.heartbeat.as_mut() {
655            let now = Instant::now();
656            heartbeat.last_sent = Some(now);
657            heartbeat.acked = false;
658            heartbeat.sleep.as_mut().reset(now + heartbeat.interval);
659        }
660        self.send_command(&Heartbeat(sequence)).await
661    }
662
663    async fn send_command<T: GatewayCommand>(&mut self, command: &T) -> Result<(), ReceiveError> {
664        let json = serde_json::to_string(&CommandPayload::new(command))
665            .expect("gateway commands always serialize");
666        self.send(json).await
667    }
668
669    /// Sends a queued command if the send limit allows it, or holds it until it does.
670    async fn send_limited(&mut self, json: String) -> Result<(), ReceiveError> {
671        match self.send_limit.try_acquire(Instant::now()) {
672            Ok(()) => self.send(json).await,
673            Err(at) => {
674                tracing::debug!(shard = %self.id, "gateway send limit reached, holding queued commands");
675                self.held = Some(HeldCommand {
676                    json,
677                    until: Box::pin(sleep_until(at)),
678                });
679                Ok(())
680            }
681        }
682    }
683
684    /// Writes a payload, bypassing the send limit (used directly only for heartbeats, identify
685    /// and resume, which the limit leaves room for).
686    async fn send(&mut self, json: String) -> Result<(), ReceiveError> {
687        let Some(connection) = self.connection.as_mut() else {
688            return Ok(());
689        };
690        if let Err(error) = connection.send(Message::text(json)).await {
691            self.disconnect(true).await;
692            return Err(ReceiveError::with_source(
693                ReceiveErrorKind::Connection,
694                error,
695            ));
696        }
697        Ok(())
698    }
699
700    /// Drops the connection. With `resume`, the session is kept so the next connection resumes
701    /// it; otherwise the next connection identifies from scratch.
702    async fn disconnect(&mut self, resume: bool) {
703        if let Some(mut connection) = self.connection.take() {
704            let code = tokio_websockets::CloseCode::try_from(RESUMABLE_CLOSE_CODE).ok();
705            let _ = tokio::time::timeout(CLOSE_TIMEOUT, connection.send(Message::close(code, "")))
706                .await;
707        }
708        self.reset_connection();
709        if !resume {
710            self.session = None;
711            self.sequence = None;
712        }
713    }
714
715    /// Clears all per-connection state.
716    fn reset_connection(&mut self) {
717        self.connection = None;
718        self.decompressor = None;
719        self.heartbeat = None;
720        self.hello_deadline = None;
721        // Leaves the IDENTIFY queue; the next connection queues again.
722        self.identify_turn = None;
723        self.state = ShardState::Disconnected;
724        // The send limit is per connection: a held command may go out as soon as the next
725        // session is active.
726        self.send_limit.clear();
727        if let Some(held) = self.held.as_mut() {
728            held.until.as_mut().reset(Instant::now());
729        }
730    }
731}
732
733/// Waits on an optional timer or turn; never completes if there is none.
734async fn optional<F: Future<Output = ()> + ?Sized>(future: Option<Pin<&mut F>>) {
735    match future {
736        Some(future) => future.await,
737        None => core::future::pending().await,
738    }
739}
740
741/// Decodes a JSON gateway payload. Also returns the dispatch sequence number, which must be
742/// tracked even if the payload itself fails to deserialize.
743fn parse(json: &str) -> (Option<u64>, Result<GatewayEvent, ReceiveError>) {
744    let Some(seed) = GatewayEventDeserializer::from_json(json) else {
745        return (
746            None,
747            Err(ReceiveError::with_source(
748                ReceiveErrorKind::Deserialize,
749                "payload has no valid `op` field",
750            )),
751        );
752    };
753    let sequence = (seed.op() == OpCode::Dispatch)
754        .then(|| seed.sequence())
755        .flatten();
756    let mut deserializer = serde_json::Deserializer::from_str(json);
757    let result = seed
758        .deserialize(&mut deserializer)
759        .map_err(|error| ReceiveError::with_source(ReceiveErrorKind::Deserialize, error));
760    (sequence, result)
761}
762
763/// Sends commands to a [`Shard`] from any task. Cheap to clone.
764///
765/// Commands are queued and written by the shard, in order, once its session is active.
766///
767/// # Send limit
768///
769/// Discord accepts [120 payloads per connection every 60 seconds][limit] and disconnects a
770/// client that sends more. The shard therefore sends at most **115** queued commands in any
771/// 61-second span (one second of margin for network jitter); the rest wait in the queue and
772/// go out as soon as the limit allows, so [`command`](Self::command) never blocks or fails
773/// because of it. The remaining room is kept for heartbeats, identify and resume, which are
774/// never held back. A new connection starts with a fresh limit.
775///
776/// discord.js counterpart: `WebSocketShard#send` from `@discordjs/ws`, which paces payloads
777/// the same way.
778///
779/// [limit]: https://docs.discord.com/developers/events/gateway#rate-limiting
780#[derive(Clone, Debug)]
781pub struct MessageSender {
782    tx: mpsc::UnboundedSender<String>,
783    presence: SharedPresence,
784}
785
786impl MessageSender {
787    /// Returns a sender connected to no shard: every command fails with
788    /// [`SendError::Closed`].
789    ///
790    /// For code that needs a sender where no shard runs, such as the context of an HTTP
791    /// interaction in djs-rs (D-403).
792    ///
793    /// discord.js counterpart: none.
794    ///
795    /// # Examples
796    ///
797    /// ```
798    /// use djs_gateway::{MessageSender, SendError};
799    /// use djs_model::gateway::{Activity, Status, payload::UpdatePresence};
800    ///
801    /// let presence = UpdatePresence::new(Status::Idle, [Activity::custom("Resting")]);
802    /// let result = MessageSender::detached().update_presence(&presence);
803    /// assert!(matches!(result, Err(SendError::Closed)));
804    /// ```
805    #[must_use]
806    pub fn detached() -> Self {
807        Self {
808            tx: mpsc::unbounded_channel().0,
809            presence: SharedPresence::default(),
810        }
811    }
812
813    /// Queues a command.
814    ///
815    /// discord.js counterpart: `WebSocketShard#send` (`@discordjs/ws`).
816    ///
817    /// # Errors
818    ///
819    /// Returns [`SendError::Closed`] if the shard has been dropped, or
820    /// [`SendError::Serialize`] if the command cannot be serialized.
821    pub fn command<T: GatewayCommand>(&self, command: &T) -> Result<(), SendError> {
822        let json =
823            serde_json::to_string(&CommandPayload::new(command)).map_err(SendError::Serialize)?;
824        self.tx.send(json).map_err(|_| SendError::Closed)
825    }
826
827    /// Updates the bot's presence on this shard, and makes it the presence the shard identifies
828    /// with from now on, so a new session keeps it (D-148).
829    ///
830    /// Prefer this over [`command`](Self::command) with an [`UpdatePresence`], which only sends
831    /// the update: after a new session the shard would show its configured
832    /// [presence](crate::ConfigBuilder::presence) again.
833    ///
834    /// discord.js counterpart: `ClientUser#setPresence` (which, unlike this method, is
835    /// forgotten when a new session starts).
836    ///
837    /// # Errors
838    ///
839    /// Returns [`SendError::Closed`] if the shard has been dropped, or
840    /// [`SendError::Serialize`] if the presence cannot be serialized.
841    ///
842    /// # Examples
843    ///
844    /// ```
845    /// use djs_gateway::Shard;
846    /// use djs_model::gateway::{Activity, Intents, ShardId, Status, payload::UpdatePresence};
847    ///
848    /// let shard = Shard::new(ShardId::ONE, "my-token", Intents::GUILDS);
849    /// shard
850    ///     .sender()
851    ///     .update_presence(&UpdatePresence::new(Status::Idle, [Activity::custom("Resting")]))
852    ///     .unwrap();
853    /// ```
854    pub fn update_presence(&self, presence: &UpdatePresence) -> Result<(), SendError> {
855        self.command(presence)?;
856        *self.presence.lock().unwrap_or_else(PoisonError::into_inner) = Some(presence.clone());
857        Ok(())
858    }
859
860    /// Returns `true` if the shard has been dropped.
861    ///
862    /// discord.js counterpart: none (`@discordjs/ws` throws when sending on a destroyed shard).
863    #[must_use]
864    pub fn is_closed(&self) -> bool {
865        self.tx.is_closed()
866    }
867}
868
869// Shards and senders move between tasks and threads; keep them `Send + Sync`.
870const _: () = {
871    const fn assert_send_sync<T: Send + Sync>() {}
872    assert_send_sync::<Shard>();
873    assert_send_sync::<MessageSender>();
874    assert_send_sync::<crate::Config>();
875};