|
| 1 | +"""Named Pipe client for the RevitDevTool bridge. |
| 2 | +
|
| 3 | +Protocol: ``[4-byte LE body length][UTF-8 JSON body]`` |
| 4 | +Matches ``RevitDevTool.McpParser.Models.BridgePipeConnection``. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import struct |
| 11 | +import time |
| 12 | +from typing import Any |
| 13 | + |
| 14 | +from .constants import ( |
| 15 | + BRIDGE_METHOD_TESTS_EXECUTE, |
| 16 | + BRIDGE_MSG_TYPE_NOTIFICATION, |
| 17 | + DEFAULT_CONNECT_TIMEOUT_MS, |
| 18 | + DEFAULT_TEST_TIMEOUT_S, |
| 19 | +) |
| 20 | +from .models import BridgeRequest, BridgeResponse, TestOutcome, TestRequest, TestResult |
| 21 | + |
| 22 | +_MAX_FRAME_SIZE = 16 * 1024 * 1024 |
| 23 | +_HEADER_FMT = "<I" |
| 24 | +_HEADER_LEN = struct.calcsize(_HEADER_FMT) |
| 25 | + |
| 26 | + |
| 27 | +class RevitBridge: |
| 28 | + """Synchronous Named Pipe client for the RevitDevTool bridge.""" |
| 29 | + |
| 30 | + def __init__(self, pipe_name: str, *, connect_timeout_ms: int = DEFAULT_CONNECT_TIMEOUT_MS) -> None: |
| 31 | + self._pipe_name = pipe_name |
| 32 | + self._connect_timeout_ms = connect_timeout_ms |
| 33 | + self._handle: Any = None |
| 34 | + |
| 35 | + def connect(self) -> None: |
| 36 | + import win32file # type: ignore[import-untyped] |
| 37 | + import win32pipe # type: ignore[import-untyped] |
| 38 | + |
| 39 | + pipe_path = rf"\\.\pipe\{self._pipe_name}" |
| 40 | + deadline = time.monotonic() + self._connect_timeout_ms / 1000.0 |
| 41 | + |
| 42 | + while True: |
| 43 | + try: |
| 44 | + self._handle = win32file.CreateFile( |
| 45 | + pipe_path, |
| 46 | + win32file.GENERIC_READ | win32file.GENERIC_WRITE, |
| 47 | + 0, None, |
| 48 | + win32file.OPEN_EXISTING, 0, None, |
| 49 | + ) |
| 50 | + win32pipe.SetNamedPipeHandleState( |
| 51 | + self._handle, win32pipe.PIPE_READMODE_BYTE, None, None, |
| 52 | + ) |
| 53 | + return |
| 54 | + except Exception: |
| 55 | + if time.monotonic() >= deadline: |
| 56 | + raise ConnectionError( |
| 57 | + f"Cannot connect to pipe '{self._pipe_name}' " |
| 58 | + f"within {self._connect_timeout_ms}ms" |
| 59 | + ) |
| 60 | + time.sleep(0.2) |
| 61 | + |
| 62 | + def disconnect(self) -> None: |
| 63 | + handle, self._handle = self._handle, None |
| 64 | + if handle is None: |
| 65 | + return |
| 66 | + import win32file # type: ignore[import-untyped] |
| 67 | + |
| 68 | + try: |
| 69 | + win32file.CloseHandle(handle) |
| 70 | + except Exception: # noqa: BLE001 |
| 71 | + pass |
| 72 | + |
| 73 | + @property |
| 74 | + def connected(self) -> bool: |
| 75 | + return self._handle is not None |
| 76 | + |
| 77 | + def execute_test(self, request: TestRequest, *, timeout_s: float = DEFAULT_TEST_TIMEOUT_S) -> TestResult: |
| 78 | + response = self._request( |
| 79 | + BridgeRequest(method=BRIDGE_METHOD_TESTS_EXECUTE, params=request.to_bridge_params()), |
| 80 | + timeout_s, |
| 81 | + ) |
| 82 | + if response.is_error: |
| 83 | + return TestResult(outcome=TestOutcome.ERROR, message=response.error_message) |
| 84 | + if isinstance(response.result, dict): |
| 85 | + return TestResult.from_dict(response.result) |
| 86 | + return TestResult(outcome=TestOutcome.ERROR, message=f"Unexpected response: {response.result}") |
| 87 | + |
| 88 | + def _request(self, req: BridgeRequest, timeout_s: float) -> BridgeResponse: |
| 89 | + self._write_frame(req.to_json_bytes()) |
| 90 | + deadline = time.monotonic() + timeout_s |
| 91 | + while True: |
| 92 | + remaining = deadline - time.monotonic() |
| 93 | + if remaining <= 0: |
| 94 | + raise TimeoutError(f"Timed out waiting for response to {req.id}") |
| 95 | + data = self._read_frame(remaining) |
| 96 | + parsed = json.loads(data) |
| 97 | + if parsed.get("type") == BRIDGE_MSG_TYPE_NOTIFICATION: |
| 98 | + continue |
| 99 | + resp = BridgeResponse.from_json(parsed) |
| 100 | + if resp.id == req.id: |
| 101 | + return resp |
| 102 | + |
| 103 | + def _write_frame(self, body: bytes) -> None: |
| 104 | + import win32file # type: ignore[import-untyped] |
| 105 | + |
| 106 | + win32file.WriteFile(self._handle, struct.pack(_HEADER_FMT, len(body)) + body) |
| 107 | + |
| 108 | + def _read_frame(self, timeout_s: float) -> bytes: |
| 109 | + header = self._read_exact(_HEADER_LEN, timeout_s) |
| 110 | + (body_len,) = struct.unpack(_HEADER_FMT, header) |
| 111 | + if body_len <= 0 or body_len > _MAX_FRAME_SIZE: |
| 112 | + raise RuntimeError(f"Invalid frame length: {body_len}") |
| 113 | + return self._read_exact(body_len, timeout_s) |
| 114 | + |
| 115 | + def _read_exact(self, count: int, timeout_s: float) -> bytes: |
| 116 | + import win32file # type: ignore[import-untyped] |
| 117 | + |
| 118 | + buf = bytearray() |
| 119 | + deadline = time.monotonic() + timeout_s |
| 120 | + while len(buf) < count: |
| 121 | + if time.monotonic() >= deadline: |
| 122 | + raise TimeoutError(f"Timed out reading {count} bytes (got {len(buf)})") |
| 123 | + _, data = win32file.ReadFile(self._handle, count - len(buf)) |
| 124 | + if not data: |
| 125 | + raise ConnectionError("Pipe closed while reading") |
| 126 | + buf.extend(data) |
| 127 | + return bytes(buf) |
0 commit comments