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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use super::*;
/// Default healthy `ErrorBoundary` configured with standard history and trip limits.
impl Default for ErrorBoundary {
/// Creates a default healthy `ErrorBoundary`.
///
/// # Returns
///
/// - `Self` - Healthy error boundary using default limits.
fn default() -> Self {
Self::with_limits(
FAULT_DEFAULT_SCOPE,
DEFAULT_MAX_CONSECUTIVE_FAULTS,
DEFAULT_FAULT_HISTORY_LIMIT,
)
}
}
/// Fault-isolation execution, recovery, and telemetry methods for `ErrorBoundary`.
impl ErrorBoundary {
/// Creates a named `ErrorBoundary` with default consecutive-fault and history limits.
///
/// # Arguments
///
/// - `NameType` - Diagnostic boundary name.
///
/// # Returns
///
/// - `Self` - Healthy named error boundary.
#[must_use]
pub fn named<NameType>(name: NameType) -> Self
where
NameType: Into<String>,
{
Self::with_limits(
name,
DEFAULT_MAX_CONSECUTIVE_FAULTS,
DEFAULT_FAULT_HISTORY_LIMIT,
)
}
/// Creates a named `ErrorBoundary` with explicit consecutive-fault trip threshold and history capacity.
///
/// # Arguments
///
/// - `NameType` - Diagnostic boundary name.
/// - `u32` - Consecutive panic threshold triggering `ErrorBoundaryState::Tripped` (clamped to `>= 1`).
/// - `usize` - Maximum number of recent `FaultRecord` items kept in memory.
///
/// # Returns
///
/// - `Self` - Configured healthy error boundary.
#[must_use]
pub fn with_limits<NameType>(
name: NameType,
max_consecutive_faults: u32,
history_limit: usize,
) -> Self
where
NameType: Into<String>,
{
Self {
name: name.into(),
state: ErrorBoundaryState::Healthy,
max_consecutive_faults: max_consecutive_faults.max(1),
history_limit,
total_faults: 0,
consecutive_faults: 0,
recoveries: 0,
successful_invocations: 0,
next_sequence: 1,
history: VecDeque::with_capacity(history_limit.min(DEFAULT_FAULT_HISTORY_LIMIT)),
}
}
/// Executes `operation` inside `catch_unwind`, updating fault telemetry and returning a structured `FaultRecord` on panic.
///
/// # Arguments
///
/// - `FaultOrigin` - Runtime site category for fault attribution.
/// - `&str` - Component, effect, or task scope label.
/// - `u64` - Monotonic timestamp in milliseconds.
/// - `CallbackFn` - Protected closure to execute.
///
/// # Returns
///
/// - `Result<ReturnValue, FaultRecord>` - Operation return value or captured fault record.
pub fn guard<CallbackFn, ReturnValue>(
&mut self,
origin: FaultOrigin,
scope: &str,
timestamp_ms: u64,
operation: CallbackFn,
) -> Result<ReturnValue, FaultRecord>
where
CallbackFn: FnOnce() -> ReturnValue,
{
match run_isolated(operation) {
Ok(value) => {
let next_ok: u64 = self.get_successful_invocations().saturating_add(1);
self.set_successful_invocations(next_ok);
if self.get_state() != ErrorBoundaryState::Tripped {
self.set_consecutive_faults(0);
self.set_state(ErrorBoundaryState::Healthy);
}
Ok(value)
}
Err(message) => {
let sequence: u64 = self.get_next_sequence();
self.set_next_sequence(sequence.saturating_add(1));
let next_total: u64 = self.get_total_faults().saturating_add(1);
self.set_total_faults(next_total);
let next_consecutive: u32 = self.get_consecutive_faults().saturating_add(1);
self.set_consecutive_faults(next_consecutive);
let next_state: ErrorBoundaryState =
if next_consecutive >= self.get_max_consecutive_faults() {
ErrorBoundaryState::Tripped
} else {
ErrorBoundaryState::Degraded
};
self.set_state(next_state);
let scope_label: String = if scope.is_empty() {
self.get_name().clone()
} else {
scope.to_string()
};
let record: FaultRecord =
FaultRecord::new(sequence, origin, scope_label, message, timestamp_ms);
let limit: usize = self.get_history_limit();
if limit > 0 {
let history: &mut VecDeque<FaultRecord> = self.get_mut_history();
while history.len() >= limit {
let _: Option<FaultRecord> = history.pop_front();
}
history.push_back(record.clone());
}
Err(record)
}
}
}
/// Executes `operation` under panic isolation, invoking `fallback` with the captured `FaultRecord` if it panics.
///
/// # Arguments
///
/// - `FaultOrigin` - Runtime site category for fault attribution.
/// - `&str` - Component, effect, or task scope label.
/// - `u64` - Monotonic timestamp in milliseconds.
/// - `CallbackFn` - Protected primary closure.
/// - `FallbackFn` - Recovery closure invoked with `&FaultRecord` on panic.
///
/// # Returns
///
/// - `ReturnValue` - Primary result or fallback recovery result.
pub fn guard_or<CallbackFn, FallbackFn, ReturnValue>(
&mut self,
origin: FaultOrigin,
scope: &str,
timestamp_ms: u64,
operation: CallbackFn,
fallback: FallbackFn,
) -> ReturnValue
where
CallbackFn: FnOnce() -> ReturnValue,
FallbackFn: FnOnce(&FaultRecord) -> ReturnValue,
{
match self.guard(origin, scope, timestamp_ms, operation) {
Ok(value) => value,
Err(record) => fallback(&record),
}
}
/// Resets a `Degraded` or `Tripped` boundary back to `Healthy`, clearing its consecutive fault counter.
///
/// # Returns
///
/// - `bool` - `true` when the boundary transitioned out of a faulted state.
pub fn recover(&mut self) -> bool {
if self.get_state() == ErrorBoundaryState::Healthy && self.get_consecutive_faults() == 0 {
return false;
}
self.set_state(ErrorBoundaryState::Healthy);
self.set_consecutive_faults(0);
let next_recoveries: u64 = self.get_recoveries().saturating_add(1);
self.set_recoveries(next_recoveries);
true
}
/// Returns `true` when the boundary has reached its consecutive-fault trip threshold.
///
/// # Returns
///
/// - `bool` - `true` when `state == ErrorBoundaryState::Tripped`.
#[must_use]
pub fn is_tripped(&self) -> bool {
self.get_state() == ErrorBoundaryState::Tripped
}
/// Returns the most recently intercepted fault record, if any.
///
/// # Returns
///
/// - `Option<&FaultRecord>` - Latest fault record in the history ring.
#[must_use]
pub fn last_fault(&self) -> Option<&FaultRecord> {
self.get_history().back()
}
/// Returns an ordered snapshot of all retained recent fault records (oldest first).
///
/// # Returns
///
/// - `Vec<FaultRecord>` - Retained fault history snapshot.
#[must_use]
pub fn recent_faults(&self) -> Vec<FaultRecord> {
self.get_history().iter().cloned().collect()
}
/// Captures a compact copyable telemetry snapshot of this error boundary.
///
/// # Returns
///
/// - `ErrorBoundaryTelemetry` - Current health state and fault counters.
#[must_use]
pub fn telemetry(&self) -> ErrorBoundaryTelemetry {
ErrorBoundaryTelemetry::new(
self.get_state(),
self.get_total_faults(),
self.get_consecutive_faults(),
self.get_recoveries(),
self.get_successful_invocations(),
self.get_history().len(),
)
}
}