smoothapi-py 0.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.1.0/.gitignore +39 -0
- smoothapi_py-0.1.0/LICENSE +21 -0
- smoothapi_py-0.1.0/PKG-INFO +101 -0
- smoothapi_py-0.1.0/README.md +86 -0
- smoothapi_py-0.1.0/pyproject.toml +24 -0
- smoothapi_py-0.1.0/smooth_api/__init__.py +104 -0
- smoothapi_py-0.1.0/smooth_api/config.py +27 -0
- smoothapi_py-0.1.0/smooth_api/state.py +67 -0
- smoothapi_py-0.1.0/smooth_api/utils.py +13 -0
- smoothapi_py-0.1.0/tests/conftest.py +1 -0
- smoothapi_py-0.1.0/tests/test_resilience.py +157 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# ─── Node.js ───────────────────────────────────────────────
|
|
2
|
+
node_modules/
|
|
3
|
+
dist/
|
|
4
|
+
*.js.map
|
|
5
|
+
.env
|
|
6
|
+
.env.local
|
|
7
|
+
npm-debug.log*
|
|
8
|
+
yarn-error.log*
|
|
9
|
+
package-lock.json
|
|
10
|
+
|
|
11
|
+
# ─── TypeScript ────────────────────────────────────────────
|
|
12
|
+
*.tsbuildinfo
|
|
13
|
+
|
|
14
|
+
# ─── Python ────────────────────────────────────────────────
|
|
15
|
+
__pycache__/
|
|
16
|
+
*.py[cod]
|
|
17
|
+
*$py.class
|
|
18
|
+
*.pyc
|
|
19
|
+
*.pyo
|
|
20
|
+
*.pyd
|
|
21
|
+
.venv/
|
|
22
|
+
venv/
|
|
23
|
+
env/
|
|
24
|
+
.pytest_cache/
|
|
25
|
+
.mypy_cache/
|
|
26
|
+
*.egg-info/
|
|
27
|
+
dist/
|
|
28
|
+
build/
|
|
29
|
+
*.egg
|
|
30
|
+
MANIFEST
|
|
31
|
+
.python-version
|
|
32
|
+
|
|
33
|
+
# ─── OS / Editor ───────────────────────────────────────────
|
|
34
|
+
.DS_Store
|
|
35
|
+
Thumbs.db
|
|
36
|
+
.vscode/
|
|
37
|
+
.idea/
|
|
38
|
+
*.swp
|
|
39
|
+
*.swo
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aryan Sharma
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: smoothapi-py
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: API resilience library — exponential backoff and circuit breaker
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: backoff,circuit-breaker,http,resilience,retry
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Provides-Extra: dev
|
|
10
|
+
Requires-Dist: httpx>=0.24; extra == 'dev'
|
|
11
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
|
|
12
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
13
|
+
Requires-Dist: requests>=2.28; extra == 'dev'
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# smoothapi-py
|
|
17
|
+
|
|
18
|
+
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.
|
|
19
|
+
|
|
20
|
+
Zero dependencies. Fully typed. Supports both sync and async functions out of the box. Automatically integrates with `requests` and `httpx` if installed.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install smoothapi-py
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- **Exponential Backoff with Full Jitter:** Prevents the "thundering herd" problem by randomizing retry delays.
|
|
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 transient codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
|
|
33
|
+
- **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
Define your configuration once and apply the `@resilient_api` decorator to your functions:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
41
|
+
from smooth_api.config import BackoffConfig, CircuitBreakerConfig
|
|
42
|
+
import requests
|
|
43
|
+
|
|
44
|
+
config = ResilientConfig(
|
|
45
|
+
backoff=BackoffConfig(
|
|
46
|
+
base_delay=0.1, # seconds to wait before first retry
|
|
47
|
+
max_delay=30.0, # cap on exponential growth
|
|
48
|
+
max_retries=3 # max number of retry attempts
|
|
49
|
+
),
|
|
50
|
+
circuit_breaker=CircuitBreakerConfig(
|
|
51
|
+
failure_threshold=3, # trip OPEN after 3 consecutive failures
|
|
52
|
+
cooldown_ms=10_000 # stay OPEN for 10 seconds before probing
|
|
53
|
+
),
|
|
54
|
+
# Optional: return this exact object when the circuit is OPEN
|
|
55
|
+
fallback={"status": "degraded", "data": []},
|
|
56
|
+
# Optional: HTTP status codes to trigger a retry
|
|
57
|
+
retry_on=[429, 500, 502, 503, 504]
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
@resilient_api(config)
|
|
61
|
+
def get_user_data(user_id: str):
|
|
62
|
+
res = requests.get(f"https://api.example.com/users/{user_id}")
|
|
63
|
+
res.raise_for_status()
|
|
64
|
+
return res.json()
|
|
65
|
+
|
|
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
|
+
# You can also override the fallback at runtime per-call:
|
|
74
|
+
data = get_user_data("456", fallback={"status": "override"})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Async Support
|
|
78
|
+
|
|
79
|
+
The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
import httpx
|
|
83
|
+
|
|
84
|
+
@resilient_api(config)
|
|
85
|
+
async def get_user_data_async(user_id: str):
|
|
86
|
+
async with httpx.AsyncClient() as client:
|
|
87
|
+
res = await client.get(f"https://api.example.com/users/{user_id}")
|
|
88
|
+
res.raise_for_status()
|
|
89
|
+
return res.json()
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## How It Works
|
|
93
|
+
|
|
94
|
+
1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
|
|
95
|
+
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`).
|
|
96
|
+
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.
|
|
97
|
+
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.
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
MIT
|
|
@@ -0,0 +1,86 @@
|
|
|
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
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
Define your configuration once and apply the `@resilient_api` decorator to your functions:
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
26
|
+
from smooth_api.config import BackoffConfig, CircuitBreakerConfig
|
|
27
|
+
import requests
|
|
28
|
+
|
|
29
|
+
config = ResilientConfig(
|
|
30
|
+
backoff=BackoffConfig(
|
|
31
|
+
base_delay=0.1, # seconds to wait before first retry
|
|
32
|
+
max_delay=30.0, # cap on exponential growth
|
|
33
|
+
max_retries=3 # max number of retry attempts
|
|
34
|
+
),
|
|
35
|
+
circuit_breaker=CircuitBreakerConfig(
|
|
36
|
+
failure_threshold=3, # trip OPEN after 3 consecutive failures
|
|
37
|
+
cooldown_ms=10_000 # stay OPEN for 10 seconds before probing
|
|
38
|
+
),
|
|
39
|
+
# Optional: return this exact object when the circuit is OPEN
|
|
40
|
+
fallback={"status": "degraded", "data": []},
|
|
41
|
+
# Optional: HTTP status codes to trigger a retry
|
|
42
|
+
retry_on=[429, 500, 502, 503, 504]
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
@resilient_api(config)
|
|
46
|
+
def get_user_data(user_id: str):
|
|
47
|
+
res = requests.get(f"https://api.example.com/users/{user_id}")
|
|
48
|
+
res.raise_for_status()
|
|
49
|
+
return res.json()
|
|
50
|
+
|
|
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
|
+
# You can also override the fallback at runtime per-call:
|
|
59
|
+
data = get_user_data("456", fallback={"status": "override"})
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Async Support
|
|
63
|
+
|
|
64
|
+
The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
import httpx
|
|
68
|
+
|
|
69
|
+
@resilient_api(config)
|
|
70
|
+
async def get_user_data_async(user_id: str):
|
|
71
|
+
async with httpx.AsyncClient() as client:
|
|
72
|
+
res = await client.get(f"https://api.example.com/users/{user_id}")
|
|
73
|
+
res.raise_for_status()
|
|
74
|
+
return res.json()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## How It Works
|
|
78
|
+
|
|
79
|
+
1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
|
|
80
|
+
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`).
|
|
81
|
+
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.
|
|
82
|
+
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.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "smoothapi-py"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "API resilience 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"]
|
|
@@ -0,0 +1,104 @@
|
|
|
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 .state import CircuitBreakerState
|
|
9
|
+
from .utils import calculate_backoff, sleep_backoff
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from requests.exceptions import HTTPError as RequestsHTTPError
|
|
13
|
+
except ImportError:
|
|
14
|
+
RequestsHTTPError = None # type: ignore[assignment,misc]
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from httpx import HTTPStatusError as HttpxHTTPStatusError
|
|
18
|
+
except ImportError:
|
|
19
|
+
HttpxHTTPStatusError = None # type: ignore[assignment,misc]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _get_status_code(err: Exception) -> int | None:
|
|
23
|
+
if RequestsHTTPError and isinstance(err, RequestsHTTPError):
|
|
24
|
+
return err.response.status_code
|
|
25
|
+
if HttpxHTTPStatusError and isinstance(err, HttpxHTTPStatusError):
|
|
26
|
+
return err.response.status_code
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resilient_api(config: ResilientConfig):
|
|
31
|
+
def decorator(fn):
|
|
32
|
+
# One breaker per decorated function, shared across all calls to fn.
|
|
33
|
+
breaker = CircuitBreakerState(config.circuit_breaker)
|
|
34
|
+
|
|
35
|
+
# fn.__qualname__ is the circuit key. Each decorated function gets its
|
|
36
|
+
# own domain entry in the breaker map, isolated from all others.
|
|
37
|
+
domain = fn.__qualname__
|
|
38
|
+
|
|
39
|
+
if asyncio.iscoroutinefunction(fn):
|
|
40
|
+
@functools.wraps(fn)
|
|
41
|
+
async def wrapper(*args, **kwargs):
|
|
42
|
+
# Runtime fallback overrides the config-level fallback.
|
|
43
|
+
fallback = kwargs.pop('fallback', config.fallback)
|
|
44
|
+
|
|
45
|
+
if not breaker.can_request(domain):
|
|
46
|
+
if fallback is not None:
|
|
47
|
+
return fallback
|
|
48
|
+
raise RuntimeError(f'Circuit breaker is OPEN for: {domain}')
|
|
49
|
+
|
|
50
|
+
last_err: Exception | None = None
|
|
51
|
+
|
|
52
|
+
for attempt in range(config.backoff.max_retries + 1):
|
|
53
|
+
try:
|
|
54
|
+
result = await fn(*args, **kwargs)
|
|
55
|
+
breaker.record_success(domain)
|
|
56
|
+
return result
|
|
57
|
+
except Exception as err:
|
|
58
|
+
status = _get_status_code(err)
|
|
59
|
+
# Non-retryable HTTP errors (e.g. 400, 401, 404) bubble up immediately.
|
|
60
|
+
if status is not None and status not in config.retry_on:
|
|
61
|
+
raise
|
|
62
|
+
breaker.record_failure(domain)
|
|
63
|
+
last_err = err
|
|
64
|
+
if attempt < config.backoff.max_retries:
|
|
65
|
+
await asyncio.sleep(calculate_backoff(attempt, config.backoff))
|
|
66
|
+
|
|
67
|
+
raise last_err # type: ignore[misc]
|
|
68
|
+
|
|
69
|
+
return wrapper
|
|
70
|
+
|
|
71
|
+
else:
|
|
72
|
+
@functools.wraps(fn)
|
|
73
|
+
def wrapper(*args, **kwargs): # type: ignore[misc]
|
|
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
|
+
last_err: Exception | None = None
|
|
82
|
+
|
|
83
|
+
for attempt in range(config.backoff.max_retries + 1):
|
|
84
|
+
try:
|
|
85
|
+
result = fn(*args, **kwargs)
|
|
86
|
+
breaker.record_success(domain)
|
|
87
|
+
return result
|
|
88
|
+
except Exception as err:
|
|
89
|
+
status = _get_status_code(err)
|
|
90
|
+
if status is not None and status not in config.retry_on:
|
|
91
|
+
raise
|
|
92
|
+
breaker.record_failure(domain)
|
|
93
|
+
last_err = err
|
|
94
|
+
if attempt < config.backoff.max_retries:
|
|
95
|
+
sleep_backoff(calculate_backoff(attempt, config.backoff))
|
|
96
|
+
|
|
97
|
+
raise last_err # type: ignore[misc]
|
|
98
|
+
|
|
99
|
+
return wrapper
|
|
100
|
+
|
|
101
|
+
return decorator
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
__all__ = ['resilient_api', 'ResilientConfig']
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class BackoffConfig:
|
|
9
|
+
base_delay: float = 0.1 # seconds, doubles each attempt before jitter
|
|
10
|
+
max_delay: float = 30.0 # ceiling on the pre-jitter exponential
|
|
11
|
+
max_retries: int = 3
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class CircuitBreakerConfig:
|
|
16
|
+
failure_threshold: int = 3 # consecutive failures to trip OPEN
|
|
17
|
+
cooldown_ms: int = 10_000 # time in OPEN before probing with HALF_OPEN
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ResilientConfig:
|
|
22
|
+
backoff: BackoffConfig = field(default_factory=BackoffConfig)
|
|
23
|
+
circuit_breaker: CircuitBreakerConfig = field(default_factory=CircuitBreakerConfig)
|
|
24
|
+
# Returned immediately on an OPEN circuit, no network IO.
|
|
25
|
+
fallback: Any = None
|
|
26
|
+
# HTTP status codes that trigger a retry. Mirrors DEFAULT_RETRY_ON in index.ts.
|
|
27
|
+
retry_on: list[int] = field(default_factory=lambda: [429, 500, 502, 503, 504])
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from .config import CircuitBreakerConfig
|
|
9
|
+
|
|
10
|
+
CircuitState = Literal['CLOSED', 'OPEN', 'HALF_OPEN']
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class CircuitEntry:
|
|
15
|
+
state: CircuitState
|
|
16
|
+
failure_count: int
|
|
17
|
+
last_failure_time: float #epoch seconds (not ms)
|
|
18
|
+
|
|
19
|
+
class CircuitBreakerState:
|
|
20
|
+
def __init__(self, config: CircuitBreakerConfig | None = None):
|
|
21
|
+
self._config = config or CircuitBreakerConfig()
|
|
22
|
+
self._map: dict[str, CircuitEntry] = {}
|
|
23
|
+
self._lock = threading.Lock()
|
|
24
|
+
|
|
25
|
+
# No lock needed here
|
|
26
|
+
def _get_or_create(self, domain: str) -> CircuitEntry:
|
|
27
|
+
if domain not in self._map:
|
|
28
|
+
self._map[domain] = CircuitEntry(
|
|
29
|
+
state='CLOSED',
|
|
30
|
+
failure_count=0,
|
|
31
|
+
last_failure_time=0.0,
|
|
32
|
+
)
|
|
33
|
+
return self._map[domain]
|
|
34
|
+
|
|
35
|
+
def can_request(self, domain: str) -> bool:
|
|
36
|
+
with self._lock:
|
|
37
|
+
entry = self._get_or_create(domain)
|
|
38
|
+
if entry.state == 'CLOSED' or entry.state == 'HALF_OPEN':
|
|
39
|
+
return True
|
|
40
|
+
# cooldown_ms is in ms; time.time() is in seconds
|
|
41
|
+
elapsed = time.time() - entry.last_failure_time
|
|
42
|
+
if elapsed > self._config.cooldown_ms / 1000:
|
|
43
|
+
entry.state = 'HALF_OPEN'
|
|
44
|
+
return True
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
def record_success(self, domain: str) -> None:
|
|
48
|
+
with self._lock:
|
|
49
|
+
entry = self._get_or_create(domain)
|
|
50
|
+
entry.state = 'CLOSED'
|
|
51
|
+
entry.failure_count = 0
|
|
52
|
+
|
|
53
|
+
def record_failure(self, domain: str) -> None:
|
|
54
|
+
with self._lock:
|
|
55
|
+
entry = self._get_or_create(domain)
|
|
56
|
+
entry.failure_count += 1
|
|
57
|
+
if entry.state == 'HALF_OPEN':
|
|
58
|
+
entry.state = 'OPEN'
|
|
59
|
+
entry.last_failure_time = time.time()
|
|
60
|
+
return
|
|
61
|
+
if entry.failure_count >= self._config.failure_threshold:
|
|
62
|
+
entry.state = 'OPEN'
|
|
63
|
+
entry.last_failure_time = time.time()
|
|
64
|
+
|
|
65
|
+
def get_state(self, domain: str) -> CircuitState:
|
|
66
|
+
with self._lock:
|
|
67
|
+
return self._get_or_create(domain).state
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import random
|
|
3
|
+
|
|
4
|
+
def calculate_backoff(attempt: int, config) -> float:
|
|
5
|
+
exponential = config.base_delay * (2 ** attempt)
|
|
6
|
+
capped = min(config.max_delay, exponential)
|
|
7
|
+
return random.uniform(0, capped)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def sleep_backoff(seconds: float) -> None:
|
|
11
|
+
time.sleep(seconds)
|
|
12
|
+
|
|
13
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# pytest package marker
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Integration tests for smooth_api against the sandbox server on port 3001."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
from smooth_api import resilient_api, ResilientConfig
|
|
10
|
+
from smooth_api.config import BackoffConfig, CircuitBreakerConfig
|
|
11
|
+
|
|
12
|
+
BASE = "http://localhost:3001"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def reset():
|
|
16
|
+
"""Reset sandbox request counter between tests."""
|
|
17
|
+
requests.get(f"{BASE}/reset")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# ─── Fixtures ─────────────────────────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
@pytest.fixture(autouse=True)
|
|
23
|
+
def reset_counter():
|
|
24
|
+
reset()
|
|
25
|
+
yield
|
|
26
|
+
reset()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ─── Retry logic ──────────────────────────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
def test_retries_on_500_and_eventually_succeeds():
|
|
32
|
+
config = ResilientConfig(
|
|
33
|
+
backoff=BackoffConfig(base_delay=0.01, max_delay=0.1, max_retries=5),
|
|
34
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
@resilient_api(config)
|
|
38
|
+
def get_data():
|
|
39
|
+
res = requests.get(f"{BASE}/unstable-data")
|
|
40
|
+
res.raise_for_status()
|
|
41
|
+
return res.json()
|
|
42
|
+
|
|
43
|
+
result = get_data()
|
|
44
|
+
assert result == {"success": True, "data": "Solid Data"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_retry_respects_retry_on_codes():
|
|
48
|
+
"""429 and 500 trigger retries; 200 does not."""
|
|
49
|
+
config = ResilientConfig(
|
|
50
|
+
backoff=BackoffConfig(base_delay=0.01, max_delay=0.1, max_retries=3),
|
|
51
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
|
|
52
|
+
retry_on=[429, 500],
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
call_count = [0]
|
|
56
|
+
|
|
57
|
+
@resilient_api(config)
|
|
58
|
+
def get_data():
|
|
59
|
+
call_count[0] += 1
|
|
60
|
+
res = requests.get(f"{BASE}/unstable-data")
|
|
61
|
+
res.raise_for_status()
|
|
62
|
+
return res.json()
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
get_data()
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
# At least one retry happened (call_count > 1) or first call succeeded
|
|
70
|
+
assert call_count[0] >= 1
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# ─── Circuit breaker ──────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
def test_circuit_trips_and_returns_fallback():
|
|
76
|
+
fallback = {"data": "cached"}
|
|
77
|
+
config = ResilientConfig(
|
|
78
|
+
backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
|
|
79
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
|
|
80
|
+
retry_on=[500, 429],
|
|
81
|
+
fallback=fallback,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
call_count = [0]
|
|
85
|
+
|
|
86
|
+
@resilient_api(config)
|
|
87
|
+
def get_data():
|
|
88
|
+
call_count[0] += 1
|
|
89
|
+
# Always raise so failures accumulate without recordSuccess resetting the count.
|
|
90
|
+
raise requests.exceptions.HTTPError(
|
|
91
|
+
response=type('R', (), {'status_code': 500})()
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
results = []
|
|
95
|
+
for _ in range(5):
|
|
96
|
+
result = get_data(fallback=fallback)
|
|
97
|
+
results.append(result)
|
|
98
|
+
|
|
99
|
+
assert fallback in results, f"circuit should have returned fallback, got: {results}"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_circuit_open_raises_runtime_error_without_fallback():
|
|
103
|
+
config = ResilientConfig(
|
|
104
|
+
backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
|
|
105
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
|
|
106
|
+
retry_on=[500, 429],
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
@resilient_api(config)
|
|
110
|
+
def get_data():
|
|
111
|
+
# Always raises a 500 so recordSuccess never fires and count accumulates.
|
|
112
|
+
raise requests.exceptions.HTTPError(
|
|
113
|
+
response=type('R', (), {'status_code': 500})()
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# 3 calls trip the circuit (threshold=3, no successes to reset count)
|
|
117
|
+
for _ in range(3):
|
|
118
|
+
try:
|
|
119
|
+
get_data()
|
|
120
|
+
except Exception:
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
# Next call should raise RuntimeError (OPEN, no fallback)
|
|
124
|
+
with pytest.raises(RuntimeError, match="Circuit breaker is OPEN"):
|
|
125
|
+
get_data()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ─── Recovery ─────────────────────────────────────────────────────────────────
|
|
129
|
+
|
|
130
|
+
def test_circuit_recovers_after_cooldown():
|
|
131
|
+
cooldown_ms = 500
|
|
132
|
+
config = ResilientConfig(
|
|
133
|
+
backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
|
|
134
|
+
circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=cooldown_ms),
|
|
135
|
+
retry_on=[500, 429],
|
|
136
|
+
fallback={"tripped": True},
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
@resilient_api(config)
|
|
140
|
+
def get_data():
|
|
141
|
+
res = requests.get(f"{BASE}/unstable-data")
|
|
142
|
+
res.raise_for_status()
|
|
143
|
+
return res.json()
|
|
144
|
+
|
|
145
|
+
# Trip the circuit
|
|
146
|
+
for _ in range(9):
|
|
147
|
+
get_data(fallback={"tripped": True})
|
|
148
|
+
|
|
149
|
+
# Wait for cooldown
|
|
150
|
+
time.sleep((cooldown_ms / 1000) + 0.2)
|
|
151
|
+
|
|
152
|
+
# Reset sandbox so next request gets 200
|
|
153
|
+
reset()
|
|
154
|
+
|
|
155
|
+
# Probe should succeed and close the circuit
|
|
156
|
+
result = get_data()
|
|
157
|
+
assert result == {"success": True, "data": "Solid Data"}
|