Common System 0.2.0
Common interfaces and patterns for system integration
Loading...
Searching...
No Matches
circuit_breaker_example.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
14
16
17#include <chrono>
18#include <iostream>
19#include <string>
20#include <thread>
21
22using namespace kcenon::common;
23using namespace kcenon::common::resilience;
24
26{
27 switch (s)
28 {
29 case circuit_state::CLOSED:
30 return "CLOSED";
31 case circuit_state::OPEN:
32 return "OPEN";
33 case circuit_state::HALF_OPEN:
34 return "HALF_OPEN";
35 default:
36 return "UNKNOWN";
37 }
38}
39
40// Simulated external service call
41bool call_external_service(bool should_fail)
42{
43 if (should_fail)
44 {
45 throw std::runtime_error("Service unavailable");
46 }
47 return true;
48}
49
50int main()
51{
52 std::cout << "=== Circuit Breaker Example ===\n\n";
53
54 // Configure: open after 3 failures, 1-second timeout
56 config.failure_threshold = 3;
57 config.success_threshold = 2;
58 config.timeout = std::chrono::seconds(1);
59
60 circuit_breaker breaker(config);
61 std::cout << "Initial state: " << state_name(breaker.get_state()) << "\n\n";
62
63 // Phase 1: Simulate failures to trip the breaker
64 std::cout << "1. Simulating failures...\n";
65 for (int i = 0; i < 4; ++i)
66 {
67 if (!breaker.allow_request())
68 {
69 std::cout << " Request " << i << ": REJECTED (circuit open)\n";
70 continue;
71 }
72
73 try
74 {
75 auto guard = breaker.make_guard();
76 call_external_service(true); // Will fail
77 guard.record_success();
78 }
79 catch (const std::exception& e)
80 {
81 std::cout << " Request " << i << ": FAILED (" << e.what() << ")\n";
82 }
83
84 std::cout << " State: " << state_name(breaker.get_state()) << "\n";
85 }
86
87 // Phase 2: Wait for timeout and try again
88 std::cout << "\n2. Waiting for timeout (1s)...\n";
89 std::this_thread::sleep_for(std::chrono::milliseconds(1100));
90 std::cout << " State after timeout: " << state_name(breaker.get_state()) << "\n";
91
92 // Phase 3: Recover with successful requests
93 std::cout << "\n3. Recovering with successful requests...\n";
94 for (int i = 0; i < 3; ++i)
95 {
96 if (!breaker.allow_request())
97 {
98 std::cout << " Recovery " << i << ": REJECTED\n";
99 continue;
100 }
101
102 auto guard = breaker.make_guard();
103 call_external_service(false); // Success
104 guard.record_success();
105 std::cout << " Recovery " << i << ": SUCCESS, state=" << state_name(breaker.get_state())
106 << "\n";
107 }
108
109 // Phase 4: Show stats
110 std::cout << "\n4. Circuit breaker stats:\n";
111 auto stats = breaker.get_stats();
112 for (auto it = stats.begin(); it != stats.end(); ++it)
113 {
114 const auto& name = it->first;
115 const auto& val = it->second;
116 std::visit(
117 [&name](const auto& v) { std::cout << " " << name << ": " << v << "\n"; },
118 val);
119 }
120
121 std::cout << "\nDone.\n";
122 return 0;
123}
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.
Core interfaces.
Definition adapter.h:21
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)....