state.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. """Define the reflex state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import copy
  5. import functools
  6. import inspect
  7. import json
  8. import traceback
  9. import urllib.parse
  10. from abc import ABC
  11. from collections import defaultdict
  12. from types import FunctionType
  13. from typing import (
  14. Any,
  15. AsyncIterator,
  16. Callable,
  17. ClassVar,
  18. Dict,
  19. List,
  20. Optional,
  21. Sequence,
  22. Set,
  23. Tuple,
  24. Type,
  25. Union,
  26. )
  27. import cloudpickle
  28. import pydantic
  29. from redis import Redis
  30. from reflex import constants
  31. from reflex.base import Base
  32. from reflex.event import Event, EventHandler, EventSpec, fix_events, window_alert
  33. from reflex.utils import format, prerequisites, types
  34. from reflex.vars import BaseVar, ComputedVar, ReflexDict, ReflexList, Var
  35. Delta = Dict[str, Any]
  36. class State(Base, ABC, extra=pydantic.Extra.allow):
  37. """The state of the app."""
  38. # A map from the var name to the var.
  39. vars: ClassVar[Dict[str, Var]] = {}
  40. # The base vars of the class.
  41. base_vars: ClassVar[Dict[str, BaseVar]] = {}
  42. # The computed vars of the class.
  43. computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
  44. # Vars inherited by the parent state.
  45. inherited_vars: ClassVar[Dict[str, Var]] = {}
  46. # Backend vars that are never sent to the client.
  47. backend_vars: ClassVar[Dict[str, Any]] = {}
  48. # Backend vars inherited
  49. inherited_backend_vars: ClassVar[Dict[str, Any]] = {}
  50. # The event handlers.
  51. event_handlers: ClassVar[Dict[str, EventHandler]] = {}
  52. # The parent state.
  53. parent_state: Optional[State] = None
  54. # The substates of the state.
  55. substates: Dict[str, State] = {}
  56. # The set of dirty vars.
  57. dirty_vars: Set[str] = set()
  58. # The set of dirty substates.
  59. dirty_substates: Set[str] = set()
  60. # The routing path that triggered the state
  61. router_data: Dict[str, Any] = {}
  62. # Mapping of var name to set of computed variables that depend on it
  63. computed_var_dependencies: Dict[str, Set[str]] = {}
  64. # Mapping of var name to set of substates that depend on it
  65. substate_var_dependencies: Dict[str, Set[str]] = {}
  66. # Per-instance copy of backend variable values
  67. _backend_vars: Dict[str, Any] = {}
  68. def __init__(self, *args, parent_state: Optional[State] = None, **kwargs):
  69. """Initialize the state.
  70. Args:
  71. *args: The args to pass to the Pydantic init method.
  72. parent_state: The parent state.
  73. **kwargs: The kwargs to pass to the Pydantic init method.
  74. """
  75. kwargs["parent_state"] = parent_state
  76. super().__init__(*args, **kwargs)
  77. # initialize per-instance var dependency tracking
  78. self.computed_var_dependencies = defaultdict(set)
  79. self.substate_var_dependencies = defaultdict(set)
  80. # Setup the substates.
  81. for substate in self.get_substates():
  82. self.substates[substate.get_name()] = substate(parent_state=self)
  83. # Convert the event handlers to functions.
  84. for name, event_handler in self.event_handlers.items():
  85. fn = functools.partial(event_handler.fn, self)
  86. fn.__module__ = event_handler.fn.__module__ # type: ignore
  87. fn.__qualname__ = event_handler.fn.__qualname__ # type: ignore
  88. setattr(self, name, fn)
  89. # Initialize computed vars dependencies.
  90. inherited_vars = set(self.inherited_vars).union(
  91. set(self.inherited_backend_vars),
  92. )
  93. for cvar_name, cvar in self.computed_vars.items():
  94. # Add the dependencies.
  95. for var in cvar.deps(objclass=type(self)):
  96. self.computed_var_dependencies[var].add(cvar_name)
  97. if var in inherited_vars:
  98. # track that this substate depends on its parent for this var
  99. state_name = self.get_name()
  100. parent_state = self.parent_state
  101. while parent_state is not None and var in parent_state.vars:
  102. parent_state.substate_var_dependencies[var].add(state_name)
  103. state_name, parent_state = (
  104. parent_state.get_name(),
  105. parent_state.parent_state,
  106. )
  107. # Initialize the mutable fields.
  108. self._init_mutable_fields()
  109. # Create a fresh copy of the backend variables for this instance
  110. self._backend_vars = copy.deepcopy(self.backend_vars)
  111. def _init_mutable_fields(self):
  112. """Initialize mutable fields.
  113. So that mutation to them can be detected by the app:
  114. * list
  115. """
  116. for field in self.base_vars.values():
  117. value = getattr(self, field.name)
  118. value_in_rx_data = _convert_mutable_datatypes(
  119. value, self._reassign_field, field.name
  120. )
  121. if types._issubclass(field.type_, Union[List, Dict]):
  122. setattr(self, field.name, value_in_rx_data)
  123. self.clean()
  124. def _reassign_field(self, field_name: str):
  125. """Reassign the given field.
  126. Primarily for mutation in fields of mutable data types.
  127. Args:
  128. field_name: The name of the field we want to reassign
  129. """
  130. setattr(
  131. self,
  132. field_name,
  133. getattr(self, field_name),
  134. )
  135. def __repr__(self) -> str:
  136. """Get the string representation of the state.
  137. Returns:
  138. The string representation of the state.
  139. """
  140. return f"{self.__class__.__name__}({self.dict()})"
  141. @classmethod
  142. def __init_subclass__(cls, **kwargs):
  143. """Do some magic for the subclass initialization.
  144. Args:
  145. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  146. """
  147. super().__init_subclass__(**kwargs)
  148. # Get the parent vars.
  149. parent_state = cls.get_parent_state()
  150. if parent_state is not None:
  151. cls.inherited_vars = parent_state.vars
  152. cls.inherited_backend_vars = parent_state.backend_vars
  153. cls.new_backend_vars = {
  154. name: value
  155. for name, value in cls.__dict__.items()
  156. if types.is_backend_variable(name)
  157. and name not in cls.inherited_backend_vars
  158. and not isinstance(value, FunctionType)
  159. }
  160. cls.backend_vars = {**cls.inherited_backend_vars, **cls.new_backend_vars}
  161. # Set the base and computed vars.
  162. cls.base_vars = {
  163. f.name: BaseVar(name=f.name, type_=f.outer_type_).set_state(cls)
  164. for f in cls.get_fields().values()
  165. if f.name not in cls.get_skip_vars()
  166. }
  167. cls.computed_vars = {
  168. v.name: v.set_state(cls)
  169. for v in cls.__dict__.values()
  170. if isinstance(v, ComputedVar)
  171. }
  172. cls.vars = {
  173. **cls.inherited_vars,
  174. **cls.base_vars,
  175. **cls.computed_vars,
  176. }
  177. cls.event_handlers = {}
  178. # Setup the base vars at the class level.
  179. for prop in cls.base_vars.values():
  180. cls._init_var(prop)
  181. # Set up the event handlers.
  182. events = {
  183. name: fn
  184. for name, fn in cls.__dict__.items()
  185. if not name.startswith("_")
  186. and isinstance(fn, Callable)
  187. and not isinstance(fn, EventHandler)
  188. }
  189. for name, fn in events.items():
  190. handler = EventHandler(fn=fn)
  191. cls.event_handlers[name] = handler
  192. setattr(cls, name, handler)
  193. @classmethod
  194. def get_skip_vars(cls) -> Set[str]:
  195. """Get the vars to skip when serializing.
  196. Returns:
  197. The vars to skip when serializing.
  198. """
  199. return set(cls.inherited_vars) | {
  200. "parent_state",
  201. "substates",
  202. "dirty_vars",
  203. "dirty_substates",
  204. "router_data",
  205. "computed_var_dependencies",
  206. "substate_var_dependencies",
  207. "_backend_vars",
  208. }
  209. @classmethod
  210. @functools.lru_cache()
  211. def get_parent_state(cls) -> Optional[Type[State]]:
  212. """Get the parent state.
  213. Returns:
  214. The parent state.
  215. """
  216. parent_states = [
  217. base
  218. for base in cls.__bases__
  219. if types._issubclass(base, State) and base is not State
  220. ]
  221. assert len(parent_states) < 2, "Only one parent state is allowed."
  222. return parent_states[0] if len(parent_states) == 1 else None # type: ignore
  223. @classmethod
  224. @functools.lru_cache()
  225. def get_substates(cls) -> Set[Type[State]]:
  226. """Get the substates of the state.
  227. Returns:
  228. The substates of the state.
  229. """
  230. return set(cls.__subclasses__())
  231. @classmethod
  232. @functools.lru_cache()
  233. def get_name(cls) -> str:
  234. """Get the name of the state.
  235. Returns:
  236. The name of the state.
  237. """
  238. return format.to_snake_case(cls.__name__)
  239. @classmethod
  240. @functools.lru_cache()
  241. def get_full_name(cls) -> str:
  242. """Get the full name of the state.
  243. Returns:
  244. The full name of the state.
  245. """
  246. name = cls.get_name()
  247. parent_state = cls.get_parent_state()
  248. if parent_state is not None:
  249. name = ".".join((parent_state.get_full_name(), name))
  250. return name
  251. @classmethod
  252. @functools.lru_cache()
  253. def get_class_substate(cls, path: Sequence[str]) -> Type[State]:
  254. """Get the class substate.
  255. Args:
  256. path: The path to the substate.
  257. Returns:
  258. The class substate.
  259. Raises:
  260. ValueError: If the substate is not found.
  261. """
  262. if len(path) == 0:
  263. return cls
  264. if path[0] == cls.get_name():
  265. if len(path) == 1:
  266. return cls
  267. path = path[1:]
  268. for substate in cls.get_substates():
  269. if path[0] == substate.get_name():
  270. return substate.get_class_substate(path[1:])
  271. raise ValueError(f"Invalid path: {path}")
  272. @classmethod
  273. def get_class_var(cls, path: Sequence[str]) -> Any:
  274. """Get the class var.
  275. Args:
  276. path: The path to the var.
  277. Returns:
  278. The class var.
  279. Raises:
  280. ValueError: If the path is invalid.
  281. """
  282. path, name = path[:-1], path[-1]
  283. substate = cls.get_class_substate(tuple(path))
  284. if not hasattr(substate, name):
  285. raise ValueError(f"Invalid path: {path}")
  286. return getattr(substate, name)
  287. @classmethod
  288. def _init_var(cls, prop: BaseVar):
  289. """Initialize a variable.
  290. Args:
  291. prop: The variable to initialize
  292. Raises:
  293. TypeError: if the variable has an incorrect type
  294. """
  295. if not types.is_valid_var_type(prop.type_):
  296. raise TypeError(
  297. "State vars must be primitive Python types, "
  298. "Plotly figures, Pandas dataframes, "
  299. "or subclasses of rx.Base. "
  300. f'Found var "{prop.name}" with type {prop.type_}.'
  301. )
  302. cls._set_var(prop)
  303. cls._create_setter(prop)
  304. cls._set_default_value(prop)
  305. @classmethod
  306. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  307. """Add dynamically a variable to the State.
  308. The variable added this way can be used in the same way as a variable
  309. defined statically in the model.
  310. Args:
  311. name: The name of the variable
  312. type_: The type of the variable
  313. default_value: The default value of the variable
  314. Raises:
  315. NameError: if a variable of this name already exists
  316. """
  317. if name in cls.__fields__:
  318. raise NameError(
  319. f"The variable '{name}' already exist. Use a different name"
  320. )
  321. # create the variable based on name and type
  322. var = BaseVar(name=name, type_=type_)
  323. var.set_state(cls)
  324. # add the pydantic field dynamically (must be done before _init_var)
  325. cls.add_field(var, default_value)
  326. cls._init_var(var)
  327. # update the internal dicts so the new variable is correctly handled
  328. cls.base_vars.update({name: var})
  329. cls.vars.update({name: var})
  330. # let substates know about the new variable
  331. for substate_class in cls.__subclasses__():
  332. substate_class.vars.setdefault(name, var)
  333. @classmethod
  334. def _set_var(cls, prop: BaseVar):
  335. """Set the var as a class member.
  336. Args:
  337. prop: The var instance to set.
  338. """
  339. setattr(cls, prop.name, prop)
  340. @classmethod
  341. def _create_setter(cls, prop: BaseVar):
  342. """Create a setter for the var.
  343. Args:
  344. prop: The var to create a setter for.
  345. """
  346. setter_name = prop.get_setter_name(include_state=False)
  347. if setter_name not in cls.__dict__:
  348. event_handler = EventHandler(fn=prop.get_setter())
  349. cls.event_handlers[setter_name] = event_handler
  350. setattr(cls, setter_name, event_handler)
  351. @classmethod
  352. def _set_default_value(cls, prop: BaseVar):
  353. """Set the default value for the var.
  354. Args:
  355. prop: The var to set the default value for.
  356. """
  357. # Get the pydantic field for the var.
  358. field = cls.get_fields()[prop.name]
  359. default_value = prop.get_default_value()
  360. if field.required and default_value is not None:
  361. field.required = False
  362. field.default = default_value
  363. def get_token(self) -> str:
  364. """Return the token of the client associated with this state.
  365. Returns:
  366. The token of the client.
  367. """
  368. return self.router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
  369. def get_sid(self) -> str:
  370. """Return the session ID of the client associated with this state.
  371. Returns:
  372. The session ID of the client.
  373. """
  374. return self.router_data.get(constants.RouteVar.SESSION_ID, "")
  375. def get_headers(self) -> Dict:
  376. """Return the headers of the client associated with this state.
  377. Returns:
  378. The headers of the client.
  379. """
  380. return self.router_data.get(constants.RouteVar.HEADERS, {})
  381. def get_client_ip(self) -> str:
  382. """Return the IP of the client associated with this state.
  383. Returns:
  384. The IP of the client.
  385. """
  386. return self.router_data.get(constants.RouteVar.CLIENT_IP, "")
  387. def get_current_page(self) -> str:
  388. """Obtain the path of current page from the router data.
  389. Returns:
  390. The current page.
  391. """
  392. return self.router_data.get(constants.RouteVar.PATH, "")
  393. def get_query_params(self) -> Dict[str, str]:
  394. """Obtain the query parameters for the queried page.
  395. The query object contains both the URI parameters and the GET parameters.
  396. Returns:
  397. The dict of query parameters.
  398. """
  399. return self.router_data.get(constants.RouteVar.QUERY, {})
  400. def get_cookies(self) -> Dict[str, str]:
  401. """Obtain the cookies of the client stored in the browser.
  402. Returns:
  403. The dict of cookies.
  404. """
  405. cookie_dict = {}
  406. cookies = self.get_headers().get(constants.RouteVar.COOKIE, "").split(";")
  407. cookie_pairs = [cookie.split("=") for cookie in cookies if cookie]
  408. for pair in cookie_pairs:
  409. key, value = pair[0].strip(), urllib.parse.unquote(pair[1].strip())
  410. try:
  411. # cast non-string values to the actual types.
  412. value = json.loads(value)
  413. except json.JSONDecodeError:
  414. pass
  415. finally:
  416. cookie_dict[key] = value
  417. return cookie_dict
  418. @classmethod
  419. def setup_dynamic_args(cls, args: dict[str, str]):
  420. """Set up args for easy access in renderer.
  421. Args:
  422. args: a dict of args
  423. """
  424. def argsingle_factory(param):
  425. @ComputedVar
  426. def inner_func(self) -> str:
  427. return self.get_query_params().get(param, "")
  428. return inner_func
  429. def arglist_factory(param):
  430. @ComputedVar
  431. def inner_func(self) -> List:
  432. return self.get_query_params().get(param, [])
  433. return inner_func
  434. for param, value in args.items():
  435. if value == constants.RouteArgType.SINGLE:
  436. func = argsingle_factory(param)
  437. elif value == constants.RouteArgType.LIST:
  438. func = arglist_factory(param)
  439. else:
  440. continue
  441. func.fget.__name__ = param # to allow passing as a prop
  442. cls.vars[param] = cls.computed_vars[param] = func.set_state(cls) # type: ignore
  443. setattr(cls, param, func)
  444. def __getattribute__(self, name: str) -> Any:
  445. """Get the state var.
  446. If the var is inherited, get the var from the parent state.
  447. Args:
  448. name: The name of the var.
  449. Returns:
  450. The value of the var.
  451. """
  452. # If the state hasn't been initialized yet, return the default value.
  453. if not super().__getattribute__("__dict__"):
  454. return super().__getattribute__(name)
  455. inherited_vars = {
  456. **super().__getattribute__("inherited_vars"),
  457. **super().__getattribute__("inherited_backend_vars"),
  458. }
  459. if name in inherited_vars:
  460. return getattr(super().__getattribute__("parent_state"), name)
  461. elif name in super().__getattribute__("_backend_vars"):
  462. return super().__getattribute__("_backend_vars").__getitem__(name)
  463. return super().__getattribute__(name)
  464. def __setattr__(self, name: str, value: Any):
  465. """Set the attribute.
  466. If the attribute is inherited, set the attribute on the parent state.
  467. Args:
  468. name: The name of the attribute.
  469. value: The value of the attribute.
  470. """
  471. # Set the var on the parent state.
  472. inherited_vars = {**self.inherited_vars, **self.inherited_backend_vars}
  473. if name in inherited_vars:
  474. setattr(self.parent_state, name, value)
  475. return
  476. if types.is_backend_variable(name) and name != "_backend_vars":
  477. self._backend_vars.__setitem__(name, value)
  478. self.dirty_vars.add(name)
  479. self.mark_dirty()
  480. return
  481. # Make sure lists and dicts are converted to ReflexList and ReflexDict.
  482. if name in self.vars and types._isinstance(value, Union[List, Dict]):
  483. value = _convert_mutable_datatypes(value, self._reassign_field, name)
  484. # Set the attribute.
  485. super().__setattr__(name, value)
  486. # Add the var to the dirty list.
  487. if name in self.vars or name in self.computed_var_dependencies:
  488. self.dirty_vars.add(name)
  489. self.mark_dirty()
  490. # For now, handle router_data updates as a special case
  491. if name == constants.ROUTER_DATA:
  492. self.dirty_vars.add(name)
  493. self.mark_dirty()
  494. # propagate router_data updates down the state tree
  495. for substate in self.substates.values():
  496. setattr(substate, name, value)
  497. def reset(self):
  498. """Reset all the base vars to their default values."""
  499. # Reset the base vars.
  500. fields = self.get_fields()
  501. for prop_name in self.base_vars:
  502. setattr(self, prop_name, fields[prop_name].default)
  503. # Recursively reset the substates.
  504. for substate in self.substates.values():
  505. substate.reset()
  506. # Clean the state.
  507. self.clean()
  508. def get_substate(self, path: Sequence[str]) -> Optional[State]:
  509. """Get the substate.
  510. Args:
  511. path: The path to the substate.
  512. Returns:
  513. The substate.
  514. Raises:
  515. ValueError: If the substate is not found.
  516. """
  517. if len(path) == 0:
  518. return self
  519. if path[0] == self.get_name():
  520. if len(path) == 1:
  521. return self
  522. path = path[1:]
  523. if path[0] not in self.substates:
  524. raise ValueError(f"Invalid path: {path}")
  525. return self.substates[path[0]].get_substate(path[1:])
  526. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  527. """Obtain event info and process event.
  528. Args:
  529. event: The event to process.
  530. Yields:
  531. The state update after processing the event.
  532. Raises:
  533. ValueError: If the state value is None.
  534. """
  535. # Get the event handler.
  536. path = event.name.split(".")
  537. path, name = path[:-1], path[-1]
  538. substate = self.get_substate(path)
  539. handler = substate.event_handlers[name] # type: ignore
  540. if not substate:
  541. raise ValueError(
  542. "The value of state cannot be None when processing an event."
  543. )
  544. # Get the event generator.
  545. event_iter = self._process_event(
  546. handler=handler,
  547. state=substate,
  548. payload=event.payload,
  549. )
  550. # Clean the state before processing the event.
  551. self.clean()
  552. # Run the event generator and return state updates.
  553. async for events, final in event_iter:
  554. # Fix the returned events.
  555. events = fix_events(events, event.token) # type: ignore
  556. # Get the delta after processing the event.
  557. delta = self.get_delta()
  558. # Yield the state update.
  559. yield StateUpdate(delta=delta, events=events, final=final)
  560. # Clean the state to prepare for the next event.
  561. self.clean()
  562. async def _process_event(
  563. self, handler: EventHandler, state: State, payload: Dict
  564. ) -> AsyncIterator[Tuple[Optional[List[EventSpec]], bool]]:
  565. """Process event.
  566. Args:
  567. handler: Eventhandler to process.
  568. state: State to process the handler.
  569. payload: The event payload.
  570. Yields:
  571. Tuple containing:
  572. 0: The state update after processing the event.
  573. 1: Whether the event is the final event.
  574. """
  575. # Get the function to process the event.
  576. fn = functools.partial(handler.fn, state)
  577. # Wrap the function in a try/except block.
  578. try:
  579. # Handle async functions.
  580. if asyncio.iscoroutinefunction(fn.func):
  581. events = await fn(**payload)
  582. # Handle regular functions.
  583. else:
  584. events = fn(**payload)
  585. # Handle async generators.
  586. if inspect.isasyncgen(events):
  587. async for event in events:
  588. yield event, False
  589. yield None, True
  590. # Handle regular generators.
  591. elif inspect.isgenerator(events):
  592. try:
  593. while True:
  594. yield next(events), False
  595. except StopIteration as si:
  596. # the "return" value of the generator is not available
  597. # in the loop, we must catch StopIteration to access it
  598. if si.value is not None:
  599. yield si.value, False
  600. yield None, True
  601. # Handle regular event chains.
  602. else:
  603. yield events, True
  604. # If an error occurs, throw a window alert.
  605. except Exception:
  606. error = traceback.format_exc()
  607. print(error)
  608. yield [window_alert("An error occurred. See logs for details.")], True
  609. def _always_dirty_computed_vars(self) -> Set[str]:
  610. """The set of ComputedVars that always need to be recalculated.
  611. Returns:
  612. Set of all ComputedVar in this state where cache=False
  613. """
  614. return set(
  615. cvar_name
  616. for cvar_name, cvar in self.computed_vars.items()
  617. if not cvar.cache
  618. )
  619. def _mark_dirty_computed_vars(self) -> None:
  620. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  621. dirty_vars = self.dirty_vars
  622. while dirty_vars:
  623. calc_vars, dirty_vars = dirty_vars, set()
  624. for cvar in self._dirty_computed_vars(from_vars=calc_vars):
  625. self.dirty_vars.add(cvar)
  626. dirty_vars.add(cvar)
  627. actual_var = self.computed_vars.get(cvar)
  628. if actual_var:
  629. actual_var.mark_dirty(instance=self)
  630. def _dirty_computed_vars(self, from_vars: Optional[Set[str]] = None) -> Set[str]:
  631. """Determine ComputedVars that need to be recalculated based on the given vars.
  632. Args:
  633. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  634. Returns:
  635. Set of computed vars to include in the delta.
  636. """
  637. return set(
  638. cvar
  639. for dirty_var in from_vars or self.dirty_vars
  640. for cvar in self.computed_var_dependencies[dirty_var]
  641. )
  642. def get_delta(self) -> Delta:
  643. """Get the delta for the state.
  644. Returns:
  645. The delta for the state.
  646. """
  647. delta = {}
  648. # Apply dirty variables down into substates
  649. self.dirty_vars.update(self._always_dirty_computed_vars())
  650. self.mark_dirty()
  651. # Return the dirty vars for this instance, any cached/dependent computed vars,
  652. # and always dirty computed vars (cache=False)
  653. delta_vars = (
  654. self.dirty_vars.intersection(self.base_vars)
  655. .union(self._dirty_computed_vars())
  656. .union(self._always_dirty_computed_vars())
  657. )
  658. subdelta = {
  659. prop: getattr(self, prop)
  660. for prop in delta_vars
  661. if not types.is_backend_variable(prop)
  662. }
  663. if len(subdelta) > 0:
  664. delta[self.get_full_name()] = subdelta
  665. # Recursively find the substate deltas.
  666. substates = self.substates
  667. for substate in self.dirty_substates:
  668. delta.update(substates[substate].get_delta())
  669. # Format the delta.
  670. delta = format.format_state(delta)
  671. # Return the delta.
  672. return delta
  673. def mark_dirty(self):
  674. """Mark the substate and all parent states as dirty."""
  675. state_name = self.get_name()
  676. if (
  677. self.parent_state is not None
  678. and state_name not in self.parent_state.dirty_substates
  679. ):
  680. self.parent_state.dirty_substates.add(self.get_name())
  681. self.parent_state.mark_dirty()
  682. # have to mark computed vars dirty to allow access to newly computed
  683. # values within the same ComputedVar function
  684. self._mark_dirty_computed_vars()
  685. # Propagate dirty var / computed var status into substates
  686. substates = self.substates
  687. for var in self.dirty_vars:
  688. for substate_name in self.substate_var_dependencies[var]:
  689. self.dirty_substates.add(substate_name)
  690. substate = substates[substate_name]
  691. substate.dirty_vars.add(var)
  692. substate.mark_dirty()
  693. def clean(self):
  694. """Reset the dirty vars."""
  695. # Recursively clean the substates.
  696. for substate in self.dirty_substates:
  697. self.substates[substate].clean()
  698. # Clean this state.
  699. self.dirty_vars = set()
  700. self.dirty_substates = set()
  701. def dict(self, include_computed: bool = True, **kwargs) -> Dict[str, Any]:
  702. """Convert the object to a dictionary.
  703. Args:
  704. include_computed: Whether to include computed vars.
  705. **kwargs: Kwargs to pass to the pydantic dict method.
  706. Returns:
  707. The object as a dictionary.
  708. """
  709. if include_computed:
  710. # Apply dirty variables down into substates to allow never-cached ComputedVar to
  711. # trigger recalculation of dependent vars
  712. self.dirty_vars.update(self._always_dirty_computed_vars())
  713. self.mark_dirty()
  714. base_vars = {
  715. prop_name: self.get_value(getattr(self, prop_name))
  716. for prop_name in self.base_vars
  717. }
  718. computed_vars = (
  719. {
  720. # Include the computed vars.
  721. prop_name: self.get_value(getattr(self, prop_name))
  722. for prop_name in self.computed_vars
  723. }
  724. if include_computed
  725. else {}
  726. )
  727. substate_vars = {
  728. k: v.dict(include_computed=include_computed, **kwargs)
  729. for k, v in self.substates.items()
  730. }
  731. variables = {**base_vars, **computed_vars, **substate_vars}
  732. return {k: variables[k] for k in sorted(variables)}
  733. class DefaultState(State):
  734. """The default empty state."""
  735. pass
  736. class StateUpdate(Base):
  737. """A state update sent to the frontend."""
  738. # The state delta.
  739. delta: Delta = {}
  740. # Events to be added to the event queue.
  741. events: List[Event] = []
  742. # Whether this is the final state update for the event.
  743. final: bool = True
  744. class StateManager(Base):
  745. """A class to manage many client states."""
  746. # The state class to use.
  747. state: Type[State] = DefaultState
  748. # The mapping of client ids to states.
  749. states: Dict[str, State] = {}
  750. # The token expiration time (s).
  751. token_expiration: int = constants.TOKEN_EXPIRATION
  752. # The redis client to use.
  753. redis: Optional[Redis] = None
  754. def setup(self, state: Type[State]):
  755. """Set up the state manager.
  756. Args:
  757. state: The state class to use.
  758. """
  759. self.state = state
  760. self.redis = prerequisites.get_redis()
  761. def get_state(self, token: str) -> State:
  762. """Get the state for a token.
  763. Args:
  764. token: The token to get the state for.
  765. Returns:
  766. The state for the token.
  767. """
  768. if self.redis is not None:
  769. redis_state = self.redis.get(token)
  770. if redis_state is None:
  771. self.set_state(token, self.state())
  772. return self.get_state(token)
  773. return cloudpickle.loads(redis_state)
  774. if token not in self.states:
  775. self.states[token] = self.state()
  776. return self.states[token]
  777. def set_state(self, token: str, state: State):
  778. """Set the state for a token.
  779. Args:
  780. token: The token to set the state for.
  781. state: The state to set.
  782. """
  783. if self.redis is None:
  784. return
  785. self.redis.set(token, cloudpickle.dumps(state), ex=self.token_expiration)
  786. def _convert_mutable_datatypes(
  787. field_value: Any, reassign_field: Callable, field_name: str
  788. ) -> Any:
  789. """Recursively convert mutable data to the Rx data types.
  790. Note: right now only list & dict would be handled recursively.
  791. Args:
  792. field_value: The target field_value.
  793. reassign_field:
  794. The function to reassign the field in the parent state.
  795. field_name: the name of the field in the parent state
  796. Returns:
  797. The converted field_value
  798. """
  799. if isinstance(field_value, list):
  800. field_value = [
  801. _convert_mutable_datatypes(value, reassign_field, field_name)
  802. for value in field_value
  803. ]
  804. field_value = ReflexList(
  805. field_value, reassign_field=reassign_field, field_name=field_name
  806. )
  807. if isinstance(field_value, dict):
  808. field_value = {
  809. key: _convert_mutable_datatypes(value, reassign_field, field_name)
  810. for key, value in field_value.items()
  811. }
  812. field_value = ReflexDict(
  813. field_value, reassign_field=reassign_field, field_name=field_name
  814. )
  815. return field_value