Skip to main content

camel_processor/
script_mutator.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::exchange::Exchange;
9use camel_api::{CamelError, Headers, PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value};
10use camel_language_api::{EvalMeta, MutatingExpression, to_expression_failed};
11
12/// Collect the exact Content-Type header entries (key spelling and value) as a
13/// deterministically ordered list.
14///
15/// Both language surfaces commit changed-only per exact key, so a before/after
16/// comparison of this list detects every landed Content-Type mutation while
17/// ignoring same-value assignments.
18fn content_type_entries(headers: &Headers) -> Vec<(String, Value)> {
19    let mut entries: Vec<(String, Value)> = headers
20        .iter()
21        .filter(|(key, _)| key.eq_ignore_ascii_case("content-type"))
22        .map(|(key, value)| (key.clone(), value.clone()))
23        .collect();
24    entries.sort_by(|a, b| a.0.cmp(&b.0));
25    entries
26}
27
28/// Processor that executes a mutating expression, allowing scripts to modify the Exchange.
29/// Uses `Arc<dyn MutatingExpression>` to enable `Clone` (required by `BoxProcessor`).
30///
31/// Evaluation failures are mapped to [`CamelError::ExpressionFailed`] with
32/// the trusted route metadata supplied via [`ScriptMutator::with_meta`]
33/// (ParseError routes as class `Parse` via `LanguageError::class()`).
34#[derive(Clone)]
35pub struct ScriptMutator {
36    expression: Arc<dyn MutatingExpression>,
37    meta: EvalMeta,
38}
39
40impl ScriptMutator {
41    /// Create without route metadata. The default metadata reports language
42    /// `unknown` — tests only; production code should use
43    /// [`ScriptMutator::with_meta`].
44    pub fn new(expression: Box<dyn MutatingExpression>) -> Self {
45        Self::with_meta(
46            expression,
47            EvalMeta {
48                language: "unknown".to_string(),
49                route_id: String::new(),
50                step_id: String::new(),
51                verb: String::new(),
52                target: None,
53            },
54        )
55    }
56
57    /// Create with trusted route metadata used to enrich evaluation
58    /// failures as [`CamelError::ExpressionFailed`].
59    pub fn with_meta(expression: Box<dyn MutatingExpression>, meta: EvalMeta) -> Self {
60        Self {
61            expression: expression.into(),
62            meta,
63        }
64    }
65}
66
67impl Service<Exchange> for ScriptMutator {
68    type Response = Exchange;
69    type Error = CamelError;
70    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
71
72    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
73        Poll::Ready(Ok(()))
74    }
75
76    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
77        let expression = self.expression.clone();
78        let meta = self.meta.clone();
79        let content_type_before = content_type_entries(&exchange.input.headers);
80        Box::pin(async move {
81            let result = expression.evaluate(&mut exchange).await;
82            match result {
83                Ok(_) => {
84                    if content_type_entries(&exchange.input.headers) != content_type_before {
85                        exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
86                    }
87                    Ok(exchange)
88                }
89                Err(e) => Err(to_expression_failed(e, &meta)),
90            }
91        })
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use camel_api::{CamelError, Exchange, ExpressionErrorClass, Message, Value};
98    use camel_language_api::{EvalMeta, LanguageError};
99    use tower::ServiceExt;
100
101    use super::*;
102
103    /// A mutating expression that always fails with a structured failure.
104    struct EvalFailureMutatingExpression;
105
106    #[async_trait::async_trait]
107    impl MutatingExpression for EvalFailureMutatingExpression {
108        async fn evaluate(&self, _exchange: &mut Exchange) -> Result<Value, LanguageError> {
109            Err(LanguageError::EvalFailure {
110                class: ExpressionErrorClass::Runtime,
111                position: None,
112                detail: None,
113            })
114        }
115    }
116
117    /// A simple test mutating expression that sets a header
118    struct TestMutatingExpression;
119
120    struct ParseErrorMutatingExpression;
121    struct NotSupportedMutatingExpression;
122    struct UnknownVariableMutatingExpression;
123
124    #[async_trait::async_trait]
125    impl MutatingExpression for TestMutatingExpression {
126        async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
127            exchange
128                .input
129                .headers
130                .insert("mutated".into(), Value::Bool(true));
131            Ok(Value::Null)
132        }
133    }
134
135    #[async_trait::async_trait]
136    impl MutatingExpression for ParseErrorMutatingExpression {
137        async fn evaluate(&self, _exchange: &mut Exchange) -> Result<Value, LanguageError> {
138            Err(LanguageError::ParseError {
139                expr: "x".to_string(),
140                reason: "bad".to_string(),
141            })
142        }
143    }
144
145    #[async_trait::async_trait]
146    impl MutatingExpression for NotSupportedMutatingExpression {
147        async fn evaluate(&self, _exchange: &mut Exchange) -> Result<Value, LanguageError> {
148            Err(LanguageError::NotSupported {
149                feature: "f".to_string(),
150                language: "l".to_string(),
151            })
152        }
153    }
154
155    #[async_trait::async_trait]
156    impl MutatingExpression for UnknownVariableMutatingExpression {
157        async fn evaluate(&self, _exchange: &mut Exchange) -> Result<Value, LanguageError> {
158            Err(LanguageError::UnknownVariable("foo".to_string()))
159        }
160    }
161
162    #[tokio::test]
163    async fn test_script_mutator_modifies_exchange() {
164        let exchange = Exchange::new(Message::new("test"));
165
166        let mutator = ScriptMutator::new(Box::new(TestMutatingExpression));
167
168        let result = mutator.oneshot(exchange).await.unwrap();
169        assert_eq!(result.input.header("mutated"), Some(&Value::Bool(true)));
170    }
171
172    #[tokio::test]
173    async fn test_script_mutator_preserves_body() {
174        let exchange = Exchange::new(Message::new("original body"));
175
176        let mutator = ScriptMutator::new(Box::new(TestMutatingExpression));
177
178        let result = mutator.oneshot(exchange).await.unwrap();
179        assert_eq!(result.input.body.as_text(), Some("original body"));
180    }
181
182    #[tokio::test]
183    async fn test_script_mutator_is_clone() {
184        let mutator = ScriptMutator::new(Box::new(TestMutatingExpression));
185        let _cloned = mutator.clone();
186    }
187
188    #[tokio::test]
189    async fn script_mutator_error_is_expression_failed() {
190        let meta = EvalMeta {
191            language: "rhai".to_string(),
192            route_id: "r1".to_string(),
193            step_id: "script#0".to_string(),
194            verb: "script".to_string(),
195            target: None,
196        };
197        let mutator = ScriptMutator::with_meta(Box::new(EvalFailureMutatingExpression), meta);
198
199        let result = mutator.oneshot(Exchange::new(Message::new("test"))).await;
200
201        assert!(
202            matches!(
203                result,
204                Err(CamelError::ExpressionFailed {
205                    ref language,
206                    ref verb,
207                    class: ExpressionErrorClass::Runtime,
208                    ..
209                }) if language == "rhai" && verb == "script"
210            ),
211            "mutating-eval failure must map to ExpressionFailed with the bound meta"
212        );
213    }
214
215    #[tokio::test]
216    async fn test_script_mutator_maps_parse_error() {
217        let exchange = Exchange::new(Message::new("test"));
218        let mutator = ScriptMutator::new(Box::new(ParseErrorMutatingExpression));
219        let result = mutator.oneshot(exchange).await;
220        assert!(matches!(
221            result,
222            Err(CamelError::ExpressionFailed {
223                class: ExpressionErrorClass::Parse,
224                ..
225            })
226        ));
227    }
228
229    #[tokio::test]
230    async fn test_script_mutator_maps_not_supported_error() {
231        let exchange = Exchange::new(Message::new("test"));
232        let mutator = ScriptMutator::new(Box::new(NotSupportedMutatingExpression));
233        let result = mutator.oneshot(exchange).await;
234        // NotSupported carries no class: to_expression_failed defaults it to
235        // Runtime under the default "unknown" language.
236        assert!(matches!(
237            result,
238            Err(CamelError::ExpressionFailed {
239                ref language,
240                class: ExpressionErrorClass::Runtime,
241                ..
242            }) if language == "unknown"
243        ));
244    }
245
246    #[tokio::test]
247    async fn test_script_mutator_maps_other_language_error() {
248        let exchange = Exchange::new(Message::new("test"));
249        let mutator = ScriptMutator::new(Box::new(UnknownVariableMutatingExpression));
250        let result = mutator.oneshot(exchange).await;
251        assert!(matches!(
252            result,
253            Err(CamelError::ExpressionFailed {
254                class: ExpressionErrorClass::Runtime,
255                ..
256            })
257        ));
258    }
259
260    // ── Content-Type provenance marker ──
261
262    /// A script that assigns a new value to the `Content-Type` header.
263    struct SetContentTypeMutatingExpression(&'static str);
264
265    #[async_trait::async_trait]
266    impl MutatingExpression for SetContentTypeMutatingExpression {
267        async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
268            exchange
269                .input
270                .headers
271                .insert("Content-Type".into(), Value::String(self.0.to_string()));
272            Ok(Value::Null)
273        }
274    }
275
276    /// A script that renames the `Content-Type` header key casing, keeping the value.
277    struct RenameContentTypeCaseMutatingExpression;
278
279    #[async_trait::async_trait]
280    impl MutatingExpression for RenameContentTypeCaseMutatingExpression {
281        async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
282            let value = exchange
283                .input
284                .headers
285                .remove("Content-Type")
286                .expect("test double expects a Content-Type header");
287            exchange.input.headers.insert("content-type".into(), value);
288            Ok(Value::Null)
289        }
290    }
291
292    /// A script that removes the `Content-Type` header.
293    struct RemoveContentTypeMutatingExpression;
294
295    #[async_trait::async_trait]
296    impl MutatingExpression for RemoveContentTypeMutatingExpression {
297        async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
298            exchange.input.headers.remove("Content-Type");
299            Ok(Value::Null)
300        }
301    }
302
303    /// A script that only touches the body.
304    struct BodyOnlyMutatingExpression;
305
306    #[async_trait::async_trait]
307    impl MutatingExpression for BodyOnlyMutatingExpression {
308        async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
309            exchange.input.body = "mutated body".into();
310            Ok(Value::Null)
311        }
312    }
313
314    fn exchange_with_content_type(value: &str) -> Exchange {
315        let mut exchange = Exchange::new(Message::new("test"));
316        exchange
317            .input
318            .headers
319            .insert("Content-Type".into(), Value::String(value.into()));
320        exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
321        exchange
322    }
323
324    #[tokio::test]
325    async fn script_mutator_clears_marker_on_ct_update() {
326        let exchange = exchange_with_content_type("application/json");
327        let mutator = ScriptMutator::new(Box::new(SetContentTypeMutatingExpression("text/html")));
328
329        let result = mutator.oneshot(exchange).await.unwrap();
330        assert_eq!(
331            result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
332            None,
333            "a script write to Content-Type must clear the inherited marker"
334        );
335        assert_eq!(
336            result.input.header("Content-Type"),
337            Some(&Value::String("text/html".into()))
338        );
339    }
340
341    #[tokio::test]
342    async fn script_mutator_clears_marker_on_case_rename() {
343        let exchange = exchange_with_content_type("application/json");
344        let mutator = ScriptMutator::new(Box::new(RenameContentTypeCaseMutatingExpression));
345
346        let result = mutator.oneshot(exchange).await.unwrap();
347        assert_eq!(
348            result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
349            None,
350            "renaming the Content-Type key casing lands a mutation and must clear the marker"
351        );
352        assert_eq!(
353            result.input.header("content-type"),
354            Some(&Value::String("application/json".into()))
355        );
356    }
357
358    #[tokio::test]
359    async fn script_mutator_clears_marker_on_ct_removal() {
360        let exchange = exchange_with_content_type("application/json");
361        let mutator = ScriptMutator::new(Box::new(RemoveContentTypeMutatingExpression));
362
363        let result = mutator.oneshot(exchange).await.unwrap();
364        assert_eq!(
365            result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
366            None,
367            "removing Content-Type must clear the inherited marker"
368        );
369        assert_eq!(result.input.header("Content-Type"), None);
370    }
371
372    #[tokio::test]
373    async fn script_mutator_keeps_marker_on_same_value_assignment() {
374        let exchange = exchange_with_content_type("application/json");
375        let mutator = ScriptMutator::new(Box::new(SetContentTypeMutatingExpression(
376            "application/json",
377        )));
378
379        let result = mutator.oneshot(exchange).await.unwrap();
380        assert_eq!(
381            result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
382            Some(&Value::Bool(true)),
383            "a same-value assignment does not land a change and must keep the marker"
384        );
385    }
386
387    #[tokio::test]
388    async fn script_mutator_keeps_marker_on_body_only_script() {
389        let exchange = exchange_with_content_type("application/json");
390        let mutator = ScriptMutator::new(Box::new(BodyOnlyMutatingExpression));
391
392        let result = mutator.oneshot(exchange).await.unwrap();
393        assert_eq!(
394            result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
395            Some(&Value::Bool(true)),
396            "a body-only script must keep the marker"
397        );
398        assert_eq!(result.input.body.as_text(), Some("mutated body"));
399    }
400
401    /// Marker value and headers captured by the snapshotting test double.
402    type CapturedHeaderState = Option<(Option<Value>, camel_api::Headers)>;
403
404    /// A failing script that snapshots the marker and headers it is handed. The
405    /// `Err` path consumes the exchange, so recording the state inside `evaluate`
406    /// is the only way to assert the caller cleared nothing on the error path.
407    struct SnapshottingParseErrorMutatingExpression(Arc<std::sync::Mutex<CapturedHeaderState>>);
408
409    #[async_trait::async_trait]
410    impl MutatingExpression for SnapshottingParseErrorMutatingExpression {
411        async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
412            *self
413                .0
414                .lock()
415                .expect("test double snapshot mutex is not poisoned") = Some((
416                exchange
417                    .property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED)
418                    .cloned(),
419                exchange.input.headers.clone(),
420            ));
421            Err(LanguageError::ParseError {
422                expr: "x".to_string(),
423                reason: "bad".to_string(),
424            })
425        }
426    }
427
428    #[tokio::test]
429    async fn script_mutator_keeps_marker_on_eval_error() {
430        let snapshot = Arc::new(std::sync::Mutex::new(None));
431        let mutator = ScriptMutator::new(Box::new(SnapshottingParseErrorMutatingExpression(
432            snapshot.clone(),
433        )));
434
435        let result = mutator
436            .oneshot(exchange_with_content_type("application/json"))
437            .await;
438        assert!(
439            matches!(result, Err(CamelError::ExpressionFailed { .. })),
440            "the parse error must propagate"
441        );
442
443        let (marker, headers) = snapshot
444            .lock()
445            .expect("test double snapshot mutex is not poisoned")
446            .take()
447            .expect("the expression must have run");
448        assert_eq!(
449            marker,
450            Some(Value::Bool(true)),
451            "a failed script must not clear the marker"
452        );
453        assert_eq!(
454            headers.get("Content-Type"),
455            Some(&Value::String("application/json".into())),
456            "a failed script must not touch the headers"
457        );
458    }
459}