1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use tower::{Layer, Service, ServiceExt};
6
7use camel_api::error_handler::{
8 BoundaryKind, ExceptionDisposition, ExceptionPolicy, HEADER_REDELIVERED,
9 HEADER_REDELIVERY_COUNTER, HEADER_REDELIVERY_MAX_COUNTER, PolicyId, RetryOutcome,
10 StepDisposition,
11};
12use camel_api::{
13 BoxProcessor, CamelError, Exchange, ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
14 OriginalContentTypeInherited, PROPERTY_HTTP_CONTENT_TYPE_INHERITED, PipelineOutcome,
15 SyncBoxProcessor, Value,
16};
17
18fn is_business(error: &CamelError) -> bool {
21 matches!(error, CamelError::Business { .. })
22}
23
24fn log_business_handled(error: &CamelError) {
31 if let CamelError::Business { code, kind, .. } = error {
32 tracing::info!(code = %code, kind = %kind, "business error handled");
33 }
34}
35
36fn log_business_propagated(error: &CamelError) {
39 if let CamelError::Business { code, kind, .. } = error {
40 tracing::warn!(
41 code = %code,
42 kind = %kind,
43 "business error propagated with no handler or dead-letter channel"
44 );
45 }
46}
47
48fn log_business_disposition(
64 error: &CamelError,
65 disposition: ExceptionDisposition,
66 has_producer: bool,
67 seam_business: bool,
68 reply_seam: bool,
69) {
70 if has_producer {
71 return;
72 }
73 match disposition {
74 ExceptionDisposition::Handled | ExceptionDisposition::Continued => {
75 log_business_handled(error);
76 }
77 ExceptionDisposition::Propagate if seam_business || reply_seam => {
78 if let CamelError::Business { code, kind, .. } = error {
79 tracing::debug!(
80 code = %code,
81 kind = %kind,
82 "business error propagating to the HTTP reply seam (finalizer owns the record)"
83 );
84 }
85 }
86 _ => log_business_propagated(error),
87 }
88}
89
90async fn execute_on_steps(
91 original: Exchange,
92 original_err: CamelError,
93 on_steps: &SyncBoxProcessor,
94 disposition: ExceptionDisposition,
95 handler: Option<BoxProcessor>,
96) -> Result<Exchange, CamelError> {
97 let snapshot = original.branch_clone();
98 let mut ex = original;
99 ex.set_error(original_err.clone());
100 let mut pipeline = on_steps.clone_inner();
101 let step_result = async {
102 let svc = pipeline.ready().await?;
103 svc.call(ex).await
104 }
105 .await;
106
107 match step_result {
108 Ok(mut ex) => {
109 if disposition == ExceptionDisposition::Handled {
110 log_business_handled(&original_err);
115 ex.handle_error();
116 Ok(ex)
117 } else {
118 Err(original_err)
121 }
122 }
123 Err(_) => {
124 tracing::warn!(error = %original_err, "on_steps pipeline failed, falling back to handler/DLC");
126 let mut ex = snapshot;
127 ex.set_error(original_err.clone());
128 forward_or_propagate(ex, handler, original_err).await
129 }
130 }
131}
132
133pub async fn invoke_processor(
138 svc: &mut BoxProcessor,
139 ex: Exchange,
140) -> Result<Exchange, CamelError> {
141 match svc.ready().await {
142 Ok(ready) => ready.call(ex).await,
143 Err(err) => Err(err),
144 }
145}
146
147#[async_trait::async_trait]
152pub trait RouteErrorHandler: Send + Sync {
153 fn match_policy(&self, err: &CamelError) -> Option<PolicyId>;
155
156 async fn retry_step(
158 &self,
159 policy: Option<PolicyId>,
160 step: &mut dyn camel_api::error_handler::RetryableStep,
161 original: Exchange,
162 error: CamelError,
163 ) -> RetryOutcome;
164
165 async fn handle_step(
167 &self,
168 policy: Option<PolicyId>,
169 exchange: Exchange,
170 error: CamelError,
171 ) -> Result<StepDisposition, CamelError>;
172
173 async fn handle_boundary(
175 &self,
176 kind: BoundaryKind,
177 exchange: Exchange,
178 error: CamelError,
179 ) -> Result<Exchange, CamelError>;
180}
181
182pub struct DefaultRouteErrorHandler {
188 pub(crate) dlc_producer: Option<SyncBoxProcessor>,
189 pub(crate) policies: Vec<(ExceptionPolicy, Option<SyncBoxProcessor>)>,
190 pub use_original_message: bool,
194 business_seam_bypass: bool,
202 reply_seam: bool,
211 synthetic_policy: Option<usize>,
215}
216
217impl DefaultRouteErrorHandler {
218 pub fn new(
219 dlc_producer: Option<BoxProcessor>,
220 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
221 ) -> Self {
222 Self {
223 dlc_producer: dlc_producer.map(SyncBoxProcessor::new),
224 policies: policies
225 .into_iter()
226 .map(|(p, prod)| (p, prod.map(SyncBoxProcessor::new)))
227 .collect(),
228 use_original_message: false,
229 business_seam_bypass: false,
230 reply_seam: false,
231 synthetic_policy: None,
232 }
233 }
234
235 pub fn with_use_original_message(mut self, enabled: bool) -> Self {
237 self.use_original_message = enabled;
238 self
239 }
240
241 pub fn with_business_seam_bypass(
247 mut self,
248 enabled: bool,
249 synthetic_policy: Option<usize>,
250 ) -> Self {
251 self.business_seam_bypass = enabled;
252 self.synthetic_policy = synthetic_policy;
253 self
254 }
255
256 pub fn with_reply_seam(mut self, enabled: bool) -> Self {
261 self.reply_seam = enabled;
262 self
263 }
264
265 fn restore_original_message_if_enabled(&self, exchange: &mut Exchange) {
269 if self.use_original_message
270 && let Some(orig) =
271 exchange.get_extension::<camel_api::Message>(camel_api::ORIGINAL_MESSAGE_EXTENSION)
272 {
273 exchange.input = orig.clone();
274
275 let inherited = exchange
280 .get_extension::<OriginalContentTypeInherited>(
281 ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
282 )
283 .is_some_and(|snapshot| snapshot.0);
284 if inherited {
285 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
286 } else {
287 exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
288 }
289 }
290 }
291
292 fn resolve_producer(
301 &self,
302 policy: Option<PolicyId>,
303 seam_business: bool,
304 ) -> (ExceptionDisposition, Option<BoxProcessor>) {
305 let dlc = if seam_business {
306 None
307 } else {
308 self.dlc_producer.as_ref().map(|p| p.clone_inner())
309 };
310 match policy {
311 Some(PolicyId(idx)) => match self.policies.get(idx) {
312 Some((p, prod)) => (
313 p.disposition,
314 prod.as_ref().map(|p| p.clone_inner()).or(dlc),
315 ),
316 None => (ExceptionDisposition::Propagate, dlc),
317 },
318 None => (ExceptionDisposition::Propagate, dlc),
319 }
320 }
321}
322
323#[async_trait::async_trait]
324impl RouteErrorHandler for DefaultRouteErrorHandler {
325 fn match_policy(&self, err: &CamelError) -> Option<PolicyId> {
326 for (idx, (p, _)) in self.policies.iter().enumerate() {
327 if !(p.matches)(err) {
328 continue;
329 }
330 if self.business_seam_bypass && is_business(err) && self.synthetic_policy == Some(idx) {
336 continue;
337 }
338 return Some(PolicyId(idx));
339 }
340 None
341 }
342
343 async fn retry_step(
344 &self,
345 policy: Option<PolicyId>,
346 step: &mut dyn camel_api::error_handler::RetryableStep,
347 original: Exchange,
348 error: CamelError,
349 ) -> RetryOutcome {
350 if is_business(&error) {
355 return RetryOutcome::Exhausted {
356 exchange: original,
357 error,
358 policy,
359 };
360 }
361 let Some(PolicyId(idx)) = policy else {
362 return RetryOutcome::Exhausted {
363 exchange: original,
364 error,
365 policy: None,
366 };
367 };
368 let Some((policy_def, _)) = self.policies.get(idx) else {
369 return RetryOutcome::Exhausted {
370 exchange: original,
371 error,
372 policy,
373 };
374 };
375 let Some(ref backoff) = policy_def.retry else {
376 return RetryOutcome::Exhausted {
377 exchange: original,
378 error,
379 policy,
380 };
381 };
382
383 for attempt in 0..backoff.max_attempts {
384 let delay = backoff.delay_for(attempt);
385 tokio::time::sleep(delay).await;
386
387 let mut ex = original.branch_clone();
388 ex.input.set_header(HEADER_REDELIVERED, Value::Bool(true));
389 ex.input.set_header(
390 HEADER_REDELIVERY_COUNTER,
391 Value::Number((attempt + 1).into()),
392 );
393 ex.input.set_header(
394 HEADER_REDELIVERY_MAX_COUNTER,
395 Value::Number(backoff.max_attempts.into()),
396 );
397
398 match step.invoke(ex).await {
399 PipelineOutcome::Completed(exchange) => {
400 return RetryOutcome::Recovered(exchange);
401 }
402 PipelineOutcome::Stopped(stopped_ex) => {
403 return RetryOutcome::Stopped(stopped_ex);
404 }
405 PipelineOutcome::Failed(retry_err) => {
406 if is_business(&retry_err) {
412 return RetryOutcome::Exhausted {
413 exchange: original,
414 error: retry_err,
415 policy,
416 };
417 }
418 if attempt + 1 == backoff.max_attempts {
419 let mut final_ex = original;
420 final_ex
421 .input
422 .set_header(HEADER_REDELIVERED, Value::Bool(true));
423 final_ex.input.set_header(
424 HEADER_REDELIVERY_COUNTER,
425 Value::Number(backoff.max_attempts.into()),
426 );
427 final_ex.input.set_header(
428 HEADER_REDELIVERY_MAX_COUNTER,
429 Value::Number(backoff.max_attempts.into()),
430 );
431 return RetryOutcome::Exhausted {
432 exchange: final_ex,
433 error: retry_err,
434 policy,
435 };
436 }
437 }
438 }
439 }
440
441 RetryOutcome::Exhausted {
442 exchange: original,
443 error,
444 policy,
445 }
446 }
447
448 async fn handle_step(
449 &self,
450 policy: Option<PolicyId>,
451 mut exchange: Exchange,
452 error: CamelError,
453 ) -> Result<StepDisposition, CamelError> {
454 let seam_business = self.business_seam_bypass && is_business(&error);
455 let (disposition, producer) = self.resolve_producer(policy, seam_business);
456 log_business_disposition(
457 &error,
458 disposition,
459 producer.is_some(),
460 seam_business,
461 self.reply_seam,
462 );
463
464 if policy.is_none() && producer.is_none() {
470 tracing::debug!(
471 kind = %error.variant_name(),
472 "no on_exceptions policy matched and no dead-letter channel configured; propagating error"
473 );
474 }
475
476 if !matches!(disposition, ExceptionDisposition::Propagate)
481 && let Some(PolicyId(idx)) = policy
482 && let Some((p, _)) = self.policies.get(idx)
483 && let Some(ref steps) = p.on_steps
484 {
485 let snapshot = exchange.branch_clone();
486 exchange.set_error(error.clone());
487 let mut step_pipeline = steps.clone_inner();
488 let step_result = async {
489 let svc = step_pipeline.ready().await?;
490 svc.call(exchange).await
491 }
492 .await;
493 match step_result {
494 Ok(mut ex) => match disposition {
495 ExceptionDisposition::Handled => {
496 ex.handle_error();
497 if producer.is_some() {
501 log_business_handled(&error);
502 }
503 return Ok(StepDisposition::Handled(ex));
504 }
505 ExceptionDisposition::Continued => {
506 ex.clear_error();
507 if producer.is_some() {
508 log_business_handled(&error);
509 }
510 return Ok(StepDisposition::Continued(ex));
511 }
512 _ => {
515 exchange = snapshot;
516 }
517 },
518 Err(_) => {
519 exchange = snapshot;
520 }
521 }
522 }
523
524 self.restore_original_message_if_enabled(&mut exchange);
527 exchange.set_error(error.clone());
528 match send_to_handler(exchange, producer).await {
529 Ok(handler_ex) => match disposition {
530 ExceptionDisposition::Handled => {
531 let mut ex = handler_ex;
532 ex.clear_error();
533 Ok(StepDisposition::Handled(ex))
534 }
535 ExceptionDisposition::Continued => {
536 let mut ex = handler_ex;
537 ex.clear_error();
538 Ok(StepDisposition::Continued(ex))
539 }
540 _ => Ok(StepDisposition::Propagate(error)),
542 },
543 Err(_delegate) => Ok(StepDisposition::Propagate(error)),
547 }
548 }
549
550 async fn handle_boundary(
551 &self,
552 boundary_kind: BoundaryKind,
553 mut exchange: Exchange,
554 error: CamelError,
555 ) -> Result<Exchange, CamelError> {
556 let policy = self.match_policy(&error);
562 let seam_business = self.business_seam_bypass && is_business(&error);
563 let (disposition, producer) = self.resolve_producer(policy, seam_business);
564 log_business_disposition(
565 &error,
566 disposition,
567 producer.is_some(),
568 seam_business,
569 self.reply_seam,
570 );
571
572 if policy.is_none() && producer.is_none() {
579 tracing::debug!(
580 boundary = ?boundary_kind,
581 kind = %error.variant_name(),
582 "no on_exceptions policy matched and no dead-letter channel configured; propagating error"
583 );
584 }
585
586 if !matches!(
592 disposition,
593 ExceptionDisposition::Propagate | ExceptionDisposition::Continued
594 ) && let Some(PolicyId(idx)) = policy
595 && let Some((p, _)) = self.policies.get(idx)
596 && let Some(ref steps) = p.on_steps
597 {
598 let snapshot = exchange.branch_clone();
599 exchange.set_error(error.clone());
600 let mut step_pipeline = steps.clone_inner();
601 let step_result = async {
602 let svc = step_pipeline.ready().await?;
603 svc.call(exchange).await
604 }
605 .await;
606 match step_result {
607 Ok(mut ex) => match disposition {
608 ExceptionDisposition::Handled => {
609 ex.handle_error();
610 if producer.is_some() {
614 log_business_handled(&error);
615 }
616 return Ok(ex);
617 }
618 _ => {
620 exchange = snapshot;
621 }
622 },
623 Err(_) => {
624 exchange = snapshot;
625 }
626 }
627 }
628
629 self.restore_original_message_if_enabled(&mut exchange);
631 exchange.set_error(error.clone());
632 match send_to_handler(exchange, producer).await {
633 Ok(handler_ex) => match disposition {
634 ExceptionDisposition::Handled => {
635 let mut ex = handler_ex;
636 ex.clear_error();
637 Ok(ex)
638 }
639 _ => {
641 let mut ex = handler_ex;
642 ex.set_error(error);
643 Ok(ex)
644 }
645 },
646 Err(_delegate) => Err(error),
650 }
651 }
652}
653
654pub struct ErrorHandlerLayer {
658 dlc_producer: Option<BoxProcessor>,
660 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
662}
663
664impl ErrorHandlerLayer {
665 pub fn new(
667 dlc_producer: Option<BoxProcessor>,
668 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
669 ) -> Self {
670 Self {
671 dlc_producer,
672 policies,
673 }
674 }
675}
676
677impl<S> Layer<S> for ErrorHandlerLayer
678where
679 S: Service<Exchange, Response = Exchange, Error = CamelError> + Send + Clone + 'static,
680 S::Future: Send + 'static,
681{
682 type Service = ErrorHandlerService<S>;
683
684 fn layer(&self, inner: S) -> Self::Service {
685 ErrorHandlerService {
686 inner,
687 dlc_producer: self.dlc_producer.clone(),
688 policies: self
689 .policies
690 .iter()
691 .map(|(p, prod)| (p.clone(), prod.clone()))
692 .collect(),
693 }
694 }
695}
696
697pub struct ErrorHandlerService<S> {
705 inner: S,
706 dlc_producer: Option<BoxProcessor>,
707 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
708}
709
710impl<S: Clone> Clone for ErrorHandlerService<S> {
711 fn clone(&self) -> Self {
712 Self {
713 inner: self.inner.clone(),
714 dlc_producer: self.dlc_producer.clone(),
715 policies: self
716 .policies
717 .iter()
718 .map(|(p, prod)| (p.clone(), prod.clone()))
719 .collect(),
720 }
721 }
722}
723
724impl<S> ErrorHandlerService<S>
725where
726 S: Service<Exchange, Response = Exchange, Error = CamelError> + Send + Clone + 'static,
727 S::Future: Send + 'static,
728{
729 pub fn new(
731 inner: S,
732 dlc_producer: Option<BoxProcessor>,
733 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
734 ) -> Self {
735 Self {
736 inner,
737 dlc_producer,
738 policies,
739 }
740 }
741}
742
743impl<S> Service<Exchange> for ErrorHandlerService<S>
744where
745 S: Service<Exchange, Response = Exchange, Error = CamelError> + Send + Clone + 'static,
746 S::Future: Send + 'static,
747{
748 type Response = Exchange;
749 type Error = CamelError;
750 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
751
752 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
753 match self.inner.poll_ready(cx) {
758 Poll::Pending => Poll::Pending,
759 Poll::Ready(Err(_)) => Poll::Ready(Ok(())),
760 Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
761 }
762 }
763
764 fn call(&mut self, exchange: Exchange) -> Self::Future {
765 let mut inner = self.inner.clone();
766 let dlc = self.dlc_producer.clone();
767 let policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)> = self
768 .policies
769 .iter()
770 .map(|(p, prod)| (p.clone(), prod.clone()))
771 .collect();
772
773 Box::pin(async move {
774 let original = exchange.branch_clone();
775 let result = match inner.ready().await {
776 Ok(svc) => svc.call(exchange).await,
777 Err(e) => Err(e), };
779
780 let mut err = match result {
781 Ok(ex) => return Ok(ex),
782 Err(e) => e,
783 };
784
785 let matched = policies.into_iter().find(|(p, _)| (p.matches)(&err));
787
788 if let Some((policy, policy_producer)) = matched {
789 if let Some(ref backoff) = policy.retry
792 && !is_business(&err)
793 {
794 for attempt in 0..backoff.max_attempts {
795 let delay = backoff.delay_for(attempt);
796 tokio::time::sleep(delay).await;
797
798 let mut ex = original.branch_clone();
800 ex.input.set_header(HEADER_REDELIVERED, Value::Bool(true));
801 ex.input.set_header(
802 HEADER_REDELIVERY_COUNTER,
803 Value::Number((attempt + 1).into()),
804 );
805 ex.input.set_header(
806 HEADER_REDELIVERY_MAX_COUNTER,
807 Value::Number(backoff.max_attempts.into()),
808 );
809
810 let result = match inner.ready().await {
811 Ok(svc) => svc.call(ex).await,
812 Err(e) => Err(e), };
814 match result {
815 Ok(ex) => return Ok(ex),
816 Err(retry_err) => {
817 if is_business(&retry_err) {
824 err = retry_err;
825 break;
826 }
827 if attempt + 1 == backoff.max_attempts {
828 let mut original = original.branch_clone();
830 original
831 .input
832 .set_header(HEADER_REDELIVERED, Value::Bool(true));
833 original.input.set_header(
834 HEADER_REDELIVERY_COUNTER,
835 Value::Number(backoff.max_attempts.into()),
836 );
837 original.input.set_header(
838 HEADER_REDELIVERY_MAX_COUNTER,
839 Value::Number(backoff.max_attempts.into()),
840 );
841 if let Some(ref steps) = policy.on_steps {
842 let handler = policy_producer.clone().or(dlc.clone());
843 return execute_on_steps(
844 original,
845 retry_err,
846 steps,
847 policy.disposition,
848 handler,
849 )
850 .await;
851 }
852 original.set_error(retry_err.clone());
853 let handler = policy_producer.or(dlc);
854 return forward_or_propagate(original, handler, retry_err)
855 .await;
856 }
857 }
858 }
859 }
860 }
861 if let Some(ref steps) = policy.on_steps {
863 let handler = policy_producer.or(dlc);
864 return execute_on_steps(original, err, steps, policy.disposition, handler)
865 .await;
866 }
867 let mut ex = original.branch_clone();
868 ex.set_error(err.clone());
869 let handler = policy_producer.or(dlc);
870 forward_or_propagate(ex, handler, err).await
871 } else {
872 let mut ex = original;
874 ex.set_error(err.clone());
875 forward_or_propagate(ex, dlc, err).await
876 }
877 })
878 }
879}
880
881pub(crate) fn record_span_error(delegate_err: &CamelError) {
888 let span = tracing::Span::current();
889 if !span.is_none() {
890 span.record("error", tracing::field::display(delegate_err));
891 }
892}
893
894async fn forward_or_propagate(
902 exchange: Exchange,
903 producer: Option<BoxProcessor>,
904 original_error: CamelError,
905) -> Result<Exchange, CamelError> {
906 if producer.is_none() {
910 log_business_propagated(&original_error);
911 }
912 match send_to_handler(exchange, producer).await {
913 Ok(ex) => Ok(ex),
914 Err(_delegate) => Err(original_error),
915 }
916}
917
918async fn send_to_handler(
919 exchange: Exchange,
920 producer: Option<BoxProcessor>,
921) -> Result<Exchange, CamelError> {
922 match producer {
923 None => {
924 if !matches!(exchange.error, Some(CamelError::Business { .. })) {
928 tracing::error!(
930 error = ?exchange.error,
931 "Exchange failed with no error handler configured"
932 );
933 }
934 Ok(exchange)
935 }
936 Some(mut prod) => {
937 if let Some(CamelError::Business { code, kind, .. }) = &exchange.error {
942 tracing::info!(code = %code, kind = %kind, "business error sent to handler");
943 }
944 match prod.ready().await {
945 Err(e) => {
946 tracing::error!(
951 original_error = ?exchange.error,
952 delegate_error = %e,
953 "DLC/handler not ready"
954 );
955 record_span_error(&e);
956 Err(e)
957 }
958 Ok(svc) => match svc.call(exchange.branch_clone()).await {
959 Ok(ex) => Ok(ex),
960 Err(e) => {
961 tracing::error!(
966 original_error = ?exchange.error,
967 delegate_error = %e,
968 "DLC/handler call failed"
969 );
970 record_span_error(&e);
971 Err(e)
974 }
975 },
976 }
977 }
978 }
979}
980
981#[cfg(test)]
982mod tests {
983 use super::*;
984 use camel_api::{
985 BoxProcessor, BoxProcessorExt, CamelError, Exchange, Message, OutcomePipeline,
986 OutcomeSegment, PipelineOutcome, RetryableStep, SyncBoxProcessor, Value,
987 error_handler::RedeliveryPolicy,
988 };
989 use std::future::Future;
990 use std::pin::Pin;
991 use std::sync::{
992 Arc,
993 atomic::{AtomicU32, Ordering},
994 };
995 use std::time::Duration;
996 use tower::ServiceExt;
997
998 fn make_exchange() -> Exchange {
999 Exchange::new(Message::new("test"))
1000 }
1001
1002 fn failing_processor() -> BoxProcessor {
1003 BoxProcessor::from_fn(|_ex| {
1004 Box::pin(async { Err(CamelError::ProcessorError("boom".into())) })
1005 })
1006 }
1007
1008 fn ok_processor() -> BoxProcessor {
1009 BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }))
1010 }
1011
1012 fn fail_n_times(n: u32) -> BoxProcessor {
1013 let count = Arc::new(AtomicU32::new(0));
1014 BoxProcessor::from_fn(move |ex| {
1015 let count = Arc::clone(&count);
1016 Box::pin(async move {
1017 let c = count.fetch_add(1, Ordering::SeqCst);
1018 if c < n {
1019 Err(CamelError::ProcessorError(format!("attempt {c}")))
1020 } else {
1021 Ok(ex)
1022 }
1023 })
1024 })
1025 }
1026
1027 #[tokio::test]
1028 async fn test_ok_passthrough() {
1029 let svc = ErrorHandlerService::new(ok_processor(), None, vec![]);
1030 let result = svc.oneshot(make_exchange()).await;
1031 assert!(result.is_ok());
1032 assert!(!result.unwrap().has_error());
1033 }
1034
1035 #[tokio::test]
1036 async fn test_error_goes_to_dlc() {
1037 let received = Arc::new(std::sync::Mutex::new(Vec::<Exchange>::new()));
1038 let received_clone = Arc::clone(&received);
1039 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1040 let r = Arc::clone(&received_clone);
1041 Box::pin(async move {
1042 r.lock().unwrap().push(ex.clone());
1043 Ok(ex)
1044 })
1045 });
1046
1047 let svc = ErrorHandlerService::new(failing_processor(), Some(dlc), vec![]);
1048 let result = svc.oneshot(make_exchange()).await;
1049 assert!(result.is_ok());
1050 let ex = result.unwrap();
1051 assert!(ex.has_error());
1052 assert_eq!(received.lock().unwrap().len(), 1);
1053 }
1054
1055 #[tokio::test]
1056 async fn test_retry_recovers() {
1057 let inner = fail_n_times(2);
1058 let policy = ExceptionPolicy {
1059 matches: Arc::new(|_| true),
1060 retry: Some(RedeliveryPolicy {
1061 max_attempts: 3,
1062 initial_delay: Duration::from_millis(1),
1063 multiplier: 1.0,
1064 max_delay: Duration::from_millis(10),
1065 jitter_factor: 0.0,
1066 }),
1067 handled_by: None,
1068 on_steps: None,
1069 disposition: ExceptionDisposition::Propagate,
1070 };
1071 let svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1072 let result = svc.oneshot(make_exchange()).await;
1073 assert!(result.is_ok());
1074 assert!(!result.unwrap().has_error());
1075 }
1076
1077 #[tokio::test]
1078 async fn test_retry_exhausted_goes_to_dlc() {
1079 let inner = fail_n_times(10);
1080 let received = Arc::new(std::sync::Mutex::new(0u32));
1081 let received_clone = Arc::clone(&received);
1082 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1083 let r = Arc::clone(&received_clone);
1084 Box::pin(async move {
1085 *r.lock().unwrap() += 1;
1086 Ok(ex)
1087 })
1088 });
1089 let policy = ExceptionPolicy {
1090 matches: Arc::new(|_| true),
1091 retry: Some(RedeliveryPolicy {
1092 max_attempts: 2,
1093 initial_delay: Duration::from_millis(1),
1094 multiplier: 1.0,
1095 max_delay: Duration::from_millis(10),
1096 jitter_factor: 0.0,
1097 }),
1098 handled_by: None,
1099 on_steps: None,
1100 disposition: ExceptionDisposition::Propagate,
1101 };
1102 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![(policy, None)]);
1103 let result = svc.oneshot(make_exchange()).await;
1104 assert!(result.is_ok());
1105 assert!(result.unwrap().has_error());
1106 assert_eq!(*received.lock().unwrap(), 1);
1107 }
1108
1109 #[test]
1110 fn test_poll_ready_delegates_to_inner() {
1111 use std::sync::atomic::AtomicBool;
1112
1113 #[derive(Clone)]
1115 struct DelayedReadyService {
1116 ready: Arc<AtomicBool>,
1117 }
1118
1119 impl Service<Exchange> for DelayedReadyService {
1120 type Response = Exchange;
1121 type Error = CamelError;
1122 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1123
1124 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1125 if self.ready.fetch_or(true, Ordering::SeqCst) {
1126 Poll::Ready(Ok(()))
1128 } else {
1129 cx.waker().wake_by_ref();
1131 Poll::Pending
1132 }
1133 }
1134
1135 fn call(&mut self, ex: Exchange) -> Self::Future {
1136 Box::pin(async move { Ok(ex) })
1137 }
1138 }
1139
1140 let waker = futures::task::noop_waker();
1141 let mut cx = Context::from_waker(&waker);
1142
1143 let inner = DelayedReadyService {
1144 ready: Arc::new(AtomicBool::new(false)),
1145 };
1146 let mut svc = ErrorHandlerService::new(inner, None, vec![]);
1147
1148 let first = Pin::new(&mut svc).poll_ready(&mut cx);
1150 assert!(first.is_pending(), "expected Pending on first poll_ready");
1151
1152 let second = Pin::new(&mut svc).poll_ready(&mut cx);
1154 assert!(second.is_ready(), "expected Ready on second poll_ready");
1155 }
1156
1157 #[tokio::test]
1158 async fn test_no_matching_policy_uses_dlc() {
1159 let received = Arc::new(std::sync::Mutex::new(0u32));
1160 let received_clone = Arc::clone(&received);
1161 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1162 let r = Arc::clone(&received_clone);
1163 Box::pin(async move {
1164 *r.lock().unwrap() += 1;
1165 Ok(ex)
1166 })
1167 });
1168 let policy = ExceptionPolicy::new(|e| matches!(e, CamelError::Io(_)));
1169 let svc = ErrorHandlerService::new(failing_processor(), Some(dlc), vec![(policy, None)]);
1170 let result = svc.oneshot(make_exchange()).await;
1171 assert!(result.is_ok());
1172 assert_eq!(*received.lock().unwrap(), 1);
1173 }
1174
1175 #[tokio::test]
1176 async fn test_redelivery_headers_are_set() {
1177 use camel_api::error_handler::{
1178 HEADER_REDELIVERED, HEADER_REDELIVERY_COUNTER, HEADER_REDELIVERY_MAX_COUNTER,
1179 RedeliveryPolicy,
1180 };
1181
1182 let inner = fail_n_times(10);
1183 let received = Arc::new(std::sync::Mutex::new(None));
1184 let received_clone = Arc::clone(&received);
1185 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1186 let r = Arc::clone(&received_clone);
1187 Box::pin(async move {
1188 *r.lock().unwrap() = Some(ex.clone());
1189 Ok(ex)
1190 })
1191 });
1192
1193 let policy = ExceptionPolicy {
1194 matches: Arc::new(|_| true),
1195 retry: Some(RedeliveryPolicy {
1196 max_attempts: 2,
1197 initial_delay: Duration::from_millis(1),
1198 multiplier: 1.0,
1199 max_delay: Duration::from_millis(10),
1200 jitter_factor: 0.0,
1201 }),
1202 handled_by: None,
1203 on_steps: None,
1204 disposition: ExceptionDisposition::Propagate,
1205 };
1206
1207 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![(policy, None)]);
1208 let _ = svc.oneshot(make_exchange()).await.unwrap();
1209
1210 let ex = received.lock().unwrap().take().unwrap();
1211 assert_eq!(
1212 ex.input.header(HEADER_REDELIVERED),
1213 Some(&Value::Bool(true))
1214 );
1215 assert_eq!(
1216 ex.input.header(HEADER_REDELIVERY_COUNTER),
1217 Some(&Value::Number(2.into()))
1218 );
1219 assert_eq!(
1220 ex.input.header(HEADER_REDELIVERY_MAX_COUNTER),
1221 Some(&Value::Number(2.into()))
1222 );
1223 }
1224
1225 #[tokio::test]
1226 async fn test_jitter_produces_varying_delays_in_retry_flow() {
1227 use std::time::Instant;
1228
1229 let inner = fail_n_times(10);
1230 let received = Arc::new(std::sync::Mutex::new(None));
1231 let received_clone = Arc::clone(&received);
1232 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1233 let r = Arc::clone(&received_clone);
1234 Box::pin(async move {
1235 *r.lock().unwrap() = Some(ex.clone());
1236 Ok(ex)
1237 })
1238 });
1239
1240 let policy = ExceptionPolicy {
1241 matches: Arc::new(|_| true),
1242 retry: Some(RedeliveryPolicy {
1243 max_attempts: 5,
1244 initial_delay: Duration::from_millis(20),
1245 multiplier: 1.0,
1246 max_delay: Duration::from_millis(100),
1247 jitter_factor: 0.5,
1248 }),
1249 handled_by: None,
1250 on_steps: None,
1251 disposition: ExceptionDisposition::Propagate,
1252 };
1253
1254 let start = Instant::now();
1255 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![(policy, None)]);
1256 let _ = svc.oneshot(make_exchange()).await.unwrap();
1257 let elapsed = start.elapsed();
1258
1259 assert!(
1260 received.lock().unwrap().is_some(),
1261 "DLC should have received exchange"
1262 );
1263
1264 assert!(
1265 elapsed >= Duration::from_millis(50),
1266 "5 retries with 20ms base delay should take at least 50ms (with jitter low bound)"
1267 );
1268
1269 assert!(
1270 elapsed <= Duration::from_millis(500),
1271 "5 retries with 20ms base delay + 50% jitter should not exceed 500ms"
1272 );
1273 }
1274
1275 #[tokio::test]
1276 async fn test_on_steps_handled_true_consumes_error() {
1277 use tower::ServiceExt;
1278
1279 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1280 ex.input.body = camel_api::Body::Bytes("handled".into());
1281 async move { Ok(ex) }
1282 }));
1283 let policy = ExceptionPolicy {
1284 matches: Arc::new(|_| true),
1285 retry: None,
1286 handled_by: None,
1287 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1288 disposition: ExceptionDisposition::Handled,
1289 };
1290 let inner = tower::service_fn(|_ex: Exchange| async {
1291 Err::<Exchange, CamelError>(CamelError::RouteError("fail".to_string()))
1292 });
1293 let mut svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1294 let ex = Exchange::default();
1295 let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1296 assert!(result.error.is_none(), "handled:true should clear error");
1297 assert!(matches!(result.input.body, camel_api::Body::Bytes(_)));
1298 }
1299
1300 #[tokio::test]
1301 async fn test_on_steps_handled_false_propagates_error() {
1302 use tower::ServiceExt;
1303
1304 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1305 ex.input.body = camel_api::Body::Bytes("handled".into());
1306 async move { Ok(ex) }
1307 }));
1308 let policy = ExceptionPolicy {
1309 matches: Arc::new(|_| true),
1310 retry: None,
1311 handled_by: None,
1312 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1313 disposition: ExceptionDisposition::Propagate,
1314 };
1315 let inner = tower::service_fn(|_ex: Exchange| async {
1316 Err::<Exchange, CamelError>(CamelError::RouteError("fail".to_string()))
1317 });
1318 let mut svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1319 let ex = Exchange::default();
1320 let result = svc.ready().await.unwrap().call(ex).await;
1321 assert!(result.is_err(), "handled:false should propagate error");
1322 }
1323
1324 #[derive(Clone)]
1332 struct ReadinessFailService {
1333 error: CamelError,
1334 }
1335
1336 impl ReadinessFailService {
1337 fn new(error: CamelError) -> Self {
1338 Self { error }
1339 }
1340 }
1341
1342 impl Service<Exchange> for ReadinessFailService {
1343 type Response = Exchange;
1344 type Error = CamelError;
1345 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1346
1347 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1348 Poll::Ready(Err(self.error.clone()))
1349 }
1350
1351 fn call(&mut self, ex: Exchange) -> Self::Future {
1352 Box::pin(async move { Ok(ex) })
1355 }
1356 }
1357
1358 #[tokio::test]
1359 async fn test_readiness_error_goes_to_dlc() {
1360 let readiness_err = CamelError::ProcessorError("readiness-fail".into());
1361 let inner = ReadinessFailService {
1362 error: readiness_err,
1363 };
1364
1365 let received = Arc::new(std::sync::Mutex::new(Vec::<Exchange>::new()));
1366 let received_clone = Arc::clone(&received);
1367 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1368 let r = Arc::clone(&received_clone);
1369 Box::pin(async move {
1370 r.lock().unwrap().push(ex.clone());
1371 Ok(ex)
1372 })
1373 });
1374
1375 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![]);
1376 let result = svc.oneshot(make_exchange()).await;
1377
1378 assert!(
1380 result.is_ok(),
1381 "readiness error should be captured and sent to DLC, got: {:?}",
1382 result
1383 );
1384 let ex = result.unwrap();
1385 assert!(ex.has_error(), "exchange should carry the readiness error");
1386 assert_eq!(
1387 received.lock().unwrap().len(),
1388 1,
1389 "DLC should have received the exchange exactly once"
1390 );
1391 }
1392
1393 #[tokio::test]
1394 async fn test_readiness_error_goes_to_matching_policy() {
1395 let readiness_err = CamelError::ProcessorError("readiness-fail".into());
1396 let inner = ReadinessFailService {
1397 error: readiness_err,
1398 };
1399
1400 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1401 ex.input.body = camel_api::Body::Bytes("handled-readiness".into());
1402 async move { Ok(ex) }
1403 }));
1404 let policy = ExceptionPolicy {
1405 matches: Arc::new(|_| true),
1406 retry: None,
1407 handled_by: None,
1408 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1409 disposition: ExceptionDisposition::Handled,
1410 };
1411
1412 let svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1413 let result = svc.oneshot(make_exchange()).await;
1414
1415 assert!(
1417 result.is_ok(),
1418 "readiness error should be captured by policy, got: {:?}",
1419 result
1420 );
1421 let ex = result.unwrap();
1422 assert!(ex.error.is_none(), "handled:true should clear error");
1423 assert!(
1424 matches!(ex.input.body, camel_api::Body::Bytes(_)),
1425 "on_steps should have modified the body"
1426 );
1427 }
1428
1429 #[test]
1430 fn test_poll_ready_converts_readiness_error_to_ok() {
1431 let readiness_err = CamelError::ProcessorError("readiness-fail".into());
1432 let inner = ReadinessFailService {
1433 error: readiness_err,
1434 };
1435 let mut svc = ErrorHandlerService::new(inner, None, vec![]);
1436
1437 let waker = futures::task::noop_waker();
1438 let mut cx = Context::from_waker(&waker);
1439
1440 let poll = Pin::new(&mut svc).poll_ready(&mut cx);
1442 match poll {
1443 Poll::Ready(Ok(())) => { }
1444 Poll::Ready(Err(e)) => panic!("poll_ready leaked readiness error: {:?}", e),
1445 Poll::Pending => panic!("poll_ready should be Ready for readiness errors"),
1446 }
1447 }
1448
1449 #[tokio::test]
1452 async fn test_invoke_processor_returns_ok_on_success() {
1453 let mut svc = ok_processor();
1454 let ex = make_exchange();
1455 let result = invoke_processor(&mut svc, ex).await;
1456 assert!(result.is_ok());
1457 }
1458
1459 #[tokio::test]
1460 async fn test_invoke_processor_captures_readiness_error() {
1461 let mut failing_ready: BoxProcessor = BoxProcessor::new(ReadinessFailService::new(
1462 CamelError::ProcessorError("not ready".into()),
1463 ));
1464 let ex = make_exchange();
1465 let result = invoke_processor(&mut failing_ready, ex).await;
1466 assert!(result.is_err());
1467 }
1468
1469 #[tokio::test]
1470 async fn test_on_steps_handled_true_clears_exception_properties() {
1471 use tower::ServiceExt;
1472
1473 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1474 ex.input.body = camel_api::Body::Bytes("handled".into());
1475 async move { Ok(ex) }
1476 }));
1477 let policy = ExceptionPolicy {
1478 matches: Arc::new(|_| true),
1479 retry: None,
1480 handled_by: None,
1481 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1482 disposition: ExceptionDisposition::Handled,
1483 };
1484 let inner = tower::service_fn(|_ex: Exchange| async {
1485 Err::<Exchange, CamelError>(CamelError::RouteError("fail".to_string()))
1486 });
1487 let mut svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1488 let ex = Exchange::default();
1489 let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1490 assert!(result.error.is_none(), "handled:true should clear error");
1491 assert!(
1492 !result
1493 .properties
1494 .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_MESSAGE),
1495 "handled:true should clear exception properties"
1496 );
1497 assert!(
1498 !result
1499 .properties
1500 .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_KIND),
1501 "handled:true should clear exception kind property"
1502 );
1503 assert!(
1504 !result
1505 .properties
1506 .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_CAUGHT),
1507 "handled:true should clear exception caught property"
1508 );
1509 }
1510
1511 #[test]
1514 fn test_match_policy_returns_id_for_matching_error() {
1515 let handler = DefaultRouteErrorHandler::new(
1516 None,
1517 vec![(
1518 ExceptionPolicy::new(|e| matches!(e, CamelError::ProcessorError(_))),
1519 None,
1520 )],
1521 );
1522 let id = handler.match_policy(&CamelError::ProcessorError("test".into()));
1523 assert_eq!(id, Some(PolicyId(0)));
1524 }
1525
1526 #[test]
1527 fn test_match_policy_returns_none_for_unmatched() {
1528 let handler = DefaultRouteErrorHandler::new(None, vec![]);
1529 let id = handler.match_policy(&CamelError::ProcessorError("test".into()));
1530 assert_eq!(id, None);
1531 }
1532
1533 #[tokio::test]
1536 async fn test_retry_step_succeeds_on_second_attempt() {
1537 let mut policy = ExceptionPolicy::new(|_| true);
1538 policy.retry = Some(RedeliveryPolicy::new(3));
1539 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1540 let mut step = fail_n_times(1); let ex = make_exchange();
1542 let outcome = handler
1543 .retry_step(
1544 Some(PolicyId(0)),
1545 &mut step,
1546 ex,
1547 CamelError::ProcessorError("attempt 0".into()),
1548 )
1549 .await;
1550 assert!(matches!(outcome, RetryOutcome::Recovered(_)));
1551 }
1552
1553 #[tokio::test]
1554 async fn test_retry_step_exhausted_when_all_fail() {
1555 let mut policy = ExceptionPolicy::new(|_| true);
1556 policy.retry = Some(RedeliveryPolicy::new(3));
1557 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1558 let mut step = failing_processor();
1559 let ex = make_exchange();
1560 let outcome = handler
1561 .retry_step(
1562 Some(PolicyId(0)),
1563 &mut step,
1564 ex,
1565 CamelError::ProcessorError("boom".into()),
1566 )
1567 .await;
1568 assert!(matches!(outcome, RetryOutcome::Exhausted { .. }));
1569 }
1570
1571 #[tokio::test]
1572 async fn test_retry_step_no_policy_returns_exhausted_immediately() {
1573 let handler = DefaultRouteErrorHandler::new(None, vec![]);
1574 let mut step = ok_processor();
1575 let ex = make_exchange();
1576 let outcome = handler
1577 .retry_step(
1578 None,
1579 &mut step,
1580 ex,
1581 CamelError::ProcessorError("boom".into()),
1582 )
1583 .await;
1584 assert!(matches!(
1585 outcome,
1586 RetryOutcome::Exhausted { policy: None, .. }
1587 ));
1588 }
1589
1590 #[tokio::test]
1593 async fn test_handle_step_propagate_sends_to_dlc() {
1594 let dlc = BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }));
1595 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1596 let ex = make_exchange();
1597 let result = handler
1598 .handle_step(None, ex, CamelError::ProcessorError("boom".into()))
1599 .await;
1600 assert!(matches!(result, Ok(StepDisposition::Propagate(_))));
1601 }
1602
1603 #[tokio::test]
1604 async fn test_handle_step_handled_uses_handler_output() {
1605 let handler_producer = BoxProcessor::from_fn(|mut ex| {
1606 Box::pin(async move {
1607 ex.input.set_header("processed_by", Value::Bool(true));
1608 Ok(ex)
1609 })
1610 });
1611 let policy = ExceptionPolicy {
1612 matches: std::sync::Arc::new(|_| true),
1613 retry: None,
1614 handled_by: None,
1615 on_steps: None,
1616 disposition: ExceptionDisposition::Handled,
1617 };
1618 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(handler_producer))]);
1619 let mut ex = make_exchange();
1620 ex.set_error(CamelError::ProcessorError("boom".into()));
1621 let result = handler
1622 .handle_step(
1623 Some(PolicyId(0)),
1624 ex,
1625 CamelError::ProcessorError("boom".into()),
1626 )
1627 .await;
1628 match result {
1629 Ok(StepDisposition::Handled(ex)) => {
1630 assert!(!ex.has_error(), "error should be cleared");
1631 assert_eq!(
1632 ex.input.header("processed_by"),
1633 Some(&Value::Bool(true)),
1634 "should use handler's output exchange"
1635 );
1636 }
1637 other => panic!("expected Handled, got {:?}", other.is_ok()),
1638 }
1639 }
1640
1641 #[tokio::test]
1642 async fn test_handle_step_continued_clears_error() {
1643 let policy = ExceptionPolicy {
1644 matches: std::sync::Arc::new(|_| true),
1645 retry: None,
1646 handled_by: None,
1647 on_steps: None,
1648 disposition: ExceptionDisposition::Continued,
1649 };
1650 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1651 let mut ex = make_exchange();
1652 ex.set_error(CamelError::ProcessorError("boom".into()));
1653 let result = handler
1654 .handle_step(
1655 Some(PolicyId(0)),
1656 ex,
1657 CamelError::ProcessorError("boom".into()),
1658 )
1659 .await;
1660 match result {
1661 Ok(StepDisposition::Continued(ex)) => assert!(!ex.has_error()),
1662 other => panic!("expected Continued, got {:?}", other.is_ok()),
1663 }
1664 }
1665
1666 #[tokio::test]
1667 async fn test_handle_step_with_on_steps_handled() {
1668 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1669 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
1670 async move { Ok(ex) }
1671 }));
1672 let policy = ExceptionPolicy {
1673 matches: std::sync::Arc::new(|_| true),
1674 retry: None,
1675 handled_by: None,
1676 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1677 disposition: ExceptionDisposition::Handled,
1678 };
1679 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1680 let mut ex = make_exchange();
1681 ex.set_error(CamelError::ProcessorError("boom".into()));
1682 let result = handler
1683 .handle_step(
1684 Some(PolicyId(0)),
1685 ex,
1686 CamelError::ProcessorError("boom".into()),
1687 )
1688 .await;
1689 match result {
1690 Ok(StepDisposition::Handled(ex)) => {
1691 assert!(!ex.has_error(), "error should be cleared");
1692 assert!(
1693 matches!(ex.input.body, camel_api::Body::Bytes(_)),
1694 "on_steps should have modified the body"
1695 );
1696 }
1697 other => panic!("expected Handled, got: {}", other.is_ok()),
1698 }
1699 }
1700
1701 #[tokio::test]
1702 async fn test_handle_step_dlc_failure_propagates() {
1703 let failing_dlc = BoxProcessor::from_fn(|_| {
1704 Box::pin(async { Err(CamelError::ProcessorError("dlc broken".into())) })
1705 });
1706 let handler = DefaultRouteErrorHandler::new(Some(failing_dlc), vec![]);
1707 let ex = make_exchange();
1708 let result = handler
1709 .handle_step(None, ex, CamelError::ProcessorError("original".into()))
1710 .await;
1711 assert!(
1712 matches!(result, Ok(StepDisposition::Propagate(_))),
1713 "DLC failure should still return Propagate with original error"
1714 );
1715 }
1716
1717 #[tokio::test]
1720 async fn test_handle_boundary_security_error_goes_to_dlc() {
1721 let dlc_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
1722 let count_clone = dlc_count.clone();
1723 let dlc = BoxProcessor::from_fn(move |ex| {
1724 let c = count_clone.clone();
1725 Box::pin(async move {
1726 c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1727 Ok(ex)
1728 })
1729 });
1730 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1731 let ex = make_exchange();
1732 let result = handler
1733 .handle_boundary(
1734 BoundaryKind::Security,
1735 ex,
1736 CamelError::Unauthorized("denied".into()),
1737 )
1738 .await;
1739 assert!(result.is_ok());
1740 assert_eq!(dlc_count.load(std::sync::atomic::Ordering::SeqCst), 1);
1741 }
1742
1743 #[tokio::test]
1744 async fn test_handle_boundary_handled_clears_error() {
1745 let policy = ExceptionPolicy {
1746 matches: std::sync::Arc::new(|_| true),
1747 retry: None,
1748 handled_by: None,
1749 on_steps: None,
1750 disposition: ExceptionDisposition::Handled,
1751 };
1752 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1753 let ex = make_exchange();
1754 let result = handler
1755 .handle_boundary(
1756 BoundaryKind::Security,
1757 ex,
1758 CamelError::Unauthorized("denied".into()),
1759 )
1760 .await;
1761 assert!(result.is_ok());
1762 assert!(
1763 !result.unwrap().has_error(),
1764 "Handled disposition should clear error"
1765 );
1766 }
1767
1768 #[tokio::test]
1769 async fn test_handle_boundary_propagate_preserves_error() {
1770 let policy = ExceptionPolicy {
1771 matches: std::sync::Arc::new(|_| true),
1772 retry: None,
1773 handled_by: None,
1774 on_steps: None,
1775 disposition: ExceptionDisposition::Propagate,
1776 };
1777 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1778 let ex = make_exchange();
1779 let result = handler
1780 .handle_boundary(
1781 BoundaryKind::CircuitBreaker,
1782 ex,
1783 CamelError::CircuitOpen("open".into()),
1784 )
1785 .await;
1786 assert!(result.is_ok(), "boundary errors always return Ok");
1787 assert!(
1788 result.unwrap().has_error(),
1789 "Propagate disposition should preserve error"
1790 );
1791 }
1792
1793 #[tokio::test]
1794 async fn test_handle_boundary_continued_preserves_error_like_propagate() {
1795 let dlc_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
1796 let count_clone = dlc_count.clone();
1797 let dlc = BoxProcessor::from_fn(move |ex| {
1798 let c = count_clone.clone();
1799 Box::pin(async move {
1800 c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1801 Ok(ex)
1802 })
1803 });
1804 let policy = ExceptionPolicy {
1805 matches: std::sync::Arc::new(|_| true),
1806 retry: None,
1807 handled_by: None,
1808 on_steps: None,
1809 disposition: ExceptionDisposition::Continued,
1810 };
1811 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![(policy, None)]);
1812 let ex = make_exchange();
1813 let result = handler
1814 .handle_boundary(
1815 BoundaryKind::Security,
1816 ex,
1817 CamelError::Unauthorized("denied".into()),
1818 )
1819 .await;
1820 assert!(result.is_ok(), "boundary errors always return Ok");
1821 assert!(
1822 result.unwrap().has_error(),
1823 "Continued at boundary should preserve error"
1824 );
1825 assert_eq!(
1826 dlc_count.load(std::sync::atomic::Ordering::SeqCst),
1827 1,
1828 "DLC should be called"
1829 );
1830 }
1831
1832 #[tokio::test]
1833 async fn test_handle_boundary_with_on_steps_handled() {
1834 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1835 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
1836 async move { Ok(ex) }
1837 }));
1838 let policy = ExceptionPolicy {
1839 matches: std::sync::Arc::new(|_| true),
1840 retry: None,
1841 handled_by: None,
1842 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1843 disposition: ExceptionDisposition::Handled,
1844 };
1845 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1846 let ex = make_exchange();
1847 let result = handler
1848 .handle_boundary(
1849 BoundaryKind::Security,
1850 ex,
1851 CamelError::Unauthorized("denied".into()),
1852 )
1853 .await;
1854 assert!(result.is_ok(), "boundary errors always return Ok");
1855 let ex = result.unwrap();
1856 assert!(!ex.has_error(), "Handled disposition should clear error");
1857 assert!(
1858 matches!(ex.input.body, camel_api::Body::Bytes(_)),
1859 "on_steps should have modified the body"
1860 );
1861 }
1862
1863 #[tokio::test]
1864 async fn retry_step_segment_stop_maps_to_retry_outcome_stopped() {
1865 use std::sync::Arc;
1866 use std::sync::atomic::{AtomicUsize, Ordering};
1867
1868 #[derive(Clone)]
1869 struct StoppingSegment {
1870 n: Arc<AtomicUsize>,
1871 }
1872 impl OutcomePipeline for StoppingSegment {
1873 fn clone_box(&self) -> Box<dyn OutcomePipeline> {
1874 Box::new(self.clone())
1875 }
1876 fn run<'a>(
1877 &'a mut self,
1878 ex: Exchange,
1879 ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
1880 let n = self.n.clone();
1881 Box::pin(async move {
1882 n.fetch_add(1, Ordering::SeqCst);
1883 PipelineOutcome::Stopped(ex)
1884 })
1885 }
1886 }
1887
1888 let call_count = Arc::new(AtomicUsize::new(0));
1889 let seg = OutcomeSegment::new(Box::new(StoppingSegment {
1890 n: call_count.clone(),
1891 }));
1892 let mut retryable: Box<dyn RetryableStep> = Box::new(seg);
1893
1894 let mut policy = ExceptionPolicy::new(|_e: &CamelError| true);
1895 policy.retry = Some(RedeliveryPolicy::new(3));
1896 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1897
1898 let original = Exchange::new(Message::new("retry-me"));
1899 let err = CamelError::ProcessorError("trigger retry".into());
1900 let outcome = handler
1901 .retry_step(Some(PolicyId(0)), retryable.as_mut(), original, err)
1902 .await;
1903
1904 assert!(
1905 matches!(outcome, RetryOutcome::Stopped(_)),
1906 "Segment Stop must map to RetryOutcome::Stopped, got {:?}",
1907 outcome
1908 );
1909 assert_eq!(
1910 call_count.load(Ordering::SeqCst),
1911 1,
1912 "Stop must short-circuit retry — only 1 invoke expected, got {}",
1913 call_count.load(Ordering::SeqCst)
1914 );
1915 }
1916
1917 #[tokio::test]
1918 async fn retry_step_new_signature_works_with_dlc_producer() {
1919 use std::sync::Arc;
1920 use std::sync::atomic::{AtomicUsize, Ordering};
1921
1922 #[derive(Clone)]
1923 struct CountingProducer {
1924 count: Arc<AtomicUsize>,
1925 succeed_on: usize,
1926 }
1927 impl tower::Service<Exchange> for CountingProducer {
1928 type Response = Exchange;
1929 type Error = CamelError;
1930 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1931 fn poll_ready(
1932 &mut self,
1933 _cx: &mut std::task::Context<'_>,
1934 ) -> std::task::Poll<Result<(), Self::Error>> {
1935 std::task::Poll::Ready(Ok(()))
1936 }
1937 fn call(&mut self, ex: Exchange) -> Self::Future {
1938 let n = self.count.fetch_add(1, Ordering::SeqCst);
1939 let succeed_on = self.succeed_on;
1940 Box::pin(async move {
1941 if n >= succeed_on {
1942 Ok(ex)
1943 } else {
1944 Err(CamelError::ProcessorError("retry".into()))
1945 }
1946 })
1947 }
1948 }
1949
1950 let count = Arc::new(AtomicUsize::new(0));
1951 let producer = CountingProducer {
1952 count: count.clone(),
1953 succeed_on: 2,
1954 };
1955 let sync_bp = SyncBoxProcessor::new(BoxProcessor::new(producer));
1956 let bp1 = sync_bp.clone_inner();
1957 let bp2 = sync_bp.clone_inner();
1958 let mut retryable1: Box<dyn RetryableStep> = Box::new(bp1);
1959 let mut retryable2: Box<dyn RetryableStep> = Box::new(bp2);
1960
1961 let ex = Exchange::new(Message::new("dlc"));
1962 let outcome1 = retryable1.invoke(ex.clone()).await;
1963 let outcome2 = retryable2.invoke(ex).await;
1964 assert!(matches!(outcome1, PipelineOutcome::Failed(_)));
1965 assert!(matches!(outcome2, PipelineOutcome::Failed(_)));
1966 assert_eq!(
1967 count.load(Ordering::SeqCst),
1968 2,
1969 "DLC producer must be invoked exactly twice through SyncBoxProcessor"
1970 );
1971 drop(retryable1);
1972 drop(retryable2);
1973 drop(sync_bp);
1974 }
1975
1976 #[tokio::test]
1979 async fn test_use_original_message_restores_body_before_dlc() {
1980 let dlc_received = Arc::new(std::sync::Mutex::new(None::<Exchange>));
1983 let dlc_received_clone = Arc::clone(&dlc_received);
1984 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1985 let r = Arc::clone(&dlc_received_clone);
1986 Box::pin(async move {
1987 *r.lock().unwrap() = Some(ex.clone());
1988 Ok(ex)
1989 })
1990 });
1991
1992 let mut handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1993 handler.use_original_message = true;
1994
1995 let mut ex = make_exchange();
1997 ex.input = Message::new("original-body");
1998
1999 let original: Arc<Message> = Arc::new(ex.input.clone());
2001 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, original);
2002
2003 ex.input.body = camel_api::Body::Bytes("mutated-body".into());
2005
2006 let result = handler
2008 .handle_step(None, ex, CamelError::ProcessorError("boom".into()))
2009 .await;
2010 assert!(matches!(result, Ok(StepDisposition::Propagate(_))));
2011
2012 let received = dlc_received
2014 .lock()
2015 .unwrap()
2016 .take()
2017 .expect("DLC should have been called");
2018 let received_text = match &received.input.body {
2019 camel_api::Body::Text(s) => s.clone(),
2020 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
2021 camel_api::Body::Json(v) => v.to_string(),
2022 _ => String::new(),
2023 };
2024 assert_eq!(
2025 received_text, "original-body",
2026 "DLC should receive original message body, not mutated version"
2027 );
2028 }
2029
2030 #[tokio::test]
2031 async fn test_use_original_message_handle_boundary_restores_before_dlc() {
2032 let dlc_received = Arc::new(std::sync::Mutex::new(None::<Exchange>));
2033 let dlc_received_clone = Arc::clone(&dlc_received);
2034 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
2035 let r = Arc::clone(&dlc_received_clone);
2036 Box::pin(async move {
2037 *r.lock().unwrap() = Some(ex.clone());
2038 Ok(ex)
2039 })
2040 });
2041
2042 let mut handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
2043 handler.use_original_message = true;
2044
2045 let mut ex = make_exchange();
2046 ex.input = Message::new("orig-boundary");
2047
2048 let original: Arc<Message> = Arc::new(ex.input.clone());
2049 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, original);
2050
2051 ex.input.body = camel_api::Body::Bytes("mutated-boundary".into());
2053
2054 let result = handler
2055 .handle_boundary(
2056 BoundaryKind::Security,
2057 ex,
2058 CamelError::Unauthorized("denied".into()),
2059 )
2060 .await;
2061 assert!(result.is_ok());
2062
2063 let received = dlc_received
2064 .lock()
2065 .unwrap()
2066 .take()
2067 .expect("DLC should have been called");
2068 let received_text = match &received.input.body {
2069 camel_api::Body::Text(s) => s.clone(),
2070 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
2071 camel_api::Body::Json(v) => v.to_string(),
2072 _ => String::new(),
2073 };
2074 assert_eq!(
2075 received_text, "orig-boundary",
2076 "handle_boundary should restore original message before sending to DLC"
2077 );
2078 }
2079
2080 #[tokio::test]
2081 async fn test_use_original_message_false_does_not_restore() {
2082 let dlc_received = Arc::new(std::sync::Mutex::new(None::<Exchange>));
2084 let dlc_received_clone = Arc::clone(&dlc_received);
2085 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
2086 let r = Arc::clone(&dlc_received_clone);
2087 Box::pin(async move {
2088 *r.lock().unwrap() = Some(ex.clone());
2089 Ok(ex)
2090 })
2091 });
2092
2093 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
2094 let mut ex = make_exchange();
2097 ex.input = Message::new("original-body");
2098
2099 let original: Arc<Message> = Arc::new(ex.input.clone());
2101 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, original);
2102
2103 ex.input.body = camel_api::Body::Bytes("mutated-body".into());
2105
2106 let result = handler
2107 .handle_step(None, ex, CamelError::ProcessorError("boom".into()))
2108 .await;
2109 assert!(matches!(result, Ok(StepDisposition::Propagate(_))));
2110
2111 let received = dlc_received
2112 .lock()
2113 .unwrap()
2114 .take()
2115 .expect("DLC should have been called");
2116 let received_text = match &received.input.body {
2117 camel_api::Body::Text(s) => s.clone(),
2118 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
2119 camel_api::Body::Json(v) => v.to_string(),
2120 _ => String::new(),
2121 };
2122 assert_eq!(
2123 received_text, "mutated-body",
2124 "When use_original_message=false, DLC should see the mutated body"
2125 );
2126 }
2127
2128 fn handled_policy() -> ExceptionPolicy {
2131 ExceptionPolicy {
2132 matches: Arc::new(|_| true),
2133 retry: None,
2134 handled_by: None,
2135 on_steps: None,
2136 disposition: ExceptionDisposition::Handled,
2137 }
2138 }
2139
2140 fn body_text(body: &camel_api::Body) -> String {
2141 match body {
2142 camel_api::Body::Text(s) => s.clone(),
2143 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
2144 camel_api::Body::Json(v) => v.to_string(),
2145 _ => String::new(),
2146 }
2147 }
2148
2149 #[tokio::test]
2150 async fn restore_reinstates_marker_for_untouched_original() {
2151 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)])
2152 .with_use_original_message(true);
2153
2154 let mut original = Message::new("original-body");
2155 original.set_header("Content-Type", "application/xml");
2156
2157 let mut ex = make_exchange();
2158 ex.input = original.clone();
2159 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
2160 ex.set_extension(
2161 camel_api::ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
2162 Arc::new(camel_api::OriginalContentTypeInherited(true)),
2163 );
2164
2165 ex.input.set_header("Content-Type", "application/json");
2168 ex.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
2169
2170 let disposition = handler
2171 .handle_step(
2172 Some(PolicyId(0)),
2173 ex,
2174 CamelError::ProcessorError("boom".into()),
2175 )
2176 .await
2177 .expect("handle_step should succeed");
2178 let StepDisposition::Handled(ex) = disposition else {
2179 panic!("expected Handled disposition");
2180 };
2181
2182 assert_eq!(body_text(&ex.input.body), "original-body");
2183 assert_eq!(
2184 ex.input.header("Content-Type"),
2185 Some(&Value::String("application/xml".into()))
2186 );
2187 assert_eq!(
2188 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
2189 Some(&Value::Bool(true)),
2190 "restoring an inherited original must reinstate the marker"
2191 );
2192 }
2193
2194 #[tokio::test]
2195 async fn restore_removes_live_marker_when_snapshot_false() {
2196 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)])
2197 .with_use_original_message(true);
2198
2199 let original = Message::new("original-body");
2202
2203 let mut ex = make_exchange();
2204 ex.input = original.clone();
2205 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
2206 ex.set_extension(
2207 camel_api::ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
2208 Arc::new(camel_api::OriginalContentTypeInherited(false)),
2209 );
2210 ex.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
2211
2212 let disposition = handler
2213 .handle_step(
2214 Some(PolicyId(0)),
2215 ex,
2216 CamelError::ProcessorError("boom".into()),
2217 )
2218 .await
2219 .expect("handle_step should succeed");
2220 let StepDisposition::Handled(ex) = disposition else {
2221 panic!("expected Handled disposition");
2222 };
2223
2224 assert_eq!(
2225 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
2226 None,
2227 "a stored false snapshot must clear a live marker"
2228 );
2229 }
2230
2231 #[tokio::test]
2232 async fn restore_clears_marker_when_snapshot_absent() {
2233 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)])
2234 .with_use_original_message(true);
2235
2236 let original = Message::new("original-body");
2239
2240 let mut ex = make_exchange();
2241 ex.input = original.clone();
2242 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
2243 ex.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
2244
2245 let disposition = handler
2246 .handle_step(
2247 Some(PolicyId(0)),
2248 ex,
2249 CamelError::ProcessorError("boom".into()),
2250 )
2251 .await
2252 .expect("handle_step should succeed");
2253 let StepDisposition::Handled(ex) = disposition else {
2254 panic!("expected Handled disposition");
2255 };
2256
2257 assert_eq!(
2258 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
2259 None,
2260 "an absent provenance snapshot must clear a live marker"
2261 );
2262 }
2263
2264 #[tokio::test]
2265 async fn restore_without_use_original_message_leaves_marker_untouched() {
2266 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)]);
2267 let mut original = Message::new("original-body");
2270 original.set_header("Content-Type", "application/xml");
2271
2272 let mut ex = make_exchange();
2273 ex.input = original.clone();
2274 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
2275 ex.input = Message::new("mutated-body");
2276 ex.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
2277
2278 let disposition = handler
2279 .handle_step(
2280 Some(PolicyId(0)),
2281 ex,
2282 CamelError::ProcessorError("boom".into()),
2283 )
2284 .await
2285 .expect("handle_step should succeed");
2286 let StepDisposition::Handled(ex) = disposition else {
2287 panic!("expected Handled disposition");
2288 };
2289
2290 assert_eq!(
2291 body_text(&ex.input.body),
2292 "mutated-body",
2293 "restoration must not run when use_original_message is disabled"
2294 );
2295 assert_eq!(
2296 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
2297 Some(&Value::Bool(true)),
2298 "restoration must not run when use_original_message is disabled"
2299 );
2300 }
2301
2302 #[tokio::test]
2305 async fn propagate_skips_on_steps_in_handle_step() {
2306 let on_steps_called = Arc::new(AtomicU32::new(0));
2307 let on_steps_called_clone = on_steps_called.clone();
2308 let steps_pipeline = BoxProcessor::new(tower::service_fn(move |mut ex: Exchange| {
2309 let c = on_steps_called_clone.clone();
2310 Box::pin(async move {
2311 c.fetch_add(1, Ordering::SeqCst);
2312 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
2313 Ok(ex)
2314 })
2315 }));
2316 let dlc_called = Arc::new(AtomicU32::new(0));
2317 let dlc_called_clone = dlc_called.clone();
2318 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
2319 let c = dlc_called_clone.clone();
2320 Box::pin(async move {
2321 c.fetch_add(1, Ordering::SeqCst);
2322 Ok(ex)
2323 })
2324 });
2325 let policy = ExceptionPolicy {
2326 matches: std::sync::Arc::new(|_| true),
2327 retry: None,
2328 handled_by: None,
2329 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
2330 disposition: ExceptionDisposition::Propagate,
2331 };
2332 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![(policy, None)]);
2333 let mut ex = make_exchange();
2334 ex.set_error(CamelError::ProcessorError("boom".into()));
2335 let result = handler
2336 .handle_step(
2337 Some(PolicyId(0)),
2338 ex,
2339 CamelError::ProcessorError("boom".into()),
2340 )
2341 .await;
2342 assert!(
2343 matches!(result, Ok(StepDisposition::Propagate(_))),
2344 "Propagate disposition should return Propagate"
2345 );
2346 assert_eq!(
2347 on_steps_called.load(Ordering::SeqCst),
2348 0,
2349 "on_steps must NOT be called when disposition is Propagate (double side-effect bug)"
2350 );
2351 assert_eq!(
2352 dlc_called.load(Ordering::SeqCst),
2353 1,
2354 "DLC should still be called when disposition is Propagate"
2355 );
2356 }
2357
2358 #[tokio::test]
2359 async fn propagate_skips_on_steps_in_handle_boundary() {
2360 let on_steps_called = Arc::new(AtomicU32::new(0));
2361 let on_steps_called_clone = on_steps_called.clone();
2362 let steps_pipeline = BoxProcessor::new(tower::service_fn(move |mut ex: Exchange| {
2363 let c = on_steps_called_clone.clone();
2364 Box::pin(async move {
2365 c.fetch_add(1, Ordering::SeqCst);
2366 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
2367 Ok(ex)
2368 })
2369 }));
2370 let dlc_called = Arc::new(AtomicU32::new(0));
2371 let dlc_called_clone = dlc_called.clone();
2372 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
2373 let c = dlc_called_clone.clone();
2374 Box::pin(async move {
2375 c.fetch_add(1, Ordering::SeqCst);
2376 Ok(ex)
2377 })
2378 });
2379 let policy = ExceptionPolicy {
2380 matches: std::sync::Arc::new(|_| true),
2381 retry: None,
2382 handled_by: None,
2383 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
2384 disposition: ExceptionDisposition::Propagate,
2385 };
2386 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![(policy, None)]);
2387 let ex = make_exchange();
2388 let result = handler
2389 .handle_boundary(
2390 BoundaryKind::CircuitBreaker,
2391 ex,
2392 CamelError::CircuitOpen("open".into()),
2393 )
2394 .await;
2395 assert!(result.is_ok(), "boundary errors always return Ok");
2396 assert!(
2397 result.unwrap().has_error(),
2398 "Propagate disposition should preserve error"
2399 );
2400 assert_eq!(
2401 on_steps_called.load(Ordering::SeqCst),
2402 0,
2403 "on_steps must NOT be called when disposition is Propagate (double side-effect bug)"
2404 );
2405 assert_eq!(
2406 dlc_called.load(Ordering::SeqCst),
2407 1,
2408 "DLC should still be called when disposition is Propagate"
2409 );
2410 }
2411
2412 fn failing_delegate() -> BoxProcessor {
2420 BoxProcessor::from_fn(|_| {
2421 Box::pin(async { Err(CamelError::ProcessorError("delegate-broken".into())) })
2422 })
2423 }
2424
2425 fn handled_policy_with(producer: Option<BoxProcessor>) -> DefaultRouteErrorHandler {
2428 let policy = ExceptionPolicy {
2429 matches: std::sync::Arc::new(|_| true),
2430 retry: None,
2431 handled_by: None,
2432 on_steps: None,
2433 disposition: ExceptionDisposition::Handled,
2434 };
2435 DefaultRouteErrorHandler::new(None, vec![(policy, producer)])
2436 }
2437
2438 fn assert_propagates_original(result: &Result<StepDisposition, CamelError>) {
2439 assert!(
2440 matches!(
2441 result,
2442 Ok(StepDisposition::Propagate(CamelError::ProcessorError(m)))
2443 if m == "original-err"
2444 ),
2445 "delegate failure must propagate the ORIGINAL error, got: {:?}",
2446 result
2447 .as_ref()
2448 .map(|d| d_variant_name(d))
2449 .unwrap_or_default()
2450 );
2451 }
2452
2453 fn d_variant_name(d: &StepDisposition) -> &'static str {
2455 match d {
2456 StepDisposition::Propagate(_) => "Propagate",
2457 StepDisposition::Handled(_) => "Handled",
2458 StepDisposition::Continued(_) => "Continued",
2459 _ => "other",
2460 }
2461 }
2462
2463 #[tokio::test]
2464 async fn delegate_call_failure_with_handled_propagates_original() {
2465 ensure_global_registry();
2468 let handler = handled_policy_with(Some(failing_delegate()));
2469 let result = handler
2470 .handle_step(
2471 Some(PolicyId(0)),
2472 make_exchange(),
2473 CamelError::ProcessorError("original-err".into()),
2474 )
2475 .await;
2476 assert_propagates_original(&result);
2477 }
2478
2479 #[test]
2480 fn delegate_failure_emits_system_broken_log_and_span_error() {
2481 let handler = handled_policy_with(Some(failing_delegate()));
2482 let mut ex = make_exchange();
2483 ex.set_error(CamelError::ProcessorError("original-err".into()));
2484 let (result, captured, span_records) = capture_debugs_with_span_records(|| {
2485 let span = tracing::info_span!("delegate_failure_test", error = tracing::field::Empty);
2487 let _guard = span.enter();
2488 tokio::runtime::Builder::new_current_thread()
2489 .enable_all()
2490 .build()
2491 .expect("current-thread runtime")
2492 .block_on(handler.handle_step(
2493 Some(PolicyId(0)),
2494 ex,
2495 CamelError::ProcessorError("original-err".into()),
2496 ))
2497 });
2498 assert!(
2499 matches!(result, Ok(StepDisposition::Propagate(_))),
2500 "delegate failure must propagate, got: {}",
2501 result
2502 .as_ref()
2503 .map(|d| d_variant_name(d))
2504 .unwrap_or("Err(..)")
2505 );
2506 assert!(
2508 captured.iter().any(|line| {
2509 line.contains("DLC/handler call failed")
2510 && line.contains("original-err")
2511 && line.contains("delegate-broken")
2512 }),
2513 "expected system-broken log structuring BOTH errors, captured: {captured:?}"
2514 );
2515 assert!(
2517 span_records.iter().any(|line| {
2518 line.contains("error=")
2519 && line.contains("delegate-broken")
2520 && !line.contains("original-err")
2521 }),
2522 "expected span error record carrying the DELEGATE error, span records: {span_records:?}"
2523 );
2524 }
2525
2526 #[tokio::test]
2527 async fn retry_exhausted_then_delegate_failure_propagates_original() {
2528 ensure_global_registry();
2531 let policy = ExceptionPolicy {
2532 matches: std::sync::Arc::new(|_| true),
2533 retry: Some(RedeliveryPolicy {
2534 max_attempts: 1,
2535 initial_delay: Duration::from_millis(1),
2536 multiplier: 1.0,
2537 max_delay: Duration::from_millis(10),
2538 jitter_factor: 0.0,
2539 }),
2540 handled_by: None,
2541 on_steps: None,
2542 disposition: ExceptionDisposition::Handled,
2543 };
2544 let svc = ErrorHandlerService::new(
2545 failing_processor(),
2546 Some(failing_delegate()),
2547 vec![(policy, None)],
2548 );
2549 let result = svc.oneshot(make_exchange()).await;
2550 assert!(
2551 matches!(&result, Err(CamelError::ProcessorError(m)) if m == "boom"),
2552 "retry-exhausted ORIGINAL error must surface as Err, got: {:?}",
2553 result.map(|ex| ex.has_error())
2554 );
2555 }
2556
2557 #[tokio::test]
2558 async fn on_steps_fallback_delegate_failure_propagates_original() {
2559 ensure_global_registry();
2562 let policy = ExceptionPolicy {
2566 matches: std::sync::Arc::new(|_| true),
2567 retry: None,
2568 handled_by: None,
2569 on_steps: Some(SyncBoxProcessor::new(failing_processor())),
2570 disposition: ExceptionDisposition::Handled,
2571 };
2572 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(failing_delegate()))]);
2573 let result = handler
2574 .handle_step(
2575 Some(PolicyId(0)),
2576 make_exchange(),
2577 CamelError::ProcessorError("original-err".into()),
2578 )
2579 .await;
2580 assert_propagates_original(&result);
2581 }
2582
2583 #[tokio::test]
2584 async fn no_match_dlc_delegate_failure_propagates_original() {
2585 ensure_global_registry();
2588 let policy = ExceptionPolicy::new(|e| matches!(e, CamelError::Io(_)));
2592 let svc = ErrorHandlerService::new(
2593 failing_processor(),
2594 Some(failing_delegate()),
2595 vec![(policy, None)],
2596 );
2597 let result = svc.oneshot(make_exchange()).await;
2598 assert!(
2599 matches!(&result, Err(CamelError::ProcessorError(m)) if m == "boom"),
2600 "no-match DLC delegate failure must surface the ORIGINAL error as Err, got: {:?}",
2601 result.map(|ex| ex.has_error())
2602 );
2603 }
2604
2605 #[tokio::test]
2606 async fn delegate_ready_failure_propagates_original() {
2607 ensure_global_registry();
2610 let not_ready: BoxProcessor = BoxProcessor::new(ReadinessFailService::new(
2611 CamelError::ProcessorError("delegate-not-ready".into()),
2612 ));
2613 let handler = handled_policy_with(Some(not_ready));
2614 let result = handler
2615 .handle_step(
2616 Some(PolicyId(0)),
2617 make_exchange(),
2618 CamelError::ProcessorError("original-err".into()),
2619 )
2620 .await;
2621 assert_propagates_original(&result);
2622 }
2623
2624 #[tokio::test]
2625 async fn delegate_failure_with_continued_propagates_original() {
2626 ensure_global_registry();
2629 let policy = ExceptionPolicy {
2630 matches: std::sync::Arc::new(|_| true),
2631 retry: None,
2632 handled_by: None,
2633 on_steps: None,
2634 disposition: ExceptionDisposition::Continued,
2635 };
2636 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(failing_delegate()))]);
2637 let result = handler
2638 .handle_step(
2639 Some(PolicyId(0)),
2640 make_exchange(),
2641 CamelError::ProcessorError("original-err".into()),
2642 )
2643 .await;
2644 assert_propagates_original(&result);
2645 }
2646
2647 #[tokio::test]
2648 async fn boundary_delegate_failure_returns_original_err() {
2649 ensure_global_registry();
2652 let handler = DefaultRouteErrorHandler::new(Some(failing_delegate()), vec![]);
2653 let result = handler
2654 .handle_boundary(
2655 BoundaryKind::Security,
2656 make_exchange(),
2657 CamelError::Unauthorized("denied".into()),
2658 )
2659 .await;
2660 assert!(
2661 matches!(&result, Err(CamelError::Unauthorized(m)) if m == "denied"),
2662 "boundary delegate failure must return the ORIGINAL boundary error, got: {:?}",
2663 result
2664 );
2665 }
2666
2667 #[tokio::test]
2668 async fn tap_policy_without_handled_propagates() {
2669 let delegate_hits = Arc::new(AtomicU32::new(0));
2673 let hits = Arc::clone(&delegate_hits);
2674 let tap_delegate = BoxProcessor::from_fn(move |ex: Exchange| {
2675 let h = Arc::clone(&hits);
2676 Box::pin(async move {
2677 h.fetch_add(1, Ordering::SeqCst);
2678 Ok(ex)
2679 })
2680 });
2681 let policy = ExceptionPolicy {
2682 matches: std::sync::Arc::new(|_| true),
2683 retry: None,
2684 handled_by: None,
2685 on_steps: None,
2686 disposition: ExceptionDisposition::Propagate,
2687 };
2688 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(tap_delegate))]);
2689 let result = handler
2690 .handle_step(
2691 Some(PolicyId(0)),
2692 make_exchange(),
2693 CamelError::ProcessorError("original-err".into()),
2694 )
2695 .await;
2696 assert_propagates_original(&result);
2697 assert_eq!(
2698 delegate_hits.load(Ordering::SeqCst),
2699 1,
2700 "delegate must have received the exchange exactly once"
2701 );
2702 }
2703
2704 #[test]
2705 fn test_handle_step_no_match_emits_silent_propagate_diagnostic() {
2706 let handler = DefaultRouteErrorHandler::new(None, vec![]);
2709 let (result, captured) = capture_debugs(|| {
2710 tokio::runtime::Builder::new_current_thread()
2711 .enable_all()
2712 .build()
2713 .expect("current-thread runtime")
2714 .block_on(handler.handle_step(
2715 None,
2716 make_exchange(),
2717 CamelError::Unauthorized("denied".into()),
2718 ))
2719 });
2720 assert!(result.is_ok(), "step handler always returns Ok");
2721 assert!(
2722 captured.iter().any(|line| {
2723 line.contains(
2724 "no on_exceptions policy matched and no dead-letter channel configured; \
2725 propagating error",
2726 )
2727 }),
2728 "expected silent-propagate diagnostic, captured: {captured:?}"
2729 );
2730 assert!(
2731 captured
2732 .iter()
2733 .any(|line| line.contains("kind=Unauthorized")),
2734 "diagnostic should name the error kind, captured: {captured:?}"
2735 );
2736 }
2737
2738 #[test]
2739 fn test_handle_boundary_no_match_emits_silent_propagate_diagnostic() {
2740 let handler = DefaultRouteErrorHandler::new(None, vec![]);
2741 let (result, captured) = capture_debugs(|| {
2742 tokio::runtime::Builder::new_current_thread()
2743 .enable_all()
2744 .build()
2745 .expect("current-thread runtime")
2746 .block_on(handler.handle_boundary(
2747 BoundaryKind::Security,
2748 make_exchange(),
2749 CamelError::Unauthorized("denied".into()),
2750 ))
2751 });
2752 assert!(result.is_ok(), "boundary handler always returns Ok");
2753 assert!(
2754 captured.iter().any(|line| {
2755 line.contains(
2756 "no on_exceptions policy matched and no dead-letter channel configured; \
2757 propagating error",
2758 )
2759 }),
2760 "expected silent-propagate diagnostic, captured: {captured:?}"
2761 );
2762 assert!(
2763 captured.iter().any(
2764 |line| line.contains("boundary=Security") && line.contains("kind=Unauthorized")
2765 ),
2766 "diagnostic should name the boundary gate and error kind, captured: {captured:?}"
2767 );
2768 }
2769
2770 use crate::test_log_capture::{capture_debugs_with_span_records, ensure_global_registry};
2777
2778 fn capture_debugs<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
2780 let (out, events, _span_records) = capture_debugs_with_span_records(f);
2781 (out, events)
2782 }
2783}