serenade_validator/messenger.rs
1//! Messenger [`ValidateHook`] adapter.
2
3use std::any::Any;
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use serenade_messenger::{DispatchContext, MessengerError, ValidateHook};
8
9use crate::{ConstraintViolationList, Validatable, Validator};
10
11type PayloadValidateFn = dyn Fn(&dyn Any, &dyn Validator) -> ConstraintViolationList + Send + Sync;
12
13/// Maps message names to typed [`Validatable`] payloads and rejects on violations.
14///
15/// # Examples
16///
17/// ```
18/// use serenade_messenger::{
19/// Command, CommandHandler, Message, MessageBus, ValidationMiddleware,
20/// };
21/// use serenade_validator::{
22/// Constraint, ConstraintViolationList, Length, MessengerValidateHook, NotBlank,
23/// RecursiveValidator, Validatable, Validator,
24/// };
25///
26/// struct EnqueueJob {
27/// code: String,
28/// }
29///
30/// impl Message for EnqueueJob {
31/// const NAME: &'static str = "job.enqueue";
32/// }
33/// impl Command for EnqueueJob {}
34///
35/// impl Validatable for EnqueueJob {
36/// fn validate(&self, validator: &dyn Validator) -> ConstraintViolationList {
37/// validator.validate_value(
38/// &self.code,
39/// "code",
40/// &[&NotBlank as &dyn Constraint, &Length::new(1, 32)],
41/// )
42/// }
43/// }
44///
45/// struct OkHandler;
46/// impl CommandHandler<EnqueueJob> for OkHandler {
47/// fn handle(&self, _: &EnqueueJob) -> Result<(), serenade_messenger::MessengerError> {
48/// Ok(())
49/// }
50/// }
51///
52/// let mut hook = MessengerValidateHook::new(RecursiveValidator);
53/// hook.register::<EnqueueJob>();
54/// let mut bus = MessageBus::new();
55/// bus.add_middleware(ValidationMiddleware::new(hook));
56/// bus.register_command(OkHandler).unwrap();
57/// assert!(bus
58/// .dispatch_command(&EnqueueJob { code: String::new() })
59/// .is_err());
60/// ```
61pub struct MessengerValidateHook<V> {
62 validator: V,
63 by_name: HashMap<&'static str, Arc<PayloadValidateFn>>,
64}
65
66impl<V> MessengerValidateHook<V> {
67 /// Creates a hook around `validator`.
68 #[must_use]
69 pub fn new(validator: V) -> Self {
70 Self {
71 validator,
72 by_name: HashMap::new(),
73 }
74 }
75
76 /// Registers `T` under `T::NAME` when `T: Message + Validatable`.
77 pub fn register<T>(&mut self)
78 where
79 T: serenade_messenger::Message + Validatable + 'static,
80 {
81 self.by_name.insert(
82 T::NAME,
83 Arc::new(|payload: &dyn Any, validator: &dyn Validator| {
84 payload
85 .downcast_ref::<T>()
86 .map_or_else(ConstraintViolationList::new, |typed| {
87 typed.validate(validator)
88 })
89 }),
90 );
91 }
92}
93
94impl<V: Validator> ValidateHook for MessengerValidateHook<V> {
95 fn validate(&self, ctx: &DispatchContext<'_>) -> Result<(), MessengerError> {
96 let Some(check) = self.by_name.get(ctx.message_name) else {
97 return Ok(());
98 };
99 let violations = check(ctx.payload, &self.validator);
100 if violations.is_empty() {
101 return Ok(());
102 }
103 let summary = violations
104 .as_slice()
105 .iter()
106 .map(|v| {
107 if v.property_path.is_empty() {
108 v.message.clone()
109 } else {
110 format!("{}: {}", v.property_path, v.message)
111 }
112 })
113 .collect::<Vec<_>>()
114 .join("; ");
115 Err(MessengerError::Rejected {
116 name: ctx.message_name,
117 message: summary,
118 })
119 }
120}