|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Port of the channel proxy in packages/playwright-core/src/client/channelOwner.ts.""" |
| 16 | + |
| 17 | +import asyncio |
| 18 | +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple |
| 19 | + |
| 20 | +from pyee.asyncio import AsyncIOEventEmitter |
| 21 | + |
| 22 | +if TYPE_CHECKING: # pragma: no cover |
| 23 | + from playwright._impl._connection import ChannelOwner, Connection |
| 24 | + |
| 25 | + |
| 26 | +class Channel: |
| 27 | + """The base of the generated channels in _protocol_channels.py.""" |
| 28 | + |
| 29 | + def __init__(self, connection: "Connection", object: "ChannelOwner") -> None: |
| 30 | + self._connection = connection |
| 31 | + self._guid = object._guid |
| 32 | + self._object = object |
| 33 | + self._emitter = AsyncIOEventEmitter() |
| 34 | + self._emitter.on( |
| 35 | + "error", lambda exc: self._connection._on_event_listener_error(exc) |
| 36 | + ) |
| 37 | + # (event, handler) -> the wrappers registered for it, in order. |
| 38 | + self._event_listeners: Dict[Tuple[str, Any], List[Callable[[Any], Any]]] = {} |
| 39 | + |
| 40 | + async def _call( |
| 41 | + self, method: str, params: Mapping[str, Any], timeout: float |
| 42 | + ) -> Dict[str, Any]: |
| 43 | + """Sends a command and returns its result, {} when it has none.""" |
| 44 | + result = await self._connection.wrap_api_call( |
| 45 | + lambda: self._inner_send(method, _filter_none(params), timeout) |
| 46 | + ) |
| 47 | + return result or {} |
| 48 | + |
| 49 | + def _add_event_listener( |
| 50 | + self, event: str, handler: Any, listener: Callable[[Any], Any] |
| 51 | + ) -> None: |
| 52 | + """Registers listener, the wrapper that calls handler with the typed payload. |
| 53 | +
|
| 54 | + A handler can be registered more than once, like on an EventEmitter; |
| 55 | + each off<Event> call removes one registration. |
| 56 | + """ |
| 57 | + self._event_listeners.setdefault((event, handler), []).append(listener) |
| 58 | + self._emitter.on(event, listener) |
| 59 | + |
| 60 | + def _remove_event_listener(self, event: str, handler: Any) -> None: |
| 61 | + listeners = self._event_listeners.get((event, handler)) |
| 62 | + if not listeners: |
| 63 | + return |
| 64 | + listener = listeners.pop() |
| 65 | + if not listeners: |
| 66 | + del self._event_listeners[(event, handler)] |
| 67 | + self._emitter.remove_listener(event, listener) |
| 68 | + |
| 69 | + def send_no_reply( |
| 70 | + self, |
| 71 | + method: str, |
| 72 | + params: Mapping[str, Any] = None, |
| 73 | + is_internal: bool = False, |
| 74 | + title: str = None, |
| 75 | + ) -> None: |
| 76 | + """Sends a message without waiting for the reply. |
| 77 | +
|
| 78 | + For messages that must go out synchronously, such as __waitInfo__ and |
| 79 | + updateSubscription. |
| 80 | + """ |
| 81 | + self._connection.wrap_api_call_sync( |
| 82 | + lambda: self._connection._send_message_to_server( |
| 83 | + self._object, method, _filter_none(params or {}), 0, True |
| 84 | + ), |
| 85 | + is_internal, |
| 86 | + title, |
| 87 | + ) |
| 88 | + |
| 89 | + async def _inner_send( |
| 90 | + self, method: str, params: Dict[str, Any], timeout: float |
| 91 | + ) -> Optional[Dict[str, Any]]: |
| 92 | + if self._connection._error: |
| 93 | + error = self._connection._error |
| 94 | + self._connection._error = None |
| 95 | + raise error |
| 96 | + callback = self._connection._send_message_to_server( |
| 97 | + self._object, method, params, timeout |
| 98 | + ) |
| 99 | + try: |
| 100 | + done, _ = await asyncio.wait( |
| 101 | + { |
| 102 | + self._connection._transport.on_error_future, |
| 103 | + callback.future, |
| 104 | + }, |
| 105 | + return_when=asyncio.FIRST_COMPLETED, |
| 106 | + ) |
| 107 | + except asyncio.CancelledError as exc: |
| 108 | + await self._connection._abort( |
| 109 | + self._object, |
| 110 | + callback, |
| 111 | + str(exc) or "Task was cancelled", |
| 112 | + ) |
| 113 | + raise |
| 114 | + if not callback.future.done(): |
| 115 | + callback.future.cancel() |
| 116 | + result = next(iter(done)).result() |
| 117 | + if not result: |
| 118 | + return None |
| 119 | + assert isinstance(result, dict) |
| 120 | + return result |
| 121 | + |
| 122 | + |
| 123 | +def _filter_none(d: Mapping) -> Dict: |
| 124 | + result = {} |
| 125 | + for k, v in d.items(): |
| 126 | + if v is None: |
| 127 | + continue |
| 128 | + result[k] = _filter_none(v) if isinstance(v, dict) else v |
| 129 | + return result |
0 commit comments