Skip to main content

djs_gateway/
config.rs

1//! Shard configuration.
2
3use core::{fmt, time::Duration};
4use std::sync::Arc;
5
6use djs_model::gateway::{
7    Intents,
8    payload::{IdentifyProperties, UpdatePresence},
9};
10use tokio_websockets::Connector;
11
12use crate::{Compression, IdentifyQueue, LocalIdentifyQueue};
13
14/// The default gateway URL, used until a URL from
15/// [Get Gateway Bot](https://docs.discord.com/developers/events/gateway#get-gateway-bot) is
16/// provided.
17pub const DEFAULT_GATEWAY_URL: &str = "wss://gateway.discord.gg";
18
19/// The configuration of a [`Shard`](crate::Shard).
20///
21/// Cheap to clone. Clones share the TLS configuration and the [IDENTIFY
22/// queue](ConfigBuilder::identify_queue), so shards created from clones of one configuration
23/// take turns identifying. Build one with [`Config::builder`].
24///
25/// The [`Debug`] implementation redacts the token.
26///
27/// discord.js counterpart: `WebSocketManagerOptions` (`@discordjs/ws`).
28#[derive(Clone)]
29pub struct Config {
30    pub(crate) token: Box<str>,
31    pub(crate) intents: Intents,
32    pub(crate) gateway_url: Box<str>,
33    pub(crate) compression: Compression,
34    pub(crate) properties: IdentifyProperties,
35    pub(crate) large_threshold: Option<u8>,
36    pub(crate) connect_timeout: Duration,
37    pub(crate) hello_timeout: Duration,
38    pub(crate) tls: Arc<Connector>,
39    pub(crate) identify_queue: Arc<dyn IdentifyQueue>,
40    pub(crate) presence: Option<UpdatePresence>,
41}
42
43impl Config {
44    /// Creates a configuration with default settings.
45    ///
46    /// Pass the raw token, without the `Bot ` prefix.
47    ///
48    /// discord.js counterpart: `new WebSocketManager(options)` (`@discordjs/ws`).
49    #[must_use]
50    pub fn new(token: impl Into<String>, intents: Intents) -> Self {
51        Self::builder(token, intents).build()
52    }
53
54    /// Returns a builder to customise the configuration.
55    ///
56    /// discord.js counterpart: `WebSocketManagerOptions` (`@discordjs/ws`).
57    ///
58    /// # Examples
59    ///
60    /// ```
61    /// use djs_gateway::{Compression, Config};
62    /// use djs_model::gateway::Intents;
63    ///
64    /// let config = Config::builder("my-token", Intents::GUILDS | Intents::GUILD_MESSAGES)
65    ///     .gateway_url("wss://gateway.discord.gg")
66    ///     .compression(Compression::None)
67    ///     .large_threshold(250)
68    ///     .build();
69    /// assert_eq!(config.intents(), Intents::GUILDS | Intents::GUILD_MESSAGES);
70    /// ```
71    pub fn builder(token: impl Into<String>, intents: Intents) -> ConfigBuilder {
72        ConfigBuilder {
73            config: Self {
74                token: token.into().into_boxed_str(),
75                intents,
76                gateway_url: DEFAULT_GATEWAY_URL.into(),
77                compression: Compression::default(),
78                properties: IdentifyProperties::new("djs-rs"),
79                large_threshold: None,
80                connect_timeout: Duration::from_secs(30),
81                hello_timeout: Duration::from_secs(60),
82                tls: Arc::new(crate::tls::connector()),
83                identify_queue: Arc::new(LocalIdentifyQueue::default()),
84                presence: None,
85            },
86        }
87    }
88
89    /// Returns the gateway intents.
90    ///
91    /// discord.js counterpart: the `intents` option of `WebSocketManagerOptions` (`@discordjs/ws`).
92    #[must_use]
93    pub const fn intents(&self) -> Intents {
94        self.intents
95    }
96
97    /// Returns the gateway URL used for new sessions.
98    ///
99    /// discord.js counterpart: none (`@discordjs/ws` uses the URL of Get Gateway Bot).
100    #[must_use]
101    pub fn gateway_url(&self) -> &str {
102        &self.gateway_url
103    }
104
105    /// Returns the transport compression.
106    ///
107    /// discord.js counterpart: the `compression` option of `WebSocketManagerOptions` (`@discordjs/ws`).
108    #[must_use]
109    pub const fn compression(&self) -> Compression {
110        self.compression
111    }
112
113    /// Returns the presence shards using this configuration start with.
114    ///
115    /// discord.js counterpart: the `initialPresence` option of `WebSocketManagerOptions` (`@discordjs/ws`).
116    #[must_use]
117    pub const fn presence(&self) -> Option<&UpdatePresence> {
118        self.presence.as_ref()
119    }
120
121    /// Returns the queue shards using this configuration wait in before identifying.
122    ///
123    /// discord.js counterpart: the `buildIdentifyThrottler` option of `WebSocketManagerOptions` (`@discordjs/ws`).
124    #[must_use]
125    pub fn identify_queue(&self) -> &Arc<dyn IdentifyQueue> {
126        &self.identify_queue
127    }
128}
129
130impl fmt::Debug for Config {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.debug_struct("Config")
133            .field("token", &"<redacted>")
134            .field("intents", &self.intents)
135            .field("gateway_url", &self.gateway_url)
136            .field("compression", &self.compression)
137            .field("properties", &self.properties)
138            .field("large_threshold", &self.large_threshold)
139            .field("connect_timeout", &self.connect_timeout)
140            .field("hello_timeout", &self.hello_timeout)
141            .field("identify_queue", &self.identify_queue)
142            .field("presence", &self.presence)
143            .finish_non_exhaustive()
144    }
145}
146
147/// Builds a [`Config`]. Created by [`Config::builder`].
148///
149/// discord.js counterpart: `WebSocketManagerOptions` (`@discordjs/ws`).
150#[derive(Debug)]
151#[must_use = "a builder does nothing until `build` is called"]
152pub struct ConfigBuilder {
153    config: Config,
154}
155
156impl ConfigBuilder {
157    /// Sets the gateway URL for new sessions (default [`DEFAULT_GATEWAY_URL`]).
158    ///
159    /// Use the URL returned by Get Gateway Bot. Resumes always use the `resume_gateway_url`
160    /// from the `READY` event instead. `ws://` URLs are accepted (useful for tests and proxies).
161    ///
162    /// discord.js counterpart: none (`@discordjs/ws` uses the URL of Get Gateway Bot).
163    pub fn gateway_url(mut self, url: impl Into<String>) -> Self {
164        self.config.gateway_url = url.into().into_boxed_str();
165        self
166    }
167
168    /// Sets the transport compression (default [`Compression::ZstdStream`] when the
169    /// `zstd-stream` feature is enabled).
170    ///
171    /// discord.js counterpart: the `compression` option of `WebSocketManagerOptions` (`@discordjs/ws`).
172    pub const fn compression(mut self, compression: Compression) -> Self {
173        self.config.compression = compression;
174        self
175    }
176
177    /// Sets the connection properties sent when identifying (default: library `djs-rs`).
178    ///
179    /// discord.js counterpart: the `identifyProperties` option of `WebSocketManagerOptions` (`@discordjs/ws`).
180    pub fn identify_properties(mut self, properties: IdentifyProperties) -> Self {
181        self.config.properties = properties;
182        self
183    }
184
185    /// Sets the member count (50–250) above which Discord stops sending offline members of a
186    /// guild (Discord's default is 50).
187    ///
188    /// discord.js counterpart: the `largeThreshold` option of `WebSocketManagerOptions` (`@discordjs/ws`).
189    pub const fn large_threshold(mut self, threshold: u8) -> Self {
190        self.config.large_threshold = Some(threshold);
191        self
192    }
193
194    /// Sets how long establishing the WebSocket connection (TCP, TLS and upgrade) may take
195    /// (default 30 s).
196    ///
197    /// discord.js counterpart: the `handshakeTimeout` option of `WebSocketManagerOptions` (`@discordjs/ws`).
198    pub const fn connect_timeout(mut self, timeout: Duration) -> Self {
199        self.config.connect_timeout = timeout;
200        self
201    }
202
203    /// Sets how long to wait for the Hello payload after connecting before reconnecting
204    /// (default 60 s).
205    ///
206    /// discord.js counterpart: the `helloTimeout` option of `WebSocketManagerOptions` (`@discordjs/ws`).
207    pub const fn hello_timeout(mut self, timeout: Duration) -> Self {
208        self.config.hello_timeout = timeout;
209        self
210    }
211
212    /// Sets the presence (status and activities) sent when identifying (default: none, the bot
213    /// appears online without an activity).
214    ///
215    /// A shard uses it until [`MessageSender::update_presence`](crate::MessageSender::update_presence)
216    /// replaces it; that presence is then also kept for later sessions.
217    ///
218    /// discord.js counterpart: the `presence` client option.
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// use djs_gateway::Config;
224    /// use djs_model::gateway::{Activity, Intents, Status, payload::UpdatePresence};
225    ///
226    /// let config = Config::builder("my-token", Intents::GUILDS)
227    ///     .presence(UpdatePresence::new(Status::Online, [Activity::watching("you")]))
228    ///     .build();
229    /// assert!(config.presence().is_some());
230    /// ```
231    pub fn presence(mut self, presence: UpdatePresence) -> Self {
232        self.config.presence = Some(presence);
233        self
234    }
235
236    /// Sets the queue shards wait in before identifying (default: a new
237    /// [`LocalIdentifyQueue`] with `max_concurrency` 1, shared by clones of the configuration).
238    ///
239    /// Pass a [`LocalIdentifyQueue`] created with the bot's `max_concurrency` to start several
240    /// shards at once, or an own [`IdentifyQueue`] to coordinate several processes.
241    ///
242    /// discord.js counterpart: the `buildIdentifyThrottler` option of `WebSocketManagerOptions` (`@discordjs/ws`).
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use std::sync::Arc;
248    ///
249    /// use djs_gateway::{Config, LocalIdentifyQueue};
250    /// use djs_model::gateway::Intents;
251    ///
252    /// let config = Config::builder("my-token", Intents::GUILDS)
253    ///     .identify_queue(Arc::new(LocalIdentifyQueue::new(16)))
254    ///     .build();
255    /// assert!(format!("{config:?}").contains("max_concurrency: 16"));
256    /// ```
257    pub fn identify_queue(mut self, queue: Arc<dyn IdentifyQueue>) -> Self {
258        self.config.identify_queue = queue;
259        self
260    }
261
262    /// Builds the configuration.
263    ///
264    /// discord.js counterpart: `new WebSocketManager(options)` (`@discordjs/ws`).
265    #[must_use]
266    pub fn build(self) -> Config {
267        self.config
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use core::time::Duration;
274    use std::sync::Arc;
275
276    use djs_model::gateway::{
277        Intents, Status,
278        payload::{IdentifyProperties, UpdatePresence},
279    };
280
281    use super::Config;
282    use crate::{Compression, LocalIdentifyQueue};
283
284    #[test]
285    fn defaults() {
286        let config = Config::new("a-token", Intents::GUILDS);
287        assert_eq!(config.intents(), Intents::GUILDS);
288        assert_eq!(config.gateway_url(), super::DEFAULT_GATEWAY_URL);
289        assert_eq!(config.compression(), Compression::default());
290        assert!(config.presence().is_none());
291        assert_eq!(config.connect_timeout, Duration::from_secs(30));
292        assert_eq!(config.hello_timeout, Duration::from_secs(60));
293        assert_eq!(config.large_threshold, None);
294    }
295
296    #[test]
297    fn every_setting_is_kept_and_the_token_is_never_shown() {
298        let queue = Arc::new(LocalIdentifyQueue::default());
299        let config = Config::builder("a-secret-token", Intents::GUILD_MESSAGES)
300            .gateway_url("wss://gateway.example.com")
301            .compression(Compression::None)
302            .identify_properties(IdentifyProperties::new("my-bot"))
303            .large_threshold(100)
304            .connect_timeout(Duration::from_secs(5))
305            .hello_timeout(Duration::from_secs(7))
306            .presence(UpdatePresence::new(Status::Idle, []))
307            .identify_queue(queue)
308            .build();
309        assert_eq!(config.gateway_url(), "wss://gateway.example.com");
310        assert_eq!(config.compression(), Compression::None);
311        assert_eq!(config.large_threshold, Some(100));
312        assert_eq!(config.connect_timeout, Duration::from_secs(5));
313        assert_eq!(config.hello_timeout, Duration::from_secs(7));
314        assert!(config.presence().is_some());
315        let debug = format!("{config:?}");
316        assert!(!debug.contains("a-secret-token"), "{debug}");
317        assert!(
318            debug.contains("<redacted>") && debug.contains("my-bot"),
319            "{debug}"
320        );
321        let builder = format!("{:?}", Config::builder("a-secret-token", Intents::GUILDS));
322        assert!(!builder.contains("a-secret-token"), "{builder}");
323    }
324}