mecha10-core 0.6.5

Mecha10 core runtime and foundational types
Documentation
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Circuit Breaker Pattern for Fault Tolerance
//!
//! Prevents cascading failures by temporarily blocking requests to failing services.
//! When a service experiences repeated failures, the circuit breaker "opens" and
//! fails fast without attempting the request, giving the failing service time to recover.
//!
//! # States
//!
//! 1. **Closed** - Normal operation, requests pass through
//! 2. **Open** - Service is failing, requests fail fast without trying
//! 3. **Half-Open** - Testing if service has recovered
//!
//! # State Transitions
//!
//! ```text
//!           Success
//!             ↓
//!    ┌─────────────┐
//!    │   CLOSED    │ ←─────┐
//!    │  (Normal)   │       │
//!    └─────────────┘       │
//!          │               │ Success
//!  Failure threshold       │
//!  reached                 │
//!          ↓               │
//!    ┌─────────────┐   ┌──────────┐
//!    │    OPEN     │   │ HALF-OPEN│
//!    │(Fail Fast)  │──→│ (Testing)│
//!    └─────────────┘   └──────────┘
//!      After timeout       │
//!                     Failure
//!                          ↓
//!                     (back to OPEN)
//! ```
//!
//! # Example
//!
//! ```rust
//! use mecha10_core::prelude::*;
//! use mecha10_core::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
//!
//! # async fn example(ctx: &Context) -> Result<()> {
//! // Create circuit breaker for motor control service
//! let breaker = CircuitBreaker::new(
//!     CircuitBreakerConfig {
//!         failure_threshold: 5,           // Open after 5 failures
//!         success_threshold: 2,           // Close after 2 successes in half-open
//!         timeout: Duration::from_secs(30), // Wait 30s before trying again
//!         ..Default::default()
//!     }
//! );
//!
//! // Make request through circuit breaker
//! let result = breaker.call(|| async {
//!     ctx.request("/motor/control", &command)
//!         .timeout(Duration::from_secs(5))
//!         .await
//! }).await?;
//! # Ok(())
//! # }
//! ```

use crate::error::{Mecha10Error, Result};
use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

/// Circuit breaker state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// Normal operation - requests pass through
    Closed,
    /// Service is failing - requests fail fast
    Open,
    /// Testing if service has recovered - limited requests allowed
    HalfOpen,
}

/// Circuit breaker configuration
#[derive(Debug, Clone)]
pub struct CircuitBreakerConfig {
    /// Number of consecutive failures before opening the circuit
    pub failure_threshold: u32,

    /// Number of consecutive successes in half-open state before closing
    pub success_threshold: u32,

    /// How long to wait before transitioning from open to half-open
    pub timeout: Duration,

    /// Optional: Name for logging and metrics
    pub name: Option<String>,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            success_threshold: 2,
            timeout: Duration::from_secs(60),
            name: None,
        }
    }
}

/// Internal state of the circuit breaker
#[derive(Debug)]
struct CircuitBreakerState {
    /// Current state of the circuit
    state: CircuitState,

    /// Number of consecutive failures in closed state
    failure_count: u32,

    /// Number of consecutive successes in half-open state
    success_count: u32,

    /// When the circuit was opened (for timeout calculation)
    opened_at: Option<Instant>,

    /// Total number of requests processed
    total_requests: u64,

    /// Total number of successful requests
    total_successes: u64,

    /// Total number of failed requests
    total_failures: u64,

    /// Total number of rejected requests (when circuit is open)
    total_rejected: u64,
}

impl CircuitBreakerState {
    fn new() -> Self {
        Self {
            state: CircuitState::Closed,
            failure_count: 0,
            success_count: 0,
            opened_at: None,
            total_requests: 0,
            total_successes: 0,
            total_failures: 0,
            total_rejected: 0,
        }
    }
}

