Skip to content

Commit 2e91cc0

Browse files
authored
[py] add local BiDi event listeners to the low-level modules (#18300)
* [py] generate per-event callback methods in the low-level BiDi layer * [py] add browser tests for the low-level BiDi events * [py] name the payload class in generated BiDi callback docstrings * [py] move the BiDi event tests into their domain test files * [py] let the websocket connection hand events to an optional receiver * [py] give each BiDi event callback its own subscription through a per-connection dispatcher * [py] drop a BiDi callback and look it up in one locked step so concurrent removals unsubscribe once * [py] keep a BiDi callback in dispatch until its unsubscribe is answered and log a refusal instead of raising * [py] scope, type and name the low-level BiDi event listeners as the subscription ADR decides * [py] make BiDi event listeners local with one ordered worker each and leave subscribing to the caller * [py] add sequential and concurrent BiDi listener execution, drain removal and a generic add_listener per the revised event record * [py] take a removed BiDi listener out of dispatch at once and keep only the typed per-event add methods * [py] drain a BiDi listener by joining its threads instead of counting pending payloads * [py] split BiDi listeners by execution mode and bound drain with a timeout * [py] match Ruby BiDi listeners: a thread per payload, no modes or drain, dispatcher attached on first listener * [py] drop the browser test for independent listener removal, which the unit tests cover * [py] let BiDi listener dispatch fail loudly on our own bugs and thread exhaustion, and drop the listener name guard * [py] drop the ordered BiDi listener and its SE_ORDERED_EVENTS toggle * [py] run the BiDi listener unit tests on the connection's real reader thread and drop tests that add no information * [py] type BiDi listener payload types and Domain.EVENT_TYPES so mypy passes * [py] raise a BiDi serialization error for an unhashable union discriminator instead of a TypeError * [py] run the authRequired listener test on Chromium now that the schema accepts its -1 status
1 parent 1a62cfd commit 2e91cc0

19 files changed

Lines changed: 1082 additions & 16 deletions

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ py/selenium/webdriver/common/_bidi/*
7979
!py/selenium/webdriver/common/_bidi/serialization.py
8080
!py/selenium/webdriver/common/_bidi/transport.py
8181
!py/selenium/webdriver/common/_bidi/domain.py
82+
!py/selenium/webdriver/common/_bidi/dispatcher.py
8283
py/selenium/webdriver/common/devtools/**/*
8384
!py/selenium/webdriver/common/devtools/util.py
8485
py/selenium/webdriver/common/bidi-mutation-listener.js

‎py/BUILD.bazel‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -875,7 +875,7 @@ generate_bidi(
875875

876876
# Schema-driven internal BiDi protocol layer: generated at build time from the
877877
# shared BiDi schema into `selenium/webdriver/common/_bidi/`. Only the hand-written
878-
# runtime (serialization/transport/domain) is checked in; the domain modules are
878+
# runtime (serialization/transport/domain/dispatcher) is checked in; the domain modules are
879879
# generated by the rule below and never committed.
880880
generate_bidi_protocol(
881881
name = "create-bidi-protocol-src",
@@ -913,6 +913,7 @@ py_library(
913913
# Listed explicitly, not globbed: a local generate run drops the generated modules here too, and a glob would double them against the rule's outputs.
914914
srcs = [":create-bidi-protocol-src"] + [
915915
"selenium/webdriver/common/_bidi/__init__.py",
916+
"selenium/webdriver/common/_bidi/dispatcher.py",
916917
"selenium/webdriver/common/_bidi/domain.py",
917918
"selenium/webdriver/common/_bidi/serialization.py",
918919
"selenium/webdriver/common/_bidi/transport.py",

‎py/generate_bidi_protocol.py‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ class EventIR:
197197
wire: str
198198
name: str
199199
payload_class: str | None
200+
spec_href: str | None = None
200201

201202

202203
@dataclass
@@ -826,6 +827,7 @@ def build_event(schema: Schema, event: dict) -> EventIR:
826827
wire=event["method"],
827828
name=safe_name(camel_to_snake(event["name"])),
828829
payload_class=type_class_name(payload) if payload else None,
830+
spec_href=event.get("specHref"),
829831
)
830832

831833

@@ -835,6 +837,11 @@ def _guard_same_domain(domain: str, *type_names: str | None) -> None:
835837
raise ValueError(f"{domain}: cross-domain type reference {name!r} not yet supported")
836838

837839

840+
def _listener_method(e: EventIR) -> str:
841+
"""The listener method name a domain class gets for an event."""
842+
return f"add_{e.name}_listener"
843+
844+
838845
def build_module(schema: Schema, domain: str) -> ModuleIR:
839846
schema._pending_refs = set()
840847
records, unions = schema.types_for(domain)
@@ -1043,6 +1050,24 @@ def _emit_command(c: CommandIR) -> list[str]:
10431050
return lines
10441051

10451052

1053+
def _emit_event_listener(e: EventIR) -> list[str]:
1054+
payload = e.payload_class or "dict[str, Any]"
1055+
args = ["self", f"listener: Callable[[{payload}], Any]"]
1056+
lines = [wrap_call(f" def {_listener_method(e)}(", args, ") -> str:", 4)]
1057+
lines.append(f' """Invoke ``listener`` with each {e.wire} payload (internal, unsupported).')
1058+
lines.append("")
1059+
lines.append(f" The listener gets a ``{payload}``; one that fails validation is logged and not delivered.")
1060+
lines.append(" Each payload is invoked on its own thread, without waiting for earlier ones. This sends")
1061+
lines.append(" nothing: payloads arrive once the caller subscribes with ``Session.subscribe``.")
1062+
lines.append(" Returns the id to pass to ``remove_listener``.")
1063+
if e.spec_href:
1064+
lines.append("")
1065+
lines.append(f" See {e.spec_href}")
1066+
lines.append(' """')
1067+
lines.append(f" return self._add_listener({lit(e.wire)}, listener)")
1068+
return lines
1069+
1070+
10461071
def _emit_domain_class(mod: ModuleIR) -> str:
10471072
doc = [' """Internal, unsupported.', "", f" See {BIDI_DOC_URL}"]
10481073
if mod.spec_href:
@@ -1059,13 +1084,16 @@ def _emit_domain_class(mod: ModuleIR) -> str:
10591084
lines.append(" }")
10601085
lines.append(" EVENT_TYPES = {")
10611086
for e in mod.events:
1062-
payload = lit(f"{mod.domain}.{e.payload_class}") if e.payload_class else "None"
1087+
payload = e.payload_class or "None"
10631088
lines.append(f" {lit(e.wire)}: {payload},")
10641089
lines.append(" }")
10651090
body = []
10661091
for c in mod.commands:
10671092
body.append("")
10681093
body.extend(_emit_command(c))
1094+
for e in mod.events:
1095+
body.append("")
1096+
body.extend(_emit_event_listener(e))
10691097
return "\n".join(lines + body)
10701098

10711099

@@ -1094,7 +1122,7 @@ def _imports(mod: ModuleIR) -> list[str]:
10941122
[f.py_type for r in mod.records for f in r.fields]
10951123
+ [p.py_type for c in mod.commands for p in c.params]
10961124
+ [c.result_type for c in mod.commands]
1097-
+ ["dict[str, Any]" if any(r.extensible for r in mod.records) else ""]
1125+
+ ["dict[str, Any]" if any(r.extensible for r in mod.records) or mod.events else ""]
10981126
)
10991127
uses_any = "Any" in text_blob.split() or "Any]" in text_blob or "[Any" in text_blob
11001128

@@ -1117,6 +1145,8 @@ def _imports(mod: ModuleIR) -> list[str]:
11171145
runtime.append("register")
11181146

11191147
lines = ["from __future__ import annotations", ""]
1148+
if mod.events:
1149+
lines.append("from collections.abc import Callable")
11201150
if has_records:
11211151
lines.append("from dataclasses import dataclass, field")
11221152
if mod.enums:

‎py/selenium/webdriver/common/_bidi/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,6 @@
2525

2626
# The domain modules beside this file (network.py, browsing_context.py, ...) are
2727
# generated at build time from the shared BiDi schema by //py:create-bidi-protocol-src
28-
# and are not checked in. Only serialization.py, transport.py, domain.py and this
29-
# __init__.py are hand-written. Regenerate the domain modules locally with:
28+
# and are not checked in. Only serialization.py, transport.py, domain.py, dispatcher.py
29+
# and this __init__.py are hand-written. Regenerate the domain modules locally with:
3030
# bazel run //py:generate-bidi-protocol
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
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()

‎py/selenium/webdriver/common/_bidi/domain.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323

2424
from __future__ import annotations
2525

26-
from typing import Any
26+
from collections.abc import Callable
27+
from typing import Any, ClassVar
2728

2829
from selenium.common.exceptions import WebDriverException
2930
from selenium.webdriver.common._bidi.transport import Transport
@@ -37,6 +38,8 @@ class Domain:
3738
:class:`Transport` for the standalone path.
3839
"""
3940

41+
EVENT_TYPES: ClassVar[dict[str, Any]]
42+
4043
def __init__(self, source: Any) -> None:
4144
if isinstance(source, Transport):
4245
self._transport = source
@@ -52,3 +55,15 @@ def __init__(self, source: Any) -> None:
5255

5356
def _execute(self, cmd: str, params: Any = None, result: Any = None) -> Any:
5457
return self._transport.execute(cmd, params=params, result=result)
58+
59+
def remove_listener(self, listener_id: str) -> None:
60+
"""Stop invoking the listener an ``add_<event>_listener`` method returned ``listener_id`` for.
61+
62+
Internal, unsupported. Local only: the subscription feeding it is left to the caller. Returns at once
63+
without waiting for a running invocation to finish, so a listener may remove itself. Removing an
64+
unknown or removed id does nothing.
65+
"""
66+
self._transport.remove_listener(listener_id)
67+
68+
def _add_listener(self, event: str, listener: Callable[[Any], Any]) -> str:
69+
return self._transport.add_listener(event, self.EVENT_TYPES[event], listener)

‎py/selenium/webdriver/common/_bidi/serialization.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
import logging
3737
import math
3838
import re
39-
from collections.abc import Callable
39+
from collections.abc import Callable, Hashable
4040
from dataclasses import dataclass
4141
from enum import Enum
4242
from importlib import import_module
@@ -677,7 +677,7 @@ def from_json(cls, payload: Any) -> Any:
677677
def _select(cls, payload: dict) -> str | None:
678678
if cls._DISCRIMINATOR is not None and cls._DISCRIMINATOR in payload:
679679
tag = payload[cls._DISCRIMINATOR]
680-
if tag in cls._VARIANTS:
680+
if isinstance(tag, Hashable) and tag in cls._VARIANTS:
681681
return cls._VARIANTS[tag]
682682
for variant, keys in cls._PRESENCE:
683683
if all(key in payload for key in keys):

‎py/selenium/webdriver/common/_bidi/transport.py‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,34 +19,37 @@
1919
2020
Hand-written (not generated). :class:`Transport` serializes a command's params,
2121
sends them over the session websocket, parses the reply into its declared result
22-
type, and exposes the underlying connection for event subscription.
22+
type, and relays event listeners to the connection's dispatcher, which stores them.
2323
2424
This is internal, unsupported implementation. See
2525
https://www.selenium.dev/documentation/warnings/bidi-implementation/
2626
"""
2727

2828
from __future__ import annotations
2929

30+
from collections.abc import Callable
3031
from typing import Any
3132

33+
from selenium.webdriver.common._bidi.dispatcher import EventDispatcher
3234
from selenium.webdriver.common._bidi.errors import exception_for
3335

3436

3537
class Transport:
3638
"""Serializes params, sends over a websocket connection, parses the reply.
3739
3840
Deliberately narrow: it holds only an immutable connection reference (the id
39-
counter and callbacks live on the shared ``WebSocketConnection``). Each domain
40-
wraps the session's connection in its own ``Transport``; all the state that
41-
matters lives on the shared connection, so those transports are equivalent.
41+
counter lives on the shared ``WebSocketConnection``, and event listeners on the
42+
dispatcher attached to it). Each domain wraps the session's connection in its
43+
own ``Transport``; all the state that matters lives on the shared connection,
44+
so those transports are equivalent.
4245
"""
4346

4447
def __init__(self, connection: Any) -> None:
4548
self._connection = connection
4649

4750
@property
4851
def connection(self) -> Any:
49-
"""The underlying websocket, for event subscription (which lives on it, not here)."""
52+
"""The websocket connection this transport sends over."""
5053
return self._connection
5154

5255
def execute(self, cmd: str, params: Any = None, result: Any = None) -> Any:
@@ -56,6 +59,16 @@ def execute(self, cmd: str, params: Any = None, result: Any = None) -> Any:
5659
value = reply["result"]
5760
return result.from_json(value) if result is not None else value
5861

62+
def add_listener(self, event: str, payload_type: Any, listener: Callable[[Any], Any]) -> str:
63+
"""Add ``listener`` for the ``payload_type`` payloads of ``event`` to the connection's dispatcher."""
64+
return self._dispatcher().add_listener(event, payload_type, listener)
65+
66+
def remove_listener(self, listener_id: str) -> None:
67+
self._dispatcher().remove_listener(listener_id)
68+
69+
def _dispatcher(self) -> EventDispatcher:
70+
return self._connection.attach_event_receiver(EventDispatcher)
71+
5972
@staticmethod
6073
def _error(reply: dict) -> Exception:
6174
code = reply["error"]

0 commit comments

Comments
 (0)