29 case circuit_state::CLOSED:
31 case circuit_state::OPEN:
33 case circuit_state::HALF_OPEN:
45 throw std::runtime_error(
"Service unavailable");
52 std::cout <<
"=== Circuit Breaker Example ===\n\n";
58 config.
timeout = std::chrono::seconds(1);
64 std::cout <<
"1. Simulating failures...\n";
65 for (
int i = 0; i < 4; ++i)
69 std::cout <<
" Request " << i <<
": REJECTED (circuit open)\n";
77 guard.record_success();
79 catch (
const std::exception& e)
81 std::cout <<
" Request " << i <<
": FAILED (" << e.what() <<
")\n";
88 std::cout <<
"\n2. Waiting for timeout (1s)...\n";
89 std::this_thread::sleep_for(std::chrono::milliseconds(1100));
93 std::cout <<
"\n3. Recovering with successful requests...\n";
94 for (
int i = 0; i < 3; ++i)
98 std::cout <<
" Recovery " << i <<
": REJECTED\n";
104 guard.record_success();
110 std::cout <<
"\n4. Circuit breaker stats:\n";
112 for (
auto it = stats.begin(); it != stats.end(); ++it)
114 const auto& name = it->first;
115 const auto& val = it->second;
117 [&name](
const auto& v) { std::cout <<
" " << name <<
": " << v <<
"\n"; },
121 std::cout <<
"\nDone.\n";
Circuit breaker pattern for fault tolerance and resilience.
std::string state_name(circuit_state s)
bool call_external_service(bool should_fail)
Thread-safe circuit breaker for fault tolerance.
auto make_guard() -> guard
Create RAII guard for automatic recording.
auto allow_request() -> bool
Check if request should be allowed through the circuit.
auto get_state() const -> circuit_state
Get current circuit state.
auto get_stats() const -> std::unordered_map< std::string, interfaces::stats_value > override
Get current statistics as key-value pairs.
circuit_state
Represents the current state of a circuit breaker.
Configuration parameters for circuit breaker.
std::chrono::milliseconds timeout
Timeout before transitioning from OPEN to HALF_OPEN. Default: 30 seconds.
std::size_t failure_threshold
Number of failures required to trip the circuit (CLOSED -> OPEN). Default: 5 failures.
std::size_t success_threshold
Number of successful requests required to close the circuit (HALF_OPEN -> CLOSED)....