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