smoothapi-py 1.2.1__tar.gz → 1.3.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,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: smoothapi-py
3
- Version: 1.2.1
3
+ Version: 1.3.0
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)
@@ -202,6 +205,7 @@ config = SmoothConfig(
202
205
  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`).
203
206
  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.
204
207
  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.
208
+ 5. **Memory Management:** The circuit breaker cache is capped at 1,000 domains. When exceeded, `CLOSED` circuits with zero failures are swept to prevent memory leaks in dynamic environments.
205
209
 
206
210
  ## License
207
211
 
@@ -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)
@@ -187,6 +190,7 @@ config = SmoothConfig(
187
190
  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
191
  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
192
  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.
193
+ 5. **Memory Management:** The circuit breaker cache is capped at 1,000 domains. When exceeded, `CLOSED` circuits with zero failures are swept to prevent memory leaks in dynamic environments.
190
194
 
191
195
  ## License
192
196
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "smoothapi-py"
7
- version = "1.2.1"
7
+ version = "1.3.0"
8
8
  description = "API protection library — exponential backoff and circuit breaker"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -86,7 +86,10 @@ def smooth_api(config: SmoothConfig):
86
86
 
87
87
  for attempt in range(config.backoff.max_retries + 1):
88
88
  try:
89
- result = await fn(*args, **kwargs)
89
+ if config.timeout_ms:
90
+ result = await asyncio.wait_for(fn(*args, **kwargs), timeout=config.timeout_ms / 1000.0)
91
+ else:
92
+ result = await fn(*args, **kwargs)
90
93
  breaker.record_success(domain)
91
94
  return result
92
95
  except asyncio.CancelledError:
@@ -143,6 +146,9 @@ def smooth_api(config: SmoothConfig):
143
146
  import warnings
144
147
  # Sync deduplication requires a thread-safe lock manager, which is currently unsupported
145
148
  warnings.warn("Synchronous deduplication is not supported. Deduplication will be ignored for this function.", UserWarning, stacklevel=2)
149
+
150
+ if config.timeout_ms is not None:
151
+ raise NotImplementedError("timeout_ms is not supported for synchronous decorators. Please use your HTTP client's native timeout support.")
146
152
 
147
153
  @functools.wraps(fn)
148
154
  def wrapper(*args, **kwargs): # type: ignore[misc]
@@ -197,6 +203,8 @@ def smooth_api(config: SmoothConfig):
197
203
  return decorator
198
204
 
199
205
 
206
+ __all__ = ['smooth_api', 'SmoothConfig', 'DeduplicationConfig', 'resilient_api', 'ResilientConfig']
207
+
200
208
  import warnings
201
209
 
202
210
  def resilient_api(*args, **kwargs):
@@ -208,6 +216,4 @@ class ResilientConfig(SmoothConfig):
208
216
  warnings.warn("'ResilientConfig' is deprecated, use 'SmoothConfig' instead", DeprecationWarning, stacklevel=2)
209
217
  super().__init__(*args, **kwargs)
210
218
 
211
- __all__ = ['smooth_api', 'SmoothConfig', 'DeduplicationConfig', 'resilient_api', 'ResilientConfig']
212
-
213
219
  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
@@ -25,6 +25,7 @@ class CircuitBreakerState:
25
25
  # No lock needed here
26
26
  def _get_or_create(self, domain: str) -> CircuitEntry:
27
27
  if domain not in self._map:
28
+ self._cleanup()
28
29
  self._map[domain] = CircuitEntry(
29
30
  state='CLOSED',
30
31
  failure_count=0,
@@ -32,6 +33,17 @@ class CircuitBreakerState:
32
33
  )
33
34
  return self._map[domain]
34
35
 
36
+ def _cleanup(self) -> None:
37
+ # Enforce a strict domain limit to bound memory usage
38
+ if len(self._map) <= 1000:
39
+ return
40
+ keys_to_delete = [
41
+ k for k, v in self._map.items()
42
+ if v.state == 'CLOSED' and v.failure_count == 0
43
+ ]
44
+ for k in keys_to_delete:
45
+ del self._map[k]
46
+
35
47
  def can_request(self, domain: str) -> bool:
36
48
  with self._lock:
37
49
  entry = self._get_or_create(domain)
@@ -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"
Binary file
File without changes
File without changes