|
| 1 | +# Licensed to the Software Freedom Conservancy (SFC) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The SFC licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | + |
| 19 | +"""The event side of the generated BiDi protocol layer. |
| 20 | +
|
| 21 | +Hand-written (not generated). An :class:`EventDispatcher` holds the listeners |
| 22 | +added through the generated ``add_<event>_listener`` methods and invokes each |
| 23 | +one with the typed payloads of its event. Listening is local: nothing here sends |
| 24 | +a command, so the caller subscribes with ``session.subscribe`` itself. |
| 25 | +
|
| 26 | +This is internal, unsupported implementation. See |
| 27 | +https://www.selenium.dev/documentation/warnings/bidi-implementation/ |
| 28 | +""" |
| 29 | + |
| 30 | +from __future__ import annotations |
| 31 | + |
| 32 | +import itertools |
| 33 | +import logging |
| 34 | +import threading |
| 35 | +from collections.abc import Callable |
| 36 | +from typing import Any |
| 37 | + |
| 38 | +from selenium.common.exceptions import WebDriverException |
| 39 | +from selenium.webdriver.common._bidi.serialization import BiDiSerializationError |
| 40 | + |
| 41 | +logger = logging.getLogger(__name__) |
| 42 | + |
| 43 | + |
| 44 | +class _Listener: |
| 45 | + """Invoked with each payload on a thread of its own, without waiting for earlier invocations.""" |
| 46 | + |
| 47 | + def __init__(self, name: str, event: str, payload_type: Any, listener: Callable[[Any], Any]): |
| 48 | + self.name = name |
| 49 | + self.event = event |
| 50 | + self.payload_type = payload_type |
| 51 | + self._listener = listener |
| 52 | + self._active = True |
| 53 | + |
| 54 | + def dispatch(self, payload: Any) -> None: |
| 55 | + threading.Thread(target=self._invoke, args=(payload,), name=self.name, daemon=True).start() |
| 56 | + |
| 57 | + def deactivate(self) -> None: |
| 58 | + # Not joined: the caller may be this listener itself, removing itself or quitting the driver. |
| 59 | + self._active = False |
| 60 | + |
| 61 | + def _invoke(self, payload: Any) -> None: |
| 62 | + if not self._active: |
| 63 | + return |
| 64 | + try: |
| 65 | + self._listener(payload) |
| 66 | + # Nothing above a listener's thread can handle what escapes it, and pytest.fail() is not an Exception. |
| 67 | + except BaseException: |
| 68 | + logger.exception("A listener for %s raised", self.event) |
| 69 | + |
| 70 | + |
| 71 | +class EventDispatcher: |
| 72 | + """Holds the event listeners of one BiDi connection and runs them. |
| 73 | +
|
| 74 | + The first :class:`Transport` to add a listener attaches one to the connection, and |
| 75 | + every other transport on that connection reaches the same one, so a listener added |
| 76 | + through one domain instance can be removed through any other. |
| 77 | + """ |
| 78 | + |
| 79 | + def __init__(self) -> None: |
| 80 | + self._listeners: dict[str, _Listener] = {} |
| 81 | + self._ids = itertools.count(1) |
| 82 | + self._lock = threading.Lock() |
| 83 | + self._closed = False |
| 84 | + |
| 85 | + def add_listener(self, event: str, payload_type: Any, listener: Callable[[Any], Any]) -> str: |
| 86 | + if not callable(listener): |
| 87 | + raise TypeError("a callable is required to listen for an event") |
| 88 | + with self._lock: |
| 89 | + if self._closed: |
| 90 | + raise WebDriverException("The BiDi connection is closed") |
| 91 | + listener_id = f"{event}#{next(self._ids)}" |
| 92 | + self._listeners[listener_id] = _Listener(f"bidi-listener-{listener_id}", event, payload_type, listener) |
| 93 | + return listener_id |
| 94 | + |
| 95 | + def remove_listener(self, listener_id: str) -> None: |
| 96 | + with self._lock: |
| 97 | + removed = self._listeners.pop(listener_id, None) |
| 98 | + if removed is not None: |
| 99 | + removed.deactivate() |
| 100 | + |
| 101 | + def receive(self, method: str, params: dict[str, Any]) -> None: |
| 102 | + """Hand a payload to each listener of its event; runs on the socket's reader thread, so it never waits.""" |
| 103 | + with self._lock: |
| 104 | + listeners = [listener for listener in self._listeners.values() if listener.event == method] |
| 105 | + if not listeners: |
| 106 | + return |
| 107 | + payload_type = listeners[0].payload_type |
| 108 | + try: |
| 109 | + payload = params if payload_type is None else payload_type.from_json(params) |
| 110 | + except BiDiSerializationError as e: |
| 111 | + logger.error("Dropped a %s payload that failed validation: %s", method, e) |
| 112 | + return |
| 113 | + for listener in listeners: |
| 114 | + listener.dispatch(payload) |
| 115 | + |
| 116 | + def close(self) -> None: |
| 117 | + with self._lock: |
| 118 | + self._closed = True |
| 119 | + listeners, self._listeners = list(self._listeners.values()), {} |
| 120 | + for listener in listeners: |
| 121 | + listener.deactivate() |
0 commit comments