From 497de58a1f6ff84a2290d4379297704a7da53e8e Mon Sep 17 00:00:00 2001 From: victorcavero14 Date: Thu, 24 Sep 2026 00:37:02 +0200 Subject: [PATCH] fix(api): upload to Upload-Post off the event loop /api/social/post and the AI Shorts post sent the clip with a sync httpx.Client inside an async handler, so the whole API froze for the length of the upload. 23-sep-2026 19:47:48 UTC: one TikTok+YouTube post stalled every request, /health included, for 42 s and the uptime monitor paged "openshorts-api down" for 2 min. Both uploads (and the actor image fetch in saasshorts_generate) now run through asyncio.to_thread; an AST test rejects blocking httpx/requests calls inside async defs in app.py. Co-Authored-By: Claude Opus 5.5 --- app.py | 63 ++++++++++++++----------- tests/test_no_blocking_http_in_async.py | 51 ++++++++++++++++++++ 2 files changed, 86 insertions(+), 28 deletions(-) create mode 100644 tests/test_no_blocking_http_in_async.py diff --git a/app.py b/app.py index 346ef8a..e7a4f9a 100644 --- a/app.py +++ b/app.py @@ -5148,6 +5148,16 @@ class SocialPostRequest(BaseModel): import httpx + +def _post_video_blocking(url, headers, data, file_path, filename, timeout): + """Multipart POST of a video to Upload-Post. Blocking: call it through + asyncio.to_thread from a request handler, never inline.""" + with open(file_path, "rb") as f: + files = {"video": (filename, f.read(), "video/mp4")} + with httpx.Client(timeout=timeout) as client: + return client.post(url, headers=headers, data=data, files=files) + + @app.post("/api/social/post") async def post_to_socials(req: SocialPostRequest, request: Request): await _ensure_job_files(req.job_id, request) @@ -5219,21 +5229,16 @@ async def post_to_socials(req: SocialPostRequest, request: Request): data_payload["youtube_description"] = final_description data_payload["privacyStatus"] = "public" - # Send File - # httpx AsyncClient requires async file reading or bytes. - # Since we have MAX_FILE_SIZE_MB, reading into memory is safe-ish. - with open(file_path, "rb") as f: - file_content = f.read() - - files = { - "video": (filename, file_content, "video/mp4") - } + # The upload is a blocking multipart POST of the whole clip (tens of + # seconds for TikTok+YouTube). Run inline, it froze the event loop: + # 23-sep-2026 19:47:48 UTC one post stalled every request, /health + # included, for 42 s and the uptime monitor paged "openshorts-api + # down". It runs in a worker thread so the API keeps answering. + print(f"📡 Sending to Upload-Post for platforms: {req.platforms}") + response = await asyncio.to_thread( + _post_video_blocking, url, headers, data_payload, file_path, filename, 120.0 + ) - # Switch to synchronous Client to avoid "sync request with AsyncClient" error with multipart/files - with httpx.Client(timeout=120.0) as client: - print(f"📡 Sending to Upload-Post for platforms: {req.platforms}") - response = client.post(url, headers=headers, data=data_payload, files=files) - if response.status_code not in [200, 201, 202]: # Added 201 print(f"❌ Upload-Post Error: {response.text}") raise HTTPException(status_code=response.status_code, detail=f"Vendor API Error: {response.text}") @@ -6367,14 +6372,10 @@ async def saasshorts_post_to_socials(req: SaaSPostRequest, request: Request): data_payload["privacyStatus"] = "public" filename = os.path.basename(file_path) - with open(file_path, "rb") as f: - file_content = f.read() - - files = {"video": (filename, file_content, "video/mp4")} - - with httpx.Client(timeout=120.0) as client: - print(f"📡 [AI Shorts] Sending to Upload-Post: {req.platforms}") - response = client.post(url, headers=headers, data=data_payload, files=files) + print(f"📡 [AI Shorts] Sending to Upload-Post: {req.platforms}") + response = await asyncio.to_thread( + _post_video_blocking, url, headers, data_payload, file_path, filename, 120.0 + ) if response.status_code not in [200, 201, 202]: raise HTTPException(status_code=response.status_code, detail=f"Upload-Post Error: {response.text}") @@ -6713,16 +6714,22 @@ async def saasshorts_generate( # Download from S3 public URL to job output dir import httpx from security_utils import assert_public_url - try: + actor_local = os.path.join(job_output_dir, "selected_actor.png") + + def _fetch_actor(): # SSRF guard: block private / metadata hosts before fetching. safe_actor_url = assert_public_url(req.selected_actor_url) - actor_local = os.path.join(job_output_dir, "selected_actor.png") with httpx.Client(timeout=30.0) as client: resp = client.get(safe_actor_url) - if resp.status_code == 200: - with open(actor_local, "wb") as f: - f.write(resp.content) - selected_actor_path = actor_local + if resp.status_code != 200: + return None + with open(actor_local, "wb") as f: + f.write(resp.content) + return actor_local + + try: + # Off the event loop: DNS check + a download of up to 30 s. + selected_actor_path = await asyncio.to_thread(_fetch_actor) except Exception: pass else: diff --git a/tests/test_no_blocking_http_in_async.py b/tests/test_no_blocking_http_in_async.py new file mode 100644 index 0000000..fe496b5 --- /dev/null +++ b/tests/test_no_blocking_http_in_async.py @@ -0,0 +1,51 @@ +"""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 19:47:48 UTC: /api/social/post uploaded a clip to Upload-Post with +a sync ``httpx.Client`` inline; every request, /health included, stalled for +42 s and the uptime monitor paged "openshorts-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().parent.parent / "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)) + )