Skip to main content

industrial_protocols_kernel/
circuit.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # 熔断保护器
3//!
4//! 实现标准的熔断器模式:Closed → Open → HalfOpen 三态转换。
5//!
6//! - **Closed(闭合)** — 正常状态,请求正常通过。累计失败达到 threshold 时转为 Open。
7//! - **Open(断开)** — 拒绝所有请求。cooldown 时间后转为 HalfOpen。
8//! - **HalfOpen(半开)** — 允许一次试探请求。成功则转 Closed,失败则转 Open。
9//!
10//! 每个设备独立追踪失败计数和状态。
11
12use crate::error::{ProtocolError, Result};
13use std::collections::HashMap;
14use std::sync::Mutex;
15use std::time::{Duration, Instant};
16
17#[derive(Debug, Clone)]
18pub struct CircuitConfig {
19    pub threshold: u32,
20    pub cooldown: Duration,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum CircuitState {
25    Closed,
26    Open,
27    HalfOpen,
28}
29
30struct DeviceCircuit {
31    failures: u32,
32    state: CircuitState,
33    opened_at: Option<Instant>,
34}
35
36pub struct CircuitBreaker {
37    config: CircuitConfig,
38    devices: Mutex<HashMap<String, DeviceCircuit>>,
39}
40
41impl CircuitBreaker {
42    pub fn new(config: CircuitConfig) -> Self {
43        CircuitBreaker {
44            config,
45            devices: Mutex::new(HashMap::new()),
46        }
47    }
48
49    pub fn state(&self, device_id: &str) -> CircuitState {
50        let mut devices = self.devices.lock().unwrap();
51        let entry = devices
52            .entry(device_id.to_string())
53            .or_insert(DeviceCircuit {
54                failures: 0,
55                state: CircuitState::Closed,
56                opened_at: None,
57            });
58        self.transition_if_ready(entry);
59        entry.state
60    }
61
62    pub fn record_success(&self, device_id: &str) {
63        let mut devices = self.devices.lock().unwrap();
64        if let Some(entry) = devices.get_mut(device_id) {
65            entry.failures = 0;
66            entry.state = CircuitState::Closed;
67            entry.opened_at = None;
68        }
69    }
70
71    pub fn record_failure(&self, device_id: &str) {
72        let mut devices = self.devices.lock().unwrap();
73        let entry = devices
74            .entry(device_id.to_string())
75            .or_insert(DeviceCircuit {
76                failures: 0,
77                state: CircuitState::Closed,
78                opened_at: None,
79            });
80        entry.failures += 1;
81        if entry.failures >= self.config.threshold {
82            entry.state = CircuitState::Open;
83            entry.opened_at = Some(Instant::now());
84        }
85    }
86
87    pub fn call<F, T>(&self, device_id: &str, f: F) -> Result<T>
88    where
89        F: FnOnce() -> Result<T>,
90    {
91        match self.state(device_id) {
92            CircuitState::Open => {
93                let devices = self.devices.lock().unwrap();
94                let retry_after = devices
95                    .get(device_id)
96                    .and_then(|e| e.opened_at)
97                    .map(|t| self.config.cooldown.saturating_sub(t.elapsed()))
98                    .unwrap_or(self.config.cooldown);
99                Err(ProtocolError::CircuitOpen {
100                    device: device_id.into(),
101                    retry_after,
102                })
103            }
104            CircuitState::Closed | CircuitState::HalfOpen => match f() {
105                Ok(val) => {
106                    self.record_success(device_id);
107                    Ok(val)
108                }
109                Err(e) => {
110                    self.record_failure(device_id);
111                    Err(e)
112                }
113            },
114        }
115    }
116
117    fn transition_if_ready(&self, entry: &mut DeviceCircuit) {
118        if entry.state == CircuitState::Open
119            && let Some(t) = entry.opened_at
120            && t.elapsed() >= self.config.cooldown
121        {
122            entry.state = CircuitState::HalfOpen;
123        }
124    }
125}