Skip to content

Commit 4ee713f

Browse files
authored
Revive token socket_record after expiration (#5977)
If the socket_record expires in redis, but the instance managing it is still alive, then re-link the token to the sid. For `del` and `evicted`, do not re-link the token as this is an explicit disconnect.
1 parent 9dfbbc4 commit 4ee713f

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

reflex/utils/token_manager.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -229,16 +229,22 @@ async def enumerate_tokens(self) -> AsyncIterator[str]:
229229
if not cursor:
230230
break
231231

232-
def _handle_socket_record_del(self, token: str) -> None:
232+
async def _handle_socket_record_del(
233+
self, token: str, expired: bool = False
234+
) -> None:
233235
"""Handle deletion of a socket record from Redis.
234236
235237
Args:
236238
token: The client token whose record was deleted.
239+
expired: Whether the deletion was due to expiration.
237240
"""
238241
if (
239242
socket_record := self.token_to_socket.pop(token, None)
240-
) is not None and socket_record.instance_id != self.instance_id:
243+
) is not None and socket_record.instance_id == self.instance_id:
241244
self.sid_to_token.pop(socket_record.sid, None)
245+
if expired:
246+
# Keep the record alive as long as this process is alive and not deleted.
247+
await self.link_token_to_sid(token, socket_record.sid)
242248

243249
async def _subscribe_socket_record_updates(self) -> None:
244250
"""Subscribe to Redis keyspace notifications for socket record updates."""
@@ -262,7 +268,10 @@ async def _subscribe_socket_record_updates(self) -> None:
262268

263269
event = message["data"].decode()
264270
if event in ("del", "expired", "evicted"):
265-
self._handle_socket_record_del(token)
271+
await self._handle_socket_record_del(
272+
token,
273+
expired=(event == "expired"),
274+
)
266275
elif event == "set":
267276
await self._get_token_owner(token, refresh=True)
268277

0 commit comments

Comments
 (0)