smoothapi-py 1.3.3__tar.gz → 1.5.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.
Files changed (28) hide show
  1. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/.gitignore +48 -41
  2. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/PKG-INFO +86 -7
  3. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/README.md +85 -6
  4. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/pyproject.toml +11 -1
  5. smoothapi_py-1.5.0/smooth_api/__init__.py +534 -0
  6. smoothapi_py-1.5.0/smooth_api/config.py +193 -0
  7. smoothapi_py-1.5.0/smooth_api/state.py +240 -0
  8. smoothapi_py-1.5.0/tests/test_deprecation.py +32 -0
  9. smoothapi_py-1.5.0/tests/test_enhanced_circuit_breaker.py +237 -0
  10. smoothapi_py-1.5.0/tests/test_hooks.py +446 -0
  11. smoothapi_py-1.3.3/smooth_api/__init__.py +0 -243
  12. smoothapi_py-1.3.3/smooth_api/config.py +0 -58
  13. smoothapi_py-1.3.3/smooth_api/state.py +0 -79
  14. smoothapi_py-1.3.3/tests/test_deprecation.py +0 -12
  15. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/CHANGELOG.md +0 -0
  16. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/LICENSE +0 -0
  17. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/smooth_api/dedup.py +0 -0
  18. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/smooth_api/utils.py +0 -0
  19. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/conftest.py +0 -0
  20. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_backoff.py +0 -0
  21. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_concurrency.py +0 -0
  22. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_deduplication.py +0 -0
  23. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_edge_cases.py +0 -0
  24. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_exceptions.py +0 -0
  25. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_isolation.py +0 -0
  26. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_mock_response.py +0 -0
  27. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_resilience.py +0 -0
  28. {smoothapi_py-1.3.3 → smoothapi_py-1.5.0}/tests/test_timeout.py +0 -0
