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
5 changes: 5 additions & 0 deletions .changeset/emitter-once-reject-async.md
Original file line number Diff line number Diff line change
@@ -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.
38 changes: 31 additions & 7 deletions livekit-rtc/livekit/rtc/event_emitter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import functools
import inspect
from typing import Any, Callable, Dict, Optional, Generic, TypeVar

Expand All @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing, optional: an instance of a class with async def __call__ still passes this check for both .on() and .once(), since neither inspect.iscoroutinefunction(callback) nor the _is_coroutine marker looks at callback.__call__. On emit the coroutine is created and dropped with a "never awaited" warning, and the handler never runs.

class H:
    async def __call__(self, *args): ...

emitter.once("connected", H())  # accepted

Since this helper is now shared, it would be a cheap place to also reject inspect.iscoroutinefunction(getattr(callback, "__call__", 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))
)
Comment thread
NabiBukhsh-AI marked this conversation as resolved.
Resolved
):
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)


Expand Down Expand Up @@ -115,6 +144,7 @@ def greet_once(name):
```
"""
if callback is not None:
_check_async_callback(callback, "once")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: This is a user-visible behavior change. Passing an async callback to .once() used to register without error (the handler just never ran); it now raises ValueError, and for a module-level @room.once(...) async def ... that happens at import time. Could you add a .changeset/*.md entry (patch, livekit-rtc) so it shows up in the release notes? Recent fix PRs (#918, #936, #942, #945) all include one.


def once_callback(*args: Any, **kwargs: Any) -> None:
self.off(event, once_callback)
Expand Down Expand Up @@ -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] = {}
Expand Down
132 changes: 132 additions & 0 deletions tests/rtc/test_emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
Loading