smoothapi-py 0.1.0__tar.gz → 1.0.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.
@@ -1,6 +1,7 @@
1
1
  # ─── Node.js ───────────────────────────────────────────────
2
2
  node_modules/
3
3
  dist/
4
+ dist-test/
4
5
  *.js.map
5
6
  .env
6
7
  .env.local
@@ -37,3 +38,4 @@ Thumbs.db
37
38
  .idea/
38
39
  *.swp
39
40
  *.swo
41
+ .agent
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: smoothapi-py
3
- Version: 0.1.0
3
+ Version: 1.0.0
4
4
  Summary: API resilience library — exponential backoff and circuit breaker
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -34,7 +34,41 @@ pip install smoothapi-py
34
34
 
35
35
  ## Usage
36
36
 
37
- Define your configuration once and apply the `@resilient_api` decorator to your functions:
37
+ ### Basic Usage (Defaults)
38
+
39
+ If you don't need custom configurations, you can instantiate the decorator with its defaults by passing an empty config object.
40
+
41
+ ```python
42
+ import requests
43
+ from smooth_api import resilient_api, ResilientConfig
44
+
45
+ # Create it with default settings
46
+ config = ResilientConfig()
47
+
48
+ @resilient_api(config)
49
+ def get_user_data(user_id: str):
50
+ res = requests.get(f"https://api.example.com/users/{user_id}")
51
+ res.raise_for_status() # Always raise so the decorator knows it failed!
52
+ return res.json()
53
+
54
+ # Standard usage
55
+ try:
56
+ data = get_user_data("123")
57
+ print(data)
58
+ except Exception as e:
59
+ print("Request failed completely:", e)
60
+ ```
61
+
62
+ **Default Settings provided automatically:**
63
+ - **Retries**: 3 attempts
64
+ - **Backoff Base Delay**: 0.1 seconds (100 milliseconds)
65
+ - **Circuit Failure Threshold**: Trips after 3 consecutive failures
66
+ - **Circuit Cooldown**: Stays open for 10 seconds before probing
67
+ - **Status Codes to Retry**: `429`, `500`, `502`, `503`, and `504`
68
+
69
+ ### Advanced Usage (Custom Settings)
70
+
71
+ You can override any of the defaults to suit your application's needs, such as adding a fallback object.
38
72
 
39
73
  ```python
40
74
  from smooth_api import resilient_api, ResilientConfig
@@ -63,17 +97,33 @@ def get_user_data(user_id: str):
63
97
  res.raise_for_status()
64
98
  return res.json()
65
99
 
66
- # Standard usage
67
- try:
68
- data = get_user_data("123")
69
- print(data)
70
- except Exception as e:
71
- print("Request failed completely:", e)
72
-
73
100
  # You can also override the fallback at runtime per-call:
74
101
  data = get_user_data("456", fallback={"status": "override"})
75
102
  ```
76
103
 
104
+ ### Client Error Handling & Warnings
105
+
106
+ 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
+ ```python
109
+ from smooth_api import resilient_api, ResilientConfig
110
+
111
+ def my_callback(status: int, message: str):
112
+ print(f"Error hook: Received client error {status}")
113
+
114
+ config = ResilientConfig(
115
+ fallback_on_non_retryable=True,
116
+ # Optional: Custom error hook function
117
+ on_non_retryable_error=my_callback,
118
+ # Optional: Fallback returned on non-retryable errors
119
+ fallback={"status": "error", "message": "Not Found"}
120
+ )
121
+ ```
122
+
123
+ * **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
+ * **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
+
77
127
  ### Async Support
78
128
 
79
129
  The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
@@ -19,7 +19,41 @@ pip install smoothapi-py
19
19
 
20
20
  ## Usage
21
21
 
22
- Define your configuration once and apply the `@resilient_api` decorator to your functions:
22
+ ### Basic Usage (Defaults)
23
+
24
+ If you don't need custom configurations, you can instantiate the decorator with its defaults by passing an empty config object.
25
+
26
+ ```python
27
+ import requests
28
+ from smooth_api import resilient_api, ResilientConfig
29
+
30
+ # Create it with default settings
31
+ config = ResilientConfig()
32
+
33
+ @resilient_api(config)
34
+ def get_user_data(user_id: str):
35
+ res = requests.get(f"https://api.example.com/users/{user_id}")
36
+ res.raise_for_status() # Always raise so the decorator knows it failed!
37
+ return res.json()
38
+
39
+ # Standard usage
40
+ try:
41
+ data = get_user_data("123")
42
+ print(data)
43
+ except Exception as e:
44
+ print("Request failed completely:", e)
45
+ ```
46
+
47
+ **Default Settings provided automatically:**
48
+ - **Retries**: 3 attempts
49
+ - **Backoff Base Delay**: 0.1 seconds (100 milliseconds)
50
+ - **Circuit Failure Threshold**: Trips after 3 consecutive failures
51
+ - **Circuit Cooldown**: Stays open for 10 seconds before probing
52
+ - **Status Codes to Retry**: `429`, `500`, `502`, `503`, and `504`
53
+
54
+ ### Advanced Usage (Custom Settings)
55
+
56
+ You can override any of the defaults to suit your application's needs, such as adding a fallback object.
23
57
 
24
58
  ```python
25
59
  from smooth_api import resilient_api, ResilientConfig
@@ -48,17 +82,33 @@ def get_user_data(user_id: str):
48
82
  res.raise_for_status()
49
83
  return res.json()
50
84
 
51
- # Standard usage
52
- try:
53
- data = get_user_data("123")
54
- print(data)
55
- except Exception as e:
56
- print("Request failed completely:", e)
57
-
58
85
  # You can also override the fallback at runtime per-call:
59
86
  data = get_user_data("456", fallback={"status": "override"})
60
87
  ```
61
88
 
89
+ ### Client Error Handling & Warnings
90
+
91
+ 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:
92
+
93
+ ```python
94
+ from smooth_api import resilient_api, ResilientConfig
95
+
96
+ def my_callback(status: int, message: str):
97
+ print(f"Error hook: Received client error {status}")
98
+
99
+ config = ResilientConfig(
100
+ fallback_on_non_retryable=True,
101
+ # Optional: Custom error hook function
102
+ on_non_retryable_error=my_callback,
103
+ # Optional: Fallback returned on non-retryable errors
104
+ fallback={"status": "error", "message": "Not Found"}
105
+ )
106
+ ```
107
+
108
+ * **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`.
109
+ * **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.
110
+ ```
111
+
62
112
  ### Async Support
63
113
 
64
114
  The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "smoothapi-py"
7
- version = "0.1.0"
7
+ version = "1.0.0"
8
8
  description = "API resilience library — exponential backoff and circuit breaker"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -27,6 +27,29 @@ def _get_status_code(err: Exception) -> int | None:
27
27
  return None
28
28
 
29
29
 
30
+ class MockResponse:
31
+ def __init__(self, status_code: int, content: dict, reason: str = ""):
32
+ self.status_code = status_code
33
+ self._content = content
34
+ self.reason = reason
35
+ self.reason_phrase = reason
36
+
37
+ def json(self) -> dict:
38
+ return self._content
39
+
40
+ @property
41
+ def text(self) -> str:
42
+ import json
43
+ return json.dumps(self._content)
44
+
45
+ @property
46
+ def ok(self) -> bool:
47
+ return self.status_code < 400
48
+
49
+ def raise_for_status(self) -> None:
50
+ pass
51
+
52
+
30
53
  def resilient_api(config: ResilientConfig):
31
54
  def decorator(fn):
32
55
  # One breaker per decorated function, shared across all calls to fn.
@@ -58,11 +81,33 @@ def resilient_api(config: ResilientConfig):
58
81
  status = _get_status_code(err)
59
82
  # Non-retryable HTTP errors (e.g. 400, 401, 404) bubble up immediately.
60
83
  if status is not None and status not in config.retry_on:
84
+ if config.fallback_on_non_retryable:
85
+ import sys
86
+ reason = getattr(err.response, 'reason', getattr(err.response, 'reason_phrase', ''))
87
+ message = f"Non-retryable HTTP error: {status} {reason}".strip()
88
+ if config.on_non_retryable_error:
89
+ config.on_non_retryable_error(status, message)
90
+ else:
91
+ sys.stderr.write(f"{message}\n")
92
+
93
+ breaker.record_success(domain)
94
+ if fallback is not None:
95
+ return fallback
96
+ return MockResponse(
97
+ status_code=status,
98
+ content={"error": True, "status": status, "message": message},
99
+ reason=reason
100
+ )
61
101
  raise
62
102
  breaker.record_failure(domain)
63
103
  last_err = err
64
104
  if attempt < config.backoff.max_retries:
65
105
  await asyncio.sleep(calculate_backoff(attempt, config.backoff))
106
+ continue
107
+
108
+ # If retries are exhausted and it's an HTTP error, return the response instead of raising
109
+ if status is not None and hasattr(err, 'response'):
110
+ return err.response
66
111
 
67
112
  raise last_err # type: ignore[misc]
68
113
 
@@ -88,11 +133,32 @@ def resilient_api(config: ResilientConfig):
88
133
  except Exception as err:
89
134
  status = _get_status_code(err)
90
135
  if status is not None and status not in config.retry_on:
136
+ if config.fallback_on_non_retryable:
137
+ import sys
138
+ reason = getattr(err.response, 'reason', getattr(err.response, 'reason_phrase', ''))
139
+ message = f"Non-retryable HTTP error: {status} {reason}".strip()
140
+ if config.on_non_retryable_error:
141
+ config.on_non_retryable_error(status, message)
142
+ else:
143
+ sys.stderr.write(f"{message}\n")
144
+
145
+ breaker.record_success(domain)
146
+ if fallback is not None:
147
+ return fallback
148
+ return MockResponse(
149
+ status_code=status,
150
+ content={"error": True, "status": status, "message": message},
151
+ reason=reason
152
+ )
91
153
  raise
92
154
  breaker.record_failure(domain)
93
155
  last_err = err
94
156
  if attempt < config.backoff.max_retries:
95
157
  sleep_backoff(calculate_backoff(attempt, config.backoff))
158
+ continue
159
+
160
+ if status is not None and hasattr(err, 'response'):
161
+ return err.response
96
162
 
97
163
  raise last_err # type: ignore[misc]
98
164
 
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass, field
4
- from typing import Any
4
+ from typing import Any, Callable
5
5
 
6
6
 
7
7
  @dataclass
@@ -25,3 +25,5 @@ class ResilientConfig:
25
25
  fallback: Any = None
26
26
  # HTTP status codes that trigger a retry. Mirrors DEFAULT_RETRY_ON in index.ts.
27
27
  retry_on: list[int] = field(default_factory=lambda: [429, 500, 502, 503, 504])
28
+ fallback_on_non_retryable: bool = False
29
+ on_non_retryable_error: Callable[[int, str], None] | None = None
@@ -0,0 +1,37 @@
1
+ import asyncio
2
+ import pytest
3
+ import httpx
4
+ from smooth_api import resilient_api, ResilientConfig
5
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
6
+
7
+ BASE = "http://localhost:3001"
8
+
9
+ @pytest.fixture(autouse=True)
10
+ def reset_counter():
11
+ import requests
12
+ requests.get(f"{BASE}/reset")
13
+ yield
14
+ requests.get(f"{BASE}/reset")
15
+
16
+ @pytest.mark.asyncio
17
+ async def test_async_wrapper_concurrency():
18
+ config = ResilientConfig(
19
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
20
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
21
+ retry_on=[500],
22
+ fallback={"tripped": True}
23
+ )
24
+
25
+ @resilient_api(config)
26
+ async def get_data():
27
+ request = httpx.Request("GET", f"{BASE}/unstable-data")
28
+ response = httpx.Response(500, request=request)
29
+ raise httpx.HTTPStatusError("error", request=request, response=response)
30
+
31
+ # Trip the circuit with 8 concurrent requests
32
+ tasks = [get_data() for _ in range(8)]
33
+ await asyncio.gather(*tasks, return_exceptions=True)
34
+
35
+ # Now the circuit should be open, so the next request should instantly return fallback
36
+ fallback = await get_data()
37
+ assert fallback == {"tripped": True}, "Circuit should have tripped under load and returned fallback"
@@ -0,0 +1,18 @@
1
+ import pytest
2
+ import requests
3
+ import httpx
4
+ from smooth_api import _get_status_code
5
+
6
+ def test_get_status_code_requests():
7
+ err = requests.exceptions.HTTPError(response=type('R', (), {'status_code': 502})())
8
+ assert _get_status_code(err) == 502
9
+
10
+ def test_get_status_code_httpx():
11
+ request = httpx.Request("GET", "http://localhost")
12
+ response = httpx.Response(503, request=request)
13
+ err = httpx.HTTPStatusError("error", request=request, response=response)
14
+ assert _get_status_code(err) == 503
15
+
16
+ def test_get_status_code_unrelated_exception():
17
+ err = ValueError("Something else")
18
+ assert _get_status_code(err) is None
@@ -0,0 +1,43 @@
1
+ import pytest
2
+ import requests
3
+ from smooth_api import resilient_api, ResilientConfig
4
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
5
+
6
+ BASE = "http://localhost:3001"
7
+
8
+ @pytest.fixture(autouse=True)
9
+ def reset_counter():
10
+ requests.get(f"{BASE}/reset")
11
+ yield
12
+ requests.get(f"{BASE}/reset")
13
+
14
+ def test_decorator_isolation_and_runtime_override():
15
+ config = ResilientConfig(
16
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
17
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=2, cooldown_ms=60_000),
18
+ retry_on=[500],
19
+ fallback={"default": True}
20
+ )
21
+
22
+ @resilient_api(config)
23
+ def api_one():
24
+ raise requests.exceptions.HTTPError(response=type('R', (), {'status_code': 500})())
25
+
26
+ @resilient_api(config)
27
+ def api_two():
28
+ return {"success": True}
29
+
30
+ # Trip api_one
31
+ for _ in range(5):
32
+ try:
33
+ api_one()
34
+ except requests.exceptions.HTTPError:
35
+ pass
36
+
37
+ # api_one should return fallback with override precedence
38
+ res_one = api_one(fallback={"override": True})
39
+ assert res_one == {"override": True}, "Runtime fallback override failed"
40
+
41
+ # api_two should not be tripped
42
+ res_two = api_two()
43
+ assert res_two == {"success": True}, "Decorator state leaked to other decorated functions"
@@ -93,8 +93,11 @@ def test_circuit_trips_and_returns_fallback():
93
93
 
94
94
  results = []
95
95
  for _ in range(5):
96
- result = get_data(fallback=fallback)
97
- results.append(result)
96
+ try:
97
+ result = get_data(fallback=fallback)
98
+ results.append(result)
99
+ except requests.exceptions.HTTPError:
100
+ results.append("ERROR")
98
101
 
99
102
  assert fallback in results, f"circuit should have returned fallback, got: {results}"
100
103
 
@@ -144,7 +147,10 @@ def test_circuit_recovers_after_cooldown():
144
147
 
145
148
  # Trip the circuit
146
149
  for _ in range(9):
147
- get_data(fallback={"tripped": True})
150
+ try:
151
+ get_data(fallback={"tripped": True})
152
+ except requests.exceptions.HTTPError:
153
+ pass
148
154
 
149
155
  # Wait for cooldown
150
156
  time.sleep((cooldown_ms / 1000) + 0.2)
@@ -155,3 +161,108 @@ def test_circuit_recovers_after_cooldown():
155
161
  # Probe should succeed and close the circuit
156
162
  result = get_data()
157
163
  assert result == {"success": True, "data": "Solid Data"}
164
+
165
+
166
+ # ─── Non-retryable error fallback & callbacks ──────────────────────────────────
167
+
168
+ def test_python_non_retryable_default_behavior():
169
+ config = ResilientConfig(fallback_on_non_retryable=False)
170
+
171
+ @resilient_api(config)
172
+ def get_data():
173
+ raise requests.exceptions.HTTPError(
174
+ response=type('R', (), {'status_code': 404, 'reason': 'Not Found'})()
175
+ )
176
+
177
+ with pytest.raises(requests.exceptions.HTTPError):
178
+ get_data()
179
+
180
+
181
+ def test_python_non_retryable_fallback_and_stderr(capsys):
182
+ config = ResilientConfig(fallback_on_non_retryable=True)
183
+
184
+ @resilient_api(config)
185
+ def get_data_sync():
186
+ raise requests.exceptions.HTTPError(
187
+ response=type('R', (), {'status_code': 405, 'reason': 'Method Not Allowed'})()
188
+ )
189
+
190
+ res = get_data_sync()
191
+
192
+ # Check return type and fields
193
+ assert res.status_code == 405
194
+ assert res.ok is False
195
+ assert res.reason == "Method Not Allowed"
196
+
197
+ data = res.json()
198
+ assert data["error"] is True
199
+ assert data["status"] == 405
200
+ assert "405 Method Not Allowed" in data["message"]
201
+
202
+ # Check stderr warning
203
+ captured = capsys.readouterr()
204
+ assert "405 Method Not Allowed" in captured.err
205
+
206
+
207
+ @pytest.mark.asyncio
208
+ async def test_python_non_retryable_async_fallback_and_stderr(capsys):
209
+ config = ResilientConfig(fallback_on_non_retryable=True)
210
+
211
+ @resilient_api(config)
212
+ async def get_data_async():
213
+ raise requests.exceptions.HTTPError(
214
+ response=type('R', (), {'status_code': 404, 'reason': 'Not Found'})()
215
+ )
216
+
217
+ res = await get_data_async()
218
+
219
+ assert res.status_code == 404
220
+ assert res.ok is False
221
+
222
+ data = res.json()
223
+ assert data["error"] is True
224
+ assert data["status"] == 404
225
+
226
+ captured = capsys.readouterr()
227
+ assert "404 Not Found" in captured.err
228
+
229
+
230
+ def test_python_non_retryable_custom_fallback():
231
+ fallback_val = {"custom": "python_fallback"}
232
+ config = ResilientConfig(fallback_on_non_retryable=True, fallback=fallback_val)
233
+
234
+ @resilient_api(config)
235
+ def get_data():
236
+ raise requests.exceptions.HTTPError(
237
+ response=type('R', (), {'status_code': 400, 'reason': 'Bad Request'})()
238
+ )
239
+
240
+ res = get_data()
241
+ assert res == fallback_val
242
+
243
+
244
+ def test_python_non_retryable_custom_callback(capsys):
245
+ called = []
246
+ def callback(status, msg):
247
+ called.append((status, msg))
248
+
249
+ config = ResilientConfig(
250
+ fallback_on_non_retryable=True,
251
+ on_non_retryable_error=callback
252
+ )
253
+
254
+ @resilient_api(config)
255
+ def get_data():
256
+ raise requests.exceptions.HTTPError(
257
+ response=type('R', (), {'status_code': 403, 'reason': 'Forbidden'})()
258
+ )
259
+
260
+ res = get_data()
261
+ assert res.status_code == 403
262
+ assert len(called) == 1
263
+ assert called[0][0] == 403
264
+ assert "403 Forbidden" in called[0][1]
265
+
266
+ # Stderr should be empty since callback was used
267
+ captured = capsys.readouterr()
268
+ assert captured.err == ""
File without changes