state.py 108 KB

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