Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

32.9 KB
Raw Blame
//! Discord gateway (WebSocket) connection with heartbeating, resume and
//! reconnect-with-backoff.
//!
//! IDENTIFY sends the web client's `capabilities`
//! ([`crate::fingerprint::CAPABILITIES`]): a set of switches, each asking for
//! a newer form of READY or of the events after it. What they change for
//! RustCord (names from the community's documentation; Discord publishes none):
//!
//! | bit | name | what changes |
//! |---|---|---|
//! | 0 | LAZY_USER_NOTES | READY has no `notes` (they are read per profile) |
//! | 2, 3 | VERSIONED_READ_STATES, VERSIONED_USER_GUILD_SETTINGS | `read_state` and `user_guild_settings` are `{version, partial, entries}` |
//! | 4 | DEDUPE_USER_OBJECTS | everyone is listed once in READY's `users` and named by ID elsewhere; your own members are in `merged_members`; a server's details are under `properties` |
//! | 5 | PRIORITIZED_READY_PAYLOAD | presences, voice states and other members follow in READY_SUPPLEMENTAL |
//! | 6 | MULTIPLE_GUILD_EXPERIMENT_POPULATIONS | (experiments aren't read) |
//! | 7 | NON_CHANNEL_READ_STATES | `read_state` has entries that aren't channels (`read_state_type`) |
//! | 8 | AUTH_TOKEN_REFRESH | READY may carry a new login token ([`GatewayEvent::TokenRefreshed`]) |
//! | 9 | USER_SETTINGS_PROTO | settings come as `user_settings_proto` only |
//! | 10 | CLIENT_STATE_V2 | IDENTIFY's `client_state` (nothing is kept between sessions: sent empty) |
//! | 12 | AUTO_CALL_CONNECT | CALL_CREATE for calls already going on, unasked |
//! | 13 | DEBOUNCE_MESSAGE_REACTIONS | MESSAGE_REACTION_ADD_MANY |
//! | 14 | PASSIVE_GUILD_UPDATE_V2 | PASSIVE_UPDATE_V2 for servers that aren't open |
//! | 15 | CHANNEL_OBFUSCATION | channels you can't see come without their names |
//! | 17, 19, 20 | (undocumented) | nothing seen to change |
//!
//! A READY that isn't in that form (Discord changed it) makes the session
//! start over without capabilities, for the classic READY, which is still read.

use futures_util::{SinkExt, StreamExt};
use serde::Deserialize;
use serde_json::value::RawValue;
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::time::Instant;
use tokio_tungstenite::tungstenite::Message as WsMessage;

pub const GATEWAY_URL: &str = "wss://gateway.discord.gg";

/// Commands queued while there's no live session (before READY, or during
/// a reconnect backoff) are sent once there is one; older ones are dropped.
const MAX_PENDING: usize = 64;

#[derive(Debug)]
pub enum GatewayEvent {
    Connecting,
    /// READY or RESUMED received.
    Connected,
    Dispatch { name: String, data: Value },
    /// READY brought a new login token: the old one is to be dropped, here
    /// (the gateway itself already uses the new one) and wherever it is kept.
    TokenRefreshed(String),
    Disconnected { reason: String },
    /// Close code 4004: the token is invalid. The loop stops.
    AuthFailed,
    /// Unrecoverable close code. The loop stops.
    Fatal(String),
}

#[derive(Debug)]
pub enum GatewayCommand {
    Send(Value),
    Shutdown,
}

enum SessionEnd {
    Reconnect(String),
    AuthFailed,
    Fatal(String),
    Shutdown,
}

/// Is this an address the login token may be sent to (RESUME carries it)?
/// Only Discord's own gateways, over TLS: `wss://` on discord.gg.
fn is_discord_gateway(url: &str) -> bool {
    let Some(rest) = url.strip_prefix("wss://") else { return false };
    let host = rest.split(['/', '?', ':']).next().unwrap_or_default().to_ascii_lowercase();
    host == "discord.gg" || host.ends_with(".discord.gg")
}

