1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::hash::Hash;
3
4use crate::context::ValidationContext;
5use crate::error::{AsyncValidationError, FieldIssue, HostError};
6use crate::schema::ModelSchema;
7
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10pub struct Server;
11
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
14pub struct Client;
15
16pub trait Normalize {
18 fn normalize(&mut self);
19}
20
21pub trait Validate {
23 fn validate(&self) -> Result<(), Vec<FieldIssue>> {
24 self.validate_with(&ValidationContext::default())
25 }
26
27 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
28}
29
30pub trait ScopedValidate<Scope> {
32 fn validate_scoped(&self) -> Result<(), Vec<FieldIssue>> {
33 self.validate_scoped_with(&ValidationContext::default())
34 }
35
36 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum AsyncCheckResult {
42 Issues(Vec<FieldIssue>),
43 Host(HostError),
44}
45
46pub trait IntoAsyncError {
48 fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult;
49}
50
51impl IntoAsyncError for &'static str {
52 fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
53 AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
54 }
55}
56
57impl IntoAsyncError for String {
58 fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
59 AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
60 }
61}
62
63impl IntoAsyncError for (&'static str, &'static str) {
64 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
65 AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
66 }
67}
68
69impl IntoAsyncError for (String, String) {
70 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
71 AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
72 }
73}
74
75impl IntoAsyncError for FieldIssue {
76 fn into_async_error_result(mut self, field: &str, _code: &str) -> AsyncCheckResult {
77 if self.field.is_empty() {
78 self.field = field.to_string();
79 }
80 AsyncCheckResult::Issues(vec![self])
81 }
82}
83
84impl IntoAsyncError for Vec<FieldIssue> {
85 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
86 AsyncCheckResult::Issues(
87 self.into_iter()
88 .map(|mut v| {
89 if v.field.is_empty() {
90 v.field = field.to_string();
91 }
92 v
93 })
94 .collect(),
95 )
96 }
97}
98
99impl IntoAsyncError for HostError {
100 fn into_async_error_result(self, _field: &str, _code: &str) -> AsyncCheckResult {
101 AsyncCheckResult::Host(self)
102 }
103}
104
105impl IntoAsyncError for AsyncValidationError {
106 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
107 match self {
108 AsyncValidationError::Issues(vs) => vs.into_async_error_result(field, ""),
109 AsyncValidationError::Host(err) => AsyncCheckResult::Host(err),
110 }
111 }
112}
113
114pub trait AsyncCheckOutcome {
116 fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult;
117}
118
119impl AsyncCheckOutcome for bool {
120 fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
121 AsyncCheckResult::Issues(CheckOutcome::into_issues(self, field, code, reason))
122 }
123}
124
125impl<E: IntoAsyncError> AsyncCheckOutcome for Result<(), E> {
126 fn into_async_result(self, field: &str, code: &str, _reason: &str) -> AsyncCheckResult {
127 match self {
128 Ok(()) => AsyncCheckResult::Issues(Vec::new()),
129 Err(err) => err.into_async_error_result(field, code),
130 }
131 }
132}
133
134impl<E: IntoAsyncError> AsyncCheckOutcome for Result<bool, E> {
135 fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
136 match self {
137 Ok(true) => AsyncCheckResult::Issues(Vec::new()),
138 Ok(false) => AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, reason)]),
139 Err(err) => err.into_async_error_result(field, code),
140 }
141 }
142}
143
144#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
146#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
147pub trait AsyncValidate<R: ?Sized + Sync, Scope = ()> {
148 async fn validate_async(&self, resolver: &R) -> Result<(), AsyncValidationError> {
149 self.validate_async_with(&ValidationContext::default(), resolver)
150 .await
151 }
152
153 async fn validate_async_with(
154 &self,
155 ctx: &ValidationContext,
156 resolver: &R,
157 ) -> Result<(), AsyncValidationError>;
158}
159
160pub trait DescribeModel {
162 fn model_schema() -> ModelSchema;
163}
164
165pub trait CheckOutcome {
167 fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue>;
168}
169
170impl CheckOutcome for bool {
171 fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
172 if self {
173 Vec::new()
174 } else {
175 vec![FieldIssue::new(field, code, reason)]
176 }
177 }
178}
179
180impl CheckOutcome for Result<(), &'static str> {
181 fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
182 match self {
183 Ok(()) => Vec::new(),
184 Err(msg) => vec![FieldIssue::new(field, code, msg)],
185 }
186 }
187}
188
189impl CheckOutcome for Result<(), String> {
190 fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
191 match self {
192 Ok(()) => Vec::new(),
193 Err(msg) => vec![FieldIssue::new(field, code, msg)],
194 }
195 }
196}
197
198impl CheckOutcome for Result<(), (&'static str, &'static str)> {
199 fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
200 match self {
201 Ok(()) => Vec::new(),
202 Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
203 }
204 }
205}
206
207impl CheckOutcome for Result<(), (String, String)> {
208 fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
209 match self {
210 Ok(()) => Vec::new(),
211 Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
212 }
213 }
214}
215
216impl CheckOutcome for Result<(), FieldIssue> {
217 fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
218 match self {
219 Ok(()) => Vec::new(),
220 Err(mut v) => {
221 if v.field.is_empty() {
222 v.field = field.to_string();
223 }
224 vec![v]
225 }
226 }
227 }
228}
229
230impl CheckOutcome for Result<(), Vec<FieldIssue>> {
231 fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
232 match self {
233 Ok(()) => Vec::new(),
234 Err(vs) => vs
235 .into_iter()
236 .map(|mut v| {
237 if v.field.is_empty() {
238 v.field = field.to_string();
239 }
240 v
241 })
242 .collect(),
243 }
244 }
245}
246
247fn push_indexed_issues(issues: &mut Vec<FieldIssue>, index: usize, inner: Vec<FieldIssue>) {
248 for mut issue in inner {
249 if issue.field.is_empty() || issue.field == "body" {
250 issue.field = format!("[{index}]");
251 } else {
252 issue.field = format!("[{index}].{}", issue.field);
253 }
254 issues.push(issue);
255 }
256}
257
258fn push_keyed_issues(issues: &mut Vec<FieldIssue>, key: &impl std::fmt::Display, inner: Vec<FieldIssue>) {
259 for mut issue in inner {
260 if issue.field.is_empty() || issue.field == "body" {
261 issue.field = key.to_string();
262 } else {
263 issue.field = format!("{key}.{}", issue.field);
264 }
265 issues.push(issue);
266 }
267}
268
269macro_rules! impl_noop_model_traits {
270 ($($ty:ty),*) => {
271 $(
272 impl Normalize for $ty {
273 fn normalize(&mut self) {}
274 }
275
276 impl Validate for $ty {
277 fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
278 Ok(())
279 }
280 }
281
282 impl<S> ScopedValidate<S> for $ty {
283 fn validate_scoped_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
284 Ok(())
285 }
286 }
287
288 #[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
289 #[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
290 impl<R: ?Sized + Sync, S> AsyncValidate<R, S> for $ty {
291 async fn validate_async_with(
292 &self,
293 _ctx: &ValidationContext,
294 _resolver: &R,
295 ) -> Result<(), AsyncValidationError> {
296 Ok(())
297 }
298 }
299 )*
300 };
301}
302
303impl_noop_model_traits!(
304 String, bool, char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
305);
306
307impl<T: Normalize> Normalize for Option<T> {
308 fn normalize(&mut self) {
309 if let Some(value) = self {
310 value.normalize();
311 }
312 }
313}
314
315impl<T: Validate> Validate for Option<T> {
316 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
317 match self {
318 Some(value) => value.validate_with(ctx),
319 None => Ok(()),
320 }
321 }
322}
323
324impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Option<T> {
325 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
326 match self {
327 Some(value) => value.validate_scoped_with(ctx),
328 None => Ok(()),
329 }
330 }
331}
332
333#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
334#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
335impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Option<T> {
336 async fn validate_async_with(
337 &self,
338 ctx: &ValidationContext,
339 resolver: &R,
340 ) -> Result<(), AsyncValidationError> {
341 match self {
342 Some(value) => value.validate_async_with(ctx, resolver).await,
343 None => Ok(()),
344 }
345 }
346}
347
348impl<T: Normalize> Normalize for Box<T> {
349 fn normalize(&mut self) {
350 (**self).normalize();
351 }
352}
353
354impl<T: Validate> Validate for Box<T> {
355 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
356 (**self).validate_with(ctx)
357 }
358}
359
360impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Box<T> {
361 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
362 (**self).validate_scoped_with(ctx)
363 }
364}
365
366#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
367#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
368impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Box<T> {
369 async fn validate_async_with(
370 &self,
371 ctx: &ValidationContext,
372 resolver: &R,
373 ) -> Result<(), AsyncValidationError> {
374 (**self).validate_async_with(ctx, resolver).await
375 }
376}
377
378impl<T: Normalize> Normalize for Vec<T> {
379 fn normalize(&mut self) {
380 for item in self {
381 item.normalize();
382 }
383 }
384}
385
386impl<T: Validate> Validate for Vec<T> {
387 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
388 let mut issues = Vec::new();
389 for (index, item) in self.iter().enumerate() {
390 if let Err(inner) = item.validate_with(ctx) {
391 push_indexed_issues(&mut issues, index, inner);
392 }
393 }
394 if issues.is_empty() {
395 Ok(())
396 } else {
397 Err(issues)
398 }
399 }
400}
401
402impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Vec<T> {
403 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
404 let mut issues = Vec::new();
405 for (index, item) in self.iter().enumerate() {
406 if let Err(inner) = item.validate_scoped_with(ctx) {
407 push_indexed_issues(&mut issues, index, inner);
408 }
409 }
410 if issues.is_empty() {
411 Ok(())
412 } else {
413 Err(issues)
414 }
415 }
416}
417
418#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
419#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
420impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Vec<T> {
421 async fn validate_async_with(
422 &self,
423 ctx: &ValidationContext,
424 resolver: &R,
425 ) -> Result<(), AsyncValidationError> {
426 let mut issues = Vec::new();
427 for (index, item) in self.iter().enumerate() {
428 match item.validate_async_with(ctx, resolver).await {
429 Ok(()) => {}
430 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
431 Err(AsyncValidationError::Issues(inner)) => {
432 push_indexed_issues(&mut issues, index, inner);
433 }
434 }
435 }
436 if issues.is_empty() {
437 Ok(())
438 } else {
439 Err(AsyncValidationError::Issues(issues))
440 }
441 }
442}
443
444impl<T: Normalize> Normalize for BTreeSet<T> {
445 fn normalize(&mut self) {}
446}
447
448impl<T: Validate> Validate for BTreeSet<T> {
449 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
450 let mut issues = Vec::new();
451 for (index, item) in self.iter().enumerate() {
452 if let Err(inner) = item.validate_with(ctx) {
453 push_indexed_issues(&mut issues, index, inner);
454 }
455 }
456 if issues.is_empty() {
457 Ok(())
458 } else {
459 Err(issues)
460 }
461 }
462}
463
464impl<S, T: ScopedValidate<S>> ScopedValidate<S> for BTreeSet<T> {
465 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
466 let mut issues = Vec::new();
467 for (index, item) in self.iter().enumerate() {
468 if let Err(inner) = item.validate_scoped_with(ctx) {
469 push_indexed_issues(&mut issues, index, inner);
470 }
471 }
472 if issues.is_empty() {
473 Ok(())
474 } else {
475 Err(issues)
476 }
477 }
478}
479
480#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
481#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
482impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for BTreeSet<T> {
483 async fn validate_async_with(
484 &self,
485 ctx: &ValidationContext,
486 resolver: &R,
487 ) -> Result<(), AsyncValidationError> {
488 let mut issues = Vec::new();
489 for (index, item) in self.iter().enumerate() {
490 match item.validate_async_with(ctx, resolver).await {
491 Ok(()) => {}
492 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
493 Err(AsyncValidationError::Issues(inner)) => {
494 push_indexed_issues(&mut issues, index, inner);
495 }
496 }
497 }
498 if issues.is_empty() {
499 Ok(())
500 } else {
501 Err(AsyncValidationError::Issues(issues))
502 }
503 }
504}
505
506impl<T: Normalize> Normalize for HashSet<T> {
507 fn normalize(&mut self) {}
508}
509
510impl<T: Validate> Validate for HashSet<T> {
511 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
512 let mut issues = Vec::new();
513 for (index, item) in self.iter().enumerate() {
514 if let Err(inner) = item.validate_with(ctx) {
515 push_indexed_issues(&mut issues, index, inner);
516 }
517 }
518 if issues.is_empty() {
519 Ok(())
520 } else {
521 Err(issues)
522 }
523 }
524}
525
526impl<S, T: ScopedValidate<S>> ScopedValidate<S> for HashSet<T> {
527 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
528 let mut issues = Vec::new();
529 for (index, item) in self.iter().enumerate() {
530 if let Err(inner) = item.validate_scoped_with(ctx) {
531 push_indexed_issues(&mut issues, index, inner);
532 }
533 }
534 if issues.is_empty() {
535 Ok(())
536 } else {
537 Err(issues)
538 }
539 }
540}
541
542#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
543#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
544impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for HashSet<T> {
545 async fn validate_async_with(
546 &self,
547 ctx: &ValidationContext,
548 resolver: &R,
549 ) -> Result<(), AsyncValidationError> {
550 let mut issues = Vec::new();
551 for (index, item) in self.iter().enumerate() {
552 match item.validate_async_with(ctx, resolver).await {
553 Ok(()) => {}
554 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
555 Err(AsyncValidationError::Issues(inner)) => {
556 push_indexed_issues(&mut issues, index, inner);
557 }
558 }
559 }
560 if issues.is_empty() {
561 Ok(())
562 } else {
563 Err(AsyncValidationError::Issues(issues))
564 }
565 }
566}
567
568impl<K, V: Normalize> Normalize for BTreeMap<K, V> {
569 fn normalize(&mut self) {
570 for value in self.values_mut() {
571 value.normalize();
572 }
573 }
574}
575
576impl<K: std::fmt::Display, V: Validate> Validate for BTreeMap<K, V> {
577 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
578 let mut issues = Vec::new();
579 for (key, value) in self {
580 if let Err(inner) = value.validate_with(ctx) {
581 push_keyed_issues(&mut issues, key, inner);
582 }
583 }
584 if issues.is_empty() {
585 Ok(())
586 } else {
587 Err(issues)
588 }
589 }
590}
591
592impl<S, K: std::fmt::Display, V: ScopedValidate<S>> ScopedValidate<S> for BTreeMap<K, V> {
593 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
594 let mut issues = Vec::new();
595 for (key, value) in self {
596 if let Err(inner) = value.validate_scoped_with(ctx) {
597 push_keyed_issues(&mut issues, key, inner);
598 }
599 }
600 if issues.is_empty() {
601 Ok(())
602 } else {
603 Err(issues)
604 }
605 }
606}
607
608#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
609#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
610impl<R: ?Sized + Sync, S, K: std::fmt::Display + Sync, V: AsyncValidate<R, S> + Sync>
611 AsyncValidate<R, S> for BTreeMap<K, V>
612{
613 async fn validate_async_with(
614 &self,
615 ctx: &ValidationContext,
616 resolver: &R,
617 ) -> Result<(), AsyncValidationError> {
618 let mut issues = Vec::new();
619 for (key, value) in self {
620 match value.validate_async_with(ctx, resolver).await {
621 Ok(()) => {}
622 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
623 Err(AsyncValidationError::Issues(inner)) => {
624 push_keyed_issues(&mut issues, key, inner);
625 }
626 }
627 }
628 if issues.is_empty() {
629 Ok(())
630 } else {
631 Err(AsyncValidationError::Issues(issues))
632 }
633 }
634}
635
636impl<K: Eq + Hash, V: Normalize> Normalize for HashMap<K, V> {
637 fn normalize(&mut self) {
638 for value in self.values_mut() {
639 value.normalize();
640 }
641 }
642}
643
644impl<K: std::fmt::Display + Eq + Hash, V: Validate> Validate for HashMap<K, V> {
645 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
646 let mut issues = Vec::new();
647 for (key, value) in self {
648 if let Err(inner) = value.validate_with(ctx) {
649 push_keyed_issues(&mut issues, key, inner);
650 }
651 }
652 if issues.is_empty() {
653 Ok(())
654 } else {
655 Err(issues)
656 }
657 }
658}
659
660impl<S, K: std::fmt::Display + Eq + Hash, V: ScopedValidate<S>> ScopedValidate<S>
661 for HashMap<K, V>
662{
663 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
664 let mut issues = Vec::new();
665 for (key, value) in self {
666 if let Err(inner) = value.validate_scoped_with(ctx) {
667 push_keyed_issues(&mut issues, key, inner);
668 }
669 }
670 if issues.is_empty() {
671 Ok(())
672 } else {
673 Err(issues)
674 }
675 }
676}
677
678#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
679#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
680impl<R: ?Sized + Sync, S, K: std::fmt::Display + Eq + Hash + Sync, V: AsyncValidate<R, S> + Sync>
681 AsyncValidate<R, S> for HashMap<K, V>
682{
683 async fn validate_async_with(
684 &self,
685 ctx: &ValidationContext,
686 resolver: &R,
687 ) -> Result<(), AsyncValidationError> {
688 let mut issues = Vec::new();
689 for (key, value) in self {
690 match value.validate_async_with(ctx, resolver).await {
691 Ok(()) => {}
692 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
693 Err(AsyncValidationError::Issues(inner)) => {
694 push_keyed_issues(&mut issues, key, inner);
695 }
696 }
697 }
698 if issues.is_empty() {
699 Ok(())
700 } else {
701 Err(AsyncValidationError::Issues(issues))
702 }
703 }
704}