euv-core 0.53.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
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(),
        )
    }
}