Skip to content
Merged
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
26 changes: 9 additions & 17 deletions streamdeck/event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,22 @@
from logging import getLogger
from queue import Queue
from typing import TYPE_CHECKING
from typing_extensions import sentinel


if TYPE_CHECKING:
from collections.abc import Generator, Iterator
from typing import ClassVar

from typing_extensions import TypeIs

from streamdeck.models.events import EventBase



logger = getLogger("streamdeck.event_listener")


class _SENTINAL:
"""A sentinel object used to signal the end of the event stream.

Not meant to be instantiated, but rather used as a singleton (e.g. `_SENTINAL`).
"""
@classmethod
def is_sentinal(cls, event: str | bytes | type[_SENTINAL]) -> TypeIs[type[_SENTINAL]]:
"""Check if an event is the sentinal object. Provided to enable better type-checking."""
return event is cls
_END_OF_STREAM = sentinel("_END_OF_STREAM")
"""Sentinel object used to signal the end of the event stream."""


class StopStreaming(Exception): # noqa: N818
Expand All @@ -42,7 +34,7 @@ class EventListenerManager:
This allows for us to listen for not only Stream Deck events, but also other events plugin-developer -defined events.
"""
def __init__(self) -> None:
self.event_queue: Queue[str | bytes | type[_SENTINAL]] = Queue()
self.event_queue: Queue[str | bytes | _END_OF_STREAM] = Queue()
self.listeners_lookup_by_thread: dict[threading.Thread, EventListener] = {}
self._running = False

Expand Down Expand Up @@ -71,7 +63,7 @@ def _listener_wrapper(self, listener: EventListener) -> None:

except StopStreaming:
logger.debug("Event listener requested to stop streaming.")
self.event_queue.put(_SENTINAL)
self.event_queue.put(_END_OF_STREAM)

except Exception:
logger.exception("Unexpected error in wrapped listener %s. Stopping just this listener.", listener)
Expand All @@ -84,7 +76,7 @@ def stop(self) -> None:
# 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(_SENTINAL)
self.event_queue.put(_END_OF_STREAM)

for thread in self.listeners_lookup_by_thread:
logger.debug("Stopping listener %s.")
Expand All @@ -105,9 +97,9 @@ def event_stream(self) -> Generator[str | bytes, None, None]:
try:
while True:
event = self.event_queue.get()
if _SENTINAL.is_sentinal(event):
logger.debug("Sentinal received, stopping event stream.")
break # Exit loop immediately if the sentinal is received
if event is _END_OF_STREAM:
logger.debug("Sentinel received, stopping event stream.")
break # Exit loop immediately if the sentinel is received
yield event
finally:
self.stop()
Expand Down
22 changes: 21 additions & 1 deletion tests/event_listener/test_event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from unittest.mock import Mock, patch

import pytest
from streamdeck.event_listener import EventListener, EventListenerManager
from streamdeck.event_listener import EventListener, EventListenerManager, StopStreaming
from streamdeck.models.events import ApplicationDidLaunch, EventBase


Expand Down Expand Up @@ -73,6 +73,18 @@ def stop(self) -> None:
pass


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 ()
raise StopStreaming

def stop(self) -> None:
pass




def test_add_listener():
Expand Down Expand Up @@ -110,6 +122,14 @@ def test_event_stream_basic():
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()
Expand Down
Loading