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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"pydantic-settings[toml] >= 2.11",
"typing-extensions >= 4.14.0",
"exceptiongroup >= 1.3.1; python_version < '3.11'",
"taskgroup >= 0.2.2; python_version < '3.11'",
]

[project.urls]
Expand Down
10 changes: 5 additions & 5 deletions streamdeck/command_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async def set_settings(self, context: ActionInstanceIdStr, payload: PluginDefine
payload=payload,
)

async def get_settings(self, context: ActionInstanceUUIDStr) -> None:
async def get_settings(self, context: ActionInstanceIdStr) -> None:
await self._send_event("getSettings", context=context)

async def set_global_settings(self, payload: PluginDefinedData) -> None:
Expand All @@ -64,14 +64,14 @@ async def get_global_settings(self) -> None:
context=self._plugin_registration_uuid,
)

async def open_url(self, context: ActionInstanceUUIDStr, url: str) -> None:
async def open_url(self, context: ActionInstanceIdStr, url: str) -> None:
await self._send_event(
event="openUrl",
context=context,
payload={"url": url},
)

async def log_message(self, context: ActionInstanceUUIDStr, message: str) -> None:
async def log_message(self, context: ActionInstanceIdStr, message: str) -> None:
await self._send_event(
event="logMessage",
context=context,
Expand All @@ -80,7 +80,7 @@ async def log_message(self, context: ActionInstanceUUIDStr, message: str) -> Non

async def set_title(
self,
context: ActionInstanceUUIDStr,
context: ActionInstanceIdStr,
state: int | None = None,
target: Literal["hardware", "software", "both"] | None = None,
title: str | None = None,
Expand All @@ -102,7 +102,7 @@ async def set_title(

async def set_image(
self,
context: ActionInstanceUUIDStr,
context: ActionInstanceIdStr,
image: str, # base64 encoded image,
target: Literal["hardware", "software", "both"],
state: int,
Expand Down
2 changes: 0 additions & 2 deletions streamdeck/event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@

from typing_extensions import sentinel


if sys.version_info < (3, 11):
# ExceptionGroup is built in starting with Python 3.11.
from exceptiongroup import ExceptionGroup


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