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
18async fn execute_on_steps(
19 original: Exchange,
20 original_err: CamelError,
21 on_steps: &SyncBoxProcessor,
22 disposition: ExceptionDisposition,
23 handler: Option<BoxProcessor>,
24) -> Result<Exchange, CamelError> {
25 let snapshot = original.branch_clone();
26 let mut ex = original;
27 ex.set_error(original_err.clone());
28 let mut pipeline = on_steps.clone_inner();
29 let step_result = async {
30 let svc = pipeline.ready().await?;
31 svc.call(ex).await
32 }
33 .await;
34
35 match step_result {
36 Ok(mut ex) => {
37 if disposition == ExceptionDisposition::Handled {
38 ex.handle_error();
39 Ok(ex)
40 } else {
41 Err(original_err)
44 }
45 }
46 Err(_) => {
47 tracing::warn!(error = %original_err, "on_steps pipeline failed, falling back to handler/DLC");
49 let mut ex = snapshot;
50 ex.set_error(original_err.clone());
51 forward_or_propagate(ex, handler, original_err).await
52 }
53 }
54}
55
56pub async fn invoke_processor(
61 svc: &mut BoxProcessor,
62 ex: Exchange,
63) -> Result<Exchange, CamelError> {
64 match svc.ready().await {
65 Ok(ready) => ready.call(ex).await,
66 Err(err) => Err(err),
67 }
68}
69
70#[async_trait::async_trait]
75pub trait RouteErrorHandler: Send + Sync {
76 fn match_policy(&self, err: &CamelError) -> Option<PolicyId>;
78
79 async fn retry_step(
81 &self,
82 policy: Option<PolicyId>,
83 step: &mut dyn camel_api::error_handler::RetryableStep,
84 original: Exchange,
85 error: CamelError,
86 ) -> RetryOutcome;
87
88 async fn handle_step(
90 &self,
91 policy: Option<PolicyId>,
92 exchange: Exchange,
93 error: CamelError,
94 ) -> Result<StepDisposition, CamelError>;
95
96 async fn handle_boundary(
98 &self,
99 kind: BoundaryKind,
100 exchange: Exchange,
101 error: CamelError,
102 ) -> Result<Exchange, CamelError>;
103}
104
105pub struct DefaultRouteErrorHandler {
111 pub(crate) dlc_producer: Option<SyncBoxProcessor>,
112 pub(crate) policies: Vec<(ExceptionPolicy, Option<SyncBoxProcessor>)>,
113 pub use_original_message: bool,
117}
118
119impl DefaultRouteErrorHandler {
120 pub fn new(
121 dlc_producer: Option<BoxProcessor>,
122 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
123 ) -> Self {
124 Self {
125 dlc_producer: dlc_producer.map(SyncBoxProcessor::new),
126 policies: policies
127 .into_iter()
128 .map(|(p, prod)| (p, prod.map(SyncBoxProcessor::new)))
129 .collect(),
130 use_original_message: false,
131 }
132 }
133
134 pub fn with_use_original_message(mut self, enabled: bool) -> Self {
136 self.use_original_message = enabled;
137 self
138 }
139
140 fn restore_original_message_if_enabled(&self, exchange: &mut Exchange) {
144 if self.use_original_message
145 && let Some(orig) =
146 exchange.get_extension::<camel_api::Message>(camel_api::ORIGINAL_MESSAGE_EXTENSION)
147 {
148 exchange.input = orig.clone();
149
150 let inherited = exchange
155 .get_extension::<OriginalContentTypeInherited>(
156 ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
157 )
158 .is_some_and(|snapshot| snapshot.0);
159 if inherited {
160 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
161 } else {
162 exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
163 }
164 }
165 }
166
167 fn resolve_producer(
170 &self,
171 policy: Option<PolicyId>,
172 ) -> (ExceptionDisposition, Option<BoxProcessor>) {
173 match policy {
174 Some(PolicyId(idx)) => match self.policies.get(idx) {
175 Some((p, prod)) => (
176 p.disposition,
177 prod.as_ref()
178 .map(|p| p.clone_inner())
179 .or_else(|| self.dlc_producer.as_ref().map(|p| p.clone_inner())),
180 ),
181 None => (
182 ExceptionDisposition::Propagate,
183 self.dlc_producer.as_ref().map(|p| p.clone_inner()),
184 ),
185 },
186 None => (
187 ExceptionDisposition::Propagate,
188 self.dlc_producer.as_ref().map(|p| p.clone_inner()),
189 ),
190 }
191 }
192}
193
194#[async_trait::async_trait]
195impl RouteErrorHandler for DefaultRouteErrorHandler {
196 fn match_policy(&self, err: &CamelError) -> Option<PolicyId> {
197 self.policies
198 .iter()
199 .position(|(p, _)| (p.matches)(err))
200 .map(PolicyId)
201 }
202
203 async fn retry_step(
204 &self,
205 policy: Option<PolicyId>,
206 step: &mut dyn camel_api::error_handler::RetryableStep,
207 original: Exchange,
208 error: CamelError,
209 ) -> RetryOutcome {
210 let Some(PolicyId(idx)) = policy else {
211 return RetryOutcome::Exhausted {
212 exchange: original,
213 error,
214 policy: None,
215 };
216 };
217 let Some((policy_def, _)) = self.policies.get(idx) else {
218 return RetryOutcome::Exhausted {
219 exchange: original,
220 error,
221 policy,
222 };
223 };
224 let Some(ref backoff) = policy_def.retry else {
225 return RetryOutcome::Exhausted {
226 exchange: original,
227 error,
228 policy,
229 };
230 };
231
232 for attempt in 0..backoff.max_attempts {
233 let delay = backoff.delay_for(attempt);
234 tokio::time::sleep(delay).await;
235
236 let mut ex = original.branch_clone();
237 ex.input.set_header(HEADER_REDELIVERED, Value::Bool(true));
238 ex.input.set_header(
239 HEADER_REDELIVERY_COUNTER,
240 Value::Number((attempt + 1).into()),
241 );
242 ex.input.set_header(
243 HEADER_REDELIVERY_MAX_COUNTER,
244 Value::Number(backoff.max_attempts.into()),
245 );
246
247 match step.invoke(ex).await {
248 PipelineOutcome::Completed(exchange) => {
249 return RetryOutcome::Recovered(exchange);
250 }
251 PipelineOutcome::Stopped(stopped_ex) => {
252 return RetryOutcome::Stopped(stopped_ex);
253 }
254 PipelineOutcome::Failed(retry_err) => {
255 if attempt + 1 == backoff.max_attempts {
256 let mut final_ex = original;
257 final_ex
258 .input
259 .set_header(HEADER_REDELIVERED, Value::Bool(true));
260 final_ex.input.set_header(
261 HEADER_REDELIVERY_COUNTER,
262 Value::Number(backoff.max_attempts.into()),
263 );
264 final_ex.input.set_header(
265 HEADER_REDELIVERY_MAX_COUNTER,
266 Value::Number(backoff.max_attempts.into()),
267 );
268 return RetryOutcome::Exhausted {
269 exchange: final_ex,
270 error: retry_err,
271 policy,
272 };
273 }
274 }
275 }
276 }
277
278 RetryOutcome::Exhausted {
279 exchange: original,
280 error,
281 policy,
282 }
283 }
284
285 async fn handle_step(
286 &self,
287 policy: Option<PolicyId>,
288 mut exchange: Exchange,
289 error: CamelError,
290 ) -> Result<StepDisposition, CamelError> {
291 let (disposition, producer) = self.resolve_producer(policy);
292
293 if policy.is_none() && producer.is_none() {
299 tracing::debug!(
300 kind = %error.variant_name(),
301 "no on_exceptions policy matched and no dead-letter channel configured; propagating error"
302 );
303 }
304
305 if !matches!(disposition, ExceptionDisposition::Propagate)
310 && let Some(PolicyId(idx)) = policy
311 && let Some((p, _)) = self.policies.get(idx)
312 && let Some(ref steps) = p.on_steps
313 {
314 let snapshot = exchange.branch_clone();
315 exchange.set_error(error.clone());
316 let mut step_pipeline = steps.clone_inner();
317 let step_result = async {
318 let svc = step_pipeline.ready().await?;
319 svc.call(exchange).await
320 }
321 .await;
322 match step_result {
323 Ok(mut ex) => match disposition {
324 ExceptionDisposition::Handled => {
325 ex.handle_error();
326 return Ok(StepDisposition::Handled(ex));
327 }
328 ExceptionDisposition::Continued => {
329 ex.clear_error();
330 return Ok(StepDisposition::Continued(ex));
331 }
332 _ => {
335 exchange = snapshot;
336 }
337 },
338 Err(_) => {
339 exchange = snapshot;
340 }
341 }
342 }
343
344 self.restore_original_message_if_enabled(&mut exchange);
347 exchange.set_error(error.clone());
348 match send_to_handler(exchange, producer).await {
349 Ok(handler_ex) => match disposition {
350 ExceptionDisposition::Handled => {
351 let mut ex = handler_ex;
352 ex.clear_error();
353 Ok(StepDisposition::Handled(ex))
354 }
355 ExceptionDisposition::Continued => {
356 let mut ex = handler_ex;
357 ex.clear_error();
358 Ok(StepDisposition::Continued(ex))
359 }
360 _ => Ok(StepDisposition::Propagate(error)),
362 },
363 Err(_delegate) => Ok(StepDisposition::Propagate(error)),
367 }
368 }
369
370 async fn handle_boundary(
371 &self,
372 boundary_kind: BoundaryKind,
373 mut exchange: Exchange,
374 error: CamelError,
375 ) -> Result<Exchange, CamelError> {
376 let policy = self.match_policy(&error);
382 let (disposition, producer) = self.resolve_producer(policy);
383
384 if policy.is_none() && producer.is_none() {
391 tracing::debug!(
392 boundary = ?boundary_kind,
393 kind = %error.variant_name(),
394 "no on_exceptions policy matched and no dead-letter channel configured; propagating error"
395 );
396 }
397
398 if !matches!(
404 disposition,
405 ExceptionDisposition::Propagate | ExceptionDisposition::Continued
406 ) && let Some(PolicyId(idx)) = policy
407 && let Some((p, _)) = self.policies.get(idx)
408 && let Some(ref steps) = p.on_steps
409 {
410 let snapshot = exchange.branch_clone();
411 exchange.set_error(error.clone());
412 let mut step_pipeline = steps.clone_inner();
413 let step_result = async {
414 let svc = step_pipeline.ready().await?;
415 svc.call(exchange).await
416 }
417 .await;
418 match step_result {
419 Ok(mut ex) => match disposition {
420 ExceptionDisposition::Handled => {
421 ex.handle_error();
422 return Ok(ex);
423 }
424 _ => {
426 exchange = snapshot;
427 }
428 },
429 Err(_) => {
430 exchange = snapshot;
431 }
432 }
433 }
434
435 self.restore_original_message_if_enabled(&mut exchange);
437 exchange.set_error(error.clone());
438 match send_to_handler(exchange, producer).await {
439 Ok(handler_ex) => match disposition {
440 ExceptionDisposition::Handled => {
441 let mut ex = handler_ex;
442 ex.clear_error();
443 Ok(ex)
444 }
445 _ => {
447 let mut ex = handler_ex;
448 ex.set_error(error);
449 Ok(ex)
450 }
451 },
452 Err(_delegate) => Err(error),
456 }
457 }
458}
459
460pub struct ErrorHandlerLayer {
464 dlc_producer: Option<BoxProcessor>,
466 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
468}
469
470impl ErrorHandlerLayer {
471 pub fn new(
473 dlc_producer: Option<BoxProcessor>,
474 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
475 ) -> Self {
476 Self {
477 dlc_producer,
478 policies,
479 }
480 }
481}
482
483impl<S> Layer<S> for ErrorHandlerLayer
484where
485 S: Service<Exchange, Response = Exchange, Error = CamelError> + Send + Clone + 'static,
486 S::Future: Send + 'static,
487{
488 type Service = ErrorHandlerService<S>;
489
490 fn layer(&self, inner: S) -> Self::Service {
491 ErrorHandlerService {
492 inner,
493 dlc_producer: self.dlc_producer.clone(),
494 policies: self
495 .policies
496 .iter()
497 .map(|(p, prod)| (p.clone(), prod.clone()))
498 .collect(),
499 }
500 }
501}
502
503pub struct ErrorHandlerService<S> {
511 inner: S,
512 dlc_producer: Option<BoxProcessor>,
513 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
514}
515
516impl<S: Clone> Clone for ErrorHandlerService<S> {
517 fn clone(&self) -> Self {
518 Self {
519 inner: self.inner.clone(),
520 dlc_producer: self.dlc_producer.clone(),
521 policies: self
522 .policies
523 .iter()
524 .map(|(p, prod)| (p.clone(), prod.clone()))
525 .collect(),
526 }
527 }
528}
529
530impl<S> ErrorHandlerService<S>
531where
532 S: Service<Exchange, Response = Exchange, Error = CamelError> + Send + Clone + 'static,
533 S::Future: Send + 'static,
534{
535 pub fn new(
537 inner: S,
538 dlc_producer: Option<BoxProcessor>,
539 policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)>,
540 ) -> Self {
541 Self {
542 inner,
543 dlc_producer,
544 policies,
545 }
546 }
547}
548
549impl<S> Service<Exchange> for ErrorHandlerService<S>
550where
551 S: Service<Exchange, Response = Exchange, Error = CamelError> + Send + Clone + 'static,
552 S::Future: Send + 'static,
553{
554 type Response = Exchange;
555 type Error = CamelError;
556 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
557
558 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
559 match self.inner.poll_ready(cx) {
564 Poll::Pending => Poll::Pending,
565 Poll::Ready(Err(_)) => Poll::Ready(Ok(())),
566 Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
567 }
568 }
569
570 fn call(&mut self, exchange: Exchange) -> Self::Future {
571 let mut inner = self.inner.clone();
572 let dlc = self.dlc_producer.clone();
573 let policies: Vec<(ExceptionPolicy, Option<BoxProcessor>)> = self
574 .policies
575 .iter()
576 .map(|(p, prod)| (p.clone(), prod.clone()))
577 .collect();
578
579 Box::pin(async move {
580 let original = exchange.branch_clone();
581 let result = match inner.ready().await {
582 Ok(svc) => svc.call(exchange).await,
583 Err(e) => Err(e), };
585
586 let err = match result {
587 Ok(ex) => return Ok(ex),
588 Err(e) => e,
589 };
590
591 let matched = policies.into_iter().find(|(p, _)| (p.matches)(&err));
593
594 if let Some((policy, policy_producer)) = matched {
595 if let Some(ref backoff) = policy.retry {
597 for attempt in 0..backoff.max_attempts {
598 let delay = backoff.delay_for(attempt);
599 tokio::time::sleep(delay).await;
600
601 let mut ex = original.branch_clone();
603 ex.input.set_header(HEADER_REDELIVERED, Value::Bool(true));
604 ex.input.set_header(
605 HEADER_REDELIVERY_COUNTER,
606 Value::Number((attempt + 1).into()),
607 );
608 ex.input.set_header(
609 HEADER_REDELIVERY_MAX_COUNTER,
610 Value::Number(backoff.max_attempts.into()),
611 );
612
613 let result = match inner.ready().await {
614 Ok(svc) => svc.call(ex).await,
615 Err(e) => Err(e), };
617 match result {
618 Ok(ex) => return Ok(ex),
619 Err(retry_err) => {
620 if attempt + 1 == backoff.max_attempts {
621 let mut original = original.branch_clone();
623 original
624 .input
625 .set_header(HEADER_REDELIVERED, Value::Bool(true));
626 original.input.set_header(
627 HEADER_REDELIVERY_COUNTER,
628 Value::Number(backoff.max_attempts.into()),
629 );
630 original.input.set_header(
631 HEADER_REDELIVERY_MAX_COUNTER,
632 Value::Number(backoff.max_attempts.into()),
633 );
634 if let Some(ref steps) = policy.on_steps {
635 let handler = policy_producer.clone().or(dlc.clone());
636 return execute_on_steps(
637 original,
638 retry_err,
639 steps,
640 policy.disposition,
641 handler,
642 )
643 .await;
644 }
645 original.set_error(retry_err.clone());
646 let handler = policy_producer.or(dlc);
647 return forward_or_propagate(original, handler, retry_err)
648 .await;
649 }
650 }
651 }
652 }
653 }
654 if let Some(ref steps) = policy.on_steps {
656 let handler = policy_producer.or(dlc);
657 return execute_on_steps(original, err, steps, policy.disposition, handler)
658 .await;
659 }
660 let mut ex = original.branch_clone();
661 ex.set_error(err.clone());
662 let handler = policy_producer.or(dlc);
663 forward_or_propagate(ex, handler, err).await
664 } else {
665 let mut ex = original;
667 ex.set_error(err.clone());
668 forward_or_propagate(ex, dlc, err).await
669 }
670 })
671 }
672}
673
674pub(crate) fn record_span_error(delegate_err: &CamelError) {
681 let span = tracing::Span::current();
682 if !span.is_none() {
683 span.record("error", tracing::field::display(delegate_err));
684 }
685}
686
687async fn forward_or_propagate(
695 exchange: Exchange,
696 producer: Option<BoxProcessor>,
697 original_error: CamelError,
698) -> Result<Exchange, CamelError> {
699 match send_to_handler(exchange, producer).await {
700 Ok(ex) => Ok(ex),
701 Err(_delegate) => Err(original_error),
702 }
703}
704
705async fn send_to_handler(
706 exchange: Exchange,
707 producer: Option<BoxProcessor>,
708) -> Result<Exchange, CamelError> {
709 match producer {
710 None => {
711 tracing::error!(
713 error = ?exchange.error,
714 "Exchange failed with no error handler configured"
715 );
716 Ok(exchange)
717 }
718 Some(mut prod) => match prod.ready().await {
719 Err(e) => {
720 tracing::error!(
725 original_error = ?exchange.error,
726 delegate_error = %e,
727 "DLC/handler not ready"
728 );
729 record_span_error(&e);
730 Err(e)
731 }
732 Ok(svc) => match svc.call(exchange.branch_clone()).await {
733 Ok(ex) => Ok(ex),
734 Err(e) => {
735 tracing::error!(
740 original_error = ?exchange.error,
741 delegate_error = %e,
742 "DLC/handler call failed"
743 );
744 record_span_error(&e);
745 Err(e)
748 }
749 },
750 },
751 }
752}
753
754#[cfg(test)]
755mod tests {
756 use super::*;
757 use camel_api::{
758 BoxProcessor, BoxProcessorExt, CamelError, Exchange, Message, OutcomePipeline,
759 OutcomeSegment, PipelineOutcome, RetryableStep, SyncBoxProcessor, Value,
760 error_handler::RedeliveryPolicy,
761 };
762 use std::future::Future;
763 use std::pin::Pin;
764 use std::sync::{
765 Arc,
766 atomic::{AtomicU32, Ordering},
767 };
768 use std::time::Duration;
769 use tower::ServiceExt;
770
771 fn make_exchange() -> Exchange {
772 Exchange::new(Message::new("test"))
773 }
774
775 fn failing_processor() -> BoxProcessor {
776 BoxProcessor::from_fn(|_ex| {
777 Box::pin(async { Err(CamelError::ProcessorError("boom".into())) })
778 })
779 }
780
781 fn ok_processor() -> BoxProcessor {
782 BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }))
783 }
784
785 fn fail_n_times(n: u32) -> BoxProcessor {
786 let count = Arc::new(AtomicU32::new(0));
787 BoxProcessor::from_fn(move |ex| {
788 let count = Arc::clone(&count);
789 Box::pin(async move {
790 let c = count.fetch_add(1, Ordering::SeqCst);
791 if c < n {
792 Err(CamelError::ProcessorError(format!("attempt {c}")))
793 } else {
794 Ok(ex)
795 }
796 })
797 })
798 }
799
800 #[tokio::test]
801 async fn test_ok_passthrough() {
802 let svc = ErrorHandlerService::new(ok_processor(), None, vec![]);
803 let result = svc.oneshot(make_exchange()).await;
804 assert!(result.is_ok());
805 assert!(!result.unwrap().has_error());
806 }
807
808 #[tokio::test]
809 async fn test_error_goes_to_dlc() {
810 let received = Arc::new(std::sync::Mutex::new(Vec::<Exchange>::new()));
811 let received_clone = Arc::clone(&received);
812 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
813 let r = Arc::clone(&received_clone);
814 Box::pin(async move {
815 r.lock().unwrap().push(ex.clone());
816 Ok(ex)
817 })
818 });
819
820 let svc = ErrorHandlerService::new(failing_processor(), Some(dlc), vec![]);
821 let result = svc.oneshot(make_exchange()).await;
822 assert!(result.is_ok());
823 let ex = result.unwrap();
824 assert!(ex.has_error());
825 assert_eq!(received.lock().unwrap().len(), 1);
826 }
827
828 #[tokio::test]
829 async fn test_retry_recovers() {
830 let inner = fail_n_times(2);
831 let policy = ExceptionPolicy {
832 matches: Arc::new(|_| true),
833 retry: Some(RedeliveryPolicy {
834 max_attempts: 3,
835 initial_delay: Duration::from_millis(1),
836 multiplier: 1.0,
837 max_delay: Duration::from_millis(10),
838 jitter_factor: 0.0,
839 }),
840 handled_by: None,
841 on_steps: None,
842 disposition: ExceptionDisposition::Propagate,
843 };
844 let svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
845 let result = svc.oneshot(make_exchange()).await;
846 assert!(result.is_ok());
847 assert!(!result.unwrap().has_error());
848 }
849
850 #[tokio::test]
851 async fn test_retry_exhausted_goes_to_dlc() {
852 let inner = fail_n_times(10);
853 let received = Arc::new(std::sync::Mutex::new(0u32));
854 let received_clone = Arc::clone(&received);
855 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
856 let r = Arc::clone(&received_clone);
857 Box::pin(async move {
858 *r.lock().unwrap() += 1;
859 Ok(ex)
860 })
861 });
862 let policy = ExceptionPolicy {
863 matches: Arc::new(|_| true),
864 retry: Some(RedeliveryPolicy {
865 max_attempts: 2,
866 initial_delay: Duration::from_millis(1),
867 multiplier: 1.0,
868 max_delay: Duration::from_millis(10),
869 jitter_factor: 0.0,
870 }),
871 handled_by: None,
872 on_steps: None,
873 disposition: ExceptionDisposition::Propagate,
874 };
875 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![(policy, None)]);
876 let result = svc.oneshot(make_exchange()).await;
877 assert!(result.is_ok());
878 assert!(result.unwrap().has_error());
879 assert_eq!(*received.lock().unwrap(), 1);
880 }
881
882 #[test]
883 fn test_poll_ready_delegates_to_inner() {
884 use std::sync::atomic::AtomicBool;
885
886 #[derive(Clone)]
888 struct DelayedReadyService {
889 ready: Arc<AtomicBool>,
890 }
891
892 impl Service<Exchange> for DelayedReadyService {
893 type Response = Exchange;
894 type Error = CamelError;
895 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
896
897 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
898 if self.ready.fetch_or(true, Ordering::SeqCst) {
899 Poll::Ready(Ok(()))
901 } else {
902 cx.waker().wake_by_ref();
904 Poll::Pending
905 }
906 }
907
908 fn call(&mut self, ex: Exchange) -> Self::Future {
909 Box::pin(async move { Ok(ex) })
910 }
911 }
912
913 let waker = futures::task::noop_waker();
914 let mut cx = Context::from_waker(&waker);
915
916 let inner = DelayedReadyService {
917 ready: Arc::new(AtomicBool::new(false)),
918 };
919 let mut svc = ErrorHandlerService::new(inner, None, vec![]);
920
921 let first = Pin::new(&mut svc).poll_ready(&mut cx);
923 assert!(first.is_pending(), "expected Pending on first poll_ready");
924
925 let second = Pin::new(&mut svc).poll_ready(&mut cx);
927 assert!(second.is_ready(), "expected Ready on second poll_ready");
928 }
929
930 #[tokio::test]
931 async fn test_no_matching_policy_uses_dlc() {
932 let received = Arc::new(std::sync::Mutex::new(0u32));
933 let received_clone = Arc::clone(&received);
934 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
935 let r = Arc::clone(&received_clone);
936 Box::pin(async move {
937 *r.lock().unwrap() += 1;
938 Ok(ex)
939 })
940 });
941 let policy = ExceptionPolicy::new(|e| matches!(e, CamelError::Io(_)));
942 let svc = ErrorHandlerService::new(failing_processor(), Some(dlc), vec![(policy, None)]);
943 let result = svc.oneshot(make_exchange()).await;
944 assert!(result.is_ok());
945 assert_eq!(*received.lock().unwrap(), 1);
946 }
947
948 #[tokio::test]
949 async fn test_redelivery_headers_are_set() {
950 use camel_api::error_handler::{
951 HEADER_REDELIVERED, HEADER_REDELIVERY_COUNTER, HEADER_REDELIVERY_MAX_COUNTER,
952 RedeliveryPolicy,
953 };
954
955 let inner = fail_n_times(10);
956 let received = Arc::new(std::sync::Mutex::new(None));
957 let received_clone = Arc::clone(&received);
958 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
959 let r = Arc::clone(&received_clone);
960 Box::pin(async move {
961 *r.lock().unwrap() = Some(ex.clone());
962 Ok(ex)
963 })
964 });
965
966 let policy = ExceptionPolicy {
967 matches: Arc::new(|_| true),
968 retry: Some(RedeliveryPolicy {
969 max_attempts: 2,
970 initial_delay: Duration::from_millis(1),
971 multiplier: 1.0,
972 max_delay: Duration::from_millis(10),
973 jitter_factor: 0.0,
974 }),
975 handled_by: None,
976 on_steps: None,
977 disposition: ExceptionDisposition::Propagate,
978 };
979
980 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![(policy, None)]);
981 let _ = svc.oneshot(make_exchange()).await.unwrap();
982
983 let ex = received.lock().unwrap().take().unwrap();
984 assert_eq!(
985 ex.input.header(HEADER_REDELIVERED),
986 Some(&Value::Bool(true))
987 );
988 assert_eq!(
989 ex.input.header(HEADER_REDELIVERY_COUNTER),
990 Some(&Value::Number(2.into()))
991 );
992 assert_eq!(
993 ex.input.header(HEADER_REDELIVERY_MAX_COUNTER),
994 Some(&Value::Number(2.into()))
995 );
996 }
997
998 #[tokio::test]
999 async fn test_jitter_produces_varying_delays_in_retry_flow() {
1000 use std::time::Instant;
1001
1002 let inner = fail_n_times(10);
1003 let received = Arc::new(std::sync::Mutex::new(None));
1004 let received_clone = Arc::clone(&received);
1005 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1006 let r = Arc::clone(&received_clone);
1007 Box::pin(async move {
1008 *r.lock().unwrap() = Some(ex.clone());
1009 Ok(ex)
1010 })
1011 });
1012
1013 let policy = ExceptionPolicy {
1014 matches: Arc::new(|_| true),
1015 retry: Some(RedeliveryPolicy {
1016 max_attempts: 5,
1017 initial_delay: Duration::from_millis(20),
1018 multiplier: 1.0,
1019 max_delay: Duration::from_millis(100),
1020 jitter_factor: 0.5,
1021 }),
1022 handled_by: None,
1023 on_steps: None,
1024 disposition: ExceptionDisposition::Propagate,
1025 };
1026
1027 let start = Instant::now();
1028 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![(policy, None)]);
1029 let _ = svc.oneshot(make_exchange()).await.unwrap();
1030 let elapsed = start.elapsed();
1031
1032 assert!(
1033 received.lock().unwrap().is_some(),
1034 "DLC should have received exchange"
1035 );
1036
1037 assert!(
1038 elapsed >= Duration::from_millis(50),
1039 "5 retries with 20ms base delay should take at least 50ms (with jitter low bound)"
1040 );
1041
1042 assert!(
1043 elapsed <= Duration::from_millis(500),
1044 "5 retries with 20ms base delay + 50% jitter should not exceed 500ms"
1045 );
1046 }
1047
1048 #[tokio::test]
1049 async fn test_on_steps_handled_true_consumes_error() {
1050 use tower::ServiceExt;
1051
1052 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1053 ex.input.body = camel_api::Body::Bytes("handled".into());
1054 async move { Ok(ex) }
1055 }));
1056 let policy = ExceptionPolicy {
1057 matches: Arc::new(|_| true),
1058 retry: None,
1059 handled_by: None,
1060 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1061 disposition: ExceptionDisposition::Handled,
1062 };
1063 let inner = tower::service_fn(|_ex: Exchange| async {
1064 Err::<Exchange, CamelError>(CamelError::RouteError("fail".to_string()))
1065 });
1066 let mut svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1067 let ex = Exchange::default();
1068 let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1069 assert!(result.error.is_none(), "handled:true should clear error");
1070 assert!(matches!(result.input.body, camel_api::Body::Bytes(_)));
1071 }
1072
1073 #[tokio::test]
1074 async fn test_on_steps_handled_false_propagates_error() {
1075 use tower::ServiceExt;
1076
1077 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1078 ex.input.body = camel_api::Body::Bytes("handled".into());
1079 async move { Ok(ex) }
1080 }));
1081 let policy = ExceptionPolicy {
1082 matches: Arc::new(|_| true),
1083 retry: None,
1084 handled_by: None,
1085 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1086 disposition: ExceptionDisposition::Propagate,
1087 };
1088 let inner = tower::service_fn(|_ex: Exchange| async {
1089 Err::<Exchange, CamelError>(CamelError::RouteError("fail".to_string()))
1090 });
1091 let mut svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1092 let ex = Exchange::default();
1093 let result = svc.ready().await.unwrap().call(ex).await;
1094 assert!(result.is_err(), "handled:false should propagate error");
1095 }
1096
1097 #[derive(Clone)]
1105 struct ReadinessFailService {
1106 error: CamelError,
1107 }
1108
1109 impl ReadinessFailService {
1110 fn new(error: CamelError) -> Self {
1111 Self { error }
1112 }
1113 }
1114
1115 impl Service<Exchange> for ReadinessFailService {
1116 type Response = Exchange;
1117 type Error = CamelError;
1118 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1119
1120 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1121 Poll::Ready(Err(self.error.clone()))
1122 }
1123
1124 fn call(&mut self, ex: Exchange) -> Self::Future {
1125 Box::pin(async move { Ok(ex) })
1128 }
1129 }
1130
1131 #[tokio::test]
1132 async fn test_readiness_error_goes_to_dlc() {
1133 let readiness_err = CamelError::ProcessorError("readiness-fail".into());
1134 let inner = ReadinessFailService {
1135 error: readiness_err,
1136 };
1137
1138 let received = Arc::new(std::sync::Mutex::new(Vec::<Exchange>::new()));
1139 let received_clone = Arc::clone(&received);
1140 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1141 let r = Arc::clone(&received_clone);
1142 Box::pin(async move {
1143 r.lock().unwrap().push(ex.clone());
1144 Ok(ex)
1145 })
1146 });
1147
1148 let svc = ErrorHandlerService::new(inner, Some(dlc), vec![]);
1149 let result = svc.oneshot(make_exchange()).await;
1150
1151 assert!(
1153 result.is_ok(),
1154 "readiness error should be captured and sent to DLC, got: {:?}",
1155 result
1156 );
1157 let ex = result.unwrap();
1158 assert!(ex.has_error(), "exchange should carry the readiness error");
1159 assert_eq!(
1160 received.lock().unwrap().len(),
1161 1,
1162 "DLC should have received the exchange exactly once"
1163 );
1164 }
1165
1166 #[tokio::test]
1167 async fn test_readiness_error_goes_to_matching_policy() {
1168 let readiness_err = CamelError::ProcessorError("readiness-fail".into());
1169 let inner = ReadinessFailService {
1170 error: readiness_err,
1171 };
1172
1173 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1174 ex.input.body = camel_api::Body::Bytes("handled-readiness".into());
1175 async move { Ok(ex) }
1176 }));
1177 let policy = ExceptionPolicy {
1178 matches: Arc::new(|_| true),
1179 retry: None,
1180 handled_by: None,
1181 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1182 disposition: ExceptionDisposition::Handled,
1183 };
1184
1185 let svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1186 let result = svc.oneshot(make_exchange()).await;
1187
1188 assert!(
1190 result.is_ok(),
1191 "readiness error should be captured by policy, got: {:?}",
1192 result
1193 );
1194 let ex = result.unwrap();
1195 assert!(ex.error.is_none(), "handled:true should clear error");
1196 assert!(
1197 matches!(ex.input.body, camel_api::Body::Bytes(_)),
1198 "on_steps should have modified the body"
1199 );
1200 }
1201
1202 #[test]
1203 fn test_poll_ready_converts_readiness_error_to_ok() {
1204 let readiness_err = CamelError::ProcessorError("readiness-fail".into());
1205 let inner = ReadinessFailService {
1206 error: readiness_err,
1207 };
1208 let mut svc = ErrorHandlerService::new(inner, None, vec![]);
1209
1210 let waker = futures::task::noop_waker();
1211 let mut cx = Context::from_waker(&waker);
1212
1213 let poll = Pin::new(&mut svc).poll_ready(&mut cx);
1215 match poll {
1216 Poll::Ready(Ok(())) => { }
1217 Poll::Ready(Err(e)) => panic!("poll_ready leaked readiness error: {:?}", e),
1218 Poll::Pending => panic!("poll_ready should be Ready for readiness errors"),
1219 }
1220 }
1221
1222 #[tokio::test]
1225 async fn test_invoke_processor_returns_ok_on_success() {
1226 let mut svc = ok_processor();
1227 let ex = make_exchange();
1228 let result = invoke_processor(&mut svc, ex).await;
1229 assert!(result.is_ok());
1230 }
1231
1232 #[tokio::test]
1233 async fn test_invoke_processor_captures_readiness_error() {
1234 let mut failing_ready: BoxProcessor = BoxProcessor::new(ReadinessFailService::new(
1235 CamelError::ProcessorError("not ready".into()),
1236 ));
1237 let ex = make_exchange();
1238 let result = invoke_processor(&mut failing_ready, ex).await;
1239 assert!(result.is_err());
1240 }
1241
1242 #[tokio::test]
1243 async fn test_on_steps_handled_true_clears_exception_properties() {
1244 use tower::ServiceExt;
1245
1246 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1247 ex.input.body = camel_api::Body::Bytes("handled".into());
1248 async move { Ok(ex) }
1249 }));
1250 let policy = ExceptionPolicy {
1251 matches: Arc::new(|_| true),
1252 retry: None,
1253 handled_by: None,
1254 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1255 disposition: ExceptionDisposition::Handled,
1256 };
1257 let inner = tower::service_fn(|_ex: Exchange| async {
1258 Err::<Exchange, CamelError>(CamelError::RouteError("fail".to_string()))
1259 });
1260 let mut svc = ErrorHandlerService::new(inner, None, vec![(policy, None)]);
1261 let ex = Exchange::default();
1262 let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1263 assert!(result.error.is_none(), "handled:true should clear error");
1264 assert!(
1265 !result
1266 .properties
1267 .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_MESSAGE),
1268 "handled:true should clear exception properties"
1269 );
1270 assert!(
1271 !result
1272 .properties
1273 .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_KIND),
1274 "handled:true should clear exception kind property"
1275 );
1276 assert!(
1277 !result
1278 .properties
1279 .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_CAUGHT),
1280 "handled:true should clear exception caught property"
1281 );
1282 }
1283
1284 #[test]
1287 fn test_match_policy_returns_id_for_matching_error() {
1288 let handler = DefaultRouteErrorHandler::new(
1289 None,
1290 vec![(
1291 ExceptionPolicy::new(|e| matches!(e, CamelError::ProcessorError(_))),
1292 None,
1293 )],
1294 );
1295 let id = handler.match_policy(&CamelError::ProcessorError("test".into()));
1296 assert_eq!(id, Some(PolicyId(0)));
1297 }
1298
1299 #[test]
1300 fn test_match_policy_returns_none_for_unmatched() {
1301 let handler = DefaultRouteErrorHandler::new(None, vec![]);
1302 let id = handler.match_policy(&CamelError::ProcessorError("test".into()));
1303 assert_eq!(id, None);
1304 }
1305
1306 #[tokio::test]
1309 async fn test_retry_step_succeeds_on_second_attempt() {
1310 let mut policy = ExceptionPolicy::new(|_| true);
1311 policy.retry = Some(RedeliveryPolicy::new(3));
1312 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1313 let mut step = fail_n_times(1); let ex = make_exchange();
1315 let outcome = handler
1316 .retry_step(
1317 Some(PolicyId(0)),
1318 &mut step,
1319 ex,
1320 CamelError::ProcessorError("attempt 0".into()),
1321 )
1322 .await;
1323 assert!(matches!(outcome, RetryOutcome::Recovered(_)));
1324 }
1325
1326 #[tokio::test]
1327 async fn test_retry_step_exhausted_when_all_fail() {
1328 let mut policy = ExceptionPolicy::new(|_| true);
1329 policy.retry = Some(RedeliveryPolicy::new(3));
1330 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1331 let mut step = failing_processor();
1332 let ex = make_exchange();
1333 let outcome = handler
1334 .retry_step(
1335 Some(PolicyId(0)),
1336 &mut step,
1337 ex,
1338 CamelError::ProcessorError("boom".into()),
1339 )
1340 .await;
1341 assert!(matches!(outcome, RetryOutcome::Exhausted { .. }));
1342 }
1343
1344 #[tokio::test]
1345 async fn test_retry_step_no_policy_returns_exhausted_immediately() {
1346 let handler = DefaultRouteErrorHandler::new(None, vec![]);
1347 let mut step = ok_processor();
1348 let ex = make_exchange();
1349 let outcome = handler
1350 .retry_step(
1351 None,
1352 &mut step,
1353 ex,
1354 CamelError::ProcessorError("boom".into()),
1355 )
1356 .await;
1357 assert!(matches!(
1358 outcome,
1359 RetryOutcome::Exhausted { policy: None, .. }
1360 ));
1361 }
1362
1363 #[tokio::test]
1366 async fn test_handle_step_propagate_sends_to_dlc() {
1367 let dlc = BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }));
1368 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1369 let ex = make_exchange();
1370 let result = handler
1371 .handle_step(None, ex, CamelError::ProcessorError("boom".into()))
1372 .await;
1373 assert!(matches!(result, Ok(StepDisposition::Propagate(_))));
1374 }
1375
1376 #[tokio::test]
1377 async fn test_handle_step_handled_uses_handler_output() {
1378 let handler_producer = BoxProcessor::from_fn(|mut ex| {
1379 Box::pin(async move {
1380 ex.input.set_header("processed_by", Value::Bool(true));
1381 Ok(ex)
1382 })
1383 });
1384 let policy = ExceptionPolicy {
1385 matches: std::sync::Arc::new(|_| true),
1386 retry: None,
1387 handled_by: None,
1388 on_steps: None,
1389 disposition: ExceptionDisposition::Handled,
1390 };
1391 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(handler_producer))]);
1392 let mut ex = make_exchange();
1393 ex.set_error(CamelError::ProcessorError("boom".into()));
1394 let result = handler
1395 .handle_step(
1396 Some(PolicyId(0)),
1397 ex,
1398 CamelError::ProcessorError("boom".into()),
1399 )
1400 .await;
1401 match result {
1402 Ok(StepDisposition::Handled(ex)) => {
1403 assert!(!ex.has_error(), "error should be cleared");
1404 assert_eq!(
1405 ex.input.header("processed_by"),
1406 Some(&Value::Bool(true)),
1407 "should use handler's output exchange"
1408 );
1409 }
1410 other => panic!("expected Handled, got {:?}", other.is_ok()),
1411 }
1412 }
1413
1414 #[tokio::test]
1415 async fn test_handle_step_continued_clears_error() {
1416 let policy = ExceptionPolicy {
1417 matches: std::sync::Arc::new(|_| true),
1418 retry: None,
1419 handled_by: None,
1420 on_steps: None,
1421 disposition: ExceptionDisposition::Continued,
1422 };
1423 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1424 let mut ex = make_exchange();
1425 ex.set_error(CamelError::ProcessorError("boom".into()));
1426 let result = handler
1427 .handle_step(
1428 Some(PolicyId(0)),
1429 ex,
1430 CamelError::ProcessorError("boom".into()),
1431 )
1432 .await;
1433 match result {
1434 Ok(StepDisposition::Continued(ex)) => assert!(!ex.has_error()),
1435 other => panic!("expected Continued, got {:?}", other.is_ok()),
1436 }
1437 }
1438
1439 #[tokio::test]
1440 async fn test_handle_step_with_on_steps_handled() {
1441 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1442 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
1443 async move { Ok(ex) }
1444 }));
1445 let policy = ExceptionPolicy {
1446 matches: std::sync::Arc::new(|_| true),
1447 retry: None,
1448 handled_by: None,
1449 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1450 disposition: ExceptionDisposition::Handled,
1451 };
1452 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1453 let mut ex = make_exchange();
1454 ex.set_error(CamelError::ProcessorError("boom".into()));
1455 let result = handler
1456 .handle_step(
1457 Some(PolicyId(0)),
1458 ex,
1459 CamelError::ProcessorError("boom".into()),
1460 )
1461 .await;
1462 match result {
1463 Ok(StepDisposition::Handled(ex)) => {
1464 assert!(!ex.has_error(), "error should be cleared");
1465 assert!(
1466 matches!(ex.input.body, camel_api::Body::Bytes(_)),
1467 "on_steps should have modified the body"
1468 );
1469 }
1470 other => panic!("expected Handled, got: {}", other.is_ok()),
1471 }
1472 }
1473
1474 #[tokio::test]
1475 async fn test_handle_step_dlc_failure_propagates() {
1476 let failing_dlc = BoxProcessor::from_fn(|_| {
1477 Box::pin(async { Err(CamelError::ProcessorError("dlc broken".into())) })
1478 });
1479 let handler = DefaultRouteErrorHandler::new(Some(failing_dlc), vec![]);
1480 let ex = make_exchange();
1481 let result = handler
1482 .handle_step(None, ex, CamelError::ProcessorError("original".into()))
1483 .await;
1484 assert!(
1485 matches!(result, Ok(StepDisposition::Propagate(_))),
1486 "DLC failure should still return Propagate with original error"
1487 );
1488 }
1489
1490 #[tokio::test]
1493 async fn test_handle_boundary_security_error_goes_to_dlc() {
1494 let dlc_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
1495 let count_clone = dlc_count.clone();
1496 let dlc = BoxProcessor::from_fn(move |ex| {
1497 let c = count_clone.clone();
1498 Box::pin(async move {
1499 c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1500 Ok(ex)
1501 })
1502 });
1503 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1504 let ex = make_exchange();
1505 let result = handler
1506 .handle_boundary(
1507 BoundaryKind::Security,
1508 ex,
1509 CamelError::Unauthorized("denied".into()),
1510 )
1511 .await;
1512 assert!(result.is_ok());
1513 assert_eq!(dlc_count.load(std::sync::atomic::Ordering::SeqCst), 1);
1514 }
1515
1516 #[tokio::test]
1517 async fn test_handle_boundary_handled_clears_error() {
1518 let policy = ExceptionPolicy {
1519 matches: std::sync::Arc::new(|_| true),
1520 retry: None,
1521 handled_by: None,
1522 on_steps: None,
1523 disposition: ExceptionDisposition::Handled,
1524 };
1525 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1526 let ex = make_exchange();
1527 let result = handler
1528 .handle_boundary(
1529 BoundaryKind::Security,
1530 ex,
1531 CamelError::Unauthorized("denied".into()),
1532 )
1533 .await;
1534 assert!(result.is_ok());
1535 assert!(
1536 !result.unwrap().has_error(),
1537 "Handled disposition should clear error"
1538 );
1539 }
1540
1541 #[tokio::test]
1542 async fn test_handle_boundary_propagate_preserves_error() {
1543 let policy = ExceptionPolicy {
1544 matches: std::sync::Arc::new(|_| true),
1545 retry: None,
1546 handled_by: None,
1547 on_steps: None,
1548 disposition: ExceptionDisposition::Propagate,
1549 };
1550 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1551 let ex = make_exchange();
1552 let result = handler
1553 .handle_boundary(
1554 BoundaryKind::CircuitBreaker,
1555 ex,
1556 CamelError::CircuitOpen("open".into()),
1557 )
1558 .await;
1559 assert!(result.is_ok(), "boundary errors always return Ok");
1560 assert!(
1561 result.unwrap().has_error(),
1562 "Propagate disposition should preserve error"
1563 );
1564 }
1565
1566 #[tokio::test]
1567 async fn test_handle_boundary_continued_preserves_error_like_propagate() {
1568 let dlc_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
1569 let count_clone = dlc_count.clone();
1570 let dlc = BoxProcessor::from_fn(move |ex| {
1571 let c = count_clone.clone();
1572 Box::pin(async move {
1573 c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1574 Ok(ex)
1575 })
1576 });
1577 let policy = ExceptionPolicy {
1578 matches: std::sync::Arc::new(|_| true),
1579 retry: None,
1580 handled_by: None,
1581 on_steps: None,
1582 disposition: ExceptionDisposition::Continued,
1583 };
1584 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![(policy, None)]);
1585 let ex = make_exchange();
1586 let result = handler
1587 .handle_boundary(
1588 BoundaryKind::Security,
1589 ex,
1590 CamelError::Unauthorized("denied".into()),
1591 )
1592 .await;
1593 assert!(result.is_ok(), "boundary errors always return Ok");
1594 assert!(
1595 result.unwrap().has_error(),
1596 "Continued at boundary should preserve error"
1597 );
1598 assert_eq!(
1599 dlc_count.load(std::sync::atomic::Ordering::SeqCst),
1600 1,
1601 "DLC should be called"
1602 );
1603 }
1604
1605 #[tokio::test]
1606 async fn test_handle_boundary_with_on_steps_handled() {
1607 let steps_pipeline = BoxProcessor::new(tower::service_fn(|mut ex: Exchange| {
1608 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
1609 async move { Ok(ex) }
1610 }));
1611 let policy = ExceptionPolicy {
1612 matches: std::sync::Arc::new(|_| true),
1613 retry: None,
1614 handled_by: None,
1615 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
1616 disposition: ExceptionDisposition::Handled,
1617 };
1618 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1619 let ex = make_exchange();
1620 let result = handler
1621 .handle_boundary(
1622 BoundaryKind::Security,
1623 ex,
1624 CamelError::Unauthorized("denied".into()),
1625 )
1626 .await;
1627 assert!(result.is_ok(), "boundary errors always return Ok");
1628 let ex = result.unwrap();
1629 assert!(!ex.has_error(), "Handled disposition should clear error");
1630 assert!(
1631 matches!(ex.input.body, camel_api::Body::Bytes(_)),
1632 "on_steps should have modified the body"
1633 );
1634 }
1635
1636 #[tokio::test]
1637 async fn retry_step_segment_stop_maps_to_retry_outcome_stopped() {
1638 use std::sync::Arc;
1639 use std::sync::atomic::{AtomicUsize, Ordering};
1640
1641 #[derive(Clone)]
1642 struct StoppingSegment {
1643 n: Arc<AtomicUsize>,
1644 }
1645 impl OutcomePipeline for StoppingSegment {
1646 fn clone_box(&self) -> Box<dyn OutcomePipeline> {
1647 Box::new(self.clone())
1648 }
1649 fn run<'a>(
1650 &'a mut self,
1651 ex: Exchange,
1652 ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
1653 let n = self.n.clone();
1654 Box::pin(async move {
1655 n.fetch_add(1, Ordering::SeqCst);
1656 PipelineOutcome::Stopped(ex)
1657 })
1658 }
1659 }
1660
1661 let call_count = Arc::new(AtomicUsize::new(0));
1662 let seg = OutcomeSegment::new(Box::new(StoppingSegment {
1663 n: call_count.clone(),
1664 }));
1665 let mut retryable: Box<dyn RetryableStep> = Box::new(seg);
1666
1667 let mut policy = ExceptionPolicy::new(|_e: &CamelError| true);
1668 policy.retry = Some(RedeliveryPolicy::new(3));
1669 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, None)]);
1670
1671 let original = Exchange::new(Message::new("retry-me"));
1672 let err = CamelError::ProcessorError("trigger retry".into());
1673 let outcome = handler
1674 .retry_step(Some(PolicyId(0)), retryable.as_mut(), original, err)
1675 .await;
1676
1677 assert!(
1678 matches!(outcome, RetryOutcome::Stopped(_)),
1679 "Segment Stop must map to RetryOutcome::Stopped, got {:?}",
1680 outcome
1681 );
1682 assert_eq!(
1683 call_count.load(Ordering::SeqCst),
1684 1,
1685 "Stop must short-circuit retry — only 1 invoke expected, got {}",
1686 call_count.load(Ordering::SeqCst)
1687 );
1688 }
1689
1690 #[tokio::test]
1691 async fn retry_step_new_signature_works_with_dlc_producer() {
1692 use std::sync::Arc;
1693 use std::sync::atomic::{AtomicUsize, Ordering};
1694
1695 #[derive(Clone)]
1696 struct CountingProducer {
1697 count: Arc<AtomicUsize>,
1698 succeed_on: usize,
1699 }
1700 impl tower::Service<Exchange> for CountingProducer {
1701 type Response = Exchange;
1702 type Error = CamelError;
1703 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1704 fn poll_ready(
1705 &mut self,
1706 _cx: &mut std::task::Context<'_>,
1707 ) -> std::task::Poll<Result<(), Self::Error>> {
1708 std::task::Poll::Ready(Ok(()))
1709 }
1710 fn call(&mut self, ex: Exchange) -> Self::Future {
1711 let n = self.count.fetch_add(1, Ordering::SeqCst);
1712 let succeed_on = self.succeed_on;
1713 Box::pin(async move {
1714 if n >= succeed_on {
1715 Ok(ex)
1716 } else {
1717 Err(CamelError::ProcessorError("retry".into()))
1718 }
1719 })
1720 }
1721 }
1722
1723 let count = Arc::new(AtomicUsize::new(0));
1724 let producer = CountingProducer {
1725 count: count.clone(),
1726 succeed_on: 2,
1727 };
1728 let sync_bp = SyncBoxProcessor::new(BoxProcessor::new(producer));
1729 let bp1 = sync_bp.clone_inner();
1730 let bp2 = sync_bp.clone_inner();
1731 let mut retryable1: Box<dyn RetryableStep> = Box::new(bp1);
1732 let mut retryable2: Box<dyn RetryableStep> = Box::new(bp2);
1733
1734 let ex = Exchange::new(Message::new("dlc"));
1735 let outcome1 = retryable1.invoke(ex.clone()).await;
1736 let outcome2 = retryable2.invoke(ex).await;
1737 assert!(matches!(outcome1, PipelineOutcome::Failed(_)));
1738 assert!(matches!(outcome2, PipelineOutcome::Failed(_)));
1739 assert_eq!(
1740 count.load(Ordering::SeqCst),
1741 2,
1742 "DLC producer must be invoked exactly twice through SyncBoxProcessor"
1743 );
1744 drop(retryable1);
1745 drop(retryable2);
1746 drop(sync_bp);
1747 }
1748
1749 #[tokio::test]
1752 async fn test_use_original_message_restores_body_before_dlc() {
1753 let dlc_received = Arc::new(std::sync::Mutex::new(None::<Exchange>));
1756 let dlc_received_clone = Arc::clone(&dlc_received);
1757 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1758 let r = Arc::clone(&dlc_received_clone);
1759 Box::pin(async move {
1760 *r.lock().unwrap() = Some(ex.clone());
1761 Ok(ex)
1762 })
1763 });
1764
1765 let mut handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1766 handler.use_original_message = true;
1767
1768 let mut ex = make_exchange();
1770 ex.input = Message::new("original-body");
1771
1772 let original: Arc<Message> = Arc::new(ex.input.clone());
1774 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, original);
1775
1776 ex.input.body = camel_api::Body::Bytes("mutated-body".into());
1778
1779 let result = handler
1781 .handle_step(None, ex, CamelError::ProcessorError("boom".into()))
1782 .await;
1783 assert!(matches!(result, Ok(StepDisposition::Propagate(_))));
1784
1785 let received = dlc_received
1787 .lock()
1788 .unwrap()
1789 .take()
1790 .expect("DLC should have been called");
1791 let received_text = match &received.input.body {
1792 camel_api::Body::Text(s) => s.clone(),
1793 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
1794 camel_api::Body::Json(v) => v.to_string(),
1795 _ => String::new(),
1796 };
1797 assert_eq!(
1798 received_text, "original-body",
1799 "DLC should receive original message body, not mutated version"
1800 );
1801 }
1802
1803 #[tokio::test]
1804 async fn test_use_original_message_handle_boundary_restores_before_dlc() {
1805 let dlc_received = Arc::new(std::sync::Mutex::new(None::<Exchange>));
1806 let dlc_received_clone = Arc::clone(&dlc_received);
1807 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1808 let r = Arc::clone(&dlc_received_clone);
1809 Box::pin(async move {
1810 *r.lock().unwrap() = Some(ex.clone());
1811 Ok(ex)
1812 })
1813 });
1814
1815 let mut handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1816 handler.use_original_message = true;
1817
1818 let mut ex = make_exchange();
1819 ex.input = Message::new("orig-boundary");
1820
1821 let original: Arc<Message> = Arc::new(ex.input.clone());
1822 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, original);
1823
1824 ex.input.body = camel_api::Body::Bytes("mutated-boundary".into());
1826
1827 let result = handler
1828 .handle_boundary(
1829 BoundaryKind::Security,
1830 ex,
1831 CamelError::Unauthorized("denied".into()),
1832 )
1833 .await;
1834 assert!(result.is_ok());
1835
1836 let received = dlc_received
1837 .lock()
1838 .unwrap()
1839 .take()
1840 .expect("DLC should have been called");
1841 let received_text = match &received.input.body {
1842 camel_api::Body::Text(s) => s.clone(),
1843 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
1844 camel_api::Body::Json(v) => v.to_string(),
1845 _ => String::new(),
1846 };
1847 assert_eq!(
1848 received_text, "orig-boundary",
1849 "handle_boundary should restore original message before sending to DLC"
1850 );
1851 }
1852
1853 #[tokio::test]
1854 async fn test_use_original_message_false_does_not_restore() {
1855 let dlc_received = Arc::new(std::sync::Mutex::new(None::<Exchange>));
1857 let dlc_received_clone = Arc::clone(&dlc_received);
1858 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
1859 let r = Arc::clone(&dlc_received_clone);
1860 Box::pin(async move {
1861 *r.lock().unwrap() = Some(ex.clone());
1862 Ok(ex)
1863 })
1864 });
1865
1866 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![]);
1867 let mut ex = make_exchange();
1870 ex.input = Message::new("original-body");
1871
1872 let original: Arc<Message> = Arc::new(ex.input.clone());
1874 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, original);
1875
1876 ex.input.body = camel_api::Body::Bytes("mutated-body".into());
1878
1879 let result = handler
1880 .handle_step(None, ex, CamelError::ProcessorError("boom".into()))
1881 .await;
1882 assert!(matches!(result, Ok(StepDisposition::Propagate(_))));
1883
1884 let received = dlc_received
1885 .lock()
1886 .unwrap()
1887 .take()
1888 .expect("DLC should have been called");
1889 let received_text = match &received.input.body {
1890 camel_api::Body::Text(s) => s.clone(),
1891 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
1892 camel_api::Body::Json(v) => v.to_string(),
1893 _ => String::new(),
1894 };
1895 assert_eq!(
1896 received_text, "mutated-body",
1897 "When use_original_message=false, DLC should see the mutated body"
1898 );
1899 }
1900
1901 fn handled_policy() -> ExceptionPolicy {
1904 ExceptionPolicy {
1905 matches: Arc::new(|_| true),
1906 retry: None,
1907 handled_by: None,
1908 on_steps: None,
1909 disposition: ExceptionDisposition::Handled,
1910 }
1911 }
1912
1913 fn body_text(body: &camel_api::Body) -> String {
1914 match body {
1915 camel_api::Body::Text(s) => s.clone(),
1916 camel_api::Body::Bytes(b) => String::from_utf8_lossy(b).to_string(),
1917 camel_api::Body::Json(v) => v.to_string(),
1918 _ => String::new(),
1919 }
1920 }
1921
1922 #[tokio::test]
1923 async fn restore_reinstates_marker_for_untouched_original() {
1924 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)])
1925 .with_use_original_message(true);
1926
1927 let mut original = Message::new("original-body");
1928 original.set_header("Content-Type", "application/xml");
1929
1930 let mut ex = make_exchange();
1931 ex.input = original.clone();
1932 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
1933 ex.set_extension(
1934 camel_api::ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
1935 Arc::new(camel_api::OriginalContentTypeInherited(true)),
1936 );
1937
1938 ex.input.set_header("Content-Type", "application/json");
1941 ex.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
1942
1943 let disposition = handler
1944 .handle_step(
1945 Some(PolicyId(0)),
1946 ex,
1947 CamelError::ProcessorError("boom".into()),
1948 )
1949 .await
1950 .expect("handle_step should succeed");
1951 let StepDisposition::Handled(ex) = disposition else {
1952 panic!("expected Handled disposition");
1953 };
1954
1955 assert_eq!(body_text(&ex.input.body), "original-body");
1956 assert_eq!(
1957 ex.input.header("Content-Type"),
1958 Some(&Value::String("application/xml".into()))
1959 );
1960 assert_eq!(
1961 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
1962 Some(&Value::Bool(true)),
1963 "restoring an inherited original must reinstate the marker"
1964 );
1965 }
1966
1967 #[tokio::test]
1968 async fn restore_removes_live_marker_when_snapshot_false() {
1969 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)])
1970 .with_use_original_message(true);
1971
1972 let original = Message::new("original-body");
1975
1976 let mut ex = make_exchange();
1977 ex.input = original.clone();
1978 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
1979 ex.set_extension(
1980 camel_api::ORIGINAL_CONTENT_TYPE_INHERITED_EXTENSION,
1981 Arc::new(camel_api::OriginalContentTypeInherited(false)),
1982 );
1983 ex.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
1984
1985 let disposition = handler
1986 .handle_step(
1987 Some(PolicyId(0)),
1988 ex,
1989 CamelError::ProcessorError("boom".into()),
1990 )
1991 .await
1992 .expect("handle_step should succeed");
1993 let StepDisposition::Handled(ex) = disposition else {
1994 panic!("expected Handled disposition");
1995 };
1996
1997 assert_eq!(
1998 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
1999 None,
2000 "a stored false snapshot must clear a live marker"
2001 );
2002 }
2003
2004 #[tokio::test]
2005 async fn restore_clears_marker_when_snapshot_absent() {
2006 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)])
2007 .with_use_original_message(true);
2008
2009 let original = Message::new("original-body");
2012
2013 let mut ex = make_exchange();
2014 ex.input = original.clone();
2015 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
2016 ex.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
2017
2018 let disposition = handler
2019 .handle_step(
2020 Some(PolicyId(0)),
2021 ex,
2022 CamelError::ProcessorError("boom".into()),
2023 )
2024 .await
2025 .expect("handle_step should succeed");
2026 let StepDisposition::Handled(ex) = disposition else {
2027 panic!("expected Handled disposition");
2028 };
2029
2030 assert_eq!(
2031 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
2032 None,
2033 "an absent provenance snapshot must clear a live marker"
2034 );
2035 }
2036
2037 #[tokio::test]
2038 async fn restore_without_use_original_message_leaves_marker_untouched() {
2039 let handler = DefaultRouteErrorHandler::new(None, vec![(handled_policy(), None)]);
2040 let mut original = Message::new("original-body");
2043 original.set_header("Content-Type", "application/xml");
2044
2045 let mut ex = make_exchange();
2046 ex.input = original.clone();
2047 ex.set_extension(camel_api::ORIGINAL_MESSAGE_EXTENSION, Arc::new(original));
2048 ex.input = Message::new("mutated-body");
2049 ex.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
2050
2051 let disposition = handler
2052 .handle_step(
2053 Some(PolicyId(0)),
2054 ex,
2055 CamelError::ProcessorError("boom".into()),
2056 )
2057 .await
2058 .expect("handle_step should succeed");
2059 let StepDisposition::Handled(ex) = disposition else {
2060 panic!("expected Handled disposition");
2061 };
2062
2063 assert_eq!(
2064 body_text(&ex.input.body),
2065 "mutated-body",
2066 "restoration must not run when use_original_message is disabled"
2067 );
2068 assert_eq!(
2069 ex.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
2070 Some(&Value::Bool(true)),
2071 "restoration must not run when use_original_message is disabled"
2072 );
2073 }
2074
2075 #[tokio::test]
2078 async fn propagate_skips_on_steps_in_handle_step() {
2079 let on_steps_called = Arc::new(AtomicU32::new(0));
2080 let on_steps_called_clone = on_steps_called.clone();
2081 let steps_pipeline = BoxProcessor::new(tower::service_fn(move |mut ex: Exchange| {
2082 let c = on_steps_called_clone.clone();
2083 Box::pin(async move {
2084 c.fetch_add(1, Ordering::SeqCst);
2085 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
2086 Ok(ex)
2087 })
2088 }));
2089 let dlc_called = Arc::new(AtomicU32::new(0));
2090 let dlc_called_clone = dlc_called.clone();
2091 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
2092 let c = dlc_called_clone.clone();
2093 Box::pin(async move {
2094 c.fetch_add(1, Ordering::SeqCst);
2095 Ok(ex)
2096 })
2097 });
2098 let policy = ExceptionPolicy {
2099 matches: std::sync::Arc::new(|_| true),
2100 retry: None,
2101 handled_by: None,
2102 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
2103 disposition: ExceptionDisposition::Propagate,
2104 };
2105 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![(policy, None)]);
2106 let mut ex = make_exchange();
2107 ex.set_error(CamelError::ProcessorError("boom".into()));
2108 let result = handler
2109 .handle_step(
2110 Some(PolicyId(0)),
2111 ex,
2112 CamelError::ProcessorError("boom".into()),
2113 )
2114 .await;
2115 assert!(
2116 matches!(result, Ok(StepDisposition::Propagate(_))),
2117 "Propagate disposition should return Propagate"
2118 );
2119 assert_eq!(
2120 on_steps_called.load(Ordering::SeqCst),
2121 0,
2122 "on_steps must NOT be called when disposition is Propagate (double side-effect bug)"
2123 );
2124 assert_eq!(
2125 dlc_called.load(Ordering::SeqCst),
2126 1,
2127 "DLC should still be called when disposition is Propagate"
2128 );
2129 }
2130
2131 #[tokio::test]
2132 async fn propagate_skips_on_steps_in_handle_boundary() {
2133 let on_steps_called = Arc::new(AtomicU32::new(0));
2134 let on_steps_called_clone = on_steps_called.clone();
2135 let steps_pipeline = BoxProcessor::new(tower::service_fn(move |mut ex: Exchange| {
2136 let c = on_steps_called_clone.clone();
2137 Box::pin(async move {
2138 c.fetch_add(1, Ordering::SeqCst);
2139 ex.input.body = camel_api::Body::Bytes("on_steps_ran".into());
2140 Ok(ex)
2141 })
2142 }));
2143 let dlc_called = Arc::new(AtomicU32::new(0));
2144 let dlc_called_clone = dlc_called.clone();
2145 let dlc = BoxProcessor::from_fn(move |ex: Exchange| {
2146 let c = dlc_called_clone.clone();
2147 Box::pin(async move {
2148 c.fetch_add(1, Ordering::SeqCst);
2149 Ok(ex)
2150 })
2151 });
2152 let policy = ExceptionPolicy {
2153 matches: std::sync::Arc::new(|_| true),
2154 retry: None,
2155 handled_by: None,
2156 on_steps: Some(SyncBoxProcessor::new(steps_pipeline)),
2157 disposition: ExceptionDisposition::Propagate,
2158 };
2159 let handler = DefaultRouteErrorHandler::new(Some(dlc), vec![(policy, None)]);
2160 let ex = make_exchange();
2161 let result = handler
2162 .handle_boundary(
2163 BoundaryKind::CircuitBreaker,
2164 ex,
2165 CamelError::CircuitOpen("open".into()),
2166 )
2167 .await;
2168 assert!(result.is_ok(), "boundary errors always return Ok");
2169 assert!(
2170 result.unwrap().has_error(),
2171 "Propagate disposition should preserve error"
2172 );
2173 assert_eq!(
2174 on_steps_called.load(Ordering::SeqCst),
2175 0,
2176 "on_steps must NOT be called when disposition is Propagate (double side-effect bug)"
2177 );
2178 assert_eq!(
2179 dlc_called.load(Ordering::SeqCst),
2180 1,
2181 "DLC should still be called when disposition is Propagate"
2182 );
2183 }
2184
2185 fn failing_delegate() -> BoxProcessor {
2193 BoxProcessor::from_fn(|_| {
2194 Box::pin(async { Err(CamelError::ProcessorError("delegate-broken".into())) })
2195 })
2196 }
2197
2198 fn handled_policy_with(producer: Option<BoxProcessor>) -> DefaultRouteErrorHandler {
2201 let policy = ExceptionPolicy {
2202 matches: std::sync::Arc::new(|_| true),
2203 retry: None,
2204 handled_by: None,
2205 on_steps: None,
2206 disposition: ExceptionDisposition::Handled,
2207 };
2208 DefaultRouteErrorHandler::new(None, vec![(policy, producer)])
2209 }
2210
2211 fn assert_propagates_original(result: &Result<StepDisposition, CamelError>) {
2212 assert!(
2213 matches!(
2214 result,
2215 Ok(StepDisposition::Propagate(CamelError::ProcessorError(m)))
2216 if m == "original-err"
2217 ),
2218 "delegate failure must propagate the ORIGINAL error, got: {:?}",
2219 result
2220 .as_ref()
2221 .map(|d| d_variant_name(d))
2222 .unwrap_or_default()
2223 );
2224 }
2225
2226 fn d_variant_name(d: &StepDisposition) -> &'static str {
2228 match d {
2229 StepDisposition::Propagate(_) => "Propagate",
2230 StepDisposition::Handled(_) => "Handled",
2231 StepDisposition::Continued(_) => "Continued",
2232 _ => "other",
2233 }
2234 }
2235
2236 #[tokio::test]
2237 async fn delegate_call_failure_with_handled_propagates_original() {
2238 ensure_global_registry();
2241 let handler = handled_policy_with(Some(failing_delegate()));
2242 let result = handler
2243 .handle_step(
2244 Some(PolicyId(0)),
2245 make_exchange(),
2246 CamelError::ProcessorError("original-err".into()),
2247 )
2248 .await;
2249 assert_propagates_original(&result);
2250 }
2251
2252 #[test]
2253 fn delegate_failure_emits_system_broken_log_and_span_error() {
2254 let handler = handled_policy_with(Some(failing_delegate()));
2255 let mut ex = make_exchange();
2256 ex.set_error(CamelError::ProcessorError("original-err".into()));
2257 let (result, captured, span_records) = capture_debugs_with_span_records(|| {
2258 let span = tracing::info_span!("delegate_failure_test", error = tracing::field::Empty);
2260 let _guard = span.enter();
2261 tokio::runtime::Builder::new_current_thread()
2262 .enable_all()
2263 .build()
2264 .expect("current-thread runtime")
2265 .block_on(handler.handle_step(
2266 Some(PolicyId(0)),
2267 ex,
2268 CamelError::ProcessorError("original-err".into()),
2269 ))
2270 });
2271 assert!(
2272 matches!(result, Ok(StepDisposition::Propagate(_))),
2273 "delegate failure must propagate, got: {}",
2274 result
2275 .as_ref()
2276 .map(|d| d_variant_name(d))
2277 .unwrap_or("Err(..)")
2278 );
2279 assert!(
2281 captured.iter().any(|line| {
2282 line.contains("DLC/handler call failed")
2283 && line.contains("original-err")
2284 && line.contains("delegate-broken")
2285 }),
2286 "expected system-broken log structuring BOTH errors, captured: {captured:?}"
2287 );
2288 assert!(
2290 span_records.iter().any(|line| {
2291 line.contains("error=")
2292 && line.contains("delegate-broken")
2293 && !line.contains("original-err")
2294 }),
2295 "expected span error record carrying the DELEGATE error, span records: {span_records:?}"
2296 );
2297 }
2298
2299 #[tokio::test]
2300 async fn retry_exhausted_then_delegate_failure_propagates_original() {
2301 ensure_global_registry();
2304 let policy = ExceptionPolicy {
2305 matches: std::sync::Arc::new(|_| true),
2306 retry: Some(RedeliveryPolicy {
2307 max_attempts: 1,
2308 initial_delay: Duration::from_millis(1),
2309 multiplier: 1.0,
2310 max_delay: Duration::from_millis(10),
2311 jitter_factor: 0.0,
2312 }),
2313 handled_by: None,
2314 on_steps: None,
2315 disposition: ExceptionDisposition::Handled,
2316 };
2317 let svc = ErrorHandlerService::new(
2318 failing_processor(),
2319 Some(failing_delegate()),
2320 vec![(policy, None)],
2321 );
2322 let result = svc.oneshot(make_exchange()).await;
2323 assert!(
2324 matches!(&result, Err(CamelError::ProcessorError(m)) if m == "boom"),
2325 "retry-exhausted ORIGINAL error must surface as Err, got: {:?}",
2326 result.map(|ex| ex.has_error())
2327 );
2328 }
2329
2330 #[tokio::test]
2331 async fn on_steps_fallback_delegate_failure_propagates_original() {
2332 ensure_global_registry();
2335 let policy = ExceptionPolicy {
2339 matches: std::sync::Arc::new(|_| true),
2340 retry: None,
2341 handled_by: None,
2342 on_steps: Some(SyncBoxProcessor::new(failing_processor())),
2343 disposition: ExceptionDisposition::Handled,
2344 };
2345 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(failing_delegate()))]);
2346 let result = handler
2347 .handle_step(
2348 Some(PolicyId(0)),
2349 make_exchange(),
2350 CamelError::ProcessorError("original-err".into()),
2351 )
2352 .await;
2353 assert_propagates_original(&result);
2354 }
2355
2356 #[tokio::test]
2357 async fn no_match_dlc_delegate_failure_propagates_original() {
2358 ensure_global_registry();
2361 let policy = ExceptionPolicy::new(|e| matches!(e, CamelError::Io(_)));
2365 let svc = ErrorHandlerService::new(
2366 failing_processor(),
2367 Some(failing_delegate()),
2368 vec![(policy, None)],
2369 );
2370 let result = svc.oneshot(make_exchange()).await;
2371 assert!(
2372 matches!(&result, Err(CamelError::ProcessorError(m)) if m == "boom"),
2373 "no-match DLC delegate failure must surface the ORIGINAL error as Err, got: {:?}",
2374 result.map(|ex| ex.has_error())
2375 );
2376 }
2377
2378 #[tokio::test]
2379 async fn delegate_ready_failure_propagates_original() {
2380 ensure_global_registry();
2383 let not_ready: BoxProcessor = BoxProcessor::new(ReadinessFailService::new(
2384 CamelError::ProcessorError("delegate-not-ready".into()),
2385 ));
2386 let handler = handled_policy_with(Some(not_ready));
2387 let result = handler
2388 .handle_step(
2389 Some(PolicyId(0)),
2390 make_exchange(),
2391 CamelError::ProcessorError("original-err".into()),
2392 )
2393 .await;
2394 assert_propagates_original(&result);
2395 }
2396
2397 #[tokio::test]
2398 async fn delegate_failure_with_continued_propagates_original() {
2399 ensure_global_registry();
2402 let policy = ExceptionPolicy {
2403 matches: std::sync::Arc::new(|_| true),
2404 retry: None,
2405 handled_by: None,
2406 on_steps: None,
2407 disposition: ExceptionDisposition::Continued,
2408 };
2409 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(failing_delegate()))]);
2410 let result = handler
2411 .handle_step(
2412 Some(PolicyId(0)),
2413 make_exchange(),
2414 CamelError::ProcessorError("original-err".into()),
2415 )
2416 .await;
2417 assert_propagates_original(&result);
2418 }
2419
2420 #[tokio::test]
2421 async fn boundary_delegate_failure_returns_original_err() {
2422 ensure_global_registry();
2425 let handler = DefaultRouteErrorHandler::new(Some(failing_delegate()), vec![]);
2426 let result = handler
2427 .handle_boundary(
2428 BoundaryKind::Security,
2429 make_exchange(),
2430 CamelError::Unauthorized("denied".into()),
2431 )
2432 .await;
2433 assert!(
2434 matches!(&result, Err(CamelError::Unauthorized(m)) if m == "denied"),
2435 "boundary delegate failure must return the ORIGINAL boundary error, got: {:?}",
2436 result
2437 );
2438 }
2439
2440 #[tokio::test]
2441 async fn tap_policy_without_handled_propagates() {
2442 let delegate_hits = Arc::new(AtomicU32::new(0));
2446 let hits = Arc::clone(&delegate_hits);
2447 let tap_delegate = BoxProcessor::from_fn(move |ex: Exchange| {
2448 let h = Arc::clone(&hits);
2449 Box::pin(async move {
2450 h.fetch_add(1, Ordering::SeqCst);
2451 Ok(ex)
2452 })
2453 });
2454 let policy = ExceptionPolicy {
2455 matches: std::sync::Arc::new(|_| true),
2456 retry: None,
2457 handled_by: None,
2458 on_steps: None,
2459 disposition: ExceptionDisposition::Propagate,
2460 };
2461 let handler = DefaultRouteErrorHandler::new(None, vec![(policy, Some(tap_delegate))]);
2462 let result = handler
2463 .handle_step(
2464 Some(PolicyId(0)),
2465 make_exchange(),
2466 CamelError::ProcessorError("original-err".into()),
2467 )
2468 .await;
2469 assert_propagates_original(&result);
2470 assert_eq!(
2471 delegate_hits.load(Ordering::SeqCst),
2472 1,
2473 "delegate must have received the exchange exactly once"
2474 );
2475 }
2476
2477 #[test]
2478 fn test_handle_step_no_match_emits_silent_propagate_diagnostic() {
2479 let handler = DefaultRouteErrorHandler::new(None, vec![]);
2482 let (result, captured) = capture_debugs(|| {
2483 tokio::runtime::Builder::new_current_thread()
2484 .enable_all()
2485 .build()
2486 .expect("current-thread runtime")
2487 .block_on(handler.handle_step(
2488 None,
2489 make_exchange(),
2490 CamelError::Unauthorized("denied".into()),
2491 ))
2492 });
2493 assert!(result.is_ok(), "step handler always returns Ok");
2494 assert!(
2495 captured.iter().any(|line| {
2496 line.contains(
2497 "no on_exceptions policy matched and no dead-letter channel configured; \
2498 propagating error",
2499 )
2500 }),
2501 "expected silent-propagate diagnostic, captured: {captured:?}"
2502 );
2503 assert!(
2504 captured
2505 .iter()
2506 .any(|line| line.contains("kind=Unauthorized")),
2507 "diagnostic should name the error kind, captured: {captured:?}"
2508 );
2509 }
2510
2511 #[test]
2512 fn test_handle_boundary_no_match_emits_silent_propagate_diagnostic() {
2513 let handler = DefaultRouteErrorHandler::new(None, vec![]);
2514 let (result, captured) = capture_debugs(|| {
2515 tokio::runtime::Builder::new_current_thread()
2516 .enable_all()
2517 .build()
2518 .expect("current-thread runtime")
2519 .block_on(handler.handle_boundary(
2520 BoundaryKind::Security,
2521 make_exchange(),
2522 CamelError::Unauthorized("denied".into()),
2523 ))
2524 });
2525 assert!(result.is_ok(), "boundary handler always returns Ok");
2526 assert!(
2527 captured.iter().any(|line| {
2528 line.contains(
2529 "no on_exceptions policy matched and no dead-letter channel configured; \
2530 propagating error",
2531 )
2532 }),
2533 "expected silent-propagate diagnostic, captured: {captured:?}"
2534 );
2535 assert!(
2536 captured.iter().any(
2537 |line| line.contains("boundary=Security") && line.contains("kind=Unauthorized")
2538 ),
2539 "diagnostic should name the boundary gate and error kind, captured: {captured:?}"
2540 );
2541 }
2542
2543 use crate::test_log_capture::{capture_debugs_with_span_records, ensure_global_registry};
2550
2551 fn capture_debugs<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
2553 let (out, events, _span_records) = capture_debugs_with_span_records(f);
2554 (out, events)
2555 }
2556}