smoothapi-py 1.0.0__tar.gz → 1.2.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-1.0.0 → smoothapi_py-1.2.0}/PKG-INFO +72 -15
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/README.md +193 -136
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/pyproject.toml +24 -24
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/smooth_api/__init__.py +208 -170
- smoothapi_py-1.2.0/smooth_api/config.py +56 -0
- smoothapi_py-1.2.0/smooth_api/dedup.py +116 -0
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/tests/conftest.py +1 -1
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/tests/test_concurrency.py +37 -37
- smoothapi_py-1.2.0/tests/test_deduplication.py +209 -0
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/tests/test_exceptions.py +18 -18
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/tests/test_isolation.py +43 -43
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/tests/test_resilience.py +268 -268
- smoothapi_py-1.0.0/smooth_api/config.py +0 -29
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/.gitignore +0 -0
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/LICENSE +0 -0
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/smooth_api/state.py +0 -0
- {smoothapi_py-1.0.0 → smoothapi_py-1.2.0}/smooth_api/utils.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: smoothapi-py
|
|
3
|
-
Version: 1.
|
|
4
|
-
Summary: API
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: API protection library — exponential backoff and circuit breaker
|
|
5
5
|
License: MIT
|
|
6
6
|
License-File: LICENSE
|
|
7
7
|
Keywords: backoff,circuit-breaker,http,resilience,retry
|
|
@@ -15,7 +15,7 @@ Description-Content-Type: text/markdown
|
|
|
15
15
|
|
|
16
16
|
# smoothapi-py
|
|
17
17
|
|
|
18
|
-
API
|
|
18
|
+
API protection 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.
|
|
19
19
|
|
|
20
20
|
Zero dependencies. Fully typed. Supports both sync and async functions out of the box. Automatically integrates with `requests` and `httpx` if installed.
|
|
21
21
|
|
|
@@ -29,23 +29,24 @@ pip install smoothapi-py
|
|
|
29
29
|
|
|
30
30
|
- **Exponential Backoff with Full Jitter:** Prevents the "thundering herd" problem by randomizing retry delays.
|
|
31
31
|
- **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
|
|
32
|
-
- **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on
|
|
32
|
+
- **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on retryable 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 merges concurrent identical requests into a single network call (async only).
|
|
34
35
|
|
|
35
36
|
## Usage
|
|
36
37
|
|
|
37
38
|
### Basic Usage (Defaults)
|
|
38
39
|
|
|
39
|
-
If you don't need custom configurations, you can
|
|
40
|
+
If you don't need custom configurations, you can use the decorator with its defaults by passing an empty config object.
|
|
40
41
|
|
|
41
42
|
```python
|
|
42
43
|
import requests
|
|
43
|
-
from smooth_api import
|
|
44
|
+
from smooth_api import smooth_api, SmoothConfig
|
|
44
45
|
|
|
45
46
|
# Create it with default settings
|
|
46
|
-
config =
|
|
47
|
+
config = SmoothConfig()
|
|
47
48
|
|
|
48
|
-
@
|
|
49
|
+
@smooth_api(config)
|
|
49
50
|
def get_user_data(user_id: str):
|
|
50
51
|
res = requests.get(f"https://api.example.com/users/{user_id}")
|
|
51
52
|
res.raise_for_status() # Always raise so the decorator knows it failed!
|
|
@@ -71,11 +72,11 @@ except Exception as e:
|
|
|
71
72
|
You can override any of the defaults to suit your application's needs, such as adding a fallback object.
|
|
72
73
|
|
|
73
74
|
```python
|
|
74
|
-
from smooth_api import
|
|
75
|
+
from smooth_api import smooth_api, SmoothConfig
|
|
75
76
|
from smooth_api.config import BackoffConfig, CircuitBreakerConfig
|
|
76
77
|
import requests
|
|
77
78
|
|
|
78
|
-
config =
|
|
79
|
+
config = SmoothConfig(
|
|
79
80
|
backoff=BackoffConfig(
|
|
80
81
|
base_delay=0.1, # seconds to wait before first retry
|
|
81
82
|
max_delay=30.0, # cap on exponential growth
|
|
@@ -91,7 +92,7 @@ config = ResilientConfig(
|
|
|
91
92
|
retry_on=[429, 500, 502, 503, 504]
|
|
92
93
|
)
|
|
93
94
|
|
|
94
|
-
@
|
|
95
|
+
@smooth_api(config)
|
|
95
96
|
def get_user_data(user_id: str):
|
|
96
97
|
res = requests.get(f"https://api.example.com/users/{user_id}")
|
|
97
98
|
res.raise_for_status()
|
|
@@ -106,12 +107,12 @@ data = get_user_data("456", fallback={"status": "override"})
|
|
|
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:
|
|
107
108
|
|
|
108
109
|
```python
|
|
109
|
-
from smooth_api import
|
|
110
|
+
from smooth_api import smooth_api, SmoothConfig
|
|
110
111
|
|
|
111
112
|
def my_callback(status: int, message: str):
|
|
112
113
|
print(f"Error hook: Received client error {status}")
|
|
113
114
|
|
|
114
|
-
config =
|
|
115
|
+
config = SmoothConfig(
|
|
115
116
|
fallback_on_non_retryable=True,
|
|
116
117
|
# Optional: Custom error hook function
|
|
117
118
|
on_non_retryable_error=my_callback,
|
|
@@ -122,7 +123,7 @@ config = ResilientConfig(
|
|
|
122
123
|
|
|
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`.
|
|
124
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.
|
|
125
|
-
|
|
126
|
+
|
|
126
127
|
|
|
127
128
|
### Async Support
|
|
128
129
|
|
|
@@ -131,7 +132,7 @@ The decorator automatically detects if your function is a coroutine and uses `as
|
|
|
131
132
|
```python
|
|
132
133
|
import httpx
|
|
133
134
|
|
|
134
|
-
@
|
|
135
|
+
@smooth_api(config)
|
|
135
136
|
async def get_user_data_async(user_id: str):
|
|
136
137
|
async with httpx.AsyncClient() as client:
|
|
137
138
|
res = await client.get(f"https://api.example.com/users/{user_id}")
|
|
@@ -139,6 +140,62 @@ async def get_user_data_async(user_id: str):
|
|
|
139
140
|
return res.json()
|
|
140
141
|
```
|
|
141
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 smooth_api, SmoothConfig
|
|
152
|
+
from smooth_api.config import DeduplicationConfig
|
|
153
|
+
|
|
154
|
+
config = SmoothConfig(deduplication=DeduplicationConfig())
|
|
155
|
+
|
|
156
|
+
@smooth_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 = SmoothConfig(deduplication=DeduplicationConfig(key_fn=my_key))
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
**Opt out of deduplication** for specific calls:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
config = SmoothConfig(
|
|
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
|
+
|
|
142
199
|
## How It Works
|
|
143
200
|
|
|
144
201
|
1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
|
|
@@ -1,136 +1,193 @@
|
|
|
1
|
-
# smoothapi-py
|
|
2
|
-
|
|
3
|
-
API
|
|
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
|
|
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
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
res.
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
1
|
+
# smoothapi-py
|
|
2
|
+
|
|
3
|
+
API protection 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 retryable 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 merges 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 use the decorator with its defaults by passing an empty config object.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import requests
|
|
29
|
+
from smooth_api import smooth_api, SmoothConfig
|
|
30
|
+
|
|
31
|
+
# Create it with default settings
|
|
32
|
+
config = SmoothConfig()
|
|
33
|
+
|
|
34
|
+
@smooth_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 smooth_api, SmoothConfig
|
|
61
|
+
from smooth_api.config import BackoffConfig, CircuitBreakerConfig
|
|
62
|
+
import requests
|
|
63
|
+
|
|
64
|
+
config = SmoothConfig(
|
|
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
|
+
@smooth_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 smooth_api, SmoothConfig
|
|
96
|
+
|
|
97
|
+
def my_callback(status: int, message: str):
|
|
98
|
+
print(f"Error hook: Received client error {status}")
|
|
99
|
+
|
|
100
|
+
config = SmoothConfig(
|
|
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
|
+
@smooth_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 smooth_api, SmoothConfig
|
|
137
|
+
from smooth_api.config import DeduplicationConfig
|
|
138
|
+
|
|
139
|
+
config = SmoothConfig(deduplication=DeduplicationConfig())
|
|
140
|
+
|
|
141
|
+
@smooth_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 = SmoothConfig(deduplication=DeduplicationConfig(key_fn=my_key))
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**Opt out of deduplication** for specific calls:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
config = SmoothConfig(
|
|
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
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
[build-system]
|
|
2
|
-
requires = ["hatchling"]
|
|
3
|
-
build-backend = "hatchling.build"
|
|
4
|
-
|
|
5
|
-
[project]
|
|
6
|
-
name = "smoothapi-py"
|
|
7
|
-
version = "1.
|
|
8
|
-
description = "API
|
|
9
|
-
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.10"
|
|
11
|
-
license = { text = "MIT" }
|
|
12
|
-
keywords = ["resilience", "circuit-breaker", "retry", "backoff", "http"]
|
|
13
|
-
dependencies = []
|
|
14
|
-
|
|
15
|
-
[project.optional-dependencies]
|
|
16
|
-
dev = [
|
|
17
|
-
"pytest>=7.0",
|
|
18
|
-
"pytest-asyncio>=0.21",
|
|
19
|
-
"requests>=2.28",
|
|
20
|
-
"httpx>=0.24",
|
|
21
|
-
]
|
|
22
|
-
|
|
23
|
-
[tool.hatch.build.targets.wheel]
|
|
24
|
-
packages = ["smooth_api"]
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "smoothapi-py"
|
|
7
|
+
version = "1.2.0"
|
|
8
|
+
description = "API protection library — exponential backoff and circuit breaker"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
keywords = ["resilience", "circuit-breaker", "retry", "backoff", "http"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
dev = [
|
|
17
|
+
"pytest>=7.0",
|
|
18
|
+
"pytest-asyncio>=0.21",
|
|
19
|
+
"requests>=2.28",
|
|
20
|
+
"httpx>=0.24",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["smooth_api"]
|