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 news/+super-background-handler.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A background event handler that overrides one from a mixin or a parent state can call it with `await super().handler()` again, instead of raising `ImmutableStateError`.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A background event handler that overrides one from a mixin or a parent state can call it with `await super().handler()` again, instead of raising `ImmutableStateError`.
27 changes: 22 additions & 5 deletions packages/reflex-base/src/reflex_base/event/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
TYPE_CHECKING,
Annotated,
Any,
ClassVar,
Generic,
Literal,
NoReturn,
Expand Down Expand Up @@ -572,6 +573,11 @@ class EventHandler(EventActionsMixin):

state: "type[BaseState] | None" = dataclasses.field(default=None, repr=False)

# The StateProxy type, installed by reflex.istate.proxy, which binds the
# handlers `super()` reaches from a background task. Until then nothing is one:
# isinstance against () is always false.
_state_proxy: ClassVar[Any] = ()

_type_hints: dict[str, Any] | None = dataclasses.field(
default=None, repr=False, compare=False
)
Expand Down Expand Up @@ -784,11 +790,22 @@ def __get__(self, instance: Any, owner: type | None = None) -> Any:
if not isinstance(instance, self.state):
# Held by a class that is not its state, nor a substate of it.
return self
state = (
instance
if type(instance) is self.state
else _owner_state(instance, self.state)
)
instance_type = type(instance)
if instance_type is self.state:
state = instance
elif instance_type is not owner and issubclass(
instance_type, EventHandler._state_proxy
):
# Only `super()` hands a background task's proxy to the descriptor
# (the proxy binds its own attributes), to run the overridden
# handler in the same task. Attribute access passes the instance's
# own type as `owner`, so the check stays off that path; `super()`
# passes the wrapped state's class.
return EventHandler._state_proxy._bind_overridden_handler(
instance, self.fn, self.state
)
else:
state = _owner_state(instance, self.state)
if self.is_background:
return _no_chain_background_task(state, self.fn)
return types.MethodType(self.fn, state)
Expand Down
23 changes: 22 additions & 1 deletion reflex/istate/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

import wrapt
from reflex_base import constants
from reflex_base.event import Event
from reflex_base.event import Event, EventHandler
from reflex_base.event.context import EventContext
from reflex_base.utils.exceptions import ImmutableStateError
from reflex_base.utils.serializers import (
Expand Down Expand Up @@ -422,6 +422,26 @@ def __getattr__(self, name: str) -> Any:
)
return value

def _bind_overridden_handler(
self, fn: Callable, owner: type[BaseState]
) -> Callable:
"""Bind the function of a handler that `super()` reached through this proxy.

Bound like the handlers `__getattr__` returns, but without the guard
against calling a background task directly: an overriding background
handler runs the one it extends in its own task.

Args:
fn: The function of the overridden handler.
owner: The state class or mixin declaring the overridden handler.

Returns:
The function bound to this proxy, or to the ancestor declaring it.
"""
if owner._mixin or type(self.__wrapped__) is owner:
return MethodType(fn, self)
return functools.partial(_call_on_ancestor, self, fn, owner)

def __setattr__(self, name: str, value: Any) -> None:
"""Set the attribute on the underlying state instance.

Expand Down Expand Up @@ -1359,3 +1379,4 @@ def _dirty_state(self) -> BaseState:


Field._proxy = MutableProxy
EventHandler._state_proxy = StateProxy
83 changes: 83 additions & 0 deletions tests/units/istate/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,89 @@ async def test_inherited_handler_runs_on_its_state(
assert substate.count == 10 # pyright: ignore [reportAttributeAccessIssue]


class SuperBackgroundMixin(BaseState, mixin=True):
"""A mixin whose background handler a state overrides."""

steps: list[str] = []

@rx.event(background=True)
async def save(self):
"""Record the mixin's step."""
async with self:
self.steps.append("mixin")


class SuperBackgroundMixinUser(SuperBackgroundMixin, BaseState):
"""A state extending the mixin's background handler through super()."""

@rx.event(background=True)
async def save(self):
"""Record this state's step, then the mixin's."""
async with self:
self.steps.append("user")
await super().save()


class SuperBackgroundParent(BaseState):
"""A state whose background handler its substate overrides."""

steps: list[str] = []

@rx.event(background=True)
async def save(self):
"""Record the parent's step."""
async with self:
self.steps.append("parent")


class SuperBackgroundChild(SuperBackgroundParent):
"""A substate extending its parent's background handler through super()."""

@rx.event(background=True)
async def save(self):
"""Record this state's step, then the parent's."""
async with self:
self.steps.append("child")
await super().save()


@pytest.mark.asyncio
@pytest.mark.parametrize(
("state_cls", "steps_owner", "steps"),
[
(SuperBackgroundMixinUser, SuperBackgroundMixinUser, ["user", "mixin"]),
(SuperBackgroundChild, SuperBackgroundParent, ["child", "parent"]),
],
)
async def test_background_handler_extends_its_base_through_super(
token: str,
state_manager: StateManager,
attached_mock_event_context: EventContext,
state_cls: type[BaseState],
steps_owner: type[BaseState],
steps: list[str],
) -> None:
"""A background handler calling super() runs the overridden handler in the same task.

Args:
token: The client token.
state_manager: The state manager to exercise.
attached_mock_event_context: The attached event context.
state_cls: The state overriding the background handler.
steps_owner: The state storing the recorded steps.
steps: The steps both handlers record, in order.
"""
state_token = BaseStateToken(ident=token, cls=state_cls)
async with state_manager.modify_state(state_token) as root:
proxy = StateProxy(root.get_substate(state_cls.get_full_name().split(".")))

await state_cls.save.fn(proxy) # pyright: ignore [reportAttributeAccessIssue]

async with state_manager.modify_state(state_token) as root:
owner = root.get_substate(steps_owner.get_full_name().split("."))
assert owner.steps == steps # pyright: ignore [reportAttributeAccessIssue]


@pytest.mark.asyncio
@pytest.mark.parametrize("proxy_cls", [StateProxy, ReadOnlyStateProxy])
@pytest.mark.parametrize("state_cls", [RouterProxyState, RouterProxySubState])
Expand Down
Loading