state.py 41 KB

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