Skip to main content

camel_processor/
marshal.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::data_format::DataFormat;
10use camel_api::{CamelError, Exchange};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13enum MarshalSide {
14    Step,
15    Response,
16}
17
18#[derive(Clone)]
19pub struct MarshalService<P> {
20    inner: P,
21    format: Arc<dyn DataFormat>,
22    side: MarshalSide,
23}
24
25impl<P> MarshalService<P> {
26    pub fn new(inner: P, format: Arc<dyn DataFormat>) -> Self {
27        Self {
28            inner,
29            format,
30            side: MarshalSide::Step,
31        }
32    }
33
34    /// Build a marshal step for the response side of an exchange.
35    ///
36    /// Response-side marshal failures are deliberately wrapped in
37    /// [`CamelError::ProcessorErrorWithSource`] so the HTTP finalizer maps the
38    /// failure to 500. This follows the ADR-0096 blame rule: conversion
39    /// failures default to 500 unless the failing step's input is by definition
40    /// the request. The binding-injected unmarshal is that seam; it
41    /// reclassifies [`CamelError::TypeConversionFailed`] to
42    /// [`CamelError::ValidationError`] (HTTP 400) via
43    /// [`UnmarshalService::for_request_binding`]. The source chain preserves
44    /// the original error.
45    pub fn for_response(inner: P, format: Arc<dyn DataFormat>) -> Self {
46        Self {
47            inner,
48            format,
49            side: MarshalSide::Response,
50        }
51    }
52}
53
54const _: fn() = || {
55    fn assert_send_sync_static<T: Send + Sync + 'static>() {}
56    assert_send_sync_static::<CamelError>();
57};
58
59#[derive(Clone)]
60pub struct UnmarshalService<P> {
61    inner: P,
62    format: Arc<dyn DataFormat>,
63    request_borne: bool,
64}
65
66impl<P> UnmarshalService<P> {
67    pub fn new(inner: P, format: Arc<dyn DataFormat>) -> Self {
68        Self {
69            inner,
70            format,
71            request_borne: false,
72        }
73    }
74
75    /// Build an unmarshal step for a REST binding's request body (ADR-0096).
76    ///
77    /// The binding-injected unmarshal is the request-borne seam: its failing
78    /// input is by definition the client request. A format
79    /// [`CamelError::TypeConversionFailed`] is reclassified to
80    /// [`CamelError::ValidationError`] so consumers map it to 400. Every other
81    /// error — other format variants and inner-service failures — passes
82    /// through unchanged. User-authored `unmarshal` steps use [`Self::new`] and
83    /// inherit the 500 default.
84    pub fn for_request_binding(inner: P, format: Arc<dyn DataFormat>) -> Self {
85        Self {
86            inner,
87            format,
88            request_borne: true,
89        }
90    }
91}
92
93impl<P> Service<Exchange> for MarshalService<P>
94where
95    P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
96    P::Future: Send,
97{
98    type Response = Exchange;
99    type Error = CamelError;
100    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
101
102    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
103        self.inner.poll_ready(cx)
104    }
105
106    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
107        let body = std::mem::replace(&mut exchange.input.body, Body::Empty);
108        let format = self.format.clone();
109        match format.marshal_in_exchange(&mut exchange, body) {
110            Ok(new_body) => {
111                exchange.input.body = new_body;
112                let fut = self.inner.call(exchange);
113                Box::pin(fut)
114            }
115            Err(e) => {
116                if self.side == MarshalSide::Response {
117                    let format_name = self.format.name().to_string();
118                    Box::pin(async move {
119                        Err(CamelError::ProcessorErrorWithSource(
120                            format!("response marshal failed ({format_name})"),
121                            Arc::new(e),
122                        ))
123                    })
124                } else {
125                    Box::pin(async move { Err(e) })
126                }
127            }
128        }
129    }
130}
131
132impl<P> Service<Exchange> for UnmarshalService<P>
133where
134    P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
135    P::Future: Send,
136{
137    type Response = Exchange;
138    type Error = CamelError;
139    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
140
141    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
142        self.inner.poll_ready(cx)
143    }
144
145    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
146        let body = std::mem::replace(&mut exchange.input.body, Body::Empty);
147        let format = self.format.clone();
148        match format.unmarshal_in_exchange(&mut exchange, body) {
149            Ok(new_body) => {
150                exchange.input.body = new_body;
151                let fut = self.inner.call(exchange);
152                Box::pin(fut)
153            }
154            Err(e) => {
155                // ADR-0096: only the binding seam's format conversion failure is
156                // request-borne. Inner-service errors bypass this mapping.
157                let e = if self.request_borne {
158                    match e {
159                        CamelError::TypeConversionFailed(msg) => {
160                            CamelError::ValidationError(format!("request body rejected: {msg}"))
161                        }
162                        other => other,
163                    }
164                } else {
165                    e
166                };
167                Box::pin(async move { Err(e) })
168            }
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::data_format::JsonDataFormat;
177    use crate::data_format::XmlDataFormat;
178    use crate::data_format::builtin_data_format;
179    use camel_api::{IdentityProcessor, Message, Value};
180    use serde_json::json;
181    use std::sync::Arc;
182    use tower::ServiceExt;
183
184    struct FailingDataFormat;
185
186    impl DataFormat for FailingDataFormat {
187        fn name(&self) -> &str {
188            "failing"
189        }
190
191        fn marshal(&self, _body: Body) -> Result<Body, CamelError> {
192            Err(CamelError::ProcessorError("marshal-fail".to_string()))
193        }
194
195        fn unmarshal(&self, _body: Body) -> Result<Body, CamelError> {
196            Err(CamelError::ProcessorError("unmarshal-fail".to_string()))
197        }
198    }
199
200    struct ConversionFailingDataFormat;
201
202    impl DataFormat for ConversionFailingDataFormat {
203        fn name(&self) -> &str {
204            "conversion-failing"
205        }
206
207        fn marshal(&self, body: Body) -> Result<Body, CamelError> {
208            Ok(body)
209        }
210
211        fn unmarshal(&self, _body: Body) -> Result<Body, CamelError> {
212            Err(CamelError::TypeConversionFailed("boom".to_string()))
213        }
214    }
215
216    struct RouteFailingDataFormat;
217
218    impl DataFormat for RouteFailingDataFormat {
219        fn name(&self) -> &str {
220            "route-failing"
221        }
222
223        fn marshal(&self, body: Body) -> Result<Body, CamelError> {
224            Ok(body)
225        }
226
227        fn unmarshal(&self, _body: Body) -> Result<Body, CamelError> {
228            Err(CamelError::RouteError("x".to_string()))
229        }
230    }
231
232    #[tokio::test]
233    async fn test_marshal_json_to_text() {
234        let df = builtin_data_format("json").unwrap();
235        let svc = MarshalService::new(IdentityProcessor, df);
236        let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1}))));
237        let result = svc.oneshot(exchange).await.unwrap();
238        assert!(matches!(result.input.body, Body::Text(_)));
239    }
240
241    #[tokio::test]
242    async fn test_unmarshal_text_to_json() {
243        let df = builtin_data_format("json").unwrap();
244        let svc = UnmarshalService::new(IdentityProcessor, df);
245        let exchange = Exchange::new(Message::new(Body::Text(r#"{"b":2}"#.to_string())));
246        let result = svc.oneshot(exchange).await.unwrap();
247        assert!(matches!(result.input.body, Body::Json(_)));
248    }
249
250    #[tokio::test]
251    async fn test_marshal_preserves_headers() {
252        let df = builtin_data_format("json").unwrap();
253        let svc = MarshalService::new(IdentityProcessor, df);
254        let mut msg = Message::new(Body::Json(json!(1)));
255        msg.set_header("keep", Value::Bool(true));
256        let exchange = Exchange::new(msg);
257        let result = svc.oneshot(exchange).await.unwrap();
258        assert_eq!(result.input.header("keep"), Some(&Value::Bool(true)));
259    }
260
261    #[tokio::test]
262    async fn test_unmarshal_invalid_returns_error() {
263        let df = builtin_data_format("json").unwrap();
264        let svc = UnmarshalService::new(IdentityProcessor, df);
265        let exchange = Exchange::new(Message::new(Body::Text("bad".to_string())));
266        let result = svc.oneshot(exchange).await;
267        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
268    }
269
270    #[tokio::test]
271    async fn test_marshal_xml_json_to_text() {
272        let df = builtin_data_format("xml").unwrap();
273        let svc = MarshalService::new(IdentityProcessor, df);
274        let exchange = Exchange::new(Message::new(Body::Json(json!({"root": {"c": "1"}}))));
275        let result = svc.oneshot(exchange).await.unwrap();
276        match result.input.body {
277            Body::Text(s) => {
278                assert_eq!(s, "<root><c>1</c></root>");
279            }
280            _ => panic!("expected Body::Text, got {:?}", result.input.body),
281        }
282    }
283
284    #[tokio::test]
285    async fn test_unmarshal_text_to_json_via_xml() {
286        let df = builtin_data_format("xml").unwrap();
287        let svc = UnmarshalService::new(IdentityProcessor, df);
288        let exchange = Exchange::new(Message::new(Body::Text("<root><c/></root>".to_string())));
289        let result = svc.oneshot(exchange).await.unwrap();
290        match result.input.body {
291            Body::Json(v) => {
292                assert_eq!(v["root"]["c"], serde_json::Value::Null);
293                assert_eq!(v, json!({"root": {"c": null}}));
294            }
295            _ => panic!("expected Body::Json, got {:?}", result.input.body),
296        }
297    }
298
299    #[tokio::test]
300    async fn test_marshal_error_propagates() {
301        let svc = MarshalService::new(IdentityProcessor, Arc::new(FailingDataFormat));
302        let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
303        let result = svc.oneshot(exchange).await;
304        assert!(matches!(result, Err(CamelError::ProcessorError(msg)) if msg == "marshal-fail"));
305    }
306
307    #[tokio::test]
308    async fn test_unmarshal_error_propagates() {
309        let svc = UnmarshalService::new(IdentityProcessor, Arc::new(FailingDataFormat));
310        let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
311        let result = svc.oneshot(exchange).await;
312        assert!(matches!(result, Err(CamelError::ProcessorError(msg)) if msg == "unmarshal-fail"));
313    }
314
315    const MARSHAL_HOOK_KEY: &str = "TestMarshalHookCalled";
316
317    struct HeaderWritingMarshalFormat;
318
319    impl DataFormat for HeaderWritingMarshalFormat {
320        fn name(&self) -> &str {
321            "header-writer-marshal"
322        }
323        fn marshal(&self, body: Body) -> Result<Body, CamelError> {
324            Ok(body)
325        }
326        fn unmarshal(&self, body: Body) -> Result<Body, CamelError> {
327            Ok(body)
328        }
329
330        fn marshal_in_exchange(
331            &self,
332            exchange: &mut Exchange,
333            body: Body,
334        ) -> Result<Body, CamelError> {
335            exchange
336                .input
337                .headers
338                .insert(MARSHAL_HOOK_KEY.to_string(), serde_json::Value::Bool(true));
339            Ok(body)
340        }
341    }
342
343    #[tokio::test]
344    async fn test_marshal_service_propagates_exchange_to_hook() {
345        let svc = MarshalService::new(IdentityProcessor, Arc::new(HeaderWritingMarshalFormat));
346        let ex = Exchange::new(Message::new(Body::Json(serde_json::json!({}))));
347        let result = svc.oneshot(ex).await.unwrap();
348        assert_eq!(
349            result.input.headers.get(MARSHAL_HOOK_KEY),
350            Some(&serde_json::Value::Bool(true))
351        );
352    }
353
354    const UNMARSHAL_HOOK_KEY: &str = "TestUnmarshalHookCalled";
355
356    struct HeaderWritingUnmarshalFormat;
357
358    impl DataFormat for HeaderWritingUnmarshalFormat {
359        fn name(&self) -> &str {
360            "header-writer-unmarshal"
361        }
362        fn marshal(&self, body: Body) -> Result<Body, CamelError> {
363            Ok(body)
364        }
365        fn unmarshal(&self, body: Body) -> Result<Body, CamelError> {
366            Ok(body)
367        }
368
369        fn unmarshal_in_exchange(
370            &self,
371            exchange: &mut Exchange,
372            body: Body,
373        ) -> Result<Body, CamelError> {
374            exchange.input.headers.insert(
375                UNMARSHAL_HOOK_KEY.to_string(),
376                serde_json::Value::Bool(true),
377            );
378            Ok(body)
379        }
380    }
381
382    #[tokio::test]
383    async fn test_unmarshal_service_propagates_exchange_to_hook() {
384        let svc = UnmarshalService::new(IdentityProcessor, Arc::new(HeaderWritingUnmarshalFormat));
385        let ex = Exchange::new(Message::new(Body::Json(serde_json::json!({}))));
386        let result = svc.oneshot(ex).await.unwrap();
387        assert_eq!(
388            result.input.headers.get(UNMARSHAL_HOOK_KEY),
389            Some(&serde_json::Value::Bool(true))
390        );
391    }
392
393    #[tokio::test]
394    async fn for_response_wraps_marshal_error_with_source() {
395        let svc =
396            MarshalService::for_response(IdentityProcessor, Arc::new(XmlDataFormat::default()));
397        let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1, "b": 2}))));
398        let result = svc.oneshot(exchange).await;
399        match result {
400            Err(CamelError::ProcessorErrorWithSource(msg, source)) => {
401                assert!(
402                    msg.contains("response marshal failed"),
403                    "message must name the response-side failure, got {msg:?}"
404                );
405                assert!(
406                    matches!(
407                        source.downcast_ref::<CamelError>(),
408                        Some(CamelError::TypeConversionFailed(_))
409                    ),
410                    "source must preserve the original TypeConversionFailed, got {source:?}"
411                );
412            }
413            other => panic!("expected ProcessorErrorWithSource, got {other:?}"),
414        }
415    }
416
417    #[tokio::test]
418    async fn new_keeps_type_conversion_failure() {
419        let svc = MarshalService::new(IdentityProcessor, Arc::new(XmlDataFormat::default()));
420        let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1, "b": 2}))));
421        let result = svc.oneshot(exchange).await;
422        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
423    }
424
425    #[tokio::test]
426    async fn for_response_passes_success_through() {
427        let svc =
428            MarshalService::for_response(IdentityProcessor, Arc::new(JsonDataFormat::default()));
429        let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1}))));
430        let result = svc.oneshot(exchange).await.unwrap();
431        assert_eq!(result.input.body, Body::Text("{\"a\":1}".to_string()));
432    }
433
434    #[tokio::test]
435    async fn request_binding_reclassifies_format_conversion_failure() {
436        let svc = UnmarshalService::for_request_binding(
437            IdentityProcessor,
438            Arc::new(ConversionFailingDataFormat),
439        );
440        let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
441        let result = svc.oneshot(exchange).await;
442        match result {
443            Err(CamelError::ValidationError(msg)) => {
444                assert!(
445                    msg.contains("request body rejected: boom"),
446                    "message must name the request-borne rejection, got {msg:?}"
447                );
448            }
449            other => panic!("expected ValidationError, got {other:?}"),
450        }
451    }
452
453    #[tokio::test]
454    async fn request_binding_passes_inner_conversion_failure_through() {
455        let inner = tower::service_fn(|_ex: Exchange| async {
456            Err::<Exchange, CamelError>(CamelError::TypeConversionFailed("inner".to_string()))
457        });
458        let svc = UnmarshalService::for_request_binding(inner, Arc::new(JsonDataFormat::default()));
459        let exchange = Exchange::new(Message::new(Body::Text(r#"{"a":1}"#.to_string())));
460        let result = svc.oneshot(exchange).await;
461        assert!(
462            matches!(result, Err(CamelError::TypeConversionFailed(msg)) if msg == "inner"),
463            "inner conversion failures must bypass the reclassification boundary"
464        );
465    }
466
467    #[tokio::test]
468    async fn request_binding_passes_other_format_variants_through() {
469        let svc = UnmarshalService::for_request_binding(
470            IdentityProcessor,
471            Arc::new(RouteFailingDataFormat),
472        );
473        let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
474        let result = svc.oneshot(exchange).await;
475        assert!(
476            matches!(result, Err(CamelError::RouteError(msg)) if msg == "x"),
477            "only TypeConversionFailed is reclassified"
478        );
479    }
480
481    #[tokio::test]
482    async fn step_unmarshal_keeps_conversion_failure() {
483        let svc = UnmarshalService::new(IdentityProcessor, Arc::new(ConversionFailingDataFormat));
484        let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
485        let result = svc.oneshot(exchange).await;
486        assert!(matches!(result, Err(CamelError::TypeConversionFailed(msg)) if msg == "boom"));
487    }
488}