1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
//! Implements the Circuit Breaker pattern for supervised tasks.
use crate::enums::{CircuitBreakerConfig, SupervisorEvent};
use std::time::Instant;
use tokio::sync::broadcast;
use tracing::{info, warn};
/// Represents the state of a circuit breaker.
#[derive(Debug, Clone, PartialEq)]
pub enum CircuitState {
/// The circuit is closed, allowing requests to pass through.
Closed,
/// The circuit is open, blocking requests and failing fast.
Open { opened_at: Instant },
/// The circuit is half-open, allowing a single test request to pass through.
HalfOpen,
}
/// Implements the Circuit Breaker pattern for a supervised task.
#[derive(Debug, Clone)]
pub struct CircuitBreaker {
config: CircuitBreakerConfig,
state: CircuitState,
consecutive_failures: usize,
event_tx: broadcast::Sender<SupervisorEvent>,
task_id: String,
task_name: String,
}
impl CircuitBreaker {
/// Creates a new `CircuitBreaker` instance.
pub fn new(
config: CircuitBreakerConfig,
event_tx: broadcast::Sender<SupervisorEvent>,
task_id: String,
task_name: String,
) -> Self {
Self {
config,
state: CircuitState::Closed,
consecutive_failures: 0,
event_tx,
task_id,
task_name,
}
}
/// Checks if the circuit is allowing execution.
///
/// Returns `true` if the task can proceed, `false` otherwise.
pub fn allow_request(&mut self) -> bool {
match self.state {
CircuitState::Closed => true,
CircuitState::Open { opened_at } => {
if opened_at.elapsed() >= self.config.reset_timeout {
info!(
task_id = %self.task_id,
"Circuit breaker for task {} transitioning to Half-Open.",
self.task_id
);
self.state = CircuitState::HalfOpen;
let _ = self.event_tx.send(SupervisorEvent::CircuitBreakerHalfOpen {
id: self.task_id.clone(),
name: self.task_name.clone(),
});
true // Allow one request in Half-Open state
} else {
false // Still in Open state, block request
}
}
CircuitState::HalfOpen => true, // Allow one request
}
}
/// Records a successful execution.
///
/// If the circuit was Half-Open, it transitions back to Closed.
pub fn record_success(&mut self) {
self.consecutive_failures = 0;
if self.state != CircuitState::Closed {
info!(
task_id = %self.task_id,
"Circuit breaker for task {} transitioning to Closed (success).",
self.task_id
);
self.state = CircuitState::Closed;
let _ = self.event_tx.send(SupervisorEvent::CircuitBreakerReset {
id: self.task_id.clone(),
name: self.task_name.clone(),
});
}
}
/// Records a failed execution.
///
/// If the circuit was Closed or Half-Open, it may transition to Open.
pub fn record_failure(&mut self) {
self.consecutive_failures += 1;
match self.state {
CircuitState::Closed => {
if self.consecutive_failures >= self.config.failure_threshold {
info!(
task_id = %self.task_id,
consecutive_failures = self.consecutive_failures,
"Circuit breaker for task {} tripping to Open.",
self.task_id
);
self.state = CircuitState::Open {
opened_at: Instant::now(),
};
let _ = self.event_tx.send(SupervisorEvent::CircuitBreakerTripped {
id: self.task_id.clone(),
name: self.task_name.clone(),
consecutive_failures: self.consecutive_failures,
});
}
}
CircuitState::HalfOpen => {
warn!(
task_id = %self.task_id,
"Circuit breaker for task {} failed in Half-Open, returning to Open.",
self.task_id
);
self.state = CircuitState::Open {
opened_at: Instant::now(),
};
let _ = self.event_tx.send(SupervisorEvent::CircuitBreakerTripped {
id: self.task_id.clone(),
name: self.task_name.clone(),
consecutive_failures: self.consecutive_failures,
});
}
CircuitState::Open { .. } => {
// Already open, do nothing but increment failures
}
}
}
/// Resets the circuit breaker to the Closed state.
pub fn reset(&mut self) {
if self.state != CircuitState::Closed {
info!(
task_id = %self.task_id,
"Circuit breaker for task {} manually reset to Closed.",
self.task_id
);
self.state = CircuitState::Closed;
self.consecutive_failures = 0;
let _ = self.event_tx.send(SupervisorEvent::CircuitBreakerReset {
id: self.task_id.clone(),
name: self.task_name.clone(),
});
}
}
/// Returns the current state of the circuit breaker.
pub fn state(&self) -> &CircuitState {
&self.state
}
/// Returns the configured reset timeout for the circuit breaker.
pub fn reset_timeout(&self) -> std::time::Duration {
self.config.reset_timeout
}
}