Skip to main content

camel_core/step/
function_step.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::task::{Context, Poll};
5use std::time::Duration;
6
7use camel_api::{
8    CamelError, Exchange, ExchangePatch, FunctionDefinition, FunctionId, FunctionInvocationError,
9    FunctionInvoker, PatchBody,
10};
11use tower::Service;
12use tracing::Instrument;
13
14#[derive(Clone)]
15pub struct FunctionStep {
16    definition: FunctionDefinition,
17    invoker: Arc<dyn FunctionInvoker>,
18}
19
20impl FunctionStep {
21    pub fn new(invoker: Arc<dyn FunctionInvoker>, definition: FunctionDefinition) -> Self {
22        Self {
23            definition,
24            invoker,
25        }
26    }
27}
28
29impl Service<Exchange> for FunctionStep {
30    type Response = Exchange;
31    type Error = CamelError;
32    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
33
34    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
35        Poll::Ready(Ok(()))
36    }
37
38    fn call(&mut self, mut ex: Exchange) -> Self::Future {
39        let invoker = Arc::clone(&self.invoker);
40        let id = self.definition.id.clone();
41        let runtime = self.definition.runtime.clone();
42        let timeout_ms = self.definition.timeout_ms;
43        let span = tracing::info_span!(
44            target: "camel_function",
45            "function",
46            function_id = %id.0,
47            runtime = %runtime,
48            timeout_ms = timeout_ms,
49            status = tracing::field::Empty,
50            duration_ms = tracing::field::Empty,
51            error_kind = tracing::field::Empty,
52        );
53        Box::pin(async move {
54            let start = std::time::Instant::now();
55            let outcome: Result<ExchangePatch, CamelError> = async {
56                let result = tokio::time::timeout(
57                    Duration::from_millis(timeout_ms),
58                    invoker.invoke(&id, &ex),
59                )
60                .await
61                .map_err(|_| {
62                    CamelError::ProcessorError(format!(
63                        "function:timeout: {} timed out after {}ms",
64                        id.0, timeout_ms
65                    ))
66                })?;
67                let patch = result.map_err(|e| map_invocation_error(e, &id))?;
68                Ok(patch)
69            }
70            .instrument(span.clone())
71            .await;
72            let elapsed = start.elapsed().as_millis() as u64;
73            span.record("duration_ms", elapsed);
74            match &outcome {
75                Ok(_) => {
76                    span.record("status", "ok");
77                }
78                Err(CamelError::ProcessorError(msg)) => {
79                    let kind = if msg.starts_with("function:timeout:") {
80                        "timeout"
81                    } else if msg.starts_with("function:user_error:") {
82                        "user_error"
83                    } else if msg.starts_with("function:runner_unavailable:") {
84                        "runner_unavailable"
85                    } else if msg.starts_with("function:not_registered:") {
86                        "not_registered"
87                    } else if msg.starts_with("function:transport:") {
88                        "transport"
89                    } else if msg.starts_with("function:invalid_patch:") {
90                        "invalid_patch"
91                    } else {
92                        "unknown"
93                    };
94                    span.record("status", kind);
95                    span.record("error_kind", kind);
96                }
97                Err(_) => {
98                    span.record("status", "unknown");
99                    span.record("error_kind", "unknown");
100                }
101            }
102            let patch = outcome?;
103            apply_patch(&mut ex, patch);
104            Ok(ex)
105        })
106    }
107}
108
109fn map_invocation_error(err: FunctionInvocationError, id: &FunctionId) -> CamelError {
110    match err {
111        FunctionInvocationError::UserError { message, stack, .. } => {
112            let detail = match stack {
113                Some(s) if !s.is_empty() => {
114                    format!("function:user_error: {}: {}\n{}", id.0, message, s)
115                }
116                _ => format!("function:user_error: {}: {}", id.0, message),
117            };
118            CamelError::ProcessorError(detail)
119        }
120        FunctionInvocationError::Timeout { timeout_ms, .. } => CamelError::ProcessorError(format!(
121            "function:timeout: {} timed out after {}ms",
122            id.0, timeout_ms
123        )),
124        FunctionInvocationError::NotRegistered { .. } => {
125            CamelError::ProcessorError(format!("function:not_registered: {}", id.0))
126        }
127        FunctionInvocationError::RunnerUnavailable { reason } => {
128            CamelError::ProcessorError(format!("function:runner_unavailable: {}: {}", id.0, reason))
129        }
130        FunctionInvocationError::Transport(msg) => {
131            CamelError::ProcessorError(format!("function:transport: {}: {}", id.0, msg))
132        }
133        FunctionInvocationError::InvalidPatch(msg) => {
134            CamelError::ProcessorError(format!("function:invalid_patch: {}: {}", id.0, msg))
135        }
136        _ => CamelError::ProcessorError(format!(
137            "function:error: {}: unknown invocation error",
138            id.0
139        )),
140    }
141}
142
143fn apply_patch(ex: &mut Exchange, patch: ExchangePatch) {
144    if let Some(body) = patch.body {
145        ex.input.body = match body {
146            PatchBody::Text(s) => s.into(),
147            PatchBody::Json(v) => v.into(),
148            PatchBody::Empty => camel_api::Body::Empty,
149            // Future PatchBody variants leave the body unchanged.
150            _ => ex.input.body.clone(),
151        };
152    }
153    for (k, v) in patch.headers_set {
154        ex.input.set_header(k, v);
155    }
156    for k in patch.headers_removed {
157        ex.input.remove_header(&k);
158    }
159    for (k, v) in patch.properties_set {
160        ex.properties.insert(k, v);
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use async_trait::async_trait;
168    use camel_api::function::PrepareToken;
169    use camel_api::{FunctionDiff, FunctionInvokerSync};
170    use std::sync::Mutex;
171
172    struct MockInvoker {
173        responses: Mutex<Vec<Result<ExchangePatch, FunctionInvocationError>>>,
174    }
175
176    impl MockInvoker {
177        fn new(responses: Vec<Result<ExchangePatch, FunctionInvocationError>>) -> Self {
178            Self {
179                responses: Mutex::new(responses),
180            }
181        }
182    }
183
184    impl FunctionInvokerSync for MockInvoker {
185        fn stage_pending(
186            &self,
187            _def: FunctionDefinition,
188            _route_id: Option<&str>,
189            _generation: u64,
190        ) {
191        }
192        fn discard_staging(&self, _generation: u64) {}
193        fn begin_reload(&self) -> u64 {
194            0
195        }
196        fn function_refs_for_route(&self, _route_id: &str) -> Vec<(FunctionId, Option<String>)> {
197            vec![]
198        }
199        fn staged_refs_for_route(
200            &self,
201            _route_id: &str,
202            _generation: u64,
203        ) -> Vec<(FunctionId, Option<String>)> {
204            vec![]
205        }
206        fn staged_defs_for_route(
207            &self,
208            _route_id: &str,
209            _generation: u64,
210        ) -> Vec<(FunctionDefinition, Option<String>)> {
211            vec![]
212        }
213    }
214
215    #[async_trait]
216    impl FunctionInvoker for MockInvoker {
217        async fn register(
218            &self,
219            _def: FunctionDefinition,
220            _route_id: Option<&str>,
221        ) -> Result<(), FunctionInvocationError> {
222            Ok(())
223        }
224        async fn unregister(
225            &self,
226            _id: &FunctionId,
227            _route_id: Option<&str>,
228        ) -> Result<(), FunctionInvocationError> {
229            Ok(())
230        }
231        async fn invoke(
232            &self,
233            _id: &FunctionId,
234            _exchange: &Exchange,
235        ) -> Result<ExchangePatch, FunctionInvocationError> {
236            let mut resp = self.responses.lock().unwrap();
237            resp.remove(0)
238        }
239        async fn prepare_reload(
240            &self,
241            _diff: FunctionDiff,
242            _generation: u64,
243        ) -> Result<PrepareToken, FunctionInvocationError> {
244            Ok(PrepareToken::default())
245        }
246        async fn finalize_reload(
247            &self,
248            _diff: &FunctionDiff,
249            _generation: u64,
250        ) -> Result<(), FunctionInvocationError> {
251            Ok(())
252        }
253        async fn rollback_reload(
254            &self,
255            _token: PrepareToken,
256            _generation: u64,
257        ) -> Result<(), FunctionInvocationError> {
258            Ok(())
259        }
260        async fn commit_reload(
261            &self,
262            _diff: FunctionDiff,
263            _generation: u64,
264        ) -> Result<(), FunctionInvocationError> {
265            Ok(())
266        }
267        async fn commit_staged(&self) -> Result<(), FunctionInvocationError> {
268            Ok(())
269        }
270    }
271
272    fn test_definition() -> FunctionDefinition {
273        FunctionDefinition {
274            id: FunctionId::compute("deno", "test", 5000),
275            runtime: "deno".into(),
276            source: "test".into(),
277            timeout_ms: 5000,
278            route_id: None,
279            step_index: None,
280        }
281    }
282
283    #[tokio::test]
284    async fn function_step_applies_patch_body_text() {
285        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
286            body: Some(PatchBody::Text("patched".into())),
287            ..Default::default()
288        })]));
289        let mut step = FunctionStep::new(invoker, test_definition());
290        let ex = Exchange::default();
291        let result = step.call(ex).await.unwrap();
292        assert_eq!(result.input.body.as_text(), Some("patched"));
293    }
294
295    #[tokio::test]
296    async fn function_step_applies_patch_headers() {
297        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
298            headers_set: vec![("x-key".into(), serde_json::json!("val"))],
299            headers_removed: vec!["x-old".into()],
300            ..Default::default()
301        })]));
302        let mut step = FunctionStep::new(invoker, test_definition());
303        let mut ex = Exchange::default();
304        ex.input
305            .headers
306            .insert("x-old".into(), serde_json::json!("gone"));
307        let result = step.call(ex).await.unwrap();
308        assert_eq!(
309            result.input.headers.get("x-key").unwrap().as_str(),
310            Some("val")
311        );
312        assert!(!result.input.headers.contains_key("x-old"));
313    }
314
315    #[tokio::test]
316    async fn apply_patch_header_set_replaces_different_case() {
317        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
318            headers_set: vec![("content-type".into(), serde_json::json!("application/json"))],
319            ..Default::default()
320        })]));
321        let mut step = FunctionStep::new(invoker, test_definition());
322        let mut ex = Exchange::default();
323        ex.input
324            .headers
325            .insert("Content-Type".into(), serde_json::json!("application/xml"));
326        let result = step.call(ex).await.unwrap();
327
328        let matching = result
329            .input
330            .headers
331            .keys()
332            .filter(|k| k.eq_ignore_ascii_case("content-type"))
333            .count();
334        assert_eq!(matching, 1, "expected a single content-type entry");
335        assert_eq!(
336            result.input.headers.get("content-type"),
337            Some(&serde_json::json!("application/json"))
338        );
339        assert_eq!(
340            result.input.header_ic("Content-Type"),
341            Some(&serde_json::json!("application/json"))
342        );
343    }
344
345    #[tokio::test]
346    async fn apply_patch_header_remove_is_case_insensitive() {
347        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
348            headers_removed: vec!["x-flag".into()],
349            ..Default::default()
350        })]));
351        let mut step = FunctionStep::new(invoker, test_definition());
352        let mut ex = Exchange::default();
353        ex.input
354            .headers
355            .insert("X-Flag".into(), serde_json::json!("on"));
356        let result = step.call(ex).await.unwrap();
357        assert_eq!(result.input.header_ic("x-flag"), None);
358    }
359
360    #[tokio::test]
361    async fn function_step_applies_patch_properties() {
362        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
363            properties_set: vec![("prop".into(), serde_json::json!(42))],
364            ..Default::default()
365        })]));
366        let mut step = FunctionStep::new(invoker, test_definition());
367        let ex = Exchange::default();
368        let result = step.call(ex).await.unwrap();
369        assert_eq!(result.properties.get("prop").unwrap().as_i64(), Some(42));
370    }
371
372    #[tokio::test]
373    async fn function_step_maps_timeout_error() {
374        let invoker = Arc::new(MockInvoker::new(vec![Err(
375            FunctionInvocationError::Timeout {
376                function_id: FunctionId("x".into()),
377                timeout_ms: 5000,
378            },
379        )]));
380        let mut step = FunctionStep::new(invoker, test_definition());
381        let ex = Exchange::default();
382        let err = step.call(ex).await.unwrap_err();
383        let msg = match &err {
384            CamelError::ProcessorError(m) => m,
385            _ => panic!("wrong error type"),
386        };
387        assert!(msg.contains("function:timeout:"));
388    }
389
390    #[tokio::test]
391    async fn function_step_maps_user_error() {
392        let invoker = Arc::new(MockInvoker::new(vec![Err(
393            FunctionInvocationError::UserError {
394                function_id: FunctionId("x".into()),
395                message: "boom".into(),
396                stack: None,
397            },
398        )]));
399        let mut step = FunctionStep::new(invoker, test_definition());
400        let ex = Exchange::default();
401        let err = step.call(ex).await.unwrap_err();
402        let msg = match &err {
403            CamelError::ProcessorError(m) => m,
404            _ => panic!("wrong error type"),
405        };
406        assert!(msg.contains("function:user_error:"));
407        assert!(msg.contains("boom"));
408    }
409
410    #[tokio::test]
411    async fn function_step_client_side_timeout_fires() {
412        struct SlowInvoker;
413        impl FunctionInvokerSync for SlowInvoker {
414            fn stage_pending(
415                &self,
416                _def: FunctionDefinition,
417                _route_id: Option<&str>,
418                _generation: u64,
419            ) {
420            }
421            fn discard_staging(&self, _generation: u64) {}
422            fn begin_reload(&self) -> u64 {
423                0
424            }
425            fn function_refs_for_route(
426                &self,
427                _route_id: &str,
428            ) -> Vec<(FunctionId, Option<String>)> {
429                vec![]
430            }
431            fn staged_refs_for_route(
432                &self,
433                _route_id: &str,
434                _generation: u64,
435            ) -> Vec<(FunctionId, Option<String>)> {
436                vec![]
437            }
438            fn staged_defs_for_route(
439                &self,
440                _route_id: &str,
441                _generation: u64,
442            ) -> Vec<(FunctionDefinition, Option<String>)> {
443                vec![]
444            }
445        }
446        #[async_trait]
447        impl FunctionInvoker for SlowInvoker {
448            async fn register(
449                &self,
450                _def: FunctionDefinition,
451                _route_id: Option<&str>,
452            ) -> Result<(), FunctionInvocationError> {
453                Ok(())
454            }
455            async fn unregister(
456                &self,
457                _id: &FunctionId,
458                _route_id: Option<&str>,
459            ) -> Result<(), FunctionInvocationError> {
460                Ok(())
461            }
462            async fn invoke(
463                &self,
464                _id: &FunctionId,
465                _exchange: &Exchange,
466            ) -> Result<ExchangePatch, FunctionInvocationError> {
467                tokio::time::sleep(Duration::from_secs(10)).await;
468                Ok(ExchangePatch::default())
469            }
470            async fn prepare_reload(
471                &self,
472                _diff: FunctionDiff,
473                _generation: u64,
474            ) -> Result<PrepareToken, FunctionInvocationError> {
475                Ok(PrepareToken::default())
476            }
477            async fn finalize_reload(
478                &self,
479                _diff: &FunctionDiff,
480                _generation: u64,
481            ) -> Result<(), FunctionInvocationError> {
482                Ok(())
483            }
484            async fn rollback_reload(
485                &self,
486                _token: PrepareToken,
487                _generation: u64,
488            ) -> Result<(), FunctionInvocationError> {
489                Ok(())
490            }
491            async fn commit_reload(
492                &self,
493                _diff: FunctionDiff,
494                _generation: u64,
495            ) -> Result<(), FunctionInvocationError> {
496                Ok(())
497            }
498            async fn commit_staged(&self) -> Result<(), FunctionInvocationError> {
499                Ok(())
500            }
501        }
502        let def = FunctionDefinition {
503            id: FunctionId::compute("deno", "slow", 50),
504            runtime: "deno".into(),
505            source: "slow".into(),
506            timeout_ms: 50,
507            route_id: None,
508            step_index: None,
509        };
510        let mut step = FunctionStep::new(Arc::new(SlowInvoker), def);
511        let ex = Exchange::default();
512        let err = step.call(ex).await.unwrap_err();
513        let msg = match &err {
514            CamelError::ProcessorError(m) => m,
515            _ => panic!("wrong error type"),
516        };
517        assert!(msg.contains("function:timeout:"));
518    }
519
520    #[tokio::test]
521    async fn function_step_emits_tracing_span() {
522        use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
523        use tracing_subscriber::prelude::*;
524
525        // OnceLock-gated global registry: heals/prevents callsite-interest
526        // poisoning of the shared `function` span callsite (target
527        // `camel_function`), which subscriber-less sibling function-step
528        // tests in this binary hit first (fix pattern: c3853198; bd
529        // rc-img5).
530        static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
531        if INIT.set(()).is_ok() {
532            let _ = tracing::subscriber::set_global_default(tracing_subscriber::registry());
533        }
534
535        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch::default())]));
536        let def = FunctionDefinition {
537            id: FunctionId::compute("deno", "span_test", 5000),
538            runtime: "deno".into(),
539            source: "span_test".into(),
540            timeout_ms: 5000,
541            route_id: None,
542            step_index: None,
543        };
544        let mut step = FunctionStep::new(invoker, def);
545        let ex = Exchange::default();
546
547        let span_seen = Arc::new(AtomicBool::new(false));
548        let span_seen_clone = span_seen.clone();
549
550        let layer = tracing_subscriber::fmt::layer()
551            .with_writer(std::io::sink)
552            .with_filter(tracing_subscriber::filter::filter_fn(move |meta| {
553                if meta.target() == "camel_function" && meta.name() == "function" {
554                    span_seen_clone.store(true, AtomicOrdering::SeqCst);
555                }
556                true
557            }));
558
559        let _guard = tracing_subscriber::registry().with(layer).set_default();
560        let result = step.call(ex).await;
561        assert!(result.is_ok());
562        assert!(
563            span_seen.load(AtomicOrdering::SeqCst),
564            "expected function span with target 'camel_function' and name 'function'"
565        );
566    }
567
568    #[tokio::test]
569    async fn function_step_user_error_with_stack() {
570        let invoker = Arc::new(MockInvoker::new(vec![Err(
571            FunctionInvocationError::UserError {
572                function_id: FunctionId("x".into()),
573                message: "custom error".into(),
574                stack: Some("at line 1\nat line 2".into()),
575            },
576        )]));
577        let mut step = FunctionStep::new(invoker, test_definition());
578        let ex = Exchange::default();
579        let err = step.call(ex).await.unwrap_err();
580        let msg = match &err {
581            CamelError::ProcessorError(m) => m.clone(),
582            _ => panic!("wrong error type"),
583        };
584        assert!(msg.contains("function:user_error:"));
585        assert!(msg.contains("custom error"));
586        assert!(msg.contains("at line 1"));
587    }
588
589    #[tokio::test]
590    async fn function_step_maps_not_registered_error() {
591        let invoker = Arc::new(MockInvoker::new(vec![Err(
592            FunctionInvocationError::NotRegistered {
593                function_id: FunctionId("missing-fn".into()),
594            },
595        )]));
596        let mut step = FunctionStep::new(invoker, test_definition());
597        let ex = Exchange::default();
598        let err = step.call(ex).await.unwrap_err();
599        let msg = match &err {
600            CamelError::ProcessorError(m) => m,
601            other => panic!("wrong error type: {:?}", other),
602        };
603        assert!(msg.contains("function:not_registered:"), "msg was: {}", msg);
604    }
605
606    #[tokio::test]
607    async fn function_step_maps_runner_unavailable_error() {
608        let invoker = Arc::new(MockInvoker::new(vec![Err(
609            FunctionInvocationError::RunnerUnavailable {
610                reason: "runtime crashed".into(),
611            },
612        )]));
613        let mut step = FunctionStep::new(invoker, test_definition());
614        let ex = Exchange::default();
615        let err = step.call(ex).await.unwrap_err();
616        let msg = match &err {
617            CamelError::ProcessorError(m) => m,
618            _ => panic!("wrong error type"),
619        };
620        assert!(msg.contains("function:runner_unavailable:"));
621        assert!(msg.contains("runtime crashed"));
622    }
623
624    #[tokio::test]
625    async fn function_step_maps_transport_error() {
626        let invoker = Arc::new(MockInvoker::new(vec![Err(
627            FunctionInvocationError::Transport("connection refused".into()),
628        )]));
629        let mut step = FunctionStep::new(invoker, test_definition());
630        let ex = Exchange::default();
631        let err = step.call(ex).await.unwrap_err();
632        let msg = match &err {
633            CamelError::ProcessorError(m) => m,
634            _ => panic!("wrong error type"),
635        };
636        assert!(msg.contains("function:transport:"));
637        assert!(msg.contains("connection refused"));
638    }
639
640    #[tokio::test]
641    async fn function_step_maps_invalid_patch_error() {
642        let invoker = Arc::new(MockInvoker::new(vec![Err(
643            FunctionInvocationError::InvalidPatch("missing field 'body'".into()),
644        )]));
645        let mut step = FunctionStep::new(invoker, test_definition());
646        let ex = Exchange::default();
647        let err = step.call(ex).await.unwrap_err();
648        let msg = match &err {
649            CamelError::ProcessorError(m) => m,
650            _ => panic!("wrong error type"),
651        };
652        assert!(msg.contains("function:invalid_patch:"));
653        assert!(msg.contains("missing field 'body'"));
654    }
655
656    #[tokio::test]
657    async fn function_step_applies_patch_body_json() {
658        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
659            body: Some(PatchBody::Json(serde_json::json!({"key": "value"}))),
660            ..Default::default()
661        })]));
662        let mut step = FunctionStep::new(invoker, test_definition());
663        let ex = Exchange::default();
664        let result = step.call(ex).await.unwrap();
665        match result.input.body {
666            camel_api::Body::Json(v) => assert_eq!(v.get("key").unwrap().as_str(), Some("value")),
667            other => panic!("expected Json body, got {:?}", other),
668        }
669    }
670
671    #[tokio::test]
672    async fn function_step_applies_patch_body_empty() {
673        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
674            body: Some(PatchBody::Empty),
675            ..Default::default()
676        })]));
677        let mut step = FunctionStep::new(invoker, test_definition());
678        let ex = Exchange::default();
679        let result = step.call(ex).await.unwrap();
680        assert!(matches!(result.input.body, camel_api::Body::Empty));
681    }
682
683    #[tokio::test]
684    async fn function_step_poll_ready_always_ready() {
685        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch::default())]));
686        let mut step = FunctionStep::new(invoker, test_definition());
687        let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
688        let poll = step.poll_ready(&mut cx);
689        assert!(matches!(poll, std::task::Poll::Ready(Ok(()))));
690    }
691
692    #[tokio::test]
693    async fn function_step_user_error_with_empty_stack() {
694        let invoker = Arc::new(MockInvoker::new(vec![Err(
695            FunctionInvocationError::UserError {
696                function_id: FunctionId("x".into()),
697                message: "no stack".into(),
698                stack: Some("".into()),
699            },
700        )]));
701        let mut step = FunctionStep::new(invoker, test_definition());
702        let ex = Exchange::default();
703        let err = step.call(ex).await.unwrap_err();
704        let msg = match &err {
705            CamelError::ProcessorError(m) => m,
706            _ => panic!("wrong error type"),
707        };
708        assert!(msg.contains("function:user_error:"));
709        assert!(msg.contains("no stack"));
710        assert!(!msg.contains("\n"));
711    }
712
713    #[tokio::test]
714    async fn function_step_preserves_exchange_properties_not_in_patch() {
715        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
716            body: Some(PatchBody::Text("new body".into())),
717            ..Default::default()
718        })]));
719        let mut step = FunctionStep::new(invoker, test_definition());
720        let mut ex = Exchange::default();
721        ex.properties
722            .insert("existing".into(), serde_json::json!("keep"));
723        let result = step.call(ex).await.unwrap();
724        assert_eq!(
725            result.properties.get("existing").unwrap().as_str(),
726            Some("keep")
727        );
728        assert_eq!(result.input.body.as_text(), Some("new body"));
729    }
730
731    #[tokio::test]
732    async fn function_step_removes_header_not_in_set() {
733        let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
734            headers_removed: vec!["to-remove".into()],
735            ..Default::default()
736        })]));
737        let mut step = FunctionStep::new(invoker, test_definition());
738        let mut ex = Exchange::default();
739        ex.input
740            .headers
741            .insert("to-remove".into(), serde_json::json!("old"));
742        ex.input
743            .headers
744            .insert("to-keep".into(), serde_json::json!("stay"));
745        let result = step.call(ex).await.unwrap();
746        assert!(!result.input.headers.contains_key("to-remove"));
747        assert!(result.input.headers.contains_key("to-keep"));
748    }
749}