"""Background-start serve_relations with keyzoo-mapped Steam auth env.""" from __future__ import annotations import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PORT = "8765" def _map_env() -> dict[str, str]: env = os.environ.copy() if not (env.get("STEAM_API_KEY") or "").strip(): alt = (env.get("KEYZOO_ASSET_SECRET_WEB_API_KEY") or "").strip() if alt: env["STEAM_API_KEY"] = alt if not (env.get("SESSION_SECRET") or "").strip(): alt = (env.get("KEYZOO_ASSET_SECRET_SESSION_SECRET") or "").strip() if alt: env["SESSION_SECRET"] = alt return env def main() -> int: env = _map_env() steam_ok = bool((env.get("STEAM_API_KEY") or "").strip()) sess_ok = bool((env.get("SESSION_SECRET") or "").strip()) print(f"steam_auth configured: steam={steam_ok} session={sess_ok}", flush=True) if not steam_ok or not sess_ok: print("missing STEAM_API_KEY or SESSION_SECRET", file=sys.stderr) return 2 # Free the port if an old serve is still listening. try: subprocess.run( [ "powershell", "-NoProfile", "-Command", ( f"$c=Get-NetTCPConnection -LocalPort {PORT} -ErrorAction SilentlyContinue;" "if($c){$c.OwningProcess|Sort-Object -Unique|ForEach-Object{" "Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue}}" ), ], check=False, capture_output=True, text=True, ) except OSError: pass log_path = ROOT / "web" / ".refresh" / "serve_steam.log" log_path.parent.mkdir(parents=True, exist_ok=True) cmd = [ sys.executable, "-u", str(ROOT / "web" / "serve_relations.py"), "--port", PORT, "--no-browser", ] flags = 0 if sys.platform == "win32": flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined] with log_path.open("ab") as log: proc = subprocess.Popen( cmd, cwd=str(ROOT), env=env, stdout=log, stderr=subprocess.STDOUT, creationflags=flags, close_fds=True, ) print(f"started pid={proc.pid} port={PORT}", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())