Coverage for monitoring/api_server.py: 100%
233 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""FastAPI server exposing Aether Quant runtime visualization state as a JSON API.
3Reads the same files the legacy HTML dashboards read (visualization/state.json,
4visualization/scene.json, visualization/grafana/*) and serves them over HTTP so
5the React webui (localhost:3000/3002) can consume them instead of fetching files
6directly off disk. No new computation happens here - this is a read-only
7reshape/serve layer over the existing runtime exports.
9V6.6.5 (#350): users and roles (monitoring/auth.py). With a users file every /api route but /api/health needs a bearer
10token; the one write, the manual trade lock of an account, needs an operator (lock) or an admin (unlock) and is written to
11a hash-chained action log. Without a users file the reads stay open, as before, and nothing can write.
12"""
14import csv
15import hashlib
16import json
17import os
18import threading
19from datetime import datetime, timezone
20from pathlib import Path
22from fastapi import Body, FastAPI, HTTPException, Request
23from fastapi.middleware.cors import CORSMiddleware
24from fastapi.responses import JSONResponse
25from fastapi.staticfiles import StaticFiles
27# StaticFiles raises Starlette's HTTPException, of which fastapi's is a
28# *subclass* - catching the fastapi one would miss it entirely.
29from starlette.exceptions import HTTPException as StarletteHTTPException
31from json_safety import load_json_lenient
32from monitoring.assets_status import build_assets_status_from_disk
33from monitoring.auth import Role, User, authorize, verify_token
34from monitoring.auth_io import auth_required, load_users, users_file
35from monitoring.evaluation_state import build_evaluation_state, build_generations_state
36from monitoring.neural_network_state import build_neural_network_state
37from monitoring.strategy_catalog import build_strategy_catalog
39ROOT_DIR = Path(__file__).resolve().parent.parent
40# V6.6.5 (#344): AQ_DASHBOARD_ROOT points every read at another tree (the demo data in monitoring/demo, which the
41# `dashboard` image serves); unset, the paths are the repo's own, as before. AQ_DASHBOARD_DEMO=1 labels the feed as demo.
42DATA_ROOT = Path(os.environ.get("AQ_DASHBOARD_ROOT") or ROOT_DIR).resolve()
43CUSTOM_ROOT = ROOT_DIR.resolve() != DATA_ROOT
44DEMO = os.environ.get("AQ_DASHBOARD_DEMO", "") == "1"
45VISUALIZATION_DIR = DATA_ROOT / "visualization"
46GRAFANA_DIR = VISUALIZATION_DIR / "grafana"
47ML_DIR = DATA_ROOT / "ml"
48WEBUI_DIST = Path(os.environ.get("AQ_WEBUI_DIST") or (ROOT_DIR / "webui" / "dist"))
50app = FastAPI(title="Aether Quant Monitoring API")
52app.add_middleware(
53 CORSMiddleware,
54 allow_origins=[
55 "http://localhost:3000",
56 "http://localhost:3002",
57 "http://localhost:8000",
58 "http://localhost:8001",
59 "http://localhost:8080",
60 ],
61 allow_methods=["GET", "POST"],
62 allow_headers=["Authorization", "Content-Type"],
63)
65OPEN_PATHS = frozenset({"/api/health"})
66_users_lock = threading.Lock()
67_users_cache: dict = {"key": None, "users": (), "tokens": {}}
70def _current_users() -> tuple[User, ...]:
71 """The users file, reloaded when it changes. Verified tokens are remembered by their SHA-256 (PBKDF2 is slow on purpose)."""
72 path = users_file()
73 try:
74 key = (str(path), path.stat().st_mtime_ns) if path.exists() else (str(path), None)
75 except OSError:
76 key = (str(path), None)
77 with _users_lock:
78 if _users_cache["key"] != key:
79 _users_cache.update(key=key, users=load_users(), tokens={})
80 return _users_cache["users"]
83def _user_for(token: str | None) -> User | None:
84 users = _current_users()
85 if not token:
86 return None
87 fingerprint = hashlib.sha256(token.encode("utf-8")).hexdigest()
88 with _users_lock:
89 cached = _users_cache["tokens"].get(fingerprint)
90 if cached is not None:
91 return cached or None
92 user = verify_token(users, token)
93 with _users_lock:
94 _users_cache["tokens"][fingerprint] = user or False
95 return user
98def _bearer(request: Request) -> str | None:
99 header = request.headers.get("authorization", "")
100 return header[7:].strip() if header.lower().startswith("bearer ") else None
103@app.middleware("http")
104async def _require_auth(request: Request, call_next):
105 path = request.url.path
106 if not path.startswith("/api/") or path in OPEN_PATHS or request.method == "OPTIONS":
107 return await call_next(request)
108 try:
109 users = _current_users()
110 except (OSError, ValueError):
111 return JSONResponse({"detail": "the users file is unreadable or invalid; refusing to serve"}, status_code=503)
112 required = auth_required(users)
113 user = _user_for(_bearer(request)) if required else None
114 if required and user is None:
115 return JSONResponse({"detail": "a valid bearer token is required"}, status_code=401, headers={"WWW-Authenticate": "Bearer"})
116 account = request.query_params.get("account")
117 if required and not authorize(user, Role.VIEWER, account, auth_required=True):
118 return JSONResponse({"detail": "this user may not read that account"}, status_code=403)
119 request.state.user = user
120 request.state.auth_required = required
121 return await call_next(request)
124def _read_json(path: Path) -> dict:
125 # V5.4.7 (Problems.md #120): a torn/mid-write file (or a TOCTOU delete
126 # between exists() and open) previously raised JSONDecodeError /
127 # FileNotFoundError -> HTTP 500. Degrade to the documented 404 shape.
128 payload = load_json_lenient(path)
129 if payload is None:
130 raise HTTPException(status_code=404, detail=f"{path.name} not found")
131 return payload
134def _read_csv_as_rows(path: Path) -> list[dict]:
135 try:
136 with path.open("r", encoding="utf-8", newline="") as f:
137 return list(csv.DictReader(f))
138 except OSError as error:
139 raise HTTPException(status_code=404, detail=f"{path.name} not found") from error
142@app.get("/api/health")
143def health() -> dict:
144 try:
145 required = auth_required(_current_users())
146 except (OSError, ValueError):
147 required = True
148 return {"status": "ok", "demo": DEMO, "auth": "required" if required else "off"}
151@app.get("/api/auth/whoami")
152def whoami(request: Request) -> dict:
153 user = getattr(request.state, "user", None)
154 return {"auth": "required" if getattr(request.state, "auth_required", False) else "off", "user": user.name if user else None,
155 "role": user.role.name.lower() if user else None, "accounts": list(user.accounts) if user else ["*"]}
158def _accounts():
159 from execution.accounts_io import load_accounts
161 config = load_json_lenient(ROOT_DIR / "config.json") or {}
162 return load_accounts(ROOT_DIR, config.get("phase_v2", {}))
165@app.get("/api/accounts")
166def get_accounts(request: Request) -> dict:
167 """V6.6.5 (#349): the deployments, their secrets (names only) and last state; a scoped user sees their own."""
168 from execution.accounts_io import account_status_rows
170 if DEMO:
171 return {"demo": True, "accounts": [{"id": "default", "broker": "paper", "environment": "live-paper", "mode": "demo", "secrets": "0/0",
172 "secrets_missing": [], "state": "visualization/state.json", "reconciliation_breach": None}]}
173 try:
174 accounts = _accounts()
175 except ValueError as error:
176 raise HTTPException(status_code=500, detail=f"accounts.json is invalid: {error}") from None
177 user = getattr(request.state, "user", None)
178 rows = [row for row in account_status_rows(ROOT_DIR, accounts) if user is None or user.may_access(row["id"])]
179 return {"demo": False, "accounts": rows}
182@app.get("/api/readiness")
183def get_readiness() -> dict:
184 """V6.6.5 (#352): the paper-to-live scorecard `aq live-readiness` last wrote."""
185 return _read_json(GRAFANA_DIR / "live_readiness.json")
188def _append_action(record: dict) -> dict:
189 """One hash-chained line in state/api_actions.jsonl (audit.hash_chain), and the same event on the audit stream when Redis is up."""
190 from audit.hash_chain import GENESIS_HASH, compute_entry_hash
192 path = ROOT_DIR / "state" / "api_actions.jsonl"
193 path.parent.mkdir(parents=True, exist_ok=True)
194 previous = GENESIS_HASH
195 if path.exists():
196 lines = [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
197 if lines:
198 previous = json.loads(lines[-1])["hash"]
199 created = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
200 entry = {"prev_hash": previous, "event_type": "live_mode_transition", "created_at": created, "payload": record}
201 entry["hash"] = compute_entry_hash(previous, entry["event_type"], created, record)
202 with path.open("a", encoding="utf-8", newline="\n") as handle:
203 handle.write(json.dumps(entry, sort_keys=True) + "\n")
204 try:
205 from audit import LIVE_MODE_TRANSITION, AuditQueue, build_audit_event
207 AuditQueue(enabled=True, stream_name="aether:audit").push(build_audit_event(LIVE_MODE_TRANSITION, record, actor=str(record.get("user") or "api")))
208 except Exception:
209 pass
210 return entry
213@app.post("/api/accounts/{account_id}/trade-lock")
214def set_trade_lock(account_id: str, request: Request, body: dict = Body(...)) -> dict:
215 """Lock (an operator) or unlock (an admin) one account's trading through the manual trade-lock override main.py reads
216 each session. `{"locked": true}` locks, `{"locked": false}` unlocks, `{"locked": null}` hands control back to the rules (admin)."""
217 from execution.accounts import override_path, resolve_account
218 from risk.manual_override import write_manual_trade_lock_override
220 if DEMO:
221 raise HTTPException(status_code=403, detail="the demo dashboard changes nothing")
222 if "locked" not in body or body["locked"] not in (True, False, None):
223 raise HTTPException(status_code=422, detail='body must be {"locked": true | false | null}')
224 locked = body["locked"]
225 user = getattr(request.state, "user", None)
226 required = Role.OPERATOR if locked is True else Role.ADMIN
227 if not authorize(user, required, account_id, auth_required=True):
228 raise HTTPException(status_code=403, detail=f"needs an authenticated {required.name.lower()} scoped to {account_id}")
229 try:
230 account = resolve_account(_accounts(), account_id)
231 except ValueError as error:
232 raise HTTPException(status_code=404, detail=str(error)) from None
233 target = override_path(ROOT_DIR, account)
234 target.parent.mkdir(parents=True, exist_ok=True)
235 if not target.exists(): # a named account's overrides file starts empty; the default account's is config.json
236 target.write_text("{}", encoding="utf-8")
237 write_manual_trade_lock_override(locked, target)
238 entry = _append_action({"event": "manual_trade_lock", "account_id": account.id, "locked": locked, "user": user.name, "role": user.role.name.lower()})
239 return {"account": account.id, "locked": locked, "written": target.relative_to(ROOT_DIR).as_posix(), "audit_hash": entry["hash"]}
242@app.get("/api/state")
243def get_state(account: str | None = None) -> dict:
244 state_path = VISUALIZATION_DIR / "state.json"
245 if account and account != "default":
246 from execution.accounts import account_output_paths, resolve_account
248 try:
249 state_path = account_output_paths(DATA_ROOT, resolve_account(_accounts(), account))["state_path"]
250 except ValueError as error:
251 raise HTTPException(status_code=404, detail=str(error)) from None
252 state = _read_json(state_path)
253 retraining_status_path = GRAFANA_DIR / "retraining_status.json"
254 payload = load_json_lenient(retraining_status_path)
255 if payload is not None:
256 state["retraining_status"] = payload
257 paper_readiness_path = GRAFANA_DIR / "paper_readiness_report.json"
258 payload = load_json_lenient(paper_readiness_path)
259 if payload is not None:
260 state["paper_readiness"] = payload
261 return state
264@app.get("/api/scene")
265def get_scene() -> dict:
266 return _read_json(VISUALIZATION_DIR / "scene.json")
269@app.get("/api/topology")
270def get_topology() -> dict:
271 return _read_json(VISUALIZATION_DIR / "topology_state.json")
274@app.get("/api/neural-network")
275def get_neural_network() -> dict:
276 return build_neural_network_state(ML_DIR if CUSTOM_ROOT else None)
279@app.get("/api/evaluation")
280def get_evaluation() -> dict:
281 """V5.1 Phase 0 - the cost-aware rank-book simulation/capacity/stress
282 reports `aq evaluate` writes to ml/evaluation/*.json. See
283 monitoring/evaluation_state.py::build_evaluation_state() for the
284 per-section not_evaluated degrade contract."""
285 return build_evaluation_state(ML_DIR if CUSTOM_ROOT else None)
288@app.get("/api/generations")
289def get_generations() -> dict:
290 """V6.6.1 - the model generations sharing the book, their decay state and what is due (`aq cycle status`)."""
291 return build_generations_state(ML_DIR if CUSTOM_ROOT else None)
294@app.get("/api/assets-status")
295def get_assets_status() -> dict:
296 return build_assets_status_from_disk(DATA_ROOT if CUSTOM_ROOT else None)
299@app.get("/api/strategies")
300def get_strategy_catalog() -> dict:
301 return build_strategy_catalog()
304@app.get("/api/grafana/metrics-snapshot")
305def get_metrics_snapshot() -> dict:
306 return _read_json(GRAFANA_DIR / "runtime_metrics_snapshot.json")
309@app.get("/api/grafana/equity-curves")
310def get_equity_curves() -> list[dict]:
311 return _read_csv_as_rows(GRAFANA_DIR / "equity_curves.csv")
314@app.get("/api/grafana/asset-performance")
315def get_asset_performance() -> list[dict]:
316 return _read_csv_as_rows(GRAFANA_DIR / "asset_performance.csv")
319@app.get("/api/grafana/observation-equity-curve")
320def get_observation_equity_curve() -> list[dict]:
321 return _read_csv_as_rows(GRAFANA_DIR / "observation_equity_curve.csv")
324@app.get("/api/grafana/retraining-status")
325def get_retraining_status() -> dict:
326 return _read_json(GRAFANA_DIR / "retraining_status.json")
329@app.get("/api/audit-log")
330def get_audit_log() -> dict:
331 """Reads visualization/grafana/audit_log.json - written by
332 audit/postgres_worker.py after every batch it persists (development/
333 Problems.md #42). Same "main.py can't reach Postgres, so a worker
334 exports a JSON snapshot" pattern as /api/grafana/retraining-status
335 (see retraining/status_export.py's docstring)."""
336 return _read_json(GRAFANA_DIR / "audit_log.json")
339@app.get("/api/grafana/paper-readiness")
340def get_paper_readiness() -> dict:
341 return _read_json(GRAFANA_DIR / "paper_readiness_report.json")
344class SpaStaticFiles(StaticFiles):
345 """Serves the built webui with a client-side-routing fallback.
347 `StaticFiles(html=True)` alone only maps *directory* paths to
348 index.html - an unknown path like /risk or /operations still 404s. The
349 React router owns those paths, so every tab except / broke on a direct
350 load or hard refresh whenever the SPA was served from here (the Docker
351 image and any bare-uvicorn run; the vite dev server has its own
352 fallback, which is why this never showed up in local development).
354 Only extensionless paths fall back. A missing /assets/*.js must keep
355 404ing rather than silently returning index.html, which would turn a
356 broken build into a blank page with no error.
357 """
359 async def get_response(self, path: str, scope):
360 # Starlette signals a missing file by *raising* HTTPException(404),
361 # not by returning a 404 response - catching is the only way to
362 # intercept it.
363 try:
364 return await super().get_response(path, scope)
365 except StarletteHTTPException as exc:
366 if exc.status_code == 404 and not Path(path).suffix:
367 return await super().get_response("index.html", scope)
368 raise
371# Mounted last on purpose: "/" is a catch-all, so any route registered
372# below it would be shadowed by the SPA.
373if WEBUI_DIST.exists():
374 app.mount("/", SpaStaticFiles(directory=WEBUI_DIST, html=True), name="static")