/// Circuit breaker for preventing cascading failures
///
/// Wraps RPC calls and other potentially failing operations. Automatically
/// opens the circuit after repeated failures to prevent wasting resources
/// on a failing service.
///
/// # Thread Safety
///
/// Circuit breaker is thread-safe and can be cloned cheaply (uses Arc internally).
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
/// use mecha10_core::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
///
/// # async fn example(ctx: &Context) -> Result<()> {
/// let breaker = CircuitBreaker::new(
///     CircuitBreakerConfig {
///         failure_threshold: 3,
///         success_threshold: 2,
///         timeout: Duration::from_secs(30),
///         name: Some("motor_control".to_string()),
///     }
/// );
///
/// loop {
///     match breaker.call(|| async {
///         ctx.request("/motor/control", &command)
///             .timeout(Duration::from_secs(5))
///             .await
///     }).await {
///         Ok(result) => {
///             info!("Command succeeded: {:?}", result);
///         }
///         Err(e) if breaker.is_open() => {
///             warn!("Circuit breaker open, skipping request");
///             // Use fallback or degraded mode
///         }
///         Err(e) => {
///             warn!("Request failed: {}", e);
///         }
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct CircuitBreaker {
    config: CircuitBreakerConfig,
    state: Arc<RwLock<CircuitBreakerState>>,
}

impl CircuitBreaker {
    /// Create a new circuit breaker with the given configuration
    pub fn new(config: CircuitBreakerConfig) -> Self {
        debug!(
            "Creating circuit breaker '{}' with failure_threshold={}, success_threshold={}, timeout={:?}",
            config.name.as_deref().unwrap_or("unnamed"),
            config.failure_threshold,
            config.success_threshold,
            config.timeout
        );

        Self {
            config,
            state: Arc::new(RwLock::new(CircuitBreakerState::new())),
        }
    }

    /// Execute a potentially failing operation through the circuit breaker
    ///
    /// # Arguments
    ///
    /// * `operation` - Async function to execute
    ///
    /// # Returns
    ///
    /// - `Ok(T)` if operation succeeded
    /// - `Err(CircuitBreakerOpen)` if circuit is open (failing fast)
    /// - `Err(...)` if operation failed
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::circuit_breaker::CircuitBreaker;
    /// # async fn example(breaker: &CircuitBreaker) -> mecha10_core::Result<String> {
    /// let result = breaker.call(|| async {
    ///     // Your operation here
    ///     Ok("success".to_string())
    /// }).await?;
    /// # Ok(result)
    /// # }
    /// ```
    pub async fn call<F, Fut, T>(&self, operation: F) -> Result<T>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<T>>,
    {
        {
            let mut state = self.state.write().await;
            state.total_requests += 1;

            match state.state {
                CircuitState::Closed => {}
                CircuitState::Open => {
                    if let Some(opened_at) = state.opened_at {
                        if opened_at.elapsed() >= self.config.timeout {
                            info!(
                                "Circuit breaker '{}' transitioning to half-open (testing recovery)",
                                self.config.name.as_deref().unwrap_or("unnamed")
                            );
                            state.state = CircuitState::HalfOpen;
                            state.success_count = 0;
                            state.failure_count = 0;
                        } else {
                            state.total_rejected += 1;
                            return Err(Mecha10Error::CircuitBreakerOpen {
                                service: self.config.name.clone().unwrap_or_else(|| "unknown".to_string()),
                                message: format!(
                                    "Circuit breaker open due to repeated failures. Retry after {:?}",
                                    self.config.timeout - opened_at.elapsed()
                                ),
                            });
                        }
                    }
                }
                CircuitState::HalfOpen => {}
            }
        }

        let result = operation().await;

        {
            let mut state = self.state.write().await;

            match &result {
                Ok(_) => {
                    state.total_successes += 1;
                    self.on_success(&mut state).await;
                }
                Err(_) => {
                    state.total_failures += 1;
                    self.on_failure(&mut state).await;
                }
            }
        }

        result
    }

    /// Handle successful operation
    async fn on_success(&self, state: &mut CircuitBreakerState) {
        match state.state {
            CircuitState::Closed => {
                state.failure_count = 0;
            }
            CircuitState::HalfOpen => {
                state.success_count += 1;

                if state.success_count >= self.config.success_threshold {
                    info!(
                        "Circuit breaker '{}' closing (service recovered)",
                        self.config.name.as_deref().unwrap_or("unnamed")
                    );
                    state.state = CircuitState::Closed;
                    state.success_count = 0;
                    state.failure_count = 0;
                    state.opened_at = None;
                }
            }
            CircuitState::Open => {
                warn!("Success recorded in open state (unexpected)");
            }
        }
    }

