smoothapi-py 0.2.0__tar.gz → 1.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/.gitignore +1 -0
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/PKG-INFO +81 -1
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/README.md +193 -113
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/pyproject.toml +1 -1
- smoothapi_py-1.1.0/smooth_api/__init__.py +197 -0
- smoothapi_py-1.1.0/smooth_api/config.py +56 -0
- smoothapi_py-1.1.0/smooth_api/dedup.py +116 -0
- smoothapi_py-1.1.0/tests/test_concurrency.py +37 -0
- smoothapi_py-1.1.0/tests/test_deduplication.py +209 -0
- smoothapi_py-1.1.0/tests/test_exceptions.py +18 -0
- smoothapi_py-1.1.0/tests/test_isolation.py +43 -0
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/tests/test_resilience.py +114 -3
- smoothapi_py-0.2.0/smooth_api/__init__.py +0 -113
- smoothapi_py-0.2.0/smooth_api/config.py +0 -27
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/LICENSE +0 -0
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/smooth_api/state.py +0 -0
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/smooth_api/utils.py +0 -0
- {smoothapi_py-0.2.0 → smoothapi_py-1.1.0}/tests/conftest.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: smoothapi-py
|
|
3
|
-
Version:
|
|
3
|
+
Version: 1.1.0
|
|
4
4
|
Summary: API resilience library — exponential backoff and circuit breaker
|
|
5
5
|
License: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -31,6 +31,7 @@ pip install smoothapi-py
|
|
|
31
31
|
- **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
|
|
32
32
|
- **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on transient codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
|
|
33
33
|
- **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
|
|
34
|
+
- **Request Deduplication:** Automatically coalesce concurrent identical requests into a single network call (async only).
|
|
34
35
|
|
|
35
36
|
## Usage
|
|
36
37
|
|
|
@@ -101,6 +102,29 @@ def get_user_data(user_id: str):
|
|
|
101
102
|
data = get_user_data("456", fallback={"status": "override"})
|
|
102
103
|
```
|
|
103
104
|
|
|
105
|
+
### Client Error Handling & Warnings
|
|
106
|
+
|
|
107
|
+
By default, non-retryable client errors (e.g. `400`, `401`, `403`, `404`, `405`) bubble up and raise exceptions immediately. If you want to intercept these client errors:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
111
|
+
|
|
112
|
+
def my_callback(status: int, message: str):
|
|
113
|
+
print(f"Error hook: Received client error {status}")
|
|
114
|
+
|
|
115
|
+
config = ResilientConfig(
|
|
116
|
+
fallback_on_non_retryable=True,
|
|
117
|
+
# Optional: Custom error hook function
|
|
118
|
+
on_non_retryable_error=my_callback,
|
|
119
|
+
# Optional: Fallback returned on non-retryable errors
|
|
120
|
+
fallback={"status": "error", "message": "Not Found"}
|
|
121
|
+
)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
* **Default Warning**: If `fallback_on_non_retryable` is `True` and no custom `on_non_retryable_error` is defined, it will write a warning message to `sys.stderr`.
|
|
125
|
+
* **Graceful Return**: If no `fallback` is configured, it returns a mock `Response` wrapper with `status_code`, `.json()` returning `{"error": True, "status": status, "message": "..."}`, and `.ok` returning `False`. Code downstream can check `res.status_code` or call `res.json()` without raising exceptions.
|
|
126
|
+
```
|
|
127
|
+
|
|
104
128
|
### Async Support
|
|
105
129
|
|
|
106
130
|
The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
|
|
@@ -116,6 +140,62 @@ async def get_user_data_async(user_id: str):
|
|
|
116
140
|
return res.json()
|
|
117
141
|
```
|
|
118
142
|
|
|
143
|
+
### Request Deduplication (Async Only)
|
|
144
|
+
|
|
145
|
+
When multiple identical async requests are made concurrently, SmoothAPI can execute only one network call and share the result with all callers. This reduces unnecessary load on downstream services.
|
|
146
|
+
|
|
147
|
+
**Enable with default key function** (deduplicates by positional args):
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
import httpx
|
|
151
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
152
|
+
from smooth_api.config import DeduplicationConfig
|
|
153
|
+
|
|
154
|
+
config = ResilientConfig(deduplication=DeduplicationConfig())
|
|
155
|
+
|
|
156
|
+
@resilient_api(config)
|
|
157
|
+
async def get_user(user_id: int):
|
|
158
|
+
async with httpx.AsyncClient() as client:
|
|
159
|
+
res = await client.get(f"https://api.example.com/users/{user_id}")
|
|
160
|
+
res.raise_for_status()
|
|
161
|
+
return res.json()
|
|
162
|
+
|
|
163
|
+
# All three calls share a single network request
|
|
164
|
+
import asyncio
|
|
165
|
+
results = await asyncio.gather(
|
|
166
|
+
get_user(1),
|
|
167
|
+
get_user(1),
|
|
168
|
+
get_user(1),
|
|
169
|
+
)
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
**Custom key function** for advanced coalescing:
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
from smooth_api.config import DeduplicationConfig
|
|
176
|
+
|
|
177
|
+
def my_key(*args, **kwargs):
|
|
178
|
+
# Deduplicate by second argument (resource type)
|
|
179
|
+
return str(args[1]) if len(args) > 1 else str(args[0])
|
|
180
|
+
|
|
181
|
+
config = ResilientConfig(deduplication=DeduplicationConfig(key_fn=my_key))
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
**Opt out of deduplication** for specific calls:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
config = ResilientConfig(
|
|
188
|
+
deduplication=DeduplicationConfig(
|
|
189
|
+
key_fn=lambda *a, **k: None # Return None to skip dedup
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
* **Default Behavior**: Deduplicates by joining positional args with `:`. E.g., `get_user(1)` produces key `"1"`.
|
|
195
|
+
* **Error Propagation**: If the coroutine raises an exception, all waiting callers receive the same exception.
|
|
196
|
+
* **Settlement**: Once a call completes, the next call with the same key triggers a fresh execution.
|
|
197
|
+
* **Sync Functions**: Deduplication only works with async-decorated functions. Sync functions are unaffected.
|
|
198
|
+
|
|
119
199
|
## How It Works
|
|
120
200
|
|
|
121
201
|
1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
|
|
@@ -1,113 +1,193 @@
|
|
|
1
|
-
# smoothapi-py
|
|
2
|
-
|
|
3
|
-
API resilience library for Python. It provides a decorator to wrap your HTTP requests with **exponential backoff, full jitter, and a finite-state machine circuit breaker** to protect against cascading failures.
|
|
4
|
-
|
|
5
|
-
Zero dependencies. Fully typed. Supports both sync and async functions out of the box. Automatically integrates with `requests` and `httpx` if installed.
|
|
6
|
-
|
|
7
|
-
## Install
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
pip install smoothapi-py
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
## Features
|
|
14
|
-
|
|
15
|
-
- **Exponential Backoff with Full Jitter:** Prevents the "thundering herd" problem by randomizing retry delays.
|
|
16
|
-
- **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
|
|
17
|
-
- **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on transient codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
|
|
18
|
-
- **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
res.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
- **
|
|
50
|
-
- **
|
|
51
|
-
- **Circuit
|
|
52
|
-
- **
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
from smooth_api
|
|
61
|
-
import
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
res.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
1
|
+
# smoothapi-py
|
|
2
|
+
|
|
3
|
+
API resilience library for Python. It provides a decorator to wrap your HTTP requests with **exponential backoff, full jitter, and a finite-state machine circuit breaker** to protect against cascading failures.
|
|
4
|
+
|
|
5
|
+
Zero dependencies. Fully typed. Supports both sync and async functions out of the box. Automatically integrates with `requests` and `httpx` if installed.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install smoothapi-py
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- **Exponential Backoff with Full Jitter:** Prevents the "thundering herd" problem by randomizing retry delays.
|
|
16
|
+
- **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
|
|
17
|
+
- **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on transient codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
|
|
18
|
+
- **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
|
|
19
|
+
- **Request Deduplication:** Automatically coalesce concurrent identical requests into a single network call (async only).
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
### Basic Usage (Defaults)
|
|
24
|
+
|
|
25
|
+
If you don't need custom configurations, you can instantiate the decorator with its defaults by passing an empty config object.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import requests
|
|
29
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
30
|
+
|
|
31
|
+
# Create it with default settings
|
|
32
|
+
config = ResilientConfig()
|
|
33
|
+
|
|
34
|
+
@resilient_api(config)
|
|
35
|
+
def get_user_data(user_id: str):
|
|
36
|
+
res = requests.get(f"https://api.example.com/users/{user_id}")
|
|
37
|
+
res.raise_for_status() # Always raise so the decorator knows it failed!
|
|
38
|
+
return res.json()
|
|
39
|
+
|
|
40
|
+
# Standard usage
|
|
41
|
+
try:
|
|
42
|
+
data = get_user_data("123")
|
|
43
|
+
print(data)
|
|
44
|
+
except Exception as e:
|
|
45
|
+
print("Request failed completely:", e)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**Default Settings provided automatically:**
|
|
49
|
+
- **Retries**: 3 attempts
|
|
50
|
+
- **Backoff Base Delay**: 0.1 seconds (100 milliseconds)
|
|
51
|
+
- **Circuit Failure Threshold**: Trips after 3 consecutive failures
|
|
52
|
+
- **Circuit Cooldown**: Stays open for 10 seconds before probing
|
|
53
|
+
- **Status Codes to Retry**: `429`, `500`, `502`, `503`, and `504`
|
|
54
|
+
|
|
55
|
+
### Advanced Usage (Custom Settings)
|
|
56
|
+
|
|
57
|
+
You can override any of the defaults to suit your application's needs, such as adding a fallback object.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
61
|
+
from smooth_api.config import BackoffConfig, CircuitBreakerConfig
|
|
62
|
+
import requests
|
|
63
|
+
|
|
64
|
+
config = ResilientConfig(
|
|
65
|
+
backoff=BackoffConfig(
|
|
66
|
+
base_delay=0.1, # seconds to wait before first retry
|
|
67
|
+
max_delay=30.0, # cap on exponential growth
|
|
68
|
+
max_retries=3 # max number of retry attempts
|
|
69
|
+
),
|
|
70
|
+
circuit_breaker=CircuitBreakerConfig(
|
|
71
|
+
failure_threshold=3, # trip OPEN after 3 consecutive failures
|
|
72
|
+
cooldown_ms=10_000 # stay OPEN for 10 seconds before probing
|
|
73
|
+
),
|
|
74
|
+
# Optional: return this exact object when the circuit is OPEN
|
|
75
|
+
fallback={"status": "degraded", "data": []},
|
|
76
|
+
# Optional: HTTP status codes to trigger a retry
|
|
77
|
+
retry_on=[429, 500, 502, 503, 504]
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
@resilient_api(config)
|
|
81
|
+
def get_user_data(user_id: str):
|
|
82
|
+
res = requests.get(f"https://api.example.com/users/{user_id}")
|
|
83
|
+
res.raise_for_status()
|
|
84
|
+
return res.json()
|
|
85
|
+
|
|
86
|
+
# You can also override the fallback at runtime per-call:
|
|
87
|
+
data = get_user_data("456", fallback={"status": "override"})
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Client Error Handling & Warnings
|
|
91
|
+
|
|
92
|
+
By default, non-retryable client errors (e.g. `400`, `401`, `403`, `404`, `405`) bubble up and raise exceptions immediately. If you want to intercept these client errors:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
96
|
+
|
|
97
|
+
def my_callback(status: int, message: str):
|
|
98
|
+
print(f"Error hook: Received client error {status}")
|
|
99
|
+
|
|
100
|
+
config = ResilientConfig(
|
|
101
|
+
fallback_on_non_retryable=True,
|
|
102
|
+
# Optional: Custom error hook function
|
|
103
|
+
on_non_retryable_error=my_callback,
|
|
104
|
+
# Optional: Fallback returned on non-retryable errors
|
|
105
|
+
fallback={"status": "error", "message": "Not Found"}
|
|
106
|
+
)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
* **Default Warning**: If `fallback_on_non_retryable` is `True` and no custom `on_non_retryable_error` is defined, it will write a warning message to `sys.stderr`.
|
|
110
|
+
* **Graceful Return**: If no `fallback` is configured, it returns a mock `Response` wrapper with `status_code`, `.json()` returning `{"error": True, "status": status, "message": "..."}`, and `.ok` returning `False`. Code downstream can check `res.status_code` or call `res.json()` without raising exceptions.
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Async Support
|
|
114
|
+
|
|
115
|
+
The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
import httpx
|
|
119
|
+
|
|
120
|
+
@resilient_api(config)
|
|
121
|
+
async def get_user_data_async(user_id: str):
|
|
122
|
+
async with httpx.AsyncClient() as client:
|
|
123
|
+
res = await client.get(f"https://api.example.com/users/{user_id}")
|
|
124
|
+
res.raise_for_status()
|
|
125
|
+
return res.json()
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Request Deduplication (Async Only)
|
|
129
|
+
|
|
130
|
+
When multiple identical async requests are made concurrently, SmoothAPI can execute only one network call and share the result with all callers. This reduces unnecessary load on downstream services.
|
|
131
|
+
|
|
132
|
+
**Enable with default key function** (deduplicates by positional args):
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
import httpx
|
|
136
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
137
|
+
from smooth_api.config import DeduplicationConfig
|
|
138
|
+
|
|
139
|
+
config = ResilientConfig(deduplication=DeduplicationConfig())
|
|
140
|
+
|
|
141
|
+
@resilient_api(config)
|
|
142
|
+
async def get_user(user_id: int):
|
|
143
|
+
async with httpx.AsyncClient() as client:
|
|
144
|
+
res = await client.get(f"https://api.example.com/users/{user_id}")
|
|
145
|
+
res.raise_for_status()
|
|
146
|
+
return res.json()
|
|
147
|
+
|
|
148
|
+
# All three calls share a single network request
|
|
149
|
+
import asyncio
|
|
150
|
+
results = await asyncio.gather(
|
|
151
|
+
get_user(1),
|
|
152
|
+
get_user(1),
|
|
153
|
+
get_user(1),
|
|
154
|
+
)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
**Custom key function** for advanced coalescing:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from smooth_api.config import DeduplicationConfig
|
|
161
|
+
|
|
162
|
+
def my_key(*args, **kwargs):
|
|
163
|
+
# Deduplicate by second argument (resource type)
|
|
164
|
+
return str(args[1]) if len(args) > 1 else str(args[0])
|
|
165
|
+
|
|
166
|
+
config = ResilientConfig(deduplication=DeduplicationConfig(key_fn=my_key))
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**Opt out of deduplication** for specific calls:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
config = ResilientConfig(
|
|
173
|
+
deduplication=DeduplicationConfig(
|
|
174
|
+
key_fn=lambda *a, **k: None # Return None to skip dedup
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
* **Default Behavior**: Deduplicates by joining positional args with `:`. E.g., `get_user(1)` produces key `"1"`.
|
|
180
|
+
* **Error Propagation**: If the coroutine raises an exception, all waiting callers receive the same exception.
|
|
181
|
+
* **Settlement**: Once a call completes, the next call with the same key triggers a fresh execution.
|
|
182
|
+
* **Sync Functions**: Deduplication only works with async-decorated functions. Sync functions are unaffected.
|
|
183
|
+
|
|
184
|
+
## How It Works
|
|
185
|
+
|
|
186
|
+
1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
|
|
187
|
+
2. **Circuit Check:** Before execution, the breaker checks the state. If it's `OPEN`, the request is blocked instantly (returning your fallback, or raising `RuntimeError`).
|
|
188
|
+
3. **Execution & Retries:** If an exception is raised, it attempts to extract the HTTP status code (supports `requests` and `httpx`). If the status is in `retry_on`, it's counted as a failure and the thread sleeps with backoff.
|
|
189
|
+
4. **Recovery:** After `cooldown_ms`, the breaker enters `HALF_OPEN`. The next execution acts as a probe. If it succeeds, the circuit closes. If it fails, it snaps back to `OPEN` immediately.
|
|
190
|
+
|
|
191
|
+
## License
|
|
192
|
+
|
|
193
|
+
MIT
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import functools
|
|
5
|
+
from urllib.parse import urlparse
|
|
6
|
+
|
|
7
|
+
from .config import ResilientConfig
|
|
8
|
+
from .dedup import RequestDeduplicator
|
|
9
|
+
from .state import CircuitBreakerState
|
|
10
|
+
from .utils import calculate_backoff, sleep_backoff
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from requests.exceptions import HTTPError as RequestsHTTPError
|
|
14
|
+
except ImportError:
|
|
15
|
+
RequestsHTTPError = None # type: ignore[assignment,misc]
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
from httpx import HTTPStatusError as HttpxHTTPStatusError
|
|
19
|
+
except ImportError:
|
|
20
|
+
HttpxHTTPStatusError = None # type: ignore[assignment,misc]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _get_status_code(err: Exception) -> int | None:
|
|
24
|
+
if RequestsHTTPError and isinstance(err, RequestsHTTPError):
|
|
25
|
+
return err.response.status_code
|
|
26
|
+
if HttpxHTTPStatusError and isinstance(err, HttpxHTTPStatusError):
|
|
27
|
+
return err.response.status_code
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MockResponse:
|
|
32
|
+
def __init__(self, status_code: int, content: dict, reason: str = ""):
|
|
33
|
+
self.status_code = status_code
|
|
34
|
+
self._content = content
|
|
35
|
+
self.reason = reason
|
|
36
|
+
self.reason_phrase = reason
|
|
37
|
+
|
|
38
|
+
def json(self) -> dict:
|
|
39
|
+
return self._content
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def text(self) -> str:
|
|
43
|
+
import json
|
|
44
|
+
return json.dumps(self._content)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def ok(self) -> bool:
|
|
48
|
+
return self.status_code < 400
|
|
49
|
+
|
|
50
|
+
def raise_for_status(self) -> None:
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def resilient_api(config: ResilientConfig):
|
|
55
|
+
def decorator(fn):
|
|
56
|
+
# One breaker per decorated function, shared across all calls to fn.
|
|
57
|
+
breaker = CircuitBreakerState(config.circuit_breaker)
|
|
58
|
+
|
|
59
|
+
# fn.__qualname__ is the circuit key. Each decorated function gets its
|
|
60
|
+
# own domain entry in the breaker map, isolated from all others.
|
|
61
|
+
domain = fn.__qualname__
|
|
62
|
+
|
|
63
|
+
# One deduplicator per decorated function (None when feature is off).
|
|
64
|
+
deduplicator = (
|
|
65
|
+
RequestDeduplicator(config.deduplication.key_fn)
|
|
66
|
+
if config.deduplication is not None
|
|
67
|
+
else None
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
if asyncio.iscoroutinefunction(fn):
|
|
71
|
+
@functools.wraps(fn)
|
|
72
|
+
async def wrapper(*args, **kwargs):
|
|
73
|
+
# Runtime fallback overrides the config-level fallback.
|
|
74
|
+
fallback = kwargs.pop('fallback', config.fallback)
|
|
75
|
+
|
|
76
|
+
if not breaker.can_request(domain):
|
|
77
|
+
if fallback is not None:
|
|
78
|
+
return fallback
|
|
79
|
+
raise RuntimeError(f'Circuit breaker is OPEN for: {domain}')
|
|
80
|
+
|
|
81
|
+
# Inner coroutine that contains the retry+breaker logic.
|
|
82
|
+
# Extracted so the deduplicator can decide whether to run it
|
|
83
|
+
# or attach to an already-running Future.
|
|
84
|
+
async def _execute():
|
|
85
|
+
last_err: Exception | None = None
|
|
86
|
+
|
|
87
|
+
for attempt in range(config.backoff.max_retries + 1):
|
|
88
|
+
try:
|
|
89
|
+
result = await fn(*args, **kwargs)
|
|
90
|
+
breaker.record_success(domain)
|
|
91
|
+
return result
|
|
92
|
+
except asyncio.CancelledError:
|
|
93
|
+
# CancelledError is a BaseException (Python 3.8+) and
|
|
94
|
+
# escapes `except Exception`. We still need to record
|
|
95
|
+
# the failure so sustained cancellation (e.g. client
|
|
96
|
+
# timeouts) is counted toward tripping the circuit,
|
|
97
|
+
# then re-raise so the cancellation propagates normally.
|
|
98
|
+
breaker.record_failure(domain)
|
|
99
|
+
raise
|
|
100
|
+
except Exception as err:
|
|
101
|
+
status = _get_status_code(err)
|
|
102
|
+
# Non-retryable HTTP errors (e.g. 400, 401, 404) bubble up immediately.
|
|
103
|
+
if status is not None and status not in config.retry_on:
|
|
104
|
+
if config.fallback_on_non_retryable:
|
|
105
|
+
import sys
|
|
106
|
+
reason = getattr(err.response, 'reason', getattr(err.response, 'reason_phrase', ''))
|
|
107
|
+
message = f"Non-retryable HTTP error: {status} {reason}".strip()
|
|
108
|
+
if config.on_non_retryable_error:
|
|
109
|
+
config.on_non_retryable_error(status, message)
|
|
110
|
+
else:
|
|
111
|
+
sys.stderr.write(f"{message}\n")
|
|
112
|
+
|
|
113
|
+
breaker.record_success(domain)
|
|
114
|
+
if fallback is not None:
|
|
115
|
+
return fallback
|
|
116
|
+
return MockResponse(
|
|
117
|
+
status_code=status,
|
|
118
|
+
content={"error": True, "status": status, "message": message},
|
|
119
|
+
reason=reason
|
|
120
|
+
)
|
|
121
|
+
raise
|
|
122
|
+
breaker.record_failure(domain)
|
|
123
|
+
last_err = err
|
|
124
|
+
if attempt < config.backoff.max_retries:
|
|
125
|
+
await asyncio.sleep(calculate_backoff(attempt, config.backoff))
|
|
126
|
+
continue
|
|
127
|
+
|
|
128
|
+
# If retries are exhausted and it's an HTTP error, return the response instead of raising
|
|
129
|
+
if status is not None and hasattr(err, 'response'):
|
|
130
|
+
return err.response
|
|
131
|
+
|
|
132
|
+
raise last_err # type: ignore[misc]
|
|
133
|
+
|
|
134
|
+
if deduplicator is not None:
|
|
135
|
+
return await deduplicator.execute(_execute, args, kwargs)
|
|
136
|
+
|
|
137
|
+
return await _execute()
|
|
138
|
+
|
|
139
|
+
return wrapper
|
|
140
|
+
|
|
141
|
+
else:
|
|
142
|
+
@functools.wraps(fn)
|
|
143
|
+
def wrapper(*args, **kwargs): # type: ignore[misc]
|
|
144
|
+
fallback = kwargs.pop('fallback', config.fallback)
|
|
145
|
+
|
|
146
|
+
if not breaker.can_request(domain):
|
|
147
|
+
if fallback is not None:
|
|
148
|
+
return fallback
|
|
149
|
+
raise RuntimeError(f'Circuit breaker is OPEN for: {domain}')
|
|
150
|
+
|
|
151
|
+
last_err: Exception | None = None
|
|
152
|
+
|
|
153
|
+
for attempt in range(config.backoff.max_retries + 1):
|
|
154
|
+
try:
|
|
155
|
+
result = fn(*args, **kwargs)
|
|
156
|
+
breaker.record_success(domain)
|
|
157
|
+
return result
|
|
158
|
+
except Exception as err:
|
|
159
|
+
status = _get_status_code(err)
|
|
160
|
+
if status is not None and status not in config.retry_on:
|
|
161
|
+
if config.fallback_on_non_retryable:
|
|
162
|
+
import sys
|
|
163
|
+
reason = getattr(err.response, 'reason', getattr(err.response, 'reason_phrase', ''))
|
|
164
|
+
message = f"Non-retryable HTTP error: {status} {reason}".strip()
|
|
165
|
+
if config.on_non_retryable_error:
|
|
166
|
+
config.on_non_retryable_error(status, message)
|
|
167
|
+
else:
|
|
168
|
+
sys.stderr.write(f"{message}\n")
|
|
169
|
+
|
|
170
|
+
breaker.record_success(domain)
|
|
171
|
+
if fallback is not None:
|
|
172
|
+
return fallback
|
|
173
|
+
return MockResponse(
|
|
174
|
+
status_code=status,
|
|
175
|
+
content={"error": True, "status": status, "message": message},
|
|
176
|
+
reason=reason
|
|
177
|
+
)
|
|
178
|
+
raise
|
|
179
|
+
breaker.record_failure(domain)
|
|
180
|
+
last_err = err
|
|
181
|
+
if attempt < config.backoff.max_retries:
|
|
182
|
+
sleep_backoff(calculate_backoff(attempt, config.backoff))
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
if status is not None and hasattr(err, 'response'):
|
|
186
|
+
return err.response
|
|
187
|
+
|
|
188
|
+
raise last_err # type: ignore[misc]
|
|
189
|
+
|
|
190
|
+
return wrapper
|
|
191
|
+
|
|
192
|
+
return decorator
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
__all__ = ['resilient_api', 'ResilientConfig', 'DeduplicationConfig']
|
|
196
|
+
|
|
197
|
+
from .config import DeduplicationConfig # re-export for convenience
|