|
| 1 | +"""Internal helpers for in-memory state expiration.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import contextlib |
| 5 | +import dataclasses |
| 6 | +import heapq |
| 7 | +import time |
| 8 | +from typing import ClassVar |
| 9 | + |
| 10 | +from reflex.state import BaseState |
| 11 | + |
| 12 | +from . import _default_token_expiration |
| 13 | + |
| 14 | + |
| 15 | +@dataclasses.dataclass |
| 16 | +class StateManagerExpiration: |
| 17 | + """Internal base for managers with in-memory state expiration.""" |
| 18 | + |
| 19 | + _locked_expiration_poll_interval: ClassVar[float] = 0.1 |
| 20 | + _recheck_expired_locks_on_unlock: ClassVar[bool] = False |
| 21 | + |
| 22 | + token_expiration: int = dataclasses.field(default_factory=_default_token_expiration) |
| 23 | + |
| 24 | + # The mapping of client ids to states. |
| 25 | + states: dict[str, BaseState] = dataclasses.field(default_factory=dict) |
| 26 | + |
| 27 | + # The dict of mutexes for each client. |
| 28 | + _states_locks: dict[str, asyncio.Lock] = dataclasses.field( |
| 29 | + default_factory=dict, |
| 30 | + init=False, |
| 31 | + ) |
| 32 | + |
| 33 | + # The latest expiration deadline for each token. |
| 34 | + _token_expires_at: dict[str, float] = dataclasses.field( |
| 35 | + default_factory=dict, |
| 36 | + init=False, |
| 37 | + ) |
| 38 | + |
| 39 | + # Last time a token was touched. |
| 40 | + _token_last_touched: dict[str, float] = dataclasses.field( |
| 41 | + default_factory=dict, |
| 42 | + init=False, |
| 43 | + ) |
| 44 | + |
| 45 | + # Deadline-ordered token expiration heap. |
| 46 | + _token_expiration_heap: list[tuple[float, str]] = dataclasses.field( |
| 47 | + default_factory=list, |
| 48 | + init=False, |
| 49 | + repr=False, |
| 50 | + ) |
| 51 | + |
| 52 | + # Tokens whose expiration is deferred until their state lock is released. |
| 53 | + _pending_locked_expirations: set[str] = dataclasses.field( |
| 54 | + default_factory=set, |
| 55 | + init=False, |
| 56 | + repr=False, |
| 57 | + ) |
| 58 | + |
| 59 | + # Wake any background expiration worker when token activity changes. |
| 60 | + _token_activity: asyncio.Event = dataclasses.field( |
| 61 | + default_factory=asyncio.Event, |
| 62 | + init=False, |
| 63 | + repr=False, |
| 64 | + ) |
| 65 | + |
| 66 | + _scheduled_expiration_deadline: float | None = dataclasses.field( |
| 67 | + default=None, |
| 68 | + init=False, |
| 69 | + repr=False, |
| 70 | + ) |
| 71 | + |
| 72 | + def _touch_token(self, token: str): |
| 73 | + """Record access for a token. |
| 74 | +
|
| 75 | + Args: |
| 76 | + token: The token that was accessed. |
| 77 | + """ |
| 78 | + touched_at = time.time() |
| 79 | + expires_at = touched_at + self.token_expiration |
| 80 | + self._token_last_touched[token] = touched_at |
| 81 | + self._token_expires_at[token] = expires_at |
| 82 | + self._pending_locked_expirations.discard(token) |
| 83 | + heapq.heappush(self._token_expiration_heap, (expires_at, token)) |
| 84 | + self._maybe_compact_expiration_heap() |
| 85 | + if ( |
| 86 | + self._scheduled_expiration_deadline is None |
| 87 | + or expires_at <= self._scheduled_expiration_deadline |
| 88 | + ): |
| 89 | + self._token_activity.set() |
| 90 | + |
| 91 | + def _maybe_compact_expiration_heap(self): |
| 92 | + """Rebuild the heap when stale deadline entries accumulate.""" |
| 93 | + if len(self._token_expiration_heap) <= (2 * len(self._token_expires_at)) + 1: |
| 94 | + return |
| 95 | + self._token_expiration_heap = [ |
| 96 | + (expires_at, token) |
| 97 | + for token, expires_at in self._token_expires_at.items() |
| 98 | + if token not in self._pending_locked_expirations |
| 99 | + ] |
| 100 | + heapq.heapify(self._token_expiration_heap) |
| 101 | + |
| 102 | + def _next_expiration(self) -> tuple[float, str] | None: |
| 103 | + """Get the next valid token expiration from the heap. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + The next expiration deadline and token, or None if there are no |
| 107 | + active deadlines to process. |
| 108 | + """ |
| 109 | + while self._token_expiration_heap: |
| 110 | + expires_at, token = self._token_expiration_heap[0] |
| 111 | + current_expiration = self._token_expires_at.get(token) |
| 112 | + if ( |
| 113 | + current_expiration != expires_at |
| 114 | + or token in self._pending_locked_expirations |
| 115 | + ): |
| 116 | + heapq.heappop(self._token_expiration_heap) |
| 117 | + continue |
| 118 | + return expires_at, token |
| 119 | + return None |
| 120 | + |
| 121 | + def _purge_token(self, token: str): |
| 122 | + """Remove a token from all in-memory expiration bookkeeping. |
| 123 | +
|
| 124 | + Args: |
| 125 | + token: The token to purge. |
| 126 | + """ |
| 127 | + self._token_last_touched.pop(token, None) |
| 128 | + self._token_expires_at.pop(token, None) |
| 129 | + self.states.pop(token, None) |
| 130 | + self._states_locks.pop(token, None) |
| 131 | + self._pending_locked_expirations.discard(token) |
| 132 | + |
| 133 | + def _purge_expired_tokens( |
| 134 | + self, |
| 135 | + now: float | None = None, |
| 136 | + ) -> list[str]: |
| 137 | + """Purge expired in-memory state entries. |
| 138 | +
|
| 139 | + If a token's state lock is currently held, defer cleanup until a later pass |
| 140 | + to avoid replacing the state while it is being modified. |
| 141 | +
|
| 142 | + Args: |
| 143 | + now: The time to compare against. |
| 144 | +
|
| 145 | + Returns: |
| 146 | + The list of purged tokens. |
| 147 | + """ |
| 148 | + now = time.time() if now is None else now |
| 149 | + expired_tokens = [] |
| 150 | + while ( |
| 151 | + next_expiration := self._next_expiration() |
| 152 | + ) is not None and next_expiration[0] <= now: |
| 153 | + _expires_at, token = heapq.heappop(self._token_expiration_heap) |
| 154 | + if ( |
| 155 | + state_lock := self._states_locks.get(token) |
| 156 | + ) is not None and state_lock.locked(): |
| 157 | + self._pending_locked_expirations.add(token) |
| 158 | + continue |
| 159 | + self._purge_token(token) |
| 160 | + expired_tokens.append(token) |
| 161 | + return expired_tokens |
| 162 | + |
| 163 | + def _next_expiration_in( |
| 164 | + self, |
| 165 | + now: float | None = None, |
| 166 | + ) -> float | None: |
| 167 | + """Get the delay until the next expiration check should run. |
| 168 | +
|
| 169 | + Args: |
| 170 | + now: The time to compare against. |
| 171 | +
|
| 172 | + Returns: |
| 173 | + The number of seconds until the next check, or None when there are no |
| 174 | + tracked tokens. |
| 175 | + """ |
| 176 | + if (next_expiration := self._next_expiration()) is None: |
| 177 | + if ( |
| 178 | + self._pending_locked_expirations |
| 179 | + and not self._recheck_expired_locks_on_unlock |
| 180 | + ): |
| 181 | + return self._locked_expiration_poll_interval |
| 182 | + return None |
| 183 | + |
| 184 | + now = time.time() if now is None else now |
| 185 | + next_delay = max(0.0, next_expiration[0] - now) |
| 186 | + if ( |
| 187 | + self._pending_locked_expirations |
| 188 | + and not self._recheck_expired_locks_on_unlock |
| 189 | + ): |
| 190 | + return min(next_delay, self._locked_expiration_poll_interval) |
| 191 | + return next_delay |
| 192 | + |
| 193 | + def _reset_token_activity_wait(self): |
| 194 | + """Reset the token activity event before waiting.""" |
| 195 | + self._token_activity.clear() |
| 196 | + |
| 197 | + def _prepare_expiration_wait( |
| 198 | + self, |
| 199 | + *, |
| 200 | + now: float | None = None, |
| 201 | + default_timeout: float | None = None, |
| 202 | + ) -> float | None: |
| 203 | + """Prepare the next wait window for an expiration worker. |
| 204 | +
|
| 205 | + Args: |
| 206 | + now: The current time. |
| 207 | + default_timeout: A fallback timeout when there are no in-memory token |
| 208 | + deadlines to wait on. |
| 209 | +
|
| 210 | + Returns: |
| 211 | + The timeout to use for the next wait. |
| 212 | + """ |
| 213 | + self._reset_token_activity_wait() |
| 214 | + now = time.time() if now is None else now |
| 215 | + timeout = self._next_expiration_in(now=now) |
| 216 | + if timeout is None: |
| 217 | + timeout = default_timeout |
| 218 | + elif default_timeout is not None: |
| 219 | + timeout = min(timeout, default_timeout) |
| 220 | + self._scheduled_expiration_deadline = None if timeout is None else now + timeout |
| 221 | + return timeout |
| 222 | + |
| 223 | + def _notify_token_unlocked(self, token: str): |
| 224 | + """Requeue a deferred expiration check for a token after its lock is released. |
| 225 | +
|
| 226 | + Args: |
| 227 | + token: The unlocked token. |
| 228 | + """ |
| 229 | + if token not in self._pending_locked_expirations: |
| 230 | + return |
| 231 | + self._pending_locked_expirations.discard(token) |
| 232 | + if (expires_at := self._token_expires_at.get(token)) is None: |
| 233 | + return |
| 234 | + heapq.heappush(self._token_expiration_heap, (expires_at, token)) |
| 235 | + self._token_activity.set() |
| 236 | + |
| 237 | + async def _wait_for_token_activity(self, timeout: float | None): |
| 238 | + """Wait for token activity or a timeout. |
| 239 | +
|
| 240 | + Args: |
| 241 | + timeout: The maximum time to wait. When None, waits indefinitely. |
| 242 | + """ |
| 243 | + try: |
| 244 | + if timeout is None: |
| 245 | + await self._token_activity.wait() |
| 246 | + return |
| 247 | + with contextlib.suppress(asyncio.TimeoutError): |
| 248 | + await asyncio.wait_for(self._token_activity.wait(), timeout=timeout) |
| 249 | + finally: |
| 250 | + self._scheduled_expiration_deadline = None |
0 commit comments