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, PROPERTY_HTTP_CONTENT_TYPE_INHERITED, 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 _ => ex.input.body.clone(),
151 };
152 }
153 let set_touches_ct = patch
154 .headers_set
155 .iter()
156 .any(|(k, _)| k.eq_ignore_ascii_case("content-type"));
157 let removed_touches_ct = patch
158 .headers_removed
159 .iter()
160 .any(|k| k.eq_ignore_ascii_case("content-type"));
161 for (k, v) in patch.headers_set {
162 ex.input.set_header(k, v);
163 }
164 for k in patch.headers_removed {
165 ex.input.remove_header(&k);
166 }
167 if set_touches_ct || removed_touches_ct {
168 ex.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
169 }
170 for (k, v) in patch.properties_set {
171 ex.properties.insert(k, v);
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178 use async_trait::async_trait;
179 use camel_api::function::PrepareToken;
180 use camel_api::{FunctionDiff, FunctionInvokerSync};
181 use std::sync::Mutex;
182
183 struct MockInvoker {
184 responses: Mutex<Vec<Result<ExchangePatch, FunctionInvocationError>>>,
185 }
186
187 impl MockInvoker {
188 fn new(responses: Vec<Result<ExchangePatch, FunctionInvocationError>>) -> Self {
189 Self {
190 responses: Mutex::new(responses),
191 }
192 }
193 }
194
195 impl FunctionInvokerSync for MockInvoker {
196 fn stage_pending(
197 &self,
198 _def: FunctionDefinition,
199 _route_id: Option<&str>,
200 _generation: u64,
201 ) {
202 }
203 fn discard_staging(&self, _generation: u64) {}
204 fn begin_reload(&self) -> u64 {
205 0
206 }
207 fn function_refs_for_route(&self, _route_id: &str) -> Vec<(FunctionId, Option<String>)> {
208 vec![]
209 }
210 fn staged_refs_for_route(
211 &self,
212 _route_id: &str,
213 _generation: u64,
214 ) -> Vec<(FunctionId, Option<String>)> {
215 vec![]
216 }
217 fn staged_defs_for_route(
218 &self,
219 _route_id: &str,
220 _generation: u64,
221 ) -> Vec<(FunctionDefinition, Option<String>)> {
222 vec![]
223 }
224 }
225
226 #[async_trait]
227 impl FunctionInvoker for MockInvoker {
228 async fn register(
229 &self,
230 _def: FunctionDefinition,
231 _route_id: Option<&str>,
232 ) -> Result<(), FunctionInvocationError> {
233 Ok(())
234 }
235 async fn unregister(
236 &self,
237 _id: &FunctionId,
238 _route_id: Option<&str>,
239 ) -> Result<(), FunctionInvocationError> {
240 Ok(())
241 }
242 async fn invoke(
243 &self,
244 _id: &FunctionId,
245 _exchange: &Exchange,
246 ) -> Result<ExchangePatch, FunctionInvocationError> {
247 let mut resp = self.responses.lock().unwrap();
248 resp.remove(0)
249 }
250 async fn prepare_reload(
251 &self,
252 _diff: FunctionDiff,
253 _generation: u64,
254 ) -> Result<PrepareToken, FunctionInvocationError> {
255 Ok(PrepareToken::default())
256 }
257 async fn finalize_reload(
258 &self,
259 _diff: &FunctionDiff,
260 _generation: u64,
261 ) -> Result<(), FunctionInvocationError> {
262 Ok(())
263 }
264 async fn rollback_reload(
265 &self,
266 _token: PrepareToken,
267 _generation: u64,
268 ) -> Result<(), FunctionInvocationError> {
269 Ok(())
270 }
271 async fn commit_reload(
272 &self,
273 _diff: FunctionDiff,
274 _generation: u64,
275 ) -> Result<(), FunctionInvocationError> {
276 Ok(())
277 }
278 async fn commit_staged(&self) -> Result<(), FunctionInvocationError> {
279 Ok(())
280 }
281 }
282
283 fn test_definition() -> FunctionDefinition {
284 FunctionDefinition {
285 id: FunctionId::compute("deno", "test", 5000),
286 runtime: "deno".into(),
287 source: "test".into(),
288 timeout_ms: 5000,
289 route_id: None,
290 step_index: None,
291 }
292 }
293
294 #[tokio::test]
295 async fn function_step_applies_patch_body_text() {
296 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
297 body: Some(PatchBody::Text("patched".into())),
298 ..Default::default()
299 })]));
300 let mut step = FunctionStep::new(invoker, test_definition());
301 let ex = Exchange::default();
302 let result = step.call(ex).await.unwrap();
303 assert_eq!(result.input.body.as_text(), Some("patched"));
304 }
305
306 #[tokio::test]
307 async fn function_step_applies_patch_headers() {
308 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
309 headers_set: vec![("x-key".into(), serde_json::json!("val"))],
310 headers_removed: vec!["x-old".into()],
311 ..Default::default()
312 })]));
313 let mut step = FunctionStep::new(invoker, test_definition());
314 let mut ex = Exchange::default();
315 ex.input
316 .headers
317 .insert("x-old".into(), serde_json::json!("gone"));
318 let result = step.call(ex).await.unwrap();
319 assert_eq!(
320 result.input.headers.get("x-key").unwrap().as_str(),
321 Some("val")
322 );
323 assert!(!result.input.headers.contains_key("x-old"));
324 }
325
326 #[tokio::test]
327 async fn apply_patch_header_set_replaces_different_case() {
328 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
329 headers_set: vec![("content-type".into(), serde_json::json!("application/json"))],
330 ..Default::default()
331 })]));
332 let mut step = FunctionStep::new(invoker, test_definition());
333 let mut ex = Exchange::default();
334 ex.input
335 .headers
336 .insert("Content-Type".into(), serde_json::json!("application/xml"));
337 let result = step.call(ex).await.unwrap();
338
339 let matching = result
340 .input
341 .headers
342 .keys()
343 .filter(|k| k.eq_ignore_ascii_case("content-type"))
344 .count();
345 assert_eq!(matching, 1, "expected a single content-type entry");
346 assert_eq!(
347 result.input.headers.get("content-type"),
348 Some(&serde_json::json!("application/json"))
349 );
350 assert_eq!(
351 result.input.header_ic("Content-Type"),
352 Some(&serde_json::json!("application/json"))
353 );
354 }
355
356 #[tokio::test]
357 async fn apply_patch_header_remove_is_case_insensitive() {
358 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
359 headers_removed: vec!["x-flag".into()],
360 ..Default::default()
361 })]));
362 let mut step = FunctionStep::new(invoker, test_definition());
363 let mut ex = Exchange::default();
364 ex.input
365 .headers
366 .insert("X-Flag".into(), serde_json::json!("on"));
367 let result = step.call(ex).await.unwrap();
368 assert_eq!(result.input.header_ic("x-flag"), None);
369 }
370
371 #[tokio::test]
372 async fn function_step_applies_patch_properties() {
373 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
374 properties_set: vec![("prop".into(), serde_json::json!(42))],
375 ..Default::default()
376 })]));
377 let mut step = FunctionStep::new(invoker, test_definition());
378 let ex = Exchange::default();
379 let result = step.call(ex).await.unwrap();
380 assert_eq!(result.properties.get("prop").unwrap().as_i64(), Some(42));
381 }
382
383 #[tokio::test]
384 async fn function_step_maps_timeout_error() {
385 let invoker = Arc::new(MockInvoker::new(vec![Err(
386 FunctionInvocationError::Timeout {
387 function_id: FunctionId("x".into()),
388 timeout_ms: 5000,
389 },
390 )]));
391 let mut step = FunctionStep::new(invoker, test_definition());
392 let ex = Exchange::default();
393 let err = step.call(ex).await.unwrap_err();
394 let msg = match &err {
395 CamelError::ProcessorError(m) => m,
396 _ => panic!("wrong error type"),
397 };
398 assert!(msg.contains("function:timeout:"));
399 }
400
401 #[tokio::test]
402 async fn function_step_maps_user_error() {
403 let invoker = Arc::new(MockInvoker::new(vec![Err(
404 FunctionInvocationError::UserError {
405 function_id: FunctionId("x".into()),
406 message: "boom".into(),
407 stack: None,
408 },
409 )]));
410 let mut step = FunctionStep::new(invoker, test_definition());
411 let ex = Exchange::default();
412 let err = step.call(ex).await.unwrap_err();
413 let msg = match &err {
414 CamelError::ProcessorError(m) => m,
415 _ => panic!("wrong error type"),
416 };
417 assert!(msg.contains("function:user_error:"));
418 assert!(msg.contains("boom"));
419 }
420
421 #[tokio::test]
422 async fn function_step_client_side_timeout_fires() {
423 struct SlowInvoker;
424 impl FunctionInvokerSync for SlowInvoker {
425 fn stage_pending(
426 &self,
427 _def: FunctionDefinition,
428 _route_id: Option<&str>,
429 _generation: u64,
430 ) {
431 }
432 fn discard_staging(&self, _generation: u64) {}
433 fn begin_reload(&self) -> u64 {
434 0
435 }
436 fn function_refs_for_route(
437 &self,
438 _route_id: &str,
439 ) -> Vec<(FunctionId, Option<String>)> {
440 vec![]
441 }
442 fn staged_refs_for_route(
443 &self,
444 _route_id: &str,
445 _generation: u64,
446 ) -> Vec<(FunctionId, Option<String>)> {
447 vec![]
448 }
449 fn staged_defs_for_route(
450 &self,
451 _route_id: &str,
452 _generation: u64,
453 ) -> Vec<(FunctionDefinition, Option<String>)> {
454 vec![]
455 }
456 }
457 #[async_trait]
458 impl FunctionInvoker for SlowInvoker {
459 async fn register(
460 &self,
461 _def: FunctionDefinition,
462 _route_id: Option<&str>,
463 ) -> Result<(), FunctionInvocationError> {
464 Ok(())
465 }
466 async fn unregister(
467 &self,
468 _id: &FunctionId,
469 _route_id: Option<&str>,
470 ) -> Result<(), FunctionInvocationError> {
471 Ok(())
472 }
473 async fn invoke(
474 &self,
475 _id: &FunctionId,
476 _exchange: &Exchange,
477 ) -> Result<ExchangePatch, FunctionInvocationError> {
478 tokio::time::sleep(Duration::from_secs(10)).await;
479 Ok(ExchangePatch::default())
480 }
481 async fn prepare_reload(
482 &self,
483 _diff: FunctionDiff,
484 _generation: u64,
485 ) -> Result<PrepareToken, FunctionInvocationError> {
486 Ok(PrepareToken::default())
487 }
488 async fn finalize_reload(
489 &self,
490 _diff: &FunctionDiff,
491 _generation: u64,
492 ) -> Result<(), FunctionInvocationError> {
493 Ok(())
494 }
495 async fn rollback_reload(
496 &self,
497 _token: PrepareToken,
498 _generation: u64,
499 ) -> Result<(), FunctionInvocationError> {
500 Ok(())
501 }
502 async fn commit_reload(
503 &self,
504 _diff: FunctionDiff,
505 _generation: u64,
506 ) -> Result<(), FunctionInvocationError> {
507 Ok(())
508 }
509 async fn commit_staged(&self) -> Result<(), FunctionInvocationError> {
510 Ok(())
511 }
512 }
513 let def = FunctionDefinition {
514 id: FunctionId::compute("deno", "slow", 50),
515 runtime: "deno".into(),
516 source: "slow".into(),
517 timeout_ms: 50,
518 route_id: None,
519 step_index: None,
520 };
521 let mut step = FunctionStep::new(Arc::new(SlowInvoker), def);
522 let ex = Exchange::default();
523 let err = step.call(ex).await.unwrap_err();
524 let msg = match &err {
525 CamelError::ProcessorError(m) => m,
526 _ => panic!("wrong error type"),
527 };
528 assert!(msg.contains("function:timeout:"));
529 }
530
531 #[tokio::test]
532 async fn function_step_emits_tracing_span() {
533 use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
534 use tracing_subscriber::prelude::*;
535
536 static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
542 if INIT.set(()).is_ok() {
543 let _ = tracing::subscriber::set_global_default(tracing_subscriber::registry());
544 }
545
546 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch::default())]));
547 let def = FunctionDefinition {
548 id: FunctionId::compute("deno", "span_test", 5000),
549 runtime: "deno".into(),
550 source: "span_test".into(),
551 timeout_ms: 5000,
552 route_id: None,
553 step_index: None,
554 };
555 let mut step = FunctionStep::new(invoker, def);
556 let ex = Exchange::default();
557
558 let span_seen = Arc::new(AtomicBool::new(false));
559 let span_seen_clone = span_seen.clone();
560
561 let layer = tracing_subscriber::fmt::layer()
562 .with_writer(std::io::sink)
563 .with_filter(tracing_subscriber::filter::filter_fn(move |meta| {
564 if meta.target() == "camel_function" && meta.name() == "function" {
565 span_seen_clone.store(true, AtomicOrdering::SeqCst);
566 }
567 true
568 }));
569
570 let _guard = tracing_subscriber::registry().with(layer).set_default();
571 let result = step.call(ex).await;
572 assert!(result.is_ok());
573 assert!(
574 span_seen.load(AtomicOrdering::SeqCst),
575 "expected function span with target 'camel_function' and name 'function'"
576 );
577 }
578
579 #[tokio::test]
580 async fn function_step_user_error_with_stack() {
581 let invoker = Arc::new(MockInvoker::new(vec![Err(
582 FunctionInvocationError::UserError {
583 function_id: FunctionId("x".into()),
584 message: "custom error".into(),
585 stack: Some("at line 1\nat line 2".into()),
586 },
587 )]));
588 let mut step = FunctionStep::new(invoker, test_definition());
589 let ex = Exchange::default();
590 let err = step.call(ex).await.unwrap_err();
591 let msg = match &err {
592 CamelError::ProcessorError(m) => m.clone(),
593 _ => panic!("wrong error type"),
594 };
595 assert!(msg.contains("function:user_error:"));
596 assert!(msg.contains("custom error"));
597 assert!(msg.contains("at line 1"));
598 }
599
600 #[tokio::test]
601 async fn function_step_maps_not_registered_error() {
602 let invoker = Arc::new(MockInvoker::new(vec![Err(
603 FunctionInvocationError::NotRegistered {
604 function_id: FunctionId("missing-fn".into()),
605 },
606 )]));
607 let mut step = FunctionStep::new(invoker, test_definition());
608 let ex = Exchange::default();
609 let err = step.call(ex).await.unwrap_err();
610 let msg = match &err {
611 CamelError::ProcessorError(m) => m,
612 other => panic!("wrong error type: {:?}", other),
613 };
614 assert!(msg.contains("function:not_registered:"), "msg was: {}", msg);
615 }
616
617 #[tokio::test]
618 async fn function_step_maps_runner_unavailable_error() {
619 let invoker = Arc::new(MockInvoker::new(vec![Err(
620 FunctionInvocationError::RunnerUnavailable {
621 reason: "runtime crashed".into(),
622 },
623 )]));
624 let mut step = FunctionStep::new(invoker, test_definition());
625 let ex = Exchange::default();
626 let err = step.call(ex).await.unwrap_err();
627 let msg = match &err {
628 CamelError::ProcessorError(m) => m,
629 _ => panic!("wrong error type"),
630 };
631 assert!(msg.contains("function:runner_unavailable:"));
632 assert!(msg.contains("runtime crashed"));
633 }
634
635 #[tokio::test]
636 async fn function_step_maps_transport_error() {
637 let invoker = Arc::new(MockInvoker::new(vec![Err(
638 FunctionInvocationError::Transport("connection refused".into()),
639 )]));
640 let mut step = FunctionStep::new(invoker, test_definition());
641 let ex = Exchange::default();
642 let err = step.call(ex).await.unwrap_err();
643 let msg = match &err {
644 CamelError::ProcessorError(m) => m,
645 _ => panic!("wrong error type"),
646 };
647 assert!(msg.contains("function:transport:"));
648 assert!(msg.contains("connection refused"));
649 }
650
651 #[tokio::test]
652 async fn function_step_maps_invalid_patch_error() {
653 let invoker = Arc::new(MockInvoker::new(vec![Err(
654 FunctionInvocationError::InvalidPatch("missing field 'body'".into()),
655 )]));
656 let mut step = FunctionStep::new(invoker, test_definition());
657 let ex = Exchange::default();
658 let err = step.call(ex).await.unwrap_err();
659 let msg = match &err {
660 CamelError::ProcessorError(m) => m,
661 _ => panic!("wrong error type"),
662 };
663 assert!(msg.contains("function:invalid_patch:"));
664 assert!(msg.contains("missing field 'body'"));
665 }
666
667 #[tokio::test]
668 async fn function_step_applies_patch_body_json() {
669 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
670 body: Some(PatchBody::Json(serde_json::json!({"key": "value"}))),
671 ..Default::default()
672 })]));
673 let mut step = FunctionStep::new(invoker, test_definition());
674 let ex = Exchange::default();
675 let result = step.call(ex).await.unwrap();
676 match result.input.body {
677 camel_api::Body::Json(v) => assert_eq!(v.get("key").unwrap().as_str(), Some("value")),
678 other => panic!("expected Json body, got {:?}", other),
679 }
680 }
681
682 #[tokio::test]
683 async fn function_step_applies_patch_body_empty() {
684 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
685 body: Some(PatchBody::Empty),
686 ..Default::default()
687 })]));
688 let mut step = FunctionStep::new(invoker, test_definition());
689 let ex = Exchange::default();
690 let result = step.call(ex).await.unwrap();
691 assert!(matches!(result.input.body, camel_api::Body::Empty));
692 }
693
694 #[tokio::test]
695 async fn function_step_poll_ready_always_ready() {
696 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch::default())]));
697 let mut step = FunctionStep::new(invoker, test_definition());
698 let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
699 let poll = step.poll_ready(&mut cx);
700 assert!(matches!(poll, std::task::Poll::Ready(Ok(()))));
701 }
702
703 #[tokio::test]
704 async fn function_step_user_error_with_empty_stack() {
705 let invoker = Arc::new(MockInvoker::new(vec![Err(
706 FunctionInvocationError::UserError {
707 function_id: FunctionId("x".into()),
708 message: "no stack".into(),
709 stack: Some("".into()),
710 },
711 )]));
712 let mut step = FunctionStep::new(invoker, test_definition());
713 let ex = Exchange::default();
714 let err = step.call(ex).await.unwrap_err();
715 let msg = match &err {
716 CamelError::ProcessorError(m) => m,
717 _ => panic!("wrong error type"),
718 };
719 assert!(msg.contains("function:user_error:"));
720 assert!(msg.contains("no stack"));
721 assert!(!msg.contains("\n"));
722 }
723
724 #[tokio::test]
725 async fn function_step_preserves_exchange_properties_not_in_patch() {
726 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
727 body: Some(PatchBody::Text("new body".into())),
728 ..Default::default()
729 })]));
730 let mut step = FunctionStep::new(invoker, test_definition());
731 let mut ex = Exchange::default();
732 ex.properties
733 .insert("existing".into(), serde_json::json!("keep"));
734 let result = step.call(ex).await.unwrap();
735 assert_eq!(
736 result.properties.get("existing").unwrap().as_str(),
737 Some("keep")
738 );
739 assert_eq!(result.input.body.as_text(), Some("new body"));
740 }
741
742 #[tokio::test]
743 async fn function_patch_clears_marker_on_ct_set() {
744 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
745 headers_set: vec![("Content-Type".into(), serde_json::json!("application/json"))],
746 ..Default::default()
747 })]));
748 let mut step = FunctionStep::new(invoker, test_definition());
749 let mut ex = Exchange::default();
750 ex.set_property(
751 PROPERTY_HTTP_CONTENT_TYPE_INHERITED,
752 serde_json::json!(true),
753 );
754 let result = step.call(ex).await.unwrap();
755 assert_eq!(
756 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
757 None,
758 "a patch that sets Content-Type must clear the inherited marker"
759 );
760 }
761
762 #[tokio::test]
763 async fn function_patch_clears_marker_on_ct_remove() {
764 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
765 headers_removed: vec!["content-type".into()],
766 ..Default::default()
767 })]));
768 let mut step = FunctionStep::new(invoker, test_definition());
769 let mut ex = Exchange::default();
770 ex.set_property(
771 PROPERTY_HTTP_CONTENT_TYPE_INHERITED,
772 serde_json::json!(true),
773 );
774 let result = step.call(ex).await.unwrap();
775 assert_eq!(
776 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
777 None,
778 "a patch that removes Content-Type must clear the inherited marker"
779 );
780 }
781
782 #[tokio::test]
783 async fn function_patch_keeps_marker_on_other_headers() {
784 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
785 headers_set: vec![("X-Flag".into(), serde_json::json!("on"))],
786 ..Default::default()
787 })]));
788 let mut step = FunctionStep::new(invoker, test_definition());
789 let mut ex = Exchange::default();
790 ex.set_property(
791 PROPERTY_HTTP_CONTENT_TYPE_INHERITED,
792 serde_json::json!(true),
793 );
794 let result = step.call(ex).await.unwrap();
795 assert_eq!(
796 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
797 Some(&serde_json::json!(true)),
798 "a patch that does not touch Content-Type must keep the inherited marker"
799 );
800 }
801
802 #[tokio::test]
803 async fn function_step_removes_header_not_in_set() {
804 let invoker = Arc::new(MockInvoker::new(vec![Ok(ExchangePatch {
805 headers_removed: vec!["to-remove".into()],
806 ..Default::default()
807 })]));
808 let mut step = FunctionStep::new(invoker, test_definition());
809 let mut ex = Exchange::default();
810 ex.input
811 .headers
812 .insert("to-remove".into(), serde_json::json!("old"));
813 ex.input
814 .headers
815 .insert("to-keep".into(), serde_json::json!("stay"));
816 let result = step.call(ex).await.unwrap();
817 assert!(!result.input.headers.contains_key("to-remove"));
818 assert!(result.input.headers.contains_key("to-keep"));
819 }
820}