- kurgan/hw/client.py: HardwareClient polls the service's state once a second on its own thread, reconnecting (and greeting again) whenever the pipe breaks, and sends the app's chase clock with each poll. Profile and RAM lighting changes are sent at once: bad values are ValueError before anything is sent; an unreachable or refusing service is HardwareUnavailable. A state that stops arriving (5 s) or a service loop that stops publishing (15 s) counts as unavailable. PipeTransport for the real pipe, LocalTransport (same encoding and checks, no pipe) for --demo and tests. - Telemetry: the CPU package temperature and power (CpuSensors(package=...)) and the Commander PRO RPMs for the power model (SystemPower(fans=...)) come from the service; the app opens neither PawnIO nor the Commander PRO. "hardware service" is its own health source, and while it's down the missing CPU temperature isn't reported a second time. - The fan UI, profile buttons and fan history come from the service's state; the RAM lighting zone goes through it (LightingService(ram=...)), and the case fan and GPU zones stay local. The alert monitor balloons "Hardware service unavailable"; the header shows a hardware service pill instead of the admin-rights one (and warns if the app itself runs elevated); the tray lines read the service's fans. POSTs answer 503 while it's unavailable. - Removed --gpu-fan-ports, --no-gpu-fan-control and --rgb-memory-*: the service owns those now. - settings.json: cooling and lighting.memory are legacy. Old files keep them (still validated), nothing reads them, and defaults no longer add them. - --demo runs the real HardwareService in-process on the demo fakes, with its settings in demo-hw-settings.json, through the same client. - --preview reads the CPU temperature and fan power from the service too. - Tests: 13 for the client (including a real pipe end to end); the alert, lighting, settings and web tests follow the new shapes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
156 lines
6.6 KiB
Python
156 lines
6.6 KiB
Python
import http.client
|
|
import json
|
|
import socket
|
|
import unittest
|
|
|
|
from kurgan.hw.client import HardwareUnavailable
|
|
from kurgan.web.server import WebServer
|
|
|
|
|
|
class FakeApp:
|
|
def __init__(self):
|
|
self.calls = []
|
|
|
|
def state(self):
|
|
return {"ok": True}
|
|
|
|
def history(self):
|
|
return {"rows": []}
|
|
|
|
def config(self):
|
|
return {"profiles": []}
|
|
|
|
def set_lighting(self, zone, mode):
|
|
self.calls.append(("lighting", zone, mode))
|
|
if mode == "rainbow":
|
|
raise ValueError("Unknown lighting mode")
|
|
|
|
def set_fan_profile(self, profile):
|
|
self.calls.append(("profile", profile))
|
|
if profile == "full-disk":
|
|
raise OSError("disk full")
|
|
if profile == "no-service":
|
|
raise HardwareUnavailable("the hardware service isn't running (no pipe)")
|
|
|
|
def set_ai(self, backend, variant):
|
|
self.calls.append(("ai", backend, variant))
|
|
|
|
def ai_model(self, action):
|
|
self.calls.append(("model", action))
|
|
|
|
def records(self, days):
|
|
self.calls.append(("records", days))
|
|
if not 1 <= days <= 400:
|
|
raise ValueError("days must be a whole number from 1 to 400")
|
|
return {"metrics": [], "rows": [], "days": days}
|
|
|
|
|
|
def free_port() -> int:
|
|
with socket.socket() as s:
|
|
s.bind(("127.0.0.1", 0))
|
|
return s.getsockname()[1]
|
|
|
|
|
|
class WebServerTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.app = FakeApp()
|
|
cls.port = free_port()
|
|
cls.server = WebServer(cls.app, cls.port)
|
|
cls.server.start()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.server.close()
|
|
|
|
def setUp(self):
|
|
self.app.calls.clear()
|
|
|
|
def request(self, method, path, body=None, headers=None, host=None):
|
|
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
|
|
try:
|
|
data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
|
|
base = {"Host": host or f"127.0.0.1:{self.port}"}
|
|
if method == "POST":
|
|
base.update({"Content-Type": "application/json", "X-Kurgan": "1"})
|
|
base.update(headers or {})
|
|
connection.request(method, path, body=data, headers={k: v for k, v in base.items() if v is not None})
|
|
response = connection.getresponse()
|
|
return response.status, response.getheader("Content-Type"), response.read()
|
|
finally:
|
|
connection.close()
|
|
|
|
def test_api_and_ui_are_served(self):
|
|
status, kind, body = self.request("GET", "/api/state")
|
|
self.assertEqual((status, json.loads(body)), (200, {"ok": True}))
|
|
status, kind, body = self.request("GET", "/", host=f"localhost:{self.port}")
|
|
self.assertEqual(status, 200)
|
|
self.assertTrue(kind.startswith("text/html"))
|
|
self.assertIn(b"THE KURGAN", body)
|
|
status, kind, _ = self.request("GET", "/static/app.js")
|
|
self.assertEqual(status, 200)
|
|
self.assertIn("javascript", kind)
|
|
|
|
def test_only_files_in_static_are_served(self):
|
|
for path in ("/static/../server.py", "/static/..%2Fserver.py", "/static/missing.js", "/server.py"):
|
|
with self.subTest(path=path):
|
|
self.assertEqual(self.request("GET", path)[0], 404)
|
|
|
|
def test_foreign_host_is_refused(self): # DNS rebinding
|
|
self.assertEqual(self.request("GET", "/api/state", host="attacker.example")[0], 403)
|
|
self.assertEqual(self.request("POST", "/api/ai/model", {"action": "load"}, host="attacker.example")[0], 403)
|
|
self.assertEqual(self.app.calls, [])
|
|
|
|
def test_posts_need_the_header_json_and_our_origin(self):
|
|
refused = (({"X-Kurgan": None}, 403), ({"Origin": "https://attacker.example"}, 403),
|
|
({"Content-Type": "text/plain"}, 415))
|
|
for headers, expected in refused:
|
|
with self.subTest(headers=headers):
|
|
status, _, _ = self.request("POST", "/api/cooling/profile", {"profile": "quiet"}, headers)
|
|
self.assertEqual(status, expected)
|
|
self.assertEqual(self.app.calls, [])
|
|
status, _, body = self.request("POST", "/api/cooling/profile", {"profile": "quiet"},
|
|
{"Origin": f"http://127.0.0.1:{self.port}"})
|
|
self.assertEqual((status, json.loads(body)), (200, {"ok": True}))
|
|
self.assertEqual(self.app.calls, [("profile", "quiet")])
|
|
|
|
def test_bad_bodies_and_failures_report_errors(self):
|
|
cases = (("/api/lighting", {"zone": "gpu"}, 400, "mode is required"),
|
|
("/api/lighting", {"zone": "gpu", "mode": "rainbow"}, 400, "Unknown lighting mode"),
|
|
("/api/lighting", [1, 2], 400, "JSON object"),
|
|
("/api/lighting", b"{nope", 400, None),
|
|
("/api/lighting", b"x" * 20000, 400, "oversized"),
|
|
("/api/ai/active", {"backend": 3}, 400, "string or null"),
|
|
("/api/cooling/profile", {"profile": "full-disk"}, 500, "disk full"),
|
|
("/api/cooling/profile", {"profile": "no-service"}, 503, "isn't running"),
|
|
("/api/fans", {"x": 1}, 404, None))
|
|
for path, body, expected, message in cases:
|
|
with self.subTest(path=path, body=body):
|
|
status, _, raw = self.request("POST", path, body)
|
|
self.assertEqual(status, expected)
|
|
if message:
|
|
self.assertIn(message, json.loads(raw)["error"])
|
|
|
|
def test_ai_choice_allows_none(self):
|
|
status, _, _ = self.request("POST", "/api/ai/active", {"backend": None})
|
|
self.assertEqual(status, 200)
|
|
self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"})
|
|
self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")])
|
|
|
|
def test_records_serves_the_long_term_rollups(self):
|
|
status, _, body = self.request("GET", "/api/records") # no days: the default week
|
|
self.assertEqual((status, json.loads(body)["days"]), (200, 7))
|
|
status, _, body = self.request("GET", "/api/records?days=30")
|
|
self.assertEqual((status, json.loads(body)["days"]), (200, 30))
|
|
self.assertEqual(self.app.calls, [("records", 7), ("records", 30)])
|
|
for path in ("/api/records?days=abc", "/api/records?days=0", "/api/records?days=-3",
|
|
"/api/records?days=401", "/api/records?days=1.5"):
|
|
with self.subTest(path=path):
|
|
status, _, raw = self.request("GET", path)
|
|
self.assertEqual(status, 400)
|
|
self.assertIn("whole number", json.loads(raw)["error"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|