smoothapi-py 1.2.2__tar.gz → 1.3.1__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.2.2 → smoothapi_py-1.3.1}/PKG-INFO +6 -3
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/README.md +4 -1
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/pyproject.toml +1 -1
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/smooth_api/__init__.py +35 -5
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/smooth_api/config.py +2 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/tests/test_resilience.py +83 -0
- smoothapi_py-1.3.1/tests/test_timeout.py +33 -0
- smoothapi_py-1.2.2/out.txt +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/.gitignore +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/LICENSE +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/smooth_api/dedup.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/smooth_api/state.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/smooth_api/utils.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/tests/conftest.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/tests/test_concurrency.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/tests/test_deduplication.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/tests/test_exceptions.py +0 -0
- {smoothapi_py-1.2.2 → smoothapi_py-1.3.1}/tests/test_isolation.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: smoothapi-py
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.1
|
|
4
4
|
Summary: API protection library — exponential backoff and circuit breaker
|
|
5
5
|
License: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -32,6 +32,7 @@ pip install smoothapi-py
|
|
|
32
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
34
|
- **Request Deduplication:** Automatically merges concurrent identical requests into a single network call (async only).
|
|
35
|
+
- **Request Timeouts:** Configurable timeouts to automatically abort requests that hang indefinitely (async only).
|
|
35
36
|
|
|
36
37
|
## Usage
|
|
37
38
|
|
|
@@ -89,7 +90,9 @@ config = SmoothConfig(
|
|
|
89
90
|
# Optional: return this exact object when the circuit is OPEN
|
|
90
91
|
fallback={"status": "degraded", "data": []},
|
|
91
92
|
# Optional: HTTP status codes to trigger a retry
|
|
92
|
-
retry_on=[429, 500, 502, 503, 504]
|
|
93
|
+
retry_on=[429, 500, 502, 503, 504],
|
|
94
|
+
# Optional: Abort a request attempt if it takes longer than 5000ms (Async Only)
|
|
95
|
+
timeout_ms=5000
|
|
93
96
|
)
|
|
94
97
|
|
|
95
98
|
@smooth_api(config)
|
|
@@ -17,6 +17,7 @@ pip install smoothapi-py
|
|
|
17
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
18
|
- **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
|
|
19
19
|
- **Request Deduplication:** Automatically merges concurrent identical requests into a single network call (async only).
|
|
20
|
+
- **Request Timeouts:** Configurable timeouts to automatically abort requests that hang indefinitely (async only).
|
|
20
21
|
|
|
21
22
|
## Usage
|
|
22
23
|
|
|
@@ -74,7 +75,9 @@ config = SmoothConfig(
|
|
|
74
75
|
# Optional: return this exact object when the circuit is OPEN
|
|
75
76
|
fallback={"status": "degraded", "data": []},
|
|
76
77
|
# Optional: HTTP status codes to trigger a retry
|
|
77
|
-
retry_on=[429, 500, 502, 503, 504]
|
|
78
|
+
retry_on=[429, 500, 502, 503, 504],
|
|
79
|
+
# Optional: Abort a request attempt if it takes longer than 5000ms (Async Only)
|
|
80
|
+
timeout_ms=5000
|
|
78
81
|
)
|
|
79
82
|
|
|
80
83
|
@smooth_api(config)
|
|
@@ -28,6 +28,20 @@ def _get_status_code(err: Exception) -> int | None:
|
|
|
28
28
|
return None
|
|
29
29
|
|
|
30
30
|
|
|
31
|
+
def _get_retry_after_delay(err: Exception) -> float | None:
|
|
32
|
+
if hasattr(err, "response") and err.response is not None:
|
|
33
|
+
if hasattr(err.response, "headers"):
|
|
34
|
+
retry_after = err.response.headers.get("Retry-After")
|
|
35
|
+
if retry_after is not None:
|
|
36
|
+
try:
|
|
37
|
+
delay = float(retry_after)
|
|
38
|
+
if delay > 0:
|
|
39
|
+
return delay
|
|
40
|
+
except ValueError:
|
|
41
|
+
pass
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
31
45
|
class MockResponse:
|
|
32
46
|
def __init__(self, status_code: int, content: dict, reason: str = ""):
|
|
33
47
|
self.status_code = status_code
|
|
@@ -86,7 +100,10 @@ def smooth_api(config: SmoothConfig):
|
|
|
86
100
|
|
|
87
101
|
for attempt in range(config.backoff.max_retries + 1):
|
|
88
102
|
try:
|
|
89
|
-
|
|
103
|
+
if config.timeout_ms is not None:
|
|
104
|
+
result = await asyncio.wait_for(fn(*args, **kwargs), timeout=config.timeout_ms / 1000.0)
|
|
105
|
+
else:
|
|
106
|
+
result = await fn(*args, **kwargs)
|
|
90
107
|
breaker.record_success(domain)
|
|
91
108
|
return result
|
|
92
109
|
except asyncio.CancelledError:
|
|
@@ -122,7 +139,12 @@ def smooth_api(config: SmoothConfig):
|
|
|
122
139
|
breaker.record_failure(domain)
|
|
123
140
|
last_err = err
|
|
124
141
|
if attempt < config.backoff.max_retries:
|
|
125
|
-
|
|
142
|
+
delay = calculate_backoff(attempt, config.backoff)
|
|
143
|
+
if status == 429:
|
|
144
|
+
retry_after_delay = _get_retry_after_delay(err)
|
|
145
|
+
if retry_after_delay is not None:
|
|
146
|
+
delay = retry_after_delay
|
|
147
|
+
await asyncio.sleep(delay)
|
|
126
148
|
continue
|
|
127
149
|
|
|
128
150
|
# If retries are exhausted and it's an HTTP error, return the response instead of raising
|
|
@@ -143,6 +165,9 @@ def smooth_api(config: SmoothConfig):
|
|
|
143
165
|
import warnings
|
|
144
166
|
# Sync deduplication requires a thread-safe lock manager, which is currently unsupported
|
|
145
167
|
warnings.warn("Synchronous deduplication is not supported. Deduplication will be ignored for this function.", UserWarning, stacklevel=2)
|
|
168
|
+
|
|
169
|
+
if config.timeout_ms is not None:
|
|
170
|
+
raise NotImplementedError("timeout_ms is not supported for synchronous decorators. Please use your HTTP client's native timeout support.")
|
|
146
171
|
|
|
147
172
|
@functools.wraps(fn)
|
|
148
173
|
def wrapper(*args, **kwargs): # type: ignore[misc]
|
|
@@ -184,7 +209,12 @@ def smooth_api(config: SmoothConfig):
|
|
|
184
209
|
breaker.record_failure(domain)
|
|
185
210
|
last_err = err
|
|
186
211
|
if attempt < config.backoff.max_retries:
|
|
187
|
-
|
|
212
|
+
delay = calculate_backoff(attempt, config.backoff)
|
|
213
|
+
if status == 429:
|
|
214
|
+
retry_after_delay = _get_retry_after_delay(err)
|
|
215
|
+
if retry_after_delay is not None:
|
|
216
|
+
delay = retry_after_delay
|
|
217
|
+
sleep_backoff(delay)
|
|
188
218
|
continue
|
|
189
219
|
|
|
190
220
|
if status is not None and hasattr(err, 'response'):
|
|
@@ -197,6 +227,8 @@ def smooth_api(config: SmoothConfig):
|
|
|
197
227
|
return decorator
|
|
198
228
|
|
|
199
229
|
|
|
230
|
+
__all__ = ['smooth_api', 'SmoothConfig', 'DeduplicationConfig', 'resilient_api', 'ResilientConfig']
|
|
231
|
+
|
|
200
232
|
import warnings
|
|
201
233
|
|
|
202
234
|
def resilient_api(*args, **kwargs):
|
|
@@ -208,6 +240,4 @@ class ResilientConfig(SmoothConfig):
|
|
|
208
240
|
warnings.warn("'ResilientConfig' is deprecated, use 'SmoothConfig' instead", DeprecationWarning, stacklevel=2)
|
|
209
241
|
super().__init__(*args, **kwargs)
|
|
210
242
|
|
|
211
|
-
__all__ = ['smooth_api', 'SmoothConfig', 'DeduplicationConfig', 'resilient_api', 'ResilientConfig']
|
|
212
|
-
|
|
213
243
|
from .config import DeduplicationConfig # re-export for convenience
|
|
@@ -54,3 +54,5 @@ class SmoothConfig:
|
|
|
54
54
|
on_non_retryable_error: Callable[[int, str], None] | None = None
|
|
55
55
|
# When set, enables request deduplication for async-decorated functions.
|
|
56
56
|
deduplication: Optional[DeduplicationConfig] = None
|
|
57
|
+
# Maximum duration in milliseconds before a request attempt is aborted.
|
|
58
|
+
timeout_ms: Optional[int] = None
|
|
@@ -70,6 +70,89 @@ def test_retry_respects_retry_on_codes():
|
|
|
70
70
|
assert call_count[0] >= 1
|
|
71
71
|
|
|
72
72
|
|
|
73
|
+
def test_retry_respects_retry_after_header_sync():
|
|
74
|
+
"""Retry-After header on 429 should override backoff calculation."""
|
|
75
|
+
config = SmoothConfig(
|
|
76
|
+
backoff=BackoffConfig(base_delay=10.0, max_delay=10.0, max_retries=1),
|
|
77
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
|
|
78
|
+
retry_on=[429],
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
call_count = [0]
|
|
82
|
+
|
|
83
|
+
class MockResponse:
|
|
84
|
+
status_code = 429
|
|
85
|
+
headers = {"Retry-After": "0.1"}
|
|
86
|
+
reason = "Too Many Requests"
|
|
87
|
+
|
|
88
|
+
class MockResponseSuccess:
|
|
89
|
+
status_code = 200
|
|
90
|
+
headers = {}
|
|
91
|
+
reason = "OK"
|
|
92
|
+
|
|
93
|
+
def json(self):
|
|
94
|
+
return {"success": True}
|
|
95
|
+
|
|
96
|
+
@smooth_api(config)
|
|
97
|
+
def get_data():
|
|
98
|
+
call_count[0] += 1
|
|
99
|
+
if call_count[0] == 1:
|
|
100
|
+
err = requests.exceptions.HTTPError("429")
|
|
101
|
+
err.response = MockResponse()
|
|
102
|
+
raise err
|
|
103
|
+
|
|
104
|
+
return MockResponseSuccess()
|
|
105
|
+
|
|
106
|
+
start_time = time.time()
|
|
107
|
+
get_data()
|
|
108
|
+
duration = time.time() - start_time
|
|
109
|
+
|
|
110
|
+
assert call_count[0] == 2
|
|
111
|
+
assert 0.1 <= duration < 5.0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@pytest.mark.asyncio
|
|
115
|
+
async def test_retry_respects_retry_after_header_async():
|
|
116
|
+
"""Retry-After header on 429 should override backoff calculation for async functions."""
|
|
117
|
+
config = SmoothConfig(
|
|
118
|
+
backoff=BackoffConfig(base_delay=10.0, max_delay=10.0, max_retries=1),
|
|
119
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
|
|
120
|
+
retry_on=[429],
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
call_count = [0]
|
|
124
|
+
|
|
125
|
+
class MockResponse:
|
|
126
|
+
status_code = 429
|
|
127
|
+
headers = {"Retry-After": "0.1"}
|
|
128
|
+
reason = "Too Many Requests"
|
|
129
|
+
|
|
130
|
+
class MockResponseSuccess:
|
|
131
|
+
status_code = 200
|
|
132
|
+
headers = {}
|
|
133
|
+
reason = "OK"
|
|
134
|
+
|
|
135
|
+
def json(self):
|
|
136
|
+
return {"success": True}
|
|
137
|
+
|
|
138
|
+
@smooth_api(config)
|
|
139
|
+
async def get_data_async():
|
|
140
|
+
call_count[0] += 1
|
|
141
|
+
if call_count[0] == 1:
|
|
142
|
+
err = requests.exceptions.HTTPError("429")
|
|
143
|
+
err.response = MockResponse()
|
|
144
|
+
raise err
|
|
145
|
+
|
|
146
|
+
return MockResponseSuccess()
|
|
147
|
+
|
|
148
|
+
start_time = time.time()
|
|
149
|
+
await get_data_async()
|
|
150
|
+
duration = time.time() - start_time
|
|
151
|
+
|
|
152
|
+
assert call_count[0] == 2
|
|
153
|
+
assert 0.1 <= duration < 5.0
|
|
154
|
+
|
|
155
|
+
|
|
73
156
|
# ─── Circuit breaker ──────────────────────────────────────────────────────────
|
|
74
157
|
|
|
75
158
|
def test_circuit_trips_and_returns_fallback():
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import pytest
|
|
3
|
+
from smooth_api import smooth_api, SmoothConfig
|
|
4
|
+
from smooth_api.config import BackoffConfig
|
|
5
|
+
|
|
6
|
+
@pytest.mark.asyncio
|
|
7
|
+
async def test_async_timeout_aborts_and_retries():
|
|
8
|
+
call_count = 0
|
|
9
|
+
|
|
10
|
+
@smooth_api(SmoothConfig(
|
|
11
|
+
timeout_ms=100,
|
|
12
|
+
backoff=BackoffConfig(max_retries=1, base_delay=0.01)
|
|
13
|
+
))
|
|
14
|
+
async def fetch_data():
|
|
15
|
+
nonlocal call_count
|
|
16
|
+
call_count += 1
|
|
17
|
+
if call_count == 1:
|
|
18
|
+
await asyncio.sleep(0.5) # Should timeout
|
|
19
|
+
return "delayed"
|
|
20
|
+
return "success"
|
|
21
|
+
|
|
22
|
+
result = await fetch_data()
|
|
23
|
+
assert result == "success"
|
|
24
|
+
assert call_count == 2
|
|
25
|
+
|
|
26
|
+
def test_sync_timeout_raises_not_implemented():
|
|
27
|
+
with pytest.raises(NotImplementedError, match="timeout_ms is not supported for synchronous decorators"):
|
|
28
|
+
@smooth_api(SmoothConfig(
|
|
29
|
+
timeout_ms=100,
|
|
30
|
+
backoff=BackoffConfig(max_retries=1, base_delay=0.01)
|
|
31
|
+
))
|
|
32
|
+
def fetch_data_sync():
|
|
33
|
+
return "success"
|
smoothapi_py-1.2.2/out.txt
DELETED
|
Binary file
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|