state.py 33 KB

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