Skip to main content

orch/channels/
discord_ws.rs

1//! Discord Gateway websocket client.
2//!
3//! Delivers real-time events from Discord's Gateway API (wss://gateway.discord.gg)
4//! replacing the HTTP polling approach in `discord.rs`.
5//!
6//! Protocol flow:
7//!   connect → Hello → Identify → Ready → receive MESSAGE_CREATE events
8//!   heartbeat every `heartbeat_interval` ms to keep the connection alive
9//!   on disconnect: resume with session_id+seq, or re-identify from scratch
10
11use super::access::Access;
12use super::{Channel, IncomingMessage, OutgoingMessage};
13use anyhow::Context;
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use futures::{SinkExt, StreamExt};
17use reqwest::Client;
18use serde::Deserialize;
19use serde_json::Value;
20use std::env::consts;
21use std::fmt;
22use std::fmt::Debug;
23use std::fmt::Formatter;
24use std::time::Duration;
25use tokio::net::TcpStream;
26use tokio::sync::mpsc;
27use tokio::time;
28use tokio_tungstenite::tungstenite;
29use tokio_tungstenite::{connect_async, tungstenite::Message};
30
31// ── Gateway opcodes ──────────────────────────────────────────────────────────
32
33const OP_DISPATCH: u64 = 0;
34const OP_HEARTBEAT: u64 = 1;
35const OP_IDENTIFY: u64 = 2;
36const OP_RESUME: u64 = 6;
37const OP_RECONNECT: u64 = 7;
38const OP_INVALID_SESSION: u64 = 9;
39const OP_HELLO: u64 = 10;
40const OP_HEARTBEAT_ACK: u64 = 11;
41
42/// Gateway intents bitmask.
43/// GUILDS(1) | GUILD_MESSAGES(512) | MESSAGE_CONTENT(32768)
44const GATEWAY_INTENTS: u64 = 1 | (1 << 9) | (1 << 15);
45
46const DEFAULT_GATEWAY_URL: &str = "wss://gateway.discord.gg/?v=10&encoding=json";
47
48/// Timeout for websocket send operations.
49/// Must be less than heartbeat interval to fail fast before zombie detection.
50const SEND_TIMEOUT_SECS: u64 = 10;
51
52// ── Public struct ────────────────────────────────────────────────────────────
53
54/// Discord Gateway websocket client.
55///
56/// Receives real-time events via wss:// and sends messages via REST.
57/// Supports sharding via `shard_id`/`shard_count` (both read from config).
58pub struct DiscordGateway {
59    token: String,
60    client: Client,
61    channel_id: Option<String>,
62    shard_id: u64,
63    shard_count: u64,
64    access: Access,
65}
66
67impl Debug for DiscordGateway {
68    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
69        f.debug_struct("DiscordGateway")
70            .field("channel_id", &self.channel_id)
71            .field("shard_id", &self.shard_id)
72            .field("shard_count", &self.shard_count)
73            .finish_non_exhaustive()
74    }
75}
76
77impl DiscordGateway {
78    /// Create a new Gateway client.
79    ///
80    /// `shard_id` and `shard_count` follow Discord sharding conventions.
81    /// For a single-shard bot, use `shard_id = 0, shard_count = 1`.
82    pub fn new(
83        token: String,
84        channel_id: Option<String>,
85        shard_id: u64,
86        shard_count: u64,
87    ) -> anyhow::Result<Self> {
88        let client = Client::builder()
89            .timeout(Duration::from_secs(30))
90            .build()
91            .context("failed to build HTTP client")?;
92
93        Ok(Self {
94            token,
95            client,
96            channel_id,
97            shard_id,
98            shard_count,
99            access: Access::default(),
100        })
101    }
102
103    /// Restrict incoming events to `channel_id`, `extra_channels` and the given user IDs.
104    /// With no channel or no user, every incoming event is dropped
105    #[must_use]
106    pub fn with_access(mut self, extra_channels: Vec<String>, user_ids: Vec<String>) -> Self {
107        let channels = self.channel_id.iter().cloned().chain(extra_channels);
108        self.access = Access::new(channels, user_ids);
109        self
110    }
111
112    fn api_url(endpoint: &str) -> String {
113        format!("https://discord.com/api/v10{endpoint}")
114    }
115
116    /// Send a message with action row buttons to a specific channel.
117    ///
118    /// Returns the message ID of the sent message.
119    pub async fn send_with_buttons(
120        &self,
121        channel_id: &str,
122        text: &str,
123        buttons: &[(String, String)], // (label, custom_id)
124    ) -> anyhow::Result<String> {
125        let components = vec![serde_json::json!({
126            "type": 1, // ActionRow
127            "components": buttons.iter().map(|(label, custom_id)| {
128                serde_json::json!({
129                    "type": 2, // Button
130                    "style": 1, // Primary
131                    "label": label,
132                    "custom_id": custom_id
133                })
134            }).collect::<Vec<_>>()
135        })];
136
137        let body = serde_json::json!({
138            "content": text,
139            "components": components
140        });
141
142        let url = Self::api_url(&format!("/channels/{channel_id}/messages"));
143        let response = self
144            .client
145            .post(&url)
146            .header("Authorization", format!("Bot {}", self.token))
147            .json(&body)
148            .send()
149            .await?;
150
151        if !response.status().is_success() {
152            let body = response.text().await.unwrap_or_default();
153            anyhow::bail!("discord API error: {body}");
154        }
155
156        let result: serde_json::Value = response.json().await?;
157        Ok(result["id"].as_str().unwrap_or("").to_string())
158    }
159
160    async fn send_message(&self, channel_id: &str, content: &str) -> anyhow::Result<()> {
161        let url = Self::api_url(&format!("/channels/{channel_id}/messages"));
162        let resp = self
163            .client
164            .post(&url)
165            .header("Authorization", format!("Bot {}", self.token))
166            .json(&serde_json::json!({ "content": content }))
167            .send()
168            .await?;
169
170        if !resp.status().is_success() {
171            anyhow::bail!(
172                "discord send failed: {}",
173                resp.text().await.unwrap_or_default()
174            );
175        }
176        Ok(())
177    }
178}
179
180// ── Channel impl ─────────────────────────────────────────────────────────────
181
182#[async_trait]
183impl Channel for DiscordGateway {
184    fn name(&self) -> &'static str {
185        "discord"
186    }
187
188    async fn start(&self) -> anyhow::Result<mpsc::Receiver<IncomingMessage>> {
189        let (tx, rx) = mpsc::channel(64);
190        let token = self.token.clone();
191        let shard_id = self.shard_id;
192        let shard_count = self.shard_count;
193        let client = self.client.clone();
194        let access = self.access.clone();
195        access.warn_if_closed("discord");
196
197        tracing::info!(shard_id, shard_count, "discord gateway starting");
198
199        tokio::spawn(async move {
200            run_gateway(token, shard_id, shard_count, tx, client, access).await;
201        });
202
203        Ok(rx)
204    }
205
206    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
207        let target_channel = msg
208            .topic_id
209            .as_deref()
210            .or(self.channel_id.as_deref())
211            .ok_or_else(|| anyhow::anyhow!("no target channel for discord message"))?;
212
213        // If metadata carries buttons, send as an interactive message with an ActionRow.
214        if let Some(buttons_val) = msg.metadata.get("buttons")
215            && let Some(buttons_arr) = buttons_val.as_array()
216        {
217            let buttons: Vec<(String, String)> = buttons_arr
218                .iter()
219                .filter_map(|b| {
220                    let text = b["text"].as_str()?.to_string();
221                    let custom_id = b["callback_data"].as_str()?.to_string();
222                    Some((text, custom_id))
223                })
224                .collect();
225            if !buttons.is_empty() {
226                self.send_with_buttons(target_channel, &msg.body, &buttons)
227                    .await?;
228                return Ok(());
229            }
230        }
231
232        self.send_message(target_channel, &msg.body).await
233    }
234
235    async fn health_check(&self) -> anyhow::Result<()> {
236        let resp = self
237            .client
238            .get(Self::api_url("/users/@me"))
239            .header("Authorization", format!("Bot {}", self.token))
240            .send()
241            .await?;
242
243        if !resp.status().is_success() {
244            anyhow::bail!(
245                "discord health check failed: {}",
246                resp.text().await.unwrap_or_default()
247            );
248        }
249        tracing::info!("discord gateway health check passed");
250        Ok(())
251    }
252}
253
254// ── Gateway protocol ─────────────────────────────────────────────────────────
255
256/// Parsed Gateway payload (op + d + s + t).
257#[derive(Deserialize)]
258struct GatewayPayload {
259    op: u64,
260    #[serde(default)]
261    d: Value,
262    s: Option<u64>,
263    t: Option<String>,
264}
265
266/// Mutable session state shared across reconnect cycles.
267struct GatewayState {
268    session_id: Option<String>,
269    last_seq: Option<u64>,
270    resume_url: Option<String>,
271}
272
273impl GatewayState {
274    fn new() -> Self {
275        Self {
276            session_id: None,
277            last_seq: None,
278            resume_url: None,
279        }
280    }
281
282    fn clear(&mut self) {
283        self.session_id = None;
284        self.last_seq = None;
285        self.resume_url = None;
286    }
287
288    fn ws_url(&self) -> String {
289        self.resume_url.as_deref().map_or_else(
290            || DEFAULT_GATEWAY_URL.to_string(),
291            |u| format!("{}/?v=10&encoding=json", u.trim_end_matches('/')),
292        )
293    }
294}
295
296/// Main gateway loop — connects, handles protocol, reconnects on error.
297async fn run_gateway(
298    token: String,
299    shard_id: u64,
300    shard_count: u64,
301    tx: mpsc::Sender<IncomingMessage>,
302    client: Client,
303    access: Access,
304) {
305    let mut state = GatewayState::new();
306    let mut backoff = Duration::from_secs(1);
307
308    loop {
309        let ws_url = state.ws_url();
310        tracing::debug!(url = %ws_url, "connecting to discord gateway");
311
312        match time::timeout(Duration::from_secs(30), connect_async(&ws_url)).await {
313            Ok(Ok((ws, _))) => {
314                backoff = Duration::from_secs(1); // reset on success
315
316                let result = handle_connection(
317                    ws,
318                    &token,
319                    (shard_id, shard_count),
320                    &mut state,
321                    &tx,
322                    &client,
323                    &access,
324                )
325                .await;
326
327                match result {
328                    Ok(true) => {
329                        tracing::info!("discord gateway: disconnected (will resume)");
330                    }
331                    Ok(false) => {
332                        tracing::info!(
333                            "discord gateway: disconnected (not resumable), re-identifying"
334                        );
335                        state.clear();
336                    }
337                    Err(e) => {
338                        tracing::warn!(?e, "discord gateway: connection error");
339                    }
340                }
341            }
342            Ok(Err(e)) => {
343                tracing::warn!(
344                    ?e,
345                    backoff_secs = backoff.as_secs(),
346                    "discord gateway: connect failed"
347                );
348            }
349            Err(_) => {
350                tracing::warn!(
351                    backoff_secs = backoff.as_secs(),
352                    "discord gateway: connect timed out"
353                );
354            }
355        }
356
357        if tx.is_closed() {
358            tracing::debug!("discord gateway: receiver closed, shutting down");
359            return;
360        }
361
362        time::sleep(backoff).await;
363        backoff = (backoff * 2).min(Duration::from_secs(60));
364    }
365}
366
367/// Handle a single websocket connection lifecycle.
368///
369/// Returns `Ok(true)` if the session can be resumed, `Ok(false)` if we
370/// need to re-identify (invalid session or clean disconnect).
371async fn handle_connection(
372    ws: tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<TcpStream>>,
373    token: &str,
374    (shard_id, shard_count): (u64, u64),
375    state: &mut GatewayState,
376    tx: &mpsc::Sender<IncomingMessage>,
377    client: &Client,
378    access: &Access,
379) -> anyhow::Result<bool> {
380    let (mut write, mut read) = ws.split();
381
382    // ── Step 1: Hello ────────────────────────────────────────────────────────
383    let text = time::timeout(Duration::from_secs(15), next_text_message(&mut read))
384        .await
385        .map_err(|_| anyhow::anyhow!("discord gateway: Hello timed out"))??;
386    let hello: GatewayPayload = serde_json::from_str(&text)?;
387    anyhow::ensure!(
388        hello.op == OP_HELLO,
389        "expected Hello (op=10), got op={}",
390        hello.op
391    );
392
393    let hb_interval_ms = parse_heartbeat_interval(&hello.d["heartbeat_interval"]);
394    tracing::debug!(hb_interval_ms, "discord gateway: Hello received");
395
396    // ── Step 2: Identify or Resume ───────────────────────────────────────────
397    let payload = if let (Some(sid), Some(seq)) = (state.session_id.as_deref(), state.last_seq) {
398        tracing::info!(session_id = %sid, seq, "discord gateway: sending Resume");
399        serde_json::json!({
400            "op": OP_RESUME,
401            "d": {
402                "token": token,
403                "session_id": sid,
404                "seq": seq,
405            }
406        })
407    } else {
408        tracing::info!(shard_id, shard_count, "discord gateway: sending Identify");
409        serde_json::json!({
410            "op": OP_IDENTIFY,
411            "d": {
412                "token": token,
413                "intents": GATEWAY_INTENTS,
414                "properties": {
415                    "os": consts::OS,
416                    "browser": "orch",
417                    "device": "orch",
418                },
419                "shard": [shard_id, shard_count],
420            }
421        })
422    };
423
424    time::timeout(
425        Duration::from_secs(SEND_TIMEOUT_SECS),
426        write.send(Message::Text(payload.to_string())),
427    )
428    .await
429    .map_err(|_| anyhow::anyhow!("identify send timed out"))?
430    .map_err(|e| anyhow::anyhow!("identify send failed: {e}"))?;
431
432    // ── Step 3: Event loop ───────────────────────────────────────────────────
433    let mut hb_ticker = time::interval(Duration::from_millis(hb_interval_ms));
434    hb_ticker.tick().await; // consume the immediate first tick
435    let mut ack_received = true;
436
437    loop {
438        tokio::select! {
439            raw = read.next() => {
440                let msg = match raw {
441                    Some(Ok(m)) => m,
442                    Some(Err(e)) => return Err(e.into()),
443                    None => {
444                        tracing::debug!("discord gateway: stream closed");
445                        return Ok(true); // try to resume
446                    }
447                };
448
449                match msg {
450                    Message::Text(text) => {
451                        let payload: GatewayPayload = match serde_json::from_str(&text) {
452                            Ok(p) => p,
453                            Err(e) => {
454                                tracing::warn!(?e, "discord gateway: failed to parse payload");
455                                continue;
456                            }
457                        };
458
459                        if let Some(seq) = payload.s {
460                            state.last_seq = Some(seq);
461                        }
462
463                        match payload.op {
464                            OP_DISPATCH => {
465                                if let Err(e) = handle_dispatch(
466                                    payload.t.as_deref(),
467                                    &payload.d,
468                                    &mut state.session_id,
469                                    &mut state.resume_url,
470                                    tx,
471                                    client,
472                                    access,
473                                )
474                                .await
475                                {
476                                    tracing::warn!(?e, "discord gateway: dispatch error");
477                                }
478                                if tx.is_closed() {
479                                    return Ok(false);
480                                }
481                            }
482                            OP_HEARTBEAT => {
483                                // Server explicitly requested a heartbeat
484                                let d = state
485                                    .last_seq
486                                    .map_or(Value::Null, |s| serde_json::json!(s));
487                                let hb_payload = Message::Text(
488                                    serde_json::json!({"op": OP_HEARTBEAT, "d": d}).to_string(),
489                                );
490                                time::timeout(Duration::from_secs(SEND_TIMEOUT_SECS), write.send(hb_payload))
491                                    .await
492                                    .map_err(|_| anyhow::anyhow!("server heartbeat send timed out"))?
493                                    .map_err(|e| anyhow::anyhow!("server heartbeat send failed: {e}"))?;
494                            }
495                            OP_HEARTBEAT_ACK => {
496                                ack_received = true;
497                            }
498                            OP_RECONNECT => {
499                                tracing::info!("discord gateway: server requested reconnect");
500                                return Ok(true);
501                            }
502                            OP_INVALID_SESSION => {
503                                let resumable = payload.d.as_bool().unwrap_or(false);
504                                tracing::info!(resumable, "discord gateway: invalid session");
505                                if !resumable {
506                                    state.clear();
507                                    // Brief delay before re-identifying to avoid rate limiting
508                                    time::sleep(Duration::from_secs(5)).await;
509                                }
510                                return Ok(resumable);
511                            }
512                            op => {
513                                tracing::debug!(op, "discord gateway: unhandled opcode");
514                            }
515                        }
516                    }
517                    Message::Close(frame) => {
518                        let code = frame.as_ref().map_or(0, |f| u16::from(f.code));
519                        // Non-resumable Discord Gateway close codes per Discord docs
520                        let resumable = !matches!(code, 4004 | 4010 | 4011 | 4013 | 4014);
521                        if resumable {
522                            tracing::info!(code, ?frame, "discord gateway: close frame, will attempt resume");
523                        } else {
524                            state.clear();
525                            tracing::error!(
526                                code,
527                                "discord gateway: non-resumable close code — check bot token and intent configuration"
528                            );
529                        }
530                        return Ok(resumable);
531                    }
532                    Message::Ping(data) => {
533                        time::timeout(Duration::from_secs(SEND_TIMEOUT_SECS), write.send(Message::Pong(data)))
534                            .await
535                            .map_err(|_| anyhow::anyhow!("pong send timed out"))?
536                            .map_err(|e| anyhow::anyhow!("pong send failed: {e}"))?;
537                    }
538                    _ => {}
539                }
540            }
541
542            _ = hb_ticker.tick() => {
543                if !ack_received {
544                    tracing::warn!(
545                        "discord gateway: heartbeat not acknowledged (zombie connection), reconnecting"
546                    );
547                    return Ok(true);
548                }
549                ack_received = false;
550                let d = state
551                    .last_seq
552                    .map_or(Value::Null, |s| serde_json::json!(s));
553                let hb_payload = Message::Text(
554                    serde_json::json!({"op": OP_HEARTBEAT, "d": d}).to_string(),
555                );
556                time::timeout(Duration::from_secs(SEND_TIMEOUT_SECS), write.send(hb_payload))
557                    .await
558                    .map_err(|_| anyhow::anyhow!("periodic heartbeat send timed out"))?
559                    .map_err(|e| anyhow::anyhow!("periodic heartbeat send failed: {e}"))?;
560            }
561        }
562    }
563}
564
565/// Read the next text frame from the stream, skipping non-text control frames.
566async fn next_text_message<S>(read: &mut S) -> anyhow::Result<String>
567where
568    S: StreamExt<Item = Result<Message, tungstenite::Error>> + Unpin,
569{
570    loop {
571        match read.next().await {
572            Some(Ok(Message::Text(t))) => return Ok(t),
573            Some(Ok(_)) => {}
574            Some(Err(e)) => return Err(e.into()),
575            None => anyhow::bail!("stream closed before receiving expected message"),
576        }
577    }
578}
579
580/// Handle a DISPATCH event (op=0).
581async fn handle_dispatch(
582    event_type: Option<&str>,
583    data: &Value,
584    session_id: &mut Option<String>,
585    resume_url: &mut Option<String>,
586    tx: &mpsc::Sender<IncomingMessage>,
587    client: &Client,
588    access: &Access,
589) -> anyhow::Result<()> {
590    match event_type {
591        Some("READY") => {
592            if let Some(sid) = data["session_id"].as_str() {
593                *session_id = Some(sid.to_string());
594            }
595            if let Some(url) = data["resume_gateway_url"].as_str() {
596                *resume_url = Some(url.to_string());
597            }
598            let username = data["user"]["username"].as_str().unwrap_or("unknown");
599            tracing::info!(username, "discord gateway: ready");
600        }
601        Some("RESUMED") => {
602            tracing::info!("discord gateway: session resumed");
603        }
604        Some("MESSAGE_CREATE") => {
605            // Validate channel_id is present and non-empty — it's required for routing/replies.
606            let Some(msg_channel_id) = data["channel_id"].as_str().filter(|s| !s.is_empty()) else {
607                tracing::warn!("discord MESSAGE_CREATE missing channel_id, skipping");
608                return Ok(());
609            };
610
611            // Skip messages from bots (avoid reacting to ourselves)
612            if data["author"]["bot"].as_bool().unwrap_or(false) {
613                return Ok(());
614            }
615
616            let user_id = data["author"]["id"].as_str().unwrap_or_default();
617            if !access.allows(msg_channel_id, user_id) {
618                tracing::warn!(
619                    channel = msg_channel_id,
620                    user = user_id,
621                    "dropping discord message from unauthorized sender"
622                );
623                return Ok(());
624            }
625
626            // Validate message id is present and non-empty. If malformed, skip the event.
627            let Some(id_str) = data["id"].as_str().filter(|s| !s.is_empty()) else {
628                tracing::warn!("discord MESSAGE_CREATE missing message id, skipping");
629                return Ok(());
630            };
631
632            let id = id_str.to_string();
633            let author = data["author"]["username"]
634                .as_str()
635                .unwrap_or("unknown")
636                .to_string();
637            let body = data["content"].as_str().unwrap_or("").to_string();
638            let timestamp = data["timestamp"]
639                .as_str()
640                .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
641                .map_or_else(Utc::now, |dt| dt.with_timezone(&Utc));
642
643            let incoming = IncomingMessage {
644                channel: "discord".to_string(),
645                id,
646                thread_id: msg_channel_id.to_string(),
647                author,
648                body,
649                timestamp,
650                metadata: serde_json::json!({}),
651                topic_id: Some(msg_channel_id.to_string()),
652            };
653
654            tx.send(incoming)
655                .await
656                .map_err(|_| anyhow::anyhow!("receiver closed"))?;
657        }
658        Some("INTERACTION_CREATE") => {
659            // Handle message component interactions (e.g. button clicks)
660            let interaction_type = data["type"].as_u64().unwrap_or(0);
661            if interaction_type == 3 {
662                // MESSAGE_COMPONENT
663                let Some(interaction_id) = data["id"].as_str().filter(|s| !s.is_empty()) else {
664                    tracing::warn!("ignoring INTERACTION_CREATE with missing id");
665                    return Ok(());
666                };
667                let Some(interaction_token) = data["token"].as_str().filter(|s| !s.is_empty())
668                else {
669                    tracing::warn!("ignoring INTERACTION_CREATE with missing token");
670                    return Ok(());
671                };
672                let interaction_id = interaction_id.to_string();
673                let interaction_token = interaction_token.to_string();
674                let Some(inter_channel_id) = data["channel_id"].as_str().filter(|s| !s.is_empty())
675                else {
676                    tracing::warn!("ignoring INTERACTION_CREATE with missing channel_id");
677                    return Ok(());
678                };
679                let inter_channel_id = inter_channel_id.to_string();
680                let user_id = data["member"]["user"]["id"]
681                    .as_str()
682                    .or_else(|| data["user"]["id"].as_str())
683                    .unwrap_or_default();
684                if !access.allows(&inter_channel_id, user_id) {
685                    tracing::warn!(
686                        channel = inter_channel_id,
687                        user = user_id,
688                        "dropping discord interaction from unauthorized sender"
689                    );
690                    return Ok(());
691                }
692                let custom_id = data["data"]["custom_id"]
693                    .as_str()
694                    .filter(|s| !s.is_empty())
695                    .unwrap_or("button_click")
696                    .to_string();
697                let author = data["member"]["user"]["username"]
698                    .as_str()
699                    .or_else(|| data["user"]["username"].as_str())
700                    .unwrap_or("unknown")
701                    .to_string();
702
703                // Acknowledge the interaction (type 6 = DEFERRED_UPDATE_MESSAGE)
704                let callback_url = format!(
705                    "https://discord.com/api/v10/interactions/{interaction_id}/{interaction_token}/callback"
706                );
707                let http_client = client.clone();
708                if let Err(e) = http_client
709                    .post(&callback_url)
710                    .header("Content-Type", "application/json")
711                    .json(&serde_json::json!({ "type": 6 }))
712                    .send()
713                    .await
714                    .map_err(reqwest::Error::without_url)
715                {
716                    tracing::warn!(interaction_id, error = %e, "failed to acknowledge Discord interaction");
717                }
718
719                let incoming = IncomingMessage {
720                    channel: "discord".to_string(),
721                    id: interaction_id.clone(),
722                    thread_id: inter_channel_id.clone(),
723                    author,
724                    body: custom_id.clone(),
725                    timestamp: Utc::now(),
726                    metadata: serde_json::json!({
727                        "interaction_id": interaction_id,
728                        "interaction_token": interaction_token,
729                        "custom_id": custom_id,
730                    }),
731                    topic_id: Some(inter_channel_id),
732                };
733
734                tx.send(incoming)
735                    .await
736                    .map_err(|_| anyhow::anyhow!("receiver closed"))?;
737            }
738        }
739        Some(t) => {
740            tracing::debug!(event_type = %t, "discord gateway: unhandled event");
741        }
742        None => {}
743    }
744    Ok(())
745}
746
747// ── Heartbeat interval parsing ───────────────────────────────────────────────
748
749/// Parse heartbeat interval from Discord gateway Hello payload.
750/// Rejects zero or invalid values and falls back to Discord's default (41.25 seconds).
751fn parse_heartbeat_interval(value: &Value) -> u64 {
752    value.as_u64().filter(|&v| v > 0).unwrap_or(41_250)
753}
754
755// ── Tests ────────────────────────────────────────────────────────────────────
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760    use tokio::sync::mpsc;
761
762    /// Build a reqwest::Client that cannot make real network calls.
763    /// All external hosts resolve to 127.0.0.1:1 and connections time out in 1ms.
764    fn no_network_client() -> Client {
765        Client::builder()
766            .connect_timeout(Duration::from_millis(1))
767            .resolve("discord.com", "127.0.0.1:1".parse().unwrap())
768            .build()
769            .unwrap()
770    }
771
772    fn test_access() -> Access {
773        Access::new(
774            ["987654321", "ch", "chan-456"].map(String::from),
775            ["u1".to_string()],
776        )
777    }
778
779    #[tokio::test]
780    async fn handle_dispatch_message_create_sends_to_channel() {
781        let (tx, mut rx) = mpsc::channel(10);
782        let data = serde_json::json!({
783            "id": "123456789",
784            "channel_id": "987654321",
785            "author": {"id": "u1", "username": "testuser", "bot": false},
786            "content": "hello world",
787            "timestamp": "2024-01-01T00:00:00+00:00",
788        });
789
790        let access = test_access();
791        let mut session_id = None;
792        let mut resume_url = None;
793        let client = no_network_client();
794
795        handle_dispatch(
796            Some("MESSAGE_CREATE"),
797            &data,
798            &mut session_id,
799            &mut resume_url,
800            &tx,
801            &client,
802            &access,
803        )
804        .await
805        .expect("dispatch should succeed for valid MESSAGE_CREATE");
806
807        let msg = rx
808            .recv()
809            .await
810            .expect("should receive MESSAGE_CREATE event from dispatch");
811        assert_eq!(msg.id, "123456789");
812        assert_eq!(msg.thread_id, "987654321");
813        assert_eq!(msg.topic_id, Some("987654321".to_string()));
814        assert_eq!(msg.author, "testuser");
815        assert_eq!(msg.body, "hello world");
816        assert_eq!(msg.channel, "discord");
817    }
818
819    #[tokio::test]
820    async fn handle_dispatch_skips_bot_messages() {
821        let (tx, mut rx) = mpsc::channel(10);
822        let data = serde_json::json!({
823            "id": "111",
824            "channel_id": "222",
825            "author": {"id": "u1", "username": "botuser", "bot": true},
826            "content": "I am a bot",
827            "timestamp": "2024-01-01T00:00:00+00:00",
828        });
829
830        let access = test_access();
831        let mut session_id = None;
832        let mut resume_url = None;
833        let client = no_network_client();
834
835        handle_dispatch(
836            Some("MESSAGE_CREATE"),
837            &data,
838            &mut session_id,
839            &mut resume_url,
840            &tx,
841            &client,
842            &access,
843        )
844        .await
845        .expect("dispatch should succeed for bot message (just skipping send)");
846
847        // Nothing should arrive
848        assert!(rx.try_recv().is_err());
849    }
850
851    async fn dispatch_one(event: &str, data: &Value) -> mpsc::Receiver<IncomingMessage> {
852        let (tx, rx) = mpsc::channel(10);
853        let mut session_id = None;
854        let mut resume_url = None;
855        handle_dispatch(
856            Some(event),
857            data,
858            &mut session_id,
859            &mut resume_url,
860            &tx,
861            &no_network_client(),
862            &test_access(),
863        )
864        .await
865        .expect("dispatch should succeed");
866        rx
867    }
868
869    #[tokio::test]
870    async fn handle_dispatch_drops_message_from_other_channel() {
871        let data = serde_json::json!({
872            "id": "999",
873            "channel_id": "other-channel",
874            "author": {"id": "u1", "username": "user", "bot": false},
875            "content": "hello",
876            "timestamp": "2024-01-01T00:00:00+00:00",
877        });
878        let mut rx = dispatch_one("MESSAGE_CREATE", &data).await;
879        assert!(rx.try_recv().is_err());
880    }
881
882    #[tokio::test]
883    async fn handle_dispatch_drops_message_from_other_user() {
884        let data = serde_json::json!({
885            "id": "42",
886            "channel_id": "ch",
887            "author": {"id": "intruder", "username": "user", "bot": false},
888            "content": "hello",
889            "timestamp": "2024-01-01T00:00:00+00:00",
890        });
891        let mut rx = dispatch_one("MESSAGE_CREATE", &data).await;
892        assert!(rx.try_recv().is_err());
893    }
894
895    #[tokio::test]
896    async fn handle_dispatch_drops_interaction_from_other_user() {
897        let data = serde_json::json!({
898            "type": 3,
899            "id": "i1",
900            "token": "tok",
901            "channel_id": "ch",
902            "data": {"custom_id": "x"},
903            "member": {"user": {"id": "intruder", "username": "x"}}
904        });
905        let mut rx = dispatch_one("INTERACTION_CREATE", &data).await;
906        assert!(rx.try_recv().is_err());
907    }
908
909    #[tokio::test]
910    async fn handle_dispatch_ready_sets_session_and_resume_url() {
911        let (tx, _rx) = mpsc::channel(10);
912        let data = serde_json::json!({
913            "session_id": "abc123",
914            "resume_gateway_url": "wss://us-east1.discord.gg",
915            "user": {"username": "mybot"},
916        });
917
918        let access = test_access();
919        let mut session_id = None;
920        let mut resume_url = None;
921        let client = no_network_client();
922
923        handle_dispatch(
924            Some("READY"),
925            &data,
926            &mut session_id,
927            &mut resume_url,
928            &tx,
929            &client,
930            &access,
931        )
932        .await
933        .expect("dispatch should succeed for READY event");
934
935        assert_eq!(session_id.as_deref(), Some("abc123"));
936        assert_eq!(resume_url.as_deref(), Some("wss://us-east1.discord.gg"));
937    }
938
939    #[tokio::test]
940    async fn handle_dispatch_receiver_closed_returns_error() {
941        let (tx, rx) = mpsc::channel(1);
942        drop(rx); // close receiver
943
944        let data = serde_json::json!({
945            "id": "1",
946            "channel_id": "ch",
947            "author": {"id": "u1", "username": "u", "bot": false},
948            "content": "msg",
949            "timestamp": "2024-01-01T00:00:00+00:00",
950        });
951
952        let access = test_access();
953        let mut session_id = None;
954        let mut resume_url = None;
955        let client = Client::new();
956
957        let result = handle_dispatch(
958            Some("MESSAGE_CREATE"),
959            &data,
960            &mut session_id,
961            &mut resume_url,
962            &tx,
963            &client,
964            &access,
965        )
966        .await;
967
968        assert!(result.is_err());
969        assert!(result.unwrap_err().to_string().contains("receiver closed"));
970    }
971
972    #[tokio::test]
973    async fn handle_dispatch_interaction_create_button_click() {
974        let (tx, mut rx) = mpsc::channel(10);
975        let data = serde_json::json!({
976            "type": 3, // MESSAGE_COMPONENT
977            "id": "interaction-123",
978            "token": "interaction-token-abc",
979            "channel_id": "chan-456",
980            "data": {
981                "custom_id": "select_project:owner/repo"
982            },
983            "member": {
984                "user": {"id": "u1", "username": "clicker"}
985            }
986        });
987
988        let access = test_access();
989        let mut session_id = None;
990        let mut resume_url = None;
991        let client = no_network_client();
992
993        handle_dispatch(
994            Some("INTERACTION_CREATE"),
995            &data,
996            &mut session_id,
997            &mut resume_url,
998            &tx,
999            &client,
1000            &access,
1001        )
1002        .await
1003        .expect("dispatch should succeed for INTERACTION_CREATE");
1004
1005        let msg = rx
1006            .recv()
1007            .await
1008            .expect("should receive INTERACTION_CREATE event from dispatch");
1009        assert_eq!(msg.channel, "discord");
1010        assert_eq!(msg.id, "interaction-123");
1011        assert_eq!(msg.thread_id, "chan-456");
1012        assert_eq!(msg.topic_id, Some("chan-456".to_string()));
1013        assert_eq!(msg.body, "select_project:owner/repo");
1014        assert_eq!(msg.author, "clicker");
1015        assert_eq!(
1016            msg.metadata["custom_id"].as_str(),
1017            Some("select_project:owner/repo")
1018        );
1019        assert_eq!(
1020            msg.metadata["interaction_id"].as_str(),
1021            Some("interaction-123")
1022        );
1023        assert_eq!(
1024            msg.metadata["interaction_token"].as_str(),
1025            Some("interaction-token-abc")
1026        );
1027    }
1028
1029    #[tokio::test]
1030    async fn handle_dispatch_interaction_create_ignores_non_component() {
1031        let (tx, mut rx) = mpsc::channel(10);
1032        let data = serde_json::json!({
1033            "type": 1, // PING, not MESSAGE_COMPONENT
1034            "id": "interaction-999",
1035            "token": "tok",
1036            "channel_id": "ch",
1037        });
1038
1039        let access = test_access();
1040        let mut session_id = None;
1041        let mut resume_url = None;
1042        let client = no_network_client();
1043
1044        handle_dispatch(
1045            Some("INTERACTION_CREATE"),
1046            &data,
1047            &mut session_id,
1048            &mut resume_url,
1049            &tx,
1050            &client,
1051            &access,
1052        )
1053        .await
1054        .expect("dispatch should succeed for non-component INTERACTION_CREATE");
1055
1056        // Should not produce a message for non-component interactions
1057        assert!(rx.try_recv().is_err());
1058    }
1059
1060    #[test]
1061    fn parse_heartbeat_interval_rejects_zero() {
1062        let zero = serde_json::json!(0);
1063        assert_eq!(parse_heartbeat_interval(&zero), 41_250);
1064    }
1065
1066    #[test]
1067    fn parse_heartbeat_interval_accepts_valid() {
1068        let valid = serde_json::json!(50_000);
1069        assert_eq!(parse_heartbeat_interval(&valid), 50_000);
1070    }
1071
1072    #[test]
1073    fn parse_heartbeat_interval_defaults_on_null() {
1074        let null = serde_json::json!(null);
1075        assert_eq!(parse_heartbeat_interval(&null), 41_250);
1076    }
1077
1078    #[test]
1079    fn parse_heartbeat_interval_defaults_on_missing() {
1080        let object = serde_json::json!({});
1081        assert_eq!(
1082            parse_heartbeat_interval(&object["heartbeat_interval"]),
1083            41_250
1084        );
1085    }
1086
1087    #[test]
1088    fn parse_heartbeat_interval_can_create_valid_duration() {
1089        // Verify that the parsed interval can be used to create a tokio interval
1090        // without panicking. This is the real-world requirement: the value must
1091        // be valid for Duration::from_millis().
1092        let zero = serde_json::json!(0);
1093        let interval_ms = parse_heartbeat_interval(&zero);
1094        let duration = Duration::from_millis(interval_ms);
1095        assert!(duration.as_millis() > 0, "duration must be non-zero");
1096    }
1097}