@@ -1,41 +1,48 @@
1
- # ─── Node.js ───────────────────────────────────────────────
2
- node_modules/
3
- dist/
4
- dist-test/
5
- *.js.map
6
- .env
7
- .env.local
8
- npm-debug.log*
9
- yarn-error.log*
10
- package-lock.json
11
-
12
- # ─── TypeScript ────────────────────────────────────────────
13
- *.tsbuildinfo
14
-
15
- # ─── Python ────────────────────────────────────────────────
16
- __pycache__/
17
- *.py[cod]
18
- *$py.class
19
- *.pyc
20
- *.pyo
21
- *.pyd
22
- .venv/
23
- venv/
24
- env/
25
- .pytest_cache/
26
- .mypy_cache/
27
- *.egg-info/
28
- dist/
29
- build/
30
- *.egg
31
- MANIFEST
32
- .python-version
33
-
34
- # ─── OS / Editor ───────────────────────────────────────────
35
- .DS_Store
36
- Thumbs.db
37
- .vscode/
38
- .idea/
39
- *.swp
40
- *.swo
41
- .agent
1
+ # ─── Node.js ───────────────────────────────────────────────
2
+ node_modules/
3
+ dist/
4
+ dist-test/
5
+ *.js.map
6
+ *.node
7
+ .env
8
+ .env.local
9
+ npm-debug.log*
10
+ yarn-error.log*
11
+ package-lock.json
12
+
13
+ # ─── TypeScript ────────────────────────────────────────────
14
+ *.tsbuildinfo
15
+
16
+ # ─── Python ────────────────────────────────────────────────
17
+ __pycache__/
18
+ *.py[cod]
19
+ *$py.class
20
+ *.pyc
21
+ *.pyo
22
+ *.pyd
23
+ .venv/
24
+ venv/
25
+ env/
26
+ .ruff_cache
27
+ .pytest_cache/
28
+ .mypy_cache/
29
+ *.egg-info/
30
+ dist/
31
+ build/
32
+ *.egg
33
+ MANIFEST
34
+ .python-version
35
+
36
+ # ─── OS / Editor ───────────────────────────────────────────
37
+ .DS_Store
38
+ Thumbs.db
39
+ .vscode/
40
+ .idea/
41
+ *.swp
42
+ *.swo
43
+ .agent
44
+
45
+ # ─── Rust ──────────────────────────────────────────────────
46
+ **/target/
47
+ **/*.rs.bk
48
+ Cargo.lock.back
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: smoothapi-py
3
- Version: 1.3.3
3
+ Version: 1.5.0
4
4
  Summary: API protection library — exponential backoff and circuit breaker
5
5
  Project-URL: Homepage, https://smoothapi.org
6
6
  Project-URL: Issues, https://github.com/AryanSharma48/smoothAPI/issues
@@ -131,21 +131,59 @@ config = SmoothConfig(
131
131
  * **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.
132
132
 
133
133
 
134
- ### Async Support
134
+ ### Async Support (httpx)
135
135
 
136
- The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
136
+ When building high-concurrency or non-blocking applications (such as FastAPI, Starlette, or `asyncio` workflows), blocking the main thread with synchronous HTTP libraries like `requests` degrades throughput. SmoothAPI natively supports asynchronous requests using [`httpx`](https://www.python-httpx.org/).
137
+
138
+ The `@smooth_api` decorator automatically detects coroutine functions (`async def`), executes non-blocking `asyncio.sleep` during backoff retry intervals, and enables async-only features such as [Request Deduplication](#request-deduplication-async-only) and `timeout_ms`.
139
+
140
+ #### Copy-Pasteable Example with `httpx.AsyncClient`
137
141
 
138
142
  ```python
143
+ import asyncio
139
144
  import httpx
145
+ from smooth_api import smooth_api, SmoothConfig
146
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
147
+
148
+ # 1. Configure SmoothAPI
149
+ config = SmoothConfig(
150
+ backoff=BackoffConfig(
151
+ base_delay=0.1, # seconds before first retry
152
+ max_delay=5.0, # max backoff delay cap
153
+ max_retries=3 # retry up to 3 times
154
+ ),
155
+ circuit_breaker=CircuitBreakerConfig(
156
+ failure_threshold=3, # trip OPEN after 3 consecutive failures
157
+ cooldown_ms=10_000 # stay OPEN for 10 seconds before probing
158
+ ),
159
+ retry_on=[429, 500, 502, 503, 504],
160
+ timeout_ms=5000 # Abort if a request attempt hangs longer than 5000ms (Async Only)
161
+ )
140
162
 
163
+ # 2. Decorate your async function
141
164
  @smooth_api(config)
142
- async def get_user_data_async(user_id: str):
165
+ async def get_user_data_async(client: httpx.AsyncClient, user_id: str):
166
+ res = await client.get(f"https://api.example.com/users/{user_id}")
167
+ res.raise_for_status() # Always raise so SmoothAPI detects HTTP error codes
168
+ return res.json()
169
+
170
+ # 3. Execute and properly await in an async context
171
+ async def main():
143
172
  async with httpx.AsyncClient() as client:
144
- res = await client.get(f"https://api.example.com/users/{user_id}")
145
- res.raise_for_status()
146
- return res.json()
173
+ try:
174
+ data = await get_user_data_async(client, "123")
175
+ print("Successfully retrieved data:", data)
176
+ except Exception as e:
177
+ print("Request failed after all retries or circuit opened:", e)
178
+
179
+ if __name__ == "__main__":
180
+ asyncio.run(main())
147
181
  ```
148
182
 
183
+ **When to use Async vs. Sync:**
184
+ * **Use Async (`httpx.AsyncClient`)**: In async web frameworks (FastAPI, aiohttp, Starlette), microservices handling high I/O concurrency, or when using request deduplication or request timeouts (`timeout_ms`).
185
+ * **Use Sync (`requests`)**: In synchronous scripts, CLI tools, worker tasks (e.g. Celery sync workers), or simple linear pipelines without an active `asyncio` event loop.
186
+
149
187
  ### Request Deduplication (Async Only)
150
188
 
151
189
  When multiple identical async requests are made concurrently, SmoothAPI can execute only one network call and share the result with all callers. This reduces unnecessary load on downstream services.
@@ -202,6 +240,47 @@ config = SmoothConfig(
202
240
  * **Settlement**: Once a call completes, the next call with the same key triggers a fresh execution.
203
241
  * **Sync Functions**: Deduplication only works with async-decorated functions. Sync functions are unaffected.
204
242
 
243
+ ### Lifecycle Event Hooks
244
+
245
+ SmoothAPI supports lifecycle event hooks to easily attach logging, metrics, alerting, or telemetry:
246
+
247
+ * **`on_success`**: Invoked on successful execution (HTTP status < 400). Receives a `SuccessContext` with `url`, `domain`, `attempts`, `duration_ms` (and `.duration` in seconds), `status`, and `response`.
248
+ * **`on_failure`**: Invoked on terminal failures (HTTP 4xx/5xx, exhausted retries, or when circuit is `OPEN`). Receives a `FailureContext` with `url`, `domain`, `attempts`, `duration_ms`, `error`, `status`, `response`, and `is_circuit_open`.
249
+ * **`on_retry`**: Invoked before sleeping on a retryable failure. Receives a `RetryContext` with attempt number, maximum retries, calculated delay (`delay` in seconds, `delay_ms` in milliseconds), HTTP status code (if available), error exception (if available), url, and function domain.
250
+ * **`on_circuit_state_change`**: Invoked whenever the circuit breaker transitions between states (`CLOSED`, `OPEN`, `HALF_OPEN`). Receives a `CircuitStateChangeEvent` with `domain`, `from_state`, `to_state`, and `failure_count`.
251
+
252
+ ```python
253
+ from smooth_api import (
254
+ smooth_api,
255
+ SmoothConfig,
256
+ RetryContext,
257
+ CircuitStateChangeEvent,
258
+ SuccessContext,
259
+ FailureContext,
260
+ )
261
+
262
+ def log_success(ctx: SuccessContext):
263
+ print(f"[Success] {ctx.domain} completed in {ctx.duration_ms:.1f}ms ({ctx.attempts} attempts)")
264
+
265
+ def log_failure(ctx: FailureContext):
266
+ print(f"[Failure] {ctx.domain} failed after {ctx.attempts} attempts. Circuit open: {ctx.is_circuit_open}")
267
+
268
+ def log_retry(ctx: RetryContext):
269
+ print(f"[Retry] Attempt {ctx.attempt}/{ctx.max_retries} for {ctx.domain} (status: {ctx.status}). Retrying in {ctx.delay_ms:.0f}ms")
270
+
271
+ def log_circuit_transition(event: CircuitStateChangeEvent):
272
+ print(f"[Circuit] {event.domain}: {event.from_state} -> {event.to_state} (failures: {event.failure_count})")
273
+
274
+ config = SmoothConfig(
275
+ on_success=log_success,
276
+ on_failure=log_failure,
277
+ on_retry=log_retry,
278
+ on_circuit_state_change=log_circuit_transition,
279
+ )
280
+ ```
281
+
282
+ Both synchronous functions and `async def` coroutines are supported as hooks (supporting both `snake_case` and `camelCase` aliases). All hooks execute with built-in fail-safe protection, ensuring that any exceptions raised inside user-defined callback functions never crash your request pipeline.
283
+
205
284
  ## How It Works
206
285
 
207
286
  1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
@@ -113,21 +113,59 @@ config = SmoothConfig(
113
113
  * **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.
114
114
 
115
115
 
116
- ### Async Support
116
+ ### Async Support (httpx)
117
117
 
118
- The decorator automatically detects if your function is a coroutine and uses `asyncio.sleep` instead of blocking the thread:
118
+ When building high-concurrency or non-blocking applications (such as FastAPI, Starlette, or `asyncio` workflows), blocking the main thread with synchronous HTTP libraries like `requests` degrades throughput. SmoothAPI natively supports asynchronous requests using [`httpx`](https://www.python-httpx.org/).
119
+
120
+ The `@smooth_api` decorator automatically detects coroutine functions (`async def`), executes non-blocking `asyncio.sleep` during backoff retry intervals, and enables async-only features such as [Request Deduplication](#request-deduplication-async-only) and `timeout_ms`.
121
+
122
+ #### Copy-Pasteable Example with `httpx.AsyncClient`
119
123
 
120
124
  ```python
125
+ import asyncio
121
126
  import httpx
127
+ from smooth_api import smooth_api, SmoothConfig
128
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
129
+
130
+ # 1. Configure SmoothAPI
131
+ config = SmoothConfig(
132
+ backoff=BackoffConfig(
133
+ base_delay=0.1, # seconds before first retry
134
+ max_delay=5.0, # max backoff delay cap
135
+ max_retries=3 # retry up to 3 times
136
+ ),
137
+ circuit_breaker=CircuitBreakerConfig(
138
+ failure_threshold=3, # trip OPEN after 3 consecutive failures
139
+ cooldown_ms=10_000 # stay OPEN for 10 seconds before probing
140
+ ),
141
+ retry_on=[429, 500, 502, 503, 504],
142
+ timeout_ms=5000 # Abort if a request attempt hangs longer than 5000ms (Async Only)
143
+ )
122
144
 
145
+ # 2. Decorate your async function
123
146
  @smooth_api(config)
124
- async def get_user_data_async(user_id: str):
147
+ async def get_user_data_async(client: httpx.AsyncClient, user_id: str):
148
+ res = await client.get(f"https://api.example.com/users/{user_id}")
149
+ res.raise_for_status() # Always raise so SmoothAPI detects HTTP error codes
150
+ return res.json()
151
+
152
+ # 3. Execute and properly await in an async context
153
+ async def main():
125
154
  async with httpx.AsyncClient() as client:
126
- res = await client.get(f"https://api.example.com/users/{user_id}")
127
- res.raise_for_status()
128
- return res.json()
155
+ try:
156
+ data = await get_user_data_async(client, "123")
157
+ print("Successfully retrieved data:", data)
158
+ except Exception as e:
159
+ print("Request failed after all retries or circuit opened:", e)
160
+
161
+ if __name__ == "__main__":
162
+ asyncio.run(main())
129
163
  ```
130
164
 
165
+ **When to use Async vs. Sync:**
166
+ * **Use Async (`httpx.AsyncClient`)**: In async web frameworks (FastAPI, aiohttp, Starlette), microservices handling high I/O concurrency, or when using request deduplication or request timeouts (`timeout_ms`).
167
+ * **Use Sync (`requests`)**: In synchronous scripts, CLI tools, worker tasks (e.g. Celery sync workers), or simple linear pipelines without an active `asyncio` event loop.
168
+
131
169
  ### Request Deduplication (Async Only)
132
170
 
133
171
  When multiple identical async requests are made concurrently, SmoothAPI can execute only one network call and share the result with all callers. This reduces unnecessary load on downstream services.
@@ -184,6 +222,47 @@ config = SmoothConfig(
184
222
  * **Settlement**: Once a call completes, the next call with the same key triggers a fresh execution.
185
223
  * **Sync Functions**: Deduplication only works with async-decorated functions. Sync functions are unaffected.
186
224
 
225
+ ### Lifecycle Event Hooks
226
+
227
+ SmoothAPI supports lifecycle event hooks to easily attach logging, metrics, alerting, or telemetry:
228
+
229
+ * **`on_success`**: Invoked on successful execution (HTTP status < 400). Receives a `SuccessContext` with `url`, `domain`, `attempts`, `duration_ms` (and `.duration` in seconds), `status`, and `response`.
230
+ * **`on_failure`**: Invoked on terminal failures (HTTP 4xx/5xx, exhausted retries, or when circuit is `OPEN`). Receives a `FailureContext` with `url`, `domain`, `attempts`, `duration_ms`, `error`, `status`, `response`, and `is_circuit_open`.
231
+ * **`on_retry`**: Invoked before sleeping on a retryable failure. Receives a `RetryContext` with attempt number, maximum retries, calculated delay (`delay` in seconds, `delay_ms` in milliseconds), HTTP status code (if available), error exception (if available), url, and function domain.
232
+ * **`on_circuit_state_change`**: Invoked whenever the circuit breaker transitions between states (`CLOSED`, `OPEN`, `HALF_OPEN`). Receives a `CircuitStateChangeEvent` with `domain`, `from_state`, `to_state`, and `failure_count`.
233
+
234
+ ```python
235
+ from smooth_api import (
236
+ smooth_api,
237
+ SmoothConfig,
238
+ RetryContext,
239
+ CircuitStateChangeEvent,
240
+ SuccessContext,
241
+ FailureContext,
242
+ )
243
+
244
+ def log_success(ctx: SuccessContext):
245
+ print(f"[Success] {ctx.domain} completed in {ctx.duration_ms:.1f}ms ({ctx.attempts} attempts)")
246
+
247
+ def log_failure(ctx: FailureContext):
248
+ print(f"[Failure] {ctx.domain} failed after {ctx.attempts} attempts. Circuit open: {ctx.is_circuit_open}")
249
+
250
+ def log_retry(ctx: RetryContext):
251
+ print(f"[Retry] Attempt {ctx.attempt}/{ctx.max_retries} for {ctx.domain} (status: {ctx.status}). Retrying in {ctx.delay_ms:.0f}ms")
252
+
253
+ def log_circuit_transition(event: CircuitStateChangeEvent):
254
+ print(f"[Circuit] {event.domain}: {event.from_state} -> {event.to_state} (failures: {event.failure_count})")
255
+
256
+ config = SmoothConfig(
257
+ on_success=log_success,
258
+ on_failure=log_failure,
259
+ on_retry=log_retry,
260
+ on_circuit_state_change=log_circuit_transition,
261
+ )
262
+ ```
263
+
264
+ Both synchronous functions and `async def` coroutines are supported as hooks (supporting both `snake_case` and `camelCase` aliases). All hooks execute with built-in fail-safe protection, ensuring that any exceptions raised inside user-defined callback functions never crash your request pipeline.
265
+
187
266
  ## How It Works
188
267
 
189
268
  1. **Isolation:** The circuit breaker state is isolated per decorated function (`fn.__qualname__`).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "smoothapi-py"
7
- version = "1.3.3"
7
+ version = "1.5.0"
8
8
  description = "API protection library — exponential backoff and circuit breaker"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -27,3 +27,13 @@ dev = [
27
27
 
28
28
  [tool.hatch.build.targets.wheel]
29
29
  packages = ["smooth_api"]
30
+
31
+ [tool.ruff]
32
+ line-length = 100
33
+
34
+ [tool.ruff.lint]
35
+ select = ["E", "F", "B"]
36
+ ignore = ["E501", "B008", "E402"]
37
+
38
+ [tool.ruff.lint.per-file-ignores]
39
+ "tests/*" = ["F401", "F841"]