Skip to main content

camel_processor/
circuit_breaker.rs

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
13// ── State ──────────────────────────────────────────────────────────────
14
15/// Circuit is closed — all calls pass through.
16const STATE_CLOSED: u8 = 0;
17/// Circuit is open — calls are rejected or fall back until expiry.
18const STATE_OPEN: u8 = 1;
19/// Half-open with the single probe slot taken (a probe is in flight, or the
20/// caller that observed expiry claims the slot).
21const STATE_HALF_OPEN_PROBE_HELD: u8 = 2;
22/// Half-open with the probe slot free — released when `poll_ready` returned
23/// `Pending` while a probe was claimed, so a re-poll can re-claim it (D-M1).
24const STATE_HALF_OPEN_PROBE_FREE: u8 = 3;
25
26/// Shared breaker state. The closed/success path touches only `state` and
27/// `consecutive_failures` with plain atomic loads; `opened_at` is the single
28/// serializer for slow-path transitions (opens, recovery close, expiry).
29struct SharedBreakerState {
30    state: AtomicU8,
31    consecutive_failures: AtomicU32,
32    opened_at: Mutex<Option<Instant>>,
33}
34
35/// Outcome of an attempt to claim the half-open probe after expiry.
36enum HalfOpenTransition {
37    /// The caller won the Open → HalfOpen transition and becomes the probe.
38    Transitioned,
39    /// The circuit is still within `open_duration`.
40    NotExpired,
41    /// Expiry passed but another caller won the CAS; re-load and retry.
42    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    /// Run a slow-path state transition while holding the `opened_at` lock.
55    ///
56    /// The closure re-loads `state` under the lock and acts only if it still
57    /// shows the expected state, so qualification, timestamp publication, and
58    /// the state CAS are atomic against recovery.
59    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    /// Attempt the Open → HalfOpen(probe claimed) transition. Returns
65    /// [`HalfOpenTransition::Transitioned`] when the caller won the transition
66    /// (it becomes the probe). The `opened_at` lock is held across the expiry
67    /// check and the CAS so a freshly re-opened circuit cannot be half-opened
68    /// off a stale timestamp.
69    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// ── Layer ──────────────────────────────────────────────────────────────
90
91/// Tower Layer that wraps an inner service with circuit-breaker logic.
92#[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    /// `route_id` + `metrics` thread the rejection counter
102    /// (`camel_circuit_breaker_rejections_total{route}`) into the wrapped
103    /// service: every open-breaker fast-fail counts as a rejection, never
104    /// as an error (dashboard-observability D2).
105    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
133// ── Service ────────────────────────────────────────────────────────────
134
135/// Tower Service implementing the circuit-breaker pattern.
136pub 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    /// Count one open-breaker fast-fail as a circuit-breaker rejection.
158    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                    // A probe is already in flight — reject this concurrent
199                    // caller. Always Err (even with fallback): returning Ok
200                    // here would let a 2nd caller reach call() → inner,
201                    // bypassing the single-probe gate. The caller retries
202                    // when after_result resolves the probe state.
203                    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                    // Claim the probe slot and forward to inner. If inner
210                    // returns Pending, release the claim so re-poll works.
211                    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                    // Lost the claim race — re-load and decide again.
225                }
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                    // D-M1: the single-probe gate lives in poll_ready — 2nd callers
258                    // get Err there and never reach call(). The probe caller (whose
259                    // poll_ready claimed the probe) proceeds here to inner.
260                    decided_half_open = true;
261                    break;
262                }
263                _ => continue,
264            }
265        }
266
267        // One load replaces the old second lock snapshot.
268        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        // Clone inner service (Tower pattern) and state handle.
275        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                        // Step 1 (bd rc-bnsxr) fast path: no RMW when already clean.
287                        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                        // Recovery runs under the transition lock: the counter
295                        // reset and the Close CAS are serialized against every
296                        // other slow-path transition, so an observer of CLOSED
297                        // never sees a stale pre-open failure count.
298                        state.with_transition(|_opened_at| {
299                            // The CAS can only lose to the lockless probe admission
300                            // (FREE -> HELD): every other HALF-code mutation holds
301                            // this same lock. A lost recovery is retried so a
302                            // concurrent admission cannot silently drop a completed
303                            // probe's recovery; the log fires only when the
304                            // transition happened.
305                            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; // state moved to OPEN/CLOSED — nothing to recover
312                                }
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                                // CAS lost only to the lockless probe admission
328                                // (FREE -> HELD); reload and retry.
329                            }
330                            if recovered {
331                                tracing::info!(
332                                    "Circuit breaker transitioning from HalfOpen to Closed"
333                                );
334                            }
335                            recovered
336                        });
337                    }
338                    // s == STATE_OPEN: leave untouched — success does not close
339                    // an open circuit.
340                }
341                Err(_) => {
342                    if current_is_half_open {
343                        // Half-open failure → reopen circuit.
344                        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                            // Slow-path transitions serialize on the opened_at
366                            // lock: qualification, timestamp publication, and
367                            // the state CAS hold the lock together, and recovery
368                            // (probe success) takes the same lock, so a threshold
369                            // qualification can never be split across an
370                            // open/expiry/recovery cycle — the invariant the old
371                            // mutex gave per after_result call.
372                            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    /// Forward to the inner service while holding the claimed half-open probe.
415    /// If the inner service returns `Pending` we MUST release the probe claim
416    /// so a re-poll can re-claim it; otherwise the breaker wedges until the
417    /// half-open probe completes.
418    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                // Release the probe claim so a re-poll can re-claim it; otherwise
423                // the breaker wedges until the half-open probe completes.
424                // (Holds the transition lock: recovery serializes against this
425                // release — a recovery reload+CAS can no longer be invalidated by
426                // it.)
427                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
449// ── Gate ──────────────────────────────────────────────────────────────
450
451/// Decision returned by [`CircuitBreakerGate::before_call`].
452pub enum CircuitBreakerDecision {
453    /// Circuit is closed or half-open — proceed with the pipeline call.
454    Allow,
455    /// Circuit is open but a fallback processor is configured.
456    /// Call this processor instead of the main pipeline.
457    Fallback(BoxProcessor),
458    /// Circuit is open with no fallback — reject the call.
459    Reject(CamelError),
460}
461
462/// Reusable circuit-breaker gate with explicit `before_call`/`after_result` API.
463#[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    /// `route_id` + `metrics` mirror [`CircuitBreakerLayer::new`]: the
473    /// RouteChannelService breaker path counts its own fast-fail Reject
474    /// arms on `camel_circuit_breaker_rejections_total{route}`.
475    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    /// Count one open-breaker fast-fail as a circuit-breaker rejection.
489    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                    // Admit ourselves as the probe.
529                    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                    // Lost the claim race — re-load and decide again.
543                }
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                    // Step 1 (bd rc-bnsxr) fast path: no RMW when already clean.
555                    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                    // Recovery runs under the transition lock: the counter reset
563                    // and the Close CAS are serialized against every other
564                    // slow-path transition, so an observer of CLOSED never sees
565                    // a stale pre-open failure count.
566                    self.state.with_transition(|_opened_at| {
567                        // The CAS can only lose to the lockless probe admission
568                        // (FREE -> HELD): every other HALF-code mutation holds
569                        // this same lock. A lost recovery is retried so a
570                        // concurrent admission cannot silently drop a completed
571                        // probe's recovery; the log fires only when the
572                        // transition happened.
573                        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; // state moved to OPEN/CLOSED — nothing to recover
578                            }
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                            // CAS lost only to the lockless probe admission
595                            // (FREE -> HELD); reload and retry.
596                        }
597                        if recovered {
598                            tracing::info!("Circuit breaker gate: HalfOpen → Closed");
599                        }
600                        recovered
601                    });
602                }
603                // s == STATE_OPEN: leave untouched — success does not close an
604                // open circuit.
605            }
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                    // Slow-path transitions serialize on the opened_at lock:
626                    // qualification, timestamp publication, and the state CAS
627                    // hold the lock together, and recovery (probe success) takes
628                    // the same lock, so a threshold qualification can never be
629                    // split across an open/expiry/recovery cycle — the invariant
630                    // the old mutex gave per after_result call.
631                    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// ── Tests ──────────────────────────────────────────────────────────────
668
669#[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    /// 1. Circuit stays closed on success.
746    #[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        // State should still be closed with 0 failures.
758        assert_eq!(
759            observe(&svc.state),
760            ObservedState::Closed {
761                consecutive_failures: 0
762            }
763        );
764    }
765
766    /// 2. Circuit opens after failure_threshold consecutive failures.
767    #[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        // Three consecutive failures should open the circuit.
774        for _ in 0..3 {
775            let result = svc.ready().await.unwrap().call(make_exchange()).await;
776            assert!(result.is_err());
777        }
778
779        // The next poll_ready should return CircuitOpen error.
780        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(_))) => {} // expected
785            other => panic!("expected CircuitOpen error, got {other:?}"),
786        }
787    }
788
789    /// 3. Circuit transitions to half-open after open_duration.
790    #[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        // Use fail_n_times(2) so the first 2 calls fail (opening the circuit),
797        // then the third (half-open probe) succeeds.
798        let mut svc = layer.layer(fail_n_times(2));
799
800        // Trigger 2 failures to open the circuit.
801        for _ in 0..2 {
802            let _ = svc.ready().await.unwrap().call(make_exchange()).await;
803        }
804
805        // Circuit is now open. Wait for open_duration to elapse.
806        tokio::time::sleep(Duration::from_millis(60)).await;
807
808        // poll_ready should transition to HalfOpen and succeed.
809        let result = svc.ready().await.unwrap().call(make_exchange()).await;
810        assert!(result.is_ok(), "half-open probe should succeed");
811
812        // After successful probe, circuit should be back to Closed.
813        assert_eq!(
814            observe(&svc.state),
815            ObservedState::Closed {
816                consecutive_failures: 0
817            }
818        );
819    }
820
821    /// 4. Half-open failure reopens circuit.
822    #[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        // Trigger 2 failures to open the circuit.
831        for _ in 0..2 {
832            let _ = svc.ready().await.unwrap().call(make_exchange()).await;
833        }
834
835        // Wait for open_duration to elapse, transitioning to HalfOpen.
836        tokio::time::sleep(Duration::from_millis(60)).await;
837
838        // Half-open probe fails → circuit reopens.
839        let result = svc.ready().await.unwrap().call(make_exchange()).await;
840        assert!(result.is_err());
841
842        // Circuit should be open again.
843        assert_eq!(observe(&svc.state), ObservedState::Open);
844    }
845
846    /// 5. Intermittent failures below threshold don't open circuit.
847    #[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        // Alternate: fail, fail, success, fail, fail, success
853        // The counter should reset on success, so threshold of 3 is never reached.
854        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                // Pattern: fail, fail, success, fail, fail, success
861                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        // Circuit should still be closed because successes reset the counter.
876        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    // ── CircuitBreakerGate tests ──────────────────────────────────────────
914
915    #[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        // Open the circuit
981        gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
982        assert!(
983            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
984            "should be open"
985        );
986
987        // Wait for open_duration to elapse → transitions to HalfOpen
988        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        // Probe fails in HalfOpen → should reopen
995        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    // ── D-M1: half-open admits a single probe ─────────────────────────────
1035
1036    /// Gate path: only the first caller in HalfOpen is admitted as the probe;
1037    /// every subsequent caller is rejected.
1038    #[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        // Trip: one failure → Open
1048        gate.after_result(&Err::<Exchange, CamelError>(CamelError::CircuitOpen(
1049            "boom".into(),
1050        )));
1051        std::thread::sleep(Duration::from_millis(10)); // past open_duration
1052        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    /// Service path: only the first `poll_ready` in HalfOpen is admitted as the
1065    /// probe; every subsequent `poll_ready` from a cloned service must be
1066    /// rejected with `CircuitOpen`.
1067    #[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        // Trip to Open
1077        let _ = svc1.ready().await.unwrap().call(make_exchange()).await;
1078
1079        // Wait past open_duration
1080        tokio::time::sleep(Duration::from_millis(10)).await;
1081
1082        // svc1 poll_ready: admitted as probe → Ready(Ok(()))
1083        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        // svc2 poll_ready: must be rejected
1092        let p2 = std::pin::Pin::new(&mut svc2).poll_ready(&mut cx);
1093        match p2 {
1094            Poll::Ready(Err(CamelError::CircuitOpen(_))) => {} // expected
1095            other => panic!("expected CircuitOpen error on 2nd probe, got {other:?}"),
1096        }
1097    }
1098
1099    // ── bd rc-bnsxr item 3: deterministic concurrency coverage ────────────
1100
1101    /// Inner service for the D-M1 release dance: its `poll_ready` is gated on
1102    /// a flag the test flips, and its first `call` fails so the breaker can be
1103    /// tripped through the normal failure path.
1104    #[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    /// 1. A concurrent success storm never observes a failure and leaves the
1136    /// circuit Closed with a clean counter.
1137    #[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    /// 2. Under a barrier-start race, exactly one caller claims the half-open
1189    /// probe; every other concurrent caller is rejected. Repeats 25 recovery
1190    /// cycles to shake scheduling skew.
1191    #[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; // allow-test-sleep: expiry timer is the behavior under test
1214
1215            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            // Resolve the probe so the next round starts from Closed.
1256            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    /// 3. Exactly-threshold concurrent failures must all be counted: no lost
1268    /// increment may leave the circuit Closed, and no extra transition may
1269    /// double-open it. A failing half-open probe then reopens it.
1270    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1271    async fn concurrent_failures_open_exactly_at_threshold() {
1272        // Phase A pins threshold atomicity (exactly-threshold concurrent failures
1273        // must open; a lost increment would leave it Closed) behind a 1-hour open
1274        // window so the post-join assertions carry no timing deadline. Phase B
1275        // covers probe-fail reopen on a fresh short-expiry gate, single-tasked.
1276
1277        // Phase A — threshold qualification, deterministic.
1278        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        // Phase B — probe-fail reopen on a fresh short-expiry gate, no concurrency.
1319        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; // allow-test-sleep: expiry timer is the behavior under test
1335        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    /// 4. Expiry reopens the probe path exactly once, and expiry must never
1350    /// re-open a circuit that a successful probe already closed.
1351    #[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; // allow-test-sleep: expiry timer is the behavior under test
1369        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        // No failures: waiting past open_duration again must not re-open it.
1395        tokio::time::sleep(Duration::from_millis(50)).await; // allow-test-sleep: expiry timer is the behavior under test
1396        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    /// 5. A half-open success closes the circuit and resets the counter, and
1410    /// further successes keep it Closed.
1411    #[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; // allow-test-sleep: expiry timer is the behavior under test
1432        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    /// 6. D-M1 release dance: a `poll_ready` Pending from the inner service
1458    /// releases the probe claim so a re-poll can re-claim it.
1459    #[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        // Trip the breaker through the ordinary failure path. The inner
1477        // service's first call fails; readiness is irrelevant to `call`.
1478        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; // allow-test-sleep: expiry timer is the behavior under test
1486
1487        let waker = futures::task::noop_waker();
1488        let mut cx = Context::from_waker(&waker);
1489
1490        // First poll: expiry claims the probe, inner says Pending, so the
1491        // claim must be released back to FREE.
1492        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        // Re-poll once the inner service is ready: the claim is re-taken and
1506        // the breaker admits the probe.
1507        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        // Complete the probe: the second inner call succeeds and closes.
1522        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}