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 <noreply@anthropic.com>
This commit is contained in:
parent
d585b93ea2
commit
497de58a1f
2 changed files with 86 additions and 28 deletions
63
app.py
63
app.py
|
|
@ -5148,6 +5148,16 @@ class SocialPostRequest(BaseModel):
|
||||||
|
|
||||||
import httpx
|
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")
|
@app.post("/api/social/post")
|
||||||
async def post_to_socials(req: SocialPostRequest, request: Request):
|
async def post_to_socials(req: SocialPostRequest, request: Request):
|
||||||
await _ensure_job_files(req.job_id, 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["youtube_description"] = final_description
|
||||||
data_payload["privacyStatus"] = "public"
|
data_payload["privacyStatus"] = "public"
|
||||||
|
|
||||||
# Send File
|
# The upload is a blocking multipart POST of the whole clip (tens of
|
||||||
# httpx AsyncClient requires async file reading or bytes.
|
# seconds for TikTok+YouTube). Run inline, it froze the event loop:
|
||||||
# Since we have MAX_FILE_SIZE_MB, reading into memory is safe-ish.
|
# 23-sep-2026 19:47:48 UTC one post stalled every request, /health
|
||||||
with open(file_path, "rb") as f:
|
# included, for 42 s and the uptime monitor paged "openshorts-api
|
||||||
file_content = f.read()
|
# down". It runs in a worker thread so the API keeps answering.
|
||||||
|
print(f"📡 Sending to Upload-Post for platforms: {req.platforms}")
|
||||||
files = {
|
response = await asyncio.to_thread(
|
||||||
"video": (filename, file_content, "video/mp4")
|
_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
|
if response.status_code not in [200, 201, 202]: # Added 201
|
||||||
print(f"❌ Upload-Post Error: {response.text}")
|
print(f"❌ Upload-Post Error: {response.text}")
|
||||||
raise HTTPException(status_code=response.status_code, detail=f"Vendor API 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"
|
data_payload["privacyStatus"] = "public"
|
||||||
|
|
||||||
filename = os.path.basename(file_path)
|
filename = os.path.basename(file_path)
|
||||||
with open(file_path, "rb") as f:
|
print(f"📡 [AI Shorts] Sending to Upload-Post: {req.platforms}")
|
||||||
file_content = f.read()
|
response = await asyncio.to_thread(
|
||||||
|
_post_video_blocking, url, headers, data_payload, file_path, filename, 120.0
|
||||||
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)
|
|
||||||
|
|
||||||
if response.status_code not in [200, 201, 202]:
|
if response.status_code not in [200, 201, 202]:
|
||||||
raise HTTPException(status_code=response.status_code, detail=f"Upload-Post Error: {response.text}")
|
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
|
# Download from S3 public URL to job output dir
|
||||||
import httpx
|
import httpx
|
||||||
from security_utils import assert_public_url
|
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.
|
# SSRF guard: block private / metadata hosts before fetching.
|
||||||
safe_actor_url = assert_public_url(req.selected_actor_url)
|
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:
|
with httpx.Client(timeout=30.0) as client:
|
||||||
resp = client.get(safe_actor_url)
|
resp = client.get(safe_actor_url)
|
||||||
if resp.status_code == 200:
|
if resp.status_code != 200:
|
||||||
with open(actor_local, "wb") as f:
|
return None
|
||||||
f.write(resp.content)
|
with open(actor_local, "wb") as f:
|
||||||
selected_actor_path = actor_local
|
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:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
51
tests/test_no_blocking_http_in_async.py
Normal file
51
tests/test_no_blocking_http_in_async.py
Normal file
|
|
@ -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))
|
||||||
|
)
|
||||||
Loading…
Reference in a new issue