    /// Handle failed operation
    async fn on_failure(&self, state: &mut CircuitBreakerState) {
        match state.state {
            CircuitState::Closed => {
                state.failure_count += 1;

                if state.failure_count >= self.config.failure_threshold {
                    warn!(
                        "Circuit breaker '{}' opening (failure threshold reached: {} failures)",
                        self.config.name.as_deref().unwrap_or("unnamed"),
                        state.failure_count
                    );
                    state.state = CircuitState::Open;
                    state.opened_at = Some(Instant::now());
                    state.failure_count = 0;
                }
            }
            CircuitState::HalfOpen => {
                warn!(
                    "Circuit breaker '{}' re-opening (service still failing)",
                    self.config.name.as_deref().unwrap_or("unnamed")
                );
                state.state = CircuitState::Open;
                state.opened_at = Some(Instant::now());
                state.success_count = 0;
                state.failure_count = 0;
            }
            CircuitState::Open => {}
        }
    }

    /// Shared body behind `is_open`/`is_closed`/`is_half_open`, which only differ in which
    /// `CircuitState` variant they compare against.
    async fn is_state(&self, want: CircuitState) -> bool {
        let state = self.state.read().await;
        state.state == want
    }

    /// Check if the circuit breaker is currently open
    pub async fn is_open(&self) -> bool {
        self.is_state(CircuitState::Open).await
    }

    /// Check if the circuit breaker is currently closed
    pub async fn is_closed(&self) -> bool {
        self.is_state(CircuitState::Closed).await
    }

    /// Check if the circuit breaker is currently half-open
    pub async fn is_half_open(&self) -> bool {
        self.is_state(CircuitState::HalfOpen).await
    }

    /// Get the current state
    pub async fn state(&self) -> CircuitState {
        let state = self.state.read().await;
        state.state
    }

    /// Get statistics about the circuit breaker
    ///
    /// Returns (total_requests, successes, failures, rejected)
    pub async fn stats(&self) -> (u64, u64, u64, u64) {
        let state = self.state.read().await;
        (
            state.total_requests,
            state.total_successes,
            state.total_failures,
            state.total_rejected,
        )
    }

    /// Get success rate (0.0 to 1.0)
    pub async fn success_rate(&self) -> f64 {
        let state = self.state.read().await;
        let total_attempted = state.total_successes + state.total_failures;

        if total_attempted == 0 {
            1.0
        } else {
            state.total_successes as f64 / total_attempted as f64
        }
    }

    /// Manually reset the circuit breaker to closed state
    ///
    /// Use with caution - only when you know the service has recovered.
    pub async fn reset(&self) {
        self.force_state("reset to closed", CircuitState::Closed, None).await;
    }

    /// Manually open the circuit breaker
    ///
    /// Use for maintenance or manual intervention.
    pub async fn open(&self) {
        self.force_state("manually opened", CircuitState::Open, Some(Instant::now()))
            .await;
    }

    /// Shared implementation behind `reset`/`open`, which differ only in the target state, the
    /// `opened_at` timestamp to record, and the log message.
    async fn force_state(&self, log_action: &str, new_state: CircuitState, opened_at: Option<Instant>) {
        let mut state = self.state.write().await;
        info!(
            "Circuit breaker '{}' {}",
            self.config.name.as_deref().unwrap_or("unnamed"),
            log_action
        );
        state.state = new_state;
        state.failure_count = 0;
        state.success_count = 0;
        state.opened_at = opened_at;
    }
}

// duplicate: false positive — matches `BehaviorLoader`'s manual `Debug` impl (in
// packages/behavior-runtime/src/loader.rs) on AST shape only: both are a single
// `f.debug_struct(...).field(...).finish()` call. They're unrelated types in unrelated
// crates, and both are manual (not `#[derive(Debug)]`) specifically to control which fields
// are shown — here, `state` is deliberately omitted — so there's no shared abstraction to
// extract for a one-line body.
impl std::fmt::Debug for CircuitBreaker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CircuitBreaker").field("config", &self.config).finish()
    }
}