state.py 103 KB

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