"""Viz2D conversion and job management routes.""" import asyncio import json import math import time import uuid from datetime import datetime, timezone from pathlib import Path from fastapi import APIRouter, BackgroundTasks, Body, File, Query, Response, UploadFile from config.paths import JOB_DIR, UPLOAD_DIR from config.runtime import CONVERSION_TARGET_MS, DEBUG_ARTIFACTS_ENABLED from errors import bad_request, conflict, not_found from services.image.loading import normalize_room_upload from services.jobs.conversion import run_conversion_task from services.jobs.store import read_job, write_job from services.jobs.timing import estimate_conversion_ms from services.spaces.upload import upload_input_image_to_spaces from enums import JobStatus router = APIRouter(prefix="/viz2d", tags=["viz2d"]) JOB_STATUS_MAX_WAIT_MS = 10_000 JOB_STATUS_WAIT_STEP_S = 0.05 JOB_TERMINAL_STATUSES = {JobStatus.COMPLETED, JobStatus.PREVIEW_READY, JobStatus.FAILED} @router.post("/convert") async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)): t_upload_start = time.perf_counter() if file.content_type and not file.content_type.startswith("image/"): bad_request("Upload must be a JPG or PNG image.") contents = await file.read() if not contents: bad_request("Upload must not be empty.") t_read = time.perf_counter() - t_upload_start t0 = time.perf_counter() normalized_contents = normalize_room_upload(contents) t_normalize = time.perf_counter() - t0 job_id = uuid.uuid4().hex original_filename = file.filename content_type = "image/jpeg" ext = ".jpg" upload_path = UPLOAD_DIR / f"{job_id}{ext}" t0 = time.perf_counter() upload_path.write_bytes(normalized_contents) t_persist = time.perf_counter() - t0 size_kb = len(contents) / 1024 print( f"\n[JOB {job_id[:8]}] Upload received: {original_filename} ({size_kb:.0f} KB)" f" | read={t_read:.2f}s | normalize={t_normalize:.2f}s | persist={t_persist:.2f}s", flush=True, ) job = { "id": job_id, "status": JobStatus.QUEUED, "phase": "queued", "progress": 0, "phaseProgress": 0, "message": "Starting analysis\u2026", "createdAt": datetime.now(timezone.utc).isoformat(), "estimatedTotalMs": estimate_conversion_ms(), "estimatedRemainingMs": estimate_conversion_ms(), "targetMs": CONVERSION_TARGET_MS, "inputUrl": f"/uploads/{upload_path.name}", "outputUrl": f"/viz2d/jobs/{job_id}/file", "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None, "requestTimings": { "serverReadMs": round(t_read * 1000), "normalizeMs": round(t_normalize * 1000), "persistMs": round(t_persist * 1000), }, } write_job(job) background_tasks.add_task(run_conversion_task, job_id, upload_path) background_tasks.add_task(upload_input_image_to_spaces, job_id, upload_path, original_filename, content_type) return job @router.get("/jobs") async def viz2d_list_jobs( status: str | None = Query(None, description="Filter by status: COMPLETED, FAILED, PROCESSING"), limit: int = Query(50, ge=1, le=200), offset: int = Query(0, ge=0), ): """List all jobs, newest first.""" job_files = sorted(JOB_DIR.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True) jobs = [] for path in job_files: try: job = json.loads(path.read_text()) except (json.JSONDecodeError, OSError): continue if status and job.get("status") != status: continue jobs.append(job) total = len(jobs) return {"total": total, "offset": offset, "limit": limit, "jobs": jobs[offset : offset + limit]} @router.post("/jobs/{job_id}/client-timings") async def viz2d_record_client_timings(job_id: str, payload: dict = Body(...)): """Persist bounded browser timing events alongside their conversion job.""" raw_events = payload.get("events") if not isinstance(raw_events, list): bad_request("events must be a list.") events = [] for raw_event in raw_events[:20]: if not isinstance(raw_event, dict): continue event = {} for key, value in list(raw_event.items())[:40]: if not isinstance(key, str) or len(key) > 64: continue if isinstance(value, bool): event[key] = value elif isinstance(value, (int, float)): try: numeric_value = float(value) except (OverflowError, ValueError): continue if math.isfinite(numeric_value): event[key] = round(numeric_value, 3) elif isinstance(value, str): event[key] = value[:200] if isinstance(event.get("type"), str): events.append(event) job = read_job(job_id) existing = job.get("clientTimingEvents") if not isinstance(existing, list): existing = [] job["clientTimingEvents"] = (existing + events)[-50:] job["clientTimingsUpdatedAt"] = datetime.now(timezone.utc).isoformat() write_job(job) return {"ok": True, "stored": len(events)} @router.get("/jobs/{job_id}") async def viz2d_job_status( job_id: str, wait_ms: int = Query(0, alias="waitMs", ge=0, le=JOB_STATUS_MAX_WAIT_MS), ): """Return the job, optionally holding the request until it changes. With waitMs the response is sent as soon as status, phase or progress moves (or the job finishes), so clients learn of completion within one check step instead of up to a full client-side polling interval. """ job = read_job(job_id) if wait_ms <= 0 or job.get("status") in JOB_TERMINAL_STATUSES: return job snapshot = (job.get("status"), job.get("phase"), job.get("progress")) deadline = time.monotonic() + wait_ms / 1000 while time.monotonic() < deadline: await asyncio.sleep(JOB_STATUS_WAIT_STEP_S) job = read_job(job_id) if job.get("status") in JOB_TERMINAL_STATUSES: return job if (job.get("status"), job.get("phase"), job.get("progress")) != snapshot: return job return job @router.get("/jobs/{job_id}/debug") async def viz2d_job_debug(job_id: str): read_job(job_id) if not DEBUG_ARTIFACTS_ENABLED: not_found("Debug artifacts are disabled on this server.") manifest_path = JOB_DIR / f"{job_id}.debug" / "manifest.json" if not manifest_path.exists(): not_found("Debug artifacts are not available yet.") return Response( content=manifest_path.read_bytes(), media_type="application/json", headers={"Cache-Control": "no-store"}, ) @router.get("/jobs/{job_id}/debug/assets/{asset_name}") async def viz2d_job_debug_asset(job_id: str, asset_name: str): read_job(job_id) if Path(asset_name).name != asset_name: bad_request("Invalid debug asset name.") asset_path = JOB_DIR / f"{job_id}.debug" / asset_name if not asset_path.exists() or not asset_path.is_file(): not_found("Debug asset not found.") media_type = "image/jpeg" if asset_path.suffix.lower() in {".jpg", ".jpeg"} else "application/octet-stream" return Response( content=asset_path.read_bytes(), media_type=media_type, headers={"Cache-Control": "private, max-age=3600"}, ) @router.get("/jobs/{job_id}/file") async def viz2d_job_file(job_id: str): job = read_job(job_id) if job.get("status") not in (JobStatus.COMPLETED, JobStatus.PREVIEW_READY): conflict("Job is not completed yet.") binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle" if not binary_bundle_path.exists(): not_found("Job output not found.") is_preview = job.get("status") == JobStatus.PREVIEW_READY return Response( content=binary_bundle_path.read_bytes(), media_type="application/zip", headers={ "Content-Disposition": 'attachment; filename="visualizer.vizbundle"', "X-Bundle-Quality": "preview" if is_preview else "full", }, ) @router.get("/jobs/{job_id}/assets/{asset_name}") async def viz2d_job_asset(job_id: str, asset_name: str): read_job(job_id) if Path(asset_name).name != asset_name: bad_request("Invalid asset name.") asset_path = JOB_DIR / f"{job_id}.assets" / asset_name if not asset_path.exists() or not asset_path.is_file(): not_found("Job asset not found.") return Response( content=asset_path.read_bytes(), media_type="application/octet-stream", headers={"Cache-Control": "private, max-age=3600"}, )