diff --git a/docs/events/chaining_events.md b/docs/events/chaining_events.md index 2e3078844fe..36498a203ac 100644 --- a/docs/events/chaining_events.md +++ b/docs/events/chaining_events.md @@ -90,11 +90,12 @@ state. ```md alert info # Rules for awaiting event handlers -- Only inside an event handler (or `app.modify_state`); awaiting a handler anywhere else raises an error. +- Only inside an event handler (or `app.modify_state`); awaiting a handler anywhere else, such as in an API route outside `app.modify_state`, raises an error. - Calling the handler, like `State.add(5)`, only binds its arguments. Nothing runs until it is awaited, so it can still be returned or yielded as before. Each `await` runs it again. - A background task awaiting a handler outside `async with self` queues the event and waits for it to finish; inside `async with self` the handler runs right away on the locked state. - A background handler cannot be awaited while the state lock is held, as it would wait for that lock. `yield` it instead. - Frontend-only events like `rx.redirect` cannot be awaited. `yield` or return them. +- Only backend code that awaits a handler receives a non-event return value. When the handler runs from an event trigger, such as `on_click`, such a value is dropped, and in dev mode a warning says so; returned events are still chained. - An awaited handler passes through the app's middleware like any other event. If a middleware blocks it, the handler does not run and the `await` returns `None`. - Awaiting several handlers at once with `asyncio.gather` works, but they run concurrently on the same state and interleave at every `await` inside them. Await them one at a time when order matters. - A task started from a handler, like `asyncio.ensure_future(State.add(1))`, keeps the state lock held until it finishes when it starts before the handler returns. If the handler returns first, the task's handler is queued like a yielded event and runs under its own lock. @@ -108,6 +109,8 @@ In Reflex, event handlers run synchronously, so only one event handler can run a ```md alert info # Be sure to use the class name `State` (or any substate) rather than `self` when returning events. + +Returning `self.handler` instead of `type(self).handler`, or an event like `rx.redirect` without calling it, raises an error naming your handler. ``` Try entering an integer in the input below then clicking out. diff --git a/news/+mistaken-handler-return-values.bugfix.md b/news/+mistaken-handler-return-values.bugfix.md new file mode 100644 index 00000000000..a107539d4fb --- /dev/null +++ b/news/+mistaken-handler-return-values.bugfix.md @@ -0,0 +1 @@ +An event handler may return a value that is not an event, which backend code that `await`s the handler receives; returned events still chain and a returned coroutine still raises. Returning `self.other_handler` (meant `type(self).other_handler`), an uncalled event creator such as `rx.redirect`, or a list holding one raises the "must only return/yield" `TypeError` again, as in 0.10, instead of silently doing nothing; for an uncalled event creator the error asks "Did you mean to call it: rx.redirect(...)?". A non-event value returned by a handler that an event trigger such as `on_click` ran is dropped, and in dev mode a warning names the handler once. diff --git a/packages/reflex-base/news/+await-handler-without-token.bugfix.md b/packages/reflex-base/news/+await-handler-without-token.bugfix.md new file mode 100644 index 00000000000..5ddcc3dc3b4 --- /dev/null +++ b/packages/reflex-base/news/+await-handler-without-token.bugfix.md @@ -0,0 +1 @@ +Awaiting an event handler in an API route or other request code outside `app.modify_state` now raises `EventHandlerTypeError` instead of running it on one state shared by every caller. diff --git a/packages/reflex-base/news/+mistaken-handler-return-values.bugfix.md b/packages/reflex-base/news/+mistaken-handler-return-values.bugfix.md new file mode 100644 index 00000000000..a107539d4fb --- /dev/null +++ b/packages/reflex-base/news/+mistaken-handler-return-values.bugfix.md @@ -0,0 +1 @@ +An event handler may return a value that is not an event, which backend code that `await`s the handler receives; returned events still chain and a returned coroutine still raises. Returning `self.other_handler` (meant `type(self).other_handler`), an uncalled event creator such as `rx.redirect`, or a list holding one raises the "must only return/yield" `TypeError` again, as in 0.10, instead of silently doing nothing; for an uncalled event creator the error asks "Did you mean to call it: rx.redirect(...)?". A non-event value returned by a handler that an event trigger such as `on_click` ran is dropped, and in dev mode a warning names the handler once. diff --git a/packages/reflex-base/src/reflex_base/event/__init__.py b/packages/reflex-base/src/reflex_base/event/__init__.py index 2fdaa2ae71f..6e64c2a4883 100644 --- a/packages/reflex-base/src/reflex_base/event/__init__.py +++ b/packages/reflex-base/src/reflex_base/event/__init__.py @@ -467,6 +467,11 @@ def temporal(self) -> Self: ) +# Set on the stand-in a background handler binds to on a state instance, so a +# returned or yielded `self.background_handler` is recognized as a mistake. +_BOUND_BACKGROUND_TASK_MARKER = "_reflex_bound_background_task" + + def _no_chain_background_task(state: "BaseState", fn: Callable) -> Callable: """Protect against directly chaining a background task from another event handler. @@ -491,17 +496,45 @@ def _no_chain_background_task(state: "BaseState", fn: Callable) -> Callable: async def _no_chain_background_task_co(*args, **kwargs): # noqa: RUF029 raise RuntimeError(message) - return _no_chain_background_task_co - if inspect.isasyncgenfunction(fn): + no_chain = _no_chain_background_task_co + elif inspect.isasyncgenfunction(fn): async def _no_chain_background_task_gen(*args, **kwargs): # noqa: RUF029 yield raise RuntimeError(message) - return _no_chain_background_task_gen + no_chain = _no_chain_background_task_gen + else: + msg = f"{fn} is marked as a background task, but is not async." + raise TypeError(msg) + setattr(no_chain, _BOUND_BACKGROUND_TASK_MARKER, True) + return no_chain + + +def _is_bound_event_handler(value: Any) -> bool: + """Whether a value is an event handler accessed through a state instance. + + That is what ``self.handler`` evaluates to (see ``EventHandler.__get__``): + returned or yielded as an event, it is a mistake for ``type(self).handler``. + An inherited handler accessed through a background task's state proxy is a + ``functools.partial`` and is not recognized. - msg = f"{fn} is marked as a background task, but is not async." - raise TypeError(msg) + Args: + value: The value to check. + + Returns: + True for a handler's function bound to its state, or to a proxy of it, + and for the stand-in a background handler binds to. + """ + if type(value) is not types.MethodType: + return getattr(value, _BOUND_BACKGROUND_TASK_MARKER, None) is True + func = value.__func__ + handlers = getattr(value.__self__, "event_handlers", None) + return ( + isinstance(handlers, dict) + and (handler := handlers.get(func.__name__)) is not None + and handler.fn is func + ) def _base_state_type() -> type: @@ -3544,6 +3577,7 @@ class EventNamespace: resolve_upload_chunk_handler_param ) _values_returned_from_event = staticmethod(_values_returned_from_event) + _is_bound_event_handler = staticmethod(_is_bound_event_handler) _check_event_args_subclass_of_callback = staticmethod( _check_event_args_subclass_of_callback ) diff --git a/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py b/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py index 18d4435b376..ea550af4799 100644 --- a/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py +++ b/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py @@ -7,11 +7,13 @@ import functools import inspect import logging +import sys import warnings from collections.abc import Mapping, Sequence from enum import Enum from importlib.util import find_spec from time import perf_counter +from types import FunctionType, MethodType from typing import TYPE_CHECKING, Any from reflex.istate.manager.token import BaseStateToken @@ -19,7 +21,7 @@ from reflex.utils import types from reflex_base import otel from reflex_base.constants import CompileVars -from reflex_base.event import Event, EventHandler, EventSpec +from reflex_base.event import Event, EventHandler, EventSpec, _is_bound_event_handler from reflex_base.event.context import EventContext from reflex_base.event.processor.event_processor import EventProcessor, EventQueueEntry from reflex_base.event.processor.future import EventFuture @@ -101,21 +103,99 @@ def _is_empty_sequence(value: Any) -> bool: return is_non_string_sequence(value) and len(value) == 0 -def _holds_events_or_coroutines(value: Any) -> bool: - """Whether a sequence holds an event or an unawaited coroutine. +def _creator_function(value: Any) -> Any: + """The function that runs when a callable is called. + + Args: + value: A callable. + + Returns: + The callable itself for a function or method, else its class's + ``__call__`` (for a callable object such as ``rx.toast``). + """ + return ( + value if isinstance(value, (FunctionType, MethodType)) else type(value).__call__ + ) + + +def _is_event_creator(value: Any) -> bool: + """Whether a callable is declared to return an EventSpec, like ``rx.redirect``. + + Reflex does not mark its event creators, but each one (``rx.redirect``, + ``rx.call_script``, ``rx.toast`` ...) is annotated to return the EventSpec it + creates, as are helpers wrapping them. Returned uncalled, such a callable is a + mistake for the event it would create, never a result. + + Args: + value: The callable a handler returned. + + Returns: + True if the function, or the ``__call__`` of a callable object such as + ``rx.toast``, is annotated to return an EventSpec. + """ + try: + returns = _creator_function(value).__annotations__.get("return") + except (AttributeError, NameError): + # Not annotated (a builtin, a class), or a deferred annotation naming + # something undefined. + return False + if isinstance(returns, str): + return returns.rpartition(".")[2] == "EventSpec" + return isinstance(returns, type) and issubclass(returns, EventSpec) + + +def _creator_reference(creator: Any) -> str: + """How to name an event creator in the hint to call it. + + Args: + creator: The uncalled event creator. + + Returns: + ``rx.`` when reflex exports the creator's function under its own + name, as for ``rx.redirect``, else the function's qualified name. + """ + fn = _creator_function(creator) + if getattr(sys.modules.get("reflex"), fn.__name__, None) is creator: + return f"rx.{fn.__name__}" + return fn.__qualname__ + + +def _is_mistaken_event(value: Any) -> bool: + """Whether a value can only be an event its handler failed to reference or call. Args: value: The value a handler returned. Returns: - True for a sequence ``_is_event_like`` rejects that still holds an - event (mixed with other values) or a coroutine. + True for ``self.handler`` (meant ``type(self).handler``) and for an + uncalled event creator such as ``rx.redirect``. """ + return callable(value) and ( + _is_bound_event_handler(value) or _is_event_creator(value) + ) + + +def _is_invalid_result(value: Any) -> bool: + """Whether a return value ``_is_event_like`` rejects is a bug rather than a result. + + Args: + value: The value a handler returned. + + Returns: + True for a coroutine that was never awaited, a mistaken event, and a + sequence that holds an event (mixed with other values), a coroutine or + a mistaken event. + """ + if inspect.iscoroutine(value) or _is_mistaken_event(value): + return True if not is_non_string_sequence(value): return False try: return any( - isinstance(e, _EVENT_LIKE_TYPES) or inspect.iscoroutine(e) for e in value + isinstance(e, _EVENT_LIKE_TYPES) + or inspect.iscoroutine(e) + or _is_mistaken_event(e) + for e in value ) except TypeError: return False @@ -152,6 +232,15 @@ def _check_valid_yield(events: Any, handler_name: str = "unknown") -> Any: f"Your handler {handler_name} must only return/yield: None, Events or other EventHandlers referenced by their class (i.e. using `type(self)` or other class references)." f" Returned events of types {', '.join(map(str, map(type, events)))!s}." ) + if creators := [ + e + for e in events + if callable(e) and not isinstance(e, _EVENT_LIKE_TYPES) and _is_event_creator(e) + ]: + msg += ( + f" Did you mean to call {'it' if len(creators) == 1 else 'them'}: " + f"{', '.join(f'{_creator_reference(c)}(...)' for c in creators)}?" + ) raise TypeError(msg) @@ -483,22 +572,28 @@ async def execute_event_inline(spec: EventSpec) -> Any: The handler's return value. Raises: - EventHandlerTypeError: If there is no active EventContext, the spec is - a frontend-only or upload event, or a background handler is - awaited while the state lock is held (which would deadlock). + EventHandlerTypeError: If there is no active EventContext for a + client (outside an event handler and ``app.modify_state``), the + spec is a frontend-only or upload event, or a background handler + is awaited while the state lock is held (which would deadlock). """ from reflex_base.registry import RegistrationContext from reflex_base.utils.exceptions import EventHandlerTypeError try: ctx = EventContext.get() - except LookupError as le: + except LookupError: + ctx = None + # The event processor's root context, which every request to the app + # carries, belongs to no client: running there would share one state + # between every caller. + if ctx is None or not ctx.token: msg = ( f"Event handler `{format_event_handler(spec.handler)}` can only be " "awaited from an event handler or inside `app.modify_state`; use it " "as an event trigger or yield it instead." ) - raise EventHandlerTypeError(msg) from le + raise EventHandlerTypeError(msg) event = spec._to_event(ctx.router_data) name = event.name if spec.client_handler_name: @@ -621,10 +716,11 @@ async def process_event( handler_name=handler_name, ) return None - # A coroutine that was never awaited, or events mixed with other values, - # is a bug, not a result: chain_updates flushes the delta and then raises - # for it, as it does for any invalid yield. - invalid = inspect.iscoroutine(events) or _holds_events_or_coroutines(events) + # A coroutine that was never awaited, a mistaken event like `self.handler` + # or `rx.redirect`, or events mixed with other values, is a bug, not a + # result: chain_updates flushes the delta and then raises for it, as it + # does for any invalid yield. + invalid = _is_invalid_result(events) await chain_updates( events if invalid else None, root_state=ensure_locked(state, root_state), diff --git a/reflex/app.py b/reflex/app.py index d4c8a376a97..c946a6e5ad2 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -2314,6 +2314,12 @@ def __init__(self, namespace: str, app: App): self._client_error_window_start = 0.0 self._client_error_window_count = 0 + # In dev, warn about values that handlers triggered from the frontend + # return, which nothing receives. Read once: on_event is the hot path. + self._warn_dropped_results = not is_prod_mode() + # The handlers already warned about, so each warns once. + self._warned_dropped_results: set[str] = set() + @property def token_to_sid(self) -> Mapping[str, str]: """Token to SID mapping for backward compatibility. @@ -2598,10 +2604,42 @@ async def on_event(self, sid: str, data: Any): else "404" ).removeprefix("/") if not otel.enabled: - await self.app.event_processor.enqueue(token, event) + future = await self.app.event_processor.enqueue(token, event) + else: + with otel.remote_context(fields): + future = await self.app.event_processor.enqueue(token, event) + if self._warn_dropped_results: + future.add_done_callback( + functools.partial(self._warn_dropped_result, event.name) + ) + + def _warn_dropped_result(self, name: str, future: asyncio.Future) -> None: + """Warn once per handler that a frontend event's return value is dropped. + + The frontend event discards its future, so only backend code awaiting + the handler receives what it returns. + + Args: + name: The name of the event the frontend sent. + future: The event's future, done. + """ + if future.cancelled() or future.exception() is not None: + return + result = future.result() + # An empty list is how a handler said "no events" before return + # values were results. + if result is None or (is_non_string_sequence(result) and not result): return - with otel.remote_context(fields): - await self.app.event_processor.enqueue(token, event) + if name in self._warned_dropped_results: + return + self._warned_dropped_results.add(name) + handler = self.app._registration_context.event_handlers[name].handler + logger.warning( + f"Event handler {handler.fn.__qualname__} returned a value, but it was " + "triggered from the frontend, so the value is dropped: only backend " + "code that awaits the handler receives its return value. Return None " + "or events to chain from a handler used as an event trigger." + ) async def on_ping(self, sid: str): """Event for testing the API endpoint. diff --git a/tests/benchmarks/test_event_processing.py b/tests/benchmarks/test_event_processing.py index 46ec2c943a2..b00d51a7799 100644 --- a/tests/benchmarks/test_event_processing.py +++ b/tests/benchmarks/test_event_processing.py @@ -437,8 +437,14 @@ def on_event_harness(): """ from reflex.app import App, EventNamespace + loop = asyncio.new_event_loop() + # A real, already resolved future, like the EventFuture enqueue returns: + # the mock's default return value would bill on_event's use of the future + # (a done callback in dev mode) as mock call bookkeeping. + done = loop.create_future() + done.set_result(None) app = App() - app._event_processor = mock.Mock(enqueue=mock.AsyncMock()) + app._event_processor = mock.Mock(enqueue=mock.AsyncMock(return_value=done)) namespace = EventNamespace("/event", app) sid = "benchmark-sid" @@ -478,7 +484,6 @@ async def run_events(num_events: int) -> None: }, ) - loop = asyncio.new_event_loop() loop.run_until_complete(namespace.on_connect(sid, environ)) yield run_events, loop loop.close() diff --git a/tests/units/reflex_base/event/processor/test_base_state_processor.py b/tests/units/reflex_base/event/processor/test_base_state_processor.py index d086708b473..b79f3bb649b 100644 --- a/tests/units/reflex_base/event/processor/test_base_state_processor.py +++ b/tests/units/reflex_base/event/processor/test_base_state_processor.py @@ -4,13 +4,15 @@ import collections import contextlib import dataclasses +import functools import gc import inspect import logging import traceback +import unittest.mock import warnings import weakref -from collections.abc import Mapping +from collections.abc import Callable, Mapping from pathlib import Path from typing import Any, cast @@ -30,10 +32,11 @@ ) from reflex_base.registry import RegistrationContext from reflex_base.utils.form import FORM_DATA_ENTRIES_KEY, FormData +from reflex_base.utils.types import Receive, Scope, Send import reflex as rx from reflex import event -from reflex.app import App, EventNamespace +from reflex.app import App, EventNamespace, _RootMiddleware from reflex.compiler.utils import compile_state from reflex.event import Event, EventHandler, EventSpec from reflex.istate.delta import Delta @@ -4032,6 +4035,280 @@ async def compute(self, x: int) -> int: assert await future == 2 +def _mistaken_return_state(): + """Define a state whose handlers return or yield mistaken and valid events. + + Returns: + The state class, registered in the test's registration context. + """ + + class MistakenReturnState(State): + """Handlers that return or yield something only mistakable for an event.""" + + target_runs: int = 0 + + @event + def target(self): + self.target_runs += 1 + + @event(background=True) + async def bg_target(self): + async with self: + self.target_runs += 1 + + def _helper(self) -> int: + return self.target_runs + + @event + def returns_bound_handler(self): + return self.target + + @event + async def async_returns_bound_handler(self): + return self.target + + @event + def generator_returns_bound_handler(self): + yield + return self.target # noqa: B901 + + @event + def returns_bound_background_handler(self): + return self.bg_target + + @event(background=True) + async def background_returns_bound_handler(self): + return self.target + + @event + def returns_uncalled_redirect(self): + return rx.redirect + + @event + def returns_uncalled_toast(self): + return rx.toast + + @event + def returns_uncalled_toast_success(self): + return rx.toast.success + + @event + def returns_list_holding_bound_handler(self): + return [self.target] + + @event + def returns_tuple_holding_uncalled_call_script(self): + return (rx.call_script,) + + @event + def returns_list_holding_uncalled_creators(self): + return [rx.redirect, rx.toast] + + @event + def yields_bound_handler(self): + yield self.target + + @event + async def async_yields_bound_handler(self): + yield self.target + + @event + def yields_uncalled_redirect(self): + yield rx.redirect + + @event + async def awaits_bound_handler_return(self): + await type(self).returns_bound_handler() + + @event + def returns_bound_helper(self): + return self._helper + + @event + def returns_plain_function(self): + return len + + @event + def returns_partial(self): + return functools.partial(len) + + @event + def returns_permissive_callable(self): + # Answers every attribute lookup, so a marker check must not be hasattr. + return unittest.mock.Mock() + + @event + def returns_class_reference(self): + return type(self).target + + @event + def returns_called_redirect(self): + return rx.redirect("/x") + + @event + def returns_list_of_class_references(self): + return [type(self).target, type(self).target] + + return MistakenReturnState + + +@pytest.mark.parametrize( + ("handler_name", "hint"), + [ + ("returns_bound_handler", None), + ("async_returns_bound_handler", None), + ("generator_returns_bound_handler", None), + ("returns_bound_background_handler", None), + ("background_returns_bound_handler", None), + ("returns_uncalled_redirect", "Did you mean to call it: rx.redirect(...)?"), + ("returns_uncalled_toast", "Did you mean to call it: Toaster.send_toast(...)?"), + ( + "returns_uncalled_toast_success", + "Did you mean to call it: Toaster.toast_success(...)?", + ), + ("returns_list_holding_bound_handler", None), + ( + "returns_tuple_holding_uncalled_call_script", + "Did you mean to call it: rx.call_script(...)?", + ), + ( + "returns_list_holding_uncalled_creators", + "Did you mean to call them: rx.redirect(...), Toaster.send_toast(...)?", + ), + ("yields_bound_handler", None), + ("async_yields_bound_handler", None), + ("yields_uncalled_redirect", "Did you mean to call it: rx.redirect(...)?"), + ("awaits_bound_handler_return", None), + ], +) +async def test_returned_mistaken_event_raises_type_error( + wired_app: App, + real_base_state_processor: BaseStateEventProcessor, + token: str, + handler_name: str, + hint: str | None, +): + """A bound handler or an uncalled event creator is a mistaken event, never a result. + + ``return self.target`` (for ``type(self).target``) and ``return rx.redirect`` + (for ``rx.redirect(...)``) raise the error naming the handler, as they did + before return values became results, instead of silently doing nothing. An + uncalled event creator adds a hint naming it. + + Args: + wired_app: The App wired to the processor's state manager. + real_base_state_processor: The unmocked BaseStateEventProcessor. + token: The client token. + handler_name: The MistakenReturnState handler to run. + hint: The hint that ends the message, or None when there is none. + """ + MistakenReturnState = _mistaken_return_state() + handler = getattr(MistakenReturnState, handler_name) + raising = ( + "returns_bound_handler" + if handler_name == "awaits_bound_handler_return" + else handler_name + ) + captured: list[Exception] = [] + real_base_state_processor.backend_exception_handler = captured.append + async with real_base_state_processor as processor: + future = await processor.enqueue(token, Event.from_event_type(handler())[0]) + with pytest.raises( + TypeError, + match=rf"Your handler \S*MistakenReturnState\.{raising} must only return/yield", + ) as exc_info: + await future + await processor.join(5) + assert len(captured) == 1 + message = str(exc_info.value) + if hint is None: + assert "Did you mean" not in message + else: + assert message.endswith(f". {hint}") + async with _read_back(real_base_state_processor, token) as root: + assert (await root.get_state(MistakenReturnState)).target_runs == 0 + + +@pytest.mark.parametrize( + ("handler_name", "is_expected"), + [ + ("returns_bound_helper", lambda result, cls: result.__func__ is cls._helper), + ("returns_plain_function", lambda result, cls: result is len), + ( + "returns_partial", + lambda result, cls: isinstance(result, functools.partial), + ), + ( + "returns_permissive_callable", + lambda result, cls: isinstance(result, unittest.mock.Mock), + ), + ], +) +async def test_returned_callable_that_is_not_an_event_resolves_future( + wired_app: App, + real_base_state_processor: BaseStateEventProcessor, + token: str, + handler_name: str, + is_expected: Callable[[Any, Any], bool], +): + """A callable that is not a handler or an event creator is still a result. + + Args: + wired_app: The App wired to the processor's state manager. + real_base_state_processor: The unmocked BaseStateEventProcessor. + token: The client token. + handler_name: The MistakenReturnState handler to run. + is_expected: Whether the future resolved to the value returned. + """ + MistakenReturnState = _mistaken_return_state() + handler = getattr(MistakenReturnState, handler_name) + async with real_base_state_processor as processor: + result = await ( + await processor.enqueue(token, Event.from_event_type(handler())[0]) + ) + assert is_expected(result, MistakenReturnState) + + +@pytest.mark.parametrize( + ("handler_name", "target_runs", "client_event"), + [ + ("returns_class_reference", 1, None), + ("returns_list_of_class_references", 2, None), + ("returns_called_redirect", 0, "_redirect"), + ], +) +async def test_returned_event_reference_still_chains( + wired_app: App, + real_base_state_processor: BaseStateEventProcessor, + emitted_events: list[tuple[str, tuple[Event, ...]]], + token: str, + handler_name: str, + target_runs: int, + client_event: str | None, +): + """A class reference to a handler, or a called event creator, chains as before. + + Args: + wired_app: The App wired to the processor's state manager. + real_base_state_processor: The unmocked BaseStateEventProcessor. + emitted_events: List to capture events emitted to the client. + token: The client token. + handler_name: The MistakenReturnState handler to run. + target_runs: How many times the chained ``target`` runs. + client_event: The frontend event the handler emits, if any. + """ + MistakenReturnState = _mistaken_return_state() + handler = getattr(MistakenReturnState, handler_name) + async with real_base_state_processor as processor: + future = await processor.enqueue(token, Event.from_event_type(handler())[0]) + assert await future.wait_all() is None + await processor.join(5) + async with _read_back(real_base_state_processor, token) as root: + assert (await root.get_state(MistakenReturnState)).target_runs == target_runs + if client_event is not None: + assert client_event in {e.name for _, events in emitted_events for e in events} + + async def test_locked_root_is_set_only_while_the_lock_is_held( wired_app: App, real_base_state_processor: BaseStateEventProcessor, @@ -4464,6 +4741,82 @@ def handle(self): await NoCtxState.handle +async def test_await_from_a_request_outside_any_event_raises( + wired_app: App, + real_base_state_processor: BaseStateEventProcessor, +): + """Awaiting a handler in a request handler, outside ``app.modify_state``, is an error. + + Every request to the app carries the event processor's root context, which + belongs to no client (its token is empty). Running the handler there would + share one state between every caller of the route. + + Args: + wired_app: The App wired to the processor's state manager. + real_base_state_processor: The unmocked BaseStateEventProcessor. + """ + from reflex_base.utils.exceptions import EventHandlerTypeError + + class RouteState(State): + n: int = 0 + + @event + def add(self, amount: int) -> int: + self.n += amount + return self.n + + wired_app._event_processor = real_base_state_processor + raised: list[BaseException] = [] + + async def route(scope: Scope, receive: Receive, send: Send) -> None: + assert not EventContext.get().token + try: + await RouteState.add(1) + except EventHandlerTypeError as ex: + raised.append(ex) + + async with real_base_state_processor: + await _RootMiddleware(route, wired_app, contextlib.nullcontext)( + {"type": "http"}, unittest.mock.AsyncMock(), unittest.mock.AsyncMock() + ) + (error,) = raised + assert "can only be awaited from an event handler or inside" in str(error) + async with _read_back(real_base_state_processor, "") as root: + assert (await root.get_state(RouteState)).n == 0 + + +async def test_await_inside_app_modify_state_runs_on_that_token( + wired_app: App, + real_base_state_processor: BaseStateEventProcessor, + token: str, +): + """Inside ``app.modify_state`` an awaited handler runs on the token being modified. + + Args: + wired_app: The App wired to the processor's state manager. + real_base_state_processor: The unmocked BaseStateEventProcessor. + token: The client token. + """ + + class ModifyState(State): + n: int = 0 + + @event + def add(self, amount: int) -> int: + self.n += amount + return self.n + + wired_app._event_processor = real_base_state_processor + async with ( + real_base_state_processor, + wired_app.modify_state(BaseStateToken(ident=token, cls=ModifyState)), + ): + assert await ModifyState.add(2) == 2 + assert await ModifyState.add(3) == 5 + async with _read_back(real_base_state_processor, token) as root: + assert (await root.get_state(ModifyState)).n == 5 + + async def test_await_frontend_only_and_upload_specs_raise( wired_app: App, real_base_state_processor: BaseStateEventProcessor, diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 34405f9b8ce..bf43e6fe68b 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -5211,6 +5211,112 @@ async def test_on_event_falls_back_to_environ_without_connect( ) +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("outcome", "warns"), + [ + (42, True), + ({"rows": []}, True), + (None, False), + ([], False), + ("raise", False), + ("cancel", False), + ], +) +async def test_on_event_warns_once_in_dev_when_a_frontend_result_is_dropped( + token: str, + clean_registration_context: RegistrationContext, + event_namespace_with_processor_mock: EventNamespace, + mocker: MockerFixture, + outcome: Any, + warns: bool, +): + """A value returned by a handler the frontend triggered warns, once per handler. + + Only backend code awaiting a handler receives its return value. ``[]`` is + how a handler said "no events" before return values were results, so it + does not warn. + + Args: + token: A token. + clean_registration_context: Keeps the test's state out of the shared + registration context; the app below is created inside it. + event_namespace_with_processor_mock: The event namespace fixture. + mocker: pytest-mock fixture. + outcome: What the event's future resolves to, or how it ends. + warns: Whether the dropped value is warned about. + """ + + class DroppedResultState(rx.State): + @rx.event + def handler(self): + pass + + event_namespace = event_namespace_with_processor_mock + assert event_namespace.app._registration_context is clean_registration_context + await event_namespace._token_manager.link_token_to_sid(token, "sid1") + event_namespace.app.sio = Mock( + get_environ=Mock(return_value=_connect_environ(token)) + ) + warn = mocker.patch("reflex.app.logger.warning") + loop = asyncio.get_running_loop() + futures = [loop.create_future(), loop.create_future()] + enqueue_mock = cast(AsyncMock, event_namespace.app.event_processor.enqueue) + enqueue_mock.side_effect = futures + payload = { + **_client_event_payload(), + "name": format.format_event_handler( + DroppedResultState.event_handlers["handler"] + ), + } + for future in futures: + await event_namespace.on_event("sid1", payload) + if outcome == "raise": + future.set_exception(ValueError("handler failed")) + elif outcome == "cancel": + future.cancel() + else: + future.set_result(outcome) + await asyncio.sleep(0) + + if not warns: + warn.assert_not_called() + return + (message,) = warn.call_args.args + warn.assert_called_once_with(message) + assert "DroppedResultState.handler" in message + assert "dropped" in message + assert "await" in message + + +@pytest.mark.asyncio +async def test_on_event_does_not_watch_frontend_results_in_prod( + token: str, + monkeypatch: pytest.MonkeyPatch, +): + """In prod, a frontend event's future gets no callback: the check is dev only. + + Args: + token: A token. + monkeypatch: pytest monkeypatch fixture. + """ + monkeypatch.setenv("REFLEX_ENV_MODE", constants.Env.PROD.value) + app = App() + future = Mock() + app._event_processor = Mock(enqueue=AsyncMock(return_value=future)) + event_namespace = EventNamespace("/event", app) + try: + await event_namespace._token_manager.link_token_to_sid(token, "sid1") + event_namespace.app.sio = Mock( + get_environ=Mock(return_value=_connect_environ(token)) + ) + await event_namespace.on_event("sid1", _client_event_payload()) + finally: + await event_namespace._token_manager.disconnect_all() + cast(AsyncMock, app.event_processor.enqueue).assert_awaited_once() + future.add_done_callback.assert_not_called() + + @pytest.mark.parametrize("compile_raises", [False, True]) def test_compile_releases_memo_naming_caches( mocker: MockerFixture, compile_raises: bool @@ -5501,6 +5607,7 @@ async def test_on_event_uses_frontend_traceparent(otel_exporter): async def enqueue(token, event): await asyncio.sleep(0) seen.append(trace.get_current_span().get_span_context()) + return Mock() mock_app.event_processor.enqueue = enqueue ns = EventNamespace(namespace="/", app=mock_app)