diff --git a/news/+super-background-handler.bugfix.md b/news/+super-background-handler.bugfix.md new file mode 100644 index 00000000000..8644d068fc8 --- /dev/null +++ b/news/+super-background-handler.bugfix.md @@ -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`. diff --git a/packages/reflex-base/news/+super-background-handler.bugfix.md b/packages/reflex-base/news/+super-background-handler.bugfix.md new file mode 100644 index 00000000000..8644d068fc8 --- /dev/null +++ b/packages/reflex-base/news/+super-background-handler.bugfix.md @@ -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`. diff --git a/packages/reflex-base/src/reflex_base/event/__init__.py b/packages/reflex-base/src/reflex_base/event/__init__.py index 63844816912..13794cead68 100644 --- a/packages/reflex-base/src/reflex_base/event/__init__.py +++ b/packages/reflex-base/src/reflex_base/event/__init__.py @@ -14,6 +14,7 @@ TYPE_CHECKING, Annotated, Any, + ClassVar, Generic, Literal, NoReturn, @@ -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 ) @@ -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) diff --git a/reflex/istate/proxy.py b/reflex/istate/proxy.py index 6b5b7b75540..5690acb1974 100644 --- a/reflex/istate/proxy.py +++ b/reflex/istate/proxy.py @@ -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 ( @@ -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. @@ -1359,3 +1379,4 @@ def _dirty_state(self) -> BaseState: Field._proxy = MutableProxy +EventHandler._state_proxy = StateProxy diff --git a/tests/units/istate/test_proxy.py b/tests/units/istate/test_proxy.py index f229c25603a..69062d90835 100644 --- a/tests/units/istate/test_proxy.py +++ b/tests/units/istate/test_proxy.py @@ -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])