state.py 39 KB

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