diff --git a/.changeset/emitter-once-reject-async.md b/.changeset/emitter-once-reject-async.md new file mode 100644 index 000000000..ff1cecb35 --- /dev/null +++ b/.changeset/emitter-once-reject-async.md @@ -0,0 +1,5 @@ +--- +"livekit-rtc": patch +--- + +`EventEmitter.once()` now raises `ValueError` for an async callback, as `.on()` already did, instead of registering a handler that never ran. Both methods also reject an instance whose class defines `async def __call__`. Code that passed an async callback to `.once()`, including `@room.once(...)` on an `async def`, now fails at registration and should use a synchronous callback that starts a task. diff --git a/livekit-rtc/livekit/rtc/event_emitter.py b/livekit-rtc/livekit/rtc/event_emitter.py index 38f549011..e5e8e2f76 100644 --- a/livekit-rtc/livekit/rtc/event_emitter.py +++ b/livekit-rtc/livekit/rtc/event_emitter.py @@ -1,4 +1,5 @@ import asyncio +import functools import inspect from typing import Any, Callable, Dict, Optional, Generic, TypeVar @@ -13,6 +14,34 @@ # function in 3.16, and a bare attribute access would then fail at import time. _ASYNCIO_COROUTINE_MARKER = getattr(asyncio.coroutines, "_is_coroutine", None) + +def _check_async_callback(callback: Callable, method_name: str) -> None: + # A partial is checked by what it wraps, since that is what calling it runs. + target = callback + while isinstance(target, functools.partial): + target = target.func + + if ( + inspect.iscoroutinefunction(target) + or ( + _ASYNCIO_COROUTINE_MARKER is not None + and getattr(target, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER + ) + # An instance whose class defines `async def __call__`. A class itself is left + # alone: calling it only constructs an instance, which is synchronous. + or ( + not inspect.isclass(target) + and inspect.iscoroutinefunction(getattr(target, "__call__", None)) + ) + ): + raise ValueError( + f"Cannot register an async callback with `.{method_name}()`. Use " + "`asyncio.create_task` within your synchronous callback instead, and keep a " + "reference to the returned task until it finishes: the event loop only holds " + "a weak reference, so an unreferenced task can be garbage-collected early." + ) + + T_contra = TypeVar("T_contra", contravariant=True) @@ -115,6 +144,7 @@ def greet_once(name): ``` """ if callback is not None: + _check_async_callback(callback, "once") def once_callback(*args: Any, **kwargs: Any) -> None: self.off(event, once_callback) @@ -169,13 +199,7 @@ def greet(name): ``` """ if callback is not None: - if inspect.iscoroutinefunction(callback) or ( - _ASYNCIO_COROUTINE_MARKER is not None - and getattr(callback, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER - ): - raise ValueError( - "Cannot register an async callback with `.on()`. Use `asyncio.create_task` within your synchronous callback instead." - ) + _check_async_callback(callback, "on") if event not in self._events: self._events[event] = {} diff --git a/tests/rtc/test_emitter.py b/tests/rtc/test_emitter.py index 4f67f76a4..7bbff57b9 100644 --- a/tests/rtc/test_emitter.py +++ b/tests/rtc/test_emitter.py @@ -186,6 +186,138 @@ def test_on_rejects_async_mock() -> None: emitter.on("connected", AsyncMock()) +def test_once_rejects_async_callback() -> None: + """`.once()` refuses coroutine functions, however they are spelled.""" + EventTypes = Literal["connected"] + + emitter = EventEmitter[EventTypes]() + + async def on_connected() -> None: + pass + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", on_connected) + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", functools.partial(on_connected)) + + with pytest.raises(ValueError, match="Cannot register an async callback"): + + @emitter.once("connected") + async def on_connected_decorated() -> None: + pass + + +def test_once_rejects_sentinel_tagged_callback() -> None: + """A callable tagged with asyncio's private coroutine sentinel is rejected by `.once()`.""" + marker = getattr(asyncio.coroutines, "_is_coroutine", None) + if marker is None: + pytest.skip("asyncio.coroutines._is_coroutine is not defined on this Python") + + EventTypes = Literal["connected"] + + emitter = EventEmitter[EventTypes]() + + def on_connected() -> None: + pass + + on_connected._is_coroutine = marker # type: ignore[attr-defined] + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", on_connected) + + +def test_once_rejects_async_mock() -> None: + """`AsyncMock` is rejected by `.once()` on every supported version.""" + EventTypes = Literal["connected"] + + emitter = EventEmitter[EventTypes]() + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", AsyncMock()) + + +class _AsyncCallable: + async def __call__(self, *args: Any) -> None: + pass + + +def test_rejects_instance_with_async_call() -> None: + """An instance whose class defines `async def __call__` is rejected by `.on()` and `.once()`.""" + emitter = EventEmitter[str]() + + with pytest.raises(ValueError, match=r"Cannot register an async callback with `\.on\(\)`"): + emitter.on("connected", _AsyncCallable()) + + with pytest.raises(ValueError, match=r"Cannot register an async callback with `\.once\(\)`"): + emitter.once("connected", _AsyncCallable()) + + # nothing was registered, so emitting creates no never-awaited coroutine + with warnings.catch_warnings(): + warnings.simplefilter("error") + emitter.emit("connected") + + +def test_accepts_sync_callable_instance_and_class() -> None: + """Sync callable instances stay accepted, and so does a class: calling it only constructs it.""" + emitter = EventEmitter[str]() + calls: list[str] = [] + + class SyncCallable: + def __call__(self) -> None: + calls.append("instance") + + class Constructed: + def __init__(self) -> None: + calls.append("class") + + async def __call__(self) -> None: + pass + + emitter.on("connected", SyncCallable()) + emitter.once("connected", Constructed) + + emitter.emit("connected") + emitter.emit("connected") + assert calls == ["instance", "class", "instance"] + + +def test_partial_is_checked_by_what_it_wraps() -> None: + """A partial of an async callable instance is rejected; one of a sync instance is not.""" + emitter = EventEmitter[str]() + + for wrapped in ( + functools.partial(_AsyncCallable(), "label"), + functools.partial(functools.partial(_AsyncCallable(), "label")), + ): + with pytest.raises(ValueError, match=r"`\.on\(\)`"): + emitter.on("connected", wrapped) + with pytest.raises(ValueError, match=r"`\.once\(\)`"): + emitter.once("connected", wrapped) + + calls: list[str] = [] + + class SyncCallable: + def __call__(self, label: str) -> None: + calls.append(label) + + emitter.on("connected", functools.partial(SyncCallable(), "on")) + emitter.once("connected", functools.partial(SyncCallable(), "once")) + emitter.emit("connected") + assert calls == ["on", "once"] + + +def test_async_callback_error_says_to_keep_a_task_reference() -> None: + emitter = EventEmitter[str]() + + async def on_connected() -> None: + pass + + for register in (emitter.on, emitter.once): + with pytest.raises(ValueError, match="keep a reference to the returned task"): + register("connected", on_connected) + + class _OrderedHandler: """A callable whose hash is fixed, so a set orders it independently of registration."""