#[derive(Default)]
struct SessionState {
    /// The login token (replaced when READY brings a new one).
    token: String,
    /// A READY asked for with capabilities couldn't be read: until the app
    /// restarts, sessions ask for the classic one.
    classic: bool,
    session_id: Option<String>,
    resume_url: Option<String>,
    seq: Option<u64>,
    backoff: u64,
    /// Payloads to send as soon as a session is up (see [`MAX_PENDING`]).
    pending: Vec<Value>,
    /// What the app sent last (op, size, start of it), to name the culprit
    /// when Discord closes with 4002 "decode error". Never IDENTIFY/RESUME
    /// (they hold the token).
    recent: std::collections::VecDeque<(u64, usize, String)>,
}

/// Gateway payloads over this many bytes are refused with close code 4002.
const MAX_PAYLOAD: usize = 4096;

impl SessionState {
    /// Note an app payload going out; returns its text, or None (with a
    /// warning) if it's too big for Discord, which would end the session.
    fn outgoing(&mut self, v: &Value) -> Option<String> {
        let text = v.to_string();
        let op = v["op"].as_u64().unwrap_or(0);
        if text.len() > MAX_PAYLOAD {
            log::warn!("gateway: not sending op {op}: {} bytes is over Discord's {MAX_PAYLOAD}-byte limit", text.len());
            return None;
        }
        if self.recent.len() >= 6 {
            self.recent.pop_front();
        }
        let preview: String = text.chars().take(240).collect();
        self.recent.push_back((op, text.len(), preview));
        Some(text)
    }

    fn queue(&mut self, v: Value) {
        if self.pending.len() >= MAX_PENDING {
            self.pending.remove(0);
        }
        self.pending.push(v);
    }
}

/// Presence object for IDENTIFY and op 3. Custom status is activity type 4.
/// Presence for IDENTIFY / op 3. A custom emoji must carry its ID (a bare
/// custom-emoji name isn't a valid emoji and Discord drops the connection).
pub fn presence_payload(status: &str, custom: Option<&crate::settings_proto::CustomStatus>) -> Value {
    let mut activities = Vec::new();
    if let Some(c) = custom.filter(|c| status != "invisible" && (!c.text.is_empty() || c.emoji_name.is_some() || c.emoji_id.is_some())) {
        let mut a = json!({ "name": "Custom Status", "type": 4 });
        if !c.text.is_empty() {
            a["state"] = json!(c.text);
        }
        match (c.emoji_id, c.emoji_name.as_deref()) {
            (Some(id), name) => a["emoji"] = json!({ "id": id.to_string(), "name": name.unwrap_or("emoji"), "animated": false }),
            (None, Some(name)) => a["emoji"] = json!({ "name": name }),
            (None, None) => {}
        }
        activities.push(a);
    }
    json!({ "status": status, "since": 0, "activities": activities, "afk": false })
}

/// Op 3: change your presence on the live session.
pub fn presence_update(presence: Value) -> GatewayCommand {
    GatewayCommand::Send(json!({ "op": 3, "d": presence }))
}

