|
| 1 | +"""Token manager for handling client token to session ID mappings.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import uuid |
| 6 | +from abc import ABC, abstractmethod |
| 7 | +from typing import TYPE_CHECKING |
| 8 | + |
| 9 | +from reflex.utils import console, prerequisites |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from redis.asyncio import Redis |
| 13 | + |
| 14 | + |
| 15 | +def _get_new_token() -> str: |
| 16 | + """Generate a new unique token. |
| 17 | +
|
| 18 | + Returns: |
| 19 | + A new UUID4 token string. |
| 20 | + """ |
| 21 | + return str(uuid.uuid4()) |
| 22 | + |
| 23 | + |
| 24 | +class TokenManager(ABC): |
| 25 | + """Abstract base class for managing client token to session ID mappings.""" |
| 26 | + |
| 27 | + def __init__(self): |
| 28 | + """Initialize the token manager with local dictionaries.""" |
| 29 | + # Keep a mapping between socket ID and client token. |
| 30 | + self.token_to_sid: dict[str, str] = {} |
| 31 | + # Keep a mapping between client token and socket ID. |
| 32 | + self.sid_to_token: dict[str, str] = {} |
| 33 | + |
| 34 | + @abstractmethod |
| 35 | + async def link_token_to_sid(self, token: str, sid: str) -> str | None: |
| 36 | + """Link a token to a session ID. |
| 37 | +
|
| 38 | + Args: |
| 39 | + token: The client token. |
| 40 | + sid: The Socket.IO session ID. |
| 41 | +
|
| 42 | + Returns: |
| 43 | + New token if duplicate detected and new token generated, None otherwise. |
| 44 | + """ |
| 45 | + |
| 46 | + @abstractmethod |
| 47 | + async def disconnect_token(self, token: str, sid: str) -> None: |
| 48 | + """Clean up token mapping when client disconnects. |
| 49 | +
|
| 50 | + Args: |
| 51 | + token: The client token. |
| 52 | + sid: The Socket.IO session ID. |
| 53 | + """ |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def create(cls) -> TokenManager: |
| 57 | + """Factory method to create appropriate TokenManager implementation. |
| 58 | +
|
| 59 | + Returns: |
| 60 | + RedisTokenManager if Redis is available, LocalTokenManager otherwise. |
| 61 | + """ |
| 62 | + if prerequisites.check_redis_used(): |
| 63 | + redis_client = prerequisites.get_redis() |
| 64 | + if redis_client is not None: |
| 65 | + return RedisTokenManager(redis_client) |
| 66 | + |
| 67 | + return LocalTokenManager() |
| 68 | + |
| 69 | + |
| 70 | +class LocalTokenManager(TokenManager): |
| 71 | + """Token manager using local in-memory dictionaries (single worker).""" |
| 72 | + |
| 73 | + def __init__(self): |
| 74 | + """Initialize the local token manager.""" |
| 75 | + super().__init__() |
| 76 | + |
| 77 | + async def link_token_to_sid(self, token: str, sid: str) -> str | None: |
| 78 | + """Link a token to a session ID. |
| 79 | +
|
| 80 | + Args: |
| 81 | + token: The client token. |
| 82 | + sid: The Socket.IO session ID. |
| 83 | +
|
| 84 | + Returns: |
| 85 | + New token if duplicate detected and new token generated, None otherwise. |
| 86 | + """ |
| 87 | + # Check if token is already mapped to a different SID (duplicate tab) |
| 88 | + if token in self.token_to_sid and sid != self.token_to_sid.get(token): |
| 89 | + new_token = _get_new_token() |
| 90 | + self.token_to_sid[new_token] = sid |
| 91 | + self.sid_to_token[sid] = new_token |
| 92 | + return new_token |
| 93 | + |
| 94 | + # Normal case - link token to SID |
| 95 | + self.token_to_sid[token] = sid |
| 96 | + self.sid_to_token[sid] = token |
| 97 | + return None |
| 98 | + |
| 99 | + async def disconnect_token(self, token: str, sid: str) -> None: |
| 100 | + """Clean up token mapping when client disconnects. |
| 101 | +
|
| 102 | + Args: |
| 103 | + token: The client token. |
| 104 | + sid: The Socket.IO session ID. |
| 105 | + """ |
| 106 | + # Clean up both mappings |
| 107 | + self.token_to_sid.pop(token, None) |
| 108 | + self.sid_to_token.pop(sid, None) |
| 109 | + |
| 110 | + |
| 111 | +class RedisTokenManager(LocalTokenManager): |
| 112 | + """Token manager using Redis for distributed multi-worker support. |
| 113 | +
|
| 114 | + Inherits local dict logic from LocalTokenManager and adds Redis layer |
| 115 | + for cross-worker duplicate detection. |
| 116 | + """ |
| 117 | + |
| 118 | + def __init__(self, redis: Redis): |
| 119 | + """Initialize the Redis token manager. |
| 120 | +
|
| 121 | + Args: |
| 122 | + redis: The Redis client instance. |
| 123 | + """ |
| 124 | + # Initialize parent's local dicts |
| 125 | + super().__init__() |
| 126 | + |
| 127 | + self.redis = redis |
| 128 | + |
| 129 | + # Get token expiration from config (default 1 hour) |
| 130 | + from reflex.config import get_config |
| 131 | + |
| 132 | + config = get_config() |
| 133 | + self.token_expiration = config.redis_token_expiration |
| 134 | + |
| 135 | + def _get_redis_key(self, token: str) -> str: |
| 136 | + """Get Redis key for token mapping. |
| 137 | +
|
| 138 | + Args: |
| 139 | + token: The client token. |
| 140 | +
|
| 141 | + Returns: |
| 142 | + Redis key following Reflex conventions: {token}_sid |
| 143 | + """ |
| 144 | + return f"{token}_sid" |
| 145 | + |
| 146 | + async def link_token_to_sid(self, token: str, sid: str) -> str | None: |
| 147 | + """Link a token to a session ID with Redis-based duplicate detection. |
| 148 | +
|
| 149 | + Args: |
| 150 | + token: The client token. |
| 151 | + sid: The Socket.IO session ID. |
| 152 | +
|
| 153 | + Returns: |
| 154 | + New token if duplicate detected and new token generated, None otherwise. |
| 155 | + """ |
| 156 | + # Fast local check first (handles reconnections) |
| 157 | + if token in self.token_to_sid and self.token_to_sid[token] == sid: |
| 158 | + return None # Same token, same SID = reconnection, no Redis check needed |
| 159 | + |
| 160 | + # Check Redis for cross-worker duplicates |
| 161 | + redis_key = self._get_redis_key(token) |
| 162 | + |
| 163 | + try: |
| 164 | + token_exists_in_redis = await self.redis.exists(redis_key) |
| 165 | + except Exception as e: |
| 166 | + console.error(f"Redis error checking token existence: {e}") |
| 167 | + return await super().link_token_to_sid(token, sid) |
| 168 | + |
| 169 | + if token_exists_in_redis: |
| 170 | + # Duplicate exists somewhere - generate new token |
| 171 | + new_token = _get_new_token() |
| 172 | + new_redis_key = self._get_redis_key(new_token) |
| 173 | + |
| 174 | + try: |
| 175 | + # Store in Redis |
| 176 | + await self.redis.set(new_redis_key, "1", ex=self.token_expiration) |
| 177 | + except Exception as e: |
| 178 | + console.error(f"Redis error storing new token: {e}") |
| 179 | + # Still update local dicts and continue |
| 180 | + |
| 181 | + # Store in local dicts (always do this) |
| 182 | + self.token_to_sid[new_token] = sid |
| 183 | + self.sid_to_token[sid] = new_token |
| 184 | + return new_token |
| 185 | + |
| 186 | + # Normal case - store in both Redis and local dicts |
| 187 | + try: |
| 188 | + await self.redis.set(redis_key, "1", ex=self.token_expiration) |
| 189 | + except Exception as e: |
| 190 | + console.error(f"Redis error storing token: {e}") |
| 191 | + # Continue with local storage |
| 192 | + |
| 193 | + # Store in local dicts (always do this) |
| 194 | + self.token_to_sid[token] = sid |
| 195 | + self.sid_to_token[sid] = token |
| 196 | + return None |
| 197 | + |
| 198 | + async def disconnect_token(self, token: str, sid: str) -> None: |
| 199 | + """Clean up token mapping when client disconnects. |
| 200 | +
|
| 201 | + Args: |
| 202 | + token: The client token. |
| 203 | + sid: The Socket.IO session ID. |
| 204 | + """ |
| 205 | + # Only clean up if we own it locally (fast ownership check) |
| 206 | + if self.token_to_sid.get(token) == sid: |
| 207 | + # Clean up Redis |
| 208 | + redis_key = self._get_redis_key(token) |
| 209 | + try: |
| 210 | + await self.redis.delete(redis_key) |
| 211 | + except Exception as e: |
| 212 | + console.error(f"Redis error deleting token: {e}") |
| 213 | + |
| 214 | + # Clean up local dicts (always do this) |
| 215 | + await super().disconnect_token(token, sid) |
0 commit comments