1use 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
45macro_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 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 #[must_use]
69 pub fn interaction(&self) -> &Interaction {
70 &self.event
71 }
72
73 #[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 _ => 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 f.debug_tuple(stringify!($name)).field(self.interaction()).finish()
99 }
100 }
101 };
102}
103
104wrapper! {
105 CommandInteraction => ApplicationCommand(CommandData)
113}
114
115wrapper! {
116 AutocompleteInteraction => Autocomplete(CommandData)
122}
123
124wrapper! {
125 ComponentInteraction => MessageComponent(ComponentData)
132}
133
134wrapper! {
135 ModalInteraction => ModalSubmit(ModalSubmitData)
142}
143
144fn args(custom_id: &str) -> &str {
146 custom_id.split_once(':').map_or("", |(_, args)| args)
147}
148
149fn route_name(custom_id: &str) -> &str {
151 custom_id
152 .split_once(':')
153 .map_or(custom_id, |(name, _)| name)
154}
155
156impl ComponentInteraction {
157 #[must_use]
175 pub fn args(&self) -> &str {
176 args(&self.custom_id)
177 }
178}
179
180impl ModalInteraction {
181 #[must_use]
186 pub fn args(&self) -> &str {
187 args(&self.custom_id)
188 }
189}
190
191pub(crate) trait ErasedRoute<B: Backend, W>: Send + Sync {
193 fn spawn(&self, ctx: &Context<B>, interaction: W);
195
196 fn call(&self, ctx: &Context<B>, interaction: W) -> BoxFuture;
198}
199
200pub(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
215async 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
239type RouteMap<B, W> = HashMap<Box<str>, Arc<dyn ErasedRoute<B, W>>>;
241
242pub(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
273enum 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 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 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 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 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
348fn 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
372fn 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 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}