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                // A business error is a success for the breaker (owner
284                // decision Q4): it neither counts toward the failure
285                // threshold nor reopens a half-open probe. The result is
286                // still returned unchanged to the caller.
287                Ok(_) | Err(CamelError::Business { .. }) => {
288                    let s = state.state.load(Ordering::Acquire);
289                    if s == STATE_CLOSED {
290                        // Step 1 (bd rc-bnsxr) fast path: no RMW when already clean.
291                        if state.consecutive_failures.load(Ordering::Acquire) == 0 {
292                            return result;
293                        }
294                        state.consecutive_failures.swap(0, Ordering::Release);
295                        return result;
296                    }
297                    if matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
298                        // Recovery runs under the transition lock: the counter
299                        // reset and the Close CAS are serialized against every
300                        // other slow-path transition, so an observer of CLOSED
301                        // never sees a stale pre-open failure count.
302                        state.with_transition(|_opened_at| {
303                            // The CAS can only lose to the lockless probe admission
304                            // (FREE -> HELD): every other HALF-code mutation holds
305                            // this same lock. A lost recovery is retried so a
306                            // concurrent admission cannot silently drop a completed
307                            // probe's recovery; the log fires only when the
308                            // transition happened.
309                            let mut recovered = false;
310                            for _ in 0..3 {
311                                let s = state.state.load(Ordering::Acquire);
312                                if s != STATE_HALF_OPEN_PROBE_HELD
313                                    && s != STATE_HALF_OPEN_PROBE_FREE
314                                {
315                                    break; // state moved to OPEN/CLOSED — nothing to recover
316                                }
317                                if state
318                                    .state
319                                    .compare_exchange(
320                                        s,
321                                        STATE_CLOSED,
322                                        Ordering::AcqRel,
323                                        Ordering::Acquire,
324                                    )
325                                    .is_ok()
326                                {
327                                    state.consecutive_failures.swap(0, Ordering::Release);
328                                    recovered = true;
329                                    break;
330                                }
331                                // CAS lost only to the lockless probe admission
332                                // (FREE -> HELD); reload and retry.
333                            }
334                            if recovered {
335                                tracing::info!(
336                                    "Circuit breaker transitioning from HalfOpen to Closed"
337                                );
338                            }
339                            recovered
340                        });
341                    }
342                    // s == STATE_OPEN: leave untouched — success does not close
343                    // an open circuit.
344                }
345                Err(_) => {
346                    if current_is_half_open {
347                        // Half-open failure → reopen circuit.
348                        state.with_transition(|opened_at| {
349                            let s = state.state.load(Ordering::Acquire);
350                            if !matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE)
351                            {
352                                return false;
353                            }
354                            tracing::warn!(
355                                "Circuit breaker transitioning from HalfOpen to Open (probe failed)"
356                            );
357                            *opened_at = Some(Instant::now());
358                            let _ = state.state.compare_exchange(
359                                s,
360                                STATE_OPEN,
361                                Ordering::AcqRel,
362                                Ordering::Acquire,
363                            );
364                            true
365                        });
366                    } else {
367                        let s = state.state.load(Ordering::Acquire);
368                        if s == STATE_CLOSED {
369                            // Slow-path transitions serialize on the opened_at
370                            // lock: qualification, timestamp publication, and
371                            // the state CAS hold the lock together, and recovery
372                            // (probe success) takes the same lock, so a threshold
373                            // qualification can never be split across an
374                            // open/expiry/recovery cycle — the invariant the old
375                            // mutex gave per after_result call.
376                            state.with_transition(|opened_at| {
377                                let s = state.state.load(Ordering::Acquire);
378                                if s != STATE_CLOSED {
379                                    return false;
380                                }
381                                let prev =
382                                    state.consecutive_failures.fetch_add(1, Ordering::AcqRel);
383                                if prev + 1 >= config.failure_threshold {
384                                    *opened_at = Some(Instant::now());
385                                    if state
386                                        .state
387                                        .compare_exchange(
388                                            STATE_CLOSED,
389                                            STATE_OPEN,
390                                            Ordering::AcqRel,
391                                            Ordering::Acquire,
392                                        )
393                                        .is_ok()
394                                    {
395                                        tracing::warn!(
396                                            threshold = config.failure_threshold,
397                                            "Circuit breaker transitioning from Closed to Open (failure threshold reached)"
398                                        );
399                                    }
400                                }
401                                true
402                            });
403                        }
404                    }
405                }
406            }
407
408            result
409        })
410    }
411}
412
413impl<S> CircuitBreakerService<S>
414where
415    S: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
416    S::Future: Send,
417{
418    /// Forward to the inner service while holding the claimed half-open probe.
419    /// If the inner service returns `Pending` we MUST release the probe claim
420    /// so a re-poll can re-claim it; otherwise the breaker wedges until the
421    /// half-open probe completes.
422    fn poll_ready_as_probe(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), CamelError>> {
423        match self.inner.poll_ready(cx) {
424            Poll::Ready(result) => Poll::Ready(result),
425            Poll::Pending => {
426                // Release the probe claim so a re-poll can re-claim it; otherwise
427                // the breaker wedges until the half-open probe completes.
428                // (Holds the transition lock: recovery serializes against this
429                // release — a recovery reload+CAS can no longer be invalidated by
430                // it.)
431                let _ = self.state.with_transition(|_| {
432                    let s = self.state.state.load(Ordering::Acquire);
433                    if s == STATE_HALF_OPEN_PROBE_HELD {
434                        self.state
435                            .state
436                            .compare_exchange(
437                                STATE_HALF_OPEN_PROBE_HELD,
438                                STATE_HALF_OPEN_PROBE_FREE,
439                                Ordering::AcqRel,
440                                Ordering::Acquire,
441                            )
442                            .is_ok()
443                    } else {
444                        false
445                    }
446                });
447                Poll::Pending
448            }
449        }
450    }
451}
452
453// ── Gate ──────────────────────────────────────────────────────────────
454
455/// Decision returned by [`CircuitBreakerGate::before_call`].
456pub enum CircuitBreakerDecision {
457    /// Circuit is closed or half-open — proceed with the pipeline call.
458    Allow,
459    /// Circuit is open but a fallback processor is configured.
460    /// Call this processor instead of the main pipeline.
461    Fallback(BoxProcessor),
462    /// Circuit is open with no fallback — reject the call.
463    Reject(CamelError),
464}
465
466/// Reusable circuit-breaker gate with explicit `before_call`/`after_result` API.
467#[derive(Clone)]
468pub struct CircuitBreakerGate {
469    config: CircuitBreakerConfig,
470    state: Arc<SharedBreakerState>,
471    route_id: Arc<str>,
472    metrics: Option<Arc<dyn MetricsCollector>>,
473}
474
475impl CircuitBreakerGate {
476    /// `route_id` + `metrics` mirror [`CircuitBreakerLayer::new`]: the
477    /// RouteChannelService breaker path counts its own fast-fail Reject
478    /// arms on `camel_circuit_breaker_rejections_total{route}`.
479    pub fn new(
480        config: CircuitBreakerConfig,
481        route_id: Arc<str>,
482        metrics: Option<Arc<dyn MetricsCollector>>,
483    ) -> Self {
484        Self {
485            config,
486            state: Arc::new(SharedBreakerState::new()),
487            route_id,
488            metrics,
489        }
490    }
491
492    /// Count one open-breaker fast-fail as a circuit-breaker rejection.
493    fn record_rejection(&self) {
494        if let Some(ref metrics) = self.metrics {
495            metrics.increment_circuit_breaker_rejection(&self.route_id);
496        }
497    }
498
499    pub fn before_call(&self) -> CircuitBreakerDecision {
500        loop {
501            match self.state.state.load(Ordering::Acquire) {
502                STATE_CLOSED => return CircuitBreakerDecision::Allow,
503                STATE_OPEN => match self
504                    .state
505                    .try_transition_to_half_open(self.config.open_duration)
506                {
507                    HalfOpenTransition::Transitioned => {
508                        tracing::info!("Circuit breaker gate: Open → HalfOpen");
509                        return CircuitBreakerDecision::Allow;
510                    }
511                    HalfOpenTransition::NotExpired => {
512                        if let Some(ref fallback) = self.config.fallback {
513                            return CircuitBreakerDecision::Fallback(fallback.clone());
514                        }
515                        self.record_rejection();
516                        return CircuitBreakerDecision::Reject(CamelError::CircuitOpen(
517                            "circuit breaker is open".into(),
518                        ));
519                    }
520                    HalfOpenTransition::LostRace => continue,
521                },
522                STATE_HALF_OPEN_PROBE_HELD => {
523                    if let Some(ref fallback) = self.config.fallback {
524                        return CircuitBreakerDecision::Fallback(fallback.clone());
525                    }
526                    self.record_rejection();
527                    return CircuitBreakerDecision::Reject(CamelError::CircuitOpen(
528                        "circuit breaker is half-open (probe in flight)".into(),
529                    ));
530                }
531                STATE_HALF_OPEN_PROBE_FREE => {
532                    // Admit ourselves as the probe.
533                    if self
534                        .state
535                        .state
536                        .compare_exchange(
537                            STATE_HALF_OPEN_PROBE_FREE,
538                            STATE_HALF_OPEN_PROBE_HELD,
539                            Ordering::AcqRel,
540                            Ordering::Acquire,
541                        )
542                        .is_ok()
543                    {
544                        return CircuitBreakerDecision::Allow;
545                    }
546                    // Lost the claim race — re-load and decide again.
547                }
548                _ => continue,
549            }
550        }
551    }
552
553    pub fn after_result(&self, result: &Result<Exchange, CamelError>) {
554        match result {
555            // Breaker-neutral business failure (owner decision Q4): record
556            // it as a success in every state.
557            Ok(_) | Err(CamelError::Business { .. }) => {
558                let s = self.state.state.load(Ordering::Acquire);
559                if s == STATE_CLOSED {
560                    // Step 1 (bd rc-bnsxr) fast path: no RMW when already clean.
561                    if self.state.consecutive_failures.load(Ordering::Acquire) == 0 {
562                        return;
563                    }
564                    self.state.consecutive_failures.swap(0, Ordering::Release);
565                    return;
566                }
567                if matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
568                    // Recovery runs under the transition lock: the counter reset
569                    // and the Close CAS are serialized against every other
570                    // slow-path transition, so an observer of CLOSED never sees
571                    // a stale pre-open failure count.
572                    self.state.with_transition(|_opened_at| {
573                        // The CAS can only lose to the lockless probe admission
574                        // (FREE -> HELD): every other HALF-code mutation holds
575                        // this same lock. A lost recovery is retried so a
576                        // concurrent admission cannot silently drop a completed
577                        // probe's recovery; the log fires only when the
578                        // transition happened.
579                        let mut recovered = false;
580                        for _ in 0..3 {
581                            let s = self.state.state.load(Ordering::Acquire);
582                            if s != STATE_HALF_OPEN_PROBE_HELD && s != STATE_HALF_OPEN_PROBE_FREE {
583                                break; // state moved to OPEN/CLOSED — nothing to recover
584                            }
585                            if self
586                                .state
587                                .state
588                                .compare_exchange(
589                                    s,
590                                    STATE_CLOSED,
591                                    Ordering::AcqRel,
592                                    Ordering::Acquire,
593                                )
594                                .is_ok()
595                            {
596                                self.state.consecutive_failures.swap(0, Ordering::Release);
597                                recovered = true;
598                                break;
599                            }
600                            // CAS lost only to the lockless probe admission
601                            // (FREE -> HELD); reload and retry.
602                        }
603                        if recovered {
604                            tracing::info!("Circuit breaker gate: HalfOpen → Closed");
605                        }
606                        recovered
607                    });
608                }
609                // s == STATE_OPEN: leave untouched — success does not close an
610                // open circuit.
611            }
612            Err(_) => {
613                let s = self.state.state.load(Ordering::Acquire);
614                if matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
615                    self.state.with_transition(|opened_at| {
616                        let s = self.state.state.load(Ordering::Acquire);
617                        if !matches!(s, STATE_HALF_OPEN_PROBE_HELD | STATE_HALF_OPEN_PROBE_FREE) {
618                            return false;
619                        }
620                        tracing::warn!("Circuit breaker gate: HalfOpen → Open (probe failed)");
621                        *opened_at = Some(Instant::now());
622                        let _ = self.state.state.compare_exchange(
623                            s,
624                            STATE_OPEN,
625                            Ordering::AcqRel,
626                            Ordering::Acquire,
627                        );
628                        true
629                    });
630                } else if s == STATE_CLOSED {
631                    // Slow-path transitions serialize on the opened_at lock:
632                    // qualification, timestamp publication, and the state CAS
633                    // hold the lock together, and recovery (probe success) takes
634                    // the same lock, so a threshold qualification can never be
635                    // split across an open/expiry/recovery cycle — the invariant
636                    // the old mutex gave per after_result call.
637                    self.state.with_transition(|opened_at| {
638                        let s = self.state.state.load(Ordering::Acquire);
639                        if s != STATE_CLOSED {
640                            return false;
641                        }
642                        let prev = self
643                            .state
644                            .consecutive_failures
645                            .fetch_add(1, Ordering::AcqRel);
646                        if prev + 1 >= self.config.failure_threshold {
647                            *opened_at = Some(Instant::now());
648                            if self
649                                .state
650                                .state
651                                .compare_exchange(
652                                    STATE_CLOSED,
653                                    STATE_OPEN,
654                                    Ordering::AcqRel,
655                                    Ordering::Acquire,
656                                )
657                                .is_ok()
658                            {
659                                tracing::warn!(
660                                    threshold = self.config.failure_threshold,
661                                    "Circuit breaker gate: Closed → Open (failure threshold reached)"
662                                );
663                            }
664                        }
665                        true
666                    });
667                }
668            }
669        }
670    }
671}
672
673// ── Tests ──────────────────────────────────────────────────────────────
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678    use camel_api::{BoxProcessor, BoxProcessorExt, Message};
679    use std::sync::atomic::AtomicBool;
680    use std::sync::atomic::{AtomicU32, Ordering};
681    use std::time::Duration;
682    use tokio::sync::Barrier;
683    use tower::ServiceExt;
684
685    #[derive(Debug, PartialEq, Eq)]
686    enum ObservedState {
687        Closed { consecutive_failures: u32 },
688        Open,
689        HalfOpen { probe_admitted: bool },
690    }
691
692    fn observe(shared: &SharedBreakerState) -> ObservedState {
693        match shared.state.load(Ordering::Acquire) {
694            STATE_CLOSED => ObservedState::Closed {
695                consecutive_failures: shared.consecutive_failures.load(Ordering::Acquire),
696            },
697            STATE_OPEN => ObservedState::Open,
698            STATE_HALF_OPEN_PROBE_HELD => ObservedState::HalfOpen {
699                probe_admitted: true,
700            },
701            STATE_HALF_OPEN_PROBE_FREE => ObservedState::HalfOpen {
702                probe_admitted: false,
703            },
704            _ => unreachable!("unknown breaker state"),
705        }
706    }
707
708    fn make_exchange() -> Exchange {
709        Exchange::new(Message::new("test"))
710    }
711
712    fn gate_with(config: CircuitBreakerConfig) -> CircuitBreakerGate {
713        CircuitBreakerGate::new(config, Arc::from("test"), None)
714    }
715
716    fn ok_processor() -> BoxProcessor {
717        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }))
718    }
719
720    fn failing_processor() -> BoxProcessor {
721        BoxProcessor::from_fn(|_ex| {
722            Box::pin(async { Err(CamelError::ProcessorError("boom".into())) })
723        })
724    }
725
726    fn business_error() -> CamelError {
727        CamelError::Business {
728            code: "BIZ".into(),
729            kind: "failed".into(),
730            message: "BIZ".into(),
731            data: None,
732        }
733    }
734
735    /// Always fails with a `Business` error (owner decision Q4: a business
736    /// failure is breaker-neutral — it counts as a success).
737    fn business_processor() -> BoxProcessor {
738        BoxProcessor::from_fn(|_ex| Box::pin(async { Err(business_error()) }))
739    }
740
741    fn fail_n_times(n: u32) -> BoxProcessor {
742        let count = Arc::new(AtomicU32::new(0));
743        BoxProcessor::from_fn(move |ex| {
744            let count = Arc::clone(&count);
745            Box::pin(async move {
746                let c = count.fetch_add(1, Ordering::SeqCst);
747                if c < n {
748                    Err(CamelError::ProcessorError(format!("attempt {c}")))
749                } else {
750                    Ok(ex)
751                }
752            })
753        })
754    }
755
756    fn tag_processor(tag: &'static str) -> BoxProcessor {
757        BoxProcessor::from_fn(move |_ex| {
758            Box::pin(async move {
759                let mut out = make_exchange();
760                out.input.body = tag.to_string().into();
761                Ok(out)
762            })
763        })
764    }
765
766    /// 1. Circuit stays closed on success.
767    #[tokio::test]
768    async fn test_stays_closed_on_success() {
769        let config = CircuitBreakerConfig::new().failure_threshold(3);
770        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
771        let mut svc = layer.layer(ok_processor());
772
773        for _ in 0..5 {
774            let result = svc.ready().await.unwrap().call(make_exchange()).await;
775            assert!(result.is_ok());
776        }
777
778        // State should still be closed with 0 failures.
779        assert_eq!(
780            observe(&svc.state),
781            ObservedState::Closed {
782                consecutive_failures: 0
783            }
784        );
785    }
786
787    /// 2. Circuit opens after failure_threshold consecutive failures.
788    #[tokio::test]
789    async fn test_opens_after_failure_threshold() {
790        let config = CircuitBreakerConfig::new().failure_threshold(3);
791        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
792        let mut svc = layer.layer(failing_processor());
793
794        // Three consecutive failures should open the circuit.
795        for _ in 0..3 {
796            let result = svc.ready().await.unwrap().call(make_exchange()).await;
797            assert!(result.is_err());
798        }
799
800        // The next poll_ready should return CircuitOpen error.
801        let waker = futures::task::noop_waker();
802        let mut cx = Context::from_waker(&waker);
803        let poll = Pin::new(&mut svc).poll_ready(&mut cx);
804        match poll {
805            Poll::Ready(Err(CamelError::CircuitOpen(_))) => {} // expected
806            other => panic!("expected CircuitOpen error, got {other:?}"),
807        }
808    }
809
810    /// 3. Circuit transitions to half-open after open_duration.
811    #[tokio::test]
812    async fn test_transitions_to_half_open_after_duration() {
813        let config = CircuitBreakerConfig::new()
814            .failure_threshold(2)
815            .open_duration(Duration::from_millis(50));
816        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
817        // Use fail_n_times(2) so the first 2 calls fail (opening the circuit),
818        // then the third (half-open probe) succeeds.
819        let mut svc = layer.layer(fail_n_times(2));
820
821        // Trigger 2 failures to open the circuit.
822        for _ in 0..2 {
823            let _ = svc.ready().await.unwrap().call(make_exchange()).await;
824        }
825
826        // Circuit is now open. Wait for open_duration to elapse.
827        tokio::time::sleep(Duration::from_millis(60)).await;
828
829        // poll_ready should transition to HalfOpen and succeed.
830        let result = svc.ready().await.unwrap().call(make_exchange()).await;
831        assert!(result.is_ok(), "half-open probe should succeed");
832
833        // After successful probe, circuit should be back to Closed.
834        assert_eq!(
835            observe(&svc.state),
836            ObservedState::Closed {
837                consecutive_failures: 0
838            }
839        );
840    }
841
842    /// 4. Half-open failure reopens circuit.
843    #[tokio::test]
844    async fn test_half_open_failure_reopens() {
845        let config = CircuitBreakerConfig::new()
846            .failure_threshold(2)
847            .open_duration(Duration::from_millis(50));
848        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
849        let mut svc = layer.layer(failing_processor());
850
851        // Trigger 2 failures to open the circuit.
852        for _ in 0..2 {
853            let _ = svc.ready().await.unwrap().call(make_exchange()).await;
854        }
855
856        // Wait for open_duration to elapse, transitioning to HalfOpen.
857        tokio::time::sleep(Duration::from_millis(60)).await;
858
859        // Half-open probe fails → circuit reopens.
860        let result = svc.ready().await.unwrap().call(make_exchange()).await;
861        assert!(result.is_err());
862
863        // Circuit should be open again.
864        assert_eq!(observe(&svc.state), ObservedState::Open);
865    }
866
867    /// 5. Intermittent failures below threshold don't open circuit.
868    #[tokio::test]
869    async fn test_intermittent_failures_dont_open() {
870        let config = CircuitBreakerConfig::new().failure_threshold(3);
871        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
872
873        // Alternate: fail, fail, success, fail, fail, success
874        // The counter should reset on success, so threshold of 3 is never reached.
875        let call_count = Arc::new(AtomicU32::new(0));
876        let cc = Arc::clone(&call_count);
877        let inner = BoxProcessor::from_fn(move |ex| {
878            let cc = Arc::clone(&cc);
879            Box::pin(async move {
880                let c = cc.fetch_add(1, Ordering::SeqCst);
881                // Pattern: fail, fail, success, fail, fail, success
882                if c % 3 == 2 {
883                    Ok(ex)
884                } else {
885                    Err(CamelError::ProcessorError("intermittent".into()))
886                }
887            })
888        });
889
890        let mut svc = layer.layer(inner);
891
892        for _ in 0..6 {
893            let _ = svc.ready().await.unwrap().call(make_exchange()).await;
894        }
895
896        // Circuit should still be closed because successes reset the counter.
897        assert!(matches!(observe(&svc.state), ObservedState::Closed { .. }));
898    }
899
900    #[tokio::test]
901    async fn test_open_uses_fallback_when_configured() {
902        let fallback = tag_processor("fallback");
903        let config = CircuitBreakerConfig::new()
904            .failure_threshold(1)
905            .open_duration(Duration::from_secs(60))
906            .fallback(fallback);
907        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
908        let mut svc = layer.layer(failing_processor());
909
910        let _ = svc.ready().await.unwrap().call(make_exchange()).await;
911        let result = svc
912            .ready()
913            .await
914            .unwrap()
915            .call(make_exchange())
916            .await
917            .unwrap();
918        assert_eq!(result.input.body.as_text(), Some("fallback"));
919    }
920
921    #[tokio::test]
922    async fn test_open_without_fallback_returns_err() {
923        let config = CircuitBreakerConfig::new()
924            .failure_threshold(1)
925            .open_duration(Duration::from_secs(60));
926        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
927        let mut svc = layer.layer(failing_processor());
928
929        let _ = svc.ready().await.unwrap().call(make_exchange()).await;
930        let result = svc.ready().await;
931        assert!(matches!(result, Err(CamelError::CircuitOpen(_))));
932    }
933
934    // ── CircuitBreakerGate tests ──────────────────────────────────────────
935
936    #[test]
937    fn test_cb_gate_before_call_closed_allows() {
938        let gate = gate_with(CircuitBreakerConfig {
939            failure_threshold: 3,
940            open_duration: Duration::from_secs(60),
941            success_threshold: 1,
942            fallback: None,
943        });
944        assert!(matches!(gate.before_call(), CircuitBreakerDecision::Allow));
945    }
946
947    #[test]
948    fn test_cb_gate_records_failures_and_opens() {
949        let gate = gate_with(CircuitBreakerConfig {
950            failure_threshold: 2,
951            open_duration: Duration::from_secs(60),
952            success_threshold: 1,
953            fallback: None,
954        });
955        gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
956        assert!(
957            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
958            "still closed after 1 failure"
959        );
960        gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
961        assert!(
962            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
963            "should be open after 2 failures"
964        );
965    }
966
967    #[tokio::test]
968    async fn test_cb_gate_closes_on_success() {
969        let gate = gate_with(CircuitBreakerConfig {
970            failure_threshold: 1,
971            open_duration: Duration::from_millis(1),
972            success_threshold: 1,
973            fallback: None,
974        });
975        gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
976        assert!(
977            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
978            "should be open"
979        );
980        tokio::time::sleep(Duration::from_millis(10)).await;
981        assert!(
982            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
983            "should transition to half-open"
984        );
985        let ex = Exchange::new(Message::new("test"));
986        gate.after_result(&Ok(ex));
987        assert!(
988            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
989            "should be closed again"
990        );
991    }
992
993    #[tokio::test]
994    async fn test_cb_gate_half_open_failure_reopens() {
995        let gate = gate_with(CircuitBreakerConfig {
996            failure_threshold: 1,
997            open_duration: Duration::from_millis(1),
998            success_threshold: 1,
999            fallback: None,
1000        });
1001        // Open the circuit
1002        gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
1003        assert!(
1004            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
1005            "should be open"
1006        );
1007
1008        // Wait for open_duration to elapse → transitions to HalfOpen
1009        tokio::time::sleep(Duration::from_millis(10)).await;
1010        assert!(
1011            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1012            "should be half-open now"
1013        );
1014
1015        // Probe fails in HalfOpen → should reopen
1016        gate.after_result(&Err(CamelError::ProcessorError("probe fail".into())));
1017        assert!(
1018            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
1019            "should be open again after probe failure"
1020        );
1021    }
1022
1023    #[test]
1024    fn test_cb_gate_open_with_fallback_returns_fallback() {
1025        let fallback = BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }));
1026        let gate = gate_with(CircuitBreakerConfig {
1027            failure_threshold: 1,
1028            open_duration: Duration::from_secs(60),
1029            success_threshold: 1,
1030            fallback: Some(fallback),
1031        });
1032        gate.after_result(&Err(CamelError::ProcessorError("fail".into())));
1033        assert!(
1034            matches!(gate.before_call(), CircuitBreakerDecision::Fallback(_)),
1035            "should return fallback when open"
1036        );
1037    }
1038
1039    #[test]
1040    fn test_cb_gate_handled_error_counts_as_success() {
1041        let gate = gate_with(CircuitBreakerConfig {
1042            failure_threshold: 1,
1043            open_duration: Duration::from_secs(60),
1044            success_threshold: 1,
1045            fallback: None,
1046        });
1047        let ex = Exchange::new(Message::new("test"));
1048        gate.after_result(&Ok(ex));
1049        assert!(
1050            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1051            "handled error should not trip CB"
1052        );
1053    }
1054
1055    // ── D-M1: half-open admits a single probe ─────────────────────────────
1056
1057    /// Gate path: only the first caller in HalfOpen is admitted as the probe;
1058    /// every subsequent caller is rejected.
1059    #[test]
1060    fn gate_half_open_admits_only_one_probe() {
1061        let config = CircuitBreakerConfig {
1062            failure_threshold: 1,
1063            open_duration: Duration::from_millis(1),
1064            success_threshold: 1,
1065            fallback: None,
1066        };
1067        let gate = gate_with(config);
1068        // Trip: one failure → Open
1069        gate.after_result(&Err::<Exchange, CamelError>(CamelError::CircuitOpen(
1070            "boom".into(),
1071        )));
1072        std::thread::sleep(Duration::from_millis(10)); // past open_duration
1073        let d1 = gate.before_call();
1074        assert!(
1075            matches!(d1, CircuitBreakerDecision::Allow),
1076            "first probe must be admitted"
1077        );
1078        let d2 = gate.before_call();
1079        assert!(
1080            matches!(d2, CircuitBreakerDecision::Reject(_)),
1081            "2nd concurrent caller must be rejected"
1082        );
1083    }
1084
1085    /// Service path: only the first `poll_ready` in HalfOpen is admitted as the
1086    /// probe; every subsequent `poll_ready` from a cloned service must be
1087    /// rejected with `CircuitOpen`.
1088    #[tokio::test]
1089    async fn service_half_open_admits_only_one_probe() {
1090        let config = CircuitBreakerConfig::new()
1091            .failure_threshold(1)
1092            .open_duration(Duration::from_millis(1));
1093        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
1094        let mut svc1 = layer.layer(failing_processor());
1095        let mut svc2 = svc1.clone();
1096
1097        // Trip to Open
1098        let _ = svc1.ready().await.unwrap().call(make_exchange()).await;
1099
1100        // Wait past open_duration
1101        tokio::time::sleep(Duration::from_millis(10)).await;
1102
1103        // svc1 poll_ready: admitted as probe → Ready(Ok(()))
1104        let waker = futures::task::noop_waker();
1105        let mut cx = Context::from_waker(&waker);
1106        let p1 = std::pin::Pin::new(&mut svc1).poll_ready(&mut cx);
1107        assert!(
1108            matches!(p1, Poll::Ready(Ok(()))),
1109            "first probe admitted, got {p1:?}"
1110        );
1111
1112        // svc2 poll_ready: must be rejected
1113        let p2 = std::pin::Pin::new(&mut svc2).poll_ready(&mut cx);
1114        match p2 {
1115            Poll::Ready(Err(CamelError::CircuitOpen(_))) => {} // expected
1116            other => panic!("expected CircuitOpen error on 2nd probe, got {other:?}"),
1117        }
1118    }
1119
1120    // ── bd rc-bnsxr item 3: deterministic concurrency coverage ────────────
1121
1122    /// Inner service for the D-M1 release dance: its `poll_ready` is gated on
1123    /// a flag the test flips, and its first `call` fails so the breaker can be
1124    /// tripped through the normal failure path.
1125    #[derive(Clone)]
1126    struct ProbeReadyService {
1127        ready: Arc<AtomicBool>,
1128        calls: Arc<AtomicU32>,
1129    }
1130
1131    impl Service<Exchange> for ProbeReadyService {
1132        type Response = Exchange;
1133        type Error = CamelError;
1134        type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
1135
1136        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), CamelError>> {
1137            if self.ready.load(Ordering::Acquire) {
1138                Poll::Ready(Ok(()))
1139            } else {
1140                Poll::Pending
1141            }
1142        }
1143
1144        fn call(&mut self, _exchange: Exchange) -> Self::Future {
1145            let is_trip = self.calls.fetch_add(1, Ordering::AcqRel) == 0;
1146            Box::pin(async move {
1147                if is_trip {
1148                    Err(CamelError::ProcessorError("trip".into()))
1149                } else {
1150                    Ok(make_exchange())
1151                }
1152            })
1153        }
1154    }
1155
1156    /// 1. A concurrent success storm never observes a failure and leaves the
1157    /// circuit Closed with a clean counter.
1158    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1159    async fn concurrent_successes_stay_closed_and_clean() {
1160        const TASKS: usize = 8;
1161        const ITERS: usize = 5_000;
1162
1163        let gate = gate_with(
1164            CircuitBreakerConfig::new()
1165                .failure_threshold(8)
1166                .open_duration(Duration::from_secs(3_600)),
1167        );
1168        let barrier = Arc::new(Barrier::new(TASKS));
1169        let mut handles = Vec::with_capacity(TASKS);
1170
1171        for _ in 0..TASKS {
1172            let gate = gate.clone();
1173            let barrier = Arc::clone(&barrier);
1174            handles.push(tokio::spawn(async move {
1175                tokio::time::timeout(Duration::from_secs(5), barrier.wait())
1176                    .await
1177                    .expect("barrier wait must not deadlock");
1178                for i in 0..ITERS {
1179                    match gate.before_call() {
1180                        CircuitBreakerDecision::Allow => {}
1181                        CircuitBreakerDecision::Fallback(_) => panic!(
1182                            "no fallback configured, yet iteration {i} got Fallback: state={:?}",
1183                            observe(&gate.state)
1184                        ),
1185                        CircuitBreakerDecision::Reject(err) => panic!(
1186                            "success storm iteration {i} was rejected: {err:?}, state={:?}",
1187                            observe(&gate.state)
1188                        ),
1189                    }
1190                    gate.after_result(&Ok(make_exchange()));
1191                }
1192            }));
1193        }
1194        for handle in handles {
1195            handle
1196                .await
1197                .expect("success storm task panicked before joining");
1198        }
1199
1200        assert_eq!(
1201            observe(&gate.state),
1202            ObservedState::Closed {
1203                consecutive_failures: 0
1204            },
1205            "40k concurrent successes must never trip the breaker or dirty the counter"
1206        );
1207    }
1208
1209    /// 2. Under a barrier-start race, exactly one caller claims the half-open
1210    /// probe; every other concurrent caller is rejected. Repeats 25 recovery
1211    /// cycles to shake scheduling skew.
1212    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1213    async fn concurrent_before_call_admits_exactly_one_probe() {
1214        const TASKS: usize = 8;
1215        const ROUNDS: usize = 25;
1216
1217        let open_duration = Duration::from_millis(10);
1218        let gate = gate_with(
1219            CircuitBreakerConfig::new()
1220                .failure_threshold(1)
1221                .open_duration(open_duration),
1222        );
1223
1224        for round in 0..ROUNDS {
1225            gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1226                format!("trip {round}"),
1227            )));
1228            assert_eq!(
1229                observe(&gate.state),
1230                ObservedState::Open,
1231                "round {round}: a single failure must trip the threshold(1) breaker"
1232            );
1233
1234            tokio::time::sleep(open_duration + Duration::from_millis(10)).await; // allow-test-sleep: expiry timer is the behavior under test
1235
1236            let barrier = Arc::new(Barrier::new(TASKS));
1237            let mut handles = Vec::with_capacity(TASKS);
1238            for _ in 0..TASKS {
1239                let gate = gate.clone();
1240                let barrier = Arc::clone(&barrier);
1241                handles.push(tokio::spawn(async move {
1242                    tokio::time::timeout(Duration::from_secs(5), barrier.wait())
1243                        .await
1244                        .expect("barrier wait must not deadlock");
1245                    gate.before_call()
1246                }));
1247            }
1248
1249            let mut allows = 0usize;
1250            let mut rejects = 0usize;
1251            for handle in handles {
1252                match handle.await.expect("probe race task panicked") {
1253                    CircuitBreakerDecision::Allow => allows += 1,
1254                    CircuitBreakerDecision::Reject(_) => rejects += 1,
1255                    CircuitBreakerDecision::Fallback(_) => {
1256                        panic!("round {round}: no fallback is configured")
1257                    }
1258                }
1259            }
1260            assert_eq!(
1261                allows, 1,
1262                "round {round}: exactly one concurrent caller may be admitted as the probe"
1263            );
1264            assert_eq!(
1265                rejects, 7,
1266                "round {round}: every non-probe caller must be rejected"
1267            );
1268            assert_eq!(
1269                observe(&gate.state),
1270                ObservedState::HalfOpen {
1271                    probe_admitted: true
1272                },
1273                "round {round}: the admitted probe must hold the single probe slot"
1274            );
1275
1276            // Resolve the probe so the next round starts from Closed.
1277            gate.after_result(&Ok(make_exchange()));
1278            assert_eq!(
1279                observe(&gate.state),
1280                ObservedState::Closed {
1281                    consecutive_failures: 0
1282                },
1283                "round {round}: the successful probe must close the circuit"
1284            );
1285        }
1286    }
1287
1288    /// 3. Exactly-threshold concurrent failures must all be counted: no lost
1289    /// increment may leave the circuit Closed, and no extra transition may
1290    /// double-open it. A failing half-open probe then reopens it.
1291    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
1292    async fn concurrent_failures_open_exactly_at_threshold() {
1293        // Phase A pins threshold atomicity (exactly-threshold concurrent failures
1294        // must open; a lost increment would leave it Closed) behind a 1-hour open
1295        // window so the post-join assertions carry no timing deadline. Phase B
1296        // covers probe-fail reopen on a fresh short-expiry gate, single-tasked.
1297
1298        // Phase A — threshold qualification, deterministic.
1299        const TASKS: usize = 8;
1300        const PER_TASK: usize = 8;
1301        const THRESHOLD: u32 = 64;
1302
1303        let gate_a = gate_with(
1304            CircuitBreakerConfig::new()
1305                .failure_threshold(THRESHOLD)
1306                .open_duration(Duration::from_secs(60 * 60)),
1307        );
1308        let barrier = Arc::new(Barrier::new(TASKS));
1309        let mut handles = Vec::with_capacity(TASKS);
1310
1311        for _ in 0..TASKS {
1312            let gate = gate_a.clone();
1313            let barrier = Arc::clone(&barrier);
1314            handles.push(tokio::spawn(async move {
1315                tokio::time::timeout(Duration::from_secs(5), barrier.wait())
1316                    .await
1317                    .expect("barrier wait must not deadlock");
1318                for _ in 0..PER_TASK {
1319                    gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1320                        "boom".into(),
1321                    )));
1322                }
1323            }));
1324        }
1325        for handle in handles {
1326            handle.await.expect("threshold storm task panicked");
1327        }
1328
1329        assert_eq!(
1330            observe(&gate_a.state),
1331            ObservedState::Open,
1332            "exactly {THRESHOLD} concurrent failures must open the circuit (no lost increment)"
1333        );
1334        assert!(
1335            matches!(gate_a.before_call(), CircuitBreakerDecision::Reject(_)),
1336            "a freshly opened circuit must reject before expiry"
1337        );
1338
1339        // Phase B — probe-fail reopen on a fresh short-expiry gate, no concurrency.
1340        let open_duration = Duration::from_millis(10);
1341        let gate_b = gate_with(
1342            CircuitBreakerConfig::new()
1343                .failure_threshold(1)
1344                .open_duration(open_duration),
1345        );
1346        gate_b.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1347            "boom".into(),
1348        )));
1349        assert_eq!(
1350            observe(&gate_b.state),
1351            ObservedState::Open,
1352            "a single failure must trip a threshold-1 circuit"
1353        );
1354
1355        tokio::time::sleep(open_duration + Duration::from_millis(10)).await; // allow-test-sleep: expiry timer is the behavior under test
1356        assert!(
1357            matches!(gate_b.before_call(), CircuitBreakerDecision::Allow),
1358            "an expired circuit must admit the probe"
1359        );
1360        gate_b.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1361            "probe".into(),
1362        )));
1363        assert_eq!(
1364            observe(&gate_b.state),
1365            ObservedState::Open,
1366            "a failed probe must reopen the circuit"
1367        );
1368    }
1369
1370    /// 4. Expiry reopens the probe path exactly once, and expiry must never
1371    /// re-open a circuit that a successful probe already closed.
1372    #[tokio::test]
1373    async fn expiry_reopens_the_probe_path() {
1374        let open_duration = Duration::from_millis(20);
1375        let gate = gate_with(
1376            CircuitBreakerConfig::new()
1377                .failure_threshold(1)
1378                .open_duration(open_duration),
1379        );
1380
1381        gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1382            "boom".into(),
1383        )));
1384        assert!(
1385            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
1386            "an open circuit must reject before expiry"
1387        );
1388
1389        tokio::time::sleep(Duration::from_millis(50)).await; // allow-test-sleep: expiry timer is the behavior under test
1390        assert!(
1391            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1392            "an expired circuit must admit the first caller as the probe"
1393        );
1394        assert_eq!(
1395            observe(&gate.state),
1396            ObservedState::HalfOpen {
1397                probe_admitted: true
1398            },
1399            "the expiry winner must hold the probe slot"
1400        );
1401        assert!(
1402            matches!(gate.before_call(), CircuitBreakerDecision::Reject(_)),
1403            "the single-probe gate must reject an immediate second caller"
1404        );
1405
1406        gate.after_result(&Ok(make_exchange()));
1407        assert_eq!(
1408            observe(&gate.state),
1409            ObservedState::Closed {
1410                consecutive_failures: 0
1411            },
1412            "a successful probe must close the circuit"
1413        );
1414
1415        // No failures: waiting past open_duration again must not re-open it.
1416        tokio::time::sleep(Duration::from_millis(50)).await; // allow-test-sleep: expiry timer is the behavior under test
1417        assert!(
1418            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1419            "expiry must never re-open a Closed circuit"
1420        );
1421        assert_eq!(
1422            observe(&gate.state),
1423            ObservedState::Closed {
1424                consecutive_failures: 0
1425            },
1426            "the circuit must stay Closed after the probe recovery"
1427        );
1428    }
1429
1430    /// 5. A half-open success closes the circuit and resets the counter, and
1431    /// further successes keep it Closed.
1432    #[tokio::test]
1433    async fn success_after_half_open_closes_and_resets_counter() {
1434        let open_duration = Duration::from_millis(10);
1435        let gate = gate_with(
1436            CircuitBreakerConfig::new()
1437                .failure_threshold(2)
1438                .open_duration(open_duration),
1439        );
1440
1441        for _ in 0..2 {
1442            gate.after_result(&Err::<Exchange, CamelError>(CamelError::ProcessorError(
1443                "boom".into(),
1444            )));
1445        }
1446        assert_eq!(
1447            observe(&gate.state),
1448            ObservedState::Open,
1449            "threshold(2) must open after two failures"
1450        );
1451
1452        tokio::time::sleep(Duration::from_millis(20)).await; // allow-test-sleep: expiry timer is the behavior under test
1453        assert!(
1454            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1455            "an expired circuit must admit the probe"
1456        );
1457        gate.after_result(&Ok(make_exchange()));
1458        assert_eq!(
1459            observe(&gate.state),
1460            ObservedState::Closed {
1461                consecutive_failures: 0
1462            },
1463            "a successful probe must close the circuit and reset the counter"
1464        );
1465
1466        for _ in 0..100 {
1467            gate.after_result(&Ok(make_exchange()));
1468        }
1469        assert_eq!(
1470            observe(&gate.state),
1471            ObservedState::Closed {
1472                consecutive_failures: 0
1473            },
1474            "further successes must keep the recovered circuit Closed with a zeroed counter"
1475        );
1476    }
1477
1478    /// 6. D-M1 release dance: a `poll_ready` Pending from the inner service
1479    /// releases the probe claim so a re-poll can re-claim it.
1480    #[tokio::test]
1481    async fn poll_ready_pending_releases_the_probe_claim() {
1482        let open_duration = Duration::from_millis(10);
1483        let ready = Arc::new(AtomicBool::new(false));
1484        let calls = Arc::new(AtomicU32::new(0));
1485        let layer = CircuitBreakerLayer::new(
1486            CircuitBreakerConfig::new()
1487                .failure_threshold(1)
1488                .open_duration(open_duration),
1489            Arc::from("test"),
1490            None,
1491        );
1492        let mut svc = layer.layer(ProbeReadyService {
1493            ready: Arc::clone(&ready),
1494            calls: Arc::clone(&calls),
1495        });
1496
1497        // Trip the breaker through the ordinary failure path. The inner
1498        // service's first call fails; readiness is irrelevant to `call`.
1499        let trip = svc.call(make_exchange()).await;
1500        assert!(trip.is_err(), "the first inner call must fail to trip");
1501        assert_eq!(
1502            observe(&svc.state),
1503            ObservedState::Open,
1504            "one failed call must trip the threshold(1) breaker"
1505        );
1506        tokio::time::sleep(Duration::from_millis(20)).await; // allow-test-sleep: expiry timer is the behavior under test
1507
1508        let waker = futures::task::noop_waker();
1509        let mut cx = Context::from_waker(&waker);
1510
1511        // First poll: expiry claims the probe, inner says Pending, so the
1512        // claim must be released back to FREE.
1513        let first = Pin::new(&mut svc).poll_ready(&mut cx);
1514        assert!(
1515            matches!(first, Poll::Pending),
1516            "not-ready inner service must surface Pending, got {first:?}"
1517        );
1518        assert_eq!(
1519            observe(&svc.state),
1520            ObservedState::HalfOpen {
1521                probe_admitted: false
1522            },
1523            "Pending must release the probe claim (HELD -> FREE)"
1524        );
1525
1526        // Re-poll once the inner service is ready: the claim is re-taken and
1527        // the breaker admits the probe.
1528        ready.store(true, Ordering::Release);
1529        let second = Pin::new(&mut svc).poll_ready(&mut cx);
1530        assert!(
1531            matches!(second, Poll::Ready(Ok(()))),
1532            "a ready inner service must let the probe proceed, got {second:?}"
1533        );
1534        assert_eq!(
1535            observe(&svc.state),
1536            ObservedState::HalfOpen {
1537                probe_admitted: true
1538            },
1539            "the re-poll must re-claim the probe slot (FREE -> HELD)"
1540        );
1541
1542        // Complete the probe: the second inner call succeeds and closes.
1543        let result = svc.call(make_exchange()).await;
1544        assert!(result.is_ok(), "the half-open probe must succeed");
1545        assert_eq!(
1546            observe(&svc.state),
1547            ObservedState::Closed {
1548                consecutive_failures: 0
1549            },
1550            "a successful probe must close the circuit and reset the counter"
1551        );
1552    }
1553
1554    // ── Business errors are breaker success (business-error-model 1.6) ─────
1555
1556    #[tokio::test]
1557    async fn breaker_service_records_success() {
1558        let config = CircuitBreakerConfig::new().failure_threshold(1);
1559        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
1560        let mut svc = layer.layer(business_processor());
1561
1562        let result = svc.ready().await.unwrap().call(make_exchange()).await;
1563        assert!(
1564            matches!(result, Err(CamelError::Business { .. })),
1565            "the business error must still surface unchanged, got {result:?}"
1566        );
1567        assert_eq!(
1568            observe(&svc.state),
1569            ObservedState::Closed {
1570                consecutive_failures: 0
1571            },
1572            "a business failure must be recorded as a success"
1573        );
1574
1575        // Threshold 1: a second business failure must still not open it.
1576        let second = svc.ready().await.unwrap().call(make_exchange()).await;
1577        assert!(matches!(second, Err(CamelError::Business { .. })));
1578        assert_eq!(
1579            observe(&svc.state),
1580            ObservedState::Closed {
1581                consecutive_failures: 0
1582            }
1583        );
1584    }
1585
1586    #[test]
1587    fn breaker_gate_records_success() {
1588        let gate = gate_with(CircuitBreakerConfig::new().failure_threshold(1));
1589        let result: Result<Exchange, CamelError> = Err(business_error());
1590        gate.after_result(&result);
1591
1592        assert_eq!(
1593            observe(&gate.state),
1594            ObservedState::Closed {
1595                consecutive_failures: 0
1596            },
1597            "a business failure must be recorded as a success"
1598        );
1599        assert!(
1600            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1601            "threshold-1 breaker must stay closed after a business failure"
1602        );
1603    }
1604
1605    #[tokio::test]
1606    async fn half_open_service_closes_on_business() {
1607        let config = CircuitBreakerConfig::new()
1608            .failure_threshold(1)
1609            .open_duration(Duration::ZERO);
1610        let layer = CircuitBreakerLayer::new(config, Arc::from("test"), None);
1611        let calls = Arc::new(AtomicU32::new(0));
1612        let cc = Arc::clone(&calls);
1613        let inner = BoxProcessor::from_fn(move |ex| {
1614            let cc = Arc::clone(&cc);
1615            Box::pin(async move {
1616                if cc.fetch_add(1, Ordering::SeqCst) == 0 {
1617                    Err(CamelError::ProcessorError("system".into()))
1618                } else {
1619                    let _ = ex;
1620                    Err(business_error())
1621                }
1622            })
1623        });
1624        let mut svc = layer.layer(inner);
1625
1626        // System failure opens the breaker (threshold 1).
1627        let first = svc.ready().await.unwrap().call(make_exchange()).await;
1628        assert!(first.is_err());
1629        assert_eq!(observe(&svc.state), ObservedState::Open);
1630
1631        // Zero open_duration: the next ready transitions to half-open and
1632        // admits this call as the probe; the probe's business error is a
1633        // success and closes the breaker.
1634        let probe = svc.ready().await.unwrap().call(make_exchange()).await;
1635        assert!(
1636            matches!(probe, Err(CamelError::Business { .. })),
1637            "the probe must surface its business error unchanged, got {probe:?}"
1638        );
1639        assert_eq!(
1640            observe(&svc.state),
1641            ObservedState::Closed {
1642                consecutive_failures: 0
1643            },
1644            "a half-open probe ending in a business error must close the breaker"
1645        );
1646    }
1647
1648    #[test]
1649    fn half_open_gate_closes_on_business() {
1650        let gate = gate_with(
1651            CircuitBreakerConfig::new()
1652                .failure_threshold(1)
1653                .open_duration(Duration::ZERO),
1654        );
1655        let system: Result<Exchange, CamelError> = Err(CamelError::ProcessorError("system".into()));
1656        gate.after_result(&system);
1657        assert_eq!(observe(&gate.state), ObservedState::Open);
1658
1659        assert!(
1660            matches!(gate.before_call(), CircuitBreakerDecision::Allow),
1661            "zero open_duration must admit the half-open probe"
1662        );
1663        assert_eq!(
1664            observe(&gate.state),
1665            ObservedState::HalfOpen {
1666                probe_admitted: true
1667            }
1668        );
1669
1670        let probe: Result<Exchange, CamelError> = Err(business_error());
1671        gate.after_result(&probe);
1672        assert_eq!(
1673            observe(&gate.state),
1674            ObservedState::Closed {
1675                consecutive_failures: 0
1676            },
1677            "a half-open probe ending in a business error must close the breaker"
1678        );
1679    }
1680}