state.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310
  1. """Define the reflex state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import contextlib
  5. import copy
  6. import functools
  7. import inspect
  8. import json
  9. import os
  10. import traceback
  11. import urllib.parse
  12. import uuid
  13. from abc import ABC, abstractmethod
  14. from collections import defaultdict
  15. from types import FunctionType, MethodType
  16. from typing import (
  17. Any,
  18. AsyncIterator,
  19. Callable,
  20. ClassVar,
  21. Dict,
  22. List,
  23. Optional,
  24. Sequence,
  25. Set,
  26. Type,
  27. )
  28. import cloudpickle
  29. import pydantic
  30. import wrapt
  31. from redis.asyncio import Redis
  32. from reflex import constants
  33. from reflex.base import Base
  34. from reflex.event import (
  35. Event,
  36. EventHandler,
  37. EventSpec,
  38. _no_chain_background_task,
  39. fix_events,
  40. window_alert,
  41. )
  42. from reflex.utils import console, format, prerequisites, types
  43. from reflex.utils.exceptions import ImmutableStateError, LockExpiredError
  44. from reflex.utils.serializers import SerializedType, serialize, serializer
  45. from reflex.vars import BaseVar, ComputedVar, Var
  46. Delta = Dict[str, Any]
  47. var = ComputedVar
  48. class HeaderData(Base):
  49. """An object containing headers data."""
  50. host: str = ""
  51. origin: str = ""
  52. upgrade: str = ""
  53. connection: str = ""
  54. pragma: str = ""
  55. cache_control: str = ""
  56. user_agent: str = ""
  57. sec_websocket_version: str = ""
  58. sec_websocket_key: str = ""
  59. sec_websocket_extensions: str = ""
  60. accept_encoding: str = ""
  61. accept_language: str = ""
  62. def __init__(self, router_data: Optional[dict] = None):
  63. """Initalize the HeaderData object based on router_data.
  64. Args:
  65. router_data: the router_data dict.
  66. """
  67. super().__init__()
  68. if router_data:
  69. for k, v in router_data.get(constants.RouteVar.HEADERS, {}).items():
  70. setattr(self, format.to_snake_case(k), v)
  71. class PageData(Base):
  72. """An object containing page data."""
  73. host: str = "" # repeated with self.headers.origin (remove or keep the duplicate?)
  74. path: str = ""
  75. raw_path: str = ""
  76. full_path: str = ""
  77. full_raw_path: str = ""
  78. params: dict = {}
  79. def __init__(self, router_data: Optional[dict] = None):
  80. """Initalize the PageData object based on router_data.
  81. Args:
  82. router_data: the router_data dict.
  83. """
  84. super().__init__()
  85. if router_data:
  86. self.host = router_data.get(constants.RouteVar.HEADERS, {}).get("origin")
  87. self.path = router_data.get(constants.RouteVar.PATH, "")
  88. self.raw_path = router_data.get(constants.RouteVar.ORIGIN, "")
  89. self.full_path = f"{self.host}{self.path}"
  90. self.full_raw_path = f"{self.host}{self.raw_path}"
  91. self.params = router_data.get(constants.RouteVar.QUERY, {})
  92. class SessionData(Base):
  93. """An object containing session data."""
  94. client_token: str = ""
  95. client_ip: str = ""
  96. session_id: str = ""
  97. def __init__(self, router_data: Optional[dict] = None):
  98. """Initalize the SessionData object based on router_data.
  99. Args:
  100. router_data: the router_data dict.
  101. """
  102. super().__init__()
  103. if router_data:
  104. self.client_token = router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
  105. self.client_ip = router_data.get(constants.RouteVar.CLIENT_IP, "")
  106. self.session_id = router_data.get(constants.RouteVar.SESSION_ID, "")
  107. class RouterData(Base):
  108. """An object containing RouterData."""
  109. session: SessionData = SessionData()
  110. headers: HeaderData = HeaderData()
  111. page: PageData = PageData()
  112. def __init__(self, router_data: Optional[dict] = None):
  113. """Initialize the RouterData object.
  114. Args:
  115. router_data: the router_data dict.
  116. """
  117. super().__init__()
  118. self.session = SessionData(router_data)
  119. self.headers = HeaderData(router_data)
  120. self.page = PageData(router_data)
  121. RESERVED_BACKEND_VAR_NAMES = {
  122. "_backend_vars",
  123. "_computed_var_dependencies",
  124. "_substate_var_dependencies",
  125. "_always_dirty_computed_vars",
  126. "_always_dirty_substates",
  127. }
  128. class BaseState(Base, ABC, extra=pydantic.Extra.allow):
  129. """The state of the app."""
  130. # A map from the var name to the var.
  131. vars: ClassVar[Dict[str, Var]] = {}
  132. # The base vars of the class.
  133. base_vars: ClassVar[Dict[str, BaseVar]] = {}
  134. # The computed vars of the class.
  135. computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
  136. # Vars inherited by the parent state.
  137. inherited_vars: ClassVar[Dict[str, Var]] = {}
  138. # Backend vars that are never sent to the client.
  139. backend_vars: ClassVar[Dict[str, Any]] = {}
  140. # Backend vars inherited
  141. inherited_backend_vars: ClassVar[Dict[str, Any]] = {}
  142. # The event handlers.
  143. event_handlers: ClassVar[Dict[str, EventHandler]] = {}
  144. # A set of subclassses of this class.
  145. class_subclasses: ClassVar[Set[Type[BaseState]]] = set()
  146. # Mapping of var name to set of computed variables that depend on it
  147. _computed_var_dependencies: ClassVar[Dict[str, Set[str]]] = {}
  148. # Mapping of var name to set of substates that depend on it
  149. _substate_var_dependencies: ClassVar[Dict[str, Set[str]]] = {}
  150. # Set of vars which always need to be recomputed
  151. _always_dirty_computed_vars: ClassVar[Set[str]] = set()
  152. # Set of substates which always need to be recomputed
  153. _always_dirty_substates: ClassVar[Set[str]] = set()
  154. # The parent state.
  155. parent_state: Optional[BaseState] = None
  156. # The substates of the state.
  157. substates: Dict[str, BaseState] = {}
  158. # The set of dirty vars.
  159. dirty_vars: Set[str] = set()
  160. # The set of dirty substates.
  161. dirty_substates: Set[str] = set()
  162. # The routing path that triggered the state
  163. router_data: Dict[str, Any] = {}
  164. # Per-instance copy of backend variable values
  165. _backend_vars: Dict[str, Any] = {}
  166. # The router data for the current page
  167. router: RouterData = RouterData()
  168. def __init__(self, *args, parent_state: BaseState | None = None, **kwargs):
  169. """Initialize the state.
  170. Args:
  171. *args: The args to pass to the Pydantic init method.
  172. parent_state: The parent state.
  173. **kwargs: The kwargs to pass to the Pydantic init method.
  174. """
  175. kwargs["parent_state"] = parent_state
  176. super().__init__(*args, **kwargs)
  177. # Setup the substates.
  178. for substate in self.get_substates():
  179. self.substates[substate.get_name()] = substate(parent_state=self)
  180. # Convert the event handlers to functions.
  181. self._init_event_handlers()
  182. # Create a fresh copy of the backend variables for this instance
  183. self._backend_vars = copy.deepcopy(self.backend_vars)
  184. def _init_event_handlers(self, state: BaseState | None = None):
  185. """Initialize event handlers.
  186. Allow event handlers to be called directly on the instance. This is
  187. called recursively for all parent states.
  188. Args:
  189. state: The state to initialize the event handlers on.
  190. """
  191. if state is None:
  192. state = self
  193. # Convert the event handlers to functions.
  194. for name, event_handler in state.event_handlers.items():
  195. if event_handler.is_background:
  196. fn = _no_chain_background_task(type(state), name, event_handler.fn)
  197. else:
  198. fn = functools.partial(event_handler.fn, self)
  199. fn.__module__ = event_handler.fn.__module__ # type: ignore
  200. fn.__qualname__ = event_handler.fn.__qualname__ # type: ignore
  201. setattr(self, name, fn)
  202. # Also allow direct calling of parent state event handlers
  203. if state.parent_state is not None:
  204. self._init_event_handlers(state.parent_state)
  205. def __repr__(self) -> str:
  206. """Get the string representation of the state.
  207. Returns:
  208. The string representation of the state.
  209. """
  210. return f"{self.__class__.__name__}({self.dict()})"
  211. @classmethod
  212. def __init_subclass__(cls, **kwargs):
  213. """Do some magic for the subclass initialization.
  214. Args:
  215. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  216. Raises:
  217. ValueError: If a substate class shadows another.
  218. """
  219. is_testing_env = constants.PYTEST_CURRENT_TEST in os.environ
  220. super().__init_subclass__(**kwargs)
  221. # Event handlers should not shadow builtin state methods.
  222. cls._check_overridden_methods()
  223. # Reset subclass tracking for this class.
  224. cls.class_subclasses = set()
  225. # Get the parent vars.
  226. parent_state = cls.get_parent_state()
  227. if parent_state is not None:
  228. cls.inherited_vars = parent_state.vars
  229. cls.inherited_backend_vars = parent_state.backend_vars
  230. # Check if another substate class with the same name has already been defined.
  231. if cls.__name__ in set(c.__name__ for c in parent_state.class_subclasses):
  232. if is_testing_env:
  233. # Clear existing subclass with same name when app is reloaded via
  234. # utils.prerequisites.get_app(reload=True)
  235. parent_state.class_subclasses = set(
  236. c
  237. for c in parent_state.class_subclasses
  238. if c.__name__ != cls.__name__
  239. )
  240. else:
  241. # During normal operation, subclasses cannot have the same name, even if they are
  242. # defined in different modules.
  243. raise ValueError(
  244. f"The substate class '{cls.__name__}' has been defined multiple times. "
  245. "Shadowing substate classes is not allowed."
  246. )
  247. # Track this new subclass in the parent state's subclasses set.
  248. parent_state.class_subclasses.add(cls)
  249. cls.new_backend_vars = {
  250. name: value
  251. for name, value in cls.__dict__.items()
  252. if types.is_backend_variable(name, cls)
  253. and name not in cls.inherited_backend_vars
  254. and not isinstance(value, FunctionType)
  255. }
  256. cls.backend_vars = {**cls.inherited_backend_vars, **cls.new_backend_vars}
  257. # Set the base and computed vars.
  258. cls.base_vars = {
  259. f.name: BaseVar(_var_name=f.name, _var_type=f.outer_type_)._var_set_state(
  260. cls
  261. )
  262. for f in cls.get_fields().values()
  263. if f.name not in cls.get_skip_vars()
  264. }
  265. cls.computed_vars = {
  266. v._var_name: v._var_set_state(cls)
  267. for v in cls.__dict__.values()
  268. if isinstance(v, ComputedVar)
  269. }
  270. cls.vars = {
  271. **cls.inherited_vars,
  272. **cls.base_vars,
  273. **cls.computed_vars,
  274. }
  275. cls.event_handlers = {}
  276. # Setup the base vars at the class level.
  277. for prop in cls.base_vars.values():
  278. cls._init_var(prop)
  279. # Set up the event handlers.
  280. events = {
  281. name: fn
  282. for name, fn in cls.__dict__.items()
  283. if cls._item_is_event_handler(name, fn)
  284. }
  285. for mixin in cls._mixins():
  286. for name, value in mixin.__dict__.items():
  287. if isinstance(value, ComputedVar):
  288. fget = cls._copy_fn(value.fget)
  289. newcv = ComputedVar(fget=fget, _var_name=value._var_name)
  290. newcv._var_set_state(cls)
  291. setattr(cls, name, newcv)
  292. cls.computed_vars[newcv._var_name] = newcv
  293. cls.vars[newcv._var_name] = newcv
  294. continue
  295. if events.get(name) is not None:
  296. continue
  297. if not cls._item_is_event_handler(name, value):
  298. continue
  299. if parent_state is not None and parent_state.event_handlers.get(name):
  300. continue
  301. value = cls._copy_fn(value)
  302. value.__qualname__ = f"{cls.__name__}.{name}"
  303. events[name] = value
  304. for name, fn in events.items():
  305. handler = EventHandler(fn=fn)
  306. cls.event_handlers[name] = handler
  307. setattr(cls, name, handler)
  308. cls._init_var_dependency_dicts()
  309. for name in cls.new_backend_vars:
  310. setattr(cls, name, PrivateVarDescriptor())
  311. @staticmethod
  312. def _copy_fn(fn: Callable) -> Callable:
  313. """Copy a function. Used to copy ComputedVars and EventHandlers from mixins.
  314. Args:
  315. fn: The function to copy.
  316. Returns:
  317. The copied function.
  318. """
  319. newfn = FunctionType(
  320. fn.__code__,
  321. fn.__globals__,
  322. name=fn.__name__,
  323. argdefs=fn.__defaults__,
  324. closure=fn.__closure__,
  325. )
  326. newfn.__annotations__ = fn.__annotations__
  327. return newfn
  328. @staticmethod
  329. def _item_is_event_handler(name: str, value: Any) -> bool:
  330. """Check if the item is an event handler.
  331. Args:
  332. name: The name of the item.
  333. value: The value of the item.
  334. Returns:
  335. Whether the item is an event handler.
  336. """
  337. return (
  338. not name.startswith("_")
  339. and isinstance(value, Callable)
  340. and not isinstance(value, EventHandler)
  341. and hasattr(value, "__code__")
  342. )
  343. @classmethod
  344. def _mixins(cls) -> List[Type]:
  345. """Get the mixin classes of the state.
  346. Returns:
  347. The mixin classes of the state.
  348. """
  349. return [
  350. mixin
  351. for mixin in cls.__mro__
  352. if not issubclass(mixin, (BaseState, ABC))
  353. and mixin not in [pydantic.BaseModel, Base]
  354. ]
  355. @classmethod
  356. def _init_var_dependency_dicts(cls):
  357. """Initialize the var dependency tracking dicts.
  358. Allows the state to know which vars each ComputedVar depends on and
  359. whether a ComputedVar depends on a var in its parent state.
  360. Additional updates tracking dicts for vars and substates that always
  361. need to be recomputed.
  362. """
  363. # Initialize per-class var dependency tracking.
  364. cls._computed_var_dependencies = defaultdict(set)
  365. cls._substate_var_dependencies = defaultdict(set)
  366. inherited_vars = set(cls.inherited_vars).union(
  367. set(cls.inherited_backend_vars),
  368. )
  369. for cvar_name, cvar in cls.computed_vars.items():
  370. # Add the dependencies.
  371. for var in cvar._deps(objclass=cls):
  372. cls._computed_var_dependencies[var].add(cvar_name)
  373. if var in inherited_vars:
  374. # track that this substate depends on its parent for this var
  375. state_name = cls.get_name()
  376. parent_state = cls.get_parent_state()
  377. while parent_state is not None and var in parent_state.vars:
  378. parent_state._substate_var_dependencies[var].add(state_name)
  379. state_name, parent_state = (
  380. parent_state.get_name(),
  381. parent_state.get_parent_state(),
  382. )
  383. # ComputedVar with cache=False always need to be recomputed
  384. cls._always_dirty_computed_vars = set(
  385. cvar_name
  386. for cvar_name, cvar in cls.computed_vars.items()
  387. if not cvar._cache
  388. )
  389. # Any substate containing a ComputedVar with cache=False always needs to be recomputed
  390. cls._always_dirty_substates = set()
  391. if cls._always_dirty_computed_vars:
  392. # Tell parent classes that this substate has always dirty computed vars
  393. state_name = cls.get_name()
  394. parent_state = cls.get_parent_state()
  395. while parent_state is not None:
  396. parent_state._always_dirty_substates.add(state_name)
  397. state_name, parent_state = (
  398. parent_state.get_name(),
  399. parent_state.get_parent_state(),
  400. )
  401. @classmethod
  402. def _check_overridden_methods(cls):
  403. """Check for shadow methods and raise error if any.
  404. Raises:
  405. NameError: When an event handler shadows an inbuilt state method.
  406. """
  407. overridden_methods = set()
  408. state_base_functions = cls._get_base_functions()
  409. for name, method in inspect.getmembers(cls, inspect.isfunction):
  410. # Check if the method is overridden and not a dunder method
  411. if (
  412. not name.startswith("__")
  413. and method.__name__ in state_base_functions
  414. and state_base_functions[method.__name__] != method
  415. ):
  416. overridden_methods.add(method.__name__)
  417. for method_name in overridden_methods:
  418. raise NameError(
  419. f"The event handler name `{method_name}` shadows a builtin State method; use a different name instead"
  420. )
  421. @classmethod
  422. def get_skip_vars(cls) -> set[str]:
  423. """Get the vars to skip when serializing.
  424. Returns:
  425. The vars to skip when serializing.
  426. """
  427. return (
  428. set(cls.inherited_vars)
  429. | {
  430. "parent_state",
  431. "substates",
  432. "dirty_vars",
  433. "dirty_substates",
  434. "router_data",
  435. }
  436. | RESERVED_BACKEND_VAR_NAMES
  437. )
  438. @classmethod
  439. @functools.lru_cache()
  440. def get_parent_state(cls) -> Type[BaseState] | None:
  441. """Get the parent state.
  442. Returns:
  443. The parent state.
  444. """
  445. parent_states = [
  446. base
  447. for base in cls.__bases__
  448. if types._issubclass(base, BaseState) and base is not BaseState
  449. ]
  450. assert len(parent_states) < 2, "Only one parent state is allowed."
  451. return parent_states[0] if len(parent_states) == 1 else None # type: ignore
  452. @classmethod
  453. def get_substates(cls) -> set[Type[BaseState]]:
  454. """Get the substates of the state.
  455. Returns:
  456. The substates of the state.
  457. """
  458. return cls.class_subclasses
  459. @classmethod
  460. @functools.lru_cache()
  461. def get_name(cls) -> str:
  462. """Get the name of the state.
  463. Returns:
  464. The name of the state.
  465. """
  466. return format.to_snake_case(cls.__name__)
  467. @classmethod
  468. @functools.lru_cache()
  469. def get_full_name(cls) -> str:
  470. """Get the full name of the state.
  471. Returns:
  472. The full name of the state.
  473. """
  474. name = cls.get_name()
  475. parent_state = cls.get_parent_state()
  476. if parent_state is not None:
  477. name = ".".join((parent_state.get_full_name(), name))
  478. return name
  479. @classmethod
  480. @functools.lru_cache()
  481. def get_class_substate(cls, path: Sequence[str]) -> Type[BaseState]:
  482. """Get the class substate.
  483. Args:
  484. path: The path to the substate.
  485. Returns:
  486. The class substate.
  487. Raises:
  488. ValueError: If the substate is not found.
  489. """
  490. if len(path) == 0:
  491. return cls
  492. if path[0] == cls.get_name():
  493. if len(path) == 1:
  494. return cls
  495. path = path[1:]
  496. for substate in cls.get_substates():
  497. if path[0] == substate.get_name():
  498. return substate.get_class_substate(path[1:])
  499. raise ValueError(f"Invalid path: {path}")
  500. @classmethod
  501. def get_class_var(cls, path: Sequence[str]) -> Any:
  502. """Get the class var.
  503. Args:
  504. path: The path to the var.
  505. Returns:
  506. The class var.
  507. Raises:
  508. ValueError: If the path is invalid.
  509. """
  510. path, name = path[:-1], path[-1]
  511. substate = cls.get_class_substate(tuple(path))
  512. if not hasattr(substate, name):
  513. raise ValueError(f"Invalid path: {path}")
  514. return getattr(substate, name)
  515. @classmethod
  516. def _init_var(cls, prop: BaseVar):
  517. """Initialize a variable.
  518. Args:
  519. prop: The variable to initialize
  520. Raises:
  521. TypeError: if the variable has an incorrect type
  522. """
  523. if not types.is_valid_var_type(prop._var_type):
  524. raise TypeError(
  525. "State vars must be primitive Python types, "
  526. "Plotly figures, Pandas dataframes, "
  527. "or subclasses of rx.Base. "
  528. f'Found var "{prop._var_name}" with type {prop._var_type}.'
  529. )
  530. cls._set_var(prop)
  531. cls._create_setter(prop)
  532. cls._set_default_value(prop)
  533. @classmethod
  534. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  535. """Add dynamically a variable to the State.
  536. The variable added this way can be used in the same way as a variable
  537. defined statically in the model.
  538. Args:
  539. name: The name of the variable
  540. type_: The type of the variable
  541. default_value: The default value of the variable
  542. Raises:
  543. NameError: if a variable of this name already exists
  544. """
  545. if name in cls.__fields__:
  546. raise NameError(
  547. f"The variable '{name}' already exist. Use a different name"
  548. )
  549. # create the variable based on name and type
  550. var = BaseVar(_var_name=name, _var_type=type_)
  551. var._var_set_state(cls)
  552. # add the pydantic field dynamically (must be done before _init_var)
  553. cls.add_field(var, default_value)
  554. cls._init_var(var)
  555. # update the internal dicts so the new variable is correctly handled
  556. cls.base_vars.update({name: var})
  557. cls.vars.update({name: var})
  558. # let substates know about the new variable
  559. for substate_class in cls.__subclasses__():
  560. substate_class.vars.setdefault(name, var)
  561. # Reinitialize dependency tracking dicts.
  562. cls._init_var_dependency_dicts()
  563. @classmethod
  564. def _set_var(cls, prop: BaseVar):
  565. """Set the var as a class member.
  566. Args:
  567. prop: The var instance to set.
  568. """
  569. setattr(cls, prop._var_name, prop)
  570. @classmethod
  571. def _create_setter(cls, prop: BaseVar):
  572. """Create a setter for the var.
  573. Args:
  574. prop: The var to create a setter for.
  575. """
  576. setter_name = prop.get_setter_name(include_state=False)
  577. if setter_name not in cls.__dict__:
  578. event_handler = EventHandler(fn=prop.get_setter())
  579. cls.event_handlers[setter_name] = event_handler
  580. setattr(cls, setter_name, event_handler)
  581. @classmethod
  582. def _set_default_value(cls, prop: BaseVar):
  583. """Set the default value for the var.
  584. Args:
  585. prop: The var to set the default value for.
  586. """
  587. # Get the pydantic field for the var.
  588. field = cls.get_fields()[prop._var_name]
  589. if field.required:
  590. default_value = prop.get_default_value()
  591. if default_value is not None:
  592. field.required = False
  593. field.default = default_value
  594. if (
  595. not field.required
  596. and field.default is None
  597. and not types.is_optional(prop._var_type)
  598. ):
  599. # Ensure frontend uses null coalescing when accessing.
  600. prop._var_type = Optional[prop._var_type]
  601. @staticmethod
  602. def _get_base_functions() -> dict[str, FunctionType]:
  603. """Get all functions of the state class excluding dunder methods.
  604. Returns:
  605. The functions of rx.State class as a dict.
  606. """
  607. return {
  608. func[0]: func[1]
  609. for func in inspect.getmembers(BaseState, predicate=inspect.isfunction)
  610. if not func[0].startswith("__")
  611. }
  612. def get_token(self) -> str:
  613. """Return the token of the client associated with this state.
  614. Returns:
  615. The token of the client.
  616. """
  617. console.deprecate(
  618. feature_name="get_token",
  619. reason="replaced by `State.router.session.client_token`",
  620. deprecation_version="0.3.0",
  621. removal_version="0.5.0",
  622. )
  623. return self.router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
  624. def get_sid(self) -> str:
  625. """Return the session ID of the client associated with this state.
  626. Returns:
  627. The session ID of the client.
  628. """
  629. console.deprecate(
  630. feature_name="get_sid",
  631. reason="replaced by `State.router.session.session_id`",
  632. deprecation_version="0.3.0",
  633. removal_version="0.5.0",
  634. )
  635. return self.router_data.get(constants.RouteVar.SESSION_ID, "")
  636. def get_headers(self) -> Dict:
  637. """Return the headers of the client associated with this state.
  638. Returns:
  639. The headers of the client.
  640. """
  641. console.deprecate(
  642. feature_name="get_headers",
  643. reason="replaced by `State.router.headers`",
  644. deprecation_version="0.3.0",
  645. removal_version="0.5.0",
  646. )
  647. return self.router_data.get(constants.RouteVar.HEADERS, {})
  648. def get_client_ip(self) -> str:
  649. """Return the IP of the client associated with this state.
  650. Returns:
  651. The IP of the client.
  652. """
  653. console.deprecate(
  654. feature_name="get_client_ip",
  655. reason="replaced by `State.router.session.client_ip`",
  656. deprecation_version="0.3.0",
  657. removal_version="0.5.0",
  658. )
  659. return self.router_data.get(constants.RouteVar.CLIENT_IP, "")
  660. def get_current_page(self, origin=False) -> str:
  661. """Obtain the path of current page from the router data.
  662. Args:
  663. origin: whether to return the base route as shown in browser
  664. Returns:
  665. The current page.
  666. """
  667. console.deprecate(
  668. feature_name="get_current_page",
  669. reason="replaced by State.router.page / self.router.page",
  670. deprecation_version="0.3.0",
  671. removal_version="0.5.0",
  672. )
  673. return self.router.page.raw_path if origin else self.router.page.path
  674. def get_query_params(self) -> dict[str, str]:
  675. """Obtain the query parameters for the queried page.
  676. The query object contains both the URI parameters and the GET parameters.
  677. Returns:
  678. The dict of query parameters.
  679. """
  680. console.deprecate(
  681. feature_name="get_query_params",
  682. reason="replaced by `State.router.page.params`",
  683. deprecation_version="0.3.0",
  684. removal_version="0.5.0",
  685. )
  686. return self.router_data.get(constants.RouteVar.QUERY, {})
  687. def get_cookies(self) -> dict[str, str]:
  688. """Obtain the cookies of the client stored in the browser.
  689. Returns:
  690. The dict of cookies.
  691. """
  692. console.deprecate(
  693. feature_name=f"rx.get_cookies",
  694. reason="and has been replaced by rx.Cookie, which can be used as a state var",
  695. deprecation_version="0.3.0",
  696. removal_version="0.5.0",
  697. )
  698. cookie_dict = {}
  699. cookies = self.get_headers().get(constants.RouteVar.COOKIE, "").split(";")
  700. cookie_pairs = [cookie.split("=") for cookie in cookies if cookie]
  701. for pair in cookie_pairs:
  702. key, value = pair[0].strip(), urllib.parse.unquote(pair[1].strip())
  703. try:
  704. # cast non-string values to the actual types.
  705. value = json.loads(value)
  706. except json.JSONDecodeError:
  707. pass
  708. finally:
  709. cookie_dict[key] = value
  710. return cookie_dict
  711. @classmethod
  712. def setup_dynamic_args(cls, args: dict[str, str]):
  713. """Set up args for easy access in renderer.
  714. Args:
  715. args: a dict of args
  716. """
  717. def argsingle_factory(param):
  718. @ComputedVar
  719. def inner_func(self) -> str:
  720. return self.router.page.params.get(param, "")
  721. return inner_func
  722. def arglist_factory(param):
  723. @ComputedVar
  724. def inner_func(self) -> List:
  725. return self.router.page.params.get(param, [])
  726. return inner_func
  727. for param, value in args.items():
  728. if value == constants.RouteArgType.SINGLE:
  729. func = argsingle_factory(param)
  730. elif value == constants.RouteArgType.LIST:
  731. func = arglist_factory(param)
  732. else:
  733. continue
  734. # to allow passing as a prop
  735. func._var_name = param
  736. cls.vars[param] = cls.computed_vars[param] = func._var_set_state(cls) # type: ignore
  737. setattr(cls, param, func)
  738. # Reinitialize dependency tracking dicts.
  739. cls._init_var_dependency_dicts()
  740. def __getattribute__(self, name: str) -> Any:
  741. """Get the state var.
  742. If the var is inherited, get the var from the parent state.
  743. Args:
  744. name: The name of the var.
  745. Returns:
  746. The value of the var.
  747. """
  748. # If the state hasn't been initialized yet, return the default value.
  749. if not super().__getattribute__("__dict__"):
  750. return super().__getattribute__(name)
  751. inherited_vars = {
  752. **super().__getattribute__("inherited_vars"),
  753. **super().__getattribute__("inherited_backend_vars"),
  754. }
  755. if name in inherited_vars:
  756. return getattr(super().__getattribute__("parent_state"), name)
  757. backend_vars = super().__getattribute__("_backend_vars")
  758. if name in backend_vars:
  759. value = backend_vars[name]
  760. else:
  761. value = super().__getattribute__(name)
  762. if isinstance(value, MutableProxy.__mutable_types__) and (
  763. name in super().__getattribute__("base_vars") or name in backend_vars
  764. ):
  765. # track changes in mutable containers (list, dict, set, etc)
  766. return MutableProxy(wrapped=value, state=self, field_name=name)
  767. return value
  768. def __setattr__(self, name: str, value: Any):
  769. """Set the attribute.
  770. If the attribute is inherited, set the attribute on the parent state.
  771. Args:
  772. name: The name of the attribute.
  773. value: The value of the attribute.
  774. """
  775. if isinstance(value, MutableProxy):
  776. # unwrap proxy objects when assigning back to the state
  777. value = value.__wrapped__
  778. # Set the var on the parent state.
  779. inherited_vars = {**self.inherited_vars, **self.inherited_backend_vars}
  780. if name in inherited_vars:
  781. setattr(self.parent_state, name, value)
  782. return
  783. if (
  784. types.is_backend_variable(name, self.__class__)
  785. and name not in RESERVED_BACKEND_VAR_NAMES
  786. ):
  787. self._backend_vars.__setitem__(name, value)
  788. self.dirty_vars.add(name)
  789. self._mark_dirty()
  790. return
  791. # Set the attribute.
  792. super().__setattr__(name, value)
  793. # Add the var to the dirty list.
  794. if name in self.vars or name in self._computed_var_dependencies:
  795. self.dirty_vars.add(name)
  796. self._mark_dirty()
  797. # For now, handle router_data updates as a special case
  798. if name == constants.ROUTER_DATA:
  799. self.dirty_vars.add(name)
  800. self._mark_dirty()
  801. # propagate router_data updates down the state tree
  802. for substate in self.substates.values():
  803. setattr(substate, name, value)
  804. def reset(self):
  805. """Reset all the base vars to their default values."""
  806. # Reset the base vars.
  807. fields = self.get_fields()
  808. for prop_name in self.base_vars:
  809. if prop_name == constants.ROUTER:
  810. continue # never reset the router data
  811. setattr(self, prop_name, copy.deepcopy(fields[prop_name].default))
  812. # Recursively reset the substates.
  813. for substate in self.substates.values():
  814. substate.reset()
  815. def _reset_client_storage(self):
  816. """Reset client storage base vars to their default values."""
  817. # Client-side storage is reset during hydrate so that clearing cookies
  818. # on the browser also resets the values on the backend.
  819. fields = self.get_fields()
  820. for prop_name in self.base_vars:
  821. field = fields[prop_name]
  822. if isinstance(field.default, ClientStorageBase) or (
  823. isinstance(field.type_, type)
  824. and issubclass(field.type_, ClientStorageBase)
  825. ):
  826. setattr(self, prop_name, copy.deepcopy(field.default))
  827. # Recursively reset the substate client storage.
  828. for substate in self.substates.values():
  829. substate._reset_client_storage()
  830. def get_substate(self, path: Sequence[str]) -> BaseState | None:
  831. """Get the substate.
  832. Args:
  833. path: The path to the substate.
  834. Returns:
  835. The substate.
  836. Raises:
  837. ValueError: If the substate is not found.
  838. """
  839. if len(path) == 0:
  840. return self
  841. if path[0] == self.get_name():
  842. if len(path) == 1:
  843. return self
  844. path = path[1:]
  845. if path[0] not in self.substates:
  846. raise ValueError(f"Invalid path: {path}")
  847. return self.substates[path[0]].get_substate(path[1:])
  848. def _get_event_handler(
  849. self, event: Event
  850. ) -> tuple[BaseState | StateProxy, EventHandler]:
  851. """Get the event handler for the given event.
  852. Args:
  853. event: The event to get the handler for.
  854. Returns:
  855. The event handler.
  856. Raises:
  857. ValueError: If the event handler or substate is not found.
  858. """
  859. # Get the event handler.
  860. path = event.name.split(".")
  861. path, name = path[:-1], path[-1]
  862. substate = self.get_substate(path)
  863. if not substate:
  864. raise ValueError(
  865. "The value of state cannot be None when processing an event."
  866. )
  867. handler = substate.event_handlers[name]
  868. # For background tasks, proxy the state
  869. if handler.is_background:
  870. substate = StateProxy(substate)
  871. return substate, handler
  872. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  873. """Obtain event info and process event.
  874. Args:
  875. event: The event to process.
  876. Yields:
  877. The state update after processing the event.
  878. """
  879. # Get the event handler.
  880. substate, handler = self._get_event_handler(event)
  881. # Run the event generator and yield state updates.
  882. async for update in self._process_event(
  883. handler=handler,
  884. state=substate,
  885. payload=event.payload,
  886. ):
  887. yield update
  888. def _check_valid(self, handler: EventHandler, events: Any) -> Any:
  889. """Check if the events yielded are valid. They must be EventHandlers or EventSpecs.
  890. Args:
  891. handler: EventHandler.
  892. events: The events to be checked.
  893. Raises:
  894. TypeError: If any of the events are not valid.
  895. Returns:
  896. The events as they are if valid.
  897. """
  898. def _is_valid_type(events: Any) -> bool:
  899. return isinstance(events, (Event, EventHandler, EventSpec))
  900. if events is None or _is_valid_type(events):
  901. return events
  902. try:
  903. if all(_is_valid_type(e) for e in events):
  904. return events
  905. except TypeError:
  906. pass
  907. raise TypeError(
  908. f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`)"
  909. )
  910. def _as_state_update(
  911. self,
  912. handler: EventHandler,
  913. events: EventSpec | list[EventSpec] | None,
  914. final: bool,
  915. ) -> StateUpdate:
  916. """Convert the events to a StateUpdate.
  917. Fixes the events and checks for validity before converting.
  918. Args:
  919. handler: The handler where the events originated from.
  920. events: The events to queue with the update.
  921. final: Whether the handler is done processing.
  922. Returns:
  923. The valid StateUpdate containing the events and final flag.
  924. """
  925. # get the delta from the root of the state tree
  926. state = self
  927. while state.parent_state is not None:
  928. state = state.parent_state
  929. token = self.router.session.client_token
  930. # Convert valid EventHandler and EventSpec into Event
  931. fixed_events = fix_events(self._check_valid(handler, events), token)
  932. # Get the delta after processing the event.
  933. delta = state.get_delta()
  934. state._clean()
  935. return StateUpdate(
  936. delta=delta,
  937. events=fixed_events,
  938. final=final if not handler.is_background else True,
  939. )
  940. async def _process_event(
  941. self, handler: EventHandler, state: BaseState | StateProxy, payload: Dict
  942. ) -> AsyncIterator[StateUpdate]:
  943. """Process event.
  944. Args:
  945. handler: EventHandler to process.
  946. state: State to process the handler.
  947. payload: The event payload.
  948. Yields:
  949. StateUpdate object
  950. """
  951. # Get the function to process the event.
  952. fn = functools.partial(handler.fn, state)
  953. # Wrap the function in a try/except block.
  954. try:
  955. # Handle async functions.
  956. if asyncio.iscoroutinefunction(fn.func):
  957. events = await fn(**payload)
  958. # Handle regular functions.
  959. else:
  960. events = fn(**payload)
  961. # Handle async generators.
  962. if inspect.isasyncgen(events):
  963. async for event in events:
  964. yield state._as_state_update(handler, event, final=False)
  965. yield state._as_state_update(handler, events=None, final=True)
  966. # Handle regular generators.
  967. elif inspect.isgenerator(events):
  968. try:
  969. while True:
  970. yield state._as_state_update(handler, next(events), final=False)
  971. except StopIteration as si:
  972. # the "return" value of the generator is not available
  973. # in the loop, we must catch StopIteration to access it
  974. if si.value is not None:
  975. yield state._as_state_update(handler, si.value, final=False)
  976. yield state._as_state_update(handler, events=None, final=True)
  977. # Handle regular event chains.
  978. else:
  979. yield state._as_state_update(handler, events, final=True)
  980. # If an error occurs, throw a window alert.
  981. except Exception:
  982. error = traceback.format_exc()
  983. print(error)
  984. yield state._as_state_update(
  985. handler,
  986. window_alert("An error occurred. See logs for details."),
  987. final=True,
  988. )
  989. def _mark_dirty_computed_vars(self) -> None:
  990. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  991. dirty_vars = self.dirty_vars
  992. while dirty_vars:
  993. calc_vars, dirty_vars = dirty_vars, set()
  994. for cvar in self._dirty_computed_vars(from_vars=calc_vars):
  995. self.dirty_vars.add(cvar)
  996. dirty_vars.add(cvar)
  997. actual_var = self.computed_vars.get(cvar)
  998. if actual_var is not None:
  999. actual_var.mark_dirty(instance=self)
  1000. def _dirty_computed_vars(self, from_vars: set[str] | None = None) -> set[str]:
  1001. """Determine ComputedVars that need to be recalculated based on the given vars.
  1002. Args:
  1003. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  1004. Returns:
  1005. Set of computed vars to include in the delta.
  1006. """
  1007. return set(
  1008. cvar
  1009. for dirty_var in from_vars or self.dirty_vars
  1010. for cvar in self._computed_var_dependencies[dirty_var]
  1011. )
  1012. def get_delta(self) -> Delta:
  1013. """Get the delta for the state.
  1014. Returns:
  1015. The delta for the state.
  1016. """
  1017. delta = {}
  1018. # Apply dirty variables down into substates
  1019. self.dirty_vars.update(self._always_dirty_computed_vars)
  1020. self._mark_dirty()
  1021. # Return the dirty vars for this instance, any cached/dependent computed vars,
  1022. # and always dirty computed vars (cache=False)
  1023. delta_vars = (
  1024. self.dirty_vars.intersection(self.base_vars)
  1025. .union(self._dirty_computed_vars())
  1026. .union(self._always_dirty_computed_vars)
  1027. )
  1028. subdelta = {
  1029. prop: getattr(self, prop)
  1030. for prop in delta_vars
  1031. if not types.is_backend_variable(prop, self.__class__)
  1032. }
  1033. if len(subdelta) > 0:
  1034. delta[self.get_full_name()] = subdelta
  1035. # Recursively find the substate deltas.
  1036. substates = self.substates
  1037. for substate in self.dirty_substates.union(self._always_dirty_substates):
  1038. delta.update(substates[substate].get_delta())
  1039. # Format the delta.
  1040. delta = format.format_state(delta)
  1041. # Return the delta.
  1042. return delta
  1043. def _mark_dirty(self):
  1044. """Mark the substate and all parent states as dirty."""
  1045. state_name = self.get_name()
  1046. if (
  1047. self.parent_state is not None
  1048. and state_name not in self.parent_state.dirty_substates
  1049. ):
  1050. self.parent_state.dirty_substates.add(self.get_name())
  1051. self.parent_state._mark_dirty()
  1052. # have to mark computed vars dirty to allow access to newly computed
  1053. # values within the same ComputedVar function
  1054. self._mark_dirty_computed_vars()
  1055. # Propagate dirty var / computed var status into substates
  1056. substates = self.substates
  1057. for var in self.dirty_vars:
  1058. for substate_name in self._substate_var_dependencies[var]:
  1059. self.dirty_substates.add(substate_name)
  1060. substate = substates[substate_name]
  1061. substate.dirty_vars.add(var)
  1062. substate._mark_dirty()
  1063. def _clean(self):
  1064. """Reset the dirty vars."""
  1065. # Recursively clean the substates.
  1066. for substate in self.dirty_substates:
  1067. self.substates[substate]._clean()
  1068. # Clean this state.
  1069. self.dirty_vars = set()
  1070. self.dirty_substates = set()
  1071. def get_value(self, key: str) -> Any:
  1072. """Get the value of a field (without proxying).
  1073. The returned value will NOT track dirty state updates.
  1074. Args:
  1075. key: The key of the field.
  1076. Returns:
  1077. The value of the field.
  1078. """
  1079. if isinstance(key, MutableProxy):
  1080. return super().get_value(key.__wrapped__)
  1081. return super().get_value(key)
  1082. def dict(self, include_computed: bool = True, **kwargs) -> dict[str, Any]:
  1083. """Convert the object to a dictionary.
  1084. Args:
  1085. include_computed: Whether to include computed vars.
  1086. **kwargs: Kwargs to pass to the pydantic dict method.
  1087. Returns:
  1088. The object as a dictionary.
  1089. """
  1090. if include_computed:
  1091. # Apply dirty variables down into substates to allow never-cached ComputedVar to
  1092. # trigger recalculation of dependent vars
  1093. self.dirty_vars.update(self._always_dirty_computed_vars)
  1094. self._mark_dirty()
  1095. base_vars = {
  1096. prop_name: self.get_value(getattr(self, prop_name))
  1097. for prop_name in self.base_vars
  1098. }
  1099. computed_vars = (
  1100. {
  1101. # Include the computed vars.
  1102. prop_name: self.get_value(getattr(self, prop_name))
  1103. for prop_name in self.computed_vars
  1104. }
  1105. if include_computed
  1106. else {}
  1107. )
  1108. variables = {**base_vars, **computed_vars}
  1109. d = {
  1110. self.get_full_name(): {k: variables[k] for k in sorted(variables)},
  1111. }
  1112. for substate_d in [
  1113. v.dict(include_computed=include_computed, **kwargs)
  1114. for v in self.substates.values()
  1115. ]:
  1116. d.update(substate_d)
  1117. return d
  1118. async def __aenter__(self) -> BaseState:
  1119. """Enter the async context manager protocol.
  1120. This should not be used for the State class, but exists for
  1121. type-compatibility with StateProxy.
  1122. Raises:
  1123. TypeError: always, because async contextmanager protocol is only supported for background task.
  1124. """
  1125. raise TypeError(
  1126. "Only background task should use `async with self` to modify state."
  1127. )
  1128. async def __aexit__(self, *exc_info: Any) -> None:
  1129. """Exit the async context manager protocol.
  1130. This should not be used for the State class, but exists for
  1131. type-compatibility with StateProxy.
  1132. Args:
  1133. exc_info: The exception info tuple.
  1134. """
  1135. pass
  1136. class State(BaseState):
  1137. """The app Base State."""
  1138. # The hydrated bool.
  1139. is_hydrated: bool = False
  1140. def on_load_internal(self) -> list[Event | EventSpec] | None:
  1141. """Queue on_load handlers for the current page.
  1142. Returns:
  1143. The list of events to queue for on load handling.
  1144. """
  1145. # Do not app.compile_()! It should be already compiled by now.
  1146. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1147. load_events = app.get_load_events(self.router.page.path)
  1148. if not load_events and self.is_hydrated:
  1149. return # Fast path for page-to-page navigation
  1150. self.is_hydrated = False
  1151. return [
  1152. *fix_events(
  1153. load_events,
  1154. self.router.session.client_token,
  1155. router_data=self.router_data,
  1156. ),
  1157. type(self).set_is_hydrated(True), # type: ignore
  1158. ]
  1159. def update_vars_internal(self, vars: dict[str, Any]) -> None:
  1160. """Apply updates to fully qualified state vars.
  1161. The keys in `vars` should be in the form of `{state.get_full_name()}.{var_name}`,
  1162. and each value will be set on the appropriate substate instance.
  1163. This function is primarily used to apply cookie and local storage
  1164. updates from the frontend to the appropriate substate.
  1165. Args:
  1166. vars: The fully qualified vars and values to update.
  1167. """
  1168. for var, value in vars.items():
  1169. state_name, _, var_name = var.rpartition(".")
  1170. var_state = self.get_substate(state_name.split("."))
  1171. setattr(var_state, var_name, value)
  1172. class StateProxy(wrapt.ObjectProxy):
  1173. """Proxy of a state instance to control mutability of vars for a background task.
  1174. Since a background task runs against a state instance without holding the
  1175. state_manager lock for the token, the reference may become stale if the same
  1176. state is modified by another event handler.
  1177. The proxy object ensures that writes to the state are blocked unless
  1178. explicitly entering a context which refreshes the state from state_manager
  1179. and holds the lock for the token until exiting the context. After exiting
  1180. the context, a StateUpdate may be emitted to the frontend to notify the
  1181. client of the state change.
  1182. A background task will be passed the `StateProxy` as `self`, so mutability
  1183. can be safely performed inside an `async with self` block.
  1184. class State(rx.State):
  1185. counter: int = 0
  1186. @rx.background
  1187. async def bg_increment(self):
  1188. await asyncio.sleep(1)
  1189. async with self:
  1190. self.counter += 1
  1191. """
  1192. def __init__(self, state_instance):
  1193. """Create a proxy for a state instance.
  1194. Args:
  1195. state_instance: The state instance to proxy.
  1196. """
  1197. super().__init__(state_instance)
  1198. # compile is not relevant to backend logic
  1199. self._self_app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1200. self._self_substate_path = state_instance.get_full_name().split(".")
  1201. self._self_actx = None
  1202. self._self_mutable = False
  1203. async def __aenter__(self) -> StateProxy:
  1204. """Enter the async context manager protocol.
  1205. Sets mutability to True and enters the `App.modify_state` async context,
  1206. which refreshes the state from state_manager and holds the lock for the
  1207. given state token until exiting the context.
  1208. Background tasks should avoid blocking calls while inside the context.
  1209. Returns:
  1210. This StateProxy instance in mutable mode.
  1211. """
  1212. self._self_actx = self._self_app.modify_state(
  1213. self.__wrapped__.router.session.client_token
  1214. )
  1215. mutable_state = await self._self_actx.__aenter__()
  1216. super().__setattr__(
  1217. "__wrapped__", mutable_state.get_substate(self._self_substate_path)
  1218. )
  1219. self._self_mutable = True
  1220. return self
  1221. async def __aexit__(self, *exc_info: Any) -> None:
  1222. """Exit the async context manager protocol.
  1223. Sets proxy mutability to False and persists any state changes.
  1224. Args:
  1225. exc_info: The exception info tuple.
  1226. """
  1227. if self._self_actx is None:
  1228. return
  1229. self._self_mutable = False
  1230. await self._self_actx.__aexit__(*exc_info)
  1231. self._self_actx = None
  1232. def __enter__(self):
  1233. """Enter the regular context manager protocol.
  1234. This is not supported for background tasks, and exists only to raise a more useful exception
  1235. when the StateProxy is used incorrectly.
  1236. Raises:
  1237. TypeError: always, because only async contextmanager protocol is supported.
  1238. """
  1239. raise TypeError("Background task must use `async with self` to modify state.")
  1240. def __exit__(self, *exc_info: Any) -> None:
  1241. """Exit the regular context manager protocol.
  1242. Args:
  1243. exc_info: The exception info tuple.
  1244. """
  1245. pass
  1246. def __getattr__(self, name: str) -> Any:
  1247. """Get the attribute from the underlying state instance.
  1248. Args:
  1249. name: The name of the attribute.
  1250. Returns:
  1251. The value of the attribute.
  1252. """
  1253. value = super().__getattr__(name)
  1254. if not name.startswith("_self_") and isinstance(value, MutableProxy):
  1255. # ensure mutations to these containers are blocked unless proxy is _mutable
  1256. return ImmutableMutableProxy(
  1257. wrapped=value.__wrapped__,
  1258. state=self, # type: ignore
  1259. field_name=value._self_field_name,
  1260. )
  1261. if isinstance(value, functools.partial) and value.args[0] is self.__wrapped__:
  1262. # Rebind event handler to the proxy instance
  1263. value = functools.partial(
  1264. value.func,
  1265. self,
  1266. *value.args[1:],
  1267. **value.keywords,
  1268. )
  1269. if isinstance(value, MethodType) and value.__self__ is self.__wrapped__:
  1270. # Rebind methods to the proxy instance
  1271. value = type(value)(value.__func__, self) # type: ignore
  1272. return value
  1273. def __setattr__(self, name: str, value: Any) -> None:
  1274. """Set the attribute on the underlying state instance.
  1275. If the attribute is internal, set it on the proxy instance instead.
  1276. Args:
  1277. name: The name of the attribute.
  1278. value: The value of the attribute.
  1279. Raises:
  1280. ImmutableStateError: If the state is not in mutable mode.
  1281. """
  1282. if (
  1283. name.startswith("_self_") # wrapper attribute
  1284. or self._self_mutable # lock held
  1285. # non-persisted state attribute
  1286. or name in self.__wrapped__.get_skip_vars()
  1287. ):
  1288. super().__setattr__(name, value)
  1289. return
  1290. raise ImmutableStateError(
  1291. "Background task StateProxy is immutable outside of a context "
  1292. "manager. Use `async with self` to modify state."
  1293. )
  1294. class StateUpdate(Base):
  1295. """A state update sent to the frontend."""
  1296. # The state delta.
  1297. delta: Delta = {}
  1298. # Events to be added to the event queue.
  1299. events: List[Event] = []
  1300. # Whether this is the final state update for the event.
  1301. final: bool = True
  1302. class StateManager(Base, ABC):
  1303. """A class to manage many client states."""
  1304. # The state class to use.
  1305. state: Type[BaseState]
  1306. @classmethod
  1307. def create(cls, state: Type[BaseState]):
  1308. """Create a new state manager.
  1309. Args:
  1310. state: The state class to use.
  1311. Returns:
  1312. The state manager (either memory or redis).
  1313. """
  1314. redis = prerequisites.get_redis()
  1315. if redis is not None:
  1316. return StateManagerRedis(state=state, redis=redis)
  1317. return StateManagerMemory(state=state)
  1318. @abstractmethod
  1319. async def get_state(self, token: str) -> BaseState:
  1320. """Get the state for a token.
  1321. Args:
  1322. token: The token to get the state for.
  1323. Returns:
  1324. The state for the token.
  1325. """
  1326. pass
  1327. @abstractmethod
  1328. async def set_state(self, token: str, state: BaseState):
  1329. """Set the state for a token.
  1330. Args:
  1331. token: The token to set the state for.
  1332. state: The state to set.
  1333. """
  1334. pass
  1335. @abstractmethod
  1336. @contextlib.asynccontextmanager
  1337. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1338. """Modify the state for a token while holding exclusive lock.
  1339. Args:
  1340. token: The token to modify the state for.
  1341. Yields:
  1342. The state for the token.
  1343. """
  1344. yield self.state()
  1345. class StateManagerMemory(StateManager):
  1346. """A state manager that stores states in memory."""
  1347. # The mapping of client ids to states.
  1348. states: Dict[str, BaseState] = {}
  1349. # The mutex ensures the dict of mutexes is updated exclusively
  1350. _state_manager_lock = asyncio.Lock()
  1351. # The dict of mutexes for each client
  1352. _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({})
  1353. class Config:
  1354. """The Pydantic config."""
  1355. fields = {
  1356. "_states_locks": {"exclude": True},
  1357. }
  1358. async def get_state(self, token: str) -> BaseState:
  1359. """Get the state for a token.
  1360. Args:
  1361. token: The token to get the state for.
  1362. Returns:
  1363. The state for the token.
  1364. """
  1365. if token not in self.states:
  1366. self.states[token] = self.state()
  1367. return self.states[token]
  1368. async def set_state(self, token: str, state: BaseState):
  1369. """Set the state for a token.
  1370. Args:
  1371. token: The token to set the state for.
  1372. state: The state to set.
  1373. """
  1374. pass
  1375. @contextlib.asynccontextmanager
  1376. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1377. """Modify the state for a token while holding exclusive lock.
  1378. Args:
  1379. token: The token to modify the state for.
  1380. Yields:
  1381. The state for the token.
  1382. """
  1383. if token not in self._states_locks:
  1384. async with self._state_manager_lock:
  1385. if token not in self._states_locks:
  1386. self._states_locks[token] = asyncio.Lock()
  1387. async with self._states_locks[token]:
  1388. state = await self.get_state(token)
  1389. yield state
  1390. await self.set_state(token, state)
  1391. class StateManagerRedis(StateManager):
  1392. """A state manager that stores states in redis."""
  1393. # The redis client to use.
  1394. redis: Redis
  1395. # The token expiration time (s).
  1396. token_expiration: int = constants.Expiration.TOKEN
  1397. # The maximum time to hold a lock (ms).
  1398. lock_expiration: int = constants.Expiration.LOCK
  1399. # The keyspace subscription string when redis is waiting for lock to be released
  1400. _redis_notify_keyspace_events: str = (
  1401. "K" # Enable keyspace notifications (target a particular key)
  1402. "g" # For generic commands (DEL, EXPIRE, etc)
  1403. "x" # For expired events
  1404. "e" # For evicted events (i.e. maxmemory exceeded)
  1405. )
  1406. # These events indicate that a lock is no longer held
  1407. _redis_keyspace_lock_release_events: Set[bytes] = {
  1408. b"del",
  1409. b"expire",
  1410. b"expired",
  1411. b"evicted",
  1412. }
  1413. async def get_state(self, token: str) -> BaseState:
  1414. """Get the state for a token.
  1415. Args:
  1416. token: The token to get the state for.
  1417. Returns:
  1418. The state for the token.
  1419. """
  1420. redis_state = await self.redis.get(token)
  1421. if redis_state is None:
  1422. await self.set_state(token, self.state())
  1423. return await self.get_state(token)
  1424. return cloudpickle.loads(redis_state)
  1425. async def set_state(
  1426. self, token: str, state: BaseState, lock_id: bytes | None = None
  1427. ):
  1428. """Set the state for a token.
  1429. Args:
  1430. token: The token to set the state for.
  1431. state: The state to set.
  1432. lock_id: If provided, the lock_key must be set to this value to set the state.
  1433. Raises:
  1434. LockExpiredError: If lock_id is provided and the lock for the token is not held by that ID.
  1435. """
  1436. # check that we're holding the lock
  1437. if (
  1438. lock_id is not None
  1439. and await self.redis.get(self._lock_key(token)) != lock_id
  1440. ):
  1441. raise LockExpiredError(
  1442. f"Lock expired for token {token} while processing. Consider increasing "
  1443. f"`app.state_manager.lock_expiration` (currently {self.lock_expiration}) "
  1444. "or use `@rx.background` decorator for long-running tasks."
  1445. )
  1446. await self.redis.set(token, cloudpickle.dumps(state), ex=self.token_expiration)
  1447. @contextlib.asynccontextmanager
  1448. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1449. """Modify the state for a token while holding exclusive lock.
  1450. Args:
  1451. token: The token to modify the state for.
  1452. Yields:
  1453. The state for the token.
  1454. """
  1455. async with self._lock(token) as lock_id:
  1456. state = await self.get_state(token)
  1457. yield state
  1458. await self.set_state(token, state, lock_id)
  1459. @staticmethod
  1460. def _lock_key(token: str) -> bytes:
  1461. """Get the redis key for a token's lock.
  1462. Args:
  1463. token: The token to get the lock key for.
  1464. Returns:
  1465. The redis lock key for the token.
  1466. """
  1467. return f"{token}_lock".encode()
  1468. async def _try_get_lock(self, lock_key: bytes, lock_id: bytes) -> bool | None:
  1469. """Try to get a redis lock for a token.
  1470. Args:
  1471. lock_key: The redis key for the lock.
  1472. lock_id: The ID of the lock.
  1473. Returns:
  1474. True if the lock was obtained.
  1475. """
  1476. return await self.redis.set(
  1477. lock_key,
  1478. lock_id,
  1479. px=self.lock_expiration,
  1480. nx=True, # only set if it doesn't exist
  1481. )
  1482. async def _wait_lock(self, lock_key: bytes, lock_id: bytes) -> None:
  1483. """Wait for a redis lock to be released via pubsub.
  1484. Coroutine will not return until the lock is obtained.
  1485. Args:
  1486. lock_key: The redis key for the lock.
  1487. lock_id: The ID of the lock.
  1488. """
  1489. state_is_locked = False
  1490. lock_key_channel = f"__keyspace@0__:{lock_key.decode()}"
  1491. # Enable keyspace notifications for the lock key, so we know when it is available.
  1492. await self.redis.config_set(
  1493. "notify-keyspace-events", self._redis_notify_keyspace_events
  1494. )
  1495. async with self.redis.pubsub() as pubsub:
  1496. await pubsub.psubscribe(lock_key_channel)
  1497. while not state_is_locked:
  1498. # wait for the lock to be released
  1499. while True:
  1500. if not await self.redis.exists(lock_key):
  1501. break # key was removed, try to get the lock again
  1502. message = await pubsub.get_message(
  1503. ignore_subscribe_messages=True,
  1504. timeout=self.lock_expiration / 1000.0,
  1505. )
  1506. if message is None:
  1507. continue
  1508. if message["data"] in self._redis_keyspace_lock_release_events:
  1509. break
  1510. state_is_locked = await self._try_get_lock(lock_key, lock_id)
  1511. @contextlib.asynccontextmanager
  1512. async def _lock(self, token: str):
  1513. """Obtain a redis lock for a token.
  1514. Args:
  1515. token: The token to obtain a lock for.
  1516. Yields:
  1517. The ID of the lock (to be passed to set_state).
  1518. Raises:
  1519. LockExpiredError: If the lock has expired while processing the event.
  1520. """
  1521. lock_key = self._lock_key(token)
  1522. lock_id = uuid.uuid4().hex.encode()
  1523. if not await self._try_get_lock(lock_key, lock_id):
  1524. # Missed the fast-path to get lock, subscribe for lock delete/expire events
  1525. await self._wait_lock(lock_key, lock_id)
  1526. state_is_locked = True
  1527. try:
  1528. yield lock_id
  1529. except LockExpiredError:
  1530. state_is_locked = False
  1531. raise
  1532. finally:
  1533. if state_is_locked:
  1534. # only delete our lock
  1535. await self.redis.delete(lock_key)
  1536. async def close(self):
  1537. """Explicitly close the redis connection and connection_pool.
  1538. It is necessary in testing scenarios to close between asyncio test cases
  1539. to avoid having lingering redis connections associated with event loops
  1540. that will be closed (each test case uses its own event loop).
  1541. Note: Connections will be automatically reopened when needed.
  1542. """
  1543. await self.redis.close(close_connection_pool=True)
  1544. class ClientStorageBase:
  1545. """Base class for client-side storage."""
  1546. def options(self) -> dict[str, Any]:
  1547. """Get the options for the storage.
  1548. Returns:
  1549. All set options for the storage (not None).
  1550. """
  1551. return {
  1552. format.to_camel_case(k): v for k, v in vars(self).items() if v is not None
  1553. }
  1554. class Cookie(ClientStorageBase, str):
  1555. """Represents a state Var that is stored as a cookie in the browser."""
  1556. name: str | None
  1557. path: str
  1558. max_age: int | None
  1559. domain: str | None
  1560. secure: bool | None
  1561. same_site: str
  1562. def __new__(
  1563. cls,
  1564. object: Any = "",
  1565. encoding: str | None = None,
  1566. errors: str | None = None,
  1567. /,
  1568. name: str | None = None,
  1569. path: str = "/",
  1570. max_age: int | None = None,
  1571. domain: str | None = None,
  1572. secure: bool | None = None,
  1573. same_site: str = "lax",
  1574. ):
  1575. """Create a client-side Cookie (str).
  1576. Args:
  1577. object: The initial object.
  1578. encoding: The encoding to use.
  1579. errors: The error handling scheme to use.
  1580. name: The name of the cookie on the client side.
  1581. path: Cookie path. Use / as the path if the cookie should be accessible on all pages.
  1582. max_age: Relative max age of the cookie in seconds from when the client receives it.
  1583. domain: Domain for the cookie (sub.domain.com or .allsubdomains.com).
  1584. secure: Is the cookie only accessible through HTTPS?
  1585. same_site: Whether the cookie is sent with third party requests.
  1586. One of (true|false|none|lax|strict)
  1587. Returns:
  1588. The client-side Cookie object.
  1589. Note: expires (absolute Date) is not supported at this time.
  1590. """
  1591. if encoding or errors:
  1592. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  1593. else:
  1594. inst = super().__new__(cls, object)
  1595. inst.name = name
  1596. inst.path = path
  1597. inst.max_age = max_age
  1598. inst.domain = domain
  1599. inst.secure = secure
  1600. inst.same_site = same_site
  1601. return inst
  1602. class LocalStorage(ClientStorageBase, str):
  1603. """Represents a state Var that is stored in localStorage in the browser."""
  1604. name: str | None
  1605. sync: bool = False
  1606. def __new__(
  1607. cls,
  1608. object: Any = "",
  1609. encoding: str | None = None,
  1610. errors: str | None = None,
  1611. /,
  1612. name: str | None = None,
  1613. sync: bool = False,
  1614. ) -> "LocalStorage":
  1615. """Create a client-side localStorage (str).
  1616. Args:
  1617. object: The initial object.
  1618. encoding: The encoding to use.
  1619. errors: The error handling scheme to use.
  1620. name: The name of the storage key on the client side.
  1621. sync: Whether changes should be propagated to other tabs.
  1622. Returns:
  1623. The client-side localStorage object.
  1624. """
  1625. if encoding or errors:
  1626. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  1627. else:
  1628. inst = super().__new__(cls, object)
  1629. inst.name = name
  1630. inst.sync = sync
  1631. return inst
  1632. class MutableProxy(wrapt.ObjectProxy):
  1633. """A proxy for a mutable object that tracks changes."""
  1634. # Methods on wrapped objects which should mark the state as dirty.
  1635. __mark_dirty_attrs__ = set(
  1636. [
  1637. "add",
  1638. "append",
  1639. "clear",
  1640. "difference_update",
  1641. "discard",
  1642. "extend",
  1643. "insert",
  1644. "intersection_update",
  1645. "pop",
  1646. "popitem",
  1647. "remove",
  1648. "reverse",
  1649. "setdefault",
  1650. "sort",
  1651. "symmetric_difference_update",
  1652. "update",
  1653. ]
  1654. )
  1655. # Methods on wrapped objects might return mutable objects that should be tracked.
  1656. __wrap_mutable_attrs__ = set(
  1657. [
  1658. "get",
  1659. "setdefault",
  1660. ]
  1661. )
  1662. __mutable_types__ = (list, dict, set, Base)
  1663. def __init__(self, wrapped: Any, state: BaseState, field_name: str):
  1664. """Create a proxy for a mutable object that tracks changes.
  1665. Args:
  1666. wrapped: The object to proxy.
  1667. state: The state to mark dirty when the object is changed.
  1668. field_name: The name of the field on the state associated with the
  1669. wrapped object.
  1670. """
  1671. super().__init__(wrapped)
  1672. self._self_state = state
  1673. self._self_field_name = field_name
  1674. def _mark_dirty(
  1675. self,
  1676. wrapped=None,
  1677. instance=None,
  1678. args=tuple(),
  1679. kwargs=None,
  1680. ) -> Any:
  1681. """Mark the state as dirty, then call a wrapped function.
  1682. Intended for use with `FunctionWrapper` from the `wrapt` library.
  1683. Args:
  1684. wrapped: The wrapped function.
  1685. instance: The instance of the wrapped function.
  1686. args: The args for the wrapped function.
  1687. kwargs: The kwargs for the wrapped function.
  1688. Returns:
  1689. The result of the wrapped function.
  1690. """
  1691. self._self_state.dirty_vars.add(self._self_field_name)
  1692. self._self_state._mark_dirty()
  1693. if wrapped is not None:
  1694. return wrapped(*args, **(kwargs or {}))
  1695. def _wrap_recursive(self, value: Any) -> Any:
  1696. """Wrap a value recursively if it is mutable.
  1697. Args:
  1698. value: The value to wrap.
  1699. Returns:
  1700. The wrapped value.
  1701. """
  1702. if isinstance(value, self.__mutable_types__):
  1703. return type(self)(
  1704. wrapped=value,
  1705. state=self._self_state,
  1706. field_name=self._self_field_name,
  1707. )
  1708. return value
  1709. def _wrap_recursive_decorator(self, wrapped, instance, args, kwargs) -> Any:
  1710. """Wrap a function that returns a possibly mutable value.
  1711. Intended for use with `FunctionWrapper` from the `wrapt` library.
  1712. Args:
  1713. wrapped: The wrapped function.
  1714. instance: The instance of the wrapped function.
  1715. args: The args for the wrapped function.
  1716. kwargs: The kwargs for the wrapped function.
  1717. Returns:
  1718. The result of the wrapped function (possibly wrapped in a MutableProxy).
  1719. """
  1720. return self._wrap_recursive(wrapped(*args, **kwargs))
  1721. def __getattr__(self, __name: str) -> Any:
  1722. """Get the attribute on the proxied object and return a proxy if mutable.
  1723. Args:
  1724. __name: The name of the attribute.
  1725. Returns:
  1726. The attribute value.
  1727. """
  1728. value = super().__getattr__(__name)
  1729. if callable(value):
  1730. if __name in self.__mark_dirty_attrs__:
  1731. # Wrap special callables, like "append", which should mark state dirty.
  1732. value = wrapt.FunctionWrapper(value, self._mark_dirty)
  1733. if __name in self.__wrap_mutable_attrs__:
  1734. # Wrap methods that may return mutable objects tied to the state.
  1735. value = wrapt.FunctionWrapper(
  1736. value,
  1737. self._wrap_recursive_decorator,
  1738. )
  1739. if isinstance(value, self.__mutable_types__) and __name not in (
  1740. "__wrapped__",
  1741. "_self_state",
  1742. ):
  1743. # Recursively wrap mutable attribute values retrieved through this proxy.
  1744. return self._wrap_recursive(value)
  1745. return value
  1746. def __getitem__(self, key) -> Any:
  1747. """Get the item on the proxied object and return a proxy if mutable.
  1748. Args:
  1749. key: The key of the item.
  1750. Returns:
  1751. The item value.
  1752. """
  1753. value = super().__getitem__(key)
  1754. # Recursively wrap mutable items retrieved through this proxy.
  1755. return self._wrap_recursive(value)
  1756. def __iter__(self) -> Any:
  1757. """Iterate over the proxied object and return a proxy if mutable.
  1758. Yields:
  1759. Each item value (possibly wrapped in MutableProxy).
  1760. """
  1761. for value in super().__iter__():
  1762. # Recursively wrap mutable items retrieved through this proxy.
  1763. yield self._wrap_recursive(value)
  1764. def __delattr__(self, name):
  1765. """Delete the attribute on the proxied object and mark state dirty.
  1766. Args:
  1767. name: The name of the attribute.
  1768. """
  1769. self._mark_dirty(super().__delattr__, args=(name,))
  1770. def __delitem__(self, key):
  1771. """Delete the item on the proxied object and mark state dirty.
  1772. Args:
  1773. key: The key of the item.
  1774. """
  1775. self._mark_dirty(super().__delitem__, args=(key,))
  1776. def __setitem__(self, key, value):
  1777. """Set the item on the proxied object and mark state dirty.
  1778. Args:
  1779. key: The key of the item.
  1780. value: The value of the item.
  1781. """
  1782. self._mark_dirty(super().__setitem__, args=(key, value))
  1783. def __setattr__(self, name, value):
  1784. """Set the attribute on the proxied object and mark state dirty.
  1785. If the attribute starts with "_self_", then the state is NOT marked
  1786. dirty as these are internal proxy attributes.
  1787. Args:
  1788. name: The name of the attribute.
  1789. value: The value of the attribute.
  1790. """
  1791. if name.startswith("_self_"):
  1792. # Special case attributes of the proxy itself, not applied to the wrapped object.
  1793. super().__setattr__(name, value)
  1794. return
  1795. self._mark_dirty(super().__setattr__, args=(name, value))
  1796. def __copy__(self) -> Any:
  1797. """Return a copy of the proxy.
  1798. Returns:
  1799. A copy of the wrapped object, unconnected to the proxy.
  1800. """
  1801. return copy.copy(self.__wrapped__)
  1802. def __deepcopy__(self, memo=None) -> Any:
  1803. """Return a deepcopy of the proxy.
  1804. Args:
  1805. memo: The memo dict to use for the deepcopy.
  1806. Returns:
  1807. A deepcopy of the wrapped object, unconnected to the proxy.
  1808. """
  1809. return copy.deepcopy(self.__wrapped__, memo=memo)
  1810. @serializer
  1811. def serialize_mutable_proxy(mp: MutableProxy) -> SerializedType:
  1812. """Serialize the wrapped value of a MutableProxy.
  1813. Args:
  1814. mp: The MutableProxy to serialize.
  1815. Returns:
  1816. The serialized wrapped object.
  1817. Raises:
  1818. ValueError: when the wrapped object is not serializable.
  1819. """
  1820. value = serialize(mp.__wrapped__)
  1821. if value is None:
  1822. raise ValueError(f"Cannot serialize {type(mp.__wrapped__)}")
  1823. return value
  1824. class ImmutableMutableProxy(MutableProxy):
  1825. """A proxy for a mutable object that tracks changes.
  1826. This wrapper comes from StateProxy, and will raise an exception if an attempt is made
  1827. to modify the wrapped object when the StateProxy is immutable.
  1828. """
  1829. def _mark_dirty(
  1830. self,
  1831. wrapped=None,
  1832. instance=None,
  1833. args=tuple(),
  1834. kwargs=None,
  1835. ) -> Any:
  1836. """Raise an exception when an attempt is made to modify the object.
  1837. Intended for use with `FunctionWrapper` from the `wrapt` library.
  1838. Args:
  1839. wrapped: The wrapped function.
  1840. instance: The instance of the wrapped function.
  1841. args: The args for the wrapped function.
  1842. kwargs: The kwargs for the wrapped function.
  1843. Returns:
  1844. The result of the wrapped function.
  1845. Raises:
  1846. ImmutableStateError: if the StateProxy is not mutable.
  1847. """
  1848. if not self._self_state._self_mutable:
  1849. raise ImmutableStateError(
  1850. "Background task StateProxy is immutable outside of a context "
  1851. "manager. Use `async with self` to modify state."
  1852. )
  1853. return super()._mark_dirty(
  1854. wrapped=wrapped, instance=instance, args=args, kwargs=kwargs
  1855. )
  1856. def code_uses_state_contexts(javascript_code: str) -> bool:
  1857. """Check if the rendered Javascript uses state contexts.
  1858. Args:
  1859. javascript_code: The Javascript code to check.
  1860. Returns:
  1861. True if the code attempts to access a member of StateContexts.
  1862. """
  1863. return bool("useContext(StateContexts" in javascript_code)
  1864. class PrivateVarDescriptor:
  1865. """A descriptor to raise error in case private vars is accessed on thr frontend."""
  1866. def __get__(self, *args, **kwargs):
  1867. """Raise error on get value.
  1868. Args:
  1869. *args: The args to pass to the function.
  1870. **kwargs: The kwargs to pass to the function.
  1871. Raises:
  1872. TypeError: if a background variable is used in frontend.
  1873. """
  1874. raise TypeError("Backend Vars cannot be accessed on the frontend.")