Skip to main content

djs_rs/manager/
gateway.rs

1//! Requests answered through the gateway rather than REST (D-265, D-270): guild members
2//! ([`MemberManager::fetch_all`](super::MemberManager::fetch_all) and its siblings) and
3//! soundboard sounds ([`GuildManager::fetch_soundboard_sounds`](super::GuildManager::fetch_soundboard_sounds)).
4//!
5//! Each request is sent on the shard of its guild with a nonce of the client; the answers
6//! reach it through the collectors' index (D-264), and what they carry is cached.
7
8use core::{
9    fmt,
10    future::{Future, IntoFuture},
11    pin::Pin,
12    time::Duration,
13};
14use std::{
15    collections::{HashMap, hash_map::Entry},
16    sync::Arc,
17};
18
19use djs_cache::{Backend, CachedMember};
20use djs_collection::Collection;
21use djs_gateway::SendError;
22use djs_model::{
23    gateway::{
24        ShardId,
25        payload::{GuildMembersChunk, RequestGuildMembers, RequestSoundboardSounds},
26    },
27    id::{GuildId, SoundboardSoundId, UserId},
28    soundboard::SoundboardSound,
29};
30use tokio::{sync::mpsc, time::Instant};
31
32use crate::{
33    Context,
34    cache_ops::CacheOps,
35    collector::{EndReason, Key, MemberReply, NONCE_PREFIX, Signal, Sink},
36    context::Core,
37};
38
39/// Why a request answered through the gateway failed.
40///
41/// discord.js counterpart: the `GuildMembersTimeout` and `GuildSoundboardSoundsTimeout`
42/// errors.
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum GatewayRequestError {
46    /// The guild's shard does not run in this client (with
47    /// [`Shards::Range`](crate::Shards::Range), another process runs it).
48    #[error("the shard of guild {0} does not run in this client")]
49    ShardNotRunning(GuildId),
50    /// The request could not be queued on the shard (it stopped).
51    #[error("the request could not be sent")]
52    Send(#[from] SendError),
53    /// Discord did not answer completely in time.
54    #[error("the gateway did not answer in time")]
55    Timeout,
56    /// Discord rate limited the request (`RATE_LIMITED`); it may be sent again after
57    /// `retry_after`.
58    #[error("the request was rate limited; retry after {retry_after:?}")]
59    RateLimited {
60        /// How long to wait before asking again.
61        retry_after: Duration,
62    },
63    /// The wait ended before the answer: the guild was deleted or the client shut down.
64    #[error("the request ended before its answer: {0}")]
65    Ended(EndReason),
66}
67
68/// What the members request asks for.
69#[derive(Clone, Debug)]
70enum Members {
71    /// Every member, or those whose name starts with the query.
72    Query { query: String, limit: u32 },
73    /// The members with these IDs.
74    Users(Vec<UserId>),
75}
76
77/// A request of guild members through the gateway, not sent yet: configure it, then
78/// `.await` it. Made by [`MemberManager::fetch_all`](super::MemberManager::fetch_all),
79/// [`fetch_by_query`](super::MemberManager::fetch_by_query) and
80/// [`fetch_many`](super::MemberManager::fetch_many) (D-270).
81///
82/// discord.js counterpart: the options of `GuildMemberManager#fetch`.
83#[must_use = "the request is only sent when awaited"]
84pub struct FetchMembers<'a, B: Backend> {
85    ctx: &'a Context<B>,
86    guild_id: GuildId,
87    members: Members,
88    presences: bool,
89    time: Duration,
90}
91
92impl<B: Backend> fmt::Debug for FetchMembers<'_, B> {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.debug_struct("FetchMembers")
95            .field("guild_id", &self.guild_id)
96            .field("members", &self.members)
97            .field("presences", &self.presences)
98            .field("time", &self.time)
99            .finish_non_exhaustive()
100    }
101}
102
103/// The time discord.js waits for the members' chunks.
104const MEMBERS_TIME: Duration = Duration::from_secs(120);
105
106/// The most user IDs Discord accepts in one request.
107const MAX_USER_IDS: usize = 100;
108
109impl<'a, B: Backend> FetchMembers<'a, B> {
110    pub(crate) fn all(ctx: &'a Context<B>, guild_id: GuildId) -> Self {
111        Self::new(
112            ctx,
113            guild_id,
114            Members::Query {
115                query: String::new(),
116                limit: 0,
117            },
118        )
119    }
120
121    pub(crate) fn query(ctx: &'a Context<B>, guild_id: GuildId, query: String) -> Self {
122        Self::new(ctx, guild_id, Members::Query { query, limit: 100 })
123    }
124
125    pub(crate) fn users(ctx: &'a Context<B>, guild_id: GuildId, users: Vec<UserId>) -> Self {
126        Self::new(ctx, guild_id, Members::Users(users))
127    }
128
129    const fn new(ctx: &'a Context<B>, guild_id: GuildId, members: Members) -> Self {
130        Self {
131            ctx,
132            guild_id,
133            members,
134            presences: false,
135            time: MEMBERS_TIME,
136        }
137    }
138
139    /// The most members to return (for [`fetch_by_query`](super::MemberManager::fetch_by_query):
140    /// 1–100, 100 by default; for [`fetch_all`](super::MemberManager::fetch_all): 0, every
141    /// member, by default). No effect on [`fetch_many`](super::MemberManager::fetch_many).
142    ///
143    /// discord.js counterpart: the `limit` option.
144    pub const fn limit(mut self, limit: u32) -> Self {
145        if let Members::Query { limit: current, .. } = &mut self.members {
146            *current = limit;
147        }
148        self
149    }
150
151    /// Also asks for the members' presences, which are cached (needs the privileged
152    /// `GUILD_PRESENCES` intent).
153    ///
154    /// discord.js counterpart: the `withPresences` option.
155    pub const fn presences(mut self, presences: bool) -> Self {
156        self.presences = presences;
157        self
158    }
159
160    /// How long to wait for the whole answer (120 seconds by default, as in discord.js).
161    ///
162    /// discord.js counterpart: the `time` option.
163    pub const fn time(mut self, time: Duration) -> Self {
164        self.time = time;
165        self
166    }
167}
168
169/// The future of a [`FetchMembers`].
170type MembersFuture<'a> = Pin<
171    Box<
172        dyn Future<Output = Result<Collection<UserId, Arc<CachedMember>>, GatewayRequestError>>
173            + Send
174            + 'a,
175    >,
176>;
177
178/// The future of [`fetch_soundboard_sounds`].
179pub(crate) type SoundsFuture<'a> =
180    Pin<Box<dyn Future<Output = Result<GuildSoundboardSounds, GatewayRequestError>> + Send + 'a>>;
181
182/// The request loop of [`FetchMembers`]. Neither generic nor `async`: the future is created
183/// and boxed here, so that its code is compiled in djs-rs (D-289).
184fn fetch_members(
185    ctx: &Core,
186    guild_id: GuildId,
187    members: Members,
188    presences: bool,
189    time: Duration,
190) -> MembersFuture<'_> {
191    Box::pin(async move {
192        let sender = ctx
193            .guild_shard(guild_id)
194            .ok_or(GatewayRequestError::ShardNotRunning(guild_id))?;
195        let deadline = Instant::now().checked_add(time);
196        let requests: Vec<RequestGuildMembers> = match members {
197            Members::Query { query, limit } => {
198                vec![RequestGuildMembers::query(guild_id, query, limit)]
199            }
200            Members::Users(users) => users
201                .chunks(MAX_USER_IDS)
202                .map(|users| RequestGuildMembers::users(guild_id, users.iter().copied()))
203                .collect(),
204        };
205        let mut fetched = Collection::new();
206        for mut request in requests {
207            let nonce = ctx.collectors().nonce();
208            let (tx, mut rx) = mpsc::unbounded_channel();
209            let _registration = ctx.collectors().register(
210                Key::Nonce(nonce),
211                Some(guild_id),
212                None,
213                Sink::MemberChunks(tx),
214            );
215            request.presences = presences;
216            request.nonce = Some(format!("{NONCE_PREFIX}{nonce}").into());
217            sender.command(&request)?;
218            let mut received = 0;
219            loop {
220                let reply = match deadline {
221                    Some(deadline) => tokio::time::timeout_at(deadline, rx.recv())
222                        .await
223                        .map_err(|_| GatewayRequestError::Timeout)?,
224                    None => rx.recv().await,
225                };
226                match reply {
227                    Some(Signal::Item(MemberReply::Chunk(chunk))) => {
228                        received += 1;
229                        add_members(ctx.ops(), &chunk, &mut fetched);
230                        if received >= chunk.chunk_count {
231                            break;
232                        }
233                    }
234                    Some(Signal::Item(MemberReply::RateLimited(retry_after))) => {
235                        return Err(GatewayRequestError::RateLimited { retry_after });
236                    }
237                    Some(Signal::End(reason)) => return Err(GatewayRequestError::Ended(reason)),
238                    None => return Err(GatewayRequestError::Ended(EndReason::Shutdown)),
239                }
240            }
241        }
242        Ok(fetched)
243    })
244}
245
246/// Adds a chunk's members to `fetched`, as the cache stored them while handling the chunk
247/// (converted here when the cache keeps no members).
248fn add_members(
249    ops: &dyn CacheOps,
250    chunk: &GuildMembersChunk,
251    fetched: &mut Collection<UserId, Arc<CachedMember>>,
252) {
253    for member in &chunk.members {
254        let stored = ops
255            .member(chunk.guild_id, member.user.id)
256            .unwrap_or_else(|| ops.store_member(chunk.guild_id, member));
257        fetched.insert(member.user.id, stored);
258    }
259}
260
261impl<'a, B: Backend> IntoFuture for FetchMembers<'a, B> {
262    type Output = Result<Collection<UserId, Arc<CachedMember>>, GatewayRequestError>;
263    type IntoFuture = MembersFuture<'a>;
264
265    fn into_future(self) -> Self::IntoFuture {
266        let Self {
267            ctx,
268            guild_id,
269            members,
270            presences,
271            time,
272        } = self;
273        fetch_members(ctx.core(), guild_id, members, presences, time)
274    }
275}
276
277/// The soundboard sounds of several guilds, by guild and sound.
278pub type GuildSoundboardSounds =
279    Collection<GuildId, Collection<SoundboardSoundId, Arc<SoundboardSound>>>;
280
281/// Requests the soundboard sounds of `guild_ids` on their shards and waits up to `time` for
282/// every answer. Not `async`: the future is boxed here, so that its code is compiled in
283/// djs-rs (D-289).
284pub(crate) fn fetch_soundboard_sounds(
285    ctx: &Core,
286    guild_ids: Vec<GuildId>,
287    time: Duration,
288) -> SoundsFuture<'_> {
289    Box::pin(async move {
290        let deadline = Instant::now().checked_add(time);
291        let (tx, mut rx) = mpsc::unbounded_channel();
292        let mut registrations = Vec::with_capacity(guild_ids.len());
293        let mut by_shard: HashMap<u32, (djs_gateway::MessageSender, Vec<GuildId>)> = HashMap::new();
294        let total = ctx.shard_id().total();
295        for &guild_id in &guild_ids {
296            let number = ShardId::for_guild(guild_id, total).number();
297            let (_, guilds) = match by_shard.entry(number) {
298                Entry::Occupied(entry) => entry.into_mut(),
299                Entry::Vacant(entry) => {
300                    let sender = ctx
301                        .guild_shard(guild_id)
302                        .ok_or(GatewayRequestError::ShardNotRunning(guild_id))?;
303                    entry.insert((sender, Vec::new()))
304                }
305            };
306            guilds.push(guild_id);
307            registrations.push(ctx.collectors().register(
308                Key::Sounds(guild_id),
309                Some(guild_id),
310                None,
311                Sink::SoundboardSounds(tx.clone()),
312            ));
313        }
314        drop(tx);
315        for (sender, guilds) in by_shard.into_values() {
316            sender.command(&RequestSoundboardSounds::new(guilds))?;
317        }
318        let mut fetched = GuildSoundboardSounds::new();
319        while fetched.len() < guild_ids.len() {
320            let reply = match deadline {
321                Some(deadline) => tokio::time::timeout_at(deadline, rx.recv())
322                    .await
323                    .map_err(|_| GatewayRequestError::Timeout)?,
324                None => rx.recv().await,
325            };
326            match reply {
327                Some(Signal::Item(sounds)) => {
328                    let guild_id = sounds.guild_id;
329                    let stored = sounds
330                        .soundboard_sounds
331                        .iter()
332                        .map(|sound| {
333                            (
334                                sound.sound_id,
335                                ctx.ops().store_soundboard_sound(guild_id, sound),
336                            )
337                        })
338                        .collect();
339                    fetched.insert(guild_id, stored);
340                }
341                Some(Signal::End(reason)) => return Err(GatewayRequestError::Ended(reason)),
342                None => return Err(GatewayRequestError::Ended(EndReason::Shutdown)),
343            }
344        }
345        drop(registrations);
346        Ok(fetched)
347    })
348}