Skip to main content

djs_rs/
router.rs

1//! The interaction router (D-251–D-255): handlers registered by command name or by component
2//! and modal `custom_id`, next to [`Events::InteractionCreate`](crate::Events::InteractionCreate).
3//!
4//! | Registration | Interactions | Handler argument |
5//! |---|---|---|
6//! | [`Client::command`](crate::Client::command) | commands (slash and context menu) | [`CommandInteraction`] |
7//! | [`Client::autocomplete`](crate::Client::autocomplete) | autocomplete of a command's options | [`AutocompleteInteraction`] |
8//! | [`Client::component`](crate::Client::component) | buttons and select menus | [`ComponentInteraction`] |
9//! | [`Client::modal`](crate::Client::modal) | modal submissions | [`ModalInteraction`] |
10//!
11//! - **Commands** are routed by their full name as Discord shows it (D-253): `"ping"`,
12//!   `"mod ban"`, `"mod config set"`, or the name of a context menu command (`"Report
13//!   Message"`). A route for `"mod"` (or `"mod config"`) catches the subcommands that have no
14//!   route of their own. Slash and context menu commands sharing a name share the route; the
15//!   handler can tell them apart by [`kind`](djs_model::interaction::CommandData::kind).
16//! - **Components and modals** are routed by the part of their `custom_id` before the first
17//!   `:` (D-254): the route `"vote"` receives `vote` and `vote:42`, and
18//!   [`args`](ComponentInteraction::args) returns `42`.
19//! - Routes only route (D-255): commands are registered with Discord through
20//!   [`ctx.commands()`](crate::Context::commands), and
21//!   [`Events::InteractionCreate`](crate::Events::InteractionCreate) is still emitted for every
22//!   interaction, routed or not.
23//!
24//! Every wrapper holds the event's `Arc` (no copy), dereferences to the typed data and
25//! implements [`InteractionExt`](crate::ext::InteractionExt), so `cmd.get_string("reason")`
26//! and `cmd.reply(&ctx, …)` both work.
27//!
28//! discord.js has no router: its counterpart is a `switch` on `interaction.commandName` in the
29//! `interactionCreate` listener.
30
31use core::{fmt, ops::Deref};
32use std::{collections::HashMap, future::Future, sync::Arc};
33
34use djs_cache::Backend;
35use djs_model::{
36    gateway::payload::InteractionCreate,
37    interaction::{CommandData, ComponentData, Interaction, InteractionData, ModalSubmitData},
38};
39
40use crate::{
41    Context,
42    handler::{BoxFuture, HandlerError},
43};
44
45/// Defines a wrapper over an interaction of one kind, dereferencing to its data.
46macro_rules! wrapper {
47    (
48        $(#[$doc:meta])*
49        $name:ident => $variant:ident($data:ty)
50    ) => {
51        $(#[$doc])*
52        #[derive(Clone)]
53        pub struct $name {
54            event: Arc<InteractionCreate>,
55        }
56
57        impl $name {
58            /// Wraps `event`, if it is an interaction of this kind.
59            pub(crate) fn new(event: &Arc<InteractionCreate>) -> Option<Self> {
60                matches!(event.data, InteractionData::$variant(_)).then(|| Self {
61                    event: Arc::clone(event),
62                })
63            }
64
65            /// Returns the whole interaction: its guild, channel, member, locale, …
66            ///
67            /// discord.js counterpart: the interaction itself (discord.js routes nothing).
68            #[must_use]
69            pub fn interaction(&self) -> &Interaction {
70                &self.event
71            }
72
73            /// Returns the event payload, shared with the
74            /// [`InteractionCreate`](crate::Events::InteractionCreate) handlers.
75            ///
76            /// discord.js counterpart: the event's arguments.
77            #[must_use]
78            pub const fn event(&self) -> &Arc<InteractionCreate> {
79                &self.event
80            }
81        }
82
83        impl Deref for $name {
84            type Target = $data;
85
86            fn deref(&self) -> &$data {
87                match &self.event.data {
88                    InteractionData::$variant(data) => data,
89                    // `new` checked the kind, and the shared payload cannot change.
90                    _ => unreachable!(concat!("a ", stringify!($name), " of another kind")),
91                }
92            }
93        }
94
95        impl fmt::Debug for $name {
96            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97                // The interaction's `Debug` does not print its token.
98                f.debug_tuple(stringify!($name)).field(self.interaction()).finish()
99            }
100        }
101    };
102}
103
104wrapper! {
105    /// A command interaction given to a [`Client::command`](crate::Client::command) route
106    /// (D-252): dereferences to the [`CommandData`] (`get_string`, `subcommand`, …) and
107    /// answers through [`InteractionExt`](crate::ext::InteractionExt) (`reply`,
108    /// `defer_reply`, …).
109    ///
110    /// discord.js counterpart: `ChatInputCommandInteraction` and the context menu command
111    /// interactions.
112    CommandInteraction => ApplicationCommand(CommandData)
113}
114
115wrapper! {
116    /// An autocomplete interaction given to a [`Client::autocomplete`](crate::Client::autocomplete)
117    /// route (D-252): dereferences to the [`CommandData`] (`focused_value`, `get_string`, …)
118    /// and answers with [`respond`](crate::ext::InteractionExt::respond).
119    ///
120    /// discord.js counterpart: `AutocompleteInteraction`.
121    AutocompleteInteraction => Autocomplete(CommandData)
122}
123
124wrapper! {
125    /// A component interaction given to a [`Client::component`](crate::Client::component)
126    /// route (D-252): dereferences to the [`ComponentData`] (`custom_id`, `values`, `users`,
127    /// …), with the [`args`](Self::args) of its custom ID, and answers through
128    /// [`InteractionExt`](crate::ext::InteractionExt) (`update`, `reply`, `show_modal`, …).
129    ///
130    /// discord.js counterpart: `ButtonInteraction` and the select menu interactions.
131    ComponentInteraction => MessageComponent(ComponentData)
132}
133
134wrapper! {
135    /// A modal-submit interaction given to a [`Client::modal`](crate::Client::modal) route
136    /// (D-252): dereferences to the [`ModalSubmitData`] (`text_value`, `selected_users`, …),
137    /// with the [`args`](Self::args) of its custom ID, and answers through
138    /// [`InteractionExt`](crate::ext::InteractionExt).
139    ///
140    /// discord.js counterpart: `ModalSubmitInteraction`.
141    ModalInteraction => ModalSubmit(ModalSubmitData)
142}
143
144/// The part of a custom ID after the route name and its `:` (D-254), `""` if none.
145fn args(custom_id: &str) -> &str {
146    custom_id.split_once(':').map_or("", |(_, args)| args)
147}
148
149/// The route name of a custom ID: the part before the first `:`.
150fn route_name(custom_id: &str) -> &str {
151    custom_id
152        .split_once(':')
153        .map_or(custom_id, |(name, _)| name)
154}
155
156impl ComponentInteraction {
157    /// Returns the part of the custom ID after the route name and its `:` (D-254): `"42"`
158    /// for `vote:42`, `"a:b"` for `vote:a:b`, `""` for `vote`.
159    ///
160    /// discord.js counterpart: none (discord.js leaves the `customId` to the bot).
161    ///
162    /// # Examples
163    ///
164    /// ```no_run
165    /// # use djs_rs::prelude::*;
166    /// # let client = Client::builder("token").build();
167    /// // A button with the custom ID `vote:42` votes for option 42.
168    /// client.component("vote", |ctx, button| async move {
169    ///     let option: u32 = button.args().parse()?;
170    ///     button.reply(&ctx, format!("You voted for {option}")).await?;
171    ///     Ok(())
172    /// });
173    /// ```
174    #[must_use]
175    pub fn args(&self) -> &str {
176        args(&self.custom_id)
177    }
178}
179
180impl ModalInteraction {
181    /// Returns the part of the modal's custom ID after the route name and its `:` (D-254),
182    /// `""` if none.
183    ///
184    /// discord.js counterpart: none (discord.js leaves the `customId` to the bot).
185    #[must_use]
186    pub fn args(&self) -> &str {
187        args(&self.custom_id)
188    }
189}
190
191/// A route's handler with its interaction type erased.
192pub(crate) trait ErasedRoute<B: Backend, W>: Send + Sync {
193    /// Spawns the handler on the tokio runtime (no extra boxing).
194    fn spawn(&self, ctx: &Context<B>, interaction: W);
195
196    /// Returns the handler future, for sequential execution.
197    fn call(&self, ctx: &Context<B>, interaction: W) -> BoxFuture;
198}
199
200/// A registered route: its name (for error logs) and its handler.
201pub(crate) struct Route<F> {
202    name: Arc<str>,
203    handler: F,
204}
205
206impl<F> Route<F> {
207    pub(crate) fn new(name: &str, handler: F) -> Self {
208        Self {
209            name: name.into(),
210            handler,
211        }
212    }
213}
214
215/// Runs a route's handler future and reports its error, if any.
216async fn run(route: Arc<str>, future: impl Future<Output = Result<(), HandlerError>>) {
217    if let Err(error) = future.await {
218        tracing::error!(route = &*route, %error, "interaction route handler returned an error");
219    }
220}
221
222impl<B, W, F, Fut> ErasedRoute<B, W> for Route<F>
223where
224    B: Backend,
225    F: Fn(Context<B>, W) -> Fut + Send + Sync + 'static,
226    Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
227{
228    fn spawn(&self, ctx: &Context<B>, interaction: W) {
229        let future = (self.handler)(ctx.clone(), interaction);
230        tokio::spawn(run(Arc::clone(&self.name), future));
231    }
232
233    fn call(&self, ctx: &Context<B>, interaction: W) -> BoxFuture {
234        let future = (self.handler)(ctx.clone(), interaction);
235        Box::pin(run(Arc::clone(&self.name), future))
236    }
237}
238
239/// The routes of one interaction kind, by name.
240type RouteMap<B, W> = HashMap<Box<str>, Arc<dyn ErasedRoute<B, W>>>;
241
242/// Every route; part of the copy-on-write handler [`Registry`](crate::handler::Registry), so
243/// dispatching needs no lock.
244pub(crate) struct Routes<B: Backend> {
245    pub(crate) commands: RouteMap<B, CommandInteraction>,
246    pub(crate) autocomplete: RouteMap<B, AutocompleteInteraction>,
247    pub(crate) components: RouteMap<B, ComponentInteraction>,
248    pub(crate) modals: RouteMap<B, ModalInteraction>,
249}
250
251impl<B: Backend> Default for Routes<B> {
252    fn default() -> Self {
253        Self {
254            commands: HashMap::new(),
255            autocomplete: HashMap::new(),
256            components: HashMap::new(),
257            modals: HashMap::new(),
258        }
259    }
260}
261
262impl<B: Backend> Clone for Routes<B> {
263    fn clone(&self) -> Self {
264        Self {
265            commands: self.commands.clone(),
266            autocomplete: self.autocomplete.clone(),
267            components: self.components.clone(),
268            modals: self.modals.clone(),
269        }
270    }
271}
272
273/// The route an interaction goes to, with its wrapper.
274enum Found<'a, B: Backend> {
275    Command(
276        &'a dyn ErasedRoute<B, CommandInteraction>,
277        CommandInteraction,
278    ),
279    Autocomplete(
280        &'a dyn ErasedRoute<B, AutocompleteInteraction>,
281        AutocompleteInteraction,
282    ),
283    Component(
284        &'a dyn ErasedRoute<B, ComponentInteraction>,
285        ComponentInteraction,
286    ),
287    Modal(&'a dyn ErasedRoute<B, ModalInteraction>, ModalInteraction),
288}
289
290impl<B: Backend> Routes<B> {
291    /// Whether no route is registered.
292    pub(crate) fn is_empty(&self) -> bool {
293        self.commands.is_empty()
294            && self.autocomplete.is_empty()
295            && self.components.is_empty()
296            && self.modals.is_empty()
297    }
298
299    /// Spawns the handler of the route `event` goes to, if any.
300    pub(crate) fn spawn(&self, ctx: &Context<B>, event: &Arc<InteractionCreate>) {
301        match self.find(event) {
302            Some(Found::Command(route, interaction)) => route.spawn(ctx, interaction),
303            Some(Found::Autocomplete(route, interaction)) => route.spawn(ctx, interaction),
304            Some(Found::Component(route, interaction)) => route.spawn(ctx, interaction),
305            Some(Found::Modal(route, interaction)) => route.spawn(ctx, interaction),
306            None => {}
307        }
308    }
309
310    /// Returns the handler future of the route `event` goes to, if any.
311    pub(crate) fn call(
312        &self,
313        ctx: &Context<B>,
314        event: &Arc<InteractionCreate>,
315    ) -> Option<BoxFuture> {
316        Some(match self.find(event)? {
317            Found::Command(route, interaction) => route.call(ctx, interaction),
318            Found::Autocomplete(route, interaction) => route.call(ctx, interaction),
319            Found::Component(route, interaction) => route.call(ctx, interaction),
320            Found::Modal(route, interaction) => route.call(ctx, interaction),
321        })
322    }
323
324    /// The route `event` goes to and its wrapper.
325    fn find(&self, event: &Arc<InteractionCreate>) -> Option<Found<'_, B>> {
326        Some(match &event.data {
327            InteractionData::ApplicationCommand(data) => Found::Command(
328                &**command_route(&self.commands, data)?,
329                CommandInteraction::new(event)?,
330            ),
331            InteractionData::Autocomplete(data) => Found::Autocomplete(
332                &**command_route(&self.autocomplete, data)?,
333                AutocompleteInteraction::new(event)?,
334            ),
335            InteractionData::MessageComponent(data) => Found::Component(
336                &**self.components.get(route_name(&data.custom_id))?,
337                ComponentInteraction::new(event)?,
338            ),
339            InteractionData::ModalSubmit(data) => Found::Modal(
340                &**self.modals.get(route_name(&data.custom_id))?,
341                ModalInteraction::new(event)?,
342            ),
343            _ => return None,
344        })
345    }
346}
347
348/// The route of a command (D-253): its full path (`mod config set`), else the group
349/// (`mod config`), else the command (`mod`).
350fn command_route<'a, B: Backend, W>(
351    routes: &'a RouteMap<B, W>,
352    data: &CommandData,
353) -> Option<&'a Arc<dyn ErasedRoute<B, W>>> {
354    if routes.is_empty() {
355        return None;
356    }
357    let mut path = [data.name.as_str(), "", ""];
358    let mut len = 1;
359    for part in [data.subcommand_group(), data.subcommand()]
360        .into_iter()
361        .flatten()
362    {
363        path[len] = part;
364        len += 1;
365    }
366    (2..=len)
367        .rev()
368        .find_map(|len| joined(&path[..len], |key| routes.get(key)))
369        .or_else(|| routes.get(path[0]))
370}
371
372/// Calls `f` with `parts` joined by spaces, built on the stack when it fits (command names
373/// are at most 32 characters).
374fn joined<R>(parts: &[&str], f: impl FnOnce(&str) -> R) -> R {
375    let len = parts.iter().map(|part| part.len() + 1).sum::<usize>() - 1;
376    let mut buffer = [0; 256];
377    if len > buffer.len() {
378        return f(&parts.join(" "));
379    }
380    let mut at = 0;
381    for (index, part) in parts.iter().enumerate() {
382        if index > 0 {
383            buffer[at] = b' ';
384            at += 1;
385        }
386        buffer[at..at + part.len()].copy_from_slice(part.as_bytes());
387        at += part.len();
388    }
389    // Strings joined by an ASCII space are valid UTF-8.
390    f(core::str::from_utf8(&buffer[..at]).unwrap_or_default())
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn custom_ids_are_split_at_the_first_colon() {
399        assert_eq!((route_name("vote"), args("vote")), ("vote", ""));
400        assert_eq!((route_name("vote:42"), args("vote:42")), ("vote", "42"));
401        assert_eq!((route_name("vote:a:b"), args("vote:a:b")), ("vote", "a:b"));
402        assert_eq!((route_name(":x"), args(":x")), ("", "x"));
403    }
404
405    #[test]
406    fn paths_are_joined_on_the_stack_or_the_heap() {
407        assert_eq!(
408            joined(&["mod", "config", "set"], str::to_owned),
409            "mod config set"
410        );
411        assert_eq!(joined(&["ping"], str::to_owned), "ping");
412        let long = "ż".repeat(100);
413        assert_eq!(
414            joined(&[&long, &long], str::to_owned),
415            format!("{long} {long}")
416        );
417    }
418}