"""Real WebSocket/native gRPC integration against the same simulated bench.""" import asyncio import base64 import json from pathlib import Path import tempfile import unittest import uuid from aiohttp import ClientSession import grpc from google.protobuf import empty_pb2 from google.protobuf.json_format import MessageToDict from stl_backend.config import load_settings from stl_backend.generated import bench_pb2 as pb, bench_pb2_grpc as rpc from stl_backend.server import start_server from stl_backend.web_gateway import WebGateway ROOT = Path(__file__).resolve().parents[1] TERMINAL = {"succeeded", "failed", "interrupted"} class WebSocketTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.tmp = tempfile.TemporaryDirectory(prefix="stl-ws-") settings = load_settings(ROOT / "config/simulated.json") settings.update(listen="127.0.0.1:0", data_dir=self.tmp.name, telemetry_interval_s=.02) for cfg in settings["stations"]: cfg["simulation"].update(step_delay_s=.005) self.server, self.bench, self.grpc_port = await start_server(settings) self.gateway = WebGateway(self.bench.grpc_service, "127.0.0.1", 0, ROOT / "src/stl_backend/web") await self.gateway.start() self.url = f"http://127.0.0.1:{self.gateway.server.sockets[0].getsockname()[1]}/ws" self.client = ClientSession() self.channel = grpc.aio.insecure_channel(f"127.0.0.1:{self.grpc_port}") self.stub = rpc.BenchServiceStub(self.channel) async def asyncTearDown(self): await self.client.close() await self.channel.close() await self.gateway.stop() await self.server.stop(0) await self.bench.grpc_service.drain() await self.bench.close() self.tmp.cleanup() def request(self, method, params=None, **extra): return {"v": 1, "id": "req-" + uuid.uuid4().hex, "method": method, "params": params or {}, **extra} async def call(self, ws, method, params=None, **extra): request = self.request(method, params, **extra) await ws.send_json(request) response = await ws.receive_json(timeout=4) self.assertEqual(response["v"], 1) self.assertEqual(response["id"], request["id"]) return response async def result(self, ws, method, params=None, **extra): response = await self.call(ws, method, params, **extra) self.assertTrue(response["ok"], response) return response["result"] async def done(self, ws, item): async with asyncio.timeout(5): while item["state"] not in TERMINAL: await asyncio.sleep(.01) item = await self.result(ws, "GetQueueItem", {"command_id": item["command_id"]}) return item async def enqueue(self, ws, method, **arguments): item = await self.result(ws, "EnqueueCommand", { "command_id": "ws-" + uuid.uuid4().hex, "station_id": "S1", "operator": "ws-test", "method": method, "arguments": arguments}) item = await self.done(ws, item) self.assertEqual(item["state"], "succeeded", item) return item async def test_two_websockets_and_native_grpc_share_one_queue_and_event_cursors(self): async with self.client.ws_connect(self.url, compress=15) as first, self.client.ws_connect(self.url) as second: self.assertEqual(first.compress, 0, "Browser compression offers must remain unnegotiated") request = {"command_id": "ws-shared-command", "station_id": "S1", "operator": "ws-test", "method": "StationPower", "arguments": {"action": "supply_on"}} accepted = await self.result(first, "EnqueueCommand", request) duplicate = await self.result(second, "EnqueueCommand", request) self.assertEqual(accepted["sequence"], duplicate["sequence"]) self.assertEqual((await self.done(second, duplicate))["state"], "succeeded") native = await self.stub.GetQueue(pb.GetQueueRequest(station_id="S1", limit=100)) self.assertEqual([item.command_id for item in native.items], ["ws-shared-command"]) self.assertEqual(native.items[0].state, "succeeded") self.assertEqual(int(accepted["sequence"]), native.items[0].sequence) self.assertIsInstance(accepted["sequence"], str) query = {"station_id": "S1", "after_sequence": "0", "limit": 1000} first_events = await self.result(first, "ReadEventQueue", query) second_events = await self.result(second, "ReadEventQueue", query) self.assertEqual(first_events, second_events) self.assertTrue(any(e["command_id"] == "ws-shared-command" for e in first_events["events"])) control = await self.result(first, "GetStationControl", {"station_id": "S1"}) self.assertEqual(len(control["dimms"]), 24) native_info = await self.stub.GetSystemInfo(empty_pb2.Empty()) websocket_info = await self.result(second, "GetSystemInfo") self.assertEqual(native_info.server_id, websocket_info["server_id"]) async def test_saved_plan_run_snapshots_survive_all_wire_readers_and_later_setting_edits(self): rt = self.bench.station("S1") rt.device.amt_menu = True rt.device.mt_duration = .08 async with self.client.ws_connect(self.url) as ws: # Ordinary editable recipes must not acquire run-only snapshots # merely because the additive protobuf fields now exist. recipe = await self.result(ws, "GetRecipe", {"recipe_id": "DEMO-80"}) self.assertNotIn("boot_plan", recipe) self.assertNotIn("amt_settings", recipe) recipe.update(name="wire saved-plan fixture", preheat_air_c=25, preheat_hold_s=0, preheat_timeout_s=5, phase_timeout_s=20, finish_timeout_s=1) edited = await self.result(ws, "PutRecipe", {"recipe": recipe, "expected_revision": recipe["revision"]}) self.assertEqual(edited["revision"], recipe["revision"] + 1) self.assertNotIn("boot_plan", edited) self.assertNotIn("amt_settings", edited) native_recipe = await self.stub.GetRecipe(pb.RecipeKey(recipe_id="DEMO-80")) ordinary_fields = {field.name for field, value in native_recipe.ListFields()} self.assertNotIn("boot_plan", ordinary_fields) self.assertNotIn("amt_settings", ordinary_fields) overrides = [{"id": "rmt", "mode": "override", "value": "disable"}, {"id": "admt", "mode": "override", "value": "enable"}] await self.enqueue(ws, "SaveFirmwareSettings", uip_overrides=overrides, uip_raw_commands=["debuglog 1"], mt_selection={"efi_path": "FS0:\\EFI\\118.efi"}) await self.enqueue(ws, "SaveAmtSettings", settings={"action": "skip", "overrides": [], "raw_commands": [], "test_command": "amemdiag 1", "exit_after": True}) await self.enqueue(ws, "SaveBootPlan", plan={"preset": "custom", "mt_enabled": True, "use_in_runs": True, "stages": {"uip1": "manual", "amt": "auto", "uip2": "auto", "uefi": "auto", "mt": "auto"}}) control = await self.result(ws, "GetStationControl", {"station_id": "S1"}) frozen = {key: control[key] for key in ("firmware_settings", "boot_plan", "amt_settings")} started = await self.enqueue(ws, "StartRun", recipe_id="DEMO-80", work_order="WO-WIRE", batch_no="B-WIRE", dimms=[{"sn": "WIRE-SN", "slot": "A1", "cpu": 0, "channel": "A"}]) run_id = started["run_id"] or started["result"]["run_id"] async def assert_wire_snapshots(): calls = [("GetRun", {"run_id": run_id}), ("ListRuns", {"station_id": "S1", "limit": 10}), ("GetRunReport", {"run_id": run_id})] for method, params in calls: websocket = await self.result(ws, method, params) request_cls = pb.ListRunsRequest if method == "ListRuns" else pb.RunKey native = MessageToDict(await getattr(self.stub, method)(request_cls(**params)), preserving_proto_field_name=True) for data in (websocket, native): run = (next(r for r in data["runs"] if r["run_id"] == run_id) if method == "ListRuns" else data["run"] if method == "GetRunReport" else data) self.assertEqual(run["run_id"], run_id) for key, expected in frozen.items(): self.assertEqual(run["recipe"][key], expected, (method, key)) await assert_wire_snapshots() # Change the next run's saved choices while this run is waiting in # UIP. Read APIs must keep the original immutable run configuration. await self.enqueue(ws, "SaveBootPlan", plan={"preset": "manual", "use_in_runs": False, "mt_enabled": False}) await self.enqueue(ws, "SaveAmtSettings", settings={"action": "run", "overrides": [], "raw_commands": [], "test_command": "amemdiag 1", "exit_after": True}) await assert_wire_snapshots() for cpu in (0, 1): async with asyncio.timeout(8): while True: current = await self.result(ws, "GetStationControl", {"station_id": "S1"}) prompt = current["firmware"].get("console_prompt", {}) if (current["boot_execution"]["state"] == "waiting_user" and prompt.get("ready") and prompt.get("cpu") == cpu): break await asyncio.sleep(.01) await self.enqueue(ws, "ApplyUipParameters", run_id=run_id, overrides=overrides, raw_commands=["debuglog 1"]) await self.enqueue(ws, "ContinueUip", run_id=run_id) await asyncio.wait_for(asyncio.shield(rt.task), 25) await assert_wire_snapshots() stored = await self.bench.store.get_run(run_id) self.assertEqual(stored["state"], "completed", stored) self.assertTrue(stored["workflow_complete"]) self.assertEqual(stored["tests"]["amt"], "skipped_by_recipe") self.assertEqual(stored["tests"]["mt"], "completed") self.assertEqual(stored["supply_state"], "off") self.assertTrue(set(stored).issubset(pb.Run.DESCRIPTOR.fields_by_name)) self.assertTrue(set(stored["recipe"]).issubset(pb.Recipe.DESCRIPTOR.fields_by_name)) self.assertEqual(stored["evidence"]["boot_execution"]["plan"], frozen["boot_plan"]) async def test_one_connection_allows_out_of_order_responses_by_id(self): entered, release = asyncio.Event(), asyncio.Event() original = self.bench.snapshot async def delayed(station_id): entered.set() await release.wait() return await original(station_id) self.bench.snapshot = delayed try: async with self.client.ws_connect(self.url) as ws: await ws.send_json(self.request("GetStation", {"station_id": "S1"}, id="slow")) await asyncio.wait_for(entered.wait(), 2) await ws.send_json(self.request("GetSystemInfo", id="fast")) self.assertEqual((await ws.receive_json(timeout=2))["id"], "fast") release.set() result = await ws.receive_json(timeout=2) self.assertEqual(result["id"], "slow") self.assertEqual(result["result"]["station_id"], "S1") finally: release.set() self.bench.snapshot = original async def test_disconnect_during_acceptance_does_not_cancel_application_command(self): entered, release, completed = asyncio.Event(), asyncio.Event(), asyncio.Event() original = self.bench.enqueue_command async def delayed(request): entered.set() await release.wait() value = await original(request) completed.set() return value self.bench.enqueue_command = delayed try: ws = await self.client.ws_connect(self.url) await ws.send_json(self.request("EnqueueCommand", {"command_id": "ws-disconnect", "station_id": "S1", "operator": "ws-test", "method": "StationPower", "arguments": {"action": "supply_on"}})) await asyncio.wait_for(entered.wait(), 2) await ws.close() release.set() await asyncio.wait_for(completed.wait(), 2) async with self.client.ws_connect(self.url) as reconnected: item = await self.result(reconnected, "GetQueueItem", {"command_id": "ws-disconnect"}) self.assertEqual((await self.done(reconnected, item))["state"], "succeeded") queue = await self.result(reconnected, "GetQueue", {"station_id": "S1"}) self.assertEqual(len(queue["items"]), 1) finally: release.set() self.bench.enqueue_command = original async def test_received_command_keeps_running_after_client_disconnect(self): entered, release = asyncio.Event(), asyncio.Event() device = self.bench.station("S1").device original = device.bmc_power async def delayed(action): entered.set() await release.wait() return await original(action) device.bmc_power = delayed try: ws = await self.client.ws_connect(self.url) await self.enqueue(ws, "StationPower", action="supply_on") accepted = await self.result(ws, "EnqueueCommand", {"command_id": "ws-running", "station_id": "S1", "operator": "ws-test", "method": "StationPower", "arguments": {"action": "host_on"}}) await asyncio.wait_for(entered.wait(), 2) await ws.close() release.set() async with self.client.ws_connect(self.url) as other: self.assertEqual((await self.done(other, accepted))["state"], "succeeded") finally: release.set() device.bmc_power = original async def test_request_errors_do_not_close_socket(self): cases = [('{', "INVALID_ARGUMENT"), ('[]', "INVALID_ARGUMENT"), (json.dumps(self.request("GetSystemInfo", v=2)), "INVALID_ARGUMENT"), (json.dumps(self.request("SmokeUnknownMethod")), "UNIMPLEMENTED"), (json.dumps(self.request("GetStation", {"wrong_field": "S1"})), "INVALID_ARGUMENT"), (json.dumps(self.request("GetRun", {"run_id": "missing"})), "NOT_FOUND")] async with self.client.ws_connect(self.url) as ws: for raw, code in cases: await ws.send_str(raw) error = await ws.receive_json(timeout=2) self.assertFalse(error["ok"]) self.assertEqual(error["error"]["code"], code) await ws.send_bytes(b"not JSON") self.assertEqual((await ws.receive_json(timeout=2))["error"]["code"], "INVALID_ARGUMENT") self.assertEqual((await self.result(ws, "GetSystemInfo"))["station_count"], 4) async def test_optional_token_has_same_rules_on_websocket_and_grpc(self): self.bench.grpc_service.token = "ws-token" async with self.client.ws_connect(self.url) as browser: denied = await self.call(browser, "EnqueueCommand", {"command_id": "unauthorized", "station_id": "S1", "operator": "ws-test", "method": "StationPower", "arguments": {"action": "supply_on"}}) self.assertEqual(denied["error"]["code"], "UNAUTHENTICATED") queue = await self.result(browser, "GetQueue", {"station_id": "S1"}, authorization="Bearer ws-token") self.assertEqual(queue["items"], []) async with self.client.ws_connect(self.url, headers={"Authorization": "Bearer ws-token"}) as qt: self.assertEqual((await self.result(qt, "GetSystemInfo"))["station_count"], 4) bad = await self.call(qt, "GetSystemInfo", authorization="Bearer wrong") self.assertEqual(bad["error"]["code"], "UNAUTHENTICATED") self.assertEqual((await self.result(qt, "GetSystemInfo"))["station_count"], 4) with self.assertRaises(grpc.aio.AioRpcError) as caught: await self.stub.GetSystemInfo(empty_pb2.Empty()) self.assertEqual(caught.exception.code(), grpc.StatusCode.UNAUTHENTICATED) info = await self.stub.GetSystemInfo(empty_pb2.Empty(), metadata=(("authorization", "Bearer ws-token"),)) self.assertEqual(info.station_count, 4) async def test_console_bytes_and_offsets_match_existing_wire_conventions(self): async with self.client.ws_connect(self.url) as ws: await self.enqueue(ws, "StationPower", action="supply_on") await self.enqueue(ws, "SetDiagnosticSol", action="open") await self.enqueue(ws, "StationPower", action="host_on") async with asyncio.timeout(3): while True: diagnostic = await self.result(ws, "GetDiagnostic", {"station_id": "S1"}) if diagnostic["phase"] == "uip": break await asyncio.sleep(.01) session = diagnostic["session_id"] # Exercise the old WriteDiagnosticSol API too, not only the queue. command = await self.result(ws, "WriteDiagnosticSol", {"command_id": "ws-bytes", "station_id": "S1", "operator": "ws-test", "session_id": session, "data": base64.b64encode(b"help\r").decode()}) async with asyncio.timeout(3): while command["state"] not in TERMINAL: await asyncio.sleep(.01) command = await self.result(ws, "GetCommand", {"command_id": "ws-bytes"}) self.assertEqual(command["state"], "succeeded") self.assertEqual(self.bench.station("S1").device.sent_commands, [b"help\r"]) chunk = await self.result(ws, "ReadDiagnosticSol", {"station_id": "S1", "session_id": session, "offset": "0", "max_bytes": 65536}) self.assertIn(b"CxmtDdrTest", base64.b64decode(chunk["data"])) self.assertIsInstance(chunk["next_offset"], str) self.assertGreater(int(chunk["total_bytes"]), 0)