test_websocket_integration.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. """Real WebSocket/native gRPC integration against the same simulated bench."""
  2. import asyncio
  3. import base64
  4. import json
  5. from pathlib import Path
  6. import tempfile
  7. import unittest
  8. import uuid
  9. from aiohttp import ClientSession
  10. import grpc
  11. from google.protobuf import empty_pb2
  12. from google.protobuf.json_format import MessageToDict
  13. from stl_backend.config import load_settings
  14. from stl_backend.generated import bench_pb2 as pb, bench_pb2_grpc as rpc
  15. from stl_backend.server import start_server
  16. from stl_backend.web_gateway import WebGateway
  17. ROOT = Path(__file__).resolve().parents[1]
  18. TERMINAL = {"succeeded", "failed", "interrupted"}
  19. class WebSocketTests(unittest.IsolatedAsyncioTestCase):
  20. async def asyncSetUp(self):
  21. self.tmp = tempfile.TemporaryDirectory(prefix="stl-ws-")
  22. settings = load_settings(ROOT / "config/simulated.json")
  23. settings.update(listen="127.0.0.1:0", data_dir=self.tmp.name, telemetry_interval_s=.02)
  24. for cfg in settings["stations"]:
  25. cfg["simulation"].update(step_delay_s=.005)
  26. self.server, self.bench, self.grpc_port = await start_server(settings)
  27. self.gateway = WebGateway(self.bench.grpc_service, "127.0.0.1", 0, ROOT / "src/stl_backend/web")
  28. await self.gateway.start()
  29. self.url = f"http://127.0.0.1:{self.gateway.server.sockets[0].getsockname()[1]}/ws"
  30. self.client = ClientSession()
  31. self.channel = grpc.aio.insecure_channel(f"127.0.0.1:{self.grpc_port}")
  32. self.stub = rpc.BenchServiceStub(self.channel)
  33. async def asyncTearDown(self):
  34. await self.client.close()
  35. await self.channel.close()
  36. await self.gateway.stop()
  37. await self.server.stop(0)
  38. await self.bench.grpc_service.drain()
  39. await self.bench.close()
  40. self.tmp.cleanup()
  41. def request(self, method, params=None, **extra):
  42. return {"v": 1, "id": "req-" + uuid.uuid4().hex,
  43. "method": method, "params": params or {}, **extra}
  44. async def call(self, ws, method, params=None, **extra):
  45. request = self.request(method, params, **extra)
  46. await ws.send_json(request)
  47. response = await ws.receive_json(timeout=4)
  48. self.assertEqual(response["v"], 1)
  49. self.assertEqual(response["id"], request["id"])
  50. return response
  51. async def result(self, ws, method, params=None, **extra):
  52. response = await self.call(ws, method, params, **extra)
  53. self.assertTrue(response["ok"], response)
  54. return response["result"]
  55. async def done(self, ws, item):
  56. async with asyncio.timeout(5):
  57. while item["state"] not in TERMINAL:
  58. await asyncio.sleep(.01)
  59. item = await self.result(ws, "GetQueueItem", {"command_id": item["command_id"]})
  60. return item
  61. async def enqueue(self, ws, method, **arguments):
  62. item = await self.result(ws, "EnqueueCommand", {
  63. "command_id": "ws-" + uuid.uuid4().hex, "station_id": "S1", "operator": "ws-test",
  64. "method": method, "arguments": arguments})
  65. item = await self.done(ws, item)
  66. self.assertEqual(item["state"], "succeeded", item)
  67. return item
  68. async def test_two_websockets_and_native_grpc_share_one_queue_and_event_cursors(self):
  69. async with self.client.ws_connect(self.url, compress=15) as first, self.client.ws_connect(self.url) as second:
  70. self.assertEqual(first.compress, 0, "Browser compression offers must remain unnegotiated")
  71. request = {"command_id": "ws-shared-command", "station_id": "S1", "operator": "ws-test",
  72. "method": "StationPower", "arguments": {"action": "supply_on"}}
  73. accepted = await self.result(first, "EnqueueCommand", request)
  74. duplicate = await self.result(second, "EnqueueCommand", request)
  75. self.assertEqual(accepted["sequence"], duplicate["sequence"])
  76. self.assertEqual((await self.done(second, duplicate))["state"], "succeeded")
  77. native = await self.stub.GetQueue(pb.GetQueueRequest(station_id="S1", limit=100))
  78. self.assertEqual([item.command_id for item in native.items], ["ws-shared-command"])
  79. self.assertEqual(native.items[0].state, "succeeded")
  80. self.assertEqual(int(accepted["sequence"]), native.items[0].sequence)
  81. self.assertIsInstance(accepted["sequence"], str)
  82. query = {"station_id": "S1", "after_sequence": "0", "limit": 1000}
  83. first_events = await self.result(first, "ReadEventQueue", query)
  84. second_events = await self.result(second, "ReadEventQueue", query)
  85. self.assertEqual(first_events, second_events)
  86. self.assertTrue(any(e["command_id"] == "ws-shared-command" for e in first_events["events"]))
  87. control = await self.result(first, "GetStationControl", {"station_id": "S1"})
  88. self.assertEqual(len(control["dimms"]), 24)
  89. native_info = await self.stub.GetSystemInfo(empty_pb2.Empty())
  90. websocket_info = await self.result(second, "GetSystemInfo")
  91. self.assertEqual(native_info.server_id, websocket_info["server_id"])
  92. async def test_saved_plan_run_snapshots_survive_all_wire_readers_and_later_setting_edits(self):
  93. rt = self.bench.station("S1")
  94. rt.device.amt_menu = True
  95. rt.device.mt_duration = .08
  96. async with self.client.ws_connect(self.url) as ws:
  97. # Ordinary editable recipes must not acquire run-only snapshots
  98. # merely because the additive protobuf fields now exist.
  99. recipe = await self.result(ws, "GetRecipe", {"recipe_id": "DEMO-80"})
  100. self.assertNotIn("boot_plan", recipe)
  101. self.assertNotIn("amt_settings", recipe)
  102. recipe.update(name="wire saved-plan fixture", preheat_air_c=25,
  103. preheat_hold_s=0, preheat_timeout_s=5, phase_timeout_s=20,
  104. finish_timeout_s=1)
  105. edited = await self.result(ws, "PutRecipe", {"recipe": recipe,
  106. "expected_revision": recipe["revision"]})
  107. self.assertEqual(edited["revision"], recipe["revision"] + 1)
  108. self.assertNotIn("boot_plan", edited)
  109. self.assertNotIn("amt_settings", edited)
  110. native_recipe = await self.stub.GetRecipe(pb.RecipeKey(recipe_id="DEMO-80"))
  111. ordinary_fields = {field.name for field, value in native_recipe.ListFields()}
  112. self.assertNotIn("boot_plan", ordinary_fields)
  113. self.assertNotIn("amt_settings", ordinary_fields)
  114. overrides = [{"id": "rmt", "mode": "override", "value": "disable"},
  115. {"id": "admt", "mode": "override", "value": "enable"}]
  116. await self.enqueue(ws, "SaveFirmwareSettings", uip_overrides=overrides,
  117. uip_raw_commands=["debuglog 1"], mt_selection={"efi_path": "FS0:\\EFI\\118.efi"})
  118. await self.enqueue(ws, "SaveAmtSettings", settings={"action": "skip", "overrides": [],
  119. "raw_commands": [], "test_command": "amemdiag 1", "exit_after": True})
  120. await self.enqueue(ws, "SaveBootPlan", plan={"preset": "custom", "mt_enabled": True,
  121. "use_in_runs": True, "stages": {"uip1": "manual", "amt": "auto", "uip2": "auto",
  122. "uefi": "auto", "mt": "auto"}})
  123. control = await self.result(ws, "GetStationControl", {"station_id": "S1"})
  124. frozen = {key: control[key] for key in ("firmware_settings", "boot_plan", "amt_settings")}
  125. started = await self.enqueue(ws, "StartRun", recipe_id="DEMO-80", work_order="WO-WIRE",
  126. batch_no="B-WIRE", dimms=[{"sn": "WIRE-SN", "slot": "A1", "cpu": 0, "channel": "A"}])
  127. run_id = started["run_id"] or started["result"]["run_id"]
  128. async def assert_wire_snapshots():
  129. calls = [("GetRun", {"run_id": run_id}),
  130. ("ListRuns", {"station_id": "S1", "limit": 10}),
  131. ("GetRunReport", {"run_id": run_id})]
  132. for method, params in calls:
  133. websocket = await self.result(ws, method, params)
  134. request_cls = pb.ListRunsRequest if method == "ListRuns" else pb.RunKey
  135. native = MessageToDict(await getattr(self.stub, method)(request_cls(**params)),
  136. preserving_proto_field_name=True)
  137. for data in (websocket, native):
  138. run = (next(r for r in data["runs"] if r["run_id"] == run_id) if method == "ListRuns"
  139. else data["run"] if method == "GetRunReport" else data)
  140. self.assertEqual(run["run_id"], run_id)
  141. for key, expected in frozen.items():
  142. self.assertEqual(run["recipe"][key], expected, (method, key))
  143. await assert_wire_snapshots()
  144. # Change the next run's saved choices while this run is waiting in
  145. # UIP. Read APIs must keep the original immutable run configuration.
  146. await self.enqueue(ws, "SaveBootPlan", plan={"preset": "manual", "use_in_runs": False,
  147. "mt_enabled": False})
  148. await self.enqueue(ws, "SaveAmtSettings", settings={"action": "run", "overrides": [],
  149. "raw_commands": [], "test_command": "amemdiag 1", "exit_after": True})
  150. await assert_wire_snapshots()
  151. for cpu in (0, 1):
  152. async with asyncio.timeout(8):
  153. while True:
  154. current = await self.result(ws, "GetStationControl", {"station_id": "S1"})
  155. prompt = current["firmware"].get("console_prompt", {})
  156. if (current["boot_execution"]["state"] == "waiting_user" and
  157. prompt.get("ready") and prompt.get("cpu") == cpu):
  158. break
  159. await asyncio.sleep(.01)
  160. await self.enqueue(ws, "ApplyUipParameters", run_id=run_id,
  161. overrides=overrides, raw_commands=["debuglog 1"])
  162. await self.enqueue(ws, "ContinueUip", run_id=run_id)
  163. await asyncio.wait_for(asyncio.shield(rt.task), 25)
  164. await assert_wire_snapshots()
  165. stored = await self.bench.store.get_run(run_id)
  166. self.assertEqual(stored["state"], "completed", stored)
  167. self.assertTrue(stored["workflow_complete"])
  168. self.assertEqual(stored["tests"]["amt"], "skipped_by_recipe")
  169. self.assertEqual(stored["tests"]["mt"], "completed")
  170. self.assertEqual(stored["supply_state"], "off")
  171. self.assertTrue(set(stored).issubset(pb.Run.DESCRIPTOR.fields_by_name))
  172. self.assertTrue(set(stored["recipe"]).issubset(pb.Recipe.DESCRIPTOR.fields_by_name))
  173. self.assertEqual(stored["evidence"]["boot_execution"]["plan"], frozen["boot_plan"])
  174. async def test_one_connection_allows_out_of_order_responses_by_id(self):
  175. entered, release = asyncio.Event(), asyncio.Event()
  176. original = self.bench.snapshot
  177. async def delayed(station_id):
  178. entered.set()
  179. await release.wait()
  180. return await original(station_id)
  181. self.bench.snapshot = delayed
  182. try:
  183. async with self.client.ws_connect(self.url) as ws:
  184. await ws.send_json(self.request("GetStation", {"station_id": "S1"}, id="slow"))
  185. await asyncio.wait_for(entered.wait(), 2)
  186. await ws.send_json(self.request("GetSystemInfo", id="fast"))
  187. self.assertEqual((await ws.receive_json(timeout=2))["id"], "fast")
  188. release.set()
  189. result = await ws.receive_json(timeout=2)
  190. self.assertEqual(result["id"], "slow")
  191. self.assertEqual(result["result"]["station_id"], "S1")
  192. finally:
  193. release.set()
  194. self.bench.snapshot = original
  195. async def test_disconnect_during_acceptance_does_not_cancel_application_command(self):
  196. entered, release, completed = asyncio.Event(), asyncio.Event(), asyncio.Event()
  197. original = self.bench.enqueue_command
  198. async def delayed(request):
  199. entered.set()
  200. await release.wait()
  201. value = await original(request)
  202. completed.set()
  203. return value
  204. self.bench.enqueue_command = delayed
  205. try:
  206. ws = await self.client.ws_connect(self.url)
  207. await ws.send_json(self.request("EnqueueCommand", {"command_id": "ws-disconnect",
  208. "station_id": "S1", "operator": "ws-test", "method": "StationPower",
  209. "arguments": {"action": "supply_on"}}))
  210. await asyncio.wait_for(entered.wait(), 2)
  211. await ws.close()
  212. release.set()
  213. await asyncio.wait_for(completed.wait(), 2)
  214. async with self.client.ws_connect(self.url) as reconnected:
  215. item = await self.result(reconnected, "GetQueueItem", {"command_id": "ws-disconnect"})
  216. self.assertEqual((await self.done(reconnected, item))["state"], "succeeded")
  217. queue = await self.result(reconnected, "GetQueue", {"station_id": "S1"})
  218. self.assertEqual(len(queue["items"]), 1)
  219. finally:
  220. release.set()
  221. self.bench.enqueue_command = original
  222. async def test_received_command_keeps_running_after_client_disconnect(self):
  223. entered, release = asyncio.Event(), asyncio.Event()
  224. device = self.bench.station("S1").device
  225. original = device.bmc_power
  226. async def delayed(action):
  227. entered.set()
  228. await release.wait()
  229. return await original(action)
  230. device.bmc_power = delayed
  231. try:
  232. ws = await self.client.ws_connect(self.url)
  233. await self.enqueue(ws, "StationPower", action="supply_on")
  234. accepted = await self.result(ws, "EnqueueCommand", {"command_id": "ws-running",
  235. "station_id": "S1", "operator": "ws-test", "method": "StationPower",
  236. "arguments": {"action": "host_on"}})
  237. await asyncio.wait_for(entered.wait(), 2)
  238. await ws.close()
  239. release.set()
  240. async with self.client.ws_connect(self.url) as other:
  241. self.assertEqual((await self.done(other, accepted))["state"], "succeeded")
  242. finally:
  243. release.set()
  244. device.bmc_power = original
  245. async def test_request_errors_do_not_close_socket(self):
  246. cases = [('{', "INVALID_ARGUMENT"), ('[]', "INVALID_ARGUMENT"),
  247. (json.dumps(self.request("GetSystemInfo", v=2)), "INVALID_ARGUMENT"),
  248. (json.dumps(self.request("SmokeUnknownMethod")), "UNIMPLEMENTED"),
  249. (json.dumps(self.request("GetStation", {"wrong_field": "S1"})), "INVALID_ARGUMENT"),
  250. (json.dumps(self.request("GetRun", {"run_id": "missing"})), "NOT_FOUND")]
  251. async with self.client.ws_connect(self.url) as ws:
  252. for raw, code in cases:
  253. await ws.send_str(raw)
  254. error = await ws.receive_json(timeout=2)
  255. self.assertFalse(error["ok"])
  256. self.assertEqual(error["error"]["code"], code)
  257. await ws.send_bytes(b"not JSON")
  258. self.assertEqual((await ws.receive_json(timeout=2))["error"]["code"], "INVALID_ARGUMENT")
  259. self.assertEqual((await self.result(ws, "GetSystemInfo"))["station_count"], 4)
  260. async def test_optional_token_has_same_rules_on_websocket_and_grpc(self):
  261. self.bench.grpc_service.token = "ws-token"
  262. async with self.client.ws_connect(self.url) as browser:
  263. denied = await self.call(browser, "EnqueueCommand", {"command_id": "unauthorized",
  264. "station_id": "S1", "operator": "ws-test", "method": "StationPower",
  265. "arguments": {"action": "supply_on"}})
  266. self.assertEqual(denied["error"]["code"], "UNAUTHENTICATED")
  267. queue = await self.result(browser, "GetQueue", {"station_id": "S1"},
  268. authorization="Bearer ws-token")
  269. self.assertEqual(queue["items"], [])
  270. async with self.client.ws_connect(self.url, headers={"Authorization": "Bearer ws-token"}) as qt:
  271. self.assertEqual((await self.result(qt, "GetSystemInfo"))["station_count"], 4)
  272. bad = await self.call(qt, "GetSystemInfo", authorization="Bearer wrong")
  273. self.assertEqual(bad["error"]["code"], "UNAUTHENTICATED")
  274. self.assertEqual((await self.result(qt, "GetSystemInfo"))["station_count"], 4)
  275. with self.assertRaises(grpc.aio.AioRpcError) as caught:
  276. await self.stub.GetSystemInfo(empty_pb2.Empty())
  277. self.assertEqual(caught.exception.code(), grpc.StatusCode.UNAUTHENTICATED)
  278. info = await self.stub.GetSystemInfo(empty_pb2.Empty(), metadata=(("authorization", "Bearer ws-token"),))
  279. self.assertEqual(info.station_count, 4)
  280. async def test_console_bytes_and_offsets_match_existing_wire_conventions(self):
  281. async with self.client.ws_connect(self.url) as ws:
  282. await self.enqueue(ws, "StationPower", action="supply_on")
  283. await self.enqueue(ws, "SetDiagnosticSol", action="open")
  284. await self.enqueue(ws, "StationPower", action="host_on")
  285. async with asyncio.timeout(3):
  286. while True:
  287. diagnostic = await self.result(ws, "GetDiagnostic", {"station_id": "S1"})
  288. if diagnostic["phase"] == "uip":
  289. break
  290. await asyncio.sleep(.01)
  291. session = diagnostic["session_id"]
  292. # Exercise the old WriteDiagnosticSol API too, not only the queue.
  293. command = await self.result(ws, "WriteDiagnosticSol", {"command_id": "ws-bytes",
  294. "station_id": "S1", "operator": "ws-test", "session_id": session,
  295. "data": base64.b64encode(b"help\r").decode()})
  296. async with asyncio.timeout(3):
  297. while command["state"] not in TERMINAL:
  298. await asyncio.sleep(.01)
  299. command = await self.result(ws, "GetCommand", {"command_id": "ws-bytes"})
  300. self.assertEqual(command["state"], "succeeded")
  301. self.assertEqual(self.bench.station("S1").device.sent_commands, [b"help\r"])
  302. chunk = await self.result(ws, "ReadDiagnosticSol", {"station_id": "S1", "session_id": session,
  303. "offset": "0", "max_bytes": 65536})
  304. self.assertIn(b"CxmtDdrTest", base64.b64decode(chunk["data"]))
  305. self.assertIsInstance(chunk["next_offset"], str)
  306. self.assertGreater(int(chunk["total_bytes"]), 0)