clipwright/tests/test_no_blocking_http_in_async.py
pedro-bento 83ad1feaba
All checks were successful
CI / backend-tests (pull_request) Successful in 30s
CI / frontend-build (pull_request) Successful in 29s
refactor: move backend into the clipwright package
Restructure the 37 root-level Python modules into a proper package:
  clipwright/{core,api,pipeline,layouts,media,integrations,tools}

- Rewrite every local import (module-level and deferred) to absolute
  clipwright.<group>.<mod> form; no legacy root shims or re-exports.
- Add clipwright/core/paths.py and route fonts/assets/cookies through it.
- Entry points: uvicorn clipwright.api.app:app; jobs run as
  python -m clipwright.pipeline.main; probe as -m ...quality_probe.
- child_env() appends REPO_ROOT to PYTHONPATH so the -m workers work.
- transcribe_backends: sys.modules key now clipwright.media.scene_detection.
- Tooling: root pyproject.toml (pytest pythonpath=[.], ruff), shared
  requirements-test.txt, CI installs it, Docker PYTHONPATH=/app.
- Tests: all imports/fakes/source-scans repointed; new tests/test_package_layout.py
  enforces no root modules, docstring-only __init__, and no legacy imports.
- Docs/comments updated for the new layout.

Backend: 744 passed, 19 skipped. Frontend lint+build green.
2026-10-04 20:40:38 +01:00

51 lines
1.8 KiB
Python

"""A blocking HTTP call inside an ``async def`` handler freezes the whole
uvicorn event loop for as long as the request takes.
23-sep-2026: one endpoint uploaded a clip with a sync ``httpx.Client`` inline;
every request, /health included, stalled for 42 s and the uptime monitor paged
"clipwright-api down". Blocking clients are fine in a plain ``def`` called
through ``asyncio.to_thread``; this test only rejects them lexically inside a
coroutine body (nested sync ``def``s are skipped, since those are what gets
handed to the thread).
"""
import ast
from pathlib import Path
APP = Path(__file__).resolve().parents[1] / "clipwright" / "api" / "app.py"
def _is_blocking_call(node: ast.Call) -> bool:
f = node.func
if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name):
if f.value.id == "httpx" and f.attr == "Client":
return True
if f.value.id == "requests" and f.attr in {
"get", "post", "put", "patch", "delete", "head", "request",
}:
return True
return False
def _blocking_calls_in(fn: ast.AsyncFunctionDef):
stack = list(fn.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
continue
if isinstance(node, ast.Call) and _is_blocking_call(node):
yield node.lineno
stack.extend(ast.iter_child_nodes(node))
def test_no_blocking_http_client_inside_async_handlers():
tree = ast.parse(APP.read_text(encoding="utf-8"))
offenders = [
f"{fn.name}:{line}"
for fn in ast.walk(tree)
if isinstance(fn, ast.AsyncFunctionDef)
for line in _blocking_calls_in(fn)
]
assert not offenders, (
"blocking HTTP call inside async def (wrap it in asyncio.to_thread): "
+ ", ".join(sorted(offenders))
)