Radiotomy's picture
Better failure reporting
b197de5 verified
Raw History Blame Contribute Delete
4.84 kB
import asyncio, json, os, shutil, sys, time, uuid
import httpx
from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel
KEY = os.environ.get("WORKER_KEY", "")
MAX_IN = 60 * 1024 * 1024
MAX_OUT = 80 * 1024 * 1024
TIMEOUT = 300
MAX_QUEUE = 5
KEEP_S = 3600
WORK = "/tmp/jobs"
SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "process.py")
os.makedirs(WORK, exist_ok=True)
app = FastAPI()
jobs = {}
sem = asyncio.Semaphore(1)
def auth(k):
if not KEY or k != KEY:
raise HTTPException(401, "unauthorized")
def active():
return sum(1 for j in jobs.values() if j["status"] in ("queued", "processing"))
def prune():
now = time.time()
for jid in [k for k, j in jobs.items() if now - j["created"] > KEEP_S and j["status"] not in ("queued", "processing")]:
shutil.rmtree(os.path.join(WORK, jid), ignore_errors=True)
jobs.pop(jid, None)
@app.get("/health")
def health():
return {"ok": True, "active": active()}
class JobReq(BaseModel):
glb_url: str
options: dict = {}
@app.post("/jobs")
async def create(r: JobReq, x_worker_key: str = Header(default="")):
auth(x_worker_key)
prune()
if not r.glb_url.startswith("https://"):
raise HTTPException(400, "glb_url must be https")
if active() >= MAX_QUEUE:
raise HTTPException(429, "worker busy, try again shortly")
jid = uuid.uuid4().hex
jobs[jid] = {"status": "queued", "created": time.time()}
asyncio.create_task(run(jid, r))
return {"job_id": jid}
@app.get("/jobs/{jid}")
def status(jid: str, x_worker_key: str = Header(default="")):
auth(x_worker_key)
j = jobs.get(jid)
if not j:
raise HTTPException(404, "job not found")
return {k: v for k, v in j.items() if k != "created"}
@app.get("/jobs/{jid}/result")
def result(jid: str, x_worker_key: str = Header(default="")):
auth(x_worker_key)
j = jobs.get(jid)
path = os.path.join(WORK, jid, "out.glb")
if not j or j["status"] != "completed" or not os.path.exists(path):
raise HTTPException(404, "no result")
return FileResponse(path, media_type="model/gltf-binary")
async def run(jid, r):
d = os.path.join(WORK, jid)
os.makedirs(d, exist_ok=True)
j = jobs[jid]
async with sem:
j["status"] = "processing"
t0 = time.time()
try:
src, out, rep = f"{d}/in.glb", f"{d}/out.glb", f"{d}/report.json"
n = 0
async with httpx.AsyncClient(timeout=60, follow_redirects=True) as c:
async with c.stream("GET", r.glb_url) as resp:
if resp.status_code != 200:
raise Exception(f"download failed ({resp.status_code})")
with open(src, "wb") as f:
async for ch in resp.aiter_bytes():
n += len(ch)
if n > MAX_IN:
raise Exception("input GLB is larger than 60 MB")
f.write(ch)
with open(src, "rb") as f:
if f.read(4) != b"glTF":
raise Exception("input is not a binary GLB")
proc = await asyncio.create_subprocess_exec(
sys.executable, SCRIPT, "--",
src, out, rep, json.dumps(r.options or {}),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
try:
log, _ = await asyncio.wait_for(proc.communicate(), TIMEOUT)
except asyncio.TimeoutError:
proc.kill()
raise Exception("Blender took longer than 300 s")
tail = log.decode(errors="ignore")[-600:]
if not os.path.exists(rep):
raise Exception(f"Blender failed (exit {proc.returncode}): " + tail[-300:])
with open(rep) as f:
report = json.load(f)
if report.get("error"):
raise Exception(report["error"])
if not os.path.exists(out):
raise Exception("Blender did not write an output file")
size = os.path.getsize(out)
with open(out, "rb") as f:
if f.read(4) != b"glTF":
raise Exception("output is not a valid GLB")
if size > MAX_OUT:
raise Exception("output GLB is larger than 80 MB")
report["metrics"] = {"seconds": round(time.time() - t0, 1), "input_bytes": n, "output_bytes": size}
j.update(status="completed", report=report)
except Exception as e:
j.update(status="failed", error=str(e)[:600], seconds=round(time.time() - t0, 1))
finally:
if os.path.exists(f"{d}/in.glb"):
os.remove(f"{d}/in.glb")