"""Capture engine evidence outside the evaluated application UI.""" import json import os from pathlib import Path import signal import subprocess import sys from datetime import datetime, timezone root = Path(os.environ["T37_AUDIT_DIR"]) root.mkdir(parents=True, exist_ok=True) # One session can hold several tries of the same park, so every record carries # the try it belongs to and the supervisor is told, out of band, when a try has # been settled by the engine and while the park is still reporting. attempt = int(os.environ.get("T37_TRY", "1")) outcome = os.environ.get("T37_TRY_OUTCOME") heartbeat = os.environ.get("T37_TRY_HEARTBEAT") settled = ("objective_complete", "objective_failed") with (root / "game.jsonl").open("a", buffering=1) as audit, (root / "engine.log").open("a", buffering=1) as log: def write(record): record["try"] = attempt record["observed_at"] = datetime.now(timezone.utc).isoformat() audit.write(json.dumps(record) + "\n") if heartbeat and record.get("kind") == "micropark_state": Path(heartbeat).write_text(record["observed_at"]) if outcome and record.get("kind") in settled and not Path(outcome).exists(): Path(outcome).write_text(record["kind"]) write({"kind":"engine_start", "schema":1}) child = subprocess.Popen(["stdbuf","-oL","-eL","openrct2",*sys.argv[1:]], stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True) for sig in (signal.SIGINT,signal.SIGTERM): signal.signal(sig,lambda signum,frame: child.send_signal(signum)) for line in child.stdout: log.write(line) if "T37JSON " in line: try: record,_ = json.JSONDecoder().raw_decode(line.split("T37JSON ",1)[1]) write(record) except (ValueError, TypeError) as error: write({"kind":"observer_error","message":str(error)}) code=child.wait() write({"kind":"engine_stop","returncode":code}) sys.exit(code)