use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::hash::Hash;
use crate::context::ValidationContext;
use crate::error::{AsyncValidationError, FieldIssue, HostError};
use crate::schema::ModelSchema;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Server;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Client;
pub trait Normalize {
fn normalize(&mut self);
}
pub trait Validate {
fn validate(&self) -> Result<(), Vec<FieldIssue>> {
self.validate_with(&ValidationContext::default())
}
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
}
pub trait ScopedValidate<Scope> {
fn validate_scoped(&self) -> Result<(), Vec<FieldIssue>> {
self.validate_scoped_with(&ValidationContext::default())
}
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AsyncCheckResult {
Issues(Vec<FieldIssue>),
Host(HostError),
}
pub trait IntoAsyncError {
fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult;
}
impl IntoAsyncError for &'static str {
fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
}
}
impl IntoAsyncError for String {
fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
}
}
impl IntoAsyncError for (&'static str, &'static str) {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
}
}
impl IntoAsyncError for (String, String) {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
}
}
impl IntoAsyncError for FieldIssue {
fn into_async_error_result(mut self, field: &str, _code: &str) -> AsyncCheckResult {
if self.field.is_empty() {
self.field = field.to_string();
}
AsyncCheckResult::Issues(vec![self])
}
}
impl IntoAsyncError for Vec<FieldIssue> {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(
self.into_iter()
.map(|mut v| {
if v.field.is_empty() {
v.field = field.to_string();
}
v
})
.collect(),
)
}
}
impl IntoAsyncError for HostError {
fn into_async_error_result(self, _field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Host(self)
}
}
impl IntoAsyncError for AsyncValidationError {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
match self {
AsyncValidationError::Issues(vs) => vs.into_async_error_result(field, ""),
AsyncValidationError::Host(err) => AsyncCheckResult::Host(err),
}
}
}
pub trait AsyncCheckOutcome {
fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult;
}
impl AsyncCheckOutcome for bool {
fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(CheckOutcome::into_issues(self, field, code, reason))
}
}
impl<E: IntoAsyncError> AsyncCheckOutcome for Result<(), E> {
fn into_async_result(self, field: &str, code: &str, _reason: &str) -> AsyncCheckResult {
match self {
Ok(()) => AsyncCheckResult::Issues(Vec::new()),
Err(err) => err.into_async_error_result(field, code),
}
}
}
impl<E: IntoAsyncError> AsyncCheckOutcome for Result<bool, E> {
fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
match self {
Ok(true) => AsyncCheckResult::Issues(Vec::new()),
Ok(false) => AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, reason)]),
Err(err) => err.into_async_error_result(field, code),
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
pub trait AsyncValidate<R: ?Sized + Sync, Scope = ()> {
async fn validate_async(&self, resolver: &R) -> Result<(), AsyncValidationError> {
self.validate_async_with(&ValidationContext::default(), resolver)
.await
}
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError>;
}
pub trait DescribeModel {
fn model_schema() -> ModelSchema;
}
pub trait CheckOutcome {
fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue>;
}
impl CheckOutcome for bool {
fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
if self {
Vec::new()
} else {
vec![FieldIssue::new(field, code, reason)]
}
}
}
impl CheckOutcome for Result<(), &'static str> {
fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err(msg) => vec![FieldIssue::new(field, code, msg)],
}
}
}
impl CheckOutcome for Result<(), String> {
fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err(msg) => vec![FieldIssue::new(field, code, msg)],
}
}
}
impl CheckOutcome for Result<(), (&'static str, &'static str)> {
fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
}
}
}
impl CheckOutcome for Result<(), (String, String)> {
fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
}
}
}
impl CheckOutcome for Result<(), FieldIssue> {
fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err(mut v) => {
if v.field.is_empty() {
v.field = field.to_string();
}
vec![v]
}
}
}
}
impl CheckOutcome for Result<(), Vec<FieldIssue>> {
fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err(vs) => vs
.into_iter()
.map(|mut v| {
if v.field.is_empty() {
v.field = field.to_string();
}
v
})
.collect(),
}
}
}
fn push_indexed_issues(issues: &mut Vec<FieldIssue>, index: usize, inner: Vec<FieldIssue>) {
for mut issue in inner {
if issue.field.is_empty() || issue.field == "body" {
issue.field = format!("[{index}]");
} else {
issue.field = format!("[{index}].{}", issue.field);
}
issues.push(issue);
}
}
fn push_keyed_issues(issues: &mut Vec<FieldIssue>, key: &impl std::fmt::Display, inner: Vec<FieldIssue>) {
for mut issue in inner {
if issue.field.is_empty() || issue.field == "body" {
issue.field = key.to_string();
} else {
issue.field = format!("{key}.{}", issue.field);
}
issues.push(issue);
}
}
macro_rules! impl_noop_model_traits {
($($ty:ty),*) => {
$(
impl Normalize for $ty {
fn normalize(&mut self) {}
}
impl Validate for $ty {
fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
impl<S> ScopedValidate<S> for $ty {
fn validate_scoped_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S> AsyncValidate<R, S> for $ty {
async fn validate_async_with(
&self,
_ctx: &ValidationContext,
_resolver: &R,
) -> Result<(), AsyncValidationError> {
Ok(())
}
}
)*
};
}
impl_noop_model_traits!(
String, bool, char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);
impl<T: Normalize> Normalize for Option<T> {
fn normalize(&mut self) {
if let Some(value) = self {
value.normalize();
}
}
}
impl<T: Validate> Validate for Option<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
match self {
Some(value) => value.validate_with(ctx),
None => Ok(()),
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Option<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
match self {
Some(value) => value.validate_scoped_with(ctx),
None => Ok(()),
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Option<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
match self {
Some(value) => value.validate_async_with(ctx, resolver).await,
None => Ok(()),
}
}
}
impl<T: Normalize> Normalize for Box<T> {
fn normalize(&mut self) {
(**self).normalize();
}
}
impl<T: Validate> Validate for Box<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_with(ctx)
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Box<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_scoped_with(ctx)
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Box<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
(**self).validate_async_with(ctx, resolver).await
}
}
impl<T: Normalize> Normalize for Vec<T> {
fn normalize(&mut self) {
for item in self {
item.normalize();
}
}
}
impl<T: Validate> Validate for Vec<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Vec<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Vec<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<T: Normalize> Normalize for BTreeSet<T> {
fn normalize(&mut self) {}
}
impl<T: Validate> Validate for BTreeSet<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for BTreeSet<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for BTreeSet<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<T: Normalize> Normalize for HashSet<T> {
fn normalize(&mut self) {}
}
impl<T: Validate> Validate for HashSet<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for HashSet<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for HashSet<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<K, V: Normalize> Normalize for BTreeMap<K, V> {
fn normalize(&mut self) {
for value in self.values_mut() {
value.normalize();
}
}
}
impl<K: std::fmt::Display, V: Validate> Validate for BTreeMap<K, V> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_with(ctx) {
push_keyed_issues(&mut issues, key, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, K: std::fmt::Display, V: ScopedValidate<S>> ScopedValidate<S> for BTreeMap<K, V> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_scoped_with(ctx) {
push_keyed_issues(&mut issues, key, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, K: std::fmt::Display + Sync, V: AsyncValidate<R, S> + Sync>
AsyncValidate<R, S> for BTreeMap<K, V>
{
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (key, value) in self {
match value.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_keyed_issues(&mut issues, key, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<K: Eq + Hash, V: Normalize> Normalize for HashMap<K, V> {
fn normalize(&mut self) {
for value in self.values_mut() {
value.normalize();
}
}
}
impl<K: std::fmt::Display + Eq + Hash, V: Validate> Validate for HashMap<K, V> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_with(ctx) {
push_keyed_issues(&mut issues, key, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, K: std::fmt::Display + Eq + Hash, V: ScopedValidate<S>> ScopedValidate<S>
for HashMap<K, V>
{
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_scoped_with(ctx) {
push_keyed_issues(&mut issues, key, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, K: std::fmt::Display + Eq + Hash + Sync, V: AsyncValidate<R, S> + Sync>
AsyncValidate<R, S> for HashMap<K, V>
{
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (key, value) in self {
match value.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_keyed_issues(&mut issues, key, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}