Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion streamdeck/event_handlers/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions streamdeck/event_handlers/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand Down
5 changes: 4 additions & 1 deletion streamdeck/event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
75 changes: 75 additions & 0 deletions streamdeck/event_stream_processor.py
Original file line number Diff line number Diff line change
@@ -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",
)
38 changes: 25 additions & 13 deletions streamdeck/manager.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -13,10 +13,14 @@
from streamdeck.event_handlers.registry import HandlersRegistry
from streamdeck.event_handlers.scopes import ScopeName, scope_for_event
from streamdeck.event_listener import EventListener, EventListenerManager
from streamdeck.event_stream_processor import EventStreamProcessor
from streamdeck.models.events.adapter import EventAdapter
from streamdeck.models.events.common import ActionInstanceEventMixin
from streamdeck.utils.logging import configure_streamdeck_logger
from streamdeck.websocket import WebSocketClient
from streamdeck.websocket import WebSocketEventListener, WebSocketTransport

if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup


if TYPE_CHECKING:
Expand All @@ -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."""

Expand Down Expand Up @@ -183,10 +186,10 @@ async def run(self) -> None:

Raises:
TypeError: If a registered handler requires a parameter with no stored injectable value.
ExceptionGroup: If one or more ordinary event listener cleanup operations fail.
ExceptionGroup: If event processing or runtime cleanup fails.
"""
client = WebSocketClient(port=self._port)
command_sender = StreamDeckCommandSender(client, plugin_registration_uuid=self._registration_uuid)
transport = WebSocketTransport(port=self._port)
command_sender = StreamDeckCommandSender(transport, plugin_registration_uuid=self._registration_uuid)
self._injectable_handler_param_store.register(
"command_sender",
lambda _event_data: command_sender,
Expand All @@ -196,15 +199,15 @@ async def run(self) -> None:

primary_error: BaseException | None = None
try:
async with client:
# Register the WebSocketClient as an event listener, so we can receive Stream Deck events.
self.register_event_listener(client)
async with transport:
# Register a WebSocketEventListener, so we can receive Stream Deck events.
self.register_event_listener(WebSocketEventListener(transport))

await command_sender.send_action_registration(register_event=self._register_event)

async with aclosing(self._stream_event_data()) as event_data_stream:
async for data in event_data_stream:
await self._dispatch_event(data)
await EventStreamProcessor(
dispatch=self._dispatch_event,
).run(self._stream_event_data())

logger.info("PluginManager has stopped processing events.")
except BaseException as exc:
Expand All @@ -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__,
)
Loading
Loading