/// Run the gateway until `Shutdown`, an auth failure or a fatal close.
pub async fn run<F>(token: String, presence: Value, mut cmds: UnboundedReceiver<GatewayCommand>, emit: F)
where
    F: Fn(GatewayEvent) + Send + Sync + 'static,
{
    let mut state = SessionState {
        token,
        backoff: 1,
        ..Default::default()
    };
    loop {
        emit(GatewayEvent::Connecting);
        let base = match (&state.session_id, &state.resume_url) {
            (Some(_), Some(url)) => url.clone(),
            _ => GATEWAY_URL.to_string(),
        };
        // As Discord's web client builds it in a browser (zstd-stream is only
        // for its desktop app): one deflate stream per connection.
        let url = format!("{}/?encoding=json&v=9&compress=zlib-stream", base.trim_end_matches('/'));

        match session(&presence, &url, &mut state, &mut cmds, &emit).await {
            SessionEnd::Shutdown => return,
            SessionEnd::AuthFailed => {
                emit(GatewayEvent::AuthFailed);
                return;
            }
            SessionEnd::Fatal(e) => {
                emit(GatewayEvent::Fatal(e));
                return;
            }
            SessionEnd::Reconnect(reason) => {
                log::info!("gateway disconnected: {reason}");
                emit(GatewayEvent::Disconnected { reason });
            }
        }

        // Back off, keeping whatever the app asks for meanwhile (member list
        // subscriptions, voice state…) for the next session.
        let deadline = Instant::now() + Duration::from_secs(state.backoff);
        loop {
            tokio::select! {
                _ = tokio::time::sleep_until(deadline) => break,
                cmd = cmds.recv() => match cmd {
                    Some(GatewayCommand::Send(v)) => state.queue(v),
                    Some(GatewayCommand::Shutdown) | None => return,
                },
            }
        }
        state.backoff = (state.backoff * 2).min(60);
    }
}

/// The `capabilities` IDENTIFY sends (0: none, the classic READY).
static CAPABILITIES: AtomicU64 = AtomicU64::new(crate::fingerprint::CAPABILITIES);

/// Developer override of the capabilities sent with IDENTIFY (`None`: none).
pub fn set_capabilities(capabilities: Option<u64>) {
    CAPABILITIES.store(capabilities.unwrap_or(0), Ordering::Relaxed);
}

/// The capabilities to identify with, if any.
fn capabilities(classic: bool) -> Option<u64> {
    let c = CAPABILITIES.load(Ordering::Relaxed);
    (!classic && c != 0).then_some(c)
}

/// IDENTIFY like Discord's web client: same properties as the REST
/// X-Super-Properties, and its capabilities (see the module's table).
fn identify(token: &str, presence: &Value, capabilities: Option<u64>) -> Value {
    let mut d = json!({
        "token": token,
        "properties": crate::fingerprint::properties(),
        "presence": presence,
        "compress": false,
    });
    if let Some(capabilities) = capabilities {
        d["capabilities"] = json!(capabilities);
        // Nothing is kept from an earlier session: everything comes in full.
        d["client_state"] = json!({ "guild_versions": {} });
    }
    json!({ "op": 2, "d": d })
}

/// Is this READY in the form the capabilities ask for: everyone listed once,
/// and a list of your own members for each server?
fn is_compact(ready: &Value) -> bool {
    let count = |key: &str| ready[key].as_array().map_or(0, Vec::len);
    ready["users"].is_array() && ready["guilds"].is_array() && count("guilds") == count("merged_members")
}

/// The new login token a READY carries, taken out of it (READY goes on to the
/// app, which keeps a copy on disk).
fn take_auth_token(ready: &mut Value) -> Option<String> {
    match ready.as_object_mut()?.remove("auth_token")? {
        Value::String(token) if !token.is_empty() => Some(token),
        _ => None,
    }
}

fn jitter(max_ms: u64) -> u64 {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    nanos % max_ms.max(1)
}

/// Each zlib-stream message ends with an empty sync flush.
const ZLIB_SUFFIX: [u8; 4] = [0, 0, 0xff, 0xff];

/// Inflate one complete zlib-stream message (the context carries over).
fn inflate(z: &mut flate2::Decompress, input: &[u8]) -> Option<String> {
    let mut out: Vec<u8> = Vec::with_capacity(input.len() * 8);
    let mut pos = 0;
    loop {
        if out.len() == out.capacity() {
            out.reserve(out.capacity().max(64 * 1024));
        }
        let before = z.total_in();
        let status = z.decompress_vec(&input[pos..], &mut out, flate2::FlushDecompress::Sync).ok()?;
        pos += (z.total_in() - before) as usize;
        if status == flate2::Status::StreamEnd || (pos >= input.len() && out.len() < out.capacity()) {
            break;
        }
    }
    String::from_utf8(out).ok()
}

