Coverage for src/romfarmer/web/api/builds.py: 0%
137 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""Build API routes — list, trigger, monitor, and manage builds."""
3from __future__ import annotations
5import logging
6import threading
7from pathlib import Path
8from typing import Any
10import yaml
11from fastapi import APIRouter, HTTPException, Request
13logger = logging.getLogger("romfarmer.web.api.builds")
15router = APIRouter()
17# Track running builds: {build_name: {"thread": Thread, "status": str, "log": list}}
18_running_builds: dict[str, dict[str, Any]] = {}
21def _config_root(request: Request) -> Path:
22 return request.app.state.config_root
25def _workspace(request: Request) -> Path:
26 return request.app.state.workspace
29def _state_dir(request: Request) -> Path:
30 return _workspace(request) / "state"
33def _list_build_yamls(builds_dir: Path, format_label: str) -> list[dict]:
34 """List build YAML files with metadata."""
35 if not builds_dir.exists():
36 return []
37 results = []
38 for f in sorted(builds_dir.glob("*.yaml")):
39 try:
40 raw = yaml.safe_load(f.read_text())
41 results.append(
42 {
43 "name": f.stem,
44 "file": f.name,
45 "format": format_label,
46 "description": raw.get("description", raw.get("name", f.stem)),
47 "target": raw.get("target", "—"),
48 "recipes": raw.get("recipes", []),
49 "platforms": raw.get("platforms", []),
50 }
51 )
52 except Exception as e:
53 results.append(
54 {
55 "name": f.stem,
56 "file": f.name,
57 "format": format_label,
58 "description": f"(error: {e})",
59 }
60 )
61 return results
64# ── List Builds ──────────────────────────────────────────────────────────────
67@router.get("")
68async def list_builds(request: Request):
69 """List all build configurations (both legacy and new format)."""
70 root = _config_root(request)
71 legacy = _list_build_yamls(root / "builds", "legacy")
72 new = _list_build_yamls(root / "builds" / "new", "new")
73 return {"legacy": legacy, "new": new, "total": len(legacy) + len(new)}
76@router.get("/{name}")
77async def get_build(name: str, request: Request):
78 """Get a specific build configuration."""
79 root = _config_root(request)
80 # Check new format first, then legacy
81 for subdir in ["builds/new", "builds"]:
82 path = root / subdir / f"{name}.yaml"
83 if path.exists():
84 raw = yaml.safe_load(path.read_text())
85 return {
86 "name": name,
87 "format": "new" if "new" in subdir else "legacy",
88 "config": raw,
89 }
90 raise HTTPException(status_code=404, detail=f"Build not found: {name}")
93# ── Build State ──────────────────────────────────────────────────────────────
96@router.get("/{name}/status")
97async def get_build_status(name: str, request: Request):
98 """Get the current status of a build."""
99 state_dir = _state_dir(request)
100 state_file = state_dir / f".build_state_{name}.yaml"
102 result: dict[str, Any] = {"name": name}
104 # Check if actively running in this process
105 if name in _running_builds:
106 result["running"] = True
107 result["log_lines"] = len(_running_builds[name].get("log", []))
108 else:
109 result["running"] = False
111 # Check persisted state
112 if state_file.exists():
113 try:
114 state = yaml.safe_load(state_file.read_text())
115 result["state"] = state
116 except Exception:
117 result["state"] = None
118 else:
119 result["state"] = None
121 return result
124# ── Trigger Build ────────────────────────────────────────────────────────────
127@router.post("/{name}/run")
128async def run_build(name: str, request: Request):
129 """Trigger a build by name. Runs in background thread."""
130 if name in _running_builds and _running_builds[name].get("thread", None):
131 t = _running_builds[name]["thread"]
132 if t.is_alive():
133 raise HTTPException(status_code=409, detail=f"Build '{name}' is already running")
135 _workspace(request)
136 config_root = _config_root(request)
138 # Verify build exists
139 found = False
140 for subdir in ["builds/new", "builds"]:
141 if (config_root / subdir / f"{name}.yaml").exists():
142 found = True
143 break
144 if not found:
145 raise HTTPException(status_code=404, detail=f"Build not found: {name}")
147 # Run in background thread
148 build_log: list[str] = []
150 def _run_build():
151 try:
152 build_log.append(f"Starting build: {name}")
153 from romfarmer.new_orchestrator import NewBuildOrchestrator
155 orchestrator = NewBuildOrchestrator.from_config(name)
156 build_log.append("Orchestrator loaded, validating...")
158 if hasattr(orchestrator, "validate"):
159 orchestrator.validate()
160 build_log.append("Validation passed, starting build...")
162 orchestrator.run()
163 build_log.append("Build completed successfully")
164 _running_builds[name]["status"] = "completed"
165 except Exception as e:
166 build_log.append(f"Build failed: {e}")
167 _running_builds[name]["status"] = "failed"
168 logger.exception(f"Build {name} failed")
170 thread = threading.Thread(target=_run_build, daemon=True, name=f"build-{name}")
171 _running_builds[name] = {"thread": thread, "status": "running", "log": build_log}
172 thread.start()
174 return {"status": "started", "name": name}
177@router.post("/{name}/stop")
178async def stop_build(name: str):
179 """Stop a running build (best-effort — sets a flag)."""
180 if name not in _running_builds:
181 raise HTTPException(status_code=404, detail=f"No running build: {name}")
182 # Note: Python threads can't be forcefully killed. The orchestrator
183 # would need to check a stop flag. For now, mark as stopping.
184 _running_builds[name]["status"] = "stopping"
185 return {"status": "stopping", "name": name}
188@router.get("/{name}/log")
189async def get_build_log(name: str, after: int = 0):
190 """Get build log lines (for polling). Use ?after=N to get lines after N."""
191 if name not in _running_builds:
192 raise HTTPException(status_code=404, detail=f"No active build: {name}")
193 log = _running_builds[name]["log"]
194 return {
195 "lines": log[after:],
196 "total": len(log),
197 "status": _running_builds[name]["status"],
198 }
201# ── Build Config CRUD ────────────────────────────────────────────────────────
204@router.put("/{name}")
205async def save_build(name: str, request: Request):
206 """Save/update a build configuration (new format)."""
207 body = await request.json()
208 path = _config_root(request) / "builds" / "new" / f"{name}.yaml"
209 path.parent.mkdir(parents=True, exist_ok=True)
210 path.write_text(yaml.dump(body, default_flow_style=False, sort_keys=False))
211 return {"status": "saved", "name": name, "format": "new"}
214@router.delete("/{name}/state")
215async def clean_build_state(name: str, request: Request):
216 """Clean build state for a build (like romfarmer build clean)."""
217 state_dir = _state_dir(request)
218 state_file = state_dir / f".build_state_{name}.yaml"
219 if state_file.exists():
220 state_file.unlink()
221 return {"status": "cleaned", "name": name}
222 return {"status": "no_state", "name": name}
225# ── Resolve Build ────────────────────────────────────────────────────────────
228@router.get("/{name}/resolve")
229async def resolve_build(name: str, request: Request):
230 """Resolve a new-format build and show what it would do."""
231 config_root = _config_root(request)
233 # Only works for new format builds
234 path = config_root / "builds" / "new" / f"{name}.yaml"
235 if not path.exists():
236 raise HTTPException(status_code=404, detail=f"New-format build not found: {name}")
238 try:
239 from romfarmer.new_orchestrator import NewBuildOrchestrator
241 orch = NewBuildOrchestrator.from_config(name, config_root=config_root)
242 platforms = []
243 for rc in orch.resolved_configs:
244 platforms.append(
245 {
246 "name": rc.platform_name,
247 "compression": rc.compression_format,
248 "source_count": getattr(rc, "expected_count", None),
249 "enabled": getattr(rc, "enabled", True),
250 }
251 )
253 return {
254 "name": name,
255 "target": orch.build_spec.target,
256 "recipes": orch.build_spec.recipes,
257 "platform_count": len(platforms),
258 "platforms": platforms,
259 "has_budget": orch.build_spec.has_budget_constraint(),
260 "output_base": str(orch.build_spec.get_output_base()),
261 }
262 except Exception as e:
263 raise HTTPException(status_code=500, detail=f"Resolution failed: {e}") from e