state.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883
  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 traceback
  10. import urllib.parse
  11. import uuid
  12. from abc import ABC, abstractmethod
  13. from collections import defaultdict
  14. from types import FunctionType, MethodType
  15. from typing import (
  16. Any,
  17. AsyncIterator,
  18. Callable,
  19. ClassVar,
  20. Dict,
  21. List,
  22. Optional,
  23. Sequence,
  24. Set,
  25. Type,
  26. )
  27. import cloudpickle
  28. import pydantic
  29. import wrapt
  30. from redis.asyncio import Redis
  31. from reflex import constants
  32. from reflex.base import Base
  33. from reflex.event import (
  34. Event,
  35. EventHandler,
  36. EventSpec,
  37. _no_chain_background_task,
  38. fix_events,
  39. window_alert,
  40. )
  41. from reflex.utils import console, format, prerequisites, types
  42. from reflex.utils.exceptions import ImmutableStateError, LockExpiredError
  43. from reflex.utils.exec import is_testing_env
  44. from reflex.utils.serializers import SerializedType, serialize, serializer
  45. from reflex.vars import BaseVar, ComputedVar, Var, computed_var
  46. Delta = Dict[str, Any]
  47. var = computed_var
  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. "_was_touched",
  128. }
  129. def _substate_key(
  130. token: str,
  131. state_cls_or_name: BaseState | Type[BaseState] | str | list[str],
  132. ) -> str:
  133. """Get the substate key.
  134. Args:
  135. token: The token of the state.
  136. state_cls_or_name: The state class/instance or name or sequence of name parts.
  137. Returns:
  138. The substate key.
  139. """
  140. if isinstance(state_cls_or_name, BaseState) or (
  141. isinstance(state_cls_or_name, type) and issubclass(state_cls_or_name, BaseState)
  142. ):
  143. state_cls_or_name = state_cls_or_name.get_full_name()
  144. elif isinstance(state_cls_or_name, (list, tuple)):
  145. state_cls_or_name = ".".join(state_cls_or_name)
  146. return f"{token}_{state_cls_or_name}"
  147. def _split_substate_key(substate_key: str) -> tuple[str, str]:
  148. """Split the substate key into token and state name.
  149. Args:
  150. substate_key: The substate key.
  151. Returns:
  152. Tuple of token and state name.
  153. """
  154. token, _, state_name = substate_key.partition("_")
  155. return token, state_name
  156. class BaseState(Base, ABC, extra=pydantic.Extra.allow):
  157. """The state of the app."""
  158. # A map from the var name to the var.
  159. vars: ClassVar[Dict[str, Var]] = {}
  160. # The base vars of the class.
  161. base_vars: ClassVar[Dict[str, BaseVar]] = {}
  162. # The computed vars of the class.
  163. computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
  164. # Vars inherited by the parent state.
  165. inherited_vars: ClassVar[Dict[str, Var]] = {}
  166. # Backend vars that are never sent to the client.
  167. backend_vars: ClassVar[Dict[str, Any]] = {}
  168. # Backend vars inherited
  169. inherited_backend_vars: ClassVar[Dict[str, Any]] = {}
  170. # The event handlers.
  171. event_handlers: ClassVar[Dict[str, EventHandler]] = {}
  172. # A set of subclassses of this class.
  173. class_subclasses: ClassVar[Set[Type[BaseState]]] = set()
  174. # Mapping of var name to set of computed variables that depend on it
  175. _computed_var_dependencies: ClassVar[Dict[str, Set[str]]] = {}
  176. # Mapping of var name to set of substates that depend on it
  177. _substate_var_dependencies: ClassVar[Dict[str, Set[str]]] = {}
  178. # Set of vars which always need to be recomputed
  179. _always_dirty_computed_vars: ClassVar[Set[str]] = set()
  180. # Set of substates which always need to be recomputed
  181. _always_dirty_substates: ClassVar[Set[str]] = set()
  182. # The parent state.
  183. parent_state: Optional[BaseState] = None
  184. # The substates of the state.
  185. substates: Dict[str, BaseState] = {}
  186. # The set of dirty vars.
  187. dirty_vars: Set[str] = set()
  188. # The set of dirty substates.
  189. dirty_substates: Set[str] = set()
  190. # The routing path that triggered the state
  191. router_data: Dict[str, Any] = {}
  192. # Per-instance copy of backend variable values
  193. _backend_vars: Dict[str, Any] = {}
  194. # The router data for the current page
  195. router: RouterData = RouterData()
  196. # Whether the state has ever been touched since instantiation.
  197. _was_touched: bool = False
  198. def __init__(
  199. self,
  200. *args,
  201. parent_state: BaseState | None = None,
  202. init_substates: bool = True,
  203. _reflex_internal_init: bool = False,
  204. **kwargs,
  205. ):
  206. """Initialize the state.
  207. DO NOT INSTANTIATE STATE CLASSES DIRECTLY! Use StateManager.get_state() instead.
  208. Args:
  209. *args: The args to pass to the Pydantic init method.
  210. parent_state: The parent state.
  211. init_substates: Whether to initialize the substates in this instance.
  212. _reflex_internal_init: A flag to indicate that the state is being initialized by the framework.
  213. **kwargs: The kwargs to pass to the Pydantic init method.
  214. Raises:
  215. RuntimeError: If the state is instantiated directly by end user.
  216. """
  217. if not _reflex_internal_init and not is_testing_env():
  218. raise RuntimeError(
  219. "State classes should not be instantiated directly in a Reflex app. "
  220. "See https://reflex.dev/docs/state for further information."
  221. )
  222. kwargs["parent_state"] = parent_state
  223. super().__init__(*args, **kwargs)
  224. # Setup the substates (for memory state manager only).
  225. if init_substates:
  226. for substate in self.get_substates():
  227. self.substates[substate.get_name()] = substate(
  228. parent_state=self,
  229. _reflex_internal_init=True,
  230. )
  231. # Convert the event handlers to functions.
  232. self._init_event_handlers()
  233. # Create a fresh copy of the backend variables for this instance
  234. self._backend_vars = copy.deepcopy(self.backend_vars)
  235. def _init_event_handlers(self, state: BaseState | None = None):
  236. """Initialize event handlers.
  237. Allow event handlers to be called directly on the instance. This is
  238. called recursively for all parent states.
  239. Args:
  240. state: The state to initialize the event handlers on.
  241. """
  242. if state is None:
  243. state = self
  244. # Convert the event handlers to functions.
  245. for name, event_handler in state.event_handlers.items():
  246. if event_handler.is_background:
  247. fn = _no_chain_background_task(type(state), name, event_handler.fn)
  248. else:
  249. fn = functools.partial(event_handler.fn, self)
  250. fn.__module__ = event_handler.fn.__module__ # type: ignore
  251. fn.__qualname__ = event_handler.fn.__qualname__ # type: ignore
  252. setattr(self, name, fn)
  253. # Also allow direct calling of parent state event handlers
  254. if state.parent_state is not None:
  255. self._init_event_handlers(state.parent_state)
  256. def __repr__(self) -> str:
  257. """Get the string representation of the state.
  258. Returns:
  259. The string representation of the state.
  260. """
  261. return f"{self.__class__.__name__}({self.dict()})"
  262. @classmethod
  263. def __init_subclass__(cls, **kwargs):
  264. """Do some magic for the subclass initialization.
  265. Args:
  266. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  267. Raises:
  268. ValueError: If a substate class shadows another.
  269. """
  270. super().__init_subclass__(**kwargs)
  271. # Event handlers should not shadow builtin state methods.
  272. cls._check_overridden_methods()
  273. # Reset subclass tracking for this class.
  274. cls.class_subclasses = set()
  275. # Reset dirty substate tracking for this class.
  276. cls._always_dirty_substates = set()
  277. # Get the parent vars.
  278. parent_state = cls.get_parent_state()
  279. if parent_state is not None:
  280. cls.inherited_vars = parent_state.vars
  281. cls.inherited_backend_vars = parent_state.backend_vars
  282. # Check if another substate class with the same name has already been defined.
  283. if cls.__name__ in set(c.__name__ for c in parent_state.class_subclasses):
  284. if is_testing_env():
  285. # Clear existing subclass with same name when app is reloaded via
  286. # utils.prerequisites.get_app(reload=True)
  287. parent_state.class_subclasses = set(
  288. c
  289. for c in parent_state.class_subclasses
  290. if c.__name__ != cls.__name__
  291. )
  292. else:
  293. # During normal operation, subclasses cannot have the same name, even if they are
  294. # defined in different modules.
  295. raise ValueError(
  296. f"The substate class '{cls.__name__}' has been defined multiple times. "
  297. "Shadowing substate classes is not allowed."
  298. )
  299. # Track this new subclass in the parent state's subclasses set.
  300. parent_state.class_subclasses.add(cls)
  301. new_backend_vars = {
  302. name: value
  303. for name, value in cls.__dict__.items()
  304. if types.is_backend_variable(name, cls)
  305. and name not in RESERVED_BACKEND_VAR_NAMES
  306. and name not in cls.inherited_backend_vars
  307. and not isinstance(value, FunctionType)
  308. }
  309. cls.backend_vars = {**cls.inherited_backend_vars, **new_backend_vars}
  310. # Set the base and computed vars.
  311. cls.base_vars = {
  312. f.name: BaseVar(_var_name=f.name, _var_type=f.outer_type_)._var_set_state(
  313. cls
  314. )
  315. for f in cls.get_fields().values()
  316. if f.name not in cls.get_skip_vars()
  317. }
  318. cls.computed_vars = {
  319. v._var_name: v._var_set_state(cls)
  320. for v in cls.__dict__.values()
  321. if isinstance(v, ComputedVar)
  322. }
  323. cls.vars = {
  324. **cls.inherited_vars,
  325. **cls.base_vars,
  326. **cls.computed_vars,
  327. }
  328. cls.event_handlers = {}
  329. # Setup the base vars at the class level.
  330. for prop in cls.base_vars.values():
  331. cls._init_var(prop)
  332. # Set up the event handlers.
  333. events = {
  334. name: fn
  335. for name, fn in cls.__dict__.items()
  336. if cls._item_is_event_handler(name, fn)
  337. }
  338. for mixin in cls._mixins():
  339. for name, value in mixin.__dict__.items():
  340. if isinstance(value, ComputedVar):
  341. fget = cls._copy_fn(value.fget)
  342. newcv = ComputedVar(fget=fget, _var_name=value._var_name)
  343. newcv._var_set_state(cls)
  344. setattr(cls, name, newcv)
  345. cls.computed_vars[newcv._var_name] = newcv
  346. cls.vars[newcv._var_name] = newcv
  347. continue
  348. if events.get(name) is not None:
  349. continue
  350. if not cls._item_is_event_handler(name, value):
  351. continue
  352. if parent_state is not None and parent_state.event_handlers.get(name):
  353. continue
  354. value = cls._copy_fn(value)
  355. value.__qualname__ = f"{cls.__name__}.{name}"
  356. events[name] = value
  357. for name, fn in events.items():
  358. handler = EventHandler(fn=fn)
  359. cls.event_handlers[name] = handler
  360. setattr(cls, name, handler)
  361. cls._init_var_dependency_dicts()
  362. @staticmethod
  363. def _copy_fn(fn: Callable) -> Callable:
  364. """Copy a function. Used to copy ComputedVars and EventHandlers from mixins.
  365. Args:
  366. fn: The function to copy.
  367. Returns:
  368. The copied function.
  369. """
  370. newfn = FunctionType(
  371. fn.__code__,
  372. fn.__globals__,
  373. name=fn.__name__,
  374. argdefs=fn.__defaults__,
  375. closure=fn.__closure__,
  376. )
  377. newfn.__annotations__ = fn.__annotations__
  378. return newfn
  379. @staticmethod
  380. def _item_is_event_handler(name: str, value: Any) -> bool:
  381. """Check if the item is an event handler.
  382. Args:
  383. name: The name of the item.
  384. value: The value of the item.
  385. Returns:
  386. Whether the item is an event handler.
  387. """
  388. return (
  389. not name.startswith("_")
  390. and isinstance(value, Callable)
  391. and not isinstance(value, EventHandler)
  392. and hasattr(value, "__code__")
  393. )
  394. @classmethod
  395. def _mixins(cls) -> List[Type]:
  396. """Get the mixin classes of the state.
  397. Returns:
  398. The mixin classes of the state.
  399. """
  400. return [
  401. mixin
  402. for mixin in cls.__mro__
  403. if not issubclass(mixin, (BaseState, ABC))
  404. and mixin not in [pydantic.BaseModel, Base]
  405. ]
  406. @classmethod
  407. def _init_var_dependency_dicts(cls):
  408. """Initialize the var dependency tracking dicts.
  409. Allows the state to know which vars each ComputedVar depends on and
  410. whether a ComputedVar depends on a var in its parent state.
  411. Additional updates tracking dicts for vars and substates that always
  412. need to be recomputed.
  413. """
  414. # Initialize per-class var dependency tracking.
  415. cls._computed_var_dependencies = defaultdict(set)
  416. cls._substate_var_dependencies = defaultdict(set)
  417. inherited_vars = set(cls.inherited_vars).union(
  418. set(cls.inherited_backend_vars),
  419. )
  420. for cvar_name, cvar in cls.computed_vars.items():
  421. # Add the dependencies.
  422. for var in cvar._deps(objclass=cls):
  423. cls._computed_var_dependencies[var].add(cvar_name)
  424. if var in inherited_vars:
  425. # track that this substate depends on its parent for this var
  426. state_name = cls.get_name()
  427. parent_state = cls.get_parent_state()
  428. while parent_state is not None and var in {
  429. **parent_state.vars,
  430. **parent_state.backend_vars,
  431. }:
  432. parent_state._substate_var_dependencies[var].add(state_name)
  433. state_name, parent_state = (
  434. parent_state.get_name(),
  435. parent_state.get_parent_state(),
  436. )
  437. # ComputedVar with cache=False always need to be recomputed
  438. cls._always_dirty_computed_vars = set(
  439. cvar_name
  440. for cvar_name, cvar in cls.computed_vars.items()
  441. if not cvar._cache
  442. )
  443. # Any substate containing a ComputedVar with cache=False always needs to be recomputed
  444. if cls._always_dirty_computed_vars:
  445. # Tell parent classes that this substate has always dirty computed vars
  446. state_name = cls.get_name()
  447. parent_state = cls.get_parent_state()
  448. while parent_state is not None:
  449. parent_state._always_dirty_substates.add(state_name)
  450. state_name, parent_state = (
  451. parent_state.get_name(),
  452. parent_state.get_parent_state(),
  453. )
  454. @classmethod
  455. def _check_overridden_methods(cls):
  456. """Check for shadow methods and raise error if any.
  457. Raises:
  458. NameError: When an event handler shadows an inbuilt state method.
  459. """
  460. overridden_methods = set()
  461. state_base_functions = cls._get_base_functions()
  462. for name, method in inspect.getmembers(cls, inspect.isfunction):
  463. # Check if the method is overridden and not a dunder method
  464. if (
  465. not name.startswith("__")
  466. and method.__name__ in state_base_functions
  467. and state_base_functions[method.__name__] != method
  468. ):
  469. overridden_methods.add(method.__name__)
  470. for method_name in overridden_methods:
  471. raise NameError(
  472. f"The event handler name `{method_name}` shadows a builtin State method; use a different name instead"
  473. )
  474. @classmethod
  475. def get_skip_vars(cls) -> set[str]:
  476. """Get the vars to skip when serializing.
  477. Returns:
  478. The vars to skip when serializing.
  479. """
  480. return (
  481. set(cls.inherited_vars)
  482. | {
  483. "parent_state",
  484. "substates",
  485. "dirty_vars",
  486. "dirty_substates",
  487. "router_data",
  488. }
  489. | RESERVED_BACKEND_VAR_NAMES
  490. )
  491. @classmethod
  492. @functools.lru_cache()
  493. def get_parent_state(cls) -> Type[BaseState] | None:
  494. """Get the parent state.
  495. Returns:
  496. The parent state.
  497. """
  498. parent_states = [
  499. base
  500. for base in cls.__bases__
  501. if types._issubclass(base, BaseState) and base is not BaseState
  502. ]
  503. assert len(parent_states) < 2, "Only one parent state is allowed."
  504. return parent_states[0] if len(parent_states) == 1 else None # type: ignore
  505. @classmethod
  506. def get_substates(cls) -> set[Type[BaseState]]:
  507. """Get the substates of the state.
  508. Returns:
  509. The substates of the state.
  510. """
  511. return cls.class_subclasses
  512. @classmethod
  513. @functools.lru_cache()
  514. def get_name(cls) -> str:
  515. """Get the name of the state.
  516. Returns:
  517. The name of the state.
  518. """
  519. return format.to_snake_case(cls.__name__)
  520. @classmethod
  521. @functools.lru_cache()
  522. def get_full_name(cls) -> str:
  523. """Get the full name of the state.
  524. Returns:
  525. The full name of the state.
  526. """
  527. name = cls.get_name()
  528. parent_state = cls.get_parent_state()
  529. if parent_state is not None:
  530. name = ".".join((parent_state.get_full_name(), name))
  531. return name
  532. @classmethod
  533. @functools.lru_cache()
  534. def get_class_substate(cls, path: Sequence[str]) -> Type[BaseState]:
  535. """Get the class substate.
  536. Args:
  537. path: The path to the substate.
  538. Returns:
  539. The class substate.
  540. Raises:
  541. ValueError: If the substate is not found.
  542. """
  543. if len(path) == 0:
  544. return cls
  545. if path[0] == cls.get_name():
  546. if len(path) == 1:
  547. return cls
  548. path = path[1:]
  549. for substate in cls.get_substates():
  550. if path[0] == substate.get_name():
  551. return substate.get_class_substate(path[1:])
  552. raise ValueError(f"Invalid path: {path}")
  553. @classmethod
  554. def get_class_var(cls, path: Sequence[str]) -> Any:
  555. """Get the class var.
  556. Args:
  557. path: The path to the var.
  558. Returns:
  559. The class var.
  560. Raises:
  561. ValueError: If the path is invalid.
  562. """
  563. path, name = path[:-1], path[-1]
  564. substate = cls.get_class_substate(tuple(path))
  565. if not hasattr(substate, name):
  566. raise ValueError(f"Invalid path: {path}")
  567. return getattr(substate, name)
  568. @classmethod
  569. def _init_var(cls, prop: BaseVar):
  570. """Initialize a variable.
  571. Args:
  572. prop: The variable to initialize
  573. Raises:
  574. TypeError: if the variable has an incorrect type
  575. """
  576. if not types.is_valid_var_type(prop._var_type):
  577. raise TypeError(
  578. "State vars must be primitive Python types, "
  579. "Plotly figures, Pandas dataframes, "
  580. "or subclasses of rx.Base. "
  581. f'Found var "{prop._var_name}" with type {prop._var_type}.'
  582. )
  583. cls._set_var(prop)
  584. cls._create_setter(prop)
  585. cls._set_default_value(prop)
  586. @classmethod
  587. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  588. """Add dynamically a variable to the State.
  589. The variable added this way can be used in the same way as a variable
  590. defined statically in the model.
  591. Args:
  592. name: The name of the variable
  593. type_: The type of the variable
  594. default_value: The default value of the variable
  595. Raises:
  596. NameError: if a variable of this name already exists
  597. """
  598. if name in cls.__fields__:
  599. raise NameError(
  600. f"The variable '{name}' already exist. Use a different name"
  601. )
  602. # create the variable based on name and type
  603. var = BaseVar(_var_name=name, _var_type=type_)
  604. var._var_set_state(cls)
  605. # add the pydantic field dynamically (must be done before _init_var)
  606. cls.add_field(var, default_value)
  607. cls._init_var(var)
  608. # update the internal dicts so the new variable is correctly handled
  609. cls.base_vars.update({name: var})
  610. cls.vars.update({name: var})
  611. # let substates know about the new variable
  612. for substate_class in cls.__subclasses__():
  613. substate_class.vars.setdefault(name, var)
  614. # Reinitialize dependency tracking dicts.
  615. cls._init_var_dependency_dicts()
  616. @classmethod
  617. def _set_var(cls, prop: BaseVar):
  618. """Set the var as a class member.
  619. Args:
  620. prop: The var instance to set.
  621. """
  622. setattr(cls, prop._var_name, prop)
  623. @classmethod
  624. def _create_setter(cls, prop: BaseVar):
  625. """Create a setter for the var.
  626. Args:
  627. prop: The var to create a setter for.
  628. """
  629. setter_name = prop.get_setter_name(include_state=False)
  630. if setter_name not in cls.__dict__:
  631. event_handler = EventHandler(fn=prop.get_setter())
  632. cls.event_handlers[setter_name] = event_handler
  633. setattr(cls, setter_name, event_handler)
  634. @classmethod
  635. def _set_default_value(cls, prop: BaseVar):
  636. """Set the default value for the var.
  637. Args:
  638. prop: The var to set the default value for.
  639. """
  640. # Get the pydantic field for the var.
  641. field = cls.get_fields()[prop._var_name]
  642. if field.required:
  643. default_value = prop.get_default_value()
  644. if default_value is not None:
  645. field.required = False
  646. field.default = default_value
  647. if (
  648. not field.required
  649. and field.default is None
  650. and not types.is_optional(prop._var_type)
  651. ):
  652. # Ensure frontend uses null coalescing when accessing.
  653. prop._var_type = Optional[prop._var_type]
  654. @staticmethod
  655. def _get_base_functions() -> dict[str, FunctionType]:
  656. """Get all functions of the state class excluding dunder methods.
  657. Returns:
  658. The functions of rx.State class as a dict.
  659. """
  660. return {
  661. func[0]: func[1]
  662. for func in inspect.getmembers(BaseState, predicate=inspect.isfunction)
  663. if not func[0].startswith("__")
  664. }
  665. def get_token(self) -> str:
  666. """Return the token of the client associated with this state.
  667. Returns:
  668. The token of the client.
  669. """
  670. console.deprecate(
  671. feature_name="get_token",
  672. reason="replaced by `State.router.session.client_token`",
  673. deprecation_version="0.3.0",
  674. removal_version="0.5.0",
  675. )
  676. return self.router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
  677. def get_sid(self) -> str:
  678. """Return the session ID of the client associated with this state.
  679. Returns:
  680. The session ID of the client.
  681. """
  682. console.deprecate(
  683. feature_name="get_sid",
  684. reason="replaced by `State.router.session.session_id`",
  685. deprecation_version="0.3.0",
  686. removal_version="0.5.0",
  687. )
  688. return self.router_data.get(constants.RouteVar.SESSION_ID, "")
  689. def get_headers(self) -> Dict:
  690. """Return the headers of the client associated with this state.
  691. Returns:
  692. The headers of the client.
  693. """
  694. console.deprecate(
  695. feature_name="get_headers",
  696. reason="replaced by `State.router.headers`",
  697. deprecation_version="0.3.0",
  698. removal_version="0.5.0",
  699. )
  700. return self.router_data.get(constants.RouteVar.HEADERS, {})
  701. def get_client_ip(self) -> str:
  702. """Return the IP of the client associated with this state.
  703. Returns:
  704. The IP of the client.
  705. """
  706. console.deprecate(
  707. feature_name="get_client_ip",
  708. reason="replaced by `State.router.session.client_ip`",
  709. deprecation_version="0.3.0",
  710. removal_version="0.5.0",
  711. )
  712. return self.router_data.get(constants.RouteVar.CLIENT_IP, "")
  713. def get_current_page(self, origin=False) -> str:
  714. """Obtain the path of current page from the router data.
  715. Args:
  716. origin: whether to return the base route as shown in browser
  717. Returns:
  718. The current page.
  719. """
  720. console.deprecate(
  721. feature_name="get_current_page",
  722. reason="replaced by State.router.page / self.router.page",
  723. deprecation_version="0.3.0",
  724. removal_version="0.5.0",
  725. )
  726. return self.router.page.raw_path if origin else self.router.page.path
  727. def get_query_params(self) -> dict[str, str]:
  728. """Obtain the query parameters for the queried page.
  729. The query object contains both the URI parameters and the GET parameters.
  730. Returns:
  731. The dict of query parameters.
  732. """
  733. console.deprecate(
  734. feature_name="get_query_params",
  735. reason="replaced by `State.router.page.params`",
  736. deprecation_version="0.3.0",
  737. removal_version="0.5.0",
  738. )
  739. return self.router_data.get(constants.RouteVar.QUERY, {})
  740. def get_cookies(self) -> dict[str, str]:
  741. """Obtain the cookies of the client stored in the browser.
  742. Returns:
  743. The dict of cookies.
  744. """
  745. console.deprecate(
  746. feature_name=f"rx.get_cookies",
  747. reason="and has been replaced by rx.Cookie, which can be used as a state var",
  748. deprecation_version="0.3.0",
  749. removal_version="0.5.0",
  750. )
  751. cookie_dict = {}
  752. cookies = self.get_headers().get(constants.RouteVar.COOKIE, "").split(";")
  753. cookie_pairs = [cookie.split("=") for cookie in cookies if cookie]
  754. for pair in cookie_pairs:
  755. key, value = pair[0].strip(), urllib.parse.unquote(pair[1].strip())
  756. try:
  757. # cast non-string values to the actual types.
  758. value = json.loads(value)
  759. except json.JSONDecodeError:
  760. pass
  761. finally:
  762. cookie_dict[key] = value
  763. return cookie_dict
  764. @classmethod
  765. def setup_dynamic_args(cls, args: dict[str, str]):
  766. """Set up args for easy access in renderer.
  767. Args:
  768. args: a dict of args
  769. """
  770. def argsingle_factory(param):
  771. @ComputedVar
  772. def inner_func(self) -> str:
  773. return self.router.page.params.get(param, "")
  774. return inner_func
  775. def arglist_factory(param):
  776. @ComputedVar
  777. def inner_func(self) -> List:
  778. return self.router.page.params.get(param, [])
  779. return inner_func
  780. for param, value in args.items():
  781. if value == constants.RouteArgType.SINGLE:
  782. func = argsingle_factory(param)
  783. elif value == constants.RouteArgType.LIST:
  784. func = arglist_factory(param)
  785. else:
  786. continue
  787. # to allow passing as a prop
  788. func._var_name = param
  789. cls.vars[param] = cls.computed_vars[param] = func._var_set_state(cls) # type: ignore
  790. setattr(cls, param, func)
  791. # Reinitialize dependency tracking dicts.
  792. cls._init_var_dependency_dicts()
  793. def __getattribute__(self, name: str) -> Any:
  794. """Get the state var.
  795. If the var is inherited, get the var from the parent state.
  796. Args:
  797. name: The name of the var.
  798. Returns:
  799. The value of the var.
  800. """
  801. # If the state hasn't been initialized yet, return the default value.
  802. if not super().__getattribute__("__dict__"):
  803. return super().__getattribute__(name)
  804. inherited_vars = {
  805. **super().__getattribute__("inherited_vars"),
  806. **super().__getattribute__("inherited_backend_vars"),
  807. }
  808. # For now, handle router_data updates as a special case.
  809. if name in inherited_vars or name == constants.ROUTER_DATA:
  810. parent_state = super().__getattribute__("parent_state")
  811. if parent_state is not None:
  812. return getattr(parent_state, name)
  813. backend_vars = super().__getattribute__("_backend_vars")
  814. if name in backend_vars:
  815. value = backend_vars[name]
  816. else:
  817. value = super().__getattribute__(name)
  818. if isinstance(value, MutableProxy.__mutable_types__) and (
  819. name in super().__getattribute__("base_vars") or name in backend_vars
  820. ):
  821. # track changes in mutable containers (list, dict, set, etc)
  822. return MutableProxy(wrapped=value, state=self, field_name=name)
  823. return value
  824. def __setattr__(self, name: str, value: Any):
  825. """Set the attribute.
  826. If the attribute is inherited, set the attribute on the parent state.
  827. Args:
  828. name: The name of the attribute.
  829. value: The value of the attribute.
  830. """
  831. if isinstance(value, MutableProxy):
  832. # unwrap proxy objects when assigning back to the state
  833. value = value.__wrapped__
  834. # Set the var on the parent state.
  835. inherited_vars = {**self.inherited_vars, **self.inherited_backend_vars}
  836. if name in inherited_vars:
  837. setattr(self.parent_state, name, value)
  838. return
  839. if (
  840. types.is_backend_variable(name, self.__class__)
  841. and name not in RESERVED_BACKEND_VAR_NAMES
  842. ):
  843. self._backend_vars.__setitem__(name, value)
  844. self.dirty_vars.add(name)
  845. self._mark_dirty()
  846. return
  847. # Set the attribute.
  848. super().__setattr__(name, value)
  849. # Add the var to the dirty list.
  850. if name in self.vars or name in self._computed_var_dependencies:
  851. self.dirty_vars.add(name)
  852. self._mark_dirty()
  853. # For now, handle router_data updates as a special case
  854. if name == constants.ROUTER_DATA:
  855. self.dirty_vars.add(name)
  856. self._mark_dirty()
  857. def reset(self):
  858. """Reset all the base vars to their default values."""
  859. # Reset the base vars.
  860. fields = self.get_fields()
  861. for prop_name in self.base_vars:
  862. if prop_name == constants.ROUTER:
  863. continue # never reset the router data
  864. setattr(self, prop_name, copy.deepcopy(fields[prop_name].default))
  865. # Recursively reset the substates.
  866. for substate in self.substates.values():
  867. substate.reset()
  868. def _reset_client_storage(self):
  869. """Reset client storage base vars to their default values."""
  870. # Client-side storage is reset during hydrate so that clearing cookies
  871. # on the browser also resets the values on the backend.
  872. fields = self.get_fields()
  873. for prop_name in self.base_vars:
  874. field = fields[prop_name]
  875. if isinstance(field.default, ClientStorageBase) or (
  876. isinstance(field.type_, type)
  877. and issubclass(field.type_, ClientStorageBase)
  878. ):
  879. setattr(self, prop_name, copy.deepcopy(field.default))
  880. # Recursively reset the substate client storage.
  881. for substate in self.substates.values():
  882. substate._reset_client_storage()
  883. def get_substate(self, path: Sequence[str]) -> BaseState:
  884. """Get the substate.
  885. Args:
  886. path: The path to the substate.
  887. Returns:
  888. The substate.
  889. Raises:
  890. ValueError: If the substate is not found.
  891. """
  892. if len(path) == 0:
  893. return self
  894. if path[0] == self.get_name():
  895. if len(path) == 1:
  896. return self
  897. path = path[1:]
  898. if path[0] not in self.substates:
  899. raise ValueError(f"Invalid path: {path}")
  900. return self.substates[path[0]].get_substate(path[1:])
  901. @classmethod
  902. def _get_common_ancestor(cls, other: Type[BaseState]) -> str:
  903. """Find the name of the nearest common ancestor shared by this and the other state.
  904. Args:
  905. other: The other state.
  906. Returns:
  907. Full name of the nearest common ancestor.
  908. """
  909. common_ancestor_parts = []
  910. for part1, part2 in zip(
  911. cls.get_full_name().split("."),
  912. other.get_full_name().split("."),
  913. ):
  914. if part1 != part2:
  915. break
  916. common_ancestor_parts.append(part1)
  917. return ".".join(common_ancestor_parts)
  918. @classmethod
  919. def _determine_missing_parent_states(
  920. cls, target_state_cls: Type[BaseState]
  921. ) -> tuple[str, list[str]]:
  922. """Determine the missing parent states between the target_state_cls and common ancestor of this state.
  923. Args:
  924. target_state_cls: The class of the state to find missing parent states for.
  925. Returns:
  926. The name of the common ancestor and the list of missing parent states.
  927. """
  928. common_ancestor_name = cls._get_common_ancestor(target_state_cls)
  929. common_ancestor_parts = common_ancestor_name.split(".")
  930. target_state_parts = tuple(target_state_cls.get_full_name().split("."))
  931. relative_target_state_parts = target_state_parts[len(common_ancestor_parts) :]
  932. # Determine which parent states to fetch from the common ancestor down to the target_state_cls.
  933. fetch_parent_states = [common_ancestor_name]
  934. for ix, relative_parent_state_name in enumerate(relative_target_state_parts):
  935. fetch_parent_states.append(
  936. ".".join([*fetch_parent_states[: ix + 1], relative_parent_state_name])
  937. )
  938. return common_ancestor_name, fetch_parent_states[1:-1]
  939. def _get_parent_states(self) -> list[tuple[str, BaseState]]:
  940. """Get all parent state instances up to the root of the state tree.
  941. Returns:
  942. A list of tuples containing the name and the instance of each parent state.
  943. """
  944. parent_states_with_name = []
  945. parent_state = self
  946. while parent_state.parent_state is not None:
  947. parent_state = parent_state.parent_state
  948. parent_states_with_name.append((parent_state.get_full_name(), parent_state))
  949. return parent_states_with_name
  950. async def _populate_parent_states(self, target_state_cls: Type[BaseState]):
  951. """Populate substates in the tree between the target_state_cls and common ancestor of this state.
  952. Args:
  953. target_state_cls: The class of the state to populate parent states for.
  954. Returns:
  955. The parent state instance of target_state_cls.
  956. Raises:
  957. RuntimeError: If redis is not used in this backend process.
  958. """
  959. state_manager = get_state_manager()
  960. if not isinstance(state_manager, StateManagerRedis):
  961. raise RuntimeError(
  962. f"Cannot populate parent states of {target_state_cls.get_full_name()} without redis. "
  963. "(All states should already be available -- this is likely a bug).",
  964. )
  965. # Find the missing parent states up to the common ancestor.
  966. (
  967. common_ancestor_name,
  968. missing_parent_states,
  969. ) = self._determine_missing_parent_states(target_state_cls)
  970. # Fetch all missing parent states and link them up to the common ancestor.
  971. parent_states_by_name = dict(self._get_parent_states())
  972. parent_state = parent_states_by_name[common_ancestor_name]
  973. for parent_state_name in missing_parent_states:
  974. parent_state = await state_manager.get_state(
  975. token=_substate_key(
  976. self.router.session.client_token, parent_state_name
  977. ),
  978. top_level=False,
  979. get_substates=False,
  980. parent_state=parent_state,
  981. )
  982. # Return the direct parent of target_state_cls for subsequent linking.
  983. return parent_state
  984. def _get_state_from_cache(self, state_cls: Type[BaseState]) -> BaseState:
  985. """Get a state instance from the cache.
  986. Args:
  987. state_cls: The class of the state.
  988. Returns:
  989. The instance of state_cls associated with this state's client_token.
  990. """
  991. if self.parent_state is None:
  992. root_state = self
  993. else:
  994. root_state = self._get_parent_states()[-1][1]
  995. return root_state.get_substate(state_cls.get_full_name().split("."))
  996. async def _get_state_from_redis(self, state_cls: Type[BaseState]) -> BaseState:
  997. """Get a state instance from redis.
  998. Args:
  999. state_cls: The class of the state.
  1000. Returns:
  1001. The instance of state_cls associated with this state's client_token.
  1002. Raises:
  1003. RuntimeError: If redis is not used in this backend process.
  1004. """
  1005. # Fetch all missing parent states from redis.
  1006. parent_state_of_state_cls = await self._populate_parent_states(state_cls)
  1007. # Then get the target state and all its substates.
  1008. state_manager = get_state_manager()
  1009. if not isinstance(state_manager, StateManagerRedis):
  1010. raise RuntimeError(
  1011. f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. "
  1012. "(All states should already be available -- this is likely a bug).",
  1013. )
  1014. return await state_manager.get_state(
  1015. token=_substate_key(self.router.session.client_token, state_cls),
  1016. top_level=False,
  1017. get_substates=True,
  1018. parent_state=parent_state_of_state_cls,
  1019. )
  1020. async def get_state(self, state_cls: Type[BaseState]) -> BaseState:
  1021. """Get an instance of the state associated with this token.
  1022. Allows for arbitrary access to sibling states from within an event handler.
  1023. Args:
  1024. state_cls: The class of the state.
  1025. Returns:
  1026. The instance of state_cls associated with this state's client_token.
  1027. """
  1028. # Fast case - if this state instance is already cached, get_substate from root state.
  1029. try:
  1030. return self._get_state_from_cache(state_cls)
  1031. except ValueError:
  1032. pass
  1033. # Slow case - fetch missing parent states from redis.
  1034. return await self._get_state_from_redis(state_cls)
  1035. def _get_event_handler(
  1036. self, event: Event
  1037. ) -> tuple[BaseState | StateProxy, EventHandler]:
  1038. """Get the event handler for the given event.
  1039. Args:
  1040. event: The event to get the handler for.
  1041. Returns:
  1042. The event handler.
  1043. Raises:
  1044. ValueError: If the event handler or substate is not found.
  1045. """
  1046. # Get the event handler.
  1047. path = event.name.split(".")
  1048. path, name = path[:-1], path[-1]
  1049. substate = self.get_substate(path)
  1050. if not substate:
  1051. raise ValueError(
  1052. "The value of state cannot be None when processing an event."
  1053. )
  1054. handler = substate.event_handlers[name]
  1055. # For background tasks, proxy the state
  1056. if handler.is_background:
  1057. substate = StateProxy(substate)
  1058. return substate, handler
  1059. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  1060. """Obtain event info and process event.
  1061. Args:
  1062. event: The event to process.
  1063. Yields:
  1064. The state update after processing the event.
  1065. """
  1066. # Get the event handler.
  1067. substate, handler = self._get_event_handler(event)
  1068. # Run the event generator and yield state updates.
  1069. async for update in self._process_event(
  1070. handler=handler,
  1071. state=substate,
  1072. payload=event.payload,
  1073. ):
  1074. yield update
  1075. def _check_valid(self, handler: EventHandler, events: Any) -> Any:
  1076. """Check if the events yielded are valid. They must be EventHandlers or EventSpecs.
  1077. Args:
  1078. handler: EventHandler.
  1079. events: The events to be checked.
  1080. Raises:
  1081. TypeError: If any of the events are not valid.
  1082. Returns:
  1083. The events as they are if valid.
  1084. """
  1085. def _is_valid_type(events: Any) -> bool:
  1086. return isinstance(events, (Event, EventHandler, EventSpec))
  1087. if events is None or _is_valid_type(events):
  1088. return events
  1089. try:
  1090. if all(_is_valid_type(e) for e in events):
  1091. return events
  1092. except TypeError:
  1093. pass
  1094. raise TypeError(
  1095. f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`)"
  1096. )
  1097. def _as_state_update(
  1098. self,
  1099. handler: EventHandler,
  1100. events: EventSpec | list[EventSpec] | None,
  1101. final: bool,
  1102. ) -> StateUpdate:
  1103. """Convert the events to a StateUpdate.
  1104. Fixes the events and checks for validity before converting.
  1105. Args:
  1106. handler: The handler where the events originated from.
  1107. events: The events to queue with the update.
  1108. final: Whether the handler is done processing.
  1109. Returns:
  1110. The valid StateUpdate containing the events and final flag.
  1111. """
  1112. # get the delta from the root of the state tree
  1113. state = self
  1114. while state.parent_state is not None:
  1115. state = state.parent_state
  1116. token = self.router.session.client_token
  1117. # Convert valid EventHandler and EventSpec into Event
  1118. fixed_events = fix_events(self._check_valid(handler, events), token)
  1119. # Get the delta after processing the event.
  1120. delta = state.get_delta()
  1121. state._clean()
  1122. return StateUpdate(
  1123. delta=delta,
  1124. events=fixed_events,
  1125. final=final if not handler.is_background else True,
  1126. )
  1127. async def _process_event(
  1128. self, handler: EventHandler, state: BaseState | StateProxy, payload: Dict
  1129. ) -> AsyncIterator[StateUpdate]:
  1130. """Process event.
  1131. Args:
  1132. handler: EventHandler to process.
  1133. state: State to process the handler.
  1134. payload: The event payload.
  1135. Yields:
  1136. StateUpdate object
  1137. """
  1138. # Get the function to process the event.
  1139. fn = functools.partial(handler.fn, state)
  1140. # Wrap the function in a try/except block.
  1141. try:
  1142. # Handle async functions.
  1143. if asyncio.iscoroutinefunction(fn.func):
  1144. events = await fn(**payload)
  1145. # Handle regular functions.
  1146. else:
  1147. events = fn(**payload)
  1148. # Handle async generators.
  1149. if inspect.isasyncgen(events):
  1150. async for event in events:
  1151. yield state._as_state_update(handler, event, final=False)
  1152. yield state._as_state_update(handler, events=None, final=True)
  1153. # Handle regular generators.
  1154. elif inspect.isgenerator(events):
  1155. try:
  1156. while True:
  1157. yield state._as_state_update(handler, next(events), final=False)
  1158. except StopIteration as si:
  1159. # the "return" value of the generator is not available
  1160. # in the loop, we must catch StopIteration to access it
  1161. if si.value is not None:
  1162. yield state._as_state_update(handler, si.value, final=False)
  1163. yield state._as_state_update(handler, events=None, final=True)
  1164. # Handle regular event chains.
  1165. else:
  1166. yield state._as_state_update(handler, events, final=True)
  1167. # If an error occurs, throw a window alert.
  1168. except Exception:
  1169. error = traceback.format_exc()
  1170. print(error)
  1171. yield state._as_state_update(
  1172. handler,
  1173. window_alert("An error occurred. See logs for details."),
  1174. final=True,
  1175. )
  1176. def _mark_dirty_computed_vars(self) -> None:
  1177. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  1178. dirty_vars = self.dirty_vars
  1179. while dirty_vars:
  1180. calc_vars, dirty_vars = dirty_vars, set()
  1181. for cvar in self._dirty_computed_vars(from_vars=calc_vars):
  1182. self.dirty_vars.add(cvar)
  1183. dirty_vars.add(cvar)
  1184. actual_var = self.computed_vars.get(cvar)
  1185. if actual_var is not None:
  1186. actual_var.mark_dirty(instance=self)
  1187. def _dirty_computed_vars(self, from_vars: set[str] | None = None) -> set[str]:
  1188. """Determine ComputedVars that need to be recalculated based on the given vars.
  1189. Args:
  1190. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  1191. Returns:
  1192. Set of computed vars to include in the delta.
  1193. """
  1194. return set(
  1195. cvar
  1196. for dirty_var in from_vars or self.dirty_vars
  1197. for cvar in self._computed_var_dependencies[dirty_var]
  1198. )
  1199. @classmethod
  1200. def _potentially_dirty_substates(cls) -> set[Type[BaseState]]:
  1201. """Determine substates which could be affected by dirty vars in this state.
  1202. Returns:
  1203. Set of State classes that may need to be fetched to recalc computed vars.
  1204. """
  1205. # _always_dirty_substates need to be fetched to recalc computed vars.
  1206. fetch_substates = set(
  1207. cls.get_class_substate(tuple(substate_name.split(".")))
  1208. for substate_name in cls._always_dirty_substates
  1209. )
  1210. # Substates with cached vars also need to be fetched.
  1211. for dependent_substates in cls._substate_var_dependencies.values():
  1212. fetch_substates.update(
  1213. set(
  1214. cls.get_class_substate(tuple(substate_name.split(".")))
  1215. for substate_name in dependent_substates
  1216. )
  1217. )
  1218. return fetch_substates
  1219. def get_delta(self) -> Delta:
  1220. """Get the delta for the state.
  1221. Returns:
  1222. The delta for the state.
  1223. """
  1224. delta = {}
  1225. # Apply dirty variables down into substates
  1226. self.dirty_vars.update(self._always_dirty_computed_vars)
  1227. self._mark_dirty()
  1228. # Return the dirty vars for this instance, any cached/dependent computed vars,
  1229. # and always dirty computed vars (cache=False)
  1230. delta_vars = (
  1231. self.dirty_vars.intersection(self.base_vars)
  1232. .union(self._dirty_computed_vars())
  1233. .union(self._always_dirty_computed_vars)
  1234. )
  1235. subdelta = {
  1236. prop: getattr(self, prop)
  1237. for prop in delta_vars
  1238. if not types.is_backend_variable(prop, self.__class__)
  1239. }
  1240. if len(subdelta) > 0:
  1241. delta[self.get_full_name()] = subdelta
  1242. # Recursively find the substate deltas.
  1243. substates = self.substates
  1244. for substate in self.dirty_substates.union(self._always_dirty_substates):
  1245. delta.update(substates[substate].get_delta())
  1246. # Format the delta.
  1247. delta = format.format_state(delta)
  1248. # Return the delta.
  1249. return delta
  1250. def _mark_dirty(self):
  1251. """Mark the substate and all parent states as dirty."""
  1252. state_name = self.get_name()
  1253. if (
  1254. self.parent_state is not None
  1255. and state_name not in self.parent_state.dirty_substates
  1256. ):
  1257. self.parent_state.dirty_substates.add(self.get_name())
  1258. self.parent_state._mark_dirty()
  1259. # have to mark computed vars dirty to allow access to newly computed
  1260. # values within the same ComputedVar function
  1261. self._mark_dirty_computed_vars()
  1262. self._mark_dirty_substates()
  1263. def _mark_dirty_substates(self):
  1264. """Propagate dirty var / computed var status into substates."""
  1265. substates = self.substates
  1266. for var in self.dirty_vars:
  1267. for substate_name in self._substate_var_dependencies[var]:
  1268. self.dirty_substates.add(substate_name)
  1269. substate = substates[substate_name]
  1270. substate.dirty_vars.add(var)
  1271. substate._mark_dirty()
  1272. def _update_was_touched(self):
  1273. """Update the _was_touched flag based on dirty_vars."""
  1274. if self.dirty_vars and not self._was_touched:
  1275. for var in self.dirty_vars:
  1276. if var in self.base_vars or var in self._backend_vars:
  1277. self._was_touched = True
  1278. break
  1279. def _get_was_touched(self) -> bool:
  1280. """Check current dirty_vars and flag to determine if state instance was modified.
  1281. If any dirty vars belong to this state, mark _was_touched.
  1282. This flag determines whether this state instance should be persisted to redis.
  1283. Returns:
  1284. Whether this state instance was ever modified.
  1285. """
  1286. # Ensure the flag is up to date based on the current dirty_vars
  1287. self._update_was_touched()
  1288. return self._was_touched
  1289. def _clean(self):
  1290. """Reset the dirty vars."""
  1291. # Update touched status before cleaning dirty_vars.
  1292. self._update_was_touched()
  1293. # Recursively clean the substates.
  1294. for substate in self.dirty_substates:
  1295. if substate not in self.substates:
  1296. continue
  1297. self.substates[substate]._clean()
  1298. # Clean this state.
  1299. self.dirty_vars = set()
  1300. self.dirty_substates = set()
  1301. def get_value(self, key: str) -> Any:
  1302. """Get the value of a field (without proxying).
  1303. The returned value will NOT track dirty state updates.
  1304. Args:
  1305. key: The key of the field.
  1306. Returns:
  1307. The value of the field.
  1308. """
  1309. if isinstance(key, MutableProxy):
  1310. return super().get_value(key.__wrapped__)
  1311. return super().get_value(key)
  1312. def dict(
  1313. self, include_computed: bool = True, initial: bool = False, **kwargs
  1314. ) -> dict[str, Any]:
  1315. """Convert the object to a dictionary.
  1316. Args:
  1317. include_computed: Whether to include computed vars.
  1318. initial: Whether to get the initial value of computed vars.
  1319. **kwargs: Kwargs to pass to the pydantic dict method.
  1320. Returns:
  1321. The object as a dictionary.
  1322. """
  1323. if include_computed:
  1324. # Apply dirty variables down into substates to allow never-cached ComputedVar to
  1325. # trigger recalculation of dependent vars
  1326. self.dirty_vars.update(self._always_dirty_computed_vars)
  1327. self._mark_dirty()
  1328. base_vars = {
  1329. prop_name: self.get_value(getattr(self, prop_name))
  1330. for prop_name in self.base_vars
  1331. }
  1332. if initial:
  1333. computed_vars = {
  1334. # Include initial computed vars.
  1335. prop_name: cv._initial_value
  1336. if isinstance(cv, ComputedVar)
  1337. and not isinstance(cv._initial_value, types.Unset)
  1338. else self.get_value(getattr(self, prop_name))
  1339. for prop_name, cv in self.computed_vars.items()
  1340. }
  1341. elif include_computed:
  1342. computed_vars = {
  1343. # Include the computed vars.
  1344. prop_name: self.get_value(getattr(self, prop_name))
  1345. for prop_name in self.computed_vars
  1346. }
  1347. else:
  1348. computed_vars = {}
  1349. variables = {**base_vars, **computed_vars}
  1350. d = {
  1351. self.get_full_name(): {k: variables[k] for k in sorted(variables)},
  1352. }
  1353. for substate_d in [
  1354. v.dict(include_computed=include_computed, initial=initial, **kwargs)
  1355. for v in self.substates.values()
  1356. ]:
  1357. d.update(substate_d)
  1358. return d
  1359. async def __aenter__(self) -> BaseState:
  1360. """Enter the async context manager protocol.
  1361. This should not be used for the State class, but exists for
  1362. type-compatibility with StateProxy.
  1363. Raises:
  1364. TypeError: always, because async contextmanager protocol is only supported for background task.
  1365. """
  1366. raise TypeError(
  1367. "Only background task should use `async with self` to modify state."
  1368. )
  1369. async def __aexit__(self, *exc_info: Any) -> None:
  1370. """Exit the async context manager protocol.
  1371. This should not be used for the State class, but exists for
  1372. type-compatibility with StateProxy.
  1373. Args:
  1374. exc_info: The exception info tuple.
  1375. """
  1376. pass
  1377. def __getstate__(self):
  1378. """Get the state for redis serialization.
  1379. This method is called by cloudpickle to serialize the object.
  1380. It explicitly removes parent_state and substates because those are serialized separately
  1381. by the StateManagerRedis to allow for better horizontal scaling as state size increases.
  1382. Returns:
  1383. The state dict for serialization.
  1384. """
  1385. state = super().__getstate__()
  1386. # Never serialize parent_state or substates
  1387. state["__dict__"] = state["__dict__"].copy()
  1388. state["__dict__"]["parent_state"] = None
  1389. state["__dict__"]["substates"] = {}
  1390. state["__dict__"].pop("_was_touched", None)
  1391. return state
  1392. class State(BaseState):
  1393. """The app Base State."""
  1394. # The hydrated bool.
  1395. is_hydrated: bool = False
  1396. class UpdateVarsInternalState(State):
  1397. """Substate for handling internal state var updates."""
  1398. async def update_vars_internal(self, vars: dict[str, Any]) -> None:
  1399. """Apply updates to fully qualified state vars.
  1400. The keys in `vars` should be in the form of `{state.get_full_name()}.{var_name}`,
  1401. and each value will be set on the appropriate substate instance.
  1402. This function is primarily used to apply cookie and local storage
  1403. updates from the frontend to the appropriate substate.
  1404. Args:
  1405. vars: The fully qualified vars and values to update.
  1406. """
  1407. for var, value in vars.items():
  1408. state_name, _, var_name = var.rpartition(".")
  1409. var_state_cls = State.get_class_substate(tuple(state_name.split(".")))
  1410. var_state = await self.get_state(var_state_cls)
  1411. setattr(var_state, var_name, value)
  1412. class OnLoadInternalState(State):
  1413. """Substate for handling on_load event enumeration.
  1414. This is a separate substate to avoid deserializing the entire state tree for every page navigation.
  1415. """
  1416. def on_load_internal(self) -> list[Event | EventSpec] | None:
  1417. """Queue on_load handlers for the current page.
  1418. Returns:
  1419. The list of events to queue for on load handling.
  1420. """
  1421. # Do not app.compile_()! It should be already compiled by now.
  1422. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1423. load_events = app.get_load_events(self.router.page.path)
  1424. if not load_events and self.is_hydrated:
  1425. return # Fast path for page-to-page navigation
  1426. if not load_events:
  1427. self.is_hydrated = True
  1428. return # Fast path for initial hydrate with no on_load events defined.
  1429. self.is_hydrated = False
  1430. return [
  1431. *fix_events(
  1432. load_events,
  1433. self.router.session.client_token,
  1434. router_data=self.router_data,
  1435. ),
  1436. State.set_is_hydrated(True), # type: ignore
  1437. ]
  1438. class StateProxy(wrapt.ObjectProxy):
  1439. """Proxy of a state instance to control mutability of vars for a background task.
  1440. Since a background task runs against a state instance without holding the
  1441. state_manager lock for the token, the reference may become stale if the same
  1442. state is modified by another event handler.
  1443. The proxy object ensures that writes to the state are blocked unless
  1444. explicitly entering a context which refreshes the state from state_manager
  1445. and holds the lock for the token until exiting the context. After exiting
  1446. the context, a StateUpdate may be emitted to the frontend to notify the
  1447. client of the state change.
  1448. A background task will be passed the `StateProxy` as `self`, so mutability
  1449. can be safely performed inside an `async with self` block.
  1450. class State(rx.State):
  1451. counter: int = 0
  1452. @rx.background
  1453. async def bg_increment(self):
  1454. await asyncio.sleep(1)
  1455. async with self:
  1456. self.counter += 1
  1457. """
  1458. def __init__(self, state_instance):
  1459. """Create a proxy for a state instance.
  1460. Args:
  1461. state_instance: The state instance to proxy.
  1462. """
  1463. super().__init__(state_instance)
  1464. # compile is not relevant to backend logic
  1465. self._self_app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1466. self._self_substate_path = state_instance.get_full_name().split(".")
  1467. self._self_actx = None
  1468. self._self_mutable = False
  1469. async def __aenter__(self) -> StateProxy:
  1470. """Enter the async context manager protocol.
  1471. Sets mutability to True and enters the `App.modify_state` async context,
  1472. which refreshes the state from state_manager and holds the lock for the
  1473. given state token until exiting the context.
  1474. Background tasks should avoid blocking calls while inside the context.
  1475. Returns:
  1476. This StateProxy instance in mutable mode.
  1477. """
  1478. self._self_actx = self._self_app.modify_state(
  1479. token=_substate_key(
  1480. self.__wrapped__.router.session.client_token,
  1481. self._self_substate_path,
  1482. )
  1483. )
  1484. mutable_state = await self._self_actx.__aenter__()
  1485. super().__setattr__(
  1486. "__wrapped__", mutable_state.get_substate(self._self_substate_path)
  1487. )
  1488. self._self_mutable = True
  1489. return self
  1490. async def __aexit__(self, *exc_info: Any) -> None:
  1491. """Exit the async context manager protocol.
  1492. Sets proxy mutability to False and persists any state changes.
  1493. Args:
  1494. exc_info: The exception info tuple.
  1495. """
  1496. if self._self_actx is None:
  1497. return
  1498. self._self_mutable = False
  1499. await self._self_actx.__aexit__(*exc_info)
  1500. self._self_actx = None
  1501. def __enter__(self):
  1502. """Enter the regular context manager protocol.
  1503. This is not supported for background tasks, and exists only to raise a more useful exception
  1504. when the StateProxy is used incorrectly.
  1505. Raises:
  1506. TypeError: always, because only async contextmanager protocol is supported.
  1507. """
  1508. raise TypeError("Background task must use `async with self` to modify state.")
  1509. def __exit__(self, *exc_info: Any) -> None:
  1510. """Exit the regular context manager protocol.
  1511. Args:
  1512. exc_info: The exception info tuple.
  1513. """
  1514. pass
  1515. def __getattr__(self, name: str) -> Any:
  1516. """Get the attribute from the underlying state instance.
  1517. Args:
  1518. name: The name of the attribute.
  1519. Returns:
  1520. The value of the attribute.
  1521. Raises:
  1522. ImmutableStateError: If the state is not in mutable mode.
  1523. """
  1524. if name in ["substates", "parent_state"] and not self._self_mutable:
  1525. raise ImmutableStateError(
  1526. "Background task StateProxy is immutable outside of a context "
  1527. "manager. Use `async with self` to modify state."
  1528. )
  1529. value = super().__getattr__(name)
  1530. if not name.startswith("_self_") and isinstance(value, MutableProxy):
  1531. # ensure mutations to these containers are blocked unless proxy is _mutable
  1532. return ImmutableMutableProxy(
  1533. wrapped=value.__wrapped__,
  1534. state=self, # type: ignore
  1535. field_name=value._self_field_name,
  1536. )
  1537. if isinstance(value, functools.partial) and value.args[0] is self.__wrapped__:
  1538. # Rebind event handler to the proxy instance
  1539. value = functools.partial(
  1540. value.func,
  1541. self,
  1542. *value.args[1:],
  1543. **value.keywords,
  1544. )
  1545. if isinstance(value, MethodType) and value.__self__ is self.__wrapped__:
  1546. # Rebind methods to the proxy instance
  1547. value = type(value)(value.__func__, self) # type: ignore
  1548. return value
  1549. def __setattr__(self, name: str, value: Any) -> None:
  1550. """Set the attribute on the underlying state instance.
  1551. If the attribute is internal, set it on the proxy instance instead.
  1552. Args:
  1553. name: The name of the attribute.
  1554. value: The value of the attribute.
  1555. Raises:
  1556. ImmutableStateError: If the state is not in mutable mode.
  1557. """
  1558. if (
  1559. name.startswith("_self_") # wrapper attribute
  1560. or self._self_mutable # lock held
  1561. # non-persisted state attribute
  1562. or name in self.__wrapped__.get_skip_vars()
  1563. ):
  1564. super().__setattr__(name, value)
  1565. return
  1566. raise ImmutableStateError(
  1567. "Background task StateProxy is immutable outside of a context "
  1568. "manager. Use `async with self` to modify state."
  1569. )
  1570. def get_substate(self, path: Sequence[str]) -> BaseState:
  1571. """Only allow substate access with lock held.
  1572. Args:
  1573. path: The path to the substate.
  1574. Returns:
  1575. The substate.
  1576. Raises:
  1577. ImmutableStateError: If the state is not in mutable mode.
  1578. """
  1579. if not self._self_mutable:
  1580. raise ImmutableStateError(
  1581. "Background task StateProxy is immutable outside of a context "
  1582. "manager. Use `async with self` to modify state."
  1583. )
  1584. return self.__wrapped__.get_substate(path)
  1585. async def get_state(self, state_cls: Type[BaseState]) -> BaseState:
  1586. """Get an instance of the state associated with this token.
  1587. Args:
  1588. state_cls: The class of the state.
  1589. Returns:
  1590. The state.
  1591. Raises:
  1592. ImmutableStateError: If the state is not in mutable mode.
  1593. """
  1594. if not self._self_mutable:
  1595. raise ImmutableStateError(
  1596. "Background task StateProxy is immutable outside of a context "
  1597. "manager. Use `async with self` to modify state."
  1598. )
  1599. return await self.__wrapped__.get_state(state_cls)
  1600. def _as_state_update(self, *args, **kwargs) -> StateUpdate:
  1601. """Temporarily allow mutability to access parent_state.
  1602. Args:
  1603. *args: The args to pass to the underlying state instance.
  1604. **kwargs: The kwargs to pass to the underlying state instance.
  1605. Returns:
  1606. The state update.
  1607. """
  1608. self._self_mutable = True
  1609. try:
  1610. return self.__wrapped__._as_state_update(*args, **kwargs)
  1611. finally:
  1612. self._self_mutable = False
  1613. class StateUpdate(Base):
  1614. """A state update sent to the frontend."""
  1615. # The state delta.
  1616. delta: Delta = {}
  1617. # Events to be added to the event queue.
  1618. events: List[Event] = []
  1619. # Whether this is the final state update for the event.
  1620. final: bool = True
  1621. class StateManager(Base, ABC):
  1622. """A class to manage many client states."""
  1623. # The state class to use.
  1624. state: Type[BaseState]
  1625. @classmethod
  1626. def create(cls, state: Type[BaseState]):
  1627. """Create a new state manager.
  1628. Args:
  1629. state: The state class to use.
  1630. Returns:
  1631. The state manager (either memory or redis).
  1632. """
  1633. redis = prerequisites.get_redis()
  1634. if redis is not None:
  1635. return StateManagerRedis(state=state, redis=redis)
  1636. return StateManagerMemory(state=state)
  1637. @abstractmethod
  1638. async def get_state(self, token: str) -> BaseState:
  1639. """Get the state for a token.
  1640. Args:
  1641. token: The token to get the state for.
  1642. Returns:
  1643. The state for the token.
  1644. """
  1645. pass
  1646. @abstractmethod
  1647. async def set_state(self, token: str, state: BaseState):
  1648. """Set the state for a token.
  1649. Args:
  1650. token: The token to set the state for.
  1651. state: The state to set.
  1652. """
  1653. pass
  1654. @abstractmethod
  1655. @contextlib.asynccontextmanager
  1656. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1657. """Modify the state for a token while holding exclusive lock.
  1658. Args:
  1659. token: The token to modify the state for.
  1660. Yields:
  1661. The state for the token.
  1662. """
  1663. yield self.state()
  1664. class StateManagerMemory(StateManager):
  1665. """A state manager that stores states in memory."""
  1666. # The mapping of client ids to states.
  1667. states: Dict[str, BaseState] = {}
  1668. # The mutex ensures the dict of mutexes is updated exclusively
  1669. _state_manager_lock = asyncio.Lock()
  1670. # The dict of mutexes for each client
  1671. _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({})
  1672. class Config:
  1673. """The Pydantic config."""
  1674. fields = {
  1675. "_states_locks": {"exclude": True},
  1676. }
  1677. async def get_state(self, token: str) -> BaseState:
  1678. """Get the state for a token.
  1679. Args:
  1680. token: The token to get the state for.
  1681. Returns:
  1682. The state for the token.
  1683. """
  1684. # Memory state manager ignores the substate suffix and always returns the top-level state.
  1685. token = _split_substate_key(token)[0]
  1686. if token not in self.states:
  1687. self.states[token] = self.state(_reflex_internal_init=True)
  1688. return self.states[token]
  1689. async def set_state(self, token: str, state: BaseState):
  1690. """Set the state for a token.
  1691. Args:
  1692. token: The token to set the state for.
  1693. state: The state to set.
  1694. """
  1695. pass
  1696. @contextlib.asynccontextmanager
  1697. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1698. """Modify the state for a token while holding exclusive lock.
  1699. Args:
  1700. token: The token to modify the state for.
  1701. Yields:
  1702. The state for the token.
  1703. """
  1704. # Memory state manager ignores the substate suffix and always returns the top-level state.
  1705. token = _split_substate_key(token)[0]
  1706. if token not in self._states_locks:
  1707. async with self._state_manager_lock:
  1708. if token not in self._states_locks:
  1709. self._states_locks[token] = asyncio.Lock()
  1710. async with self._states_locks[token]:
  1711. state = await self.get_state(token)
  1712. yield state
  1713. await self.set_state(token, state)
  1714. class StateManagerRedis(StateManager):
  1715. """A state manager that stores states in redis."""
  1716. # The redis client to use.
  1717. redis: Redis
  1718. # The token expiration time (s).
  1719. token_expiration: int = constants.Expiration.TOKEN
  1720. # The maximum time to hold a lock (ms).
  1721. lock_expiration: int = constants.Expiration.LOCK
  1722. # The keyspace subscription string when redis is waiting for lock to be released
  1723. _redis_notify_keyspace_events: str = (
  1724. "K" # Enable keyspace notifications (target a particular key)
  1725. "g" # For generic commands (DEL, EXPIRE, etc)
  1726. "x" # For expired events
  1727. "e" # For evicted events (i.e. maxmemory exceeded)
  1728. )
  1729. # These events indicate that a lock is no longer held
  1730. _redis_keyspace_lock_release_events: Set[bytes] = {
  1731. b"del",
  1732. b"expire",
  1733. b"expired",
  1734. b"evicted",
  1735. }
  1736. def _get_root_state(self, state: BaseState) -> BaseState:
  1737. """Chase parent_state pointers to find an instance of the top-level state.
  1738. Args:
  1739. state: The state to start from.
  1740. Returns:
  1741. An instance of the top-level state (self.state).
  1742. """
  1743. while type(state) != self.state and state.parent_state is not None:
  1744. state = state.parent_state
  1745. return state
  1746. async def _get_parent_state(self, token: str) -> BaseState | None:
  1747. """Get the parent state for the state requested in the token.
  1748. Args:
  1749. token: The token to get the state for (_substate_key).
  1750. Returns:
  1751. The parent state for the state requested by the token or None if there is no such parent.
  1752. """
  1753. parent_state = None
  1754. client_token, state_path = _split_substate_key(token)
  1755. parent_state_name = state_path.rpartition(".")[0]
  1756. if parent_state_name:
  1757. # Retrieve the parent state to populate event handlers onto this substate.
  1758. parent_state = await self.get_state(
  1759. token=_substate_key(client_token, parent_state_name),
  1760. top_level=False,
  1761. get_substates=False,
  1762. )
  1763. return parent_state
  1764. async def _populate_substates(
  1765. self,
  1766. token: str,
  1767. state: BaseState,
  1768. all_substates: bool = False,
  1769. ):
  1770. """Fetch and link substates for the given state instance.
  1771. There is no return value; the side-effect is that `state` will have `substates` populated,
  1772. and each substate will have its `parent_state` set to `state`.
  1773. Args:
  1774. token: The token to get the state for.
  1775. state: The state instance to populate substates for.
  1776. all_substates: Whether to fetch all substates or just required substates.
  1777. """
  1778. client_token, _ = _split_substate_key(token)
  1779. if all_substates:
  1780. # All substates are requested.
  1781. fetch_substates = state.get_substates()
  1782. else:
  1783. # Only _potentially_dirty_substates need to be fetched to recalc computed vars.
  1784. fetch_substates = state._potentially_dirty_substates()
  1785. tasks = {}
  1786. # Retrieve the necessary substates from redis.
  1787. for substate_cls in fetch_substates:
  1788. substate_name = substate_cls.get_name()
  1789. tasks[substate_name] = asyncio.create_task(
  1790. self.get_state(
  1791. token=_substate_key(client_token, substate_cls),
  1792. top_level=False,
  1793. get_substates=all_substates,
  1794. parent_state=state,
  1795. )
  1796. )
  1797. for substate_name, substate_task in tasks.items():
  1798. state.substates[substate_name] = await substate_task
  1799. async def get_state(
  1800. self,
  1801. token: str,
  1802. top_level: bool = True,
  1803. get_substates: bool = True,
  1804. parent_state: BaseState | None = None,
  1805. ) -> BaseState:
  1806. """Get the state for a token.
  1807. Args:
  1808. token: The token to get the state for.
  1809. top_level: If true, return an instance of the top-level state (self.state).
  1810. get_substates: If true, also retrieve substates.
  1811. parent_state: If provided, use this parent_state instead of getting it from redis.
  1812. Returns:
  1813. The state for the token.
  1814. Raises:
  1815. RuntimeError: when the state_cls is not specified in the token
  1816. """
  1817. # Split the actual token from the fully qualified substate name.
  1818. _, state_path = _split_substate_key(token)
  1819. if state_path:
  1820. # Get the State class associated with the given path.
  1821. state_cls = self.state.get_class_substate(tuple(state_path.split(".")))
  1822. else:
  1823. raise RuntimeError(
  1824. "StateManagerRedis requires token to be specified in the form of {token}_{state_full_name}"
  1825. )
  1826. # Fetch the serialized substate from redis.
  1827. redis_state = await self.redis.get(token)
  1828. if redis_state is not None:
  1829. # Deserialize the substate.
  1830. state = cloudpickle.loads(redis_state)
  1831. # Populate parent state if missing and requested.
  1832. if parent_state is None:
  1833. parent_state = await self._get_parent_state(token)
  1834. # Set up Bidirectional linkage between this state and its parent.
  1835. if parent_state is not None:
  1836. parent_state.substates[state.get_name()] = state
  1837. state.parent_state = parent_state
  1838. # Populate substates if requested.
  1839. await self._populate_substates(token, state, all_substates=get_substates)
  1840. # To retain compatibility with previous implementation, by default, we return
  1841. # the top-level state by chasing `parent_state` pointers up the tree.
  1842. if top_level:
  1843. return self._get_root_state(state)
  1844. return state
  1845. # TODO: dedupe the following logic with the above block
  1846. # Key didn't exist so we have to create a new instance for this token.
  1847. if parent_state is None:
  1848. parent_state = await self._get_parent_state(token)
  1849. # Instantiate the new state class (but don't persist it yet).
  1850. state = state_cls(
  1851. parent_state=parent_state,
  1852. init_substates=False,
  1853. _reflex_internal_init=True,
  1854. )
  1855. # Set up Bidirectional linkage between this state and its parent.
  1856. if parent_state is not None:
  1857. parent_state.substates[state.get_name()] = state
  1858. state.parent_state = parent_state
  1859. # Populate substates for the newly created state.
  1860. await self._populate_substates(token, state, all_substates=get_substates)
  1861. # To retain compatibility with previous implementation, by default, we return
  1862. # the top-level state by chasing `parent_state` pointers up the tree.
  1863. if top_level:
  1864. return self._get_root_state(state)
  1865. return state
  1866. async def set_state(
  1867. self,
  1868. token: str,
  1869. state: BaseState,
  1870. lock_id: bytes | None = None,
  1871. ):
  1872. """Set the state for a token.
  1873. Args:
  1874. token: The token to set the state for.
  1875. state: The state to set.
  1876. lock_id: If provided, the lock_key must be set to this value to set the state.
  1877. Raises:
  1878. LockExpiredError: If lock_id is provided and the lock for the token is not held by that ID.
  1879. RuntimeError: If the state instance doesn't match the state name in the token.
  1880. """
  1881. # Check that we're holding the lock.
  1882. if (
  1883. lock_id is not None
  1884. and await self.redis.get(self._lock_key(token)) != lock_id
  1885. ):
  1886. raise LockExpiredError(
  1887. f"Lock expired for token {token} while processing. Consider increasing "
  1888. f"`app.state_manager.lock_expiration` (currently {self.lock_expiration}) "
  1889. "or use `@rx.background` decorator for long-running tasks."
  1890. )
  1891. client_token, substate_name = _split_substate_key(token)
  1892. # If the substate name on the token doesn't match the instance name, it cannot have a parent.
  1893. if state.parent_state is not None and state.get_full_name() != substate_name:
  1894. raise RuntimeError(
  1895. f"Cannot `set_state` with mismatching token {token} and substate {state.get_full_name()}."
  1896. )
  1897. # Recursively set_state on all known substates.
  1898. tasks = []
  1899. for substate in state.substates.values():
  1900. tasks.append(
  1901. asyncio.create_task(
  1902. self.set_state(
  1903. token=_substate_key(client_token, substate),
  1904. state=substate,
  1905. lock_id=lock_id,
  1906. )
  1907. )
  1908. )
  1909. # Persist only the given state (parents or substates are excluded by BaseState.__getstate__).
  1910. if state._get_was_touched():
  1911. await self.redis.set(
  1912. _substate_key(client_token, state),
  1913. cloudpickle.dumps(state),
  1914. ex=self.token_expiration,
  1915. )
  1916. # Wait for substates to be persisted.
  1917. for t in tasks:
  1918. await t
  1919. @contextlib.asynccontextmanager
  1920. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1921. """Modify the state for a token while holding exclusive lock.
  1922. Args:
  1923. token: The token to modify the state for.
  1924. Yields:
  1925. The state for the token.
  1926. """
  1927. async with self._lock(token) as lock_id:
  1928. state = await self.get_state(token)
  1929. yield state
  1930. await self.set_state(token, state, lock_id)
  1931. @staticmethod
  1932. def _lock_key(token: str) -> bytes:
  1933. """Get the redis key for a token's lock.
  1934. Args:
  1935. token: The token to get the lock key for.
  1936. Returns:
  1937. The redis lock key for the token.
  1938. """
  1939. # All substates share the same lock domain, so ignore any substate path suffix.
  1940. client_token = _split_substate_key(token)[0]
  1941. return f"{client_token}_lock".encode()
  1942. async def _try_get_lock(self, lock_key: bytes, lock_id: bytes) -> bool | None:
  1943. """Try to get a redis lock for a token.
  1944. Args:
  1945. lock_key: The redis key for the lock.
  1946. lock_id: The ID of the lock.
  1947. Returns:
  1948. True if the lock was obtained.
  1949. """
  1950. return await self.redis.set(
  1951. lock_key,
  1952. lock_id,
  1953. px=self.lock_expiration,
  1954. nx=True, # only set if it doesn't exist
  1955. )
  1956. async def _wait_lock(self, lock_key: bytes, lock_id: bytes) -> None:
  1957. """Wait for a redis lock to be released via pubsub.
  1958. Coroutine will not return until the lock is obtained.
  1959. Args:
  1960. lock_key: The redis key for the lock.
  1961. lock_id: The ID of the lock.
  1962. """
  1963. state_is_locked = False
  1964. lock_key_channel = f"__keyspace@0__:{lock_key.decode()}"
  1965. # Enable keyspace notifications for the lock key, so we know when it is available.
  1966. await self.redis.config_set(
  1967. "notify-keyspace-events", self._redis_notify_keyspace_events
  1968. )
  1969. async with self.redis.pubsub() as pubsub:
  1970. await pubsub.psubscribe(lock_key_channel)
  1971. while not state_is_locked:
  1972. # wait for the lock to be released
  1973. while True:
  1974. if not await self.redis.exists(lock_key):
  1975. break # key was removed, try to get the lock again
  1976. message = await pubsub.get_message(
  1977. ignore_subscribe_messages=True,
  1978. timeout=self.lock_expiration / 1000.0,
  1979. )
  1980. if message is None:
  1981. continue
  1982. if message["data"] in self._redis_keyspace_lock_release_events:
  1983. break
  1984. state_is_locked = await self._try_get_lock(lock_key, lock_id)
  1985. @contextlib.asynccontextmanager
  1986. async def _lock(self, token: str):
  1987. """Obtain a redis lock for a token.
  1988. Args:
  1989. token: The token to obtain a lock for.
  1990. Yields:
  1991. The ID of the lock (to be passed to set_state).
  1992. Raises:
  1993. LockExpiredError: If the lock has expired while processing the event.
  1994. """
  1995. lock_key = self._lock_key(token)
  1996. lock_id = uuid.uuid4().hex.encode()
  1997. if not await self._try_get_lock(lock_key, lock_id):
  1998. # Missed the fast-path to get lock, subscribe for lock delete/expire events
  1999. await self._wait_lock(lock_key, lock_id)
  2000. state_is_locked = True
  2001. try:
  2002. yield lock_id
  2003. except LockExpiredError:
  2004. state_is_locked = False
  2005. raise
  2006. finally:
  2007. if state_is_locked:
  2008. # only delete our lock
  2009. await self.redis.delete(lock_key)
  2010. async def close(self):
  2011. """Explicitly close the redis connection and connection_pool.
  2012. It is necessary in testing scenarios to close between asyncio test cases
  2013. to avoid having lingering redis connections associated with event loops
  2014. that will be closed (each test case uses its own event loop).
  2015. Note: Connections will be automatically reopened when needed.
  2016. """
  2017. await self.redis.close(close_connection_pool=True)
  2018. def get_state_manager() -> StateManager:
  2019. """Get the state manager for the app that is currently running.
  2020. Returns:
  2021. The state manager.
  2022. """
  2023. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  2024. return app.state_manager
  2025. class ClientStorageBase:
  2026. """Base class for client-side storage."""
  2027. def options(self) -> dict[str, Any]:
  2028. """Get the options for the storage.
  2029. Returns:
  2030. All set options for the storage (not None).
  2031. """
  2032. return {
  2033. format.to_camel_case(k): v for k, v in vars(self).items() if v is not None
  2034. }
  2035. class Cookie(ClientStorageBase, str):
  2036. """Represents a state Var that is stored as a cookie in the browser."""
  2037. name: str | None
  2038. path: str
  2039. max_age: int | None
  2040. domain: str | None
  2041. secure: bool | None
  2042. same_site: str
  2043. def __new__(
  2044. cls,
  2045. object: Any = "",
  2046. encoding: str | None = None,
  2047. errors: str | None = None,
  2048. /,
  2049. name: str | None = None,
  2050. path: str = "/",
  2051. max_age: int | None = None,
  2052. domain: str | None = None,
  2053. secure: bool | None = None,
  2054. same_site: str = "lax",
  2055. ):
  2056. """Create a client-side Cookie (str).
  2057. Args:
  2058. object: The initial object.
  2059. encoding: The encoding to use.
  2060. errors: The error handling scheme to use.
  2061. name: The name of the cookie on the client side.
  2062. path: Cookie path. Use / as the path if the cookie should be accessible on all pages.
  2063. max_age: Relative max age of the cookie in seconds from when the client receives it.
  2064. domain: Domain for the cookie (sub.domain.com or .allsubdomains.com).
  2065. secure: Is the cookie only accessible through HTTPS?
  2066. same_site: Whether the cookie is sent with third party requests.
  2067. One of (true|false|none|lax|strict)
  2068. Returns:
  2069. The client-side Cookie object.
  2070. Note: expires (absolute Date) is not supported at this time.
  2071. """
  2072. if encoding or errors:
  2073. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  2074. else:
  2075. inst = super().__new__(cls, object)
  2076. inst.name = name
  2077. inst.path = path
  2078. inst.max_age = max_age
  2079. inst.domain = domain
  2080. inst.secure = secure
  2081. inst.same_site = same_site
  2082. return inst
  2083. class LocalStorage(ClientStorageBase, str):
  2084. """Represents a state Var that is stored in localStorage in the browser."""
  2085. name: str | None
  2086. sync: bool = False
  2087. def __new__(
  2088. cls,
  2089. object: Any = "",
  2090. encoding: str | None = None,
  2091. errors: str | None = None,
  2092. /,
  2093. name: str | None = None,
  2094. sync: bool = False,
  2095. ) -> "LocalStorage":
  2096. """Create a client-side localStorage (str).
  2097. Args:
  2098. object: The initial object.
  2099. encoding: The encoding to use.
  2100. errors: The error handling scheme to use.
  2101. name: The name of the storage key on the client side.
  2102. sync: Whether changes should be propagated to other tabs.
  2103. Returns:
  2104. The client-side localStorage object.
  2105. """
  2106. if encoding or errors:
  2107. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  2108. else:
  2109. inst = super().__new__(cls, object)
  2110. inst.name = name
  2111. inst.sync = sync
  2112. return inst
  2113. class MutableProxy(wrapt.ObjectProxy):
  2114. """A proxy for a mutable object that tracks changes."""
  2115. # Methods on wrapped objects which should mark the state as dirty.
  2116. __mark_dirty_attrs__ = set(
  2117. [
  2118. "add",
  2119. "append",
  2120. "clear",
  2121. "difference_update",
  2122. "discard",
  2123. "extend",
  2124. "insert",
  2125. "intersection_update",
  2126. "pop",
  2127. "popitem",
  2128. "remove",
  2129. "reverse",
  2130. "setdefault",
  2131. "sort",
  2132. "symmetric_difference_update",
  2133. "update",
  2134. ]
  2135. )
  2136. # Methods on wrapped objects might return mutable objects that should be tracked.
  2137. __wrap_mutable_attrs__ = set(
  2138. [
  2139. "get",
  2140. "setdefault",
  2141. ]
  2142. )
  2143. __mutable_types__ = (list, dict, set, Base)
  2144. def __init__(self, wrapped: Any, state: BaseState, field_name: str):
  2145. """Create a proxy for a mutable object that tracks changes.
  2146. Args:
  2147. wrapped: The object to proxy.
  2148. state: The state to mark dirty when the object is changed.
  2149. field_name: The name of the field on the state associated with the
  2150. wrapped object.
  2151. """
  2152. super().__init__(wrapped)
  2153. self._self_state = state
  2154. self._self_field_name = field_name
  2155. def _mark_dirty(
  2156. self,
  2157. wrapped=None,
  2158. instance=None,
  2159. args=tuple(),
  2160. kwargs=None,
  2161. ) -> Any:
  2162. """Mark the state as dirty, then call a wrapped function.
  2163. Intended for use with `FunctionWrapper` from the `wrapt` library.
  2164. Args:
  2165. wrapped: The wrapped function.
  2166. instance: The instance of the wrapped function.
  2167. args: The args for the wrapped function.
  2168. kwargs: The kwargs for the wrapped function.
  2169. Returns:
  2170. The result of the wrapped function.
  2171. """
  2172. self._self_state.dirty_vars.add(self._self_field_name)
  2173. self._self_state._mark_dirty()
  2174. if wrapped is not None:
  2175. return wrapped(*args, **(kwargs or {}))
  2176. def _wrap_recursive(self, value: Any) -> Any:
  2177. """Wrap a value recursively if it is mutable.
  2178. Args:
  2179. value: The value to wrap.
  2180. Returns:
  2181. The wrapped value.
  2182. """
  2183. if isinstance(value, self.__mutable_types__):
  2184. return type(self)(
  2185. wrapped=value,
  2186. state=self._self_state,
  2187. field_name=self._self_field_name,
  2188. )
  2189. return value
  2190. def _wrap_recursive_decorator(self, wrapped, instance, args, kwargs) -> Any:
  2191. """Wrap a function that returns a possibly mutable value.
  2192. Intended for use with `FunctionWrapper` from the `wrapt` library.
  2193. Args:
  2194. wrapped: The wrapped function.
  2195. instance: The instance of the wrapped function.
  2196. args: The args for the wrapped function.
  2197. kwargs: The kwargs for the wrapped function.
  2198. Returns:
  2199. The result of the wrapped function (possibly wrapped in a MutableProxy).
  2200. """
  2201. return self._wrap_recursive(wrapped(*args, **kwargs))
  2202. def __getattr__(self, __name: str) -> Any:
  2203. """Get the attribute on the proxied object and return a proxy if mutable.
  2204. Args:
  2205. __name: The name of the attribute.
  2206. Returns:
  2207. The attribute value.
  2208. """
  2209. value = super().__getattr__(__name)
  2210. if callable(value):
  2211. if __name in self.__mark_dirty_attrs__:
  2212. # Wrap special callables, like "append", which should mark state dirty.
  2213. value = wrapt.FunctionWrapper(value, self._mark_dirty)
  2214. if __name in self.__wrap_mutable_attrs__:
  2215. # Wrap methods that may return mutable objects tied to the state.
  2216. value = wrapt.FunctionWrapper(
  2217. value,
  2218. self._wrap_recursive_decorator,
  2219. )
  2220. if isinstance(value, self.__mutable_types__) and __name not in (
  2221. "__wrapped__",
  2222. "_self_state",
  2223. ):
  2224. # Recursively wrap mutable attribute values retrieved through this proxy.
  2225. return self._wrap_recursive(value)
  2226. return value
  2227. def __getitem__(self, key) -> Any:
  2228. """Get the item on the proxied object and return a proxy if mutable.
  2229. Args:
  2230. key: The key of the item.
  2231. Returns:
  2232. The item value.
  2233. """
  2234. value = super().__getitem__(key)
  2235. # Recursively wrap mutable items retrieved through this proxy.
  2236. return self._wrap_recursive(value)
  2237. def __iter__(self) -> Any:
  2238. """Iterate over the proxied object and return a proxy if mutable.
  2239. Yields:
  2240. Each item value (possibly wrapped in MutableProxy).
  2241. """
  2242. for value in super().__iter__():
  2243. # Recursively wrap mutable items retrieved through this proxy.
  2244. yield self._wrap_recursive(value)
  2245. def __delattr__(self, name):
  2246. """Delete the attribute on the proxied object and mark state dirty.
  2247. Args:
  2248. name: The name of the attribute.
  2249. """
  2250. self._mark_dirty(super().__delattr__, args=(name,))
  2251. def __delitem__(self, key):
  2252. """Delete the item on the proxied object and mark state dirty.
  2253. Args:
  2254. key: The key of the item.
  2255. """
  2256. self._mark_dirty(super().__delitem__, args=(key,))
  2257. def __setitem__(self, key, value):
  2258. """Set the item on the proxied object and mark state dirty.
  2259. Args:
  2260. key: The key of the item.
  2261. value: The value of the item.
  2262. """
  2263. self._mark_dirty(super().__setitem__, args=(key, value))
  2264. def __setattr__(self, name, value):
  2265. """Set the attribute on the proxied object and mark state dirty.
  2266. If the attribute starts with "_self_", then the state is NOT marked
  2267. dirty as these are internal proxy attributes.
  2268. Args:
  2269. name: The name of the attribute.
  2270. value: The value of the attribute.
  2271. """
  2272. if name.startswith("_self_"):
  2273. # Special case attributes of the proxy itself, not applied to the wrapped object.
  2274. super().__setattr__(name, value)
  2275. return
  2276. self._mark_dirty(super().__setattr__, args=(name, value))
  2277. def __copy__(self) -> Any:
  2278. """Return a copy of the proxy.
  2279. Returns:
  2280. A copy of the wrapped object, unconnected to the proxy.
  2281. """
  2282. return copy.copy(self.__wrapped__)
  2283. def __deepcopy__(self, memo=None) -> Any:
  2284. """Return a deepcopy of the proxy.
  2285. Args:
  2286. memo: The memo dict to use for the deepcopy.
  2287. Returns:
  2288. A deepcopy of the wrapped object, unconnected to the proxy.
  2289. """
  2290. return copy.deepcopy(self.__wrapped__, memo=memo)
  2291. def __reduce_ex__(self, protocol_version):
  2292. """Get the state for redis serialization.
  2293. This method is called by cloudpickle to serialize the object.
  2294. It explicitly serializes the wrapped object, stripping off the mutable proxy.
  2295. Args:
  2296. protocol_version: The protocol version.
  2297. Returns:
  2298. Tuple of (wrapped class, empty args, class __getstate__)
  2299. """
  2300. return self.__wrapped__.__reduce_ex__(protocol_version)
  2301. @serializer
  2302. def serialize_mutable_proxy(mp: MutableProxy) -> SerializedType:
  2303. """Serialize the wrapped value of a MutableProxy.
  2304. Args:
  2305. mp: The MutableProxy to serialize.
  2306. Returns:
  2307. The serialized wrapped object.
  2308. Raises:
  2309. ValueError: when the wrapped object is not serializable.
  2310. """
  2311. value = serialize(mp.__wrapped__)
  2312. if value is None:
  2313. raise ValueError(f"Cannot serialize {type(mp.__wrapped__)}")
  2314. return value
  2315. class ImmutableMutableProxy(MutableProxy):
  2316. """A proxy for a mutable object that tracks changes.
  2317. This wrapper comes from StateProxy, and will raise an exception if an attempt is made
  2318. to modify the wrapped object when the StateProxy is immutable.
  2319. """
  2320. def _mark_dirty(
  2321. self,
  2322. wrapped=None,
  2323. instance=None,
  2324. args=tuple(),
  2325. kwargs=None,
  2326. ) -> Any:
  2327. """Raise an exception when an attempt is made to modify the object.
  2328. Intended for use with `FunctionWrapper` from the `wrapt` library.
  2329. Args:
  2330. wrapped: The wrapped function.
  2331. instance: The instance of the wrapped function.
  2332. args: The args for the wrapped function.
  2333. kwargs: The kwargs for the wrapped function.
  2334. Returns:
  2335. The result of the wrapped function.
  2336. Raises:
  2337. ImmutableStateError: if the StateProxy is not mutable.
  2338. """
  2339. if not self._self_state._self_mutable:
  2340. raise ImmutableStateError(
  2341. "Background task StateProxy is immutable outside of a context "
  2342. "manager. Use `async with self` to modify state."
  2343. )
  2344. return super()._mark_dirty(
  2345. wrapped=wrapped, instance=instance, args=args, kwargs=kwargs
  2346. )
  2347. def code_uses_state_contexts(javascript_code: str) -> bool:
  2348. """Check if the rendered Javascript uses state contexts.
  2349. Args:
  2350. javascript_code: The Javascript code to check.
  2351. Returns:
  2352. True if the code attempts to access a member of StateContexts.
  2353. """
  2354. return bool("useContext(StateContexts" in javascript_code)