From 3617b98c78d22ad598b9aab974bdf571822c223d Mon Sep 17 00:00:00 2001 From: strohganoff Date: Thu, 3 Dec 2026 21:38:12 -0700 Subject: [PATCH] Extract event stream processing from PluginManager Rebase onto semantic identifier types and runtime cleanup. --- pyproject.toml | 1 + streamdeck/command_sender.py | 10 +- streamdeck/event_listener.py | 2 - streamdeck/event_stream_processor.py | 75 +++++++++++ streamdeck/manager.py | 38 ++++-- streamdeck/websocket.py | 123 +++++++++--------- tests/models/test_toml_settings.py | 4 +- tests/plugin_manager/conftest.py | 28 ++-- .../test_command_sender_binding.py | 4 +- tests/plugin_manager/test_plugin_manager.py | 34 ++--- tests/test_command_sender.py | 6 +- tests/test_event_stream_processor.py | 66 ++++++++++ tests/test_websocket.py | 38 +++--- uv.lock | 17 ++- 14 files changed, 300 insertions(+), 146 deletions(-) create mode 100644 streamdeck/event_stream_processor.py create mode 100644 tests/test_event_stream_processor.py diff --git a/pyproject.toml b/pyproject.toml index debb0ab..189dddd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -65,6 +65,7 @@ "pydantic-settings[toml] >= 2.11", "typing-extensions >= 4.14.0", "exceptiongroup >= 1.3.1; python_version < '3.11'", + "taskgroup >= 0.2.2; python_version < '3.11'", ] [project.urls] diff --git a/streamdeck/command_sender.py b/streamdeck/command_sender.py index 7d74f37..0ea7e2a 100644 --- a/streamdeck/command_sender.py +++ b/streamdeck/command_sender.py @@ -48,7 +48,7 @@ async def set_settings(self, context: ActionInstanceIdStr, payload: PluginDefine payload=payload, ) - async def get_settings(self, context: ActionInstanceUUIDStr) -> None: + async def get_settings(self, context: ActionInstanceIdStr) -> None: await self._send_event("getSettings", context=context) async def set_global_settings(self, payload: PluginDefinedData) -> None: @@ -64,14 +64,14 @@ async def get_global_settings(self) -> None: context=self._plugin_registration_uuid, ) - async def open_url(self, context: ActionInstanceUUIDStr, url: str) -> None: + async def open_url(self, context: ActionInstanceIdStr, url: str) -> None: await self._send_event( event="openUrl", context=context, payload={"url": url}, ) - async def log_message(self, context: ActionInstanceUUIDStr, message: str) -> None: + async def log_message(self, context: ActionInstanceIdStr, message: str) -> None: await self._send_event( event="logMessage", context=context, @@ -80,7 +80,7 @@ async def log_message(self, context: ActionInstanceUUIDStr, message: str) -> Non async def set_title( self, - context: ActionInstanceUUIDStr, + context: ActionInstanceIdStr, state: int | None = None, target: Literal["hardware", "software", "both"] | None = None, title: str | None = None, @@ -102,7 +102,7 @@ async def set_title( async def set_image( self, - context: ActionInstanceUUIDStr, + context: ActionInstanceIdStr, image: str, # base64 encoded image, target: Literal["hardware", "software", "both"], state: int, diff --git a/streamdeck/event_listener.py b/streamdeck/event_listener.py index 16d02af..113566a 100644 --- a/streamdeck/event_listener.py +++ b/streamdeck/event_listener.py @@ -24,9 +24,7 @@ from typing_extensions import sentinel - if sys.version_info < (3, 11): - # ExceptionGroup is built in starting with Python 3.11. from exceptiongroup import ExceptionGroup diff --git a/streamdeck/event_stream_processor.py b/streamdeck/event_stream_processor.py new file mode 100644 index 0000000..0451d5a --- /dev/null +++ b/streamdeck/event_stream_processor.py @@ -0,0 +1,75 @@ +"""Process a stream of validated events with sequential dispatch.""" + +from __future__ import annotations + +import asyncio +import sys +from contextlib import aclosing +from typing import TYPE_CHECKING + +from typing_extensions import sentinel + +from streamdeck.models.events import EventBase + + +if sys.version_info >= (3, 11): + from asyncio import TaskGroup +else: + from taskgroup import TaskGroup + + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, Awaitable, Callable + + +_END_DISPATCH = sentinel("_END_DISPATCH") + + +class EventStreamProcessor: + """Read events concurrently with sequential dispatch.""" + + def __init__( + self, + dispatch: Callable[[EventBase], Awaitable[None]], + ) -> None: + self._dispatch = dispatch + + async def _route_events( + self, + events: AsyncGenerator[EventBase, None], + dispatch_queue: asyncio.Queue[object], + ) -> None: + """Queue validated events in stream order.""" + async with aclosing(events): + async for event in events: + await dispatch_queue.put(event) + await dispatch_queue.put(_END_DISPATCH) + + async def _dispatch_events(self, dispatch_queue: asyncio.Queue[object]) -> None: + """Dispatch queued events one at a time, awaiting each handler.""" + while True: + item = await dispatch_queue.get() + + if item is _END_DISPATCH: + return + if not isinstance(item, EventBase): + raise TypeError(f"Unexpected dispatch queue item: {item!r}") + + await self._dispatch(item) + + async def run(self, events: AsyncGenerator[EventBase, None]) -> None: + """Route events concurrently and dispatch them sequentially. + + Raises: + ExceptionGroup: If event routing or dispatch fails. + """ + dispatch_queue: asyncio.Queue[object] = asyncio.Queue() + async with TaskGroup() as tasks: + tasks.create_task( + self._route_events(events, dispatch_queue), + name="plugin-event-router", + ) + tasks.create_task( + self._dispatch_events(dispatch_queue), + name="plugin-event-dispatcher", + ) diff --git a/streamdeck/manager.py b/streamdeck/manager.py index cddbe49..f2e40e0 100644 --- a/streamdeck/manager.py +++ b/streamdeck/manager.py @@ -1,7 +1,7 @@ from __future__ import annotations import inspect -from contextlib import aclosing +import sys from logging import getLogger from typing import TYPE_CHECKING @@ -13,10 +13,14 @@ from streamdeck.event_handlers.registry import HandlersRegistry from streamdeck.event_handlers.scopes import ScopeName, scope_for_event from streamdeck.event_listener import EventListener, EventListenerManager +from streamdeck.event_stream_processor import EventStreamProcessor from streamdeck.models.events.adapter import EventAdapter from streamdeck.models.events.common import ActionInstanceEventMixin from streamdeck.utils.logging import configure_streamdeck_logger -from streamdeck.websocket import WebSocketClient +from streamdeck.websocket import WebSocketEventListener, WebSocketTransport + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup if TYPE_CHECKING: @@ -32,7 +36,6 @@ # TODO: Fix this up to push to a log in the apropos directory and filename. logger = getLogger("streamdeck.manager") - class PluginManager: """Manages plugin actions and communicates with a WebSocket server to handle events.""" @@ -183,10 +186,10 @@ async def run(self) -> None: Raises: TypeError: If a registered handler requires a parameter with no stored injectable value. - ExceptionGroup: If one or more ordinary event listener cleanup operations fail. + ExceptionGroup: If event processing or runtime cleanup fails. """ - client = WebSocketClient(port=self._port) - command_sender = StreamDeckCommandSender(client, plugin_registration_uuid=self._registration_uuid) + transport = WebSocketTransport(port=self._port) + command_sender = StreamDeckCommandSender(transport, plugin_registration_uuid=self._registration_uuid) self._injectable_handler_param_store.register( "command_sender", lambda _event_data: command_sender, @@ -196,15 +199,15 @@ async def run(self) -> None: primary_error: BaseException | None = None try: - async with client: - # Register the WebSocketClient as an event listener, so we can receive Stream Deck events. - self.register_event_listener(client) + async with transport: + # Register a WebSocketEventListener, so we can receive Stream Deck events. + self.register_event_listener(WebSocketEventListener(transport)) await command_sender.send_action_registration(register_event=self._register_event) - async with aclosing(self._stream_event_data()) as event_data_stream: - async for data in event_data_stream: - await self._dispatch_event(data) + await EventStreamProcessor( + dispatch=self._dispatch_event, + ).run(self._stream_event_data()) logger.info("PluginManager has stopped processing events.") except BaseException as exc: @@ -213,6 +216,15 @@ async def run(self) -> None: finally: try: await self._event_listener_manager.stop() - except BaseException: + except BaseException as cleanup_error: if primary_error is None: raise + if isinstance(primary_error, Exception) and isinstance(cleanup_error, Exception): + raise ExceptionGroup( + "Plugin runtime and listener cleanup both failed", + [primary_error, cleanup_error], + ) from None + logger.exception( + "Listener cleanup failed while preserving the active %s", + type(primary_error).__name__, + ) diff --git a/streamdeck/websocket.py b/streamdeck/websocket.py index 2b1d39c..13f86c6 100644 --- a/streamdeck/websocket.py +++ b/streamdeck/websocket.py @@ -1,18 +1,9 @@ -"""Connect to Stream Deck's WebSocket server and send or receive events. - -`WebSocketClient` implements :class:`~streamdeck.event_listener.EventListener`: -its async `listen()` iterator yields inbound messages to the -`EventListenerManager`, which merges them with messages from custom -listeners. The client is the sole reader of the Stream Deck connection. - -Outbound commands use the same active connection through `send_event()`. -The `StreamDeckCommandSender` builds command payloads and delegates sending -to this client; connection setup and cleanup remain owned by the runtime via -the client's async context manager. -""" +"""Async WebSocket transport and Stream Deck event listener.""" + from __future__ import annotations import json +import sys from logging import getLogger from typing import TYPE_CHECKING @@ -24,6 +15,9 @@ WebSocketException, ) +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + from streamdeck.event_listener import EventListener, StopStreaming from streamdeck.models.events import DEFAULT_EVENT_MODELS @@ -43,74 +37,48 @@ logger = getLogger("streamdeck.websocket") -class WebSocketClient(EventListener): - """The sole reader and async sender for the active Stream Deck connection.""" - - event_models: ClassVar[list[type[EventBase]]] = DEFAULT_EVENT_MODELS +class WebSocketTransport: + """Own the connection and provide raw asynchronous send and receive calls.""" def __init__(self, port: int) -> None: - """Initialize the client for the Stream Deck WebSocket server. - - The connection is established later by :meth:`start`, so constructing - a client does not perform network I/O. - - Args: - port: The local port number provided by Stream Deck for the - WebSocket connection. - """ + """Initialize a transport for the local Stream Deck WebSocket server.""" self._port = port - self._client: ClientConnection | None = None + self._connection: ClientConnection | None = None async def send_event(self, data: dict[str, JsonValue]) -> None: """Serialize and send a command through the active connection.""" - if self._client is None: + if self._connection is None: raise ValueError("WebSocket connection not established yet.") - await self._client.send(json.dumps(data)) + await self._connection.send(json.dumps(data)) - async def listen(self) -> AsyncIterator[str | bytes]: - """Yield inbound frames; this is the connection's only receive loop.""" - if self._client is None: - raise ValueError("WebSocket connection not established yet.") + async def receive(self) -> str | bytes: + """Receive one frame from the connection. - try: - while True: - yield await self._client.recv() - except WebSocketException as exc: - if isinstance(exc, ConnectionClosedOK): - logger.debug("Connection was closed normally, stopping the client.") - elif isinstance(exc, ConnectionClosedError): - logger.exception("Connection was terminated with an error.") - elif isinstance(exc, ConnectionClosed): - logger.exception("Connection was already closed.") - else: - logger.exception("Connection closed due to an unexpected WebSocket error.") + The WebSocket event listener is the sole caller of this method. + """ + if self._connection is None: + raise ValueError("WebSocket connection not established yet.") - raise StopStreaming from None - except Exception: - logger.exception("Unexpected error while receiving from Stream Deck; stopping the runtime.") - raise StopStreaming from None + return await self._connection.recv() async def start(self) -> None: """Establish the Stream Deck connection.""" try: - self._client = await connect(uri=f"ws://localhost:{self._port}") + self._connection = await connect(uri=f"ws://localhost:{self._port}") except ConnectionRefusedError: logger.exception("Failed to connect to the WebSocket server. Make sure Stream Deck is running.") raise async def stop(self) -> None: """Close the connection if it was established.""" - if self._client is not None: - await self._client.close() - self._client = None + if self._connection is not None: + connection = self._connection + self._connection = None + await connection.close() async def __aenter__(self) -> Self: - """Open the connection and return this client for an `async with` block. - - Returns: - Self: The WebSocketClient instance after connecting to the WebSocket server. - """ + """Open the connection and return the transport.""" await self.start() return self @@ -123,11 +91,48 @@ async def __aexit__( """Close the connection, preserving any exception from the block.""" try: await self.stop() - except BaseException: + except BaseException as cleanup_error: if exc_val is None: raise + if isinstance(exc_val, Exception) and isinstance(cleanup_error, Exception): + raise ExceptionGroup( + "WebSocket runtime and connection cleanup both failed", + [exc_val, cleanup_error], + ) from None logger.exception( - "Failed to close WebSocket while handling %s", + "Failed to close WebSocket while handling %s; preserving the active exception", exc_type.__name__ if exc_type is not None else "an exception", ) return False + + +class WebSocketEventListener(EventListener): + """Yield Stream Deck messages received by a WebSocket transport.""" + + event_models: ClassVar[list[type[EventBase]]] = DEFAULT_EVENT_MODELS + + def __init__(self, transport: WebSocketTransport) -> None: + self._transport = transport + + async def listen(self) -> AsyncIterator[str | bytes]: + """Yield frames from the transport's single receive loop.""" + try: + while True: + yield await self._transport.receive() + except WebSocketException as exc: + if isinstance(exc, ConnectionClosedOK): + logger.debug("Connection was closed normally, stopping the listener.") + elif isinstance(exc, ConnectionClosedError): + logger.exception("Connection was terminated with an error.") + elif isinstance(exc, ConnectionClosed): + logger.exception("Connection was already closed.") + else: + logger.exception("Connection closed due to an unexpected WebSocket error.") + + raise StopStreaming from None + except Exception: + logger.exception("Unexpected error while receiving from Stream Deck; stopping the runtime.") + raise StopStreaming from None + + async def stop(self) -> None: + """The runtime owns the transport; listener tasks are stopped by cancellation.""" diff --git a/tests/models/test_toml_settings.py b/tests/models/test_toml_settings.py index f1f8b2e..53651ca 100644 --- a/tests/models/test_toml_settings.py +++ b/tests/models/test_toml_settings.py @@ -90,8 +90,8 @@ def test_cli_listener_modules_replace_toml_before_import(tmp_path, flag): def test_repeated_listener_aliases_combine_in_one_override(tmp_path): - from streamdeck.websocket import WebSocketClient from tests.data.dummy_event_listener import DummyEventListener + from streamdeck.websocket import WebSocketEventListener write_config( tmp_path, @@ -109,7 +109,7 @@ def test_repeated_listener_aliases_combine_in_one_override(tmp_path): "tests.data.dummy_event_listener", "streamdeck.websocket", ] - assert config.event_listeners == [DummyEventListener, WebSocketClient] + assert config.event_listeners == [DummyEventListener, WebSocketEventListener] def test_cli_listener_override_retains_toml_actions(tmp_path): diff --git a/tests/plugin_manager/conftest.py b/tests/plugin_manager/conftest.py index 5856b70..ea10857 100644 --- a/tests/plugin_manager/conftest.py +++ b/tests/plugin_manager/conftest.py @@ -7,7 +7,7 @@ from streamdeck.event_listener import EventListenerManager from streamdeck.manager import PluginManager -from streamdeck.websocket import WebSocketClient +from streamdeck.websocket import WebSocketTransport from tests.test_utils.fake_event_factories import KeyDownEventFactory @@ -49,25 +49,13 @@ def mock_streamdeck_logger(monkeypatch: pytest.MonkeyPatch) -> None: @pytest.fixture -def patch_websocket_client(monkeypatch: pytest.MonkeyPatch) -> Mock: - """Fixture that uses pytest's MonkeyPatch to mock WebSocketClient for the PluginManager run method. - - The mocked WebSocketClient can be given fake event messages to yield when listen() is called: - ```patch_websocket_client.listen.return_value = [fake_event_json1, fake_event_json2, ...]``` - - Args: - monkeypatch: pytest's monkeypatch fixture. - - Returns: - Mock: Mocked instance of WebSocketClient - """ - mock_websocket_client: Mock = create_autospec(WebSocketClient, spec_set=True) - mock_websocket_client.__aenter__.return_value = mock_websocket_client - mock_websocket_client.__aexit__.return_value = False - - monkeypatch.setattr("streamdeck.manager.WebSocketClient", lambda *args, **kwargs: mock_websocket_client) - - return mock_websocket_client +def patch_websocket_transport(monkeypatch: pytest.MonkeyPatch) -> Mock: + """Provide the manager with a transport that performs no network I/O.""" + transport: Mock = create_autospec(WebSocketTransport, spec_set=True) + transport.__aenter__.return_value = transport + transport.__aexit__.return_value = False + monkeypatch.setattr("streamdeck.manager.WebSocketTransport", lambda *args, **kwargs: transport) + return transport @pytest.fixture diff --git a/tests/plugin_manager/test_command_sender_binding.py b/tests/plugin_manager/test_command_sender_binding.py index 0c6e6fa..121fa64 100644 --- a/tests/plugin_manager/test_command_sender_binding.py +++ b/tests/plugin_manager/test_command_sender_binding.py @@ -141,7 +141,7 @@ def sync_handler(event_data: events.EventBase) -> None: assert calls == ["async-start", "async-end", "sync"] -@pytest.mark.usefixtures("patch_websocket_client") +@pytest.mark.usefixtures("patch_websocket_transport") def test_run_manager_events_handled_with_correct_params( mock_event_listener_manager_with_fake_events: tuple[Mock, list[events.EventBase]], plugin_manager: PluginManager, @@ -156,7 +156,7 @@ def test_run_manager_events_handled_with_correct_params( - Ensure that mocked event handlers were called with the correct params, binding the `command_sender` parameter if defined in the handler's signature. - NOTE: The WebSocketClient is mocked so as to be essentially ignored in this test. + NOTE: The WebSocketTransport is mocked so as to be essentially ignored in this test. Args: mock_event_listener_manager_with_fake_events (tuple[Mock, list[events.EventBase]]): Mocked instance of EventListenerManager, and a list of fake event messages it will yield. diff --git a/tests/plugin_manager/test_plugin_manager.py b/tests/plugin_manager/test_plugin_manager.py index 426c91a..0b956ff 100644 --- a/tests/plugin_manager/test_plugin_manager.py +++ b/tests/plugin_manager/test_plugin_manager.py @@ -8,6 +8,7 @@ from streamdeck.event_handlers.actions import Action from streamdeck.manager import EventAdapter, PluginManager +from streamdeck.websocket import WebSocketEventListener from streamdeck.models.events import ( #, event_adapter DEFAULT_EVENT_MODELS, DEFAULT_EVENT_NAMES, @@ -76,7 +77,7 @@ def test_plugin_manager_register_event_listener(plugin_manager: PluginManager) - assert "fake_event_name" in plugin_manager._event_adapter._event_names -@pytest.mark.usefixtures("patch_websocket_client", "patch_event_listener_manager") +@pytest.mark.usefixtures("patch_websocket_transport", "patch_event_listener_manager") def test_plugin_manager_sends_registration_event( mock_command_sender: Mock, plugin_manager: PluginManager, @@ -85,7 +86,7 @@ def test_plugin_manager_sends_registration_event( When the PluginManager.run() method is called, it should register the plugin with the StreamDeck software by sending an action registration event via the StreamDeckCommandSender instance. - NOTE: The WebSocketClient and EventListenerManager are mocked so as to be essentially ignored in this test. + NOTE: The WebSocketTransport and EventListenerManager are mocked so as to be essentially ignored in this test. """ asyncio.run(plugin_manager.run()) @@ -95,7 +96,7 @@ def test_plugin_manager_sends_registration_event( def test_plugin_manager_preserves_cancellation_when_cleanup_fails( - patch_websocket_client: Mock, + patch_websocket_transport: Mock, patch_event_listener_manager: Mock, plugin_manager: PluginManager, ) -> None: @@ -121,35 +122,28 @@ async def blocked_stream() -> AsyncIterator[str]: asyncio.run(run_and_cancel()) - patch_websocket_client.__aexit__.assert_awaited_once() + patch_websocket_transport.__aexit__.assert_awaited_once() patch_event_listener_manager.stop.assert_awaited_once() def test_plugin_manager_adds_websocket_event_listener( patch_event_listener_manager: Mock, - patch_websocket_client: Mock, + patch_websocket_transport: Mock, plugin_manager: PluginManager, # This fixture must come after patch_event_listener_manager to ensure monkeypatching occurs. ) -> None: - """Test that the PluginManager adds the WebSocketClient as an event listener. - - The PluginManager.run() method should add the WebSocketClient as an event listener to the EventListenerManager. - - Args: - patch_event_listener_manager (Mock): Mocked instance of EventListenerManager. - Patched by the fixture, and used here to check if this instance's .add_listener() method was called with the appropriate arguments. - patch_websocket_client (Mock): Mocked instance of WebSocketClient. - Patched by the fixture, and used here to check if this instance was passed to the EventListenerManager.add_listener() method as an argument. - plugin_manager (PluginManager): PluginManager fixture - """ + """Register a listener backed by the active WebSocket transport.""" asyncio.run(plugin_manager.run()) - patch_websocket_client.__aenter__.assert_awaited_once() - patch_websocket_client.__aexit__.assert_awaited_once() - patch_event_listener_manager.add_listener.assert_called_once_with(patch_websocket_client) + patch_websocket_transport.__aenter__.assert_awaited_once() + patch_websocket_transport.__aexit__.assert_awaited_once() + patch_event_listener_manager.add_listener.assert_called_once() + listener = patch_event_listener_manager.add_listener.call_args.args[0] + assert isinstance(listener, WebSocketEventListener) + assert listener._transport is patch_websocket_transport @pytest.mark.integration -@pytest.mark.usefixtures("patch_websocket_client") +@pytest.mark.usefixtures("patch_websocket_transport") def test_plugin_manager_process_event( mock_event_listener_manager_with_fake_events: tuple[Mock, list[EventBase]], _spy_handlers_registry_get_event_handlers: None, # This fixture must come after mock_event_listener_manager_with_fake_events to ensure monkeypatching occurs. diff --git a/tests/test_command_sender.py b/tests/test_command_sender.py index d8b4227..797588d 100644 --- a/tests/test_command_sender.py +++ b/tests/test_command_sender.py @@ -6,13 +6,13 @@ import pytest from streamdeck.command_sender import StreamDeckCommandSender -from streamdeck.websocket import WebSocketClient +from streamdeck.websocket import WebSocketTransport @pytest.fixture def mock_client() -> Mock: - """Fixture to mock the WebSocketClient.""" - return Mock(spec=WebSocketClient) + """Fixture to mock the WebSocketTransport.""" + return Mock(spec=WebSocketTransport) @pytest.fixture diff --git a/tests/test_event_stream_processor.py b/tests/test_event_stream_processor.py new file mode 100644 index 0000000..a6c6288 --- /dev/null +++ b/tests/test_event_stream_processor.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import asyncio +import sys +from typing import TYPE_CHECKING + +import pytest + +from streamdeck.event_stream_processor import EventStreamProcessor +from tests.test_utils.fake_event_factories import KeyDownEventFactory + + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator + + from streamdeck.models.events import EventBase + + +def test_processor_reads_ahead_and_dispatches_in_order() -> None: + async def scenario() -> None: + first, second = KeyDownEventFactory.batch(2) + source_drained = asyncio.Event() + handled: list[EventBase] = [] + + async def events() -> AsyncGenerator[EventBase, None]: + yield first + yield second + source_drained.set() + + async def dispatch(event: EventBase) -> None: + if event is first: + await source_drained.wait() + assert not handled + handled.append(event) + + await asyncio.wait_for(EventStreamProcessor(dispatch).run(events()), timeout=1) + assert handled == [first, second] + + asyncio.run(scenario()) + + +def test_dispatch_failure_closes_the_event_source() -> None: + async def scenario() -> None: + error = RuntimeError("dispatch failed") + source_closed = asyncio.Event() + + async def events() -> AsyncGenerator[EventBase, None]: + try: + yield KeyDownEventFactory.build() + await asyncio.Event().wait() + finally: + source_closed.set() + + async def dispatch(_event: EventBase) -> None: + raise error + + with pytest.raises(ExceptionGroup) as captured: + await asyncio.wait_for(EventStreamProcessor(dispatch).run(events()), timeout=1) + + assert captured.value.exceptions == (error,) + assert source_closed.is_set() + + asyncio.run(scenario()) diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 6293c0e..7551864 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -14,7 +14,7 @@ ) from streamdeck.event_listener import StopStreaming -from streamdeck.websocket import WebSocketClient +from streamdeck.websocket import WebSocketEventListener, WebSocketTransport def test_start_send_and_stop(monkeypatch: pytest.MonkeyPatch, port_number: int) -> None: @@ -24,7 +24,7 @@ async def scenario() -> None: connection.close = AsyncMock() connect_mock = AsyncMock(return_value=connection) monkeypatch.setattr("streamdeck.websocket.connect", connect_mock) - client = WebSocketClient(port_number) + client = WebSocketTransport(port_number) await client.start() connect_mock.assert_awaited_once_with(uri=f"ws://localhost:{port_number}") payload = {"event": "test", "payload": {"k": "v"}} @@ -32,7 +32,7 @@ async def scenario() -> None: connection.send.assert_awaited_once_with(json.dumps(payload)) await client.stop() connection.close.assert_awaited_once() - assert client._client is None + assert client._connection is None asyncio.run(scenario()) @@ -46,26 +46,26 @@ async def scenario() -> None: connection.close = AsyncMock() connect_mock = AsyncMock(return_value=connection) monkeypatch.setattr("streamdeck.websocket.connect", connect_mock) - client = WebSocketClient(port_number) + client = WebSocketTransport(port_number) async with client as active_client: assert active_client is client - assert client._client is connection + assert client._connection is connection connect_mock.assert_awaited_once_with(uri=f"ws://localhost:{port_number}") connection.close.assert_awaited_once() - assert client._client is None + assert client._connection is None asyncio.run(scenario()) def test_listen_yields_frames_and_stops_on_connection_close(port_number: int) -> None: async def scenario() -> None: - client = WebSocketClient(port_number) + client = WebSocketTransport(port_number) connection = Mock() connection.recv = AsyncMock(side_effect=["text", b"binary", ConnectionClosed(None, None)]) - client._client = connection + client._connection = connection received: list[str | bytes] = [] with pytest.raises(StopStreaming): - async for message in client.listen(): + async for message in WebSocketEventListener(client).listen(): received.append(message) assert received == ["text", b"binary"] @@ -74,12 +74,12 @@ async def scenario() -> None: def test_listen_translates_websocket_errors_to_stop_streaming(port_number: int) -> None: async def scenario() -> None: - client = WebSocketClient(port_number) + client = WebSocketTransport(port_number) connection = Mock() connection.recv = AsyncMock(side_effect=WebSocketException("broken")) - client._client = connection + client._connection = connection with pytest.raises(StopStreaming): - async for _ in client.listen(): + async for _ in WebSocketEventListener(client).listen(): pass asyncio.run(scenario()) @@ -90,12 +90,12 @@ def test_listen_translates_unexpected_receive_errors_to_stop_streaming( caplog: pytest.LogCaptureFixture, ) -> None: async def scenario() -> None: - client = WebSocketClient(port_number) + client = WebSocketTransport(port_number) connection = Mock() connection.recv = AsyncMock(side_effect=RuntimeError("unexpected receive failure")) - client._client = connection + client._connection = connection with pytest.raises(StopStreaming): - async for _ in client.listen(): + async for _ in WebSocketEventListener(client).listen(): pass asyncio.run(scenario()) @@ -106,7 +106,7 @@ async def scenario() -> None: @pytest.mark.parametrize( ("error", "level", "message"), [ - (ConnectionClosedOK(None, None), logging.DEBUG, "Connection was closed normally, stopping the client."), + (ConnectionClosedOK(None, None), logging.DEBUG, "Connection was closed normally, stopping the listener."), (ConnectionClosedError(None, None), logging.ERROR, "Connection was terminated with an error."), (ConnectionClosed(None, None), logging.ERROR, "Connection was already closed."), (WebSocketException("broken"), logging.ERROR, "Connection closed due to an unexpected WebSocket error."), @@ -120,12 +120,12 @@ def test_listen_logs_websocket_exception_type( message: str, ) -> None: async def scenario() -> None: - client = WebSocketClient(port_number) + client = WebSocketTransport(port_number) connection = Mock() connection.recv = AsyncMock(side_effect=error) - client._client = connection + client._connection = connection with pytest.raises(StopStreaming): - async for _ in client.listen(): + async for _ in WebSocketEventListener(client).listen(): pass caplog.set_level(logging.DEBUG, logger="streamdeck.websocket") diff --git a/uv.lock b/uv.lock index c27ea65..0571fd9 100644 --- a/uv.lock +++ b/uv.lock @@ -691,7 +691,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -1603,6 +1603,7 @@ dependencies = [ { name = "pydantic-core" }, { name = "pydantic-settings", version = "2.15.0", source = { registry = "https://pypi.org/simple" }, extra = ["toml"], marker = "python_full_version < '3.11'" }, { name = "pydantic-settings", version = "2.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "taskgroup", marker = "python_full_version < '3.11'" }, { name = "typing-extensions" }, { name = "websockets", version = "16.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "websockets", version = "17.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, @@ -1629,6 +1630,7 @@ requires-dist = [ { name = "pydantic", specifier = ">=2.11" }, { name = "pydantic-core", specifier = ">=2.33" }, { name = "pydantic-settings", extras = ["toml"], specifier = ">=2.11" }, + { name = "taskgroup", marker = "python_full_version < '3.11'", specifier = ">=0.2.2" }, { name = "typing-extensions", specifier = ">=4.14.0" }, { name = "websockets", specifier = ">=16.1" }, ] @@ -1645,6 +1647,19 @@ dev = [ ] packaging = [{ name = "twine", specifier = ">=6.1.0" }] +[[package]] +name = "taskgroup" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "exceptiongroup" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f0/8d/e218e0160cc1b692e6e0e5ba34e8865dbb171efeb5fc9a704544b3020605/taskgroup-0.2.2.tar.gz", hash = "sha256:078483ac3e78f2e3f973e2edbf6941374fbea81b9c5d0a96f51d297717f4752d", size = 11504, upload-time = "2025-01-03T09:24:13.761Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/b1/74babcc824a57904e919f3af16d86c08b524c0691504baf038ef2d7f655c/taskgroup-0.2.2-py2.py3-none-any.whl", hash = "sha256:e2c53121609f4ae97303e9ea1524304b4de6faf9eb2c9280c7f87976479a52fb", size = 14237, upload-time = "2025-01-03T09:24:11.41Z" }, +] + [[package]] name = "tomli" version = "2.5.0"