1use std::future::Future;
2use std::pin::Pin;
3use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
4use std::sync::{Arc, Mutex};
5use std::task::{Context, Poll};
6use std::time::{Duration, Instant};
7
8use tower::{Layer, Service};
9
10use camel_api::metrics::MetricsCollector;
11use camel_api::{BoxProcessor, CamelError, CircuitBreakerConfig, Exchange};
12
13const STATE_CLOSED: u8 = 0;
17const STATE_OPEN: u8 = 1;
19const STATE_HALF_OPEN_PROBE_HELD: u8 = 2;
22const STATE_HALF_OPEN_PROBE_FREE: u8 = 3;
25
26struct SharedBreakerState {
30 state: AtomicU8,
31 consecutive_failures: AtomicU32,
32 opened_at: Mutex<Option<Instant>>,
33}
34
35enum HalfOpenTransition {
37 Transitioned,
39 NotExpired,
41 LostRace,
43}
44
45impl SharedBreakerState {
46 fn new() -> Self {
47 Self {
48 state: AtomicU8::new(STATE_CLOSED),
49 consecutive_failures: AtomicU32::new(0),
50 opened_at: Mutex::new(None),
51 }
52 }
53
54 fn with_transition(&self, f: impl FnOnce(&mut Option<Instant>) -> bool) -> bool {
60 let mut guard = self.opened_at.lock().unwrap_or_else(|e| e.into_inner());
61 f(&mut guard)
62 }
63
64 fn try_transition_to_half_open(&self, open_duration: Duration) -> HalfOpenTransition {
70 let opened_at = self.opened_at.lock().unwrap_or_else(|e| e.into_inner());
71 let expired = opened_at
72 .map(|at| at.elapsed() >= open_duration)
73 .unwrap_or(false);
74 if !expired {
75 return HalfOpenTransition::NotExpired;
76 }
77 match self.state.compare_exchange(
78 STATE_OPEN,
79 STATE_HALF_OPEN_PROBE_HELD,
80 Ordering::AcqRel,
81 Ordering::Acquire,
82 ) {
83 Ok(_) => HalfOpenTransition::Transitioned,
84 Err(_) => HalfOpenTransition::LostRace,
85 }
86 }
87}
88
89#[derive(Clone)]
93pub struct CircuitBreakerLayer {
94 config: CircuitBreakerConfig,
95 state: Arc<SharedBreakerState>,
96 route_id: Arc<str>,
97 metrics: Option<Arc<dyn MetricsCollector>>,
98}
99
100impl CircuitBreakerLayer {
101 pub fn new(
106 config: CircuitBreakerConfig,
107 route_id: Arc<str>,
108 metrics: Option<Arc<dyn MetricsCollector>>,
109 ) -> Self {
110 Self {
111 config,
112 state: Arc::new(SharedBreakerState::new()),
113 route_id,
114 metrics,
115 }
116 }
117}
118
119impl<S> Layer<S> for CircuitBreakerLayer {
120 type Service = CircuitBreakerService<S>;
121
122 fn layer(&self, inner: S) -> Self::Service {
123 CircuitBreakerService {
124 inner,
125 config: self.config.clone(),
126 state: Arc::clone(&self.state),
127 route_id: Arc::clone(&self.route_id),
128 metrics: self.metrics.clone(),
129 }
130 }
131}
132
133pub struct CircuitBreakerService<S> {
137 inner: S,
138 config: CircuitBreakerConfig,
139 state: Arc<SharedBreakerState>,
140 route_id: Arc<str>,
141 metrics: Option<Arc<dyn MetricsCollector>>,
142}
143
144impl<S: Clone> Clone for CircuitBreakerService<S> {
145 fn clone(&self) -> Self {
146 Self {
147 inner: self.inner.clone(),
148 config: self.config.clone(),
149 state: Arc::clone(&self.state),
150 route_id: Arc::clone(&self.route_id),
151 metrics: self.metrics.clone(),
152 }
153 }
154}
155
156impl<S> CircuitBreakerService<S> {
157 fn record_rejection(&self) {
159 if let Some(ref metrics) = self.metrics {
160 metrics.increment_circuit_breaker_rejection(&self.route_id);
161 }
162 }
163}
164
165impl<S> Service<Exchange> for CircuitBreakerService<S>
166where
167 S: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
168 S::Future: Send,
169{
170 type Response = Exchange;
171 type Error = CamelError;
172 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
173
174 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
175 loop {
176 match self.state.state.load(Ordering::Acquire) {
177 STATE_CLOSED => return self.inner.poll_ready(cx),
178 STATE_OPEN => match self
179 .state
180 .try_transition_to_half_open(self.config.open_duration)
181 {
182 HalfOpenTransition::Transitioned => {
183 tracing::info!("Circuit breaker transitioning from Open to HalfOpen");
184 return self.poll_ready_as_probe(cx);
185 }
186 HalfOpenTransition::NotExpired => {
187 if self.config.fallback.is_some() {
188 return Poll::Ready(Ok(()));
189 }
190 self.record_rejection();
191 return Poll::Ready(Err(CamelError::CircuitOpen(
192 "circuit breaker is open".into(),
193 )));
194 }
195 HalfOpenTransition::LostRace => continue,
196 },
197 STATE_HALF_OPEN_PROBE_HELD => {
198 self.record_rejection();
204 return Poll::Ready(Err(CamelError::CircuitOpen(
205 "circuit breaker is half-open (probe in flight)".into(),
206 )));
207 }
208 STATE_HALF_OPEN_PROBE_FREE => {
209 if self
212 .state
213 .state
214 .compare_exchange(
215 STATE_HALF_OPEN_PROBE_FREE,
216 STATE_HALF_OPEN_PROBE_HELD,
217 Ordering::AcqRel,
218 Ordering::Acquire,
219 )
220 .is_ok()
221 {
222 return self.poll_ready_as_probe(cx);
223 }
224 }
226 _ => continue,
227 }
228 }
229 }
230
231 fn call(&mut self, exchange: Exchange) -> Self::Future {
232 let mut decided_half_open = false;
233 loop {
234 match self.state.state.load(Ordering::Acquire) {
235 STATE_CLOSED => break,
236 STATE_OPEN => match self
237 .state
238 .try_transition_to_half_open(self.config.open_duration)
239 {
240 HalfOpenTransition::Transitioned => {
241 tracing::info!("Circuit breaker transitioning from Open to HalfOpen");
242 decided_half_open = true;
243 break;
244 }
245 HalfOpenTransition::NotExpired => {
246 if let Some(mut fallback) = self.config.fallback.clone() {
247 return Box::pin(async move { fallback.call(exchange).await });
248 }
249 self.record_rejection();
250 return Box::pin(async {
251 Err(CamelError::CircuitOpen("circuit breaker is open".into()))
252 });
253 }
254 HalfOpenTransition::LostRace => continue,
255 },
256 STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE => {
257 decided_half_open = true;
261 break;
262 }
263 _ => continue,
264 }
265 }
266
267 let current_is_half_open = decided_half_open
269 || matches!(
270 self.state.state.load(Ordering::Acquire),
271 STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE
272 );
273
274 let mut inner = self.inner.clone();
276 let state = Arc::clone(&self.state);
277 let config = self.config.clone();
278
279 Box::pin(async move {
280 let result = inner.call(exchange).await;
281
282 match &result {
283 Ok(_) => {
284 let s = state.state.load(Ordering::Acquire);
285 if s == STATE_CLOSED {
286 if state.consecutive_failures.load(Ordering::Acquire) == 0 {
288 return result;
289 }
290 state.consecutive_failures.swap(0, Ordering::Release);
291 return result;
292 }
293 if matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
294 state.with_transition(|_opened_at| {
299 let mut recovered = false;
306 for _ in 0..3 {
307 let s = state.state.load(Ordering::Acquire);
308 if s != STATE_HALF_OPEN_PROBE_HELD
309 && s != STATE_HALF_OPEN_PROBE_FREE
310 {
311 break; }
313 if state
314 .state
315 .compare_exchange(
316 s,
317 STATE_CLOSED,
318 Ordering::AcqRel,
319 Ordering::Acquire,
320 )
321 .is_ok()
322 {
323 state.consecutive_failures.swap(0, Ordering::Release);
324 recovered = true;
325 break;
326 }
327 }
330 if recovered {
331 tracing::info!(
332 "Circuit breaker transitioning from HalfOpen to Closed"
333 );
334 }
335 recovered
336 });
337 }
338 }
341 Err(_) => {
342 if current_is_half_open {
343 state.with_transition(|opened_at| {
345 let s = state.state.load(Ordering::Acquire);
346 if !matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE)
347 {
348 return false;
349 }
350 tracing::warn!(
351 "Circuit breaker transitioning from HalfOpen to Open (probe failed)"
352 );
353 *opened_at = Some(Instant::now());
354 let _ = state.state.compare_exchange(
355 s,
356 STATE_OPEN,
357 Ordering::AcqRel,
358 Ordering::Acquire,
359 );
360 true
361 });
362 } else {
363 let s = state.state.load(Ordering::Acquire);
364 if s == STATE_CLOSED {
365 state.with_transition(|opened_at| {
373 let s = state.state.load(Ordering::Acquire);
374 if s != STATE_CLOSED {
375 return false;
376 }
377 let prev =
378 state.consecutive_failures.fetch_add(1, Ordering::AcqRel);
379 if prev + 1 >= config.failure_threshold {
380 *opened_at = Some(Instant::now());
381 if state
382 .state
383 .compare_exchange(
384 STATE_CLOSED,
385 STATE_OPEN,
386 Ordering::AcqRel,
387 Ordering::Acquire,
388 )
389 .is_ok()
390 {
391 tracing::warn!(
392 threshold = config.failure_threshold,
393 "Circuit breaker transitioning from Closed to Open (failure threshold reached)"
394 );
395 }
396 }
397 true
398 });
399 }
400 }
401 }
402 }
403
404 result
405 })
406 }
407}
408
409impl<S> CircuitBreakerService<S>
410where
411 S: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
412 S::Future: Send,
413{
414 fn poll_ready_as_probe(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), CamelError>> {
419 match self.inner.poll_ready(cx) {
420 Poll::Ready(result) => Poll::Ready(result),
421 Poll::Pending => {
422 let _ = self.state.with_transition(|_| {
428 let s = self.state.state.load(Ordering::Acquire);
429 if s == STATE_HALF_OPEN_PROBE_HELD {
430 self.state
431 .state
432 .compare_exchange(
433 STATE_HALF_OPEN_PROBE_HELD,
434 STATE_HALF_OPEN_PROBE_FREE,
435 Ordering::AcqRel,
436 Ordering::Acquire,
437 )
438 .is_ok()
439 } else {
440 false
441 }
442 });
443 Poll::Pending
444 }
445 }
446 }
447}
448
449pub enum CircuitBreakerDecision {
453 Allow,
455 Fallback(BoxProcessor),
458 Reject(CamelError),
460}
461
462#[derive(Clone)]
464pub struct CircuitBreakerGate {
465 config: CircuitBreakerConfig,
466 state: Arc<SharedBreakerState>,
467 route_id: Arc<str>,
468 metrics: Option<Arc<dyn MetricsCollector>>,
469}
470
471impl CircuitBreakerGate {
472 pub fn new(
476 config: CircuitBreakerConfig,
477 route_id: Arc<str>,
478 metrics: Option<Arc<dyn MetricsCollector>>,
479 ) -> Self {
480 Self {
481 config,
482 state: Arc::new(SharedBreakerState::new()),
483 route_id,
484 metrics,
485 }
486 }
487
488 fn record_rejection(&self) {
490 if let Some(ref metrics) = self.metrics {
491 metrics.increment_circuit_breaker_rejection(&self.route_id);
492 }
493 }
494
495 pub fn before_call(&self) -> CircuitBreakerDecision {
496 loop {
497 match self.state.state.load(Ordering::Acquire) {
498 STATE_CLOSED => return CircuitBreakerDecision::Allow,
499 STATE_OPEN => match self
500 .state
501 .try_transition_to_half_open(self.config.open_duration)
502 {
503 HalfOpenTransition::Transitioned => {
504 tracing::info!("Circuit breaker gate: Open → HalfOpen");
505 return CircuitBreakerDecision::Allow;
506 }
507 HalfOpenTransition::NotExpired => {
508 if let Some(ref fallback) = self.config.fallback {
509 return CircuitBreakerDecision::Fallback(fallback.clone());
510 }
511 self.record_rejection();
512 return CircuitBreakerDecision::Reject(CamelError::CircuitOpen(
513 "circuit breaker is open".into(),
514 ));
515 }
516 HalfOpenTransition::LostRace => continue,
517 },
518 STATE_HALF_OPEN_PROBE_HELD => {
519 if let Some(ref fallback) = self.config.fallback {
520 return CircuitBreakerDecision::Fallback(fallback.clone());
521 }
522 self.record_rejection();
523 return CircuitBreakerDecision::Reject(CamelError::CircuitOpen(
524 "circuit breaker is half-open (probe in flight)".into(),
525 ));
526 }
527 STATE_HALF_OPEN_PROBE_FREE => {
528 if self
530 .state
531 .state
532 .compare_exchange(
533 STATE_HALF_OPEN_PROBE_FREE,
534 STATE_HALF_OPEN_PROBE_HELD,
535 Ordering::AcqRel,
536 Ordering::Acquire,
537 )
538 .is_ok()
539 {
540 return CircuitBreakerDecision::Allow;
541 }
542 }
544 _ => continue,
545 }
546 }
547 }
548
549 pub fn after_result(&self, result: &Result<Exchange, CamelError>) {
550 match result {
551 Ok(_) => {
552 let s = self.state.state.load(Ordering::Acquire);
553 if s == STATE_CLOSED {
554 if self.state.consecutive_failures.load(Ordering::Acquire) == 0 {
556 return;
557 }
558 self.state.consecutive_failures.swap(0, Ordering::Release);
559 return;
560 }
561 if matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
562 self.state.with_transition(|_opened_at| {
567 let mut recovered = false;
574 for _ in 0..3 {
575 let s = self.state.state.load(Ordering::Acquire);
576 if s != STATE_HALF_OPEN_PROBE_HELD && s != STATE_HALF_OPEN_PROBE_FREE {
577 break; }
579 if self
580 .state
581 .state
582 .compare_exchange(
583 s,
584 STATE_CLOSED,
585 Ordering::AcqRel,
586 Ordering::Acquire,
587 )
588 .is_ok()
589 {
590 self.state.consecutive_failures.swap(0, Ordering::Release);
591 recovered = true;
592 break;
593 }
594 }
597 if recovered {
598 tracing::info!("Circuit breaker gate: HalfOpen → Closed");
599 }
600 recovered
601 });
602 }
603 }
606 Err(_) => {
607 let s = self.state.state.load(Ordering::Acquire);
608 if matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
609 self.state.with_transition(|opened_at| {
610 let s = self.state.state.load(Ordering::Acquire);
611 if !matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
612 return false;
613 }
614 tracing::warn!("Circuit breaker gate: HalfOpen → Open (probe failed)");
615 *opened_at = Some(Instant::now());
616 let _ = self.state.state.compare_exchange(
617 s,
618 STATE_OPEN,
619 Ordering::AcqRel,
620 Ordering::Acquire,
621 );
622 true
623 });
624 } else if s == STATE_CLOSED {
625 self.state.with_transition(|opened_at| {
632 let s = self.state.state.load(Ordering::Acquire);
633 if s != STATE_CLOSED {
634 return false;
635 }
636 let prev = self
637 .state
638 .consecutive_failures
639 .fetch_add(1, Ordering::AcqRel);
640 if prev + 1 >= self.config.failure_threshold {
641 *opened_at = Some(Instant::now());
642 if self
643 .state
644 .state
645 .compare_exchange(
646 STATE_CLOSED,
647 STATE_OPEN,
648 Ordering::AcqRel,
649 Ordering::Acquire,
650 )
651 .is_ok()
652 {
653 tracing::warn!(
654 threshold = self.config.failure_threshold,
655 "Circuit breaker gate: Closed → Open (failure threshold reached)"
656 );
657 }
658 }
659 true
660 });
661 }
662 }
663 }
664 }
665}
666
667#[cfg(test)]
670mod tests {
671 use super::*;
672 use camel_api::{BoxProcessor, BoxProcessorExt, Message};
673 use std::sync::atomic::AtomicBool;
674 use std::sync::atomic::{AtomicU32, Ordering};
675 use std::time::Duration;
676 use tokio::sync::Barrier;
677 use tower::ServiceExt;
678
679 #[derive(Debug, PartialEq, Eq)]
680 enum ObservedState {
681 Closed { consecutive_failures: u32 },
682 Open,
683 HalfOpen { probe_admitted: bool },
684 }
685
686 fn observe(shared: &SharedBreakerState) -> ObservedState {
687 match shared.state.load(Ordering::Acquire) {
688 STATE_CLOSED => ObservedState::Closed {
689 consecutive_failures: shared.consecutive_failures.load(Ordering::Acquire),
690 },
691 STATE_OPEN => ObservedState::Open,
692 STATE_HALF_OPEN_PROBE_HELD => ObservedState::HalfOpen {
693 probe_admitted: true,
694 },
695 STATE_HALF_OPEN_PROBE_FREE => ObservedState::HalfOpen {
696 probe_admitted: false,
697 },
698 _ => unreachable!("unknown breaker state"),
699 }
700 }
701
702 fn make_exchange() -> Exchange {
703 Exchange::new(Message::new("test"))
704 }
705
706 fn gate_with(config: CircuitBreakerConfig) -> CircuitBreakerGate {
707 CircuitBreakerGate::new(config, Arc::from("test"), None)
708 }
709
710 fn ok_processor() -> BoxProcessor {
711 BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }))
712 }
713
714 fn failing_processor() -> BoxProcessor {
715 BoxProcessor::from_fn(|_ex| {
716 Box::pin(async { Err(CamelError::ProcessorError("boom".into())) })
717 })
718 }
719
720 fn fail_n_times(n: u32) -> BoxProcessor {
721 let count = Arc::new(AtomicU32::new(0));
722 BoxProcessor::from_fn(move |ex| {
723 let count = Arc::clone(&count);
724 Box::pin(async move {
725 let c = count.fetch_add(1, Ordering::SeqCst);
726 if c < n {
727 Err(CamelError::ProcessorError(format!("attempt {c}")))
728 } else {
729 Ok(ex)
730 }
731 })
732 })
733 }
734
735 fn tag_processor(tag: &'static str) -> BoxProcessor {
736 BoxProcessor::from_fn(move |_ex| {
737 Box::pin(async move {
738 let mut out = make_exchange();
739 out.input.body = tag.to_string().into();
740 Ok(out)
741 })
742 })
743 }
744
745 #[tokio::test]
747 async fn test_stays_closed_on_success() {
748 let config = CircuitBreakerConfig::new().failure_threshold(3);
749 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
750 let mut svc = layer.layer(ok_processor());
751
752 for _ in 0..5 {
753 let result = svc.ready().await.unwrap().call(make_exchange()).await;
754 assert!(result.is_ok());
755 }
756
757 assert_eq!(
759 observe(&svc.state),
760 ObservedState::Closed {
761 consecutive_failures: 0
762 }
763 );
764 }
765
766 #[tokio::test]
768 async fn test_opens_after_failure_threshold() {
769 let config = CircuitBreakerConfig::new().failure_threshold(3);
770 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
771 let mut svc = layer.layer(failing_processor());
772
773 for _ in 0..3 {
775 let result = svc.ready().await.unwrap().call(make_exchange()).await;
776 assert!(result.is_err());
777 }
778
779 let waker = futures::task::noop_waker();
781 let mut cx = Context::from_waker(&waker);
782 let poll = Pin::new(&mut svc).poll_ready(&mut cx);
783 match poll {
784 Poll::Ready(Err(CamelError::CircuitOpen(_))) => {} other => panic!("expected CircuitOpen error, got {other:?}"),
786 }
787 }
788
789 #[tokio::test]
791 async fn test_transitions_to_half_open_after_duration() {
792 let config = CircuitBreakerConfig::new()
793 .failure_threshold(2)
794 .open_duration(Duration::from_millis(50));
795 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
796 let mut svc = layer.layer(fail_n_times(2));
799
800 for _ in 0..2 {
802 let _ = svc.ready().await.unwrap().call(make_exchange()).await;
803 }
804
805 tokio::time::sleep(Duration::from_millis(60)).await;
807
808 let result = svc.ready().await.unwrap().call(make_exchange()).await;
810 assert!(result.is_ok(), "half-open probe should succeed");
811
812 assert_eq!(
814 observe(&svc.state),
815 ObservedState::Closed {
816 consecutive_failures: 0
817 }
818 );
819 }
820
821 #[tokio::test]
823 async fn test_half_open_failure_reopens() {
824 let config = CircuitBreakerConfig::new()
825 .failure_threshold(2)
826 .open_duration(Duration::from_millis(50));
827 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
828 let mut svc = layer.layer(failing_processor());
829
830 for _ in 0..2 {
832 let _ = svc.ready().await.unwrap().call(make_exchange()).await;
833 }
834
835 tokio::time::sleep(Duration::from_millis(60)).await;
837
838 let result = svc.ready().await.unwrap().call(make_exchange()).await;
840 assert!(result.is_err());
841
842 assert_eq!(observe(&svc.state), ObservedState::Open);
844 }
845
846 #[tokio::test]
848 async fn test_intermittent_failures_dont_open() {
849 let config = CircuitBreakerConfig::new().failure_threshold(3);
850 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
851
852 let call_count = Arc::new(AtomicU32::new(0));
855 let cc = Arc::clone(&call_count);
856 let inner = BoxProcessor::from_fn(move |ex| {
857 let cc = Arc::clone(&cc);
858 Box::pin(async move {
859 let c = cc.fetch_add(1, Ordering::SeqCst);
860 if c % 3 == 2 {
862 Ok(ex)
863 } else {
864 Err(CamelError::ProcessorError("intermittent".into()))
865 }
866 })
867 });
868
869 let mut svc = layer.layer(inner);
870
871 for _ in 0..6 {
872 let _ = svc.ready().await.unwrap().call(make_exchange()).await;
873 }
874
875 assert!(matches!(observe(&svc.state), ObservedState::Closed { .. }));
877 }
878
879 #[tokio::test]
880 async fn test_open_uses_fallback_when_configured() {
881 let fallback = tag_processor("fallback");
882 let config = CircuitBreakerConfig::new()
883 .failure_threshold(1)
884 .open_duration(Duration::from_secs(60))
885 .fallback(fallback);
886 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
887 let mut svc = layer.layer(failing_processor());
888
889 let _ = svc.ready().await.unwrap().call(make_exchange()).await;
890 let result = svc
891 .ready()
892 .await
893 .unwrap()
894 .call(make_exchange())
895 .await
896 .unwrap();
897 assert_eq!(result.input.body.as_text(), Some("fallback"));
898 }
899
900 #[tokio::test]
901 async fn test_open_without_fallback_returns_err() {
902 let config = CircuitBreakerConfig::new()
903 .failure_threshold(1)
904 .open_duration(Duration::from_secs(60));
905 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
906 let mut svc = layer.layer(failing_processor());
907
908 let _ = svc.ready().await.unwrap().call(make_exchange()).await;
909 let result = svc.ready().await;
910 assert!(matches!(result, Err(CamelError::CircuitOpen(_))));
911 }
912
913 #[test]
916 fn test_cb_gate_before_call_closed_allows() {
917 let gate = gate_with(CircuitBreakerConfig {
918 failure_threshold: 3,
919 open_duration: Duration::from_secs(60),
920 success_threshold: 1,
921 fallback: None,
922 });
923 assert!(matches!(gate.before_call(), CircuitBreakerDecision::Allow));
924 }
925
926 #[test]
927 fn test_cb_gate_records_failures_and_opens() {
928 let gate = gate_with(CircuitBreakerConfig {
929 failure_threshold: 2,
930 open_duration: Duration::from_secs(60),
931 success_threshold: 1,
932 fallback: None,
933 });
934 gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
935 assert!(
936 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
937 "still closed after 1 failure"
938 );
939 gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
940 assert!(
941 matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
942 "should be open after 2 failures"
943 );
944 }
945
946 #[tokio::test]
947 async fn test_cb_gate_closes_on_success() {
948 let gate = gate_with(CircuitBreakerConfig {
949 failure_threshold: 1,
950 open_duration: Duration::from_millis(1),
951 success_threshold: 1,
952 fallback: None,
953 });
954 gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
955 assert!(
956 matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
957 "should be open"
958 );
959 tokio::time::sleep(Duration::from_millis(10)).await;
960 assert!(
961 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
962 "should transition to half-open"
963 );
964 let ex = Exchange::new(Message::new("test"));
965 gate.after_result(&Ok(ex));
966 assert!(
967 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
968 "should be closed again"
969 );
970 }
971
972 #[tokio::test]
973 async fn test_cb_gate_half_open_failure_reopens() {
974 let gate = gate_with(CircuitBreakerConfig {
975 failure_threshold: 1,
976 open_duration: Duration::from_millis(1),
977 success_threshold: 1,
978 fallback: None,
979 });
980 gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
982 assert!(
983 matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
984 "should be open"
985 );
986
987 tokio::time::sleep(Duration::from_millis(10)).await;
989 assert!(
990 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
991 "should be half-open now"
992 );
993
994 gate.after_result(&Err(CamelError::ProcessorError("probe fail".into())));
996 assert!(
997 matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
998 "should be open again after probe failure"
999 );
1000 }
1001
1002 #[test]
1003 fn test_cb_gate_open_with_fallback_returns_fallback() {
1004 let fallback = BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }));
1005 let gate = gate_with(CircuitBreakerConfig {
1006 failure_threshold: 1,
1007 open_duration: Duration::from_secs(60),
1008 success_threshold: 1,
1009 fallback: Some(fallback),
1010 });
1011 gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
1012 assert!(
1013 matches!(gate.before_call(), CircuitBreakerDecision::Fallback(_)),
1014 "should return fallback when open"
1015 );
1016 }
1017
1018 #[test]
1019 fn test_cb_gate_handled_error_counts_as_success() {
1020 let gate = gate_with(CircuitBreakerConfig {
1021 failure_threshold: 1,
1022 open_duration: Duration::from_secs(60),
1023 success_threshold: 1,
1024 fallback: None,
1025 });
1026 let ex = Exchange::new(Message::new("test"));
1027 gate.after_result(&Ok(ex));
1028 assert!(
1029 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1030 "handled error should not trip CB"
1031 );
1032 }
1033
1034 #[test]
1039 fn gate_half_open_admits_only_one_probe() {
1040 let config = CircuitBreakerConfig {
1041 failure_threshold: 1,
1042 open_duration: Duration::from_millis(1),
1043 success_threshold: 1,
1044 fallback: None,
1045 };
1046 let gate = gate_with(config);
1047 gate.after_result(&Err::<Exchange, CamelError>(CamelError::CircuitOpen(
1049 "boom".into(),
1050 )));
1051 std::thread::sleep(Duration::from_millis(10)); let d1 = gate.before_call();
1053 assert!(
1054 matches!(d1, CircuitBreakerDecision::Allow),
1055 "first probe must be admitted"
1056 );
1057 let d2 = gate.before_call();
1058 assert!(
1059 matches!(d2, CircuitBreakerDecision::Reject(_)),
1060 "2nd concurrent caller must be rejected"
1061 );
1062 }
1063
1064 #[tokio::test]
1068 async fn service_half_open_admits_only_one_probe() {
1069 let config = CircuitBreakerConfig::new()
1070 .failure_threshold(1)
1071 .open_duration(Duration::from_millis(1));
1072 let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
1073 let mut svc1 = layer.layer(failing_processor());
1074 let mut svc2 = svc1.clone();
1075
1076 let _ = svc1.ready().await.unwrap().call(make_exchange()).await;
1078
1079 tokio::time::sleep(Duration::from_millis(10)).await;
1081
1082 let waker = futures::task::noop_waker();
1084 let mut cx = Context::from_waker(&waker);
1085 let p1 = std::pin::Pin::new(&mut svc1).poll_ready(&mut cx);
1086 assert!(
1087 matches!(p1, Poll::Ready(Ok(()))),
1088 "first probe admitted, got {p1:?}"
1089 );
1090
1091 let p2 = std::pin::Pin::new(&mut svc2).poll_ready(&mut cx);
1093 match p2 {
1094 Poll::Ready(Err(CamelError::CircuitOpen(_))) => {} other => panic!("expected CircuitOpen error on 2nd probe, got {other:?}"),
1096 }
1097 }
1098
1099 #[derive(Clone)]
1105 struct ProbeReadyService {
1106 ready: Arc<AtomicBool>,
1107 calls: Arc<AtomicU32>,
1108 }
1109
1110 impl Service<Exchange> for ProbeReadyService {
1111 type Response = Exchange;
1112 type Error = CamelError;
1113 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1114
1115 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), CamelError>> {
1116 if self.ready.load(Ordering::Acquire) {
1117 Poll::Ready(Ok(()))
1118 } else {
1119 Poll::Pending
1120 }
1121 }
1122
1123 fn call(&mut self, _exchange: Exchange) -> Self::Future {
1124 let is_trip = self.calls.fetch_add(1, Ordering::AcqRel) == 0;
1125 Box::pin(async move {
1126 if is_trip {
1127 Err(CamelError::ProcessorError("trip".into()))
1128 } else {
1129 Ok(make_exchange())
1130 }
1131 })
1132 }
1133 }
1134
1135 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1138 async fn concurrent_successes_stay_closed_and_clean() {
1139 const TASKS: usize = 8;
1140 const ITERS: usize = 5_000;
1141
1142 let gate = gate_with(
1143 CircuitBreakerConfig::new()
1144 .failure_threshold(8)
1145 .open_duration(Duration::from_secs(3_600)),
1146 );
1147 let barrier = Arc::new(Barrier::new(TASKS));
1148 let mut handles = Vec::with_capacity(TASKS);
1149
1150 for _ in 0..TASKS {
1151 let gate = gate.clone();
1152 let barrier = Arc::clone(&barrier);
1153 handles.push(tokio::spawn(async move {
1154 tokio::time::timeout(Duration::from_secs(5), barrier.wait())
1155 .await
1156 .expect("barrier wait must not deadlock");
1157 for i in 0..ITERS {
1158 match gate.before_call() {
1159 CircuitBreakerDecision::Allow => {}
1160 CircuitBreakerDecision::Fallback(_) => panic!(
1161 "no fallback configured, yet iteration {i} got Fallback: state={:?}",
1162 observe(&gate.state)
1163 ),
1164 CircuitBreakerDecision::Reject(err) => panic!(
1165 "success storm iteration {i} was rejected: {err:?}, state={:?}",
1166 observe(&gate.state)
1167 ),
1168 }
1169 gate.after_result(&Ok(make_exchange()));
1170 }
1171 }));
1172 }
1173 for handle in handles {
1174 handle
1175 .await
1176 .expect("success storm task panicked before joining");
1177 }
1178
1179 assert_eq!(
1180 observe(&gate.state),
1181 ObservedState::Closed {
1182 consecutive_failures: 0
1183 },
1184 "40k concurrent successes must never trip the breaker or dirty the counter"
1185 );
1186 }
1187
1188 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1192 async fn concurrent_before_call_admits_exactly_one_probe() {
1193 const TASKS: usize = 8;
1194 const ROUNDS: usize = 25;
1195
1196 let open_duration = Duration::from_millis(10);
1197 let gate = gate_with(
1198 CircuitBreakerConfig::new()
1199 .failure_threshold(1)
1200 .open_duration(open_duration),
1201 );
1202
1203 for round in 0..ROUNDS {
1204 gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1205 format!("trip {round}"),
1206 )));
1207 assert_eq!(
1208 observe(&gate.state),
1209 ObservedState::Open,
1210 "round {round}: a single failure must trip the threshold(1) breaker"
1211 );
1212
1213 tokio::time::sleep(open_duration + Duration::from_millis(10)).await; let barrier = Arc::new(Barrier::new(TASKS));
1216 let mut handles = Vec::with_capacity(TASKS);
1217 for _ in 0..TASKS {
1218 let gate = gate.clone();
1219 let barrier = Arc::clone(&barrier);
1220 handles.push(tokio::spawn(async move {
1221 tokio::time::timeout(Duration::from_secs(5), barrier.wait())
1222 .await
1223 .expect("barrier wait must not deadlock");
1224 gate.before_call()
1225 }));
1226 }
1227
1228 let mut allows = 0usize;
1229 let mut rejects = 0usize;
1230 for handle in handles {
1231 match handle.await.expect("probe race task panicked") {
1232 CircuitBreakerDecision::Allow => allows += 1,
1233 CircuitBreakerDecision::Reject(_) => rejects += 1,
1234 CircuitBreakerDecision::Fallback(_) => {
1235 panic!("round {round}: no fallback is configured")
1236 }
1237 }
1238 }
1239 assert_eq!(
1240 allows, 1,
1241 "round {round}: exactly one concurrent caller may be admitted as the probe"
1242 );
1243 assert_eq!(
1244 rejects, 7,
1245 "round {round}: every non-probe caller must be rejected"
1246 );
1247 assert_eq!(
1248 observe(&gate.state),
1249 ObservedState::HalfOpen {
1250 probe_admitted: true
1251 },
1252 "round {round}: the admitted probe must hold the single probe slot"
1253 );
1254
1255 gate.after_result(&Ok(make_exchange()));
1257 assert_eq!(
1258 observe(&gate.state),
1259 ObservedState::Closed {
1260 consecutive_failures: 0
1261 },
1262 "round {round}: the successful probe must close the circuit"
1263 );
1264 }
1265 }
1266
1267 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1271 async fn concurrent_failures_open_exactly_at_threshold() {
1272 const TASKS: usize = 8;
1279 const PER_TASK: usize = 8;
1280 const THRESHOLD: u32 = 64;
1281
1282 let gate_a = gate_with(
1283 CircuitBreakerConfig::new()
1284 .failure_threshold(THRESHOLD)
1285 .open_duration(Duration::from_secs(60 * 60)),
1286 );
1287 let barrier = Arc::new(Barrier::new(TASKS));
1288 let mut handles = Vec::with_capacity(TASKS);
1289
1290 for _ in 0..TASKS {
1291 let gate = gate_a.clone();
1292 let barrier = Arc::clone(&barrier);
1293 handles.push(tokio::spawn(async move {
1294 tokio::time::timeout(Duration::from_secs(5), barrier.wait())
1295 .await
1296 .expect("barrier wait must not deadlock");
1297 for _ in 0..PER_TASK {
1298 gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1299 "boom".into(),
1300 )));
1301 }
1302 }));
1303 }
1304 for handle in handles {
1305 handle.await.expect("threshold storm task panicked");
1306 }
1307
1308 assert_eq!(
1309 observe(&gate_a.state),
1310 ObservedState::Open,
1311 "exactly {THRESHOLD} concurrent failures must open the circuit (no lost increment)"
1312 );
1313 assert!(
1314 matches!(gate_a.before_call(), CircuitBreakerDecision::Reject(_)),
1315 "a freshly opened circuit must reject before expiry"
1316 );
1317
1318 let open_duration = Duration::from_millis(10);
1320 let gate_b = gate_with(
1321 CircuitBreakerConfig::new()
1322 .failure_threshold(1)
1323 .open_duration(open_duration),
1324 );
1325 gate_b.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1326 "boom".into(),
1327 )));
1328 assert_eq!(
1329 observe(&gate_b.state),
1330 ObservedState::Open,
1331 "a single failure must trip a threshold-1 circuit"
1332 );
1333
1334 tokio::time::sleep(open_duration + Duration::from_millis(10)).await; assert!(
1336 matches!(gate_b.before_call(), CircuitBreakerDecision::Allow),
1337 "an expired circuit must admit the probe"
1338 );
1339 gate_b.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1340 "probe".into(),
1341 )));
1342 assert_eq!(
1343 observe(&gate_b.state),
1344 ObservedState::Open,
1345 "a failed probe must reopen the circuit"
1346 );
1347 }
1348
1349 #[tokio::test]
1352 async fn expiry_reopens_the_probe_path() {
1353 let open_duration = Duration::from_millis(20);
1354 let gate = gate_with(
1355 CircuitBreakerConfig::new()
1356 .failure_threshold(1)
1357 .open_duration(open_duration),
1358 );
1359
1360 gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1361 "boom".into(),
1362 )));
1363 assert!(
1364 matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
1365 "an open circuit must reject before expiry"
1366 );
1367
1368 tokio::time::sleep(Duration::from_millis(50)).await; assert!(
1370 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1371 "an expired circuit must admit the first caller as the probe"
1372 );
1373 assert_eq!(
1374 observe(&gate.state),
1375 ObservedState::HalfOpen {
1376 probe_admitted: true
1377 },
1378 "the expiry winner must hold the probe slot"
1379 );
1380 assert!(
1381 matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
1382 "the single-probe gate must reject an immediate second caller"
1383 );
1384
1385 gate.after_result(&Ok(make_exchange()));
1386 assert_eq!(
1387 observe(&gate.state),
1388 ObservedState::Closed {
1389 consecutive_failures: 0
1390 },
1391 "a successful probe must close the circuit"
1392 );
1393
1394 tokio::time::sleep(Duration::from_millis(50)).await; assert!(
1397 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1398 "expiry must never re-open a Closed circuit"
1399 );
1400 assert_eq!(
1401 observe(&gate.state),
1402 ObservedState::Closed {
1403 consecutive_failures: 0
1404 },
1405 "the circuit must stay Closed after the probe recovery"
1406 );
1407 }
1408
1409 #[tokio::test]
1412 async fn success_after_half_open_closes_and_resets_counter() {
1413 let open_duration = Duration::from_millis(10);
1414 let gate = gate_with(
1415 CircuitBreakerConfig::new()
1416 .failure_threshold(2)
1417 .open_duration(open_duration),
1418 );
1419
1420 for _ in 0..2 {
1421 gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1422 "boom".into(),
1423 )));
1424 }
1425 assert_eq!(
1426 observe(&gate.state),
1427 ObservedState::Open,
1428 "threshold(2) must open after two failures"
1429 );
1430
1431 tokio::time::sleep(Duration::from_millis(20)).await; assert!(
1433 matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1434 "an expired circuit must admit the probe"
1435 );
1436 gate.after_result(&Ok(make_exchange()));
1437 assert_eq!(
1438 observe(&gate.state),
1439 ObservedState::Closed {
1440 consecutive_failures: 0
1441 },
1442 "a successful probe must close the circuit and reset the counter"
1443 );
1444
1445 for _ in 0..100 {
1446 gate.after_result(&Ok(make_exchange()));
1447 }
1448 assert_eq!(
1449 observe(&gate.state),
1450 ObservedState::Closed {
1451 consecutive_failures: 0
1452 },
1453 "further successes must keep the recovered circuit Closed with a zeroed counter"
1454 );
1455 }
1456
1457 #[tokio::test]
1460 async fn poll_ready_pending_releases_the_probe_claim() {
1461 let open_duration = Duration::from_millis(10);
1462 let ready = Arc::new(AtomicBool::new(false));
1463 let calls = Arc::new(AtomicU32::new(0));
1464 let layer = CircuitBreakerLayer::new(
1465 CircuitBreakerConfig::new()
1466 .failure_threshold(1)
1467 .open_duration(open_duration),
1468 Arc::from("test"),
1469 None,
1470 );
1471 let mut svc = layer.layer(ProbeReadyService {
1472 ready: Arc::clone(&ready),
1473 calls: Arc::clone(&calls),
1474 });
1475
1476 let trip = svc.call(make_exchange()).await;
1479 assert!(trip.is_err(), "the first inner call must fail to trip");
1480 assert_eq!(
1481 observe(&svc.state),
1482 ObservedState::Open,
1483 "one failed call must trip the threshold(1) breaker"
1484 );
1485 tokio::time::sleep(Duration::from_millis(20)).await; let waker = futures::task::noop_waker();
1488 let mut cx = Context::from_waker(&waker);
1489
1490 let first = Pin::new(&mut svc).poll_ready(&mut cx);
1493 assert!(
1494 matches!(first, Poll::Pending),
1495 "not-ready inner service must surface Pending, got {first:?}"
1496 );
1497 assert_eq!(
1498 observe(&svc.state),
1499 ObservedState::HalfOpen {
1500 probe_admitted: false
1501 },
1502 "Pending must release the probe claim (HELD -> FREE)"
1503 );
1504
1505 ready.store(true, Ordering::Release);
1508 let second = Pin::new(&mut svc).poll_ready(&mut cx);
1509 assert!(
1510 matches!(second, Poll::Ready(Ok(()))),
1511 "a ready inner service must let the probe proceed, got {second:?}"
1512 );
1513 assert_eq!(
1514 observe(&svc.state),
1515 ObservedState::HalfOpen {
1516 probe_admitted: true
1517 },
1518 "the re-poll must re-claim the probe slot (FREE -> HELD)"
1519 );
1520
1521 let result = svc.call(make_exchange()).await;
1523 assert!(result.is_ok(), "the half-open probe must succeed");
1524 assert_eq!(
1525 observe(&svc.state),
1526 ObservedState::Closed {
1527 consecutive_failures: 0
1528 },
1529 "a successful probe must close the circuit and reset the counter"
1530 );
1531 }
1532}