Skip to content

Commit 465527b

Browse files
Emit App.modify_state deltas only to tokens a browser connected with (#7921)
* Do not emit to a shared state token in App.modify_state Modifying a SharedState by its shared token (from an API route or a background task) ended with emit_update to the shared token. No browser connects with that token, so every call logged "Attempting to send delta to disconnected client" even though the linked clients got the update through the shared state fan-out. Skip the emit when the modified state is the shared copy for that token, which is the SharedState whose _linked_to is the token's ident. A client token that is not connected still logs the warning. Closes #7913 * Emit modify_state deltas only to tokens a browser connected with A shared state token never has a socket, so App.modify_state now gates the emit on the root state's rx_router_session.session_id, which the socket connect records. This replaces the per-class _linked_to check: a connected browser token that another client links to keeps its emit, a shared token that no client linked to yet no longer warns, and the check no longer depends on the class passed in the token. * Emit modify_state deltas to connected tokens whose state expired A state that expires while its browser stays connected comes back without a session id. App.modify_state now also emits when the token manager has a socket for the token, so that browser keeps getting out-of-band updates. The test gets an expired-state case, docstrings on its helpers, and only counts warnings from the reflex.app logger. * Pin the modify_state emit test to the local token manager With REFLEX_REDIS_URL set, EventNamespace creates a RedisTokenManager: the disconnected token then logs no warning, and the socket records the test links stay in redis and break test_redis_token_manager_enumerate_tokens. * Suppress the disconnected client warning in modify_state Add a suppress_warnings keyword to EventNamespace.emit_update and pass it from App.modify_state, as suggested in review. emit_update already looks up the socket of the token, so connected tokens still get the emit and only the warning for a token without a socket is skipped. This replaces the session id and connection check added to modify_state. The modify_state emit test now checks the socket ids each update is emitted to, that modify_state logs no warning for a token without a socket, and that a regular emit_update to a disconnected token still logs it. --------- Co-authored-by: Farhan <www.mfarvirus@gmail.com>
1 parent 810bbd2 commit 465527b

3 files changed

Lines changed: 120 additions & 7 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Modifying a state with `app.modify_state` no longer logs an "Attempting to send delta to disconnected client" warning when no client is connected with the token, such as the shared token of a shared state. The clients linked to a shared state still get the update.

‎reflex/app.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2379,6 +2379,7 @@ class cannot be found.
23792379
await self.event_namespace.emit_update(
23802380
update=StateUpdate(delta=delta),
23812381
token=token.ident,
2382+
suppress_warnings=True,
23822383
)
23832384

23842385
def _validate_exception_handlers(self):
@@ -2819,12 +2820,16 @@ def on_disconnect(self, sid: str) -> asyncio.Task | None:
28192820
return task
28202821
return None
28212822

2822-
async def emit_update(self, update: StateUpdate, token: str) -> None:
2823+
async def emit_update(
2824+
self, update: StateUpdate, token: str, suppress_warnings: bool = False
2825+
) -> None:
28232826
"""Emit an update to the client.
28242827
28252828
Args:
28262829
update: The state update to send.
28272830
token: The client token (tab) associated with the event.
2831+
suppress_warnings: Whether to skip the warning when no client is
2832+
connected with the token.
28282833
"""
28292834
socket_record = self._token_manager.token_to_socket.get(token)
28302835
if (
@@ -2834,7 +2839,7 @@ async def emit_update(self, update: StateUpdate, token: str) -> None:
28342839
if isinstance(self._token_manager, RedisTokenManager):
28352840
# The socket belongs to another instance of the app, send it to the lost and found.
28362841
await self._token_manager.emit_lost_and_found(token, update)
2837-
else:
2842+
elif not suppress_warnings:
28382843
# If the socket record is None, we are not connected to a client. Prevent sending
28392844
# updates to all clients.
28402845
logger.warning(

‎tests/units/test_app.py‎

Lines changed: 112 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@
9292
from reflex.istate.manager.memory import StateManagerMemory
9393
from reflex.istate.manager.redis import StateManagerRedis
9494
from reflex.istate.manager.token import BaseStateToken
95+
from reflex.istate.shared import UPDATE_OTHER_CLIENT_TASKS
9596
from reflex.istate.storage import Cookie, LocalStorage, SessionStorage
9697
from reflex.model import Model
9798
from reflex.state import (
@@ -103,7 +104,11 @@
103104
)
104105
from reflex.utils import build
105106
from reflex.utils import exec as exec_utils
106-
from reflex.utils.token_manager import RedisTokenManager, SocketRecord
107+
from reflex.utils.token_manager import (
108+
LocalTokenManager,
109+
RedisTokenManager,
110+
SocketRecord,
111+
)
107112
from tests.units.exception_handler_helpers import logged
108113

109114
from .conftest import active_tracer, chdir, metric_points
@@ -4474,10 +4479,11 @@ class Sub(Base):
44744479
exp_delta = {Sub.get_full_name(): {"sub_count_rx_state_": 1}}
44754480
else:
44764481
exp_delta = {Base.get_full_name(): {"count_rx_state_": 1}}
4477-
assert (
4478-
app._event_namespace.emit_update.call_args.kwargs["update"].delta
4479-
== exp_delta
4480-
)
4482+
assert app._event_namespace.emit_update.call_args.kwargs == {
4483+
"update": StateUpdate(delta=exp_delta),
4484+
"token": token,
4485+
"suppress_warnings": True,
4486+
}
44814487
else:
44824488
assert app._event_namespace.emit_update.call_count == 0
44834489

@@ -4637,6 +4643,107 @@ async def test_modify_state_rebinds_event_context_to_token(
46374643
EventContext.reset(actor_token)
46384644

46394645

4646+
async def test_modify_state_emits_only_to_connected_tokens(
4647+
monkeypatch: pytest.MonkeyPatch,
4648+
clean_registration_context: RegistrationContext,
4649+
caplog: pytest.LogCaptureFixture,
4650+
):
4651+
"""Modify state emits only to tokens that a browser connected with.
4652+
4653+
A shared state token has no socket: its linked clients get the update
4654+
through the shared state fan-out. A browser token that another client links
4655+
to, or whose state expired while it stayed connected, still gets the emit.
4656+
Modify state logs no warning for a token without a socket, while a regular
4657+
emit to a browser that disconnected still does.
4658+
4659+
Args:
4660+
monkeypatch: Restore root metadata changed by defining a shared state.
4661+
clean_registration_context: Isolate the temporary shared state class.
4662+
caplog: Capture the warnings of the app.
4663+
"""
4664+
links = State.get_fields()["_reflex_internal_links"]
4665+
monkeypatch.setattr(links, "default", links.default)
4666+
monkeypatch.setattr(links, "default_factory", links.default_factory)
4667+
monkeypatch.setattr(
4668+
State, "_always_dirty_substates", State._always_dirty_substates.copy()
4669+
)
4670+
4671+
class CounterState(rx.SharedState):
4672+
count: int = 0
4673+
4674+
app = App(_state=State)
4675+
state_manager = app._state_manager = StateManagerMemory()
4676+
app._event_processor = Mock(
4677+
_root_context=EventContext(
4678+
token="", state_manager=state_manager, enqueue_impl=AsyncMock()
4679+
)
4680+
)
4681+
event_namespace = app._event_namespace = EventNamespace("/event", app)
4682+
event_namespace._token_manager = LocalTokenManager()
4683+
emit = event_namespace.emit = AsyncMock()
4684+
for token in ("client", "target", "expired", "gone"):
4685+
await event_namespace.link_token_to_sid(f"{token}-sid", token)
4686+
await event_namespace._token_manager.disconnect_token("gone", "gone-sid")
4687+
4688+
async def modify(token: str, count: int | None = None, link: str = "") -> list:
4689+
"""Modify the counter of a token and wait for the shared state fan-out.
4690+
4691+
Args:
4692+
token: The token to modify.
4693+
count: The count to set, if any.
4694+
link: The token to link the counter to, if any.
4695+
4696+
Returns:
4697+
The socket ids the updates were emitted to.
4698+
"""
4699+
emit.reset_mock()
4700+
async with app.modify_state(
4701+
BaseStateToken(ident=token, cls=CounterState)
4702+
) as root_state:
4703+
counter = await root_state.get_state(CounterState)
4704+
if link:
4705+
await counter._link_to(link)
4706+
if count is not None:
4707+
counter.count = count
4708+
await asyncio.gather(*UPDATE_OTHER_CLIENT_TASKS)
4709+
return [call.kwargs["to"] for call in emit.await_args_list]
4710+
4711+
def app_warnings() -> list[str]:
4712+
"""Get the warnings logged by the app.
4713+
4714+
Returns:
4715+
The messages of the reflex.app warning records.
4716+
"""
4717+
return [
4718+
record.getMessage()
4719+
for record in caplog.records
4720+
if record.name == "reflex.app" and record.levelno == logging.WARNING
4721+
]
4722+
4723+
with caplog.at_level(logging.WARNING, logger="reflex.app"):
4724+
assert await modify("client", link="shared") == ["client-sid"]
4725+
assert await modify("client", count=1) == ["client-sid"]
4726+
# The shared token gets no emit; its linked client gets the fan-out.
4727+
assert await modify("shared", count=2) == ["client-sid"]
4728+
# A shared token that no client linked to yet has no socket either.
4729+
assert await modify("unlinked", count=3) == []
4730+
4731+
# A browser token that another client links to is still connected.
4732+
await modify("target", count=4)
4733+
await modify("client", link="target")
4734+
assert await modify("target", count=5) == ["target-sid", "client-sid"]
4735+
# A connected browser whose state expired still gets the emit.
4736+
state_manager._purge_token(BaseStateToken(ident="expired", cls=State))
4737+
assert await modify("expired", count=6) == ["expired-sid"]
4738+
4739+
assert await modify("gone", count=7) == []
4740+
assert app_warnings() == []
4741+
4742+
await event_namespace.emit_update(StateUpdate(), token="gone")
4743+
assert emit.await_count == 0
4744+
assert app_warnings() == ["Attempting to send delta to disconnected client 'gone'"]
4745+
4746+
46404747
def test_set_contexts_no_event_processor(isolated_context: contextvars.Context):
46414748
"""When event processor is None, EventContext should not be touched."""
46424749

0 commit comments

Comments
 (0)