|
| 1 | +# Copyright 2025 The Chromium Authors |
| 2 | +# Use of this source code is governed by a BSD-style license that can be |
| 3 | +# found in the LICENSE file. |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import json |
| 8 | +import logging |
| 9 | +from typing import TYPE_CHECKING, Any |
| 10 | + |
| 11 | +import websocket |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from crossbench.plt.base import Platform |
| 15 | + |
| 16 | + |
| 17 | +class DevToolsClient: |
| 18 | + """Manages communication with the Chrome DevTools Protocol.""" |
| 19 | + |
| 20 | + def __init__(self, |
| 21 | + platform: Platform, |
| 22 | + requested_local_port: int = 0, |
| 23 | + remote_devtools_identifier: str = "chrome_devtools_remote"): |
| 24 | + self._platform: Platform = platform |
| 25 | + self._requested_local_port: int = requested_local_port |
| 26 | + self._remote_devtools_identifier: str = remote_devtools_identifier |
| 27 | + self._ws: websocket.WebSocket | None = None |
| 28 | + self._devtools_port: int = 0 |
| 29 | + |
| 30 | + def connect(self) -> None: |
| 31 | + """Establishes a WebSocket connection to the DevTools service.""" |
| 32 | + if self._ws and self._ws.connected: |
| 33 | + return |
| 34 | + try: |
| 35 | + self._devtools_port = self._platform.forward_devtools_port( |
| 36 | + local_port=self._requested_local_port, |
| 37 | + remote_identifier=self._remote_devtools_identifier) |
| 38 | + self._ws = websocket.WebSocket() |
| 39 | + self._ws.connect( |
| 40 | + f"ws://localhost:{self._devtools_port}/devtools/browser/") |
| 41 | + logging.debug("DevTools connected: ws://localhost:%s/devtools/browser/", |
| 42 | + self._devtools_port) |
| 43 | + except (websocket.WebSocketException, ConnectionRefusedError, |
| 44 | + TimeoutError) as e: |
| 45 | + logging.error("DevTools connection error: %s", e) |
| 46 | + self._disconnect_internal() |
| 47 | + raise |
| 48 | + except Exception as e: |
| 49 | + logging.error("Unexpected error during DevTools connection: %s", e) |
| 50 | + self._disconnect_internal() |
| 51 | + raise |
| 52 | + |
| 53 | + def _disconnect_internal(self) -> None: |
| 54 | + if self._ws and self._ws.connected: |
| 55 | + try: |
| 56 | + self._ws.close() |
| 57 | + except websocket.WebSocketException as e: |
| 58 | + logging.warning("Error closing DevTools WebSocket: %s", e) |
| 59 | + self._ws = None |
| 60 | + if self._devtools_port: |
| 61 | + try: |
| 62 | + self._platform.stop_port_forward(self._devtools_port) |
| 63 | + except Exception as e: # pylint: disable=broad-except |
| 64 | + # Best effort to remove forwarding, log if it fails but don't crash |
| 65 | + logging.warning( |
| 66 | + "Error removing DevTools port forwarding for port %s: %s", |
| 67 | + self._devtools_port, e) |
| 68 | + self._devtools_port = 0 |
| 69 | + |
| 70 | + def disconnect(self) -> None: |
| 71 | + """Closes the WebSocket connection and removes port forwarding.""" |
| 72 | + self._disconnect_internal() |
| 73 | + logging.debug("DevTools disconnected") |
| 74 | + |
| 75 | + def send_command(self, command_payload: dict[str, Any]) -> bool: |
| 76 | + """Sends a command to DevTools and checks the response ID. |
| 77 | +
|
| 78 | + Args: |
| 79 | + command_payload: The command payload to send. Must include an 'id'. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + True if the command was sent successfully and the response ID matches, |
| 83 | + False otherwise. |
| 84 | + """ |
| 85 | + if not self._ws or not self._ws.connected: |
| 86 | + logging.error("DevTools is not connected. Cannot send command.") |
| 87 | + return False |
| 88 | + |
| 89 | + expected_id = command_payload.get("id") |
| 90 | + if expected_id is None: |
| 91 | + logging.error("DevTools command requires an 'id' in the payload.") |
| 92 | + return False |
| 93 | + |
| 94 | + try: |
| 95 | + self._ws.send(json.dumps(command_payload).encode("utf-8")) |
| 96 | + data = self._ws.recv() |
| 97 | + response = json.loads(data) |
| 98 | + return response.get("id") == expected_id |
| 99 | + except (websocket.WebSocketException, ConnectionRefusedError, |
| 100 | + TimeoutError) as e: |
| 101 | + logging.error("DevTools communication error: %s", e) |
| 102 | + return False |
| 103 | + except json.JSONDecodeError as e: |
| 104 | + logging.error("Error decoding JSON response from DevTools: %s", e) |
| 105 | + return False |
| 106 | + |
| 107 | + def __enter__(self) -> DevToolsClient: |
| 108 | + self.connect() |
| 109 | + return self |
| 110 | + |
| 111 | + def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 112 | + self.disconnect() |
0 commit comments