/// Text of a gateway message: plain, or a finished zlib-stream chunk.
/// None while a compressed message is still arriving in pieces.
fn message_text(msg: WsMessage, z: &mut flate2::Decompress, buf: &mut Vec<u8>) -> Result<Option<String>, String> {
    match msg {
        WsMessage::Text(t) => Ok(Some(t)),
        WsMessage::Binary(b) => {
            buf.extend_from_slice(&b);
            if !buf.ends_with(&ZLIB_SUFFIX) {
                return Ok(None);
            }
            let text = inflate(z, buf);
            buf.clear();
            text.map(Some).ok_or_else(|| "couldn't decompress a gateway message".to_string())
        }
        _ => Ok(None),
    }
}

/// A gateway payload with `d` left unparsed, so READY can take the lean path.
#[derive(Deserialize)]
struct Envelope<'a> {
    op: u64,
    #[serde(default)]
    s: Option<u64>,
    #[serde(default)]
    t: Option<String>,
    #[serde(borrow, default)]
    d: Option<&'a RawValue>,
}

struct Payload {
    op: u64,
    seq: Option<u64>,
    name: Option<String>,
    data: Value,
}

/// Parse a payload. READY (tens of MB on a big account) keeps only the parts
/// RustCord reads; everything else is skipped without being built in memory.
fn parse_payload(text: &str) -> Result<Payload, serde_json::Error> {
    let env: Envelope = serde_json::from_str(text)?;
    let data = match env.d {
        None => Value::Null,
        Some(raw) if env.op == 0 && env.t.as_deref() == Some("READY") => ready_lite::parse(raw.get())?,
        Some(raw) => serde_json::from_str(raw.get())?,
    };
    Ok(Payload { op: env.op, seq: env.s, name: env.t, data })
}

/// READY carries a lot a client never needs (experiments, notification
/// settings, tutorial state, analytics tokens…). Parsing it all into a
/// `Value` costs several times the JSON's size in RAM and a good part of
/// the time between connecting and seeing the account. This parses only an
/// allowlist of keys, skipping the rest in the deserializer (no allocation).
mod ready_lite {
    use serde::de::{DeserializeSeed, Deserializer, IgnoredAny, MapAccess, SeqAccess, Visitor};
    use serde_json::{Map, Value};
    use std::fmt;

    /// Keys of an object to keep; `nested` keys hold arrays of objects that
    /// are filtered with their own `Keep`.
    pub struct Keep {
        keys: &'static [&'static str],
        nested: &'static [(&'static str, &'static Keep)],
    }

    static GUILD: Keep = Keep {
        keys: &[
            "id", "name", "icon", "owner_id", "roles", "emojis", "stickers", "channels", "unavailable", "properties",
            "members", "presences", "voice_states",
            // Boost level / count and banner: top-level on user READY guilds
            // (the channel list header and Server Boosts page need them).
            "premium_subscription_count", "premium_tier", "banner", "features", "premium_progress_bar_enabled",
            // What the server spent Boosts on (Server Boosts page: "Spent").
            "premium_features",
            // The server's tag (server dropdown → Server Tag).
            "profile",
        ],
        nested: &[],
    };

    pub static READY: Keep = Keep {
        keys: &[
            "user", "private_channels", "users", "relationships", "read_state", "user_guild_settings", "user_settings",
            "user_settings_proto", "merged_members", "merged_presences", "presences", "sessions", "session_id",
            "resume_gateway_url", "auth_token",
        ],
        nested: &[("guilds", &GUILD)],
    };

    pub fn parse(json: &str) -> Result<Value, serde_json::Error> {
        let mut de = serde_json::Deserializer::from_str(json);
        let v = (&READY).deserialize(&mut de)?;
        de.end()?;
        Ok(v)
    }

    impl<'de> DeserializeSeed<'de> for &'static Keep {
        type Value = Value;
        fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
            d.deserialize_any(ObjectVisitor(self))
        }
    }

    struct ObjectVisitor(&'static Keep);

    impl<'de> Visitor<'de> for ObjectVisitor {
        type Value = Value;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("an object")
        }

        fn visit_unit<E: serde::de::Error>(self) -> Result<Value, E> {
            Ok(Value::Null)
        }

        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
            let mut out = Map::new();
            while let Some(key) = map.next_key::<String>()? {
                if let Some((_, sub)) = self.0.nested.iter().find(|(k, _)| *k == key) {
                    out.insert(key, map.next_value_seed(ArrayOf(sub))?);
                } else if self.0.keys.contains(&key.as_str()) {
                    out.insert(key, map.next_value::<Value>()?);
                } else {
                    map.next_value::<IgnoredAny>()?;
                }
            }
            Ok(Value::Object(out))
        }
    }

    struct ArrayOf(&'static Keep);

    impl<'de> DeserializeSeed<'de> for ArrayOf {
        type Value = Value;
        fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
            d.deserialize_any(ArrayVisitor(self.0))
        }
    }

    struct ArrayVisitor(&'static Keep);

    impl<'de> Visitor<'de> for ArrayVisitor {
        type Value = Value;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("an array of objects")
        }

        fn visit_unit<E: serde::de::Error>(self) -> Result<Value, E> {
            Ok(Value::Null)
        }

        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
            let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
            while let Some(v) = seq.next_element_seed(self.0)? {
                out.push(v);
            }
            Ok(Value::Array(out))
        }
    }
}

