euv_core/runtime/fault/impl.rs
1use super::*;
2
3/// Default healthy `ErrorBoundary` configured with standard history and trip limits.
4impl Default for ErrorBoundary {
5 /// Creates a default healthy `ErrorBoundary`.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Healthy error boundary using default limits.
10 fn default() -> Self {
11 Self::with_limits(
12 FAULT_DEFAULT_SCOPE,
13 DEFAULT_MAX_CONSECUTIVE_FAULTS,
14 DEFAULT_FAULT_HISTORY_LIMIT,
15 )
16 }
17}
18
19/// Fault-isolation execution, recovery, and telemetry methods for `ErrorBoundary`.
20impl ErrorBoundary {
21 /// Creates a named `ErrorBoundary` with default consecutive-fault and history limits.
22 ///
23 /// # Arguments
24 ///
25 /// - `NameType` - Diagnostic boundary name.
26 ///
27 /// # Returns
28 ///
29 /// - `Self` - Healthy named error boundary.
30 #[must_use]
31 pub fn named<NameType>(name: NameType) -> Self
32 where
33 NameType: Into<String>,
34 {
35 Self::with_limits(
36 name,
37 DEFAULT_MAX_CONSECUTIVE_FAULTS,
38 DEFAULT_FAULT_HISTORY_LIMIT,
39 )
40 }
41
42 /// Creates a named `ErrorBoundary` with explicit consecutive-fault trip threshold and history capacity.
43 ///
44 /// # Arguments
45 ///
46 /// - `NameType` - Diagnostic boundary name.
47 /// - `u32` - Consecutive panic threshold triggering `ErrorBoundaryState::Tripped` (clamped to `>= 1`).
48 /// - `usize` - Maximum number of recent `FaultRecord` items kept in memory.
49 ///
50 /// # Returns
51 ///
52 /// - `Self` - Configured healthy error boundary.
53 #[must_use]
54 pub fn with_limits<NameType>(
55 name: NameType,
56 max_consecutive_faults: u32,
57 history_limit: usize,
58 ) -> Self
59 where
60 NameType: Into<String>,
61 {
62 Self {
63 name: name.into(),
64 state: ErrorBoundaryState::Healthy,
65 max_consecutive_faults: max_consecutive_faults.max(1),
66 history_limit,
67 total_faults: 0,
68 consecutive_faults: 0,
69 recoveries: 0,
70 successful_invocations: 0,
71 next_sequence: 1,
72 history: VecDeque::with_capacity(history_limit.min(DEFAULT_FAULT_HISTORY_LIMIT)),
73 }
74 }
75
76 /// Executes `operation` inside `catch_unwind`, updating fault telemetry and returning a structured `FaultRecord` on panic.
77 ///
78 /// # Arguments
79 ///
80 /// - `FaultOrigin` - Runtime site category for fault attribution.
81 /// - `&str` - Component, effect, or task scope label.
82 /// - `u64` - Monotonic timestamp in milliseconds.
83 /// - `CallbackFn` - Protected closure to execute.
84 ///
85 /// # Returns
86 ///
87 /// - `Result<ReturnValue, FaultRecord>` - Operation return value or captured fault record.
88 pub fn guard<CallbackFn, ReturnValue>(
89 &mut self,
90 origin: FaultOrigin,
91 scope: &str,
92 timestamp_ms: u64,
93 operation: CallbackFn,
94 ) -> Result<ReturnValue, FaultRecord>
95 where
96 CallbackFn: FnOnce() -> ReturnValue,
97 {
98 match run_isolated(operation) {
99 Ok(value) => {
100 let next_ok: u64 = self.get_successful_invocations().saturating_add(1);
101 self.set_successful_invocations(next_ok);
102 if self.get_state() != ErrorBoundaryState::Tripped {
103 self.set_consecutive_faults(0);
104 self.set_state(ErrorBoundaryState::Healthy);
105 }
106 Ok(value)
107 }
108 Err(message) => {
109 let sequence: u64 = self.get_next_sequence();
110 self.set_next_sequence(sequence.saturating_add(1));
111 let next_total: u64 = self.get_total_faults().saturating_add(1);
112 self.set_total_faults(next_total);
113 let next_consecutive: u32 = self.get_consecutive_faults().saturating_add(1);
114 self.set_consecutive_faults(next_consecutive);
115 let next_state: ErrorBoundaryState =
116 if next_consecutive >= self.get_max_consecutive_faults() {
117 ErrorBoundaryState::Tripped
118 } else {
119 ErrorBoundaryState::Degraded
120 };
121 self.set_state(next_state);
122 let scope_label: String = if scope.is_empty() {
123 self.get_name().clone()
124 } else {
125 scope.to_string()
126 };
127 let record: FaultRecord =
128 FaultRecord::new(sequence, origin, scope_label, message, timestamp_ms);
129 let limit: usize = self.get_history_limit();
130 if limit > 0 {
131 let history: &mut VecDeque<FaultRecord> = self.get_mut_history();
132 while history.len() >= limit {
133 let _: Option<FaultRecord> = history.pop_front();
134 }
135 history.push_back(record.clone());
136 }
137 Err(record)
138 }
139 }
140 }
141
142 /// Executes `operation` under panic isolation, invoking `fallback` with the captured `FaultRecord` if it panics.
143 ///
144 /// # Arguments
145 ///
146 /// - `FaultOrigin` - Runtime site category for fault attribution.
147 /// - `&str` - Component, effect, or task scope label.
148 /// - `u64` - Monotonic timestamp in milliseconds.
149 /// - `CallbackFn` - Protected primary closure.
150 /// - `FallbackFn` - Recovery closure invoked with `&FaultRecord` on panic.
151 ///
152 /// # Returns
153 ///
154 /// - `ReturnValue` - Primary result or fallback recovery result.
155 pub fn guard_or<CallbackFn, FallbackFn, ReturnValue>(
156 &mut self,
157 origin: FaultOrigin,
158 scope: &str,
159 timestamp_ms: u64,
160 operation: CallbackFn,
161 fallback: FallbackFn,
162 ) -> ReturnValue
163 where
164 CallbackFn: FnOnce() -> ReturnValue,
165 FallbackFn: FnOnce(&FaultRecord) -> ReturnValue,
166 {
167 match self.guard(origin, scope, timestamp_ms, operation) {
168 Ok(value) => value,
169 Err(record) => fallback(&record),
170 }
171 }
172
173 /// Resets a `Degraded` or `Tripped` boundary back to `Healthy`, clearing its consecutive fault counter.
174 ///
175 /// # Returns
176 ///
177 /// - `bool` - `true` when the boundary transitioned out of a faulted state.
178 pub fn recover(&mut self) -> bool {
179 if self.get_state() == ErrorBoundaryState::Healthy && self.get_consecutive_faults() == 0 {
180 return false;
181 }
182 self.set_state(ErrorBoundaryState::Healthy);
183 self.set_consecutive_faults(0);
184 let next_recoveries: u64 = self.get_recoveries().saturating_add(1);
185 self.set_recoveries(next_recoveries);
186 true
187 }
188
189 /// Returns `true` when the boundary has reached its consecutive-fault trip threshold.
190 ///
191 /// # Returns
192 ///
193 /// - `bool` - `true` when `state == ErrorBoundaryState::Tripped`.
194 #[must_use]
195 pub fn is_tripped(&self) -> bool {
196 self.get_state() == ErrorBoundaryState::Tripped
197 }
198
199 /// Returns the most recently intercepted fault record, if any.
200 ///
201 /// # Returns
202 ///
203 /// - `Option<&FaultRecord>` - Latest fault record in the history ring.
204 #[must_use]
205 pub fn last_fault(&self) -> Option<&FaultRecord> {
206 self.get_history().back()
207 }
208
209 /// Returns an ordered snapshot of all retained recent fault records (oldest first).
210 ///
211 /// # Returns
212 ///
213 /// - `Vec<FaultRecord>` - Retained fault history snapshot.
214 #[must_use]
215 pub fn recent_faults(&self) -> Vec<FaultRecord> {
216 self.get_history().iter().cloned().collect()
217 }
218
219 /// Captures a compact copyable telemetry snapshot of this error boundary.
220 ///
221 /// # Returns
222 ///
223 /// - `ErrorBoundaryTelemetry` - Current health state and fault counters.
224 #[must_use]
225 pub fn telemetry(&self) -> ErrorBoundaryTelemetry {
226 ErrorBoundaryTelemetry::new(
227 self.get_state(),
228 self.get_total_faults(),
229 self.get_consecutive_faults(),
230 self.get_recoveries(),
231 self.get_successful_invocations(),
232 self.get_history().len(),
233 )
234 }
235}