Skip to main content

camel_processor/data_format/
mod.rs

1mod csv;
2mod form;
3// `pub(crate)` so the TAR.GZ stream splitter can reuse the bounded
4// single-member GZIP decoder without widening the public data-format API.
5pub(crate) mod gzip;
6mod json;
7mod tar;
8mod tar_gz;
9#[cfg(test)]
10mod test_util;
11mod xml;
12mod zip;
13
14pub use csv::{CAMEL_CSV_HEADER_RECORD, CsvConfig, CsvDataFormat, QuoteMode, RecordSeparator};
15pub use form::{FormConfig, FormDataFormat};
16pub use gzip::{GzipConfig, GzipDataFormat};
17pub use json::{JsonConfig, JsonDataFormat};
18pub use tar::{TarConfig, TarDataFormat};
19pub use tar_gz::{TarGzConfig, TarGzDataFormat};
20pub use xml::{XmlConfig, XmlDataFormat};
21pub use zip::{ZipConfig, ZipDataFormat};
22
23use camel_api::DataFormat;
24use camel_api::body::Body;
25use camel_api::error::CamelError;
26use std::sync::Arc;
27
28/// Config-aware factory. `config` is the raw `config:` block from the DSL
29/// (or `Null` for defaults). Each arm deserializes into its own typed config
30/// with `deny_unknown_fields`, so a stray key fails closed with a precise message.
31pub fn builtin_data_format_with_config(
32    name: &str,
33    config: &serde_json::Value,
34) -> Result<Option<Arc<dyn DataFormat>>, CamelError> {
35    let df: Arc<dyn DataFormat> = match name {
36        "json" => Arc::new(JsonDataFormat::new(parse_cfg::<JsonConfig>(name, config)?)),
37        "csv" => Arc::new(CsvDataFormat::new(parse_cfg::<CsvConfig>(name, config)?)),
38        "form" => Arc::new(FormDataFormat::new(parse_cfg::<FormConfig>(name, config)?)),
39        "xml" => Arc::new(XmlDataFormat::new(parse_cfg::<XmlConfig>(name, config)?)),
40        "zip" => Arc::new(ZipDataFormat::new(parse_cfg::<ZipConfig>(name, config)?)),
41        "tar" => Arc::new(TarDataFormat::new(parse_cfg::<TarConfig>(name, config)?)),
42        "gzip" => Arc::new(GzipDataFormat::new(parse_cfg::<GzipConfig>(name, config)?)),
43        "tar.gz" => Arc::new(TarGzDataFormat::new(parse_cfg::<TarGzConfig>(
44            name, config,
45        )?)),
46        _ => return Ok(None),
47    };
48    Ok(Some(df))
49}
50
51/// Back-compat shim: existing callers keep working (config = Null → defaults).
52pub fn builtin_data_format(name: &str) -> Option<Arc<dyn DataFormat>> {
53    builtin_data_format_with_config(name, &serde_json::Value::Null)
54        .ok()
55        .flatten()
56}
57
58fn parse_cfg<T>(name: &str, v: &serde_json::Value) -> Result<T, CamelError>
59where
60    T: serde::de::DeserializeOwned + Default,
61{
62    if v.is_null() {
63        return Ok(T::default());
64    }
65    serde_json::from_value::<T>(v.clone()).map_err(|e| {
66        CamelError::RouteError(format!("invalid config for data format '{name}': {e}"))
67    })
68}
69
70/// Materializes the `marshal` input body into owned bytes, enforcing
71/// `max_input_size` (DoS cap, R3-L1) after materialization. `df` names the
72/// calling data format for error messages (e.g. `TarDataFormat`). `Text` and
73/// `Xml` use their UTF-8 bytes, `Json` is serialized, `Bytes` is copied;
74/// `Empty` and `Stream` fail closed, and streams are never consumed.
75fn materialize_marshal_input(
76    df: &str,
77    body: &Body,
78    max_input_size: u64,
79) -> Result<Vec<u8>, CamelError> {
80    let content: Vec<u8> = match body {
81        Body::Text(s) => s.as_bytes().to_vec(),
82        Body::Json(v) => serde_json::to_vec(v).map_err(|e| {
83            CamelError::TypeConversionFailed(format!("{df}::marshal cannot serialize JSON: {e}"))
84        })?,
85        Body::Bytes(b) => b.to_vec(),
86        Body::Xml(s) => s.as_bytes().to_vec(),
87        Body::Empty => {
88            return Err(CamelError::TypeConversionFailed(format!(
89                "{df}::marshal requires non-empty body"
90            )));
91        }
92        Body::Stream(_) => {
93            return Err(CamelError::TypeConversionFailed(
94                "cannot marshal Body::Stream — add 'stream_cache' or 'convert_body_to' before this step"
95                    .to_string(),
96            ));
97        }
98        _ => {
99            return Err(CamelError::TypeConversionFailed(format!(
100                "{df}::marshal does not support this body type"
101            )));
102        }
103    };
104
105    if content.len() as u64 > max_input_size {
106        return Err(CamelError::TypeConversionFailed(format!(
107            "{df}::marshal input {} bytes exceeds max_input_size {}",
108            content.len(),
109            max_input_size
110        )));
111    }
112    Ok(content)
113}
114
115/// Extracts the raw wire bytes for `unmarshal` from a materialized body.
116/// `df` names the calling data format and `wire` labels the expected payload
117/// shape (e.g. `TAR data`) for error messages. `Bytes` and `Text` yield their
118/// bytes; `Json` and `Xml` fail closed because they cannot be archive data;
119/// `Empty` fails; `Stream` fails without being consumed.
120fn raw_unmarshal_body(df: &str, wire: &str, body: &Body) -> Result<Vec<u8>, CamelError> {
121    match body {
122        Body::Bytes(b) => Ok(b.to_vec()),
123        Body::Text(s) => Ok(s.as_bytes().to_vec()),
124        Body::Empty => Err(CamelError::TypeConversionFailed(format!(
125            "{df}::unmarshal requires non-empty body"
126        ))),
127        Body::Stream(_) => Err(CamelError::TypeConversionFailed(
128            "cannot unmarshal Body::Stream — use UnmarshalService which auto-materializes"
129                .to_string(),
130        )),
131        Body::Json(_) | Body::Xml(_) => Err(CamelError::TypeConversionFailed(format!(
132            "{df}::unmarshal only supports Body::Bytes and Body::Text ({wire})"
133        ))),
134        _ => Err(CamelError::TypeConversionFailed(format!(
135            "{df}::unmarshal does not support this body type"
136        ))),
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn test_builtin_json() {
146        let df = builtin_data_format("json").unwrap();
147        assert_eq!(df.name(), "json");
148    }
149
150    #[test]
151    fn test_builtin_xml() {
152        let df = builtin_data_format("xml").unwrap();
153        assert_eq!(df.name(), "xml");
154    }
155
156    #[test]
157    fn test_builtin_csv() {
158        let csv_df = builtin_data_format("csv").unwrap();
159        assert_eq!(csv_df.name(), "csv");
160    }
161
162    #[test]
163    fn test_builtin_unknown_returns_none() {
164        assert!(builtin_data_format("protobuf").is_none());
165        assert!(builtin_data_format("").is_none());
166    }
167
168    #[test]
169    fn test_builtin_json_with_config() {
170        let config = serde_json::json!({"max_bytes": 67108864});
171        let df = builtin_data_format_with_config("json", &config)
172            .unwrap()
173            .unwrap();
174        assert_eq!(df.name(), "json");
175    }
176
177    #[test]
178    fn test_builtin_json_with_null_config_returns_default() {
179        let df = builtin_data_format_with_config("json", &serde_json::Value::Null)
180            .unwrap()
181            .unwrap();
182        assert_eq!(df.name(), "json");
183    }
184
185    #[test]
186    fn test_builtin_json_with_unknown_key_fails() {
187        let config = serde_json::json!({"max_byte": 100});
188        let result = builtin_data_format_with_config("json", &config);
189        match result {
190            Err(CamelError::RouteError(msg)) => {
191                assert!(msg.contains("invalid config"), "msg: {msg}");
192            }
193            Err(other) => panic!("expected RouteError, got: {other:?}"),
194            Ok(_) => panic!("typo should fail closed"),
195        }
196    }
197
198    #[test]
199    fn test_builtin_shim_still_works() {
200        let df = builtin_data_format("json").unwrap();
201        assert_eq!(df.name(), "json");
202    }
203
204    #[test]
205    fn builtin_archive_formats_resolve() {
206        for (name, expected) in [("tar", "tar"), ("gzip", "gzip"), ("tar.gz", "tar.gz")] {
207            let df = builtin_data_format_with_config(name, &serde_json::Value::Null)
208                .unwrap()
209                .unwrap_or_else(|| panic!("'{name}' should resolve to a built-in format"));
210            assert_eq!(df.name(), expected, "format name mismatch for '{name}'");
211        }
212    }
213
214    #[test]
215    fn builtin_archive_config_rejects_unknown_fields() {
216        for name in ["tar", "gzip", "tar.gz"] {
217            let config = serde_json::json!({"unknown_field": true});
218            match builtin_data_format_with_config(name, &config) {
219                Err(CamelError::RouteError(msg)) => {
220                    assert!(
221                        msg.contains("invalid config") && msg.contains(name),
222                        "unexpected message for '{name}': {msg}"
223                    );
224                }
225                Err(other) => panic!("expected RouteError for '{name}', got: {other:?}"),
226                Ok(_) => panic!("unknown key for '{name}' should fail closed"),
227            }
228        }
229    }
230
231    #[test]
232    fn archive_marshal_serializes_json_bodies() {
233        // The shared marshal materialization serializes `Body::Json` instead
234        // of rejecting it; every archive format must round trip it as bytes.
235        let json = serde_json::json!({"payload": "text"});
236        let expected = serde_json::to_vec(&json).unwrap();
237        for name in ["tar", "gzip", "tar.gz", "zip"] {
238            let df = builtin_data_format(name).unwrap();
239            let restored = df
240                .unmarshal(df.marshal(Body::Json(json.clone())).unwrap())
241                .unwrap();
242            match restored {
243                Body::Bytes(b) => assert_eq!(&b[..], &expected[..], "format '{name}'"),
244                other => panic!("format '{name}' must return bytes, got: {other:?}"),
245            }
246        }
247    }
248
249    #[test]
250    fn archive_unmarshal_rejects_structured_bodies_with_format_named() {
251        // The shared raw-body extraction keeps the calling format's name in
252        // the rejection message for `Json`/`Xml` unmarshal input.
253        for name in ["tar", "gzip", "tar.gz", "zip"] {
254            let df = builtin_data_format(name).unwrap();
255            let msg = format!(
256                "{}",
257                df.unmarshal(Body::Json(serde_json::json!({}))).unwrap_err()
258            );
259            assert!(
260                msg.contains("::unmarshal only supports Body::Bytes and Body::Text"),
261                "format '{name}' should name the supported body kinds: {msg}"
262            );
263        }
264    }
265}