state.py 103 KB

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