state.py 117 KB

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