Skip to main content

CircuitBreaker

Struct CircuitBreaker 

Source
pub struct CircuitBreaker { /* private fields */ }
Expand description

A circuit breaker that prevents cascading failures by stopping requests to a failing downstream service.

§State machine

Closed ──(failures ≥ threshold)──► Open
  ▲                                  │
  │                                  │ (timeout elapsed)
  │                                  ▼
  └──(success_rate ≥ threshold)── HalfOpen
  • Closed — normal operation; all requests flow through.
  • Open — all requests are rejected immediately with CircuitBreakerError::Open without calling the wrapped operation.
  • HalfOpen — a single probe request is allowed; on success the circuit closes; on failure it reopens.

§Cloning

CircuitBreaker is Clone + Send + Sync. All clones share the same underlying Arc<RwLock<CircuitState>>.

§Examples

use std::time::Duration;
use tokio_prompt_orchestrator::enhanced::CircuitBreaker;
use tokio_prompt_orchestrator::enhanced::circuit_breaker::CircuitBreakerError;

let cb = CircuitBreaker::new(5, 0.8, Duration::from_secs(30));

let result = cb.call(|| async {
    reqwest::get("https://api.example.com/infer")
        .await
        .map_err(|e| e.to_string())
}).await;

match result {
    Ok(resp) => { /* handle response */ }
    Err(CircuitBreakerError::Open) => { /* fail fast */ }
    Err(CircuitBreakerError::Failed(e)) => { /* handle error */ }
}

Implementations§

Source§

impl CircuitBreaker

Source

pub fn new( failure_threshold: usize, success_threshold: f64, timeout: Duration, ) -> Self

Create a new CircuitBreaker in the Closed state.

§Arguments
  • failure_threshold — Number of consecutive failures required to open the circuit. A value of 1 opens immediately on the first error.
  • success_threshold — Required success rate (0.0..=1.0) over the recent-results window before the circuit closes from HalfOpen. Typical values: 0.8 (80 %) or 1.0 (100 %).
  • timeout — How long to stay in the Open state before transitioning to HalfOpen and allowing one probe request through.

The default rolling-window size is 100 results. Use with_window_size to customise it.

§Examples
use std::time::Duration;
use tokio_prompt_orchestrator::enhanced::CircuitBreaker;

// Open after 5 failures; require 80 % success rate to close; probe after 60 s.
let cb = CircuitBreaker::new(5, 0.8, Duration::from_secs(60));
Source

pub fn with_window_size(self, size: usize) -> Self

Set the rolling-window size used to calculate the success rate.

The window keeps the most recent size call outcomes. A smaller window reacts faster to bursts of failures but is more sensitive to noise. The default is 100.

§Examples
use std::time::Duration;
use tokio_prompt_orchestrator::enhanced::CircuitBreaker;

// Tighter window — reacts faster to short failure bursts.
let cb = CircuitBreaker::new(5, 0.8, Duration::from_secs(30))
    .with_window_size(20);
§Panics

This function does not panic.

Source

pub async fn call<F, Fut, T, E>( &self, f: F, ) -> Result<T, CircuitBreakerError<E>>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<T, E>>,

Execute a fallible async operation through the circuit breaker.

If the circuit is Open the operation is not called and Err(CircuitBreakerError::Open) is returned immediately. Otherwise the closure is invoked; its Ok/Err outcome is recorded and may cause a state transition.

§Arguments
  • f — A FnOnce that returns a Future<Output = Result<T, E>>. The closure is called at most once per call invocation.
§Returns
  • Ok(value) — operation succeeded.
  • Err(CircuitBreakerError::Open) — circuit is open; request rejected.
  • Err(CircuitBreakerError::Failed(e)) — operation returned Err(e).
§Examples
use std::time::Duration;
use tokio_prompt_orchestrator::enhanced::CircuitBreaker;
use tokio_prompt_orchestrator::enhanced::circuit_breaker::CircuitBreakerError;

let cb = CircuitBreaker::new(3, 0.8, Duration::from_secs(10));
let result = cb.call(|| async { Ok::<_, String>("ok") }).await;
assert!(matches!(result, Ok("ok")));
Source

pub fn is_closed_sync(&self) -> bool

Returns true if the circuit is currently closed (normal operation).

This is a best-effort synchronous read — use status() for authoritative state.

Source

pub fn is_open_sync(&self) -> bool

Returns true if the circuit is currently open (rejecting requests).

Source

pub fn is_half_open_sync(&self) -> bool

Returns true if the circuit is in half-open state (testing recovery).

Source

pub async fn status(&self) -> CircuitStatus

Get current circuit status

Source

pub async fn stats(&self) -> CircuitBreakerStats

Get circuit breaker statistics

Source

pub async fn reset(&self)

Manually reset circuit breaker to closed state

Source

pub async fn trip(&self)

Force circuit to open state (for testing/maintenance)

Trait Implementations§

Source§

impl Clone for CircuitBreaker

Source§

fn clone(&self) -> CircuitBreaker

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more