async fn session<F>(
    presence: &Value,
    url: &str,
    st: &mut SessionState,
    cmds: &mut UnboundedReceiver<GatewayCommand>,
    emit: &F,
) -> SessionEnd
where
    F: Fn(GatewayEvent) + Send + Sync,
{
    // Big accounts get a READY of tens of MB without compression.
    let mut config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default();
    config.max_message_size = Some(256 << 20);
    config.max_frame_size = Some(256 << 20);
    // Opened like the web client's socket: same user agent and origin as
    // every REST request, not a bare handshake that no browser makes.
    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
    use tokio_tungstenite::tungstenite::http::HeaderValue;
    let mut request = match url.into_client_request() {
        Ok(r) => r,
        Err(e) => return SessionEnd::Reconnect(format!("bad gateway address: {e}")),
    };
    for (name, value) in crate::fingerprint::websocket_headers() {
        if let Ok(v) = HeaderValue::from_str(&value) {
            request.headers_mut().insert(name, v);
        }
    }
    let ws = match tokio_tungstenite::connect_async_with_config(request, Some(config), false).await {
        Ok((ws, _)) => ws,
        Err(e) => return SessionEnd::Reconnect(format!("couldn't connect: {e}")),
    };
    let (mut tx, mut rx) = ws.split();
    let mut zlib = flate2::Decompress::new(true);
    let mut zbuf: Vec<u8> = Vec::new();

    // Op 10 Hello.
    let interval = loop {
        match tokio::time::timeout(Duration::from_secs(20), rx.next()).await {
            Ok(Some(Ok(msg))) => match message_text(msg, &mut zlib, &mut zbuf) {
                Ok(Some(t)) => {
                    let v: Value = serde_json::from_str(&t).unwrap_or_default();
                    if v["op"].as_u64() == Some(10) {
                        break v["d"]["heartbeat_interval"].as_u64().unwrap_or(41_250);
                    }
                }
                Ok(None) => continue,
                Err(e) => return SessionEnd::Reconnect(e),
            },
            _ => return SessionEnd::Reconnect("no hello from gateway".into()),
        }
    };

    // (Set when this connection identifies with capabilities: its READY is checked.)
    let mut compact = false;
    let hello_reply = match (&st.session_id, st.seq) {
        (Some(sid), Some(seq)) => json!({
            "op": 6,
            "d": { "token": st.token, "session_id": sid, "seq": seq }
        }),
        _ => {
            let capabilities = capabilities(st.classic);
            compact = capabilities.is_some();
            identify(&st.token, presence, capabilities)
        }
    };
    if tx.send(WsMessage::Text(hello_reply.to_string())).await.is_err() {
        return SessionEnd::Reconnect("failed to identify".into());
    }
    // (When a login is refused, the log shows how long after this Discord answered.)
    log::info!("gateway: sent {}", if hello_reply["op"] == 6 { "RESUME" } else { "IDENTIFY" });

    let mut next_heartbeat = Instant::now() + Duration::from_millis(jitter(interval));
    let mut acked = true;
    // Nothing but heartbeats goes out before READY / RESUMED: the app's
    // requests wait in `st.pending` until the session is up.
    let mut connected = false;

    loop {
        tokio::select! {
            _ = tokio::time::sleep_until(next_heartbeat) => {
                if !acked {
                    return SessionEnd::Reconnect("heartbeat not acknowledged".into());
                }
                acked = false;
                let hb = json!({ "op": 1, "d": st.seq });
                if tx.send(WsMessage::Text(hb.to_string())).await.is_err() {
                    return SessionEnd::Reconnect("failed to send heartbeat".into());
                }
                next_heartbeat = Instant::now() + Duration::from_millis(interval);
            }

            msg = rx.next() => match msg {
                Some(Ok(m @ (WsMessage::Text(_) | WsMessage::Binary(_)))) => {
                    let text = match message_text(m, &mut zlib, &mut zbuf) {
                        Ok(Some(t)) => t,
                        Ok(None) => continue,
                        Err(e) => return SessionEnd::Reconnect(e),
                    };
                    crate::shape::note(&text);
                    let p = match parse_payload(&text) {
                        Ok(p) => p,
                        // (Before READY, the payload that can't be read is READY.)
                        Err(e) if compact && !connected => {
                            log::warn!("gateway: couldn't read READY ({e})");
                            let _ = tx.send(WsMessage::Close(None)).await;
                            return classic_instead(st);
                        }
                        Err(e) => {
                            log::warn!("bad gateway payload: {e}");
                            continue;
                        }
                    };
                    let size = text.len();
                    drop(text);
                    match p.op {
                        0 => {
                            if let Some(s) = p.seq {
                                st.seq = Some(s);
                            }
                            let name = p.name.unwrap_or_default();
                            let mut data = p.data;
                            if name == "READY" {
                                // First, even for a READY that is thrown away: once
                                // Discord has sent a new token, the old one is retired,
                                // and the next IDENTIFY must use the new one.
                                if let Some(token) = take_auth_token(&mut data) {
                                    log::info!("gateway: Discord replaced the login token");
                                    st.token = token.clone();
                                    emit(GatewayEvent::TokenRefreshed(token));
                                }
                                if compact && !is_compact(&data) {
                                    let _ = tx.send(WsMessage::Close(None)).await;
                                    return classic_instead(st);
                                }
                                log::info!("gateway: READY is {} KB ({})", size / 1024, if compact { "compact" } else { "classic" });
                                st.session_id = data["session_id"].as_str().map(String::from);
                                st.resume_url = data["resume_gateway_url"].as_str().filter(|u| is_discord_gateway(u)).map(String::from);
                            }
                            if name == "READY" || name == "RESUMED" {
                                st.backoff = 1;
                                connected = true;
                                emit(GatewayEvent::Connected);
                                for v in std::mem::take(&mut st.pending) {
                                    if let Some(text) = st.outgoing(&v) {
                                        let _ = tx.send(WsMessage::Text(text)).await;
                                    }
                                }
                            }
                            emit(GatewayEvent::Dispatch { name, data });
                        }
                        1 => {
                            let hb = json!({ "op": 1, "d": st.seq });
                            let _ = tx.send(WsMessage::Text(hb.to_string())).await;
                        }
                        7 => return SessionEnd::Reconnect("server asked to reconnect".into()),
                        9 => {
                            if !p.data.as_bool().unwrap_or(false) {
                                st.session_id = None;
                                st.seq = None;
                            }
                            tokio::time::sleep(Duration::from_millis(1500 + jitter(3000))).await;
                            return SessionEnd::Reconnect("invalid session".into());
                        }
                        11 => acked = true,
                        _ => {}
                    }
                }
                Some(Ok(WsMessage::Close(frame))) => {
                    let reason = frame.as_ref().map(|f| f.reason.to_string()).unwrap_or_default();
                    let code = frame.map(|f| u16::from(f.code)).unwrap_or(1000);
                    // Discord's reason says which check failed (as for 4004).
                    log::info!("gateway: Discord closed the connection: {code} {reason}");
                    if code == 4002 {
                        // Discord couldn't take something RustCord sent: say what.
                        log::warn!("gateway: last payloads sent before the 4002:");
                        // (The payloads themselves stay out of the log file:
                        // they can hold a custom status or a search.)
                        for (op, len, preview) in &st.recent {
                            log::warn!("  op {op}, {len} bytes");
                            log::debug!("    {preview}");
                        }
                    }
                    st.recent.clear();
                    return match code {
                        4004 => SessionEnd::AuthFailed,
                        4010..=4014 => SessionEnd::Fatal(format!("gateway closed with code {code}")),
                        4007 | 4009 => {
                            st.session_id = None;
                            st.seq = None;
                            SessionEnd::Reconnect(format!("session expired ({code})"))
                        }
                        _ => SessionEnd::Reconnect(format!("gateway closed ({code})")),
                    };
                }
                Some(Ok(_)) => {}
                Some(Err(e)) => return SessionEnd::Reconnect(e.to_string()),
                None => return SessionEnd::Reconnect("connection closed".into()),
            },

            cmd = cmds.recv() => match cmd {
                Some(GatewayCommand::Send(v)) => {
                    if connected {
                        if let Some(text) = st.outgoing(&v) {
                            let _ = tx.send(WsMessage::Text(text)).await;
                        }
                    } else {
                        st.queue(v);
                    }
                }
                Some(GatewayCommand::Shutdown) | None => {
                    let _ = tx.send(WsMessage::Close(None)).await;
                    return SessionEnd::Shutdown;
                }
            },
        }
    }
}

/// READY came in a form RustCord can't read with capabilities on: start a
/// new session that asks for the classic one.
fn classic_instead(st: &mut SessionState) -> SessionEnd {
    log::warn!("gateway: READY isn't in the form the capabilities ask for; starting over for the classic one");
    st.classic = true;
    st.session_id = None;
    st.seq = None;
    SessionEnd::Reconnect("READY in an unknown form".into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn identify_asks_for_the_compact_ready_unless_told_not_to() {
        let presence = json!({ "status": "online" });
        let with = identify("t", &presence, capabilities(false));
        assert_eq!(with["d"]["capabilities"], crate::fingerprint::CAPABILITIES);
        assert_eq!(with["d"]["client_state"], json!({ "guild_versions": {} }));
        // After a READY that couldn't be read: the classic one, with neither.
        let without = identify("t", &presence, capabilities(true));
        assert!(without["d"].get("capabilities").is_none() && without["d"].get("client_state").is_none());
        assert_eq!(without["d"]["token"], "t");
    }

    #[test]
    fn a_compact_ready_lists_everyone_once_and_our_members_per_server() {
        assert!(is_compact(&json!({ "users": [], "guilds": [{}, {}], "merged_members": [[], []] })));
        // An account in no server.
        assert!(is_compact(&json!({ "users": [], "guilds": [], "merged_members": [] })));
        assert!(is_compact(&json!({ "users": [], "guilds": [] })));
        // The classic READY, or one whose lists don't line up.
        assert!(!is_compact(&json!({ "guilds": [{ "members": [] }], "presences": [] })));
        assert!(!is_compact(&json!({ "users": [], "guilds": [{}, {}], "merged_members": [[]] })));
        assert!(!is_compact(&json!({ "users": [] })));
    }

    #[test]
    fn a_new_token_is_taken_out_of_ready() {
        let mut ready = json!({ "session_id": "s", "auth_token": "new" });
        assert_eq!(take_auth_token(&mut ready).as_deref(), Some("new"));
        assert_eq!(ready, json!({ "session_id": "s" }));
        assert_eq!(take_auth_token(&mut ready), None);
        // Null (no new token) is dropped too, and isn't a token.
        let mut ready = json!({ "auth_token": null });
        assert_eq!(take_auth_token(&mut ready), None);
        assert_eq!(ready, json!({}));
    }

    #[test]
    fn zlib_stream_messages_share_one_context() {
        // Like Discord: one deflate stream, each message ending in a sync flush.
        let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
        enc.write_all(br#"{"op":10,"d":{"heartbeat_interval":41250}}"#).unwrap();
        enc.flush().unwrap();
        let first = enc.get_ref().clone();
        enc.write_all(br#"{"op":0,"t":"READY","d":{}}"#).unwrap();
        enc.flush().unwrap();
        let second = enc.get_ref()[first.len()..].to_vec();

        let mut z = flate2::Decompress::new(true);
        let mut buf = Vec::new();
        let a = message_text(WsMessage::Binary(first), &mut z, &mut buf).unwrap().unwrap();
        assert!(a.contains("heartbeat_interval"));
        // The second message split over two frames.
        let (p1, p2) = second.split_at(second.len() / 2);
        assert_eq!(message_text(WsMessage::Binary(p1.to_vec()), &mut z, &mut buf).unwrap(), None);
        let b = message_text(WsMessage::Binary(p2.to_vec()), &mut z, &mut buf).unwrap().unwrap();
        assert!(b.contains("READY"));
    }

    #[test]
    fn resume_only_goes_to_discords_gateways() {
        assert!(is_discord_gateway("wss://gateway-us-east1-b.discord.gg"));
        assert!(is_discord_gateway("wss://gateway.discord.gg/?encoding=json&v=9"));
        assert!(!is_discord_gateway("ws://gateway.discord.gg"));
        assert!(!is_discord_gateway("wss://discord.gg.evil.example"));
        assert!(!is_discord_gateway("wss://evil.example/discord.gg"));
        assert!(!is_discord_gateway("wss://notdiscord.gg"));
    }

    #[test]
    fn ready_keeps_only_what_is_read() {
        let text = r#"{"t":"READY","s":1,"op":0,"d":{
            "user":{"id":"1","username":"me"},
            "experiments":[[1,2,3],[4,5,6]],
            "guilds":[{"id":"10","name":"g","data_mode":"full","roles":[{"id":"10"}],"joined_at":"x","presences":[],"guild_scheduled_events":[{"id":"9"}]}],
            "read_state":{"entries":[{"id":"5","mention_count":2}]},
            "notification_settings":{"flags":0},
            "session_id":"abc"
        }}"#;
        let p = parse_payload(text).unwrap();
        assert_eq!(p.op, 0);
        assert_eq!(p.seq, Some(1));
        assert_eq!(p.name.as_deref(), Some("READY"));
        assert_eq!(p.data["user"]["username"], "me");
        assert!(p.data.get("experiments").is_none());
        assert!(p.data.get("notification_settings").is_none());
        assert_eq!(p.data["session_id"], "abc");
        assert_eq!(p.data["read_state"]["entries"][0]["mention_count"], 2);
        let g = &p.data["guilds"][0];
        assert_eq!(g["name"], "g");
        assert_eq!(g["roles"][0]["id"], "10");
        assert!(g.get("data_mode").is_none());
        assert!(g.get("guild_scheduled_events").is_none());
    }

    #[test]
    fn other_payloads_parse_whole() {
        let p = parse_payload(r#"{"op":11,"s":null,"t":null,"d":null}"#).unwrap();
        assert_eq!(p.op, 11);
        assert!(p.data.is_null());
        let p = parse_payload(r#"{"t":"MESSAGE_CREATE","s":7,"op":0,"d":{"id":"1","content":"hi","anything":[1]}}"#).unwrap();
        assert_eq!(p.data["anything"][0], 1);
        assert_eq!(p.seq, Some(7));
    }
}