diff --git a/README.md b/README.md index 5224a13..1c9e7ae 100644 --- a/README.md +++ b/README.md @@ -92,15 +92,19 @@ def handle_will_appear(event_data): A handler must have a required positional parameter named `event_data` first; the `.on()` decorator checks this when applied. At startup, before opening the WebSocket, the manager checks that any other required parameters have a stored injectable value. The SDK provides `command_sender`; plugins can define additional injected parameters in `pyproject.toml`. The SDK passes injectable values by keyword, so declare them as positional-or-keyword or keyword-only. +Handlers may be synchronous or asynchronous. Synchronous handlers run directly +on the event loop, so keep them brief and non-blocking. Use an async handler +when it needs to await I/O or send commands: + ```python from streamdeck.command_sender import StreamDeckCommandSender @my_action.on("willAppear") -def handle_will_appear(event_data, command_sender: StreamDeckCommandSender): +async def handle_will_appear(event_data, command_sender: StreamDeckCommandSender): # Use command_sender to interact with Stream Deck - command_sender.set_title(context=event_data.context, title="Hello!") - command_sender.set_state(context=event_data.context, state=0) + await command_sender.set_title(context=event_data.context, title="Hello!") + await command_sender.set_state(context=event_data.context, state=0) ``` The `command_sender` parameter is optional. If included in the handler's signature, the SDK automatically injects a `StreamDeckCommandSender` instance that can be used to send commands back to the Stream Deck (like setting titles, states, or images). Startup raises `TypeError` for signatures whose required parameters cannot be supplied by dispatch. @@ -237,6 +241,10 @@ Use `streamdeck --help` without launch arguments to see the available options. H The CLI entry point `streamdeck.__main__.main(argv=None)` accepts an optional argument list, excluding the executable name. Both settings models use that same list; omitting it uses the process arguments. Startup prepares imports, logging, and optional debugging before loading plugin settings, then calls `run_plugin(launch, config)` with both validated models. Startup and runtime failures are logged and re-raised. +The console command owns the event loop. Code that calls `PluginManager.run()` +directly must await it, and calls to `StreamDeckCommandSender` methods must also +be awaited. + In addition to these, there is an additional option to use **debug mode**, which is discussed below. #### Debugging @@ -366,8 +374,9 @@ To create a custom event listener: ```python # custom_listener.py -from collections.abc import Generator -from typing import ClassVar, Literal +import json +from collections.abc import AsyncIterator +from typing import Literal from streamdeck.event_listener import EventListener from streamdeck.models.events import EventBase @@ -381,25 +390,22 @@ class MyCustomEvent(EventBase[Literal["somethingHappened"]]): class MyCustomEventListener(EventListener): event_models = [MyCustomEvent] - - def listen(self) -> Generator[str | bytes, None, None]: - ... - # Listen/poll for something here in a loop, and yield the result. - # This will be ran in a background thread. - # Ex: - # while self._running is True: - # result = module.check_status() - # if result is not None: - # yield json.dumps({"event": "somethingHappened", "result": result}) - # time.sleep(1) - - def stop(self) -> None: - ... - # Stop the loop or blocking call in the listen method. - # Ex: - # self._running = False + + async def listen(self) -> AsyncIterator[str | bytes]: + # Replace wait_for_status() with cancellable async I/O for your source. + while True: + result = await wait_for_status() + yield json.dumps({"event": "somethingHappened", "result": result}) + + async def stop(self) -> None: + # Close any subscription or other resources owned by this listener. + await close_status_subscription() ``` +Listeners run as asyncio tasks, so their I/O must not block the event loop. +`stop()` should be safe after partial startup and release resources even when +`listen()` is waiting for input. + ### Configuring Your Custom Listener To use your custom event listener, add it to your `pyproject.toml` file: @@ -433,9 +439,6 @@ The following upcoming improvements are in the works: - **Improved Documentation**: Expand and improve the documentation with more examples, guides, and use cases. - **Store & Bind Settings**: Automatically store and bind action instance context-holding objects to handler function arguments if they are included in the definition. - **Optional Event Pattern Matching on Hooks**: Add support for optional pattern-matching on event messages to further filter when hooks get called. -- **Async Support**: Introduce asynchronous features to handle WebSocket communication more efficiently. - - ## License This project is licensed under the MIT License. diff --git a/pyproject.toml b/pyproject.toml index 42e8b88..9a5cde3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,9 +61,10 @@ "platformdirs >= 4.3.6", "pydantic >= 2.11", "pydantic_core >= 2.33", - "websockets >= 13.1", + "websockets >= 16.1", "pydantic-settings[toml] >= 2.11", "typing-extensions >= 4.14.0", + "exceptiongroup >= 1.3.1", ] [project.urls] diff --git a/streamdeck/__main__.py b/streamdeck/__main__.py index 0975344..1e57153 100644 --- a/streamdeck/__main__.py +++ b/streamdeck/__main__.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import logging import sys @@ -24,6 +25,11 @@ def main(argv: list[str] | None = None) -> None: """Console entry point for the Pydantic Settings CLI.""" + asyncio.run(async_main(argv)) + + +async def async_main(argv: list[str] | None = None) -> None: + """Parse launch configuration and run the plugin inside the event loop.""" args = sys.argv[1:] if argv is None else list(argv) try: launch = CliApp.run(LaunchArguments, cli_args=args) @@ -44,7 +50,7 @@ def main(argv: list[str] | None = None) -> None: setup_debug_mode(launch.debug_port) config = CliApp.run(StreamDeckToolConfig, cli_args=args) - run_plugin(launch, config) + await run_plugin(launch, config) except Exception: logger.exception("Plugin startup or execution failed") raise @@ -60,7 +66,7 @@ def setup_debug_mode(debug_port: int) -> None: logger.info("Debugger attached.") -def run_plugin(launch: LaunchArguments, config: StreamDeckToolConfig) -> None: +async def run_plugin(launch: LaunchArguments, config: StreamDeckToolConfig) -> None: """Register and run the plugin using validated launch and plugin settings.""" manager = PluginManager( port=launch.port, @@ -92,7 +98,7 @@ def run_plugin(launch: LaunchArguments, config: StreamDeckToolConfig) -> None: manager.register_action(action) logger.info("Connecting to Stream Deck on port %d", launch.port) - manager.run() + await manager.run() # Also run the plugin if this script is ran as a console script. diff --git a/streamdeck/command_sender.py b/streamdeck/command_sender.py index 7615bb7..070bb61 100644 --- a/streamdeck/command_sender.py +++ b/streamdeck/command_sender.py @@ -1,10 +1,11 @@ from __future__ import annotations from logging import getLogger -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Protocol if TYPE_CHECKING: + from collections.abc import Awaitable from typing import Any, Literal from pydantic import JsonValue @@ -16,67 +17,72 @@ EventNameStr, PluginDefinedData, ) - from streamdeck.websocket import WebSocketClient logger = getLogger("streamdeck.command_sender") +class AsyncEventSender(Protocol): + """Narrow async capability required by the command sender.""" + + def send_event(self, data: dict[str, JsonValue]) -> Awaitable[None]: ... + + class StreamDeckCommandSender: """Class for sending command event messages to the Stream Deck software through a WebSocket client.""" - def __init__(self, client: WebSocketClient, plugin_registration_uuid: str): + def __init__(self, client: AsyncEventSender, plugin_registration_uuid: str): self._client = client self._plugin_registration_uuid = plugin_registration_uuid - def _send_event(self, event: EventNameStr, **kwargs: Any) -> None: - self._client.send_event({ + async def _send_event(self, event: EventNameStr, **kwargs: Any) -> None: + await self._client.send_event({ "event": event, **kwargs, }) - def set_settings(self, context: ActionInstanceUUIDStr, payload: PluginDefinedData) -> None: - self._send_event( + async def set_settings(self, context: ActionInstanceUUIDStr, payload: PluginDefinedData) -> None: + await self._send_event( event="setSettings", context=context, payload=payload, ) - def get_settings(self, context: ActionInstanceUUIDStr) -> None: - self._send_event( + async def get_settings(self, context: ActionInstanceUUIDStr) -> None: + await self._send_event( event="getSettings", context=context, ) - def set_global_settings(self, payload: PluginDefinedData) -> None: - self._send_event( + async def set_global_settings(self, payload: PluginDefinedData) -> None: + await self._send_event( event="setGlobalSettings", context=self._plugin_registration_uuid, payload=payload, ) - def get_global_settings(self) -> None: - self._send_event( + async def get_global_settings(self) -> None: + await self._send_event( event="getGlobalSettings", context=self._plugin_registration_uuid, ) - def open_url(self, context: ActionInstanceUUIDStr, url: str) -> None: - self._send_event( + async def open_url(self, context: ActionInstanceUUIDStr, url: str) -> None: + await self._send_event( event="openUrl", context=context, payload={"url": url}, ) - def log_message(self, context: ActionInstanceUUIDStr, message: str) -> None: - self._send_event( + async def log_message(self, context: ActionInstanceUUIDStr, message: str) -> None: + await self._send_event( event="logMessage", context=context, payload={"message": message}, ) - def set_title( + async def set_title( self, context: ActionInstanceUUIDStr, state: int | None = None, @@ -92,13 +98,13 @@ def set_title( if title: payload["title"] = title - self._send_event( + await self._send_event( event="setTitle", context=context, payload=payload, ) - def set_image( + async def set_image( self, context: ActionInstanceUUIDStr, image: str, # base64 encoded image, @@ -117,7 +123,7 @@ def set_image( } target_code = target_code_lookup[target] - self._send_event( + await self._send_event( event="setImage", context=context, payload={ @@ -127,33 +133,33 @@ def set_image( }, ) - def set_feedback(self, context: ActionInstanceUUIDStr, payload: PluginDefinedData) -> None: + async def set_feedback(self, context: ActionInstanceUUIDStr, payload: PluginDefinedData) -> None: """Set's the feedback of an existing layout associated with an action instance. Args: context (str): Defines the context of the command, e.g. which action instance the command is intended for. payload (PluginDefinedData): Additional information supplied as part of the command. """ - self._send_event( + await self._send_event( event="setFeedback", context=context, payload=payload, ) - def set_feedback_layout(self, context: ActionInstanceUUIDStr, layout: str) -> None: + async def set_feedback_layout(self, context: ActionInstanceUUIDStr, layout: str) -> None: """Sets the layout associated with an action instance. Args: context (str): Defines the context of the command, e.g. which action instance the command is intended for. layout (str): Name of a pre-defined layout, or relative path to a custom one. """ - self._send_event( + await self._send_event( event="setFeedbackLayout", context=context, payload={"layout": layout}, ) - def set_trigger_description( + async def set_trigger_description( self, context: ActionInstanceUUIDStr, rotate: str | None = None, @@ -181,7 +187,7 @@ def set_trigger_description( long_touch: Describes the long-touch interaction with the touch display. When None, the description will be hidden. """ - self._send_event( + await self._send_event( event="setTriggerDescription", context=context, payload={ @@ -192,28 +198,28 @@ def set_trigger_description( }, ) - def show_alert(self, context: ActionInstanceUUIDStr) -> None: + async def show_alert(self, context: ActionInstanceUUIDStr) -> None: """Temporarily show an alert icon on the image displayed by an instance of an action.""" - self._send_event( + await self._send_event( event="showAlert", context=context, ) - def show_ok(self, context: ActionInstanceUUIDStr) -> None: + async def show_ok(self, context: ActionInstanceUUIDStr) -> None: """Temporarily show an OK checkmark icon on the image displayed by an instance of an action.""" - self._send_event( + await self._send_event( event="showOk", context=context, ) - def set_state(self, context: ActionInstanceUUIDStr, state: int) -> None: - self._send_event( + async def set_state(self, context: ActionInstanceUUIDStr, state: int) -> None: + await self._send_event( event="setState", context=context, payload={"state": state}, ) - def switch_to_profile( + async def switch_to_profile( self, context: ActionInstanceUUIDStr, device: DeviceUUIDStr, @@ -241,23 +247,23 @@ def switch_to_profile( "page": page, } - self._send_event( + await self._send_event( event="switchToProfile", context=context, device=device, payload=payload, ) - def send_to_property_inspector( + async def send_to_property_inspector( self, context: ActionInstanceUUIDStr, payload: PluginDefinedData ) -> None: - self._send_event( + await self._send_event( event="sendToPropertyInspector", context=context, payload=payload, ) - def send_to_plugin( + async def send_to_plugin( self, context: ActionInstanceUUIDStr, action: ActionUUIDStr, payload: PluginDefinedData ) -> None: """Send a payload to another plugin. @@ -268,14 +274,14 @@ def send_to_plugin( which action was triggered. payload: The data that will be received by the receiving plugin. """ - self._send_event( + await self._send_event( event="sendToPlugin", context=context, action=action, payload=payload, ) - def send_action_registration( + async def send_action_registration( self, register_event: str, ) -> None: @@ -291,7 +297,7 @@ def send_action_registration( register_event (str): The registration event type, passed in by the Stream Deck software as -registerEvent option. It's value will almost definitely will be "registerPlugin". """ - self._send_event( + await self._send_event( event=register_event, uuid=self._plugin_registration_uuid, ) diff --git a/streamdeck/event_handlers/injectables.py b/streamdeck/event_handlers/injectables.py index 3c55610..7808368 100644 --- a/streamdeck/event_handlers/injectables.py +++ b/streamdeck/event_handlers/injectables.py @@ -8,6 +8,7 @@ from streamdeck.event_handlers.protocol import ( EventHandlerFunc, + EventHandlerResult, EventModel_contra, inspect_event_handler_signature, validate_event_handler_event_parameter, @@ -100,7 +101,11 @@ def resolve(self, parameter_names: Iterable[str], event_data: EventBase) -> dict if name in self._specs } - def resolve_for_handler(self, handler: Callable[..., None], event_data: EventBase) -> dict[str, object]: + def resolve_for_handler( + self, + handler: Callable[..., EventHandlerResult], + event_data: EventBase, + ) -> dict[str, object]: """Resolve values only for injectable parameters declared by a handler.""" return self.resolve(inspect.signature(handler).parameters, event_data) diff --git a/streamdeck/event_handlers/protocol.py b/streamdeck/event_handlers/protocol.py index 3728a0e..050e38b 100644 --- a/streamdeck/event_handlers/protocol.py +++ b/streamdeck/event_handlers/protocol.py @@ -1,13 +1,14 @@ from __future__ import annotations import inspect -from collections.abc import Callable, Iterable -from typing import TYPE_CHECKING, Protocol +from collections.abc import Awaitable, Callable, Iterable +from typing import TYPE_CHECKING, Protocol, TypeAlias from typing_extensions import Concatenate, ParamSpec, TypeVar # noqa: UP035 from streamdeck.models.events import EventBase + if TYPE_CHECKING: from streamdeck.types import EventNameStr @@ -18,10 +19,16 @@ InjectableHandlerParams = ParamSpec("InjectableHandlerParams", default=...) """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.""" + # The ParamSpec preserves a handler's declared trailing signature at # registration. Its default ellipsis gives catalogs and dispatch a common type # with an event-first callable and an otherwise unspecified signature. -EventHandlerFunc = Callable[Concatenate[EventModel_contra, InjectableHandlerParams], None] +EventHandlerFunc = Callable[ + Concatenate[EventModel_contra, InjectableHandlerParams], + EventHandlerResult, +] """Event-first callable whose remaining signature is preserved by a ParamSpec. At registration, the ParamSpec retains the handler's trailing parameter types diff --git a/streamdeck/event_listener.py b/streamdeck/event_listener.py index 7b83054..639fb6f 100644 --- a/streamdeck/event_listener.py +++ b/streamdeck/event_listener.py @@ -1,129 +1,276 @@ +"""Run asynchronous event listeners and merge their output into one stream. + +`EventListener` defines the interface for custom asynchronous event sources. +`EventListenerManager` runs registered listeners concurrently and forwards +their JSON messages through a shared stream, where the plugin runtime can +validate and dispatch them alongside built-in events. Listener event models +are registered separately by `PluginManager`. + +A listener may raise `StopStreaming` to request shutdown of the merged stream. +Normal completion or an unexpected failure only ends that listener; the +manager keeps the stream open until a listener requests stream-wide shutdown +or the consumer cancels or closes the stream. During cleanup, the manager +stops each listener and cancels and awaits its associated task. +""" + from __future__ import annotations -import threading +import asyncio from abc import ABC, abstractmethod +from dataclasses import dataclass from logging import getLogger -from queue import Queue from typing import TYPE_CHECKING + +from exceptiongroup import ExceptionGroup from typing_extensions import sentinel if TYPE_CHECKING: - from collections.abc import Generator, Iterator + from collections.abc import AsyncIterator, Awaitable from typing import ClassVar from streamdeck.models.events import EventBase - logger = getLogger("streamdeck.event_listener") - _END_OF_STREAM = sentinel("_END_OF_STREAM") -"""Sentinel object used to signal the end of the event stream.""" +"""Private queue marker requesting termination of the merged event stream.""" class StopStreaming(Exception): # noqa: N818 - """Raised by an EventListener implementation to signal that the entire EventManagerListener should stop streaming events.""" + """Signal that the complete merged event stream should stop. + A listener can raise this exception when its source determines that the + plugin runtime should shut down. The listener manager treats it as a + stream-wide control signal rather than logging it as an unexpected + listener failure. + """ -class EventListenerManager: - """Manages event listeners and provides a shared event queue for them to push events into. - With this class, a single event stream can be created from multiple listeners. - This allows for us to listen for not only Stream Deck events, but also other events plugin-developer -defined events. +@dataclass +class _ListenerRegistration: + """Keep one listener together with the task that runs it, if started.""" + + listener: EventListener + task: asyncio.Task[None] | None = None + + async def cleanup(self) -> list[BaseException]: + """Stop this listener and await its task, collecting either failure.""" + operations: list[Awaitable[None]] = [self.listener.stop()] + task = self.task + + # If this registration has a task, then ensure that it gets stopped + if task is not None: + if not task.done(): + task.cancel() + operations.append(task) + + results = await asyncio.gather(*operations, return_exceptions=True) + errors: list[BaseException] = [] + + # The first result is the listener's stop result. + listener_stop_result = results[0] + if isinstance(listener_stop_result, BaseException): + errors.append(listener_stop_result) + + # When this registration has a task, the second result is its outcome. + if task is not None: + task_result = results[1] + if isinstance(task_result, BaseException) and not isinstance( + task_result, asyncio.CancelledError + ): + errors.append(task_result) + + return errors + + +class EventListenerManager: + """Coordinate event listeners and expose their output as one async stream. + + The manager starts each registered listener in its own asyncio task and + forwards yielded messages through a shared async queue. Consumers receive + messages from all listeners through :meth:`event_stream`, without needing + to know which listener produced each message. The manager also handles + listener failures, stream-wide stop requests, cancellation, and listener + cleanup. """ + def __init__(self) -> None: - self.event_queue: Queue[str | bytes | _END_OF_STREAM] = Queue() - self.listeners_lookup_by_thread: dict[threading.Thread, EventListener] = {} - self._running = False + self._listeners: list[_ListenerRegistration] = [] + self._event_queue: asyncio.Queue[str | bytes | _END_OF_STREAM] = asyncio.Queue() + self._cleanup_started = False def add_listener(self, listener: EventListener) -> None: - """Registers a listener function that yields events. + """Register a listener to be started with the next event stream. + + Listeners must be registered before :meth:`event_stream` starts. Their + `event_models` are registered separately by :class:`PluginManager` + so messages from every source can be validated on the shared path. Args: - listener: A function that yields events. + listener: The async event source to add to the merged stream. """ - # Create a thread for the listener - thread = threading.Thread( - target=self._listener_wrapper, - args=(listener,), - daemon=True, - ) - self.listeners_lookup_by_thread[thread] = listener - - def _listener_wrapper(self, listener: EventListener) -> None: - """Wraps the listener function: for each event yielded, push it into the shared queue.""" - try: - for event in listener.listen(): - self.event_queue.put(event) + self._listeners.append(_ListenerRegistration(listener)) - if not self.running: - break + async def _pump(self, listener: EventListener) -> None: + """Forward one listener's messages and relay stream-wide stop requests. + + A normal return simply ends this listener's task; it does not end the + merged stream. `StopStreaming` places the manager's end-of-stream + sentinel in the shared queue. Any other exception is logged and + isolated to this listener. Cancellation is allowed to propagate so + the manager can await task completion during cleanup. + Args: + listener: The event source whose async iterator is being consumed. + """ + try: + async for message in listener.listen(): + await self._event_queue.put(message) except StopStreaming: logger.debug("Event listener requested to stop streaming.") - self.event_queue.put(_END_OF_STREAM) - + await self._event_queue.put(_END_OF_STREAM) + except asyncio.CancelledError: + raise except Exception: - logger.exception("Unexpected error in wrapped listener %s. Stopping just this listener.", listener) - - def stop(self) -> None: - """Stops the event generation loop and waits for all threads to finish. - - Listeners will check the running flag if implemented to stop listening. + logger.exception( + "Unexpected error in listener %s. Stopping just this listener.", listener + ) + try: + await listener.stop() + except Exception: + logger.exception("Failed to stop listener %s after its failure.", listener) + + async def stop(self) -> None: + """Stop all listeners and wait for their tasks to finish. + + This method is safe to call after :meth:`event_stream` has already + performed its cleanup. Every listener's `stop` hook is attempted, + even if another hook fails. + + Raises: + ExceptionGroup: One or more ordinary listener cleanup failures. + BaseException: A cancellation or other non-`Exception` cleanup failure. + """ + if self._cleanup_started: + return + + self._cleanup_started = True + ordinary_errors: list[Exception] = [] + first_base_exception: BaseException | None = None + + for result_errors in await asyncio.gather( + *(registration.cleanup() for registration in self._listeners), + return_exceptions=True, + ): + for error in ( + [result_errors] if isinstance(result_errors, BaseException) else result_errors + ): + logger.error( + "Listener cleanup failed: %s", + error, + exc_info=(type(error), error, error.__traceback__), + ) + if isinstance(error, Exception): + ordinary_errors.append(error) + elif first_base_exception is None: + first_base_exception = error + + if first_base_exception is not None: + # Raise this after the loop to allow all errors to be logged + raise first_base_exception + if ordinary_errors: + raise ExceptionGroup("Event listener cleanup failed", ordinary_errors) + + async def event_stream(self) -> AsyncIterator[str | bytes]: + """Start the listeners and yield their messages until shutdown. + + Each listener runs concurrently in an asyncio task. Messages from all + sources are yielded as they arrive. A listener ending normally does + not stop the stream, including when all listeners have ended; the + stream remains available for a later stop request. Raising + :class:`StopStreaming` from any listener ends the stream and triggers + cleanup. Cancellation and exceptions also trigger cleanup before they + propagate. + + Yields: + The `str` or `bytes` message emitted by a registered listener. + + Raises: + BaseException: Propagates cancellation or errors raised during + stream processing or cleanup. + ExceptionGroup: One or more ordinary listener cleanup failures. """ - # Set the running flag to False to stop the listeners running in separate threads. - self.running = False - # Push the sentinel to immediately unblock the queue.get() in event_stream. - self.event_queue.put(_END_OF_STREAM) - - for thread in self.listeners_lookup_by_thread: - logger.debug("Stopping listener %s.") - self.listeners_lookup_by_thread[thread].stop() - if thread.is_alive(): - thread.join() - - logger.info("All listeners have been stopped.") - - def event_stream(self) -> Generator[str | bytes, None, None]: - """Starts all registered listeners, sets the running flag to True, and yields events from the shared queue.""" logger.info("Starting event stream.") - # Set the running flag to True and start the listeners in their separate threads. - self.running = True - for thread in self.listeners_lookup_by_thread: - thread.start() - + primary_error: BaseException | None = None try: + for registration in self._listeners: + registration.task = asyncio.create_task( + self._pump(registration.listener), + name=f"event-listener-{type(registration.listener).__name__}", + ) while True: - event = self.event_queue.get() - if event is _END_OF_STREAM: - logger.debug("Sentinel received, stopping event stream.") - break # Exit loop immediately if the sentinel is received - yield event + item = await self._event_queue.get() + if item is _END_OF_STREAM: + break + if not isinstance(item, (str, bytes)): + raise TypeError(f"Unexpected event queue item: {item!r}") + yield item + except BaseException as exc: + primary_error = exc + raise finally: - self.stop() + try: + await self.stop() + except BaseException: + if primary_error is None: + raise class EventListener(ABC): - """Base class for event listeners. - - Event listeners are classes that listen for events and simply yield them as they come. - The EventListenerManager will handle the threading and pushing the events yielded into a shared queue. + """Base class for async sources of plugin events. + + Subclasses yield JSON messages as strings or bytes from :meth:`listen` and + declare the event models those messages may represent in `event_models`. + The :class:`EventListenerManager` runs each listener as an asyncio task and + merges its output with messages from other listeners. Implementations that + wait for input should use cancellable async I/O and release resources in + `stop` or in a `finally` block. """ + event_models: ClassVar[list[type[EventBase]]] - """A list of event models that the listener can yield. Read in by the PluginManager to model the incoming event data off of. + """Event models this listener can yield. - The plugin-developer must define this list in their subclass. + The plugin manager adds these models to its event adapter so listener + messages can be validated and dispatched alongside built-in events. Each + listener subclass should define this list. """ @abstractmethod - def listen(self) -> Iterator[str | bytes]: - """Start listening for events and yield them as they come. + def listen(self) -> AsyncIterator[str | bytes]: + """Listen for events and yield each message as it arrives. + + This method must return an async iterator yielding JSON strings or + bytes. It is consumed in a task managed by :class:`EventListenerManager`; + implementations should avoid blocking the event loop and should use + awaitable, cancellable operations for I/O. - This is the method that run in a separate thread. + Yields: + A JSON message that can be validated against `event_models`. + + Raises: + StopStreaming: To request termination of the entire merged stream. + asyncio.CancelledError: When the runtime is shutting down. """ @abstractmethod - def stop(self) -> None: - """Stop the listener. This could set an internal flag, close a connection, etc.""" + async def stop(self) -> None: + """Stop the listener and release resources it owns. + + The event listener manager calls this during normal stream termination + and cancellation, then waits for the listener task to finish. This + hook must be safe to call repeatedly and after partial startup. It + should release resources even when the listener's iterator is blocked + on I/O. + """ diff --git a/streamdeck/manager.py b/streamdeck/manager.py index fb8b9d2..cddbe49 100644 --- a/streamdeck/manager.py +++ b/streamdeck/manager.py @@ -1,5 +1,7 @@ from __future__ import annotations +import inspect +from contextlib import aclosing from logging import getLogger from typing import TYPE_CHECKING @@ -8,7 +10,6 @@ from streamdeck.command_sender import StreamDeckCommandSender from streamdeck.event_handlers.actions import Action, ActionBase from streamdeck.event_handlers.injectables import InjectableHandlerParamStore -from streamdeck.event_handlers.protocol import SupportsEventHandlers from streamdeck.event_handlers.registry import HandlersRegistry from streamdeck.event_handlers.scopes import ScopeName, scope_for_event from streamdeck.event_listener import EventListener, EventListenerManager @@ -19,10 +20,11 @@ if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import AsyncGenerator from typing import Literal from streamdeck.event_handlers.injectables import InjectableResolver + from streamdeck.event_handlers.protocol import SupportsEventHandlers from streamdeck.models.events import EventBase @@ -133,7 +135,7 @@ def register_injectable_handler_param( """ self._injectable_handler_param_store.register(name, resolver, scope=scope) - def _stream_event_data(self) -> Iterator[EventBase]: + async def _stream_event_data(self) -> AsyncGenerator[EventBase, None]: """Stream event data from the event listeners. Validate and model the incoming event data before yielding it. @@ -141,7 +143,7 @@ def _stream_event_data(self) -> Iterator[EventBase]: Yields: EventBase: The event data received from the event listeners. """ - for message in self._event_listener_manager.event_stream(): + async for message in self._event_listener_manager.event_stream(): try: data: EventBase = self._event_adapter.validate_json(message) except ValidationError: @@ -157,7 +159,7 @@ def _stream_event_data(self) -> Iterator[EventBase]: yield data - def _dispatch_event(self, event: EventBase) -> None: + async def _dispatch_event(self, event: EventBase) -> None: """Dispatch an event to the appropriate action handlers. Args: @@ -169,9 +171,11 @@ def _dispatch_event(self, event: EventBase) -> None: injected_params = self._injectable_handler_param_store.resolve_for_handler(event_handler, event) # TODO: from action-instance event occurrences, save metadata to the action's properties. - event_handler(event, **injected_params) + result = event_handler(event, **injected_params) + if inspect.isawaitable(result): + await result - def run(self) -> None: + async def run(self) -> None: """Run the PluginManager by connecting to the WebSocket server and processing incoming events. This method establishes a WebSocket connection, registers the plugin, listens for incoming messages, @@ -179,6 +183,7 @@ 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. """ client = WebSocketClient(port=self._port) command_sender = StreamDeckCommandSender(client, plugin_registration_uuid=self._registration_uuid) @@ -189,13 +194,25 @@ def run(self) -> None: ) self._validate_registered_handler_signatures() - with client: - # Register the WebSocketClient as an event listener, so we can receive Stream Deck events. - self.register_event_listener(client) + 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) - command_sender.send_action_registration(register_event=self._register_event) + await command_sender.send_action_registration(register_event=self._register_event) - for data in self._stream_event_data(): - self._dispatch_event(data) + async with aclosing(self._stream_event_data()) as event_data_stream: + async for data in event_data_stream: + await self._dispatch_event(data) - logger.info("PluginManager has stopped processing events.") + logger.info("PluginManager has stopped processing events.") + except BaseException as exc: + primary_error = exc + raise + finally: + try: + await self._event_listener_manager.stop() + except BaseException: + if primary_error is None: + raise diff --git a/streamdeck/websocket.py b/streamdeck/websocket.py index 5788017..a230d08 100644 --- a/streamdeck/websocket.py +++ b/streamdeck/websocket.py @@ -1,6 +1,14 @@ -"""A client for connecting to the Stream Deck device's WebSocket server and sending/receiving events. +"""Connect to Stream Deck's WebSocket server and send or receive events. -Inherits from the EventListener class to work with the EventListenerManager for processing 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. """ from __future__ import annotations @@ -8,71 +16,66 @@ from logging import getLogger from typing import TYPE_CHECKING -from websockets import ConnectionClosedError, WebSocketException -from websockets.exceptions import ConnectionClosed, ConnectionClosedOK -from websockets.sync.client import ClientConnection, connect +from websockets.asyncio.client import connect +from websockets.exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + WebSocketException, +) from streamdeck.event_listener import EventListener, StopStreaming -from streamdeck.models.events import DEFAULT_EVENT_MODELS, EventBase +from streamdeck.models.events import DEFAULT_EVENT_MODELS if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import AsyncIterator from types import TracebackType - from typing import Any, ClassVar + from typing import ClassVar - from typing_extensions import Self # noqa: UP035 + from pydantic import JsonValue + from typing_extensions import Self + from websockets.asyncio.client import ClientConnection + from streamdeck.models.events import EventBase -logger = getLogger("streamdeck.websocket") +logger = getLogger("streamdeck.websocket") class WebSocketClient(EventListener): - """A client for connecting to the Stream Deck device's WebSocket server and sending/receiving events.""" - _client: ClientConnection | None + """The sole reader and async sender for the active Stream Deck connection.""" event_models: ClassVar[list[type[EventBase]]] = DEFAULT_EVENT_MODELS - def __init__(self, port: int): - """Initialize a WebSocketClient instance. + 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 (int): The port number to connect to the WebSocket server. + port: The local port number provided by Stream Deck for the + WebSocket connection. """ self._port = port - self._client = None + self._client: ClientConnection | None = None - def send_event(self, data: dict[str, Any]) -> None: - """Send an event message to the WebSocket server. - - Args: - data (dict[str, Any]): The event data to send. - """ + async def send_event(self, data: dict[str, JsonValue]) -> None: + """Serialize and send a command through the active connection.""" if self._client is None: - msg = "WebSocket connection not established yet." - raise ValueError(msg) - - data_str = json.dumps(data) - self._client.send(message=data_str) + raise ValueError("WebSocket connection not established yet.") - def listen(self) -> Iterator[str | bytes]: - """Listen for messages from the WebSocket server indefinitely. + await self._client.send(json.dumps(data)) - TODO: implement more concise error-handling. - - Yields: - str | bytes: The received message from the WebSocket server. - """ + async def listen(self) -> AsyncIterator[str | bytes]: + """Yield inbound frames; this is the connection's only receive loop.""" if self._client is None: - msg = "WebSocket connection not established yet." - raise ValueError(msg) + raise ValueError("WebSocket connection not established yet.") try: while True: - message: str | bytes = self._client.recv() - yield message - + yield await self._client.recv() except WebSocketException as exc: if isinstance(exc, ConnectionClosedOK): logger.debug("Connection was closed normally, stopping the client.") @@ -84,34 +87,47 @@ def listen(self) -> Iterator[str | bytes]: logger.exception("Connection is closed due to an unexpected WebSocket error.") raise StopStreaming from None - except Exception: - logger.exception("Failed to receive messages from websocket server due to unexpected error.") - raise + logger.exception("Unexpected error while receiving from Stream Deck; stopping the runtime.") + raise StopStreaming from None - def start(self) -> None: - """Start the connection to the websocket server.""" + async def start(self) -> None: + """Establish the Stream Deck connection.""" try: - self._client = connect(uri=f"ws://localhost:{self._port}") + self._client = await connect(uri=f"ws://localhost:{self._port}") except ConnectionRefusedError: - logger.exception("Failed to connect to the WebSocket server. Make sure the Stream Deck software is running.") + logger.exception("Failed to connect to the WebSocket server. Make sure Stream Deck is running.") raise - def stop(self) -> None: - """Close the WebSocket connection, if open.""" + async def stop(self) -> None: + """Close the connection if it was established.""" if self._client is not None: - self._client.close() + await self._client.close() + self._client = None - def __enter__(self) -> Self: - """Start the connection to the websocket server. + 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. """ - self.start() + await self.start() return self - def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> None: - """Close the WebSocket connection, if open.""" - self.stop() - + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + """Close the connection, preserving any exception from the block.""" + try: + await self.stop() + except BaseException: + if exc_val is None: + raise + logger.exception( + "Failed to close WebSocket while handling %s", + exc_type.__name__ if exc_type is not None else "an exception", + ) + return False diff --git a/tests/data/dummy_event_listener.py b/tests/data/dummy_event_listener.py index 0486fdd..a7d2d91 100644 --- a/tests/data/dummy_event_listener.py +++ b/tests/data/dummy_event_listener.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import AsyncIterator from typing import ClassVar @@ -25,10 +25,10 @@ class DummyEventListener(EventListener): event_models: ClassVar[list[type[EventBase]]] = [DummyEvent] @override - def listen(self) -> Iterator[str | bytes]: + async def listen(self) -> AsyncIterator[str | bytes]: """Yields a dummy event.""" yield '{"event": "dummy", "something": 42}' @override - def stop(self) -> None: + async def stop(self) -> None: """Doesn't do anything.""" diff --git a/tests/event_listener/test_event_listener.py b/tests/event_listener/test_event_listener.py index 4368db6..5de0572 100644 --- a/tests/event_listener/test_event_listener.py +++ b/tests/event_listener/test_event_listener.py @@ -1,210 +1,244 @@ from __future__ import annotations -import threading -import time -from typing import TYPE_CHECKING -from unittest.mock import Mock, patch +import asyncio +from typing import TYPE_CHECKING, ClassVar, cast import pytest + from streamdeck.event_listener import EventListener, EventListenerManager, StopStreaming from streamdeck.models.events import ApplicationDidLaunch, EventBase if TYPE_CHECKING: - from collections.abc import Iterator - from typing import Any, ClassVar - - from streamdeck.types import EventNameStr - - -class MockEventListener(EventListener): - """Mock implementation of EventListener for testing.""" - event_models: ClassVar[list[type[EventBase]]] = [ApplicationDidLaunch] - - def __init__(self): - self._running = True - self.events = ["event1", "event2", "event3"] - self.listen_called = False - self.stop_called = False - - def listen(self) -> Iterator[str]: - self.listen_called = True - for event in self.events: - if not self._running: - break - yield event + from collections.abc import AsyncIterator - def stop(self) -> None: - self._running = False - self.stop_called = True - -class SlowMockEventListener(EventListener): - """Mock implementation of EventListener that yields events with a delay.""" +class ListListener(EventListener): event_models: ClassVar[list[type[EventBase]]] = [ApplicationDidLaunch] - def __init__(self, delay: float = 0.1): - self._running = True + def __init__(self, events: list[str], *, delay: float = 0) -> None: + self.events = events self.delay = delay - self.events = ["slow1", "slow2", "slow3"] + self.stopped = False - def listen(self) -> Iterator[str]: + async def listen(self) -> AsyncIterator[str]: for event in self.events: - if not self._running: - break - time.sleep(self.delay) # simulate processing time + if self.delay: + await asyncio.sleep(self.delay) yield event - def stop(self) -> None: - self._running = False - - -class ExceptionEventListener(EventListener): - """Mock implementation of EventListener that raises an exception.""" - event_models: ClassVar[list[type[EventBase]]] = [ApplicationDidLaunch] - - def listen(self) -> Iterator[str]: - self._running = True - # Raise exception after yielding one event - yield "event_before_exception" - raise ValueError("Test exception in listener") - - def stop(self) -> None: - pass + async def stop(self) -> None: + self.stopped = True -class StopStreamingEventListener(EventListener): - """Mock listener that requests the event stream to stop.""" - event_models: ClassVar[list[type[EventBase]]] = [ApplicationDidLaunch] - - def listen(self) -> Iterator[str]: - yield from () +class StopListener(ListListener): + async def listen(self) -> AsyncIterator[str]: raise StopStreaming + yield "unreachable" + + +def test_multiple_listeners_merge_and_cleanup() -> None: + async def scenario() -> None: + manager = EventListenerManager() + first = ListListener(["a", "b"]) + second = ListListener(["c", "d"], delay=0.001) + manager.add_listener(first) + manager.add_listener(second) + events: list[str] = [] + async for event in manager.event_stream(): + events.append(event) + if len(events) == 4: + break + await manager.stop() + assert set(events) == {"a", "b", "c", "d"} + assert first.stopped and second.stopped - def stop(self) -> None: - pass - - - - -def test_add_listener(): - """Test adding a listener to the manager.""" - manager = EventListenerManager() - listener = Mock() - - assert len(manager.listeners_lookup_by_thread) == 0 - - manager.add_listener(listener) - - # Check that a thread was created and added to the lookup dict - assert len(manager.listeners_lookup_by_thread) == 1 - thread = next(iter(manager.listeners_lookup_by_thread.keys())) - assert isinstance(thread, threading.Thread) - assert manager.listeners_lookup_by_thread[thread] is listener - - -def test_event_stream_basic(): - """Test that event_stream yields events from added listeners.""" - manager = EventListenerManager() - listener = MockEventListener() - - manager.add_listener(listener) - - # Collect the first few events - events : list[EventNameStr] = [] - for event in manager.event_stream(): - events.append(event) # type: ignore[arg-type] - if len(events) >= 3: # We expect 3 events from MockEventListener - manager.stop() - break - - # Check that we got the expected events - assert events == listener.events - - -def test_event_stream_stops_when_listener_raises_stop_streaming(): - """A StopStreaming request ends the stream without exposing its internal sentinel.""" - manager = EventListenerManager() - manager.add_listener(StopStreamingEventListener()) - - assert list(manager.event_stream()) == [] - - -def test_event_stream_multiple_listeners(): - """Test that events from multiple listeners are interleaved.""" - manager = EventListenerManager() - listener1 = MockEventListener() - listener2 = SlowMockEventListener(delay=0.01) # Small delay to ensure deterministic order - - manager.add_listener(listener1) - manager.add_listener(listener2) - - # Collect all events - events: list[EventNameStr] = [] - for event in manager.event_stream(): - events.append(event) # type: ignore[arg-type] - if len(events) >= 6: # We expect 6 events total (3 from each listener) - manager.stop() - break - - # Check that we got all expected events (order may vary) - assert len(events) == 6 - assert set(events) == {"event1", "event2", "event3", "slow1", "slow2", "slow3"} + asyncio.run(scenario()) -def test_stop(): - """Test that stop() correctly stops all listeners.""" - manager = EventListenerManager() - listener1 = MockEventListener() - listener2 = MockEventListener() +def test_stop_streaming_ends_the_merged_stream() -> None: + class CountingStopListener(StopListener): + def __init__(self) -> None: + super().__init__([]) + self.stop_calls = 0 - manager.add_listener(listener1) - manager.add_listener(listener2) + async def stop(self) -> None: + self.stop_calls += 1 + await super().stop() - # Start the event stream but then immediately stop it - event_iter = manager.event_stream() - next(event_iter) # Get the first event to ensure threads start - manager.stop() + async def scenario() -> None: + manager = EventListenerManager() + listener = CountingStopListener() + manager.add_listener(listener) + assert [event async for event in manager.event_stream()] == [] + await manager.stop() + assert listener.stop_calls == 1 - # Check that all listeners were stopped - assert listener1.stop_called - assert listener2.stop_called - assert not manager.running + asyncio.run(scenario()) -@patch("streamdeck.event_listener.logger") -def test_listener_exception_handling(mock_logger: Mock): - """Test that exceptions in listeners are properly caught and logged.""" - manager = EventListenerManager() - listener = ExceptionEventListener() +def test_cleanup_attempts_every_listener_when_a_stop_hook_fails() -> None: + class FailingStopListener(ListListener): + def __init__(self) -> None: + super().__init__([]) + self.stop_calls = 0 - manager.add_listener(listener) + async def stop(self) -> None: + self.stop_calls += 1 + raise RuntimeError("stop failed") - # Collect events - should get one event before the exception - events: list[Any] = [] - for event in manager.event_stream(): - events.append(event) - if len(events) >= 1: # We expect 1 event before exception - time.sleep(0.1) # Give time for exception to be raised - manager.stop() - break + async def scenario() -> None: + manager = EventListenerManager() + manager.add_listener(StopListener([])) + failing_listener = FailingStopListener() + other_listener = ListListener([]) + manager.add_listener(failing_listener) + manager.add_listener(other_listener) - assert "event_before_exception" in events - # Check that the exception was logged - mock_logger.exception.assert_called_with("Unexpected error in wrapped listener %s. Stopping just this listener.", listener) + with pytest.raises(Exception, match="Event listener cleanup failed") as exc_info: + async for _ in manager.event_stream(): + pass + assert type(exc_info.value).__name__ == "ExceptionGroup" + assert [str(error) for error in exc_info.value.exceptions] == ["stop failed"] + assert failing_listener.stop_calls == 1 + assert other_listener.stopped -def test_listener_wrapper(): - """Test the _listener_wrapper method that runs listeners in threads.""" - manager = EventListenerManager() - listener = MockEventListener() + asyncio.run(scenario()) - # Run the wrapper directly - manager.running = True - manager._listener_wrapper(listener) - # Check that events were put in the queue - assert manager.event_queue.qsize() == 3 - assert manager.event_queue.get() == "event1" - assert manager.event_queue.get() == "event2" - assert manager.event_queue.get() == "event3" +def test_stop_groups_multiple_listener_cleanup_errors() -> None: + class FailingStopListener(ListListener): + def __init__(self, message: str) -> None: + super().__init__([]) + self.message = message + + async def stop(self) -> None: + raise RuntimeError(self.message) + + async def scenario() -> None: + manager = EventListenerManager() + manager.add_listener(FailingStopListener("first stop failed")) + manager.add_listener(FailingStopListener("second stop failed")) + + with pytest.raises(Exception, match="Event listener cleanup failed") as exc_info: + await manager.stop() + + assert type(exc_info.value).__name__ == "ExceptionGroup" + assert [str(error) for error in exc_info.value.exceptions] == [ + "first stop failed", + "second stop failed", + ] + + asyncio.run(scenario()) + + +def test_event_stream_groups_multiple_listener_cleanup_errors() -> None: + class FailingStopListener(ListListener): + def __init__(self, message: str) -> None: + super().__init__([]) + self.message = message + + async def stop(self) -> None: + raise RuntimeError(self.message) + + async def scenario() -> None: + manager = EventListenerManager() + manager.add_listener(StopListener([])) + manager.add_listener(FailingStopListener("first stop failed")) + manager.add_listener(FailingStopListener("second stop failed")) + + with pytest.raises(Exception, match="Event listener cleanup failed") as exc_info: + async for _ in manager.event_stream(): + pass + + assert type(exc_info.value).__name__ == "ExceptionGroup" + assert [str(error) for error in exc_info.value.exceptions] == [ + "first stop failed", + "second stop failed", + ] + + asyncio.run(scenario()) + + +def test_event_stream_error_is_preserved_when_cleanup_fails() -> None: + class FailingStopListener(ListListener): + async def stop(self) -> None: + raise RuntimeError("cleanup failed") + + async def scenario() -> None: + manager = EventListenerManager() + manager.add_listener(FailingStopListener([])) + manager.add_listener(FailingStopListener([])) + manager._event_queue.put_nowait(cast(str, 123)) + + with pytest.raises(TypeError, match="Unexpected event queue item"): + async for _ in manager.event_stream(): + pass + + asyncio.run(scenario()) + + +def test_cleanup_does_not_group_base_exceptions() -> None: + class CancelledStopListener(ListListener): + async def stop(self) -> None: + raise asyncio.CancelledError + + class FailingStopListener(ListListener): + async def stop(self) -> None: + raise RuntimeError("ordinary cleanup failure") + + async def scenario() -> None: + manager = EventListenerManager() + manager.add_listener(CancelledStopListener([])) + manager.add_listener(FailingStopListener([])) + + with pytest.raises(asyncio.CancelledError): + await manager.stop() + + asyncio.run(scenario()) + + +def test_normal_completion_does_not_end_stream_and_stop_cancels_waiter() -> None: + async def scenario() -> None: + manager = EventListenerManager() + listener = ListListener(["once"]) + manager.add_listener(listener) + stream = manager.event_stream() + assert await anext(stream) == "once" + pending = asyncio.create_task(anext(stream)) + try: + await asyncio.wait_for(asyncio.shield(pending), timeout=0.01) + except asyncio.TimeoutError: + pass + else: + raise AssertionError("A normally completed listener must not end the stream.") + await manager.stop() + pending.cancel() + try: + await pending + except (asyncio.CancelledError, StopAsyncIteration): + pass + await stream.aclose() + assert listener.stopped + + asyncio.run(scenario()) + + +def test_listener_failure_isolated_and_logged() -> None: + class FailingListener(ListListener): + async def listen(self) -> AsyncIterator[str]: + raise ValueError("broken") + yield "unreachable" + + async def scenario() -> None: + manager = EventListenerManager() + manager.add_listener(FailingListener([])) + survivor = ListListener(["survived"]) + manager.add_listener(survivor) + stream = manager.event_stream() + assert await anext(stream) == "survived" + await stream.aclose() + assert survivor.stopped + + asyncio.run(scenario()) diff --git a/tests/plugin_manager/conftest.py b/tests/plugin_manager/conftest.py index 3b37484..f121bbe 100644 --- a/tests/plugin_manager/conftest.py +++ b/tests/plugin_manager/conftest.py @@ -1,18 +1,26 @@ from __future__ import annotations from typing import TYPE_CHECKING -from unittest.mock import Mock, create_autospec +from unittest.mock import AsyncMock, Mock, create_autospec import pytest + from streamdeck.event_listener import EventListenerManager from streamdeck.manager import PluginManager from streamdeck.websocket import WebSocketClient - from tests.test_utils.fake_event_factories import KeyDownEventFactory +async def _empty_event_stream() -> AsyncIterator[str]: + if False: + yield "" + + if TYPE_CHECKING: + from collections.abc import AsyncIterator + import pytest_mock + from streamdeck.models import events @@ -54,7 +62,8 @@ def patch_websocket_client(monkeypatch: pytest.MonkeyPatch) -> Mock: Mock: Mocked instance of WebSocketClient """ mock_websocket_client: Mock = create_autospec(WebSocketClient, spec_set=True) - mock_websocket_client.__enter__.return_value = mock_websocket_client + 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)) @@ -72,6 +81,7 @@ def mock_command_sender(mocker: pytest_mock.MockerFixture) -> Mock: Mock: Mocked instance of StreamDeckCommandSender """ mock_cmd_sender = Mock() + mock_cmd_sender.send_action_registration = AsyncMock() mocker.patch("streamdeck.manager.StreamDeckCommandSender", return_value=mock_cmd_sender) return mock_cmd_sender @@ -91,6 +101,7 @@ def patch_event_listener_manager(monkeypatch: pytest.MonkeyPatch) -> Mock: Mock: Mocked instance of EventListenerManager """ mock_event_listener_manager: Mock = create_autospec(EventListenerManager, spec_set=True) + mock_event_listener_manager.event_stream.return_value = _empty_event_stream() monkeypatch.setattr("streamdeck.manager.EventListenerManager", (lambda *args, **kwargs: mock_event_listener_manager)) @@ -105,12 +116,15 @@ 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. """ - print("MOCK EVENT LISTENER MANAGER") # Create a list of fake event messages, and convert them to json strings to be passed back by the client.listen() method. fake_event_messages: list[events.EventBase] = [ KeyDownEventFactory.build(action="my-fake-action-uuid"), ] - patch_event_listener_manager.event_stream.return_value = [event.model_dump_json() for event in fake_event_messages] + async def event_stream() -> AsyncIterator[str]: + for event in fake_event_messages: + yield event.model_dump_json() + + patch_event_listener_manager.event_stream.return_value = event_stream() return patch_event_listener_manager, fake_event_messages diff --git a/tests/plugin_manager/test_command_sender_binding.py b/tests/plugin_manager/test_command_sender_binding.py index 8b34e14..0c6e6fa 100644 --- a/tests/plugin_manager/test_command_sender_binding.py +++ b/tests/plugin_manager/test_command_sender_binding.py @@ -1,9 +1,11 @@ from __future__ import annotations +import asyncio from typing import TYPE_CHECKING from unittest.mock import Mock, create_autospec import pytest + from streamdeck.event_handlers.actions import Action from streamdeck.event_handlers.injectables import InjectableHandlerParamStore from streamdeck.event_handlers.scopes import Scope @@ -90,7 +92,7 @@ def handler(event_data: events.EventBase, extension_value: object) -> None: plugin_manager._validate_registered_handler_signatures() event_data = Mock(event="applicationDidLaunch") - plugin_manager._dispatch_event(event_data) + asyncio.run(plugin_manager._dispatch_event(event_data)) mock_handler.assert_called_once_with(event_data, extension_value=provided_value) @@ -116,6 +118,29 @@ def handler(event_data: events.EventBase, missing_value: object) -> None: ) +def test_dispatch_awaits_async_handlers_in_registration_sequence(plugin_manager: PluginManager) -> None: + """Async handlers finish before the next matching handler begins.""" + calls: list[str] = [] + + action = Action("test.action") + + @action.on("applicationDidLaunch") + async def async_handler(event_data: events.EventBase) -> None: + calls.append("async-start") + await asyncio.sleep(0) + calls.append("async-end") + + @action.on("applicationDidLaunch") + def sync_handler(event_data: events.EventBase) -> None: + calls.append("sync") + + plugin_manager.register_action(action) + plugin_manager._handlers_registry.get_event_handlers = lambda **_kwargs: [async_handler, sync_handler] + asyncio.run(plugin_manager._dispatch_event(Mock(event="applicationDidLaunch"))) + + assert calls == ["async-start", "async-end", "sync"] + + @pytest.mark.usefixtures("patch_websocket_client") def test_run_manager_events_handled_with_correct_params( mock_event_listener_manager_with_fake_events: tuple[Mock, list[events.EventBase]], @@ -155,7 +180,7 @@ def test_run_manager_events_handled_with_correct_params( # Run the PluginManager and let it process the fake event messages generated by the mocked EventListenerManager. # Since the EventListenerManager.event_stream() method is mocked to return a finite list of fake event messages, it will stop after yielding all of them rather than running indefinitely. - plugin_manager.run() + asyncio.run(plugin_manager.run()) # Ensure that mocked event handlers were called with the correct params, binding the `command_sender` parameter if defined in the handler's signature. mock_event_handler_without_cmd_sender.assert_called_once_with(fake_event_message) diff --git a/tests/plugin_manager/test_plugin_manager.py b/tests/plugin_manager/test_plugin_manager.py index 02119fd..426c91a 100644 --- a/tests/plugin_manager/test_plugin_manager.py +++ b/tests/plugin_manager/test_plugin_manager.py @@ -1,8 +1,11 @@ +import asyncio +from collections.abc import AsyncIterator from typing import cast from unittest.mock import Mock, call import pytest import pytest_mock + from streamdeck.event_handlers.actions import Action from streamdeck.manager import EventAdapter, PluginManager from streamdeck.models.events import ( #, event_adapter @@ -57,13 +60,13 @@ def test_plugin_manager_register_event_listener(plugin_manager: PluginManager) - mock_event_model_class = Mock(get_model_event_names=lambda: ["fake_event_name"]) listener = Mock(event_models=[mock_event_model_class]) - assert len(plugin_manager._event_listener_manager.listeners_lookup_by_thread) == 0 + assert len(plugin_manager._event_listener_manager._listeners) == 0 plugin_manager.register_event_listener(listener) # Validate that the PluginManager's EventListenerManager has the listener properly registered. - assert len(plugin_manager._event_listener_manager.listeners_lookup_by_thread) == 1 - assert next(iter(plugin_manager._event_listener_manager.listeners_lookup_by_thread.values())) == listener + assert len(plugin_manager._event_listener_manager._listeners) == 1 + assert plugin_manager._event_listener_manager._listeners[0].listener == listener # Validate that the PluginManager's EventAdapter has the event model class properly registered. assert len(plugin_manager._event_adapter._models) == len(DEFAULT_EVENT_MODELS) + 1 @@ -84,13 +87,44 @@ def test_plugin_manager_sends_registration_event( NOTE: The WebSocketClient and EventListenerManager are mocked so as to be essentially ignored in this test. """ - plugin_manager.run() + asyncio.run(plugin_manager.run()) mock_command_sender.send_action_registration.assert_called_once_with( register_event=plugin_manager._register_event, ) +def test_plugin_manager_preserves_cancellation_when_cleanup_fails( + patch_websocket_client: Mock, + patch_event_listener_manager: Mock, + plugin_manager: PluginManager, +) -> None: + """Close the WebSocket and preserve cancellation if listener cleanup fails.""" + + async def run_and_cancel() -> None: + stream_started = asyncio.Event() + + async def blocked_stream() -> AsyncIterator[str]: + stream_started.set() + await asyncio.Event().wait() + yield "{}" + + patch_event_listener_manager.event_stream.return_value = blocked_stream() + patch_event_listener_manager.stop.side_effect = RuntimeError("cleanup failure") + + run_task = asyncio.create_task(plugin_manager.run()) + await asyncio.wait_for(stream_started.wait(), timeout=1) + run_task.cancel() + + with pytest.raises(asyncio.CancelledError): + await run_task + + asyncio.run(run_and_cancel()) + + patch_websocket_client.__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, @@ -107,8 +141,10 @@ def test_plugin_manager_adds_websocket_event_listener( 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 """ - plugin_manager.run() + 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) @@ -124,7 +160,7 @@ def test_plugin_manager_process_event( mock_event_listener_mgr, fake_event_messages = mock_event_listener_manager_with_fake_events fake_event_message = fake_event_messages[0] - plugin_manager.run() + asyncio.run(plugin_manager.run()) # First check that the EventListenerManager's event_stream() method was called. # This has been stubbed to return the fake_event_message's json string. diff --git a/tests/test_command_sender.py b/tests/test_command_sender.py index 7e446a6..0dd9a83 100644 --- a/tests/test_command_sender.py +++ b/tests/test_command_sender.py @@ -1,8 +1,10 @@ from __future__ import annotations +import asyncio from unittest.mock import Mock import pytest + from streamdeck.command_sender import StreamDeckCommandSender from streamdeck.websocket import WebSocketClient @@ -158,9 +160,9 @@ def test_command_sender_methods( method = getattr(command_sender, method_name) if context is not None: - method(context, **extra_args) + asyncio.run(method(context, **extra_args)) else: - method(**extra_args) + asyncio.run(method(**extra_args)) # Build the expected data structure to send through the WebSocket expected_data = { @@ -171,3 +173,18 @@ def test_command_sender_methods( # Assert that the client's send_event method was called with the expected data mock_client.send_event.assert_called_once_with(expected_data) + + +def test_send_action_registration_payload( + command_sender: StreamDeckCommandSender, + mock_client: Mock, +) -> None: + """Send the registration event and registration UUID in the wire payload.""" + asyncio.run(command_sender.send_action_registration(register_event="registerPlugin")) + + mock_client.send_event.assert_called_once_with( + { + "event": "registerPlugin", + "uuid": command_sender._plugin_registration_uuid, + } + ) diff --git a/tests/test_launch_settings.py b/tests/test_launch_settings.py index 3bcd299..ac0d4c9 100644 --- a/tests/test_launch_settings.py +++ b/tests/test_launch_settings.py @@ -1,7 +1,8 @@ +import asyncio import json import subprocess import sys -from unittest.mock import Mock, call +from unittest.mock import AsyncMock, Mock, call import pytest from pydantic import ValidationError @@ -234,6 +235,7 @@ def test_launcher_imports_from_plugin_directory_and_registers_listeners_first( process_args = ["--unrelated-process-argument"] if explicit_args else args monkeypatch.setattr(sys, "argv", ["streamdeck", *process_args]) manager = Mock() + manager.run = AsyncMock() factory = Mock(return_value=manager) monkeypatch.setattr(entry, "PluginManager", factory) monkeypatch.setattr(entry, "configure_streamdeck_logger", Mock()) @@ -306,8 +308,9 @@ def test_run_plugin_uses_supplied_settings_without_reading_process_args(tmp_path ) monkeypatch.setattr(sys, "argv", ["unrelated-program", "--invalid"]) manager = Mock() + manager.run = AsyncMock() monkeypatch.setattr(entry, "PluginManager", Mock(return_value=manager)) - entry.run_plugin(launch, config) + asyncio.run(entry.run_plugin(launch, config)) assert [call[0] for call in manager.mock_calls] == [ "register_action", "register_injectable_handler_param", diff --git a/tests/test_websocket.py b/tests/test_websocket.py index bf61233..86d9c9f 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -1,98 +1,136 @@ from __future__ import annotations +import asyncio import json -from functools import partial -from typing import TYPE_CHECKING, Any -from unittest.mock import Mock +import logging +from unittest.mock import AsyncMock, Mock import pytest -from streamdeck.event_listener import StopStreaming -from streamdeck.websocket import WebSocketClient -from websockets import ( +from websockets.exceptions import ( ConnectionClosed, ConnectionClosedError, ConnectionClosedOK, - InvalidHeader, WebSocketException, ) - -if TYPE_CHECKING: - from pytest_mock import MockerFixture - - -@pytest.fixture -def mock_connection() -> Mock: - """Fixture to mock the ClientConnection object returned by websockets.sync.client.connect.""" - return Mock() - - -@pytest.fixture -def patched_connect(mocker: MockerFixture, mock_connection: Mock) -> Mock: - """Fixture to mock the ClientConnection object returned by websockets.sync.client.connect.""" - return mocker.patch("streamdeck.websocket.connect", return_value=mock_connection) +from streamdeck.event_listener import StopStreaming +from streamdeck.websocket import WebSocketClient -def test_initialization_calls_connect_correctly( - patched_connect: Mock, mock_connection: Mock, port_number: int +def test_start_send_and_stop(monkeypatch: pytest.MonkeyPatch, port_number: int) -> None: + async def scenario() -> None: + connection = Mock() + connection.send = AsyncMock() + connection.close = AsyncMock() + connect_mock = AsyncMock(return_value=connection) + monkeypatch.setattr("streamdeck.websocket.connect", connect_mock) + client = WebSocketClient(port_number) + await client.start() + connect_mock.assert_awaited_once_with(uri=f"ws://localhost:{port_number}") + payload = {"event": "test", "payload": {"k": "v"}} + await client.send_event(payload) + connection.send.assert_awaited_once_with(json.dumps(payload)) + await client.stop() + connection.close.assert_awaited_once() + assert client._client is None + + asyncio.run(scenario()) + + +def test_async_context_manager_starts_and_closes_connection( + monkeypatch: pytest.MonkeyPatch, + port_number: int, ) -> None: - """Test that WebSocketClient initializes correctly by calling the connect function with the appropriate URI.""" - with WebSocketClient(port=port_number) as client: - # Assert that 'connect' was called once with the correct URI. - patched_connect.assert_called_once_with(uri=f"ws://localhost:{port_number}") - - # Assert that the client's _client attribute is the mocked connection - assert client._client == mock_connection - - -@pytest.mark.usefixtures("patched_connect") -def test_send_event_serializes_and_sends(mock_connection: Mock, port_number: int) -> None: - """Test that the send_event method corrently serializes the data to JSON and sends it via the websocket connection.""" - with WebSocketClient(port=port_number) as client: - fake_data = {"event": "test_event", "payload": {"key": "value"}} - client.send_event(fake_data) - - # Assert that the 'send' method was called once with the serialized data. - expected_message = json.dumps(fake_data) - mock_connection.send.assert_called_once_with(message=expected_message) - - -@pytest.mark.usefixtures("patched_connect") -def test_listen_yields_messages(mock_connection: Mock, port_number: int) -> None: - """Test that listen yields messages from the WebSocket connection.""" - # Set up the mocked connection to return messages until closing - expected_results = ["message1", b"message2", "message3"] - mock_connection.recv.side_effect = expected_results + async def scenario() -> None: + connection = Mock() + connection.close = AsyncMock() + connect_mock = AsyncMock(return_value=connection) + monkeypatch.setattr("streamdeck.websocket.connect", connect_mock) + client = WebSocketClient(port_number) + async with client as active_client: + assert active_client is client + assert client._client is connection + connect_mock.assert_awaited_once_with(uri=f"ws://localhost:{port_number}") + connection.close.assert_awaited_once() + assert client._client 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) + connection = Mock() + connection.recv = AsyncMock(side_effect=["text", b"binary", ConnectionClosed(None, None)]) + client._client = connection + received: list[str | bytes] = [] + with pytest.raises(StopStreaming): + async for message in client.listen(): + received.append(message) + assert received == ["text", b"binary"] + + asyncio.run(scenario()) + + +def test_listen_translates_websocket_errors_to_stop_streaming(port_number: int) -> None: + async def scenario() -> None: + client = WebSocketClient(port_number) + connection = Mock() + connection.recv = AsyncMock(side_effect=WebSocketException("broken")) + client._client = connection + with pytest.raises(StopStreaming): + async for _ in client.listen(): + pass + + asyncio.run(scenario()) + + +def test_listen_translates_unexpected_receive_errors_to_stop_streaming( + port_number: int, + caplog: pytest.LogCaptureFixture, +) -> None: + async def scenario() -> None: + client = WebSocketClient(port_number) + connection = Mock() + connection.recv = AsyncMock(side_effect=RuntimeError("unexpected receive failure")) + client._client = connection + with pytest.raises(StopStreaming): + async for _ in client.listen(): + pass - with WebSocketClient(port=port_number) as client: - actual_messages: list[Any] = [] - for i, msg in enumerate(client.listen()): - actual_messages.append(msg) - if i == 2: - break + asyncio.run(scenario()) - assert actual_messages == expected_results + assert "Unexpected error while receiving from Stream Deck; stopping the runtime." in caplog.text @pytest.mark.parametrize( - "exception_class", + ("error", "level", "message"), [ - partial(ConnectionClosedOK, None, None), - partial(ConnectionClosedError, None, None), - partial(InvalidHeader, "header-name", None), - partial(ConnectionClosed, None, None), - WebSocketException, + (ConnectionClosedOK(None, None), logging.DEBUG, "Connection was closed normally, stopping the client."), + (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."), ], ) -@pytest.mark.usefixtures("patched_connect") -def test_listen_raises_StopStreaming_from_WebSocketException( - mock_connection: Mock, port_number: int, exception_class: type[WebSocketException] +def test_listen_logs_websocket_exception_type( + port_number: int, + caplog: pytest.LogCaptureFixture, + error: WebSocketException, + level: int, + message: str, ) -> None: - """Test that listen raises a StopStreaming exception when a WebSocketException is raised.""" - # Set up the mocked connection to return messages until closing - mock_connection.recv.side_effect = ["message1", b"message2", exception_class()] - - # This should raise a StopStreaming exception when any WebSocketException is raised - with WebSocketClient(port=port_number) as client, pytest.raises(StopStreaming): - for _ in client.listen(): - pass + async def scenario() -> None: + client = WebSocketClient(port_number) + connection = Mock() + connection.recv = AsyncMock(side_effect=error) + client._client = connection + with pytest.raises(StopStreaming): + async for _ in client.listen(): + pass + + caplog.set_level(logging.DEBUG, logger="streamdeck.websocket") + asyncio.run(scenario()) + + record = next(record for record in caplog.records if record.name == "streamdeck.websocket") + assert record.levelno == level + assert record.message == message diff --git a/uv.lock b/uv.lock index 9109585..8e58393 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" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] 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,6 +1596,7 @@ wheels = [ name = "streamdeck-plugin-sdk" source = { editable = "." } dependencies = [ + { name = "exceptiongroup" }, { 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" }, @@ -1623,12 +1624,13 @@ packaging = [ [package.metadata] requires-dist = [ + { name = "exceptiongroup", 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 = "typing-extensions", specifier = ">=4.14.0" }, - { name = "websockets", specifier = ">=13.1" }, + { name = "websockets", specifier = ">=16.1" }, ] [package.metadata.requires-dev]