use crate::events::BulkheadEvent;
use std::time::Duration;
use tower_resilience_core::events::{EventListeners, FnListener};
#[derive(Clone)]
pub struct BulkheadConfig {
pub(crate) max_concurrent_calls: usize,
pub(crate) max_wait_duration: Option<Duration>,
pub(crate) name: String,
pub(crate) event_listeners: EventListeners<BulkheadEvent>,
}
impl BulkheadConfig {
pub fn builder() -> BulkheadConfigBuilder {
BulkheadConfigBuilder::new()
}
}
pub struct BulkheadConfigBuilder {
max_concurrent_calls: usize,
max_wait_duration: Option<Duration>,
name: String,
event_listeners: EventListeners<BulkheadEvent>,
}
impl BulkheadConfigBuilder {
pub fn new() -> Self {
Self {
max_concurrent_calls: 25,
max_wait_duration: None,
name: "bulkhead".to_string(),
event_listeners: EventListeners::new(),
}
}
pub fn max_concurrent_calls(mut self, max: usize) -> Self {
self.max_concurrent_calls = max;
self
}
pub fn max_wait_duration(mut self, duration: Option<Duration>) -> Self {
self.max_wait_duration = duration;
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
pub fn on_call_permitted<F>(mut self, f: F) -> Self
where
F: Fn(usize) + Send + Sync + 'static,
{
self.event_listeners.add(FnListener::new(move |event| {
if let BulkheadEvent::CallPermitted {
concurrent_calls, ..
} = event
{
f(*concurrent_calls);
}
}));
self
}
pub fn on_call_rejected<F>(mut self, f: F) -> Self
where
F: Fn(usize) + Send + Sync + 'static,
{
self.event_listeners.add(FnListener::new(move |event| {
if let BulkheadEvent::CallRejected {
max_concurrent_calls,
..
} = event
{
f(*max_concurrent_calls);
}
}));
self
}
pub fn on_call_finished<F>(mut self, f: F) -> Self
where
F: Fn(Duration) + Send + Sync + 'static,
{
self.event_listeners.add(FnListener::new(move |event| {
if let BulkheadEvent::CallFinished { duration, .. } = event {
f(*duration);
}
}));
self
}
pub fn on_call_failed<F>(mut self, f: F) -> Self
where
F: Fn(Duration) + Send + Sync + 'static,
{
self.event_listeners.add(FnListener::new(move |event| {
if let BulkheadEvent::CallFailed { duration, .. } = event {
f(*duration);
}
}));
self
}
pub fn build(self) -> crate::layer::BulkheadLayer {
let config = BulkheadConfig {
max_concurrent_calls: self.max_concurrent_calls,
max_wait_duration: self.max_wait_duration,
name: self.name,
event_listeners: self.event_listeners,
};
crate::layer::BulkheadLayer::new(config)
}
}
impl Default for BulkheadConfigBuilder {
fn default() -> Self {
Self::new()
}
}