manager.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. """State manager for managing client states."""
  2. import asyncio
  3. import contextlib
  4. import dataclasses
  5. import functools
  6. import time
  7. import uuid
  8. from abc import ABC, abstractmethod
  9. from collections.abc import AsyncIterator
  10. from hashlib import md5
  11. from pathlib import Path
  12. from redis import ResponseError
  13. from redis.asyncio import Redis
  14. from redis.asyncio.client import PubSub
  15. from typing_extensions import override
  16. from reflex import constants
  17. from reflex.config import environment, get_config
  18. from reflex.state import BaseState, _split_substate_key, _substate_key
  19. from reflex.utils import console, path_ops, prerequisites
  20. from reflex.utils.exceptions import (
  21. InvalidLockWarningThresholdError,
  22. InvalidStateManagerModeError,
  23. LockExpiredError,
  24. StateSchemaMismatchError,
  25. )
  26. @dataclasses.dataclass
  27. class StateManager(ABC):
  28. """A class to manage many client states."""
  29. # The state class to use.
  30. state: type[BaseState]
  31. @classmethod
  32. def create(cls, state: type[BaseState]):
  33. """Create a new state manager.
  34. Args:
  35. state: The state class to use.
  36. Raises:
  37. InvalidStateManagerModeError: If the state manager mode is invalid.
  38. Returns:
  39. The state manager (either disk, memory or redis).
  40. """
  41. config = get_config()
  42. if prerequisites.parse_redis_url() is not None:
  43. config.state_manager_mode = constants.StateManagerMode.REDIS
  44. if config.state_manager_mode == constants.StateManagerMode.MEMORY:
  45. return StateManagerMemory(state=state)
  46. if config.state_manager_mode == constants.StateManagerMode.DISK:
  47. return StateManagerDisk(state=state)
  48. if config.state_manager_mode == constants.StateManagerMode.REDIS:
  49. redis = prerequisites.get_redis()
  50. if redis is not None:
  51. # make sure expiration values are obtained only from the config object on creation
  52. return StateManagerRedis(
  53. state=state,
  54. redis=redis,
  55. token_expiration=config.redis_token_expiration,
  56. lock_expiration=config.redis_lock_expiration,
  57. lock_warning_threshold=config.redis_lock_warning_threshold,
  58. )
  59. raise InvalidStateManagerModeError(
  60. f"Expected one of: DISK, MEMORY, REDIS, got {config.state_manager_mode}"
  61. )
  62. @abstractmethod
  63. async def get_state(self, token: str) -> BaseState:
  64. """Get the state for a token.
  65. Args:
  66. token: The token to get the state for.
  67. Returns:
  68. The state for the token.
  69. """
  70. pass
  71. @abstractmethod
  72. async def set_state(self, token: str, state: BaseState):
  73. """Set the state for a token.
  74. Args:
  75. token: The token to set the state for.
  76. state: The state to set.
  77. """
  78. pass
  79. @abstractmethod
  80. @contextlib.asynccontextmanager
  81. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  82. """Modify the state for a token while holding exclusive lock.
  83. Args:
  84. token: The token to modify the state for.
  85. Yields:
  86. The state for the token.
  87. """
  88. yield self.state()
  89. @dataclasses.dataclass
  90. class StateManagerMemory(StateManager):
  91. """A state manager that stores states in memory."""
  92. # The mapping of client ids to states.
  93. states: dict[str, BaseState] = dataclasses.field(default_factory=dict)
  94. # The mutex ensures the dict of mutexes is updated exclusively
  95. _state_manager_lock: asyncio.Lock = dataclasses.field(default=asyncio.Lock())
  96. # The dict of mutexes for each client
  97. _states_locks: dict[str, asyncio.Lock] = dataclasses.field(
  98. default_factory=dict, init=False
  99. )
  100. @override
  101. async def get_state(self, token: str) -> BaseState:
  102. """Get the state for a token.
  103. Args:
  104. token: The token to get the state for.
  105. Returns:
  106. The state for the token.
  107. """
  108. # Memory state manager ignores the substate suffix and always returns the top-level state.
  109. token = _split_substate_key(token)[0]
  110. if token not in self.states:
  111. self.states[token] = self.state(_reflex_internal_init=True)
  112. return self.states[token]
  113. @override
  114. async def set_state(self, token: str, state: BaseState):
  115. """Set the state for a token.
  116. Args:
  117. token: The token to set the state for.
  118. state: The state to set.
  119. """
  120. pass
  121. @override
  122. @contextlib.asynccontextmanager
  123. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  124. """Modify the state for a token while holding exclusive lock.
  125. Args:
  126. token: The token to modify the state for.
  127. Yields:
  128. The state for the token.
  129. """
  130. # Memory state manager ignores the substate suffix and always returns the top-level state.
  131. token = _split_substate_key(token)[0]
  132. if token not in self._states_locks:
  133. async with self._state_manager_lock:
  134. if token not in self._states_locks:
  135. self._states_locks[token] = asyncio.Lock()
  136. async with self._states_locks[token]:
  137. state = await self.get_state(token)
  138. yield state
  139. await self.set_state(token, state)
  140. def _default_token_expiration() -> int:
  141. """Get the default token expiration time.
  142. Returns:
  143. The default token expiration time.
  144. """
  145. return get_config().redis_token_expiration
  146. def reset_disk_state_manager():
  147. """Reset the disk state manager."""
  148. states_directory = prerequisites.get_states_dir()
  149. if states_directory.exists():
  150. for path in states_directory.iterdir():
  151. path.unlink()
  152. @dataclasses.dataclass
  153. class StateManagerDisk(StateManager):
  154. """A state manager that stores states in memory."""
  155. # The mapping of client ids to states.
  156. states: dict[str, BaseState] = dataclasses.field(default_factory=dict)
  157. # The mutex ensures the dict of mutexes is updated exclusively
  158. _state_manager_lock: asyncio.Lock = dataclasses.field(default=asyncio.Lock())
  159. # The dict of mutexes for each client
  160. _states_locks: dict[str, asyncio.Lock] = dataclasses.field(
  161. default_factory=dict,
  162. init=False,
  163. )
  164. # The token expiration time (s).
  165. token_expiration: int = dataclasses.field(default_factory=_default_token_expiration)
  166. def __post_init_(self):
  167. """Create a new state manager."""
  168. path_ops.mkdir(self.states_directory)
  169. self._purge_expired_states()
  170. @functools.cached_property
  171. def states_directory(self) -> Path:
  172. """Get the states directory.
  173. Returns:
  174. The states directory.
  175. """
  176. return prerequisites.get_states_dir()
  177. def _purge_expired_states(self):
  178. """Purge expired states from the disk."""
  179. import time
  180. for path in path_ops.ls(self.states_directory):
  181. # check path is a pickle file
  182. if path.suffix != ".pkl":
  183. continue
  184. # load last edited field from file
  185. last_edited = path.stat().st_mtime
  186. # check if the file is older than the token expiration time
  187. if time.time() - last_edited > self.token_expiration:
  188. # remove the file
  189. path.unlink()
  190. def token_path(self, token: str) -> Path:
  191. """Get the path for a token.
  192. Args:
  193. token: The token to get the path for.
  194. Returns:
  195. The path for the token.
  196. """
  197. return (
  198. self.states_directory / f"{md5(token.encode()).hexdigest()}.pkl"
  199. ).absolute()
  200. async def load_state(self, token: str) -> BaseState | None:
  201. """Load a state object based on the provided token.
  202. Args:
  203. token: The token used to identify the state object.
  204. Returns:
  205. The loaded state object or None.
  206. """
  207. token_path = self.token_path(token)
  208. if token_path.exists():
  209. try:
  210. with token_path.open(mode="rb") as file:
  211. return BaseState._deserialize(fp=file)
  212. except Exception:
  213. pass
  214. async def populate_substates(
  215. self, client_token: str, state: BaseState, root_state: BaseState
  216. ):
  217. """Populate the substates of a state object.
  218. Args:
  219. client_token: The client token.
  220. state: The state object to populate.
  221. root_state: The root state object.
  222. """
  223. for substate in state.get_substates():
  224. substate_token = _substate_key(client_token, substate)
  225. fresh_instance = await root_state.get_state(substate)
  226. instance = await self.load_state(substate_token)
  227. if instance is not None:
  228. # Ensure all substates exist, even if they weren't serialized previously.
  229. instance.substates = fresh_instance.substates
  230. else:
  231. instance = fresh_instance
  232. state.substates[substate.get_name()] = instance
  233. instance.parent_state = state
  234. await self.populate_substates(client_token, instance, root_state)
  235. @override
  236. async def get_state(
  237. self,
  238. token: str,
  239. ) -> BaseState:
  240. """Get the state for a token.
  241. Args:
  242. token: The token to get the state for.
  243. Returns:
  244. The state for the token.
  245. """
  246. client_token = _split_substate_key(token)[0]
  247. root_state = self.states.get(client_token)
  248. if root_state is not None:
  249. # Retrieved state from memory.
  250. return root_state
  251. # Deserialize root state from disk.
  252. root_state = await self.load_state(_substate_key(client_token, self.state))
  253. # Create a new root state tree with all substates instantiated.
  254. fresh_root_state = self.state(_reflex_internal_init=True)
  255. if root_state is None:
  256. root_state = fresh_root_state
  257. else:
  258. # Ensure all substates exist, even if they were not serialized previously.
  259. root_state.substates = fresh_root_state.substates
  260. self.states[client_token] = root_state
  261. await self.populate_substates(client_token, root_state, root_state)
  262. return root_state
  263. async def set_state_for_substate(self, client_token: str, substate: BaseState):
  264. """Set the state for a substate.
  265. Args:
  266. client_token: The client token.
  267. substate: The substate to set.
  268. """
  269. substate_token = _substate_key(client_token, substate)
  270. if substate._get_was_touched():
  271. substate._was_touched = False # Reset the touched flag after serializing.
  272. pickle_state = substate._serialize()
  273. if pickle_state:
  274. if not self.states_directory.exists():
  275. self.states_directory.mkdir(parents=True, exist_ok=True)
  276. self.token_path(substate_token).write_bytes(pickle_state)
  277. for substate_substate in substate.substates.values():
  278. await self.set_state_for_substate(client_token, substate_substate)
  279. @override
  280. async def set_state(self, token: str, state: BaseState):
  281. """Set the state for a token.
  282. Args:
  283. token: The token to set the state for.
  284. state: The state to set.
  285. """
  286. client_token, substate = _split_substate_key(token)
  287. await self.set_state_for_substate(client_token, state)
  288. @override
  289. @contextlib.asynccontextmanager
  290. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  291. """Modify the state for a token while holding exclusive lock.
  292. Args:
  293. token: The token to modify the state for.
  294. Yields:
  295. The state for the token.
  296. """
  297. # Memory state manager ignores the substate suffix and always returns the top-level state.
  298. client_token, substate = _split_substate_key(token)
  299. if client_token not in self._states_locks:
  300. async with self._state_manager_lock:
  301. if client_token not in self._states_locks:
  302. self._states_locks[client_token] = asyncio.Lock()
  303. async with self._states_locks[client_token]:
  304. state = await self.get_state(token)
  305. yield state
  306. await self.set_state(token, state)
  307. def _default_lock_expiration() -> int:
  308. """Get the default lock expiration time.
  309. Returns:
  310. The default lock expiration time.
  311. """
  312. return get_config().redis_lock_expiration
  313. def _default_lock_warning_threshold() -> int:
  314. """Get the default lock warning threshold.
  315. Returns:
  316. The default lock warning threshold.
  317. """
  318. return get_config().redis_lock_warning_threshold
  319. @dataclasses.dataclass
  320. class StateManagerRedis(StateManager):
  321. """A state manager that stores states in redis."""
  322. # The redis client to use.
  323. redis: Redis
  324. # The token expiration time (s).
  325. token_expiration: int = dataclasses.field(default_factory=_default_token_expiration)
  326. # The maximum time to hold a lock (ms).
  327. lock_expiration: int = dataclasses.field(default_factory=_default_lock_expiration)
  328. # The maximum time to hold a lock (ms) before warning.
  329. lock_warning_threshold: int = dataclasses.field(
  330. default_factory=_default_lock_warning_threshold
  331. )
  332. # The keyspace subscription string when redis is waiting for lock to be released.
  333. _redis_notify_keyspace_events: str = dataclasses.field(
  334. default="K" # Enable keyspace notifications (target a particular key)
  335. "g" # For generic commands (DEL, EXPIRE, etc)
  336. "x" # For expired events
  337. "e" # For evicted events (i.e. maxmemory exceeded)
  338. )
  339. # These events indicate that a lock is no longer held.
  340. _redis_keyspace_lock_release_events: set[bytes] = dataclasses.field(
  341. default_factory=lambda: {
  342. b"del",
  343. b"expire",
  344. b"expired",
  345. b"evicted",
  346. }
  347. )
  348. # Whether keyspace notifications have been enabled.
  349. _redis_notify_keyspace_events_enabled: bool = dataclasses.field(default=False)
  350. # The logical database number used by the redis client.
  351. _redis_db: int = dataclasses.field(default=0)
  352. def __post_init__(self):
  353. """Validate the lock warning threshold.
  354. Raises:
  355. InvalidLockWarningThresholdError: If the lock warning threshold is invalid.
  356. """
  357. if self.lock_warning_threshold >= (lock_expiration := self.lock_expiration):
  358. raise InvalidLockWarningThresholdError(
  359. f"The lock warning threshold({self.lock_warning_threshold}) must be less than the lock expiration time({lock_expiration})."
  360. )
  361. def _get_required_state_classes(
  362. self,
  363. target_state_cls: type[BaseState],
  364. subclasses: bool = False,
  365. required_state_classes: set[type[BaseState]] | None = None,
  366. ) -> set[type[BaseState]]:
  367. """Recursively determine which states are required to fetch the target state.
  368. This will always include potentially dirty substates that depend on vars
  369. in the target_state_cls.
  370. Args:
  371. target_state_cls: The target state class being fetched.
  372. subclasses: Whether to include subclasses of the target state.
  373. required_state_classes: Recursive argument tracking state classes that have already been seen.
  374. Returns:
  375. The set of state classes required to fetch the target state.
  376. """
  377. if required_state_classes is None:
  378. required_state_classes = set()
  379. # Get the substates if requested.
  380. if subclasses:
  381. for substate in target_state_cls.get_substates():
  382. self._get_required_state_classes(
  383. substate,
  384. subclasses=True,
  385. required_state_classes=required_state_classes,
  386. )
  387. if target_state_cls in required_state_classes:
  388. return required_state_classes
  389. required_state_classes.add(target_state_cls)
  390. # Get dependent substates.
  391. for pd_substates in target_state_cls._get_potentially_dirty_states():
  392. self._get_required_state_classes(
  393. pd_substates,
  394. subclasses=False,
  395. required_state_classes=required_state_classes,
  396. )
  397. # Get the parent state if it exists.
  398. if parent_state := target_state_cls.get_parent_state():
  399. self._get_required_state_classes(
  400. parent_state,
  401. subclasses=False,
  402. required_state_classes=required_state_classes,
  403. )
  404. return required_state_classes
  405. def _get_populated_states(
  406. self,
  407. target_state: BaseState,
  408. populated_states: dict[str, BaseState] | None = None,
  409. ) -> dict[str, BaseState]:
  410. """Recursively determine which states from target_state are already fetched.
  411. Args:
  412. target_state: The state to check for populated states.
  413. populated_states: Recursive argument tracking states seen in previous calls.
  414. Returns:
  415. A dictionary of state full name to state instance.
  416. """
  417. if populated_states is None:
  418. populated_states = {}
  419. if target_state.get_full_name() in populated_states:
  420. return populated_states
  421. populated_states[target_state.get_full_name()] = target_state
  422. for substate in target_state.substates.values():
  423. self._get_populated_states(substate, populated_states=populated_states)
  424. if target_state.parent_state is not None:
  425. self._get_populated_states(
  426. target_state.parent_state, populated_states=populated_states
  427. )
  428. return populated_states
  429. @override
  430. async def get_state(
  431. self,
  432. token: str,
  433. top_level: bool = True,
  434. for_state_instance: BaseState | None = None,
  435. ) -> BaseState:
  436. """Get the state for a token.
  437. Args:
  438. token: The token to get the state for.
  439. top_level: If true, return an instance of the top-level state (self.state).
  440. for_state_instance: If provided, attach the requested states to this existing state tree.
  441. Returns:
  442. The state for the token.
  443. Raises:
  444. RuntimeError: when the state_cls is not specified in the token, or when the parent state for a
  445. requested state was not fetched.
  446. """
  447. # Split the actual token from the fully qualified substate name.
  448. token, state_path = _split_substate_key(token)
  449. if state_path:
  450. # Get the State class associated with the given path.
  451. state_cls = self.state.get_class_substate(state_path)
  452. else:
  453. raise RuntimeError(
  454. f"StateManagerRedis requires token to be specified in the form of {{token}}_{{state_full_name}}, but got {token}"
  455. )
  456. # Determine which states we already have.
  457. flat_state_tree: dict[str, BaseState] = (
  458. self._get_populated_states(for_state_instance) if for_state_instance else {}
  459. )
  460. # Determine which states from the tree need to be fetched.
  461. required_state_classes = sorted(
  462. self._get_required_state_classes(state_cls, subclasses=True)
  463. - {type(s) for s in flat_state_tree.values()},
  464. key=lambda x: x.get_full_name(),
  465. )
  466. redis_pipeline = self.redis.pipeline()
  467. for state_cls in required_state_classes:
  468. redis_pipeline.get(_substate_key(token, state_cls))
  469. for state_cls, redis_state in zip(
  470. required_state_classes,
  471. await redis_pipeline.execute(),
  472. strict=False,
  473. ):
  474. state = None
  475. if redis_state is not None:
  476. # Deserialize the substate.
  477. with contextlib.suppress(StateSchemaMismatchError):
  478. state = BaseState._deserialize(data=redis_state)
  479. if state is None:
  480. # Key didn't exist or schema mismatch so create a new instance for this token.
  481. state = state_cls(
  482. init_substates=False,
  483. _reflex_internal_init=True,
  484. )
  485. flat_state_tree[state.get_full_name()] = state
  486. if state.get_parent_state() is not None:
  487. parent_state_name, _dot, state_name = state.get_full_name().rpartition(
  488. "."
  489. )
  490. parent_state = flat_state_tree.get(parent_state_name)
  491. if parent_state is None:
  492. raise RuntimeError(
  493. f"Parent state for {state.get_full_name()} was not found "
  494. "in the state tree, but should have already been fetched. "
  495. "This is a bug",
  496. )
  497. parent_state.substates[state_name] = state
  498. state.parent_state = parent_state
  499. # To retain compatibility with previous implementation, by default, we return
  500. # the top-level state which should always be fetched or already cached.
  501. if top_level:
  502. return flat_state_tree[self.state.get_full_name()]
  503. return flat_state_tree[state_cls.get_full_name()]
  504. @override
  505. async def set_state(
  506. self,
  507. token: str,
  508. state: BaseState,
  509. lock_id: bytes | None = None,
  510. ):
  511. """Set the state for a token.
  512. Args:
  513. token: The token to set the state for.
  514. state: The state to set.
  515. lock_id: If provided, the lock_key must be set to this value to set the state.
  516. Raises:
  517. LockExpiredError: If lock_id is provided and the lock for the token is not held by that ID.
  518. RuntimeError: If the state instance doesn't match the state name in the token.
  519. """
  520. # Check that we're holding the lock.
  521. if (
  522. lock_id is not None
  523. and await self.redis.get(self._lock_key(token)) != lock_id
  524. ):
  525. raise LockExpiredError(
  526. f"Lock expired for token {token} while processing. Consider increasing "
  527. f"`app.state_manager.lock_expiration` (currently {self.lock_expiration}) "
  528. "or use `@rx.event(background=True)` decorator for long-running tasks."
  529. )
  530. elif lock_id is not None:
  531. time_taken = self.lock_expiration / 1000 - (
  532. await self.redis.ttl(self._lock_key(token))
  533. )
  534. if time_taken > self.lock_warning_threshold / 1000:
  535. console.warn(
  536. f"Lock for token {token} was held too long {time_taken=}s, "
  537. f"use `@rx.event(background=True)` decorator for long-running tasks.",
  538. dedupe=True,
  539. )
  540. client_token, substate_name = _split_substate_key(token)
  541. # If the substate name on the token doesn't match the instance name, it cannot have a parent.
  542. if state.parent_state is not None and state.get_full_name() != substate_name:
  543. raise RuntimeError(
  544. f"Cannot `set_state` with mismatching token {token} and substate {state.get_full_name()}."
  545. )
  546. # Recursively set_state on all known substates.
  547. tasks = [
  548. asyncio.create_task(
  549. self.set_state(
  550. _substate_key(client_token, substate),
  551. substate,
  552. lock_id,
  553. )
  554. )
  555. for substate in state.substates.values()
  556. ]
  557. # Persist only the given state (parents or substates are excluded by BaseState.__getstate__).
  558. if state._get_was_touched():
  559. pickle_state = state._serialize()
  560. if pickle_state:
  561. await self.redis.set(
  562. _substate_key(client_token, state),
  563. pickle_state,
  564. ex=self.token_expiration,
  565. )
  566. # Wait for substates to be persisted.
  567. for t in tasks:
  568. await t
  569. @override
  570. @contextlib.asynccontextmanager
  571. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  572. """Modify the state for a token while holding exclusive lock.
  573. Args:
  574. token: The token to modify the state for.
  575. Yields:
  576. The state for the token.
  577. """
  578. async with self._lock(token) as lock_id:
  579. state = await self.get_state(token)
  580. yield state
  581. await self.set_state(token, state, lock_id)
  582. @staticmethod
  583. def _lock_key(token: str) -> bytes:
  584. """Get the redis key for a token's lock.
  585. Args:
  586. token: The token to get the lock key for.
  587. Returns:
  588. The redis lock key for the token.
  589. """
  590. # All substates share the same lock domain, so ignore any substate path suffix.
  591. client_token = _split_substate_key(token)[0]
  592. return f"{client_token}_lock".encode()
  593. async def _try_get_lock(self, lock_key: bytes, lock_id: bytes) -> bool | None:
  594. """Try to get a redis lock for a token.
  595. Args:
  596. lock_key: The redis key for the lock.
  597. lock_id: The ID of the lock.
  598. Returns:
  599. True if the lock was obtained.
  600. """
  601. return await self.redis.set(
  602. lock_key,
  603. lock_id,
  604. px=self.lock_expiration,
  605. nx=True, # only set if it doesn't exist
  606. )
  607. async def _get_pubsub_message(
  608. self, pubsub: PubSub, timeout: float | None = None
  609. ) -> None:
  610. """Get lock release events from the pubsub.
  611. Args:
  612. pubsub: The pubsub to get a message from.
  613. timeout: Remaining time to wait for a message.
  614. Returns:
  615. The message.
  616. """
  617. if timeout is None:
  618. timeout = self.lock_expiration / 1000.0
  619. started = time.time()
  620. message = await pubsub.get_message(
  621. ignore_subscribe_messages=True,
  622. timeout=timeout,
  623. )
  624. if (
  625. message is None
  626. or message["data"] not in self._redis_keyspace_lock_release_events
  627. ):
  628. remaining = timeout - (time.time() - started)
  629. if remaining <= 0:
  630. return
  631. await self._get_pubsub_message(pubsub, timeout=remaining)
  632. async def _enable_keyspace_notifications(self):
  633. """Enable keyspace notifications for the redis server.
  634. Raises:
  635. ResponseError: when the keyspace config cannot be set.
  636. """
  637. if self._redis_notify_keyspace_events_enabled:
  638. return
  639. # Find out which logical database index is being used.
  640. self._redis_db = self.redis.get_connection_kwargs().get("db", self._redis_db)
  641. try:
  642. await self.redis.config_set(
  643. "notify-keyspace-events",
  644. self._redis_notify_keyspace_events,
  645. )
  646. except ResponseError:
  647. # Some redis servers only allow out-of-band configuration, so ignore errors here.
  648. if not environment.REFLEX_IGNORE_REDIS_CONFIG_ERROR.get():
  649. raise
  650. self._redis_notify_keyspace_events_enabled = True
  651. async def _wait_lock(self, lock_key: bytes, lock_id: bytes) -> None:
  652. """Wait for a redis lock to be released via pubsub.
  653. Coroutine will not return until the lock is obtained.
  654. Args:
  655. lock_key: The redis key for the lock.
  656. lock_id: The ID of the lock.
  657. """
  658. # Enable keyspace notifications for the lock key, so we know when it is available.
  659. await self._enable_keyspace_notifications()
  660. lock_key_channel = f"__keyspace@{self._redis_db}__:{lock_key.decode()}"
  661. async with self.redis.pubsub() as pubsub:
  662. await pubsub.psubscribe(lock_key_channel)
  663. # wait for the lock to be released
  664. while True:
  665. # fast path
  666. if await self._try_get_lock(lock_key, lock_id):
  667. return
  668. # wait for lock events
  669. await self._get_pubsub_message(pubsub)
  670. @contextlib.asynccontextmanager
  671. async def _lock(self, token: str):
  672. """Obtain a redis lock for a token.
  673. Args:
  674. token: The token to obtain a lock for.
  675. Yields:
  676. The ID of the lock (to be passed to set_state).
  677. Raises:
  678. LockExpiredError: If the lock has expired while processing the event.
  679. """
  680. lock_key = self._lock_key(token)
  681. lock_id = uuid.uuid4().hex.encode()
  682. if not await self._try_get_lock(lock_key, lock_id):
  683. # Missed the fast-path to get lock, subscribe for lock delete/expire events
  684. await self._wait_lock(lock_key, lock_id)
  685. state_is_locked = True
  686. try:
  687. yield lock_id
  688. except LockExpiredError:
  689. state_is_locked = False
  690. raise
  691. finally:
  692. if state_is_locked:
  693. # only delete our lock
  694. await self.redis.delete(lock_key)
  695. async def close(self):
  696. """Explicitly close the redis connection and connection_pool.
  697. It is necessary in testing scenarios to close between asyncio test cases
  698. to avoid having lingering redis connections associated with event loops
  699. that will be closed (each test case uses its own event loop).
  700. Note: Connections will be automatically reopened when needed.
  701. """
  702. await self.redis.aclose(close_connection_pool=True)
  703. def get_state_manager() -> StateManager:
  704. """Get the state manager for the app that is currently running.
  705. Returns:
  706. The state manager.
  707. """
  708. return prerequisites.get_and_validate_app().app.state_manager