Handle a message from Unity
(
self,
instance: UnityInstance,
msg: dict[str, Any],
)
| 296 | await self.registry.disconnect_with_grace_period(instance_id, self.reload_grace_period_ms) |
| 297 | |
| 298 | async def _handle_unity_message( |
| 299 | self, |
| 300 | instance: UnityInstance, |
| 301 | msg: dict[str, Any], |
| 302 | ) -> None: |
| 303 | """Handle a message from Unity""" |
| 304 | msg_type = msg.get("type") |
| 305 | instance.update_heartbeat() |
| 306 | |
| 307 | if msg_type == MessageType.STATUS.value: |
| 308 | status_str = msg.get("status", "") |
| 309 | detail = _sanitize_detail(msg.get("detail")) |
| 310 | try: |
| 311 | status = InstanceStatus(status_str) |
| 312 | old_status = instance.status |
| 313 | self.registry.update_status(instance.instance_id, status, detail) |
| 314 | # Process queued commands when Unity transitions from BUSY to READY |
| 315 | if old_status == InstanceStatus.BUSY and status == InstanceStatus.READY: |
| 316 | await self._process_queue(instance) |
| 317 | except ValueError: |
| 318 | logger.warning("Unknown status: %s", status_str) |
| 319 | |
| 320 | elif msg_type == MessageType.COMMAND_RESULT.value: |
| 321 | request_id = msg.get("id", "") |
| 322 | logger.info(f"COMMAND_RESULT received: id={request_id}") |
| 323 | logger.info(f"Pending commands: {list(self._pending_commands.keys())}") |
| 324 | if request_id in self._pending_commands: |
| 325 | future = self._pending_commands.pop(request_id) |
| 326 | if not future.done(): |
| 327 | logger.info(f"Resolving command result for {request_id}") |
| 328 | future.set_result(msg) |
| 329 | else: |
| 330 | # Late result (already timed out) |
| 331 | logger.warning(f"Ignoring late COMMAND_RESULT for {request_id} (not in pending)") |
| 332 | |
| 333 | elif msg_type == MessageType.PONG.value: |
| 334 | # Heartbeat response - signal the waiting heartbeat loop |
| 335 | if instance.instance_id in self._pending_pongs: |
| 336 | self._pending_pongs[instance.instance_id].set() |
| 337 | logger.debug(f"PONG received from {instance.instance_id}") |
| 338 | |
| 339 | else: |
| 340 | logger.warning(f"Unknown Unity message type: {msg_type}") |
| 341 | |
| 342 | async def _heartbeat_loop(self, instance_id: str) -> None: |
| 343 | """ |
no test coverage detected