From 59e45cc4fde7798dc9ff047b8672a884b31c4f8a Mon Sep 17 00:00:00 2001 From: strohganoff Date: Fri, 20 Nov 2026 14:21:38 -0700 Subject: [PATCH 1/3] Separate WebSocket transport from event listening --- streamdeck/manager.py | 12 +- streamdeck/websocket.py | 123 +++++++++--------- tests/models/test_toml_settings.py | 4 +- tests/plugin_manager/conftest.py | 30 ++--- .../test_command_sender_binding.py | 4 +- tests/plugin_manager/test_plugin_manager.py | 34 ++--- tests/test_command_sender.py | 6 +- tests/test_websocket.py | 40 +++--- 8 files changed, 120 insertions(+), 133 deletions(-) diff --git a/streamdeck/manager.py b/streamdeck/manager.py index cddbe49..548fd8b 100644 --- a/streamdeck/manager.py +++ b/streamdeck/manager.py @@ -16,7 +16,7 @@ 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 TYPE_CHECKING: @@ -185,8 +185,8 @@ async def run(self) -> None: TypeError: If a registered handler requires a parameter with no stored injectable value. ExceptionGroup: If one or more ordinary event listener cleanup operations fail. """ - 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,9 +196,9 @@ 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) diff --git a/streamdeck/websocket.py b/streamdeck/websocket.py index a230d08..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 is 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 631895a..53651ca 100644 --- a/tests/models/test_toml_settings.py +++ b/tests/models/test_toml_settings.py @@ -91,7 +91,7 @@ def test_cli_listener_modules_replace_toml_before_import(tmp_path, flag): def test_repeated_listener_aliases_combine_in_one_override(tmp_path): from tests.data.dummy_event_listener import DummyEventListener - from streamdeck.websocket import WebSocketClient + 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 f121bbe..9793c00 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 @@ -116,7 +104,7 @@ def mock_event_listener_manager_with_fake_events(patch_event_listener_manager: M Returns: tuple: Mocked instance of EventListenerManager, and a list of fake event messages. """ - # Create a list of fake event messages, and convert them to json strings to be passed back by the client.listen() method. + # Create a list of fake event messages, and convert them to json strings to be passed back by the listener manager. fake_event_messages: list[events.EventBase] = [ KeyDownEventFactory.build(action="my-fake-action-uuid"), ] 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 0dd9a83..a9c5e73 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_websocket.py b/tests/test_websocket.py index 86d9c9f..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,10 +106,10 @@ 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 is closed due to an unexpected WebSocket error."), + (WebSocketException("broken"), logging.ERROR, "Connection closed due to an unexpected WebSocket error."), ], ) def test_listen_logs_websocket_exception_type( @@ -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") From 37f21b0a87786e882d21c0a3a22d0e9aa523e0b3 Mon Sep 17 00:00:00 2001 From: strohganoff Date: Fri, 20 Nov 2026 14:21:38 -0700 Subject: [PATCH 2/3] Extract event stream processing with task groups --- pyproject.toml | 3 +- streamdeck/event_listener.py | 5 +- streamdeck/event_stream_processor.py | 75 ++++++++++++++++++++++++++++ streamdeck/manager.py | 26 +++++++--- tests/test_event_stream_processor.py | 66 ++++++++++++++++++++++++ uv.lock | 21 ++++++-- 6 files changed, 184 insertions(+), 12 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 9a5cde3..189dddd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,7 +64,8 @@ "websockets >= 16.1", "pydantic-settings[toml] >= 2.11", "typing-extensions >= 4.14.0", - "exceptiongroup >= 1.3.1", + "exceptiongroup >= 1.3.1; python_version < '3.11'", + "taskgroup >= 0.2.2; python_version < '3.11'", ] [project.urls] diff --git a/streamdeck/event_listener.py b/streamdeck/event_listener.py index 639fb6f..113566a 100644 --- a/streamdeck/event_listener.py +++ b/streamdeck/event_listener.py @@ -16,14 +16,17 @@ from __future__ import annotations import asyncio +import sys from abc import ABC, abstractmethod from dataclasses import dataclass from logging import getLogger from typing import TYPE_CHECKING -from exceptiongroup import ExceptionGroup from typing_extensions import sentinel +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + if TYPE_CHECKING: from collections.abc import AsyncIterator, Awaitable 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 548fd8b..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,11 +13,15 @@ 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 WebSocketEventListener, WebSocketTransport +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -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,7 +186,7 @@ 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. """ transport = WebSocketTransport(port=self._port) command_sender = StreamDeckCommandSender(transport, plugin_registration_uuid=self._registration_uuid) @@ -202,9 +205,9 @@ async def run(self) -> None: 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/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/uv.lock b/uv.lock index 8e58393..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 = [ @@ -1596,13 +1596,14 @@ wheels = [ name = "streamdeck-plugin-sdk" source = { editable = "." } dependencies = [ - { name = "exceptiongroup" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "platformdirs", version = "4.12.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "platformdirs", version = "4.14.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "pydantic" }, { 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'" }, @@ -1624,11 +1625,12 @@ packaging = [ [package.metadata] requires-dist = [ - { name = "exceptiongroup", specifier = ">=1.3.1" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'", specifier = ">=1.3.1" }, { name = "platformdirs", specifier = ">=4.3.6" }, { 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" From 190c3ad95313de1f8e6dd3e8421fef4e82efbf5e Mon Sep 17 00:00:00 2001 From: strohganoff Date: Fri, 20 Nov 2026 14:21:38 -0700 Subject: [PATCH 3/3] Normalize handler docstrings --- streamdeck/event_handlers/protocol.py | 2 +- streamdeck/event_handlers/registry.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/streamdeck/event_handlers/protocol.py b/streamdeck/event_handlers/protocol.py index 050e38b..dd4b95c 100644 --- a/streamdeck/event_handlers/protocol.py +++ b/streamdeck/event_handlers/protocol.py @@ -20,7 +20,7 @@ """Handler-specific trailing signature; it may include parameters the SDK cannot inject.""" EventHandlerResult: TypeAlias = Awaitable[None] | None -"""Result of calling a handler: ``None`` for sync handlers or an awaitable for async handlers.""" +"""Result of calling a handler: `None` for sync handlers or an awaitable for async handlers.""" # The ParamSpec preserves a handler's declared trailing signature at # registration. Its default ellipsis gives catalogs and dispatch a common type diff --git a/streamdeck/event_handlers/registry.py b/streamdeck/event_handlers/registry.py index 46de290..2fd7268 100644 --- a/streamdeck/event_handlers/registry.py +++ b/streamdeck/event_handlers/registry.py @@ -45,7 +45,7 @@ def iter_event_handler_bindings( """Yield registered event names with their handlers, optionally filtered. Args: - event_name: The event name to retrieve, or ``ALL_EVENTS`` to enumerate every + event_name: The event name to retrieve, or `ALL_EVENTS` to enumerate every registered event. event_action_uuid: The action UUID to filter action-specific catalogs by. If None, include handlers from all catalogs. @@ -72,12 +72,12 @@ def get_event_handlers( ) -> Iterator[EventHandlerFunc]: """Yield handlers matching an event name or enumerate all registrations. - Passing ``ALL_EVENTS`` enumerates handlers registered under every event + Passing `ALL_EVENTS` enumerates handlers registered under every event name. It does not register a handler to receive every event. Args: event_name (EventNameStr | ALL_EVENTS): The event name to retrieve, - or ``ALL_EVENTS`` to enumerate every registered event. + or `ALL_EVENTS` to enumerate every registered event. event_action_uuid (str | None): The action UUID to get handlers for. If None (i.e., the event is not action-specific), get all handlers for the event.