camel_processor/
json_schema_validate.rs1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use tower::Service;
6
7use camel_api::body::Body;
8use camel_api::{CamelError, Exchange};
9
10pub struct JsonSchemaValidateService<P> {
19 inner: P,
20 validator: jsonschema::Validator,
21}
22
23impl<P> std::fmt::Debug for JsonSchemaValidateService<P> {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 f.debug_struct("JsonSchemaValidateService")
26 .finish_non_exhaustive()
27 }
28}
29
30impl<P> Clone for JsonSchemaValidateService<P>
31where
32 P: Clone,
33{
34 fn clone(&self) -> Self {
35 Self {
36 inner: self.inner.clone(),
37 validator: self.validator.clone(),
38 }
39 }
40}
41
42fn compile_json_schema(
51 schema: &serde_json::Value,
52) -> Result<jsonschema::Validator, jsonschema::ValidationError<'static>> {
53 jsonschema::options()
54 .should_validate_formats(true)
55 .build(schema)
56}
57
58impl<P> JsonSchemaValidateService<P> {
59 pub fn new(inner: P, schema: &serde_json::Value) -> Result<Self, CamelError> {
62 let validator = compile_json_schema(schema)
63 .map_err(|e| CamelError::RouteError(format!("invalid JSON schema: {e}")))?;
64 Ok(Self { inner, validator })
65 }
66}
67
68impl<P> Service<Exchange> for JsonSchemaValidateService<P>
69where
70 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
71 P::Future: Send,
72{
73 type Response = Exchange;
74 type Error = CamelError;
75 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
76
77 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
78 self.inner.poll_ready(cx)
79 }
80
81 fn call(&mut self, exchange: Exchange) -> Self::Future {
82 let result = match &exchange.input.body {
84 Body::Json(v) => {
85 let errors: Vec<String> = self
86 .validator
87 .iter_errors(v)
88 .map(|e| format!("{e} at {}", e.instance_path()))
89 .collect();
90 if errors.is_empty() {
91 Ok(())
92 } else {
93 Err(errors.join("; "))
94 }
95 }
96 _ => Ok(()),
97 };
98 match result {
99 Ok(()) => {
100 let fut = self.inner.call(exchange);
101 Box::pin(fut)
102 }
103 Err(msg) => Box::pin(async move {
104 Err(CamelError::ValidationError(format!(
105 "JSON schema validation failed: {msg}"
106 )))
107 }),
108 }
109 }
110}