use crate::common::{DEFAULT_BODY_LIMIT, VldHttpError, is_json_content_type, parse_json_body};
use bytes::Bytes;
use http::{Request, Response, StatusCode};
use http_body::Body;
use http_body_util::{BodyExt, Either, Full, LengthLimitError, Limited};
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use vld::schema::VldParse;
pub type ValidatedBody<B> = Either<Full<Bytes>, B>;
#[derive(Debug, Clone)]
pub struct Validated<T>(pub T);
impl<T> std::ops::Deref for Validated<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
#[derive(Clone)]
pub struct ValidateJsonLayer<T> {
limit: usize,
_marker: PhantomData<fn() -> T>,
}
impl<T> ValidateJsonLayer<T> {
pub fn new() -> Self {
Self::with_limit(DEFAULT_BODY_LIMIT)
}
pub fn with_limit(limit: usize) -> Self {
Self {
limit,
_marker: PhantomData,
}
}
}
impl<T> Default for ValidateJsonLayer<T> {
fn default() -> Self {
Self::new()
}
}
impl<S, T> tower_layer::Layer<S> for ValidateJsonLayer<T> {
type Service = ValidateJsonService<S, T>;
fn layer(&self, inner: S) -> Self::Service {
ValidateJsonService {
inner,
limit: self.limit,
_marker: PhantomData,
}
}
}
#[derive(Clone)]
pub struct ValidateJsonService<S, T> {
inner: S,
limit: usize,
_marker: PhantomData<fn() -> T>,
}
fn error_response<B>(err: VldHttpError) -> Response<ValidatedBody<B>> {
let mut resp = Response::new(Either::Left(Full::new(Bytes::from(err.body().to_string()))));
*resp.status_mut() =
StatusCode::from_u16(err.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY);
resp.headers_mut().insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/json"),
);
resp
}
fn body_error(e: &(dyn std::error::Error + 'static)) -> VldHttpError {
if std::iter::successors(Some(e), |e| e.source()).any(|e| e.is::<LengthLimitError>()) {
VldHttpError::payload_too_large()
} else {
VldHttpError::parse(format!("Failed to read request body: {e}"))
}
}
impl<S, T, ReqBody, ResBody> tower_service::Service<Request<ReqBody>> for ValidateJsonService<S, T>
where
S: tower_service::Service<Request<ValidatedBody<ReqBody>>, Response = Response<ResBody>>
+ Clone
+ Send
+ 'static,
S::Future: Send + 'static,
S::Error: Send + 'static,
ReqBody: Body<Data = Bytes> + Send + 'static,
ReqBody::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
ResBody: Send + 'static,
T: VldParse + Clone + Send + Sync + 'static,
{
type Response = Response<ValidatedBody<ResBody>>;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let mut inner = self.inner.clone();
std::mem::swap(&mut self.inner, &mut inner);
let limit = self.limit;
Box::pin(async move {
let is_json = req
.headers()
.get(http::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(is_json_content_type);
let (parts, body) = req.into_parts();
if !is_json {
let req = Request::from_parts(parts, Either::Right(body));
return Ok(inner.call(req).await?.map(Either::Right));
}
let bytes = match Limited::new(body, limit).collect().await {
Ok(collected) => collected.to_bytes(),
Err(e) => return Ok(error_response(body_error(&*e))),
};
let validated = match parse_json_body(&bytes)
.and_then(|v| T::vld_parse_value(&v).map_err(VldHttpError::validation))
{
Ok(v) => v,
Err(e) => return Ok(error_response(e)),
};
let mut req = Request::from_parts(parts, Either::Left(Full::new(bytes)));
req.extensions_mut().insert(Validated(validated));
Ok(inner.call(req).await?.map(Either::Right))
})
}
}
pub fn validated<T: Clone + Send + Sync + 'static>(req: &Request<impl Body>) -> Option<T> {
req.extensions().get::<Validated<T>>().map(|v| v.0.clone())
}
pub mod prelude {
pub use super::{ValidateJsonLayer, ValidateJsonService, Validated, ValidatedBody, validated};
pub use vld::prelude::*;
}