Skip to main content

camel_processor/
json_schema_validate.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::task::{Context, Poll};
5
6use tower::Service;
7
8use camel_api::body::Body;
9use camel_api::{CamelError, Exchange};
10use camel_json_schema::CompiledSchema;
11use camel_json_schema::FormatMode;
12use camel_json_schema::SchemaSource;
13use camel_json_schema::SchemaSyntax;
14
15/// Tower Service that validates the exchange body against a compiled JSON
16/// Schema. Returns `CamelError::ValidationError` if the body does not match.
17/// Validation runs BEFORE the inner service is called.
18///
19/// Non-JSON bodies (Body::Text, Body::Bytes, Body::Xml, Body::Empty,
20/// Body::Stream) are passed through without validation — the validator only
21/// runs against Body::Json. Callers that want to validate raw text/bytes
22/// must first run an Unmarshal step that produces Body::Json.
23pub struct JsonSchemaValidateService<P> {
24    inner: P,
25    validator: Arc<CompiledSchema>,
26}
27
28impl<P> std::fmt::Debug for JsonSchemaValidateService<P> {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("JsonSchemaValidateService")
31            .finish_non_exhaustive()
32    }
33}
34
35impl<P> Clone for JsonSchemaValidateService<P>
36where
37    P: Clone,
38{
39    fn clone(&self) -> Self {
40        Self {
41            inner: self.inner.clone(),
42            validator: self.validator.clone(),
43        }
44    }
45}
46
47impl<P> JsonSchemaValidateService<P> {
48    /// Compile a JSON Schema and wrap the given inner service. Returns
49    /// `CamelError::RouteError` if the schema is not a valid JSON Schema.
50    ///
51    /// The schema is an inline document, so it resolves same-document
52    /// references only: every external `$ref` fails at construction with the
53    /// named confinement rejection (ADR-0100).
54    pub fn new(inner: P, schema: &serde_json::Value) -> Result<Self, CamelError> {
55        let validator = camel_json_schema::compile(
56            &SchemaSource::Inline(schema.clone()),
57            SchemaSyntax::Auto,
58            FormatMode::Enforce,
59        )
60        .map_err(|e| CamelError::RouteError(format!("invalid JSON schema: {e}")))?;
61        Ok(Self {
62            inner,
63            validator: Arc::new(validator),
64        })
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                    .violations(v)
88                    .into_iter()
89                    .map(|violation| {
90                        format!("{} at {}", violation.message, violation.instance_path)
91                    })
92                    .collect();
93                if errors.is_empty() {
94                    Ok(())
95                } else {
96                    Err(errors.join("; "))
97                }
98            }
99            _ => Ok(()),
100        };
101        match result {
102            Ok(()) => {
103                let fut = self.inner.call(exchange);
104                Box::pin(fut)
105            }
106            Err(msg) => Box::pin(async move {
107                Err(CamelError::ValidationError(format!(
108                    "JSON schema validation failed: {msg}"
109                )))
110            }),
111        }
112    }
113}