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 pub fn for_response(inner: P, format: Arc<dyn DataFormat>) -> Self {
42 Self {
43 inner,
44 format,
45 side: MarshalSide::Response,
46 }
47 }
48}
49
50const _: fn() = || {
51 fn assert_send_sync_static<T: Send + Sync + 'static>() {}
52 assert_send_sync_static::<CamelError>();
53};
54
55#[derive(Clone)]
56pub struct UnmarshalService<P> {
57 inner: P,
58 format: Arc<dyn DataFormat>,
59}
60
61impl<P> UnmarshalService<P> {
62 pub fn new(inner: P, format: Arc<dyn DataFormat>) -> Self {
63 Self { inner, format }
64 }
65}
66
67impl<P> Service<Exchange> for MarshalService<P>
68where
69 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
70 P::Future: Send,
71{
72 type Response = Exchange;
73 type Error = CamelError;
74 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
75
76 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
77 self.inner.poll_ready(cx)
78 }
79
80 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
81 let body = std::mem::replace(&mut exchange.input.body, Body::Empty);
82 let format = self.format.clone();
83 match format.marshal_in_exchange(&mut exchange, body) {
84 Ok(new_body) => {
85 exchange.input.body = new_body;
86 let fut = self.inner.call(exchange);
87 Box::pin(fut)
88 }
89 Err(e) => {
90 if self.side == MarshalSide::Response {
91 let format_name = self.format.name().to_string();
92 Box::pin(async move {
93 Err(CamelError::ProcessorErrorWithSource(
94 format!("response marshal failed ({format_name})"),
95 Arc::new(e),
96 ))
97 })
98 } else {
99 Box::pin(async move { Err(e) })
100 }
101 }
102 }
103 }
104}
105
106impl<P> Service<Exchange> for UnmarshalService<P>
107where
108 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
109 P::Future: Send,
110{
111 type Response = Exchange;
112 type Error = CamelError;
113 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
114
115 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
116 self.inner.poll_ready(cx)
117 }
118
119 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
120 let body = std::mem::replace(&mut exchange.input.body, Body::Empty);
121 let format = self.format.clone();
122 match format.unmarshal_in_exchange(&mut exchange, body) {
123 Ok(new_body) => {
124 exchange.input.body = new_body;
125 let fut = self.inner.call(exchange);
126 Box::pin(fut)
127 }
128 Err(e) => Box::pin(async move { Err(e) }),
129 }
130 }
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use crate::data_format::JsonDataFormat;
137 use crate::data_format::XmlDataFormat;
138 use crate::data_format::builtin_data_format;
139 use camel_api::{IdentityProcessor, Message, Value};
140 use serde_json::json;
141 use std::sync::Arc;
142 use tower::ServiceExt;
143
144 struct FailingDataFormat;
145
146 impl DataFormat for FailingDataFormat {
147 fn name(&self) -> &str {
148 "failing"
149 }
150
151 fn marshal(&self, _body: Body) -> Result<Body, CamelError> {
152 Err(CamelError::ProcessorError("marshal-fail".to_string()))
153 }
154
155 fn unmarshal(&self, _body: Body) -> Result<Body, CamelError> {
156 Err(CamelError::ProcessorError("unmarshal-fail".to_string()))
157 }
158 }
159
160 #[tokio::test]
161 async fn test_marshal_json_to_text() {
162 let df = builtin_data_format("json").unwrap();
163 let svc = MarshalService::new(IdentityProcessor, df);
164 let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1}))));
165 let result = svc.oneshot(exchange).await.unwrap();
166 assert!(matches!(result.input.body, Body::Text(_)));
167 }
168
169 #[tokio::test]
170 async fn test_unmarshal_text_to_json() {
171 let df = builtin_data_format("json").unwrap();
172 let svc = UnmarshalService::new(IdentityProcessor, df);
173 let exchange = Exchange::new(Message::new(Body::Text(r#"{"b":2}"#.to_string())));
174 let result = svc.oneshot(exchange).await.unwrap();
175 assert!(matches!(result.input.body, Body::Json(_)));
176 }
177
178 #[tokio::test]
179 async fn test_marshal_preserves_headers() {
180 let df = builtin_data_format("json").unwrap();
181 let svc = MarshalService::new(IdentityProcessor, df);
182 let mut msg = Message::new(Body::Json(json!(1)));
183 msg.set_header("keep", Value::Bool(true));
184 let exchange = Exchange::new(msg);
185 let result = svc.oneshot(exchange).await.unwrap();
186 assert_eq!(result.input.header("keep"), Some(&Value::Bool(true)));
187 }
188
189 #[tokio::test]
190 async fn test_unmarshal_invalid_returns_error() {
191 let df = builtin_data_format("json").unwrap();
192 let svc = UnmarshalService::new(IdentityProcessor, df);
193 let exchange = Exchange::new(Message::new(Body::Text("bad".to_string())));
194 let result = svc.oneshot(exchange).await;
195 assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
196 }
197
198 #[tokio::test]
199 async fn test_marshal_xml_json_to_text() {
200 let df = builtin_data_format("xml").unwrap();
201 let svc = MarshalService::new(IdentityProcessor, df);
202 let exchange = Exchange::new(Message::new(Body::Json(json!({"root": {"c": "1"}}))));
203 let result = svc.oneshot(exchange).await.unwrap();
204 match result.input.body {
205 Body::Text(s) => {
206 assert_eq!(s, "<root><c>1</c></root>");
207 }
208 _ => panic!("expected Body::Text, got {:?}", result.input.body),
209 }
210 }
211
212 #[tokio::test]
213 async fn test_unmarshal_text_to_json_via_xml() {
214 let df = builtin_data_format("xml").unwrap();
215 let svc = UnmarshalService::new(IdentityProcessor, df);
216 let exchange = Exchange::new(Message::new(Body::Text("<root><c/></root>".to_string())));
217 let result = svc.oneshot(exchange).await.unwrap();
218 match result.input.body {
219 Body::Json(v) => {
220 assert_eq!(v["root"]["c"], serde_json::Value::Null);
221 assert_eq!(v, json!({"root": {"c": null}}));
222 }
223 _ => panic!("expected Body::Json, got {:?}", result.input.body),
224 }
225 }
226
227 #[tokio::test]
228 async fn test_marshal_error_propagates() {
229 let svc = MarshalService::new(IdentityProcessor, Arc::new(FailingDataFormat));
230 let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
231 let result = svc.oneshot(exchange).await;
232 assert!(matches!(result, Err(CamelError::ProcessorError(msg)) if msg == "marshal-fail"));
233 }
234
235 #[tokio::test]
236 async fn test_unmarshal_error_propagates() {
237 let svc = UnmarshalService::new(IdentityProcessor, Arc::new(FailingDataFormat));
238 let exchange = Exchange::new(Message::new(Body::Text("x".to_string())));
239 let result = svc.oneshot(exchange).await;
240 assert!(matches!(result, Err(CamelError::ProcessorError(msg)) if msg == "unmarshal-fail"));
241 }
242
243 const MARSHAL_HOOK_KEY: &str = "TestMarshalHookCalled";
244
245 struct HeaderWritingMarshalFormat;
246
247 impl DataFormat for HeaderWritingMarshalFormat {
248 fn name(&self) -> &str {
249 "header-writer-marshal"
250 }
251 fn marshal(&self, body: Body) -> Result<Body, CamelError> {
252 Ok(body)
253 }
254 fn unmarshal(&self, body: Body) -> Result<Body, CamelError> {
255 Ok(body)
256 }
257
258 fn marshal_in_exchange(
259 &self,
260 exchange: &mut Exchange,
261 body: Body,
262 ) -> Result<Body, CamelError> {
263 exchange
264 .input
265 .headers
266 .insert(MARSHAL_HOOK_KEY.to_string(), serde_json::Value::Bool(true));
267 Ok(body)
268 }
269 }
270
271 #[tokio::test]
272 async fn test_marshal_service_propagates_exchange_to_hook() {
273 let svc = MarshalService::new(IdentityProcessor, Arc::new(HeaderWritingMarshalFormat));
274 let ex = Exchange::new(Message::new(Body::Json(serde_json::json!({}))));
275 let result = svc.oneshot(ex).await.unwrap();
276 assert_eq!(
277 result.input.headers.get(MARSHAL_HOOK_KEY),
278 Some(&serde_json::Value::Bool(true))
279 );
280 }
281
282 const UNMARSHAL_HOOK_KEY: &str = "TestUnmarshalHookCalled";
283
284 struct HeaderWritingUnmarshalFormat;
285
286 impl DataFormat for HeaderWritingUnmarshalFormat {
287 fn name(&self) -> &str {
288 "header-writer-unmarshal"
289 }
290 fn marshal(&self, body: Body) -> Result<Body, CamelError> {
291 Ok(body)
292 }
293 fn unmarshal(&self, body: Body) -> Result<Body, CamelError> {
294 Ok(body)
295 }
296
297 fn unmarshal_in_exchange(
298 &self,
299 exchange: &mut Exchange,
300 body: Body,
301 ) -> Result<Body, CamelError> {
302 exchange.input.headers.insert(
303 UNMARSHAL_HOOK_KEY.to_string(),
304 serde_json::Value::Bool(true),
305 );
306 Ok(body)
307 }
308 }
309
310 #[tokio::test]
311 async fn test_unmarshal_service_propagates_exchange_to_hook() {
312 let svc = UnmarshalService::new(IdentityProcessor, Arc::new(HeaderWritingUnmarshalFormat));
313 let ex = Exchange::new(Message::new(Body::Json(serde_json::json!({}))));
314 let result = svc.oneshot(ex).await.unwrap();
315 assert_eq!(
316 result.input.headers.get(UNMARSHAL_HOOK_KEY),
317 Some(&serde_json::Value::Bool(true))
318 );
319 }
320
321 #[tokio::test]
322 async fn for_response_wraps_marshal_error_with_source() {
323 let svc =
324 MarshalService::for_response(IdentityProcessor, Arc::new(XmlDataFormat::default()));
325 let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1, "b": 2}))));
326 let result = svc.oneshot(exchange).await;
327 match result {
328 Err(CamelError::ProcessorErrorWithSource(msg, source)) => {
329 assert!(
330 msg.contains("response marshal failed"),
331 "message must name the response-side failure, got {msg:?}"
332 );
333 assert!(
334 matches!(
335 source.downcast_ref::<CamelError>(),
336 Some(CamelError::TypeConversionFailed(_))
337 ),
338 "source must preserve the original TypeConversionFailed, got {source:?}"
339 );
340 }
341 other => panic!("expected ProcessorErrorWithSource, got {other:?}"),
342 }
343 }
344
345 #[tokio::test]
346 async fn new_keeps_type_conversion_failure() {
347 let svc = MarshalService::new(IdentityProcessor, Arc::new(XmlDataFormat::default()));
348 let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1, "b": 2}))));
349 let result = svc.oneshot(exchange).await;
350 assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
351 }
352
353 #[tokio::test]
354 async fn for_response_passes_success_through() {
355 let svc =
356 MarshalService::for_response(IdentityProcessor, Arc::new(JsonDataFormat::default()));
357 let exchange = Exchange::new(Message::new(Body::Json(json!({"a": 1}))));
358 let result = svc.oneshot(exchange).await.unwrap();
359 assert_eq!(result.input.body, Body::Text("{\"a\":1}".to_string()));
360 }
361}