28 uint32_t FailureThreshold = 3,
29 uint32_t RecoveryTimeoutMs = 500
39 const CircuitState currentState = _state.load(std::memory_order_acquire);
46 const uint64_t now = nowMs();
47 const uint64_t trippedAt = _trippedAtMs.load(std::memory_order_acquire);
48 if (now >= trippedAt && (now - trippedAt) >= RecoveryTimeoutMs) {
66 _failureCount.store(0, std::memory_order_relaxed);
74 const uint32_t count = _failureCount.fetch_add(1, std::memory_order_relaxed) + 1;
75 if (count >= FailureThreshold) {
76 _trippedAtMs.store(nowMs(), std::memory_order_release);
84 _failureCount.store(0, std::memory_order_relaxed);
85 _trippedAtMs.store(0, std::memory_order_relaxed);
92 _trippedAtMs.store(nowMs(), std::memory_order_release);
99 const CircuitState s = _state.load(std::memory_order_acquire);
101 const uint64_t now = nowMs();
102 const uint64_t tripped = _trippedAtMs.load(std::memory_order_acquire);
103 if (now >= tripped && (now - tripped) >= RecoveryTimeoutMs) {
113 return _failureCount.load(std::memory_order_relaxed);
120 template <
typename Callable>
128#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)
148 [[nodiscard]]
static uint64_t nowMs() noexcept
150 return static_cast<uint64_t
>(
151 std::chrono::duration_cast<std::chrono::milliseconds>(
152 std::chrono::steady_clock::now().time_since_epoch()
158 std::atomic<uint32_t> _failureCount{0};
159 std::atomic<uint64_t> _trippedAtMs{0};
Zero-allocation Circuit Breaker pattern for isolating faulty handlers or peripheral links....
Definition CircuitBreaker.hpp:31
void recordFailure() noexcept
Record a failed operation. Increments failure counter and trips circuit Open if threshold is reached.
Definition CircuitBreaker.hpp:72
bool allowExecution() noexcept
Check if execution is permitted under current circuit state. Automatically transitions from Open to H...
Definition CircuitBreaker.hpp:37
void trip() noexcept
Manually trip the circuit breaker open.
Definition CircuitBreaker.hpp:90
void recordSuccess() noexcept
Record a successful operation execution. Resets consecutive failure counter and restores Closed state...
Definition CircuitBreaker.hpp:64
uint32_t failureCount() const noexcept
Current consecutive failure count.
Definition CircuitBreaker.hpp:111
CircuitState state() const noexcept
Current state of the circuit breaker.
Definition CircuitBreaker.hpp:97
CircuitBreaker() noexcept=default
bool execute(Callable &&fn)
Execute a protected callable through the circuit breaker.
Definition CircuitBreaker.hpp:121
void reset() noexcept
Manually reset the circuit breaker to normal Closed state.
Definition CircuitBreaker.hpp:82
Definition CircuitBreaker.hpp:13
CircuitState
Circuit Breaker operational state.
Definition CircuitBreaker.hpp:16
@ Closed
Normal operation: all calls execute.
@ Open
Tripped/Faulty: calls are fast-failed without execution.
@ HalfOpen
Recovery probing: allowing a single canary call to verify health.