-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircuit_breaker.py
More file actions
50 lines (35 loc) · 1.8 KB
/
Copy pathcircuit_breaker.py
File metadata and controls
50 lines (35 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import time
import threading
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=30, expected_exception=Exception):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.expected_exception = expected_exception
self.failure_count = 0
self.last_failure_time = None
self.state = 'CLOSED'
self.lock = threading.Lock()
def call(self, func, *args, **kwargs):
with self.lock:
if self.state == 'OPEN':
time_since_failure = time.time() - self.last_failure_time
if time_since_failure > self.recovery_timeout:
self.state = 'HALF_OPEN'
else:
raise CircuitBreakerOpenException("Circuit is open. Call denied.")
try:
result = func(*args, **kwargs)
except self.expected_exception as e:
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = 'OPEN'
raise e
else:
if self.state == 'HALF_OPEN':
self.state = 'CLOSED'
self.failure_count = 0
return result
class CircuitBreakerOpenException(Exception):
"""Custom exception raised when the circuit breaker is open."""
pass