smoothapi-py 0.1.0__py3-none-any.whl

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.
smooth_api/__init__.py ADDED
@@ -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']
smooth_api/config.py ADDED
@@ -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])
smooth_api/state.py ADDED
@@ -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
smooth_api/utils.py ADDED
@@ -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,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,8 @@
1
+ smooth_api/__init__.py,sha256=35ggfVHxfY46IeH8lo8P96aJNkr0_qLC7IomrrWBegI,3948
2
+ smooth_api/config.py,sha256=wGyuIrnh87wo1p3aHqrb3cbCGlTKWPHCCjtTM9SfcEU,943
3
+ smooth_api/state.py,sha256=ixEHZMoAqAUarsDHNCUORnWnoV06SEyOjQj4MasT9nY,2216
4
+ smooth_api/utils.py,sha256=YGWIo9KeVqG0vKFIjNUtAN0vLKkvLDrFvv9XCZk-_hk,303
5
+ smoothapi_py-0.1.0.dist-info/METADATA,sha256=P9dm3HD2jKTGlcot7KK4ZXHNlS8jDSe1LGMDtUGWsUM,3986
6
+ smoothapi_py-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
7
+ smoothapi_py-0.1.0.dist-info/licenses/LICENSE,sha256=6L4G6l0x9e_BQEo0502xkxGFGTDb2jHPS4PYm9eiM9Q,1088
8
+ smoothapi_py-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.