Przeczytaj kod uważnie
class CircuitBreaker:
def __init__(self, threshold=3):
self.state = "CLOSED"
self.failures = 0
self.threshold = threshold
def call(self, fn):
# OPEN — short-circuit, never call the real fn.
if self.state == "OPEN":
return "fallback"
try:
result = fn()
except Exception:
self.failures += 1
if self.failures >= self.threshold:
self.state = "OPEN"
return "fallback"
# Success path — only reset failure count from HALF_OPEN.
if self.state == "HALF_OPEN":
self.state = "CLOSED"
self.failures = 0
return result
def half_open(self):
# An external timer in a real CB would do this. We trigger
# it manually so the prediction stays deterministic.
self.state = "HALF_OPEN"
def ok(): return "ok"
def boom(): raise RuntimeError("dep down")
cb = CircuitBreaker(threshold=3)
cb.call(ok); print(cb.state) # CLOSED, success — state unchanged
cb.call(ok); print(cb.state) # CLOSED
cb.call(boom); print(cb.state) # 1 fail → CLOSED still (under threshold)
cb.call(boom); print(cb.state) # 2 fails → CLOSED
cb.call(boom); print(cb.state) # 3 fails → OPEN (just tripped)
cb.call(ok); print(cb.state) # OPEN — short-circuited, real fn skipped
cb.half_open()
cb.call(ok); print(cb.state) # HALF_OPEN probe success → CLOSED
# What does this print? Type your prediction.Co wypisze program? Napisz tutaj: