Skip to main content

djs_gateway/
queue.rs

1//! The IDENTIFY queue shared by shards (D-141, D-144).
2
3use core::{fmt, future::Future, pin::Pin, time::Duration};
4use std::sync::Arc;
5
6use djs_model::gateway::ShardId;
7use tokio::{
8    sync::Mutex,
9    time::{Instant, sleep_until},
10};
11
12/// Minimum time between two identifies of the same rate-limit bucket. Discord allows one per
13/// 5 seconds; the extra 100 ms absorbs network jitter.
14pub(crate) const IDENTIFY_INTERVAL: Duration = Duration::from_millis(5_100);
15
16/// Decides when a shard may send its IDENTIFY payload.
17///
18/// Discord lets a bot start [`max_concurrency`] sessions every 5 seconds: shard `n` belongs to
19/// the rate-limit bucket `n % max_concurrency`, and each bucket accepts one IDENTIFY per
20/// 5 seconds. Identifying too fast gets the connection closed. Every [`Shard`] waits for its
21/// turn here before identifying — on the first connection and whenever its session has to be
22/// started again (resuming does not identify).
23///
24/// [`LocalIdentifyQueue`] coordinates the shards of one process and is the default. Implement
25/// this trait to coordinate several processes, for example through a shared store.
26///
27/// discord.js counterpart: `IIdentifyThrottler` from `@discordjs/ws`.
28///
29/// [`max_concurrency`]: https://docs.discord.com/developers/events/gateway#session-start-limit-object
30/// [`Shard`]: crate::Shard
31///
32/// # Examples
33///
34/// A queue that lets every shard identify at once — only correct if something else (here, a
35/// proxy in front of the gateway) does the throttling:
36///
37/// ```
38/// use core::{future::Future, pin::Pin};
39///
40/// use djs_gateway::IdentifyQueue;
41/// use djs_model::gateway::ShardId;
42///
43/// #[derive(Debug)]
44/// struct ProxyThrottles;
45///
46/// impl IdentifyQueue for ProxyThrottles {
47///     fn wait_turn(&self, _shard: ShardId) -> Pin<Box<dyn Future<Output = ()> + Send>> {
48///         Box::pin(async {})
49///     }
50/// }
51/// ```
52pub trait IdentifyQueue: fmt::Debug + Send + Sync {
53    /// Returns a future that completes when `shard` may identify.
54    ///
55    /// The shard sends IDENTIFY right after the future completes, so an implementation should
56    /// count the identify as made at that moment. The future is dropped without completing if
57    /// the shard's connection closes while it waits; the shard then leaves the queue and asks
58    /// again on its next connection.
59    fn wait_turn(&self, shard: ShardId) -> Pin<Box<dyn Future<Output = ()> + Send>>;
60}
61
62/// The in-process [`IdentifyQueue`]: one IDENTIFY per rate-limit bucket every 5 seconds.
63///
64/// Shards of the same bucket identify one after another, in the order they asked; buckets
65/// are independent. Share one queue (behind an [`Arc`]) between all shards of a process —
66/// [`create_shards`](crate::create_shards) and cloned [`Config`](crate::Config)s do that.
67///
68/// discord.js counterpart: `SimpleIdentifyThrottler` from `@discordjs/ws`.
69///
70/// # Examples
71///
72/// ```
73/// use std::sync::Arc;
74///
75/// use djs_gateway::{Config, LocalIdentifyQueue};
76/// use djs_model::gateway::Intents;
77///
78/// // `max_concurrency` comes from Get Gateway Bot's `session_start_limit`.
79/// let queue = Arc::new(LocalIdentifyQueue::new(16));
80/// let config = Config::builder("my-token", Intents::GUILDS)
81///     .identify_queue(queue)
82///     .build();
83/// ```
84#[derive(Clone)]
85pub struct LocalIdentifyQueue {
86    /// When each bucket last let a shard identify. The mutex is fair, so waiting shards are
87    /// served in order.
88    buckets: Arc<[Mutex<Option<Instant>>]>,
89}
90
91impl LocalIdentifyQueue {
92    /// Creates a queue for a bot whose `max_concurrency` (from Get Gateway Bot's
93    /// `session_start_limit`) is the given value. `0` is treated as `1`.
94    ///
95    /// discord.js counterpart: `new SimpleIdentifyThrottler(maxConcurrency)` (`@discordjs/ws`).
96    #[must_use]
97    pub fn new(max_concurrency: u32) -> Self {
98        let buckets = (0..max_concurrency.max(1))
99            .map(|_| Mutex::new(None))
100            .collect();
101        Self { buckets }
102    }
103
104    /// Returns the number of rate-limit buckets (the `max_concurrency` the queue was created
105    /// with, at least `1`).
106    ///
107    /// discord.js counterpart: the `maxConcurrency` of `SimpleIdentifyThrottler` (`@discordjs/ws`).
108    #[must_use]
109    pub fn max_concurrency(&self) -> u32 {
110        // Created from a `u32`, so this never saturates.
111        u32::try_from(self.buckets.len()).unwrap_or(u32::MAX)
112    }
113}
114
115impl Default for LocalIdentifyQueue {
116    /// A queue with `max_concurrency` 1: one IDENTIFY every 5 seconds.
117    fn default() -> Self {
118        Self::new(1)
119    }
120}
121
122impl fmt::Debug for LocalIdentifyQueue {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_struct("LocalIdentifyQueue")
125            .field("max_concurrency", &self.buckets.len())
126            .finish()
127    }
128}
129
130impl IdentifyQueue for LocalIdentifyQueue {
131    fn wait_turn(&self, shard: ShardId) -> Pin<Box<dyn Future<Output = ()> + Send>> {
132        let buckets = Arc::clone(&self.buckets);
133        let bucket = shard.number() as usize % buckets.len();
134        Box::pin(async move {
135            let mut last = buckets[bucket].lock().await;
136            if let Some(last) = *last {
137                sleep_until(last + IDENTIFY_INTERVAL).await;
138            }
139            *last = Some(Instant::now());
140        })
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::{IDENTIFY_INTERVAL, IdentifyQueue, Instant, LocalIdentifyQueue, ShardId};
147
148    async fn turn(queue: &LocalIdentifyQueue, number: u32) -> Instant {
149        queue.wait_turn(ShardId::new(number, 64)).await;
150        Instant::now()
151    }
152
153    // No sockets here, so tokio's paused clock is reliable.
154    #[tokio::test(start_paused = true)]
155    async fn one_identify_per_bucket_every_interval() {
156        let queue = LocalIdentifyQueue::new(4);
157        let start = Instant::now();
158        // Shards 0..8: two per bucket.
159        let mut turns = Vec::new();
160        for number in 0..8 {
161            turns.push(tokio::spawn({
162                let queue = queue.clone();
163                async move { turn(&queue, number).await }
164            }));
165        }
166        let mut at = Vec::new();
167        for task in turns {
168            at.push(task.await.unwrap() - start);
169        }
170        // The first shard of every bucket identifies at once, the second one interval later.
171        assert!(at[..4].iter().all(|&after| after.is_zero()), "{at:?}");
172        assert!(
173            at[4..].iter().all(|&after| after == IDENTIFY_INTERVAL),
174            "{at:?}"
175        );
176    }
177
178    #[tokio::test(start_paused = true)]
179    async fn a_shard_waits_for_its_own_previous_identify() {
180        let queue = LocalIdentifyQueue::default();
181        let first = turn(&queue, 0).await;
182        let again = turn(&queue, 0).await;
183        assert_eq!(again - first, IDENTIFY_INTERVAL);
184    }
185
186    #[tokio::test(start_paused = true)]
187    async fn cancelled_waits_take_no_turn() {
188        let queue = LocalIdentifyQueue::new(1);
189        let start = turn(&queue, 0).await;
190        // A shard that gives up while waiting (its connection closed) takes no turn.
191        let abandoned = queue.wait_turn(ShardId::new(1, 64));
192        let waited = tokio::time::timeout(IDENTIFY_INTERVAL / 2, abandoned).await;
193        assert!(waited.is_err(), "the turn came too early");
194        let next = turn(&queue, 2).await;
195        assert_eq!(next - start, IDENTIFY_INTERVAL);
196        let after = turn(&queue, 3).await;
197        assert_eq!(after - start, IDENTIFY_INTERVAL * 2);
198    }
199
200    #[test]
201    fn zero_concurrency_means_one_bucket() {
202        assert_eq!(LocalIdentifyQueue::new(0).max_concurrency(), 1);
203        assert_eq!(LocalIdentifyQueue::new(16).max_concurrency(), 16);
204    }
205}