Skip to main content

camel_processor/
json_schema_validate.rs

1use 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
10/// Tower Service that validates the exchange body against a compiled JSON
11/// Schema. Returns `CamelError::ValidationError` if the body does not match.
12/// Validation runs BEFORE the inner service is called.
13///
14/// Non-JSON bodies (Body::Text, Body::Bytes, Body::Xml, Body::Empty,
15/// Body::Stream) are passed through without validation — the validator only
16/// runs against Body::Json. Callers that want to validate raw text/bytes
17/// must first run an Unmarshal step that produces Body::Json.
18pub 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
42/// Compile a JSON Schema with `format` keyword validation forced on.
43///
44/// Format validation is enabled for every draft, while the schema's `$schema`
45/// key keeps selecting draft semantics (draft 2020-12 when absent).
46///
47/// `crates/components/camel-validator/src/compiled.rs` carries the twin
48/// helper: no common crate exists that both consumers could share without a
49/// new dependency edge.
50fn 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    /// Compile a JSON Schema and wrap the given inner service. Returns
60    /// `CamelError::RouteError` if the schema is not a valid JSON Schema.
61    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        // Only Body::Json is validated. Anything else passes through.
83        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}