state.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  1. """Define the reflex state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import builtins
  5. import contextlib
  6. import copy
  7. import dataclasses
  8. import functools
  9. import inspect
  10. import pickle
  11. import sys
  12. import typing
  13. import warnings
  14. from abc import ABC
  15. from collections.abc import AsyncIterator, Callable, Sequence
  16. from hashlib import md5
  17. from types import FunctionType
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. BinaryIO,
  22. ClassVar,
  23. TypeVar,
  24. cast,
  25. get_args,
  26. get_type_hints,
  27. )
  28. import pydantic.v1 as pydantic
  29. from pydantic import BaseModel as BaseModelV2
  30. from pydantic.v1 import BaseModel as BaseModelV1
  31. from pydantic.v1.fields import ModelField
  32. from rich.markup import escape
  33. from typing_extensions import Self
  34. import reflex.istate.dynamic
  35. from reflex import constants, event
  36. from reflex.base import Base
  37. from reflex.config import PerformanceMode, environment
  38. from reflex.event import (
  39. BACKGROUND_TASK_MARKER,
  40. Event,
  41. EventHandler,
  42. EventSpec,
  43. fix_events,
  44. )
  45. from reflex.istate.data import RouterData
  46. from reflex.istate.proxy import ImmutableMutableProxy as ImmutableMutableProxy
  47. from reflex.istate.proxy import MutableProxy, StateProxy
  48. from reflex.istate.storage import ClientStorageBase
  49. from reflex.model import Model
  50. from reflex.utils import console, format, prerequisites, types
  51. from reflex.utils.exceptions import (
  52. ComputedVarShadowsBaseVarsError,
  53. ComputedVarShadowsStateVarError,
  54. DynamicComponentInvalidSignatureError,
  55. DynamicRouteArgShadowsStateVarError,
  56. EventHandlerShadowsBuiltInStateMethodError,
  57. ReflexRuntimeError,
  58. SetUndefinedStateVarError,
  59. StateMismatchError,
  60. StateSchemaMismatchError,
  61. StateSerializationError,
  62. StateTooLargeError,
  63. UnretrievableVarValueError,
  64. )
  65. from reflex.utils.exceptions import ImmutableStateError as ImmutableStateError
  66. from reflex.utils.exec import is_testing_env
  67. from reflex.utils.types import (
  68. _isinstance,
  69. get_origin,
  70. is_union,
  71. true_type_for_pydantic_field,
  72. value_inside_optional,
  73. )
  74. from reflex.vars import VarData
  75. from reflex.vars.base import (
  76. ComputedVar,
  77. DynamicRouteVar,
  78. Var,
  79. computed_var,
  80. dispatch,
  81. get_unique_variable_name,
  82. is_computed_var,
  83. )
  84. if TYPE_CHECKING:
  85. from reflex.components.component import Component
  86. Delta = dict[str, Any]
  87. var = computed_var
  88. if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF:
  89. # If the state is this large, it's considered a performance issue.
  90. TOO_LARGE_SERIALIZED_STATE = environment.REFLEX_STATE_SIZE_LIMIT.get() * 1024
  91. # Only warn about each state class size once.
  92. _WARNED_ABOUT_STATE_SIZE: set[str] = set()
  93. # Errors caught during pickling of state
  94. HANDLED_PICKLE_ERRORS = (
  95. pickle.PicklingError,
  96. AttributeError,
  97. IndexError,
  98. TypeError,
  99. ValueError,
  100. )
  101. # For BaseState.get_var_value
  102. VAR_TYPE = TypeVar("VAR_TYPE")
  103. def _no_chain_background_task(
  104. state_cls: type[BaseState], name: str, fn: Callable
  105. ) -> Callable:
  106. """Protect against directly chaining a background task from another event handler.
  107. Args:
  108. state_cls: The state class that the event handler is in.
  109. name: The name of the background task.
  110. fn: The background task coroutine function / generator.
  111. Returns:
  112. A compatible coroutine function / generator that raises a runtime error.
  113. Raises:
  114. TypeError: If the background task is not async.
  115. """
  116. call = f"{state_cls.__name__}.{name}"
  117. message = (
  118. f"Cannot directly call background task {name!r}, use "
  119. f"`yield {call}` or `return {call}` instead."
  120. )
  121. if inspect.iscoroutinefunction(fn):
  122. async def _no_chain_background_task_co(*args, **kwargs):
  123. raise RuntimeError(message)
  124. return _no_chain_background_task_co
  125. if inspect.isasyncgenfunction(fn):
  126. async def _no_chain_background_task_gen(*args, **kwargs):
  127. yield
  128. raise RuntimeError(message)
  129. return _no_chain_background_task_gen
  130. raise TypeError(f"{fn} is marked as a background task, but is not async.")
  131. def _substate_key(
  132. token: str,
  133. state_cls_or_name: BaseState | type[BaseState] | str | Sequence[str],
  134. ) -> str:
  135. """Get the substate key.
  136. Args:
  137. token: The token of the state.
  138. state_cls_or_name: The state class/instance or name or sequence of name parts.
  139. Returns:
  140. The substate key.
  141. """
  142. if isinstance(state_cls_or_name, BaseState) or (
  143. isinstance(state_cls_or_name, type) and issubclass(state_cls_or_name, BaseState)
  144. ):
  145. state_cls_or_name = state_cls_or_name.get_full_name()
  146. elif isinstance(state_cls_or_name, (list, tuple)):
  147. state_cls_or_name = ".".join(state_cls_or_name)
  148. return f"{token}_{state_cls_or_name}"
  149. def _split_substate_key(substate_key: str) -> tuple[str, str]:
  150. """Split the substate key into token and state name.
  151. Args:
  152. substate_key: The substate key.
  153. Returns:
  154. Tuple of token and state name.
  155. """
  156. token, _, state_name = substate_key.partition("_")
  157. return token, state_name
  158. @dataclasses.dataclass(frozen=True, init=False)
  159. class EventHandlerSetVar(EventHandler):
  160. """A special event handler to wrap setvar functionality."""
  161. state_cls: type[BaseState] = dataclasses.field(init=False)
  162. def __init__(self, state_cls: type[BaseState]):
  163. """Initialize the EventHandlerSetVar.
  164. Args:
  165. state_cls: The state class that vars will be set on.
  166. """
  167. super().__init__(
  168. fn=type(self).setvar,
  169. state_full_name=state_cls.get_full_name(),
  170. )
  171. object.__setattr__(self, "state_cls", state_cls)
  172. def setvar(self, var_name: str, value: Any):
  173. """Set the state variable to the value of the event.
  174. Note: `self` here will be an instance of the state, not EventHandlerSetVar.
  175. Args:
  176. var_name: The name of the variable to set.
  177. value: The value to set the variable to.
  178. """
  179. getattr(self, constants.SETTER_PREFIX + var_name)(value)
  180. def __call__(self, *args: Any) -> EventSpec:
  181. """Performs pre-checks and munging on the provided args that will become an EventSpec.
  182. Args:
  183. *args: The event args.
  184. Returns:
  185. The (partial) EventSpec that will be used to create the event to setvar.
  186. Raises:
  187. AttributeError: If the given Var name does not exist on the state.
  188. EventHandlerValueError: If the given Var name is not a str
  189. NotImplementedError: If the setter for the given Var is async
  190. """
  191. from reflex.utils.exceptions import EventHandlerValueError
  192. if args:
  193. if not isinstance(args[0], str):
  194. raise EventHandlerValueError(
  195. f"Var name must be passed as a string, got {args[0]!r}"
  196. )
  197. handler = getattr(self.state_cls, constants.SETTER_PREFIX + args[0], None)
  198. # Check that the requested Var setter exists on the State at compile time.
  199. if handler is None:
  200. raise AttributeError(
  201. f"Variable `{args[0]}` cannot be set on `{self.state_cls.get_full_name()}`"
  202. )
  203. if asyncio.iscoroutinefunction(handler.fn):
  204. raise NotImplementedError(
  205. f"Setter for {args[0]} is async, which is not supported."
  206. )
  207. return super().__call__(*args)
  208. if TYPE_CHECKING:
  209. from pydantic.v1.fields import ModelField
  210. def _unwrap_field_type(type_: types.GenericType) -> type:
  211. """Unwrap rx.Field type annotations.
  212. Args:
  213. type_: The type to unwrap.
  214. Returns:
  215. The unwrapped type.
  216. """
  217. from reflex.vars import Field
  218. if get_origin(type_) is Field:
  219. return get_args(type_)[0]
  220. return type_
  221. def get_var_for_field(cls: type[BaseState], f: ModelField) -> Var:
  222. """Get a Var instance for a Pydantic field.
  223. Args:
  224. cls: The state class.
  225. f: The Pydantic field.
  226. Returns:
  227. The Var instance.
  228. """
  229. name = f.name + "_rx_state_"
  230. field_name = format.format_state_name(cls.get_full_name()) + "." + name
  231. return dispatch(
  232. field_name=field_name,
  233. var_data=VarData.from_state(cls, f.name),
  234. result_var_type=_unwrap_field_type(true_type_for_pydantic_field(f)),
  235. )
  236. async def _resolve_delta(delta: Delta) -> Delta:
  237. """Await all coroutines in the delta.
  238. Args:
  239. delta: The delta to process.
  240. Returns:
  241. The same delta dict with all coroutines resolved to their return value.
  242. """
  243. tasks = {}
  244. for state_name, state_delta in delta.items():
  245. for var_name, value in state_delta.items():
  246. if asyncio.iscoroutine(value):
  247. tasks[state_name, var_name] = asyncio.create_task(value)
  248. for (state_name, var_name), task in tasks.items():
  249. delta[state_name][var_name] = await task
  250. return delta
  251. all_base_state_classes: dict[str, None] = {}
  252. class BaseState(Base, ABC, extra=pydantic.Extra.allow):
  253. """The state of the app."""
  254. # A map from the var name to the var.
  255. vars: ClassVar[builtins.dict[str, Var]] = {}
  256. # The base vars of the class.
  257. base_vars: ClassVar[builtins.dict[str, Var]] = {}
  258. # The computed vars of the class.
  259. computed_vars: ClassVar[builtins.dict[str, ComputedVar]] = {}
  260. # Vars inherited by the parent state.
  261. inherited_vars: ClassVar[builtins.dict[str, Var]] = {}
  262. # Backend base vars that are never sent to the client.
  263. backend_vars: ClassVar[builtins.dict[str, Any]] = {}
  264. # Backend base vars inherited
  265. inherited_backend_vars: ClassVar[builtins.dict[str, Any]] = {}
  266. # The event handlers.
  267. event_handlers: ClassVar[builtins.dict[str, EventHandler]] = {}
  268. # A set of subclassses of this class.
  269. class_subclasses: ClassVar[set[type[BaseState]]] = set()
  270. # Mapping of var name to set of (state_full_name, var_name) that depend on it.
  271. _var_dependencies: ClassVar[builtins.dict[str, set[tuple[str, str]]]] = {}
  272. # Set of vars which always need to be recomputed
  273. _always_dirty_computed_vars: ClassVar[set[str]] = set()
  274. # Set of substates which always need to be recomputed
  275. _always_dirty_substates: ClassVar[set[str]] = set()
  276. # Set of states which might need to be recomputed if vars in this state change.
  277. _potentially_dirty_states: ClassVar[set[str]] = set()
  278. # The parent state.
  279. parent_state: BaseState | None = None
  280. # The substates of the state.
  281. substates: builtins.dict[str, BaseState] = {}
  282. # The set of dirty vars.
  283. dirty_vars: set[str] = set()
  284. # The set of dirty substates.
  285. dirty_substates: set[str] = set()
  286. # The routing path that triggered the state
  287. router_data: builtins.dict[str, Any] = {}
  288. # Per-instance copy of backend base variable values
  289. _backend_vars: builtins.dict[str, Any] = {}
  290. # The router data for the current page
  291. router: RouterData = RouterData()
  292. # Whether the state has ever been touched since instantiation.
  293. _was_touched: bool = False
  294. # Whether this state class is a mixin and should not be instantiated.
  295. _mixin: ClassVar[bool] = False
  296. # A special event handler for setting base vars.
  297. setvar: ClassVar[EventHandler]
  298. def __init__(
  299. self,
  300. parent_state: BaseState | None = None,
  301. init_substates: bool = True,
  302. _reflex_internal_init: bool = False,
  303. **kwargs,
  304. ):
  305. """Initialize the state.
  306. DO NOT INSTANTIATE STATE CLASSES DIRECTLY! Use StateManager.get_state() instead.
  307. Args:
  308. parent_state: The parent state.
  309. init_substates: Whether to initialize the substates in this instance.
  310. _reflex_internal_init: A flag to indicate that the state is being initialized by the framework.
  311. **kwargs: The kwargs to set as attributes on the state.
  312. Raises:
  313. ReflexRuntimeError: If the state is instantiated directly by end user.
  314. """
  315. from reflex.utils.exceptions import ReflexRuntimeError
  316. if not _reflex_internal_init and not is_testing_env():
  317. raise ReflexRuntimeError(
  318. "State classes should not be instantiated directly in a Reflex app. "
  319. "See https://reflex.dev/docs/state/ for further information."
  320. )
  321. if type(self)._mixin:
  322. raise ReflexRuntimeError(
  323. f"{type(self).__name__} is a state mixin and cannot be instantiated directly."
  324. )
  325. kwargs["parent_state"] = parent_state
  326. super().__init__()
  327. for name, value in kwargs.items():
  328. setattr(self, name, value)
  329. # Setup the substates (for memory state manager only).
  330. if init_substates:
  331. for substate in self.get_substates():
  332. self.substates[substate.get_name()] = substate(
  333. parent_state=self,
  334. _reflex_internal_init=True,
  335. )
  336. # Create a fresh copy of the backend variables for this instance
  337. self._backend_vars = copy.deepcopy(self.backend_vars)
  338. def __repr__(self) -> str:
  339. """Get the string representation of the state.
  340. Returns:
  341. The string representation of the state.
  342. """
  343. return f"{type(self).__name__}({self.dict()})"
  344. @classmethod
  345. def _get_computed_vars(cls) -> list[tuple[str, ComputedVar]]:
  346. """Helper function to get all computed vars of a instance.
  347. Returns:
  348. A list of computed vars.
  349. """
  350. return [
  351. (name, v)
  352. for mixin in [*cls._mixins(), cls]
  353. for name, v in mixin.__dict__.items()
  354. if is_computed_var(v) and name not in cls.inherited_vars
  355. ]
  356. @classmethod
  357. def _validate_module_name(cls) -> None:
  358. """Check if the module name is valid.
  359. Reflex uses ___ as state name module separator.
  360. Raises:
  361. NameError: If the module name is invalid.
  362. """
  363. if "___" in cls.__module__:
  364. raise NameError(
  365. "The module name of a State class cannot contain '___'. "
  366. "Please rename the module."
  367. )
  368. @classmethod
  369. def __init_subclass__(cls, mixin: bool = False, **kwargs):
  370. """Do some magic for the subclass initialization.
  371. Args:
  372. mixin: Whether the subclass is a mixin and should not be initialized.
  373. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  374. Raises:
  375. StateValueError: If a substate class shadows another.
  376. """
  377. from reflex.utils.exceptions import StateValueError
  378. super().__init_subclass__(**kwargs)
  379. cls._mixin = mixin
  380. if mixin:
  381. return
  382. # Handle locally-defined states for pickling.
  383. if "<locals>" in cls.__qualname__:
  384. cls._handle_local_def()
  385. # Validate the module name.
  386. cls._validate_module_name()
  387. # Event handlers should not shadow builtin state methods.
  388. cls._check_overridden_methods()
  389. # Computed vars should not shadow builtin state props.
  390. cls._check_overridden_basevars()
  391. # Reset subclass tracking for this class.
  392. cls.class_subclasses = set()
  393. # Reset dirty substate tracking for this class.
  394. cls._always_dirty_substates = set()
  395. cls._potentially_dirty_states = set()
  396. # Get the parent vars.
  397. parent_state = cls.get_parent_state()
  398. if parent_state is not None:
  399. cls.inherited_vars = parent_state.vars
  400. cls.inherited_backend_vars = parent_state.backend_vars
  401. # Check if another substate class with the same name has already been defined.
  402. if cls.get_name() in {c.get_name() for c in parent_state.class_subclasses}:
  403. # This should not happen, since we have added module prefix to state names in #3214
  404. raise StateValueError(
  405. f"The substate class '{cls.get_name()}' has been defined multiple times. "
  406. "Shadowing substate classes is not allowed."
  407. )
  408. # Track this new subclass in the parent state's subclasses set.
  409. parent_state.class_subclasses.add(cls)
  410. # Get computed vars.
  411. computed_vars = cls._get_computed_vars()
  412. cls._check_overridden_computed_vars()
  413. new_backend_vars = {
  414. name: value
  415. for name, value in cls.__dict__.items()
  416. if types.is_backend_base_variable(name, cls)
  417. }
  418. # Add annotated backend vars that may not have a default value.
  419. new_backend_vars.update(
  420. {
  421. name: cls._get_var_default(name, annotation_value)
  422. for name, annotation_value in cls._get_type_hints().items()
  423. if name not in new_backend_vars
  424. and types.is_backend_base_variable(name, cls)
  425. }
  426. )
  427. cls.backend_vars = {
  428. **cls.inherited_backend_vars,
  429. **new_backend_vars,
  430. }
  431. # Set the base and computed vars.
  432. cls.base_vars = {
  433. f.name: get_var_for_field(cls, f)
  434. for f in cls.get_fields().values()
  435. if f.name not in cls.get_skip_vars()
  436. }
  437. cls.computed_vars = {
  438. name: v._replace(merge_var_data=VarData.from_state(cls))
  439. for name, v in computed_vars
  440. }
  441. cls.vars = {
  442. **cls.inherited_vars,
  443. **cls.base_vars,
  444. **cls.computed_vars,
  445. }
  446. cls.event_handlers = {}
  447. # Setup the base vars at the class level.
  448. for name, prop in cls.base_vars.items():
  449. cls._init_var(name, prop)
  450. # Set up the event handlers.
  451. events = {
  452. name: fn
  453. for name, fn in cls.__dict__.items()
  454. if cls._item_is_event_handler(name, fn)
  455. }
  456. for mixin_cls in cls._mixins():
  457. for name, value in mixin_cls.__dict__.items():
  458. if name in cls.inherited_vars:
  459. continue
  460. if is_computed_var(value):
  461. fget = cls._copy_fn(value.fget)
  462. newcv = value._replace(fget=fget, _var_data=VarData.from_state(cls))
  463. # cleanup refs to mixin cls in var_data
  464. setattr(cls, name, newcv)
  465. cls.computed_vars[newcv._js_expr] = newcv
  466. cls.vars[newcv._js_expr] = newcv
  467. continue
  468. if types.is_backend_base_variable(name, mixin_cls):
  469. cls.backend_vars[name] = copy.deepcopy(value)
  470. continue
  471. if events.get(name) is not None:
  472. continue
  473. if not cls._item_is_event_handler(name, value):
  474. continue
  475. if parent_state is not None and parent_state.event_handlers.get(name):
  476. continue
  477. value = cls._copy_fn(value)
  478. value.__qualname__ = f"{cls.__name__}.{name}"
  479. events[name] = value
  480. # Create the setvar event handler for this state
  481. cls._create_setvar()
  482. for name, fn in events.items():
  483. handler = cls._create_event_handler(fn)
  484. cls.event_handlers[name] = handler
  485. setattr(cls, name, handler)
  486. # Initialize per-class var dependency tracking.
  487. cls._var_dependencies = {}
  488. cls._init_var_dependency_dicts()
  489. all_base_state_classes[cls.get_full_name()] = None
  490. @classmethod
  491. def _add_event_handler(
  492. cls,
  493. name: str,
  494. fn: Callable,
  495. ):
  496. """Add an event handler dynamically to the state.
  497. Args:
  498. name: The name of the event handler.
  499. fn: The function to call when the event is triggered.
  500. """
  501. handler = cls._create_event_handler(fn)
  502. cls.event_handlers[name] = handler
  503. setattr(cls, name, handler)
  504. @staticmethod
  505. def _copy_fn(fn: Callable) -> Callable:
  506. """Copy a function. Used to copy ComputedVars and EventHandlers from mixins.
  507. Args:
  508. fn: The function to copy.
  509. Returns:
  510. The copied function.
  511. """
  512. newfn = FunctionType(
  513. fn.__code__,
  514. fn.__globals__,
  515. name=fn.__name__,
  516. argdefs=fn.__defaults__,
  517. closure=fn.__closure__,
  518. )
  519. newfn.__annotations__ = fn.__annotations__
  520. if mark := getattr(fn, BACKGROUND_TASK_MARKER, None):
  521. setattr(newfn, BACKGROUND_TASK_MARKER, mark)
  522. return newfn
  523. @staticmethod
  524. def _item_is_event_handler(name: str, value: Any) -> bool:
  525. """Check if the item is an event handler.
  526. Args:
  527. name: The name of the item.
  528. value: The value of the item.
  529. Returns:
  530. Whether the item is an event handler.
  531. """
  532. return (
  533. not name.startswith("_")
  534. and isinstance(value, Callable)
  535. and not isinstance(value, EventHandler)
  536. and hasattr(value, "__code__")
  537. )
  538. @classmethod
  539. def _evaluate(cls, f: Callable[[Self], Any], of_type: type | None = None) -> Var:
  540. """Evaluate a function to a ComputedVar. Experimental.
  541. Args:
  542. f: The function to evaluate.
  543. of_type: The type of the ComputedVar. Defaults to Component.
  544. Returns:
  545. The ComputedVar.
  546. """
  547. console.warn(
  548. "The _evaluate method is experimental and may be removed in future versions."
  549. )
  550. from reflex.components.component import Component
  551. of_type = of_type or Component
  552. unique_var_name = get_unique_variable_name()
  553. @computed_var(_js_expr=unique_var_name, return_type=of_type)
  554. def computed_var_func(state: Self):
  555. result = f(state)
  556. if not _isinstance(result, of_type, nested=1, treat_var_as_type=False):
  557. console.warn(
  558. f"Inline ComputedVar {f} expected type {escape(str(of_type))}, got {type(result)}. "
  559. "You can specify expected type with `of_type` argument."
  560. )
  561. return result
  562. setattr(cls, unique_var_name, computed_var_func)
  563. cls.computed_vars[unique_var_name] = computed_var_func
  564. cls.vars[unique_var_name] = computed_var_func
  565. cls._update_substate_inherited_vars({unique_var_name: computed_var_func})
  566. cls._always_dirty_computed_vars.add(unique_var_name)
  567. return getattr(cls, unique_var_name)
  568. @classmethod
  569. def _mixins(cls) -> list[type]:
  570. """Get the mixin classes of the state.
  571. Returns:
  572. The mixin classes of the state.
  573. """
  574. return [
  575. mixin
  576. for mixin in cls.__mro__
  577. if (
  578. mixin not in [pydantic.BaseModel, Base, cls]
  579. and issubclass(mixin, BaseState)
  580. and mixin._mixin is True
  581. )
  582. ]
  583. @classmethod
  584. def _handle_local_def(cls):
  585. """Handle locally-defined states for pickling."""
  586. known_names = dir(reflex.istate.dynamic)
  587. proposed_name = cls.__name__
  588. for ix in range(len(known_names)):
  589. if proposed_name not in known_names:
  590. break
  591. proposed_name = f"{cls.__name__}_{ix}"
  592. setattr(reflex.istate.dynamic, proposed_name, cls)
  593. cls.__original_name__ = cls.__name__
  594. cls.__original_module__ = cls.__module__
  595. cls.__name__ = cls.__qualname__ = proposed_name
  596. cls.__module__ = reflex.istate.dynamic.__name__
  597. @classmethod
  598. def _get_type_hints(cls) -> dict[str, Any]:
  599. """Get the type hints for this class.
  600. If the class is dynamic, evaluate the type hints with the original
  601. module in the local namespace.
  602. Returns:
  603. The type hints dict.
  604. """
  605. original_module = getattr(cls, "__original_module__", None)
  606. if original_module is not None:
  607. localns = sys.modules[original_module].__dict__
  608. else:
  609. localns = None
  610. return get_type_hints(cls, localns=localns)
  611. @classmethod
  612. def _init_var_dependency_dicts(cls):
  613. """Initialize the var dependency tracking dicts.
  614. Allows the state to know which vars each ComputedVar depends on and
  615. whether a ComputedVar depends on a var in its parent state.
  616. Additional updates tracking dicts for vars and substates that always
  617. need to be recomputed.
  618. """
  619. for cvar_name, cvar in cls.computed_vars.items():
  620. if not cvar._cache:
  621. # Do not perform dep calculation when cache=False (these are always dirty).
  622. continue
  623. for state_name, dvar_set in cvar._deps(objclass=cls).items():
  624. state_cls = cls.get_root_state().get_class_substate(state_name)
  625. for dvar in dvar_set:
  626. defining_state_cls = state_cls
  627. while dvar in {
  628. *defining_state_cls.inherited_vars,
  629. *defining_state_cls.inherited_backend_vars,
  630. }:
  631. parent_state = defining_state_cls.get_parent_state()
  632. if parent_state is not None:
  633. defining_state_cls = parent_state
  634. defining_state_cls._var_dependencies.setdefault(dvar, set()).add(
  635. (cls.get_full_name(), cvar_name)
  636. )
  637. defining_state_cls._potentially_dirty_states.add(
  638. cls.get_full_name()
  639. )
  640. # ComputedVar with cache=False always need to be recomputed
  641. cls._always_dirty_computed_vars = {
  642. cvar_name
  643. for cvar_name, cvar in cls.computed_vars.items()
  644. if not cvar._cache
  645. }
  646. # Any substate containing a ComputedVar with cache=False always needs to be recomputed
  647. if cls._always_dirty_computed_vars:
  648. # Tell parent classes that this substate has always dirty computed vars
  649. state_name = cls.get_name()
  650. parent_state = cls.get_parent_state()
  651. while parent_state is not None:
  652. parent_state._always_dirty_substates.add(state_name)
  653. state_name, parent_state = (
  654. parent_state.get_name(),
  655. parent_state.get_parent_state(),
  656. )
  657. # Reset cached schema value
  658. cls._to_schema.cache_clear()
  659. @classmethod
  660. def _check_overridden_methods(cls):
  661. """Check for shadow methods and raise error if any.
  662. Raises:
  663. EventHandlerShadowsBuiltInStateMethodError: When an event handler shadows an inbuilt state method.
  664. """
  665. overridden_methods = set()
  666. state_base_functions = cls._get_base_functions()
  667. for name, method in inspect.getmembers(cls, inspect.isfunction):
  668. # Check if the method is overridden and not a dunder method
  669. if (
  670. not name.startswith("__")
  671. and method.__name__ in state_base_functions
  672. and state_base_functions[method.__name__] != method
  673. ):
  674. overridden_methods.add(method.__name__)
  675. for method_name in overridden_methods:
  676. raise EventHandlerShadowsBuiltInStateMethodError(
  677. f"The event handler name `{method_name}` shadows a builtin State method; use a different name instead"
  678. )
  679. @classmethod
  680. def _check_overridden_basevars(cls):
  681. """Check for shadow base vars and raise error if any.
  682. Raises:
  683. ComputedVarShadowsBaseVarsError: When a computed var shadows a base var.
  684. """
  685. for name, computed_var_ in cls._get_computed_vars():
  686. if name in cls.__annotations__:
  687. raise ComputedVarShadowsBaseVarsError(
  688. f"The computed var name `{computed_var_._js_expr}` shadows a base var in {cls.__module__}.{cls.__name__}; use a different name instead"
  689. )
  690. @classmethod
  691. def _check_overridden_computed_vars(cls) -> None:
  692. """Check for shadow computed vars and raise error if any.
  693. Raises:
  694. ComputedVarShadowsStateVarError: When a computed var shadows another.
  695. """
  696. for name, cv in cls.__dict__.items():
  697. if not is_computed_var(cv):
  698. continue
  699. name = cv._js_expr
  700. if name in cls.inherited_vars or name in cls.inherited_backend_vars:
  701. raise ComputedVarShadowsStateVarError(
  702. f"The computed var name `{cv._js_expr}` shadows a var in {cls.__module__}.{cls.__name__}; use a different name instead"
  703. )
  704. @classmethod
  705. def get_skip_vars(cls) -> set[str]:
  706. """Get the vars to skip when serializing.
  707. Returns:
  708. The vars to skip when serializing.
  709. """
  710. return (
  711. set(cls.inherited_vars)
  712. | {
  713. "parent_state",
  714. "substates",
  715. "dirty_vars",
  716. "dirty_substates",
  717. "router_data",
  718. }
  719. | types.RESERVED_BACKEND_VAR_NAMES
  720. )
  721. @classmethod
  722. @functools.lru_cache
  723. def get_parent_state(cls) -> type[BaseState] | None:
  724. """Get the parent state.
  725. Raises:
  726. ValueError: If more than one parent state is found.
  727. Returns:
  728. The parent state.
  729. """
  730. parent_states = [
  731. base
  732. for base in cls.__bases__
  733. if issubclass(base, BaseState) and base is not BaseState and not base._mixin
  734. ]
  735. if len(parent_states) >= 2:
  736. raise ValueError(f"Only one parent state is allowed {parent_states}.")
  737. # The first non-mixin state in the mro is our parent.
  738. for base in cls.mro()[1:]:
  739. if not issubclass(base, BaseState) or base._mixin:
  740. continue
  741. if base is BaseState:
  742. break
  743. return base
  744. return None # No known parent
  745. @classmethod
  746. @functools.lru_cache
  747. def get_root_state(cls) -> type[BaseState]:
  748. """Get the root state.
  749. Returns:
  750. The root state.
  751. """
  752. parent_state = cls.get_parent_state()
  753. return cls if parent_state is None else parent_state.get_root_state()
  754. @classmethod
  755. def get_substates(cls) -> set[type[BaseState]]:
  756. """Get the substates of the state.
  757. Returns:
  758. The substates of the state.
  759. """
  760. return cls.class_subclasses
  761. @classmethod
  762. @functools.lru_cache
  763. def get_name(cls) -> str:
  764. """Get the name of the state.
  765. Returns:
  766. The name of the state.
  767. """
  768. module = cls.__module__.replace(".", "___")
  769. return format.to_snake_case(f"{module}___{cls.__name__}")
  770. @classmethod
  771. @functools.lru_cache
  772. def get_full_name(cls) -> str:
  773. """Get the full name of the state.
  774. Returns:
  775. The full name of the state.
  776. """
  777. name = cls.get_name()
  778. parent_state = cls.get_parent_state()
  779. if parent_state is not None:
  780. name = ".".join((parent_state.get_full_name(), name))
  781. return name
  782. @classmethod
  783. @functools.lru_cache
  784. def get_class_substate(cls, path: Sequence[str] | str) -> type[BaseState]:
  785. """Get the class substate.
  786. Args:
  787. path: The path to the substate.
  788. Returns:
  789. The class substate.
  790. Raises:
  791. ValueError: If the substate is not found.
  792. """
  793. if isinstance(path, str):
  794. path = tuple(path.split("."))
  795. if len(path) == 0:
  796. return cls
  797. if path[0] == cls.get_name():
  798. if len(path) == 1:
  799. return cls
  800. path = path[1:]
  801. for substate in cls.get_substates():
  802. if path[0] == substate.get_name():
  803. return substate.get_class_substate(path[1:])
  804. raise ValueError(f"Invalid path: {path}")
  805. @classmethod
  806. def get_class_var(cls, path: Sequence[str]) -> Any:
  807. """Get the class var.
  808. Args:
  809. path: The path to the var.
  810. Returns:
  811. The class var.
  812. Raises:
  813. ValueError: If the path is invalid.
  814. """
  815. path, name = path[:-1], path[-1]
  816. substate = cls.get_class_substate(tuple(path))
  817. if not hasattr(substate, name):
  818. raise ValueError(f"Invalid path: {path}")
  819. return getattr(substate, name)
  820. @classmethod
  821. def _init_var(cls, name: str, prop: Var):
  822. """Initialize a variable.
  823. Args:
  824. name: The name of the variable
  825. prop: The variable to initialize
  826. Raises:
  827. VarTypeError: if the variable has an incorrect type
  828. """
  829. from reflex.utils.exceptions import VarTypeError
  830. if not types.is_valid_var_type(prop._var_type):
  831. raise VarTypeError(
  832. "State vars must be of a serializable type. "
  833. "Valid types include strings, numbers, booleans, lists, "
  834. "dictionaries, dataclasses, datetime objects, and pydantic models. "
  835. f'Found var "{prop._js_expr}" with type {prop._var_type}.'
  836. )
  837. cls._set_var(name, prop)
  838. cls._create_setter(name, prop)
  839. cls._set_default_value(name, prop)
  840. @classmethod
  841. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  842. """Add dynamically a variable to the State.
  843. The variable added this way can be used in the same way as a variable
  844. defined statically in the model.
  845. Args:
  846. name: The name of the variable
  847. type_: The type of the variable
  848. default_value: The default value of the variable
  849. Raises:
  850. NameError: if a variable of this name already exists
  851. """
  852. if name in cls.__fields__:
  853. raise NameError(
  854. f"The variable '{name}' already exist. Use a different name"
  855. )
  856. # create the variable based on name and type
  857. var = Var(
  858. _js_expr=format.format_state_name(cls.get_full_name())
  859. + "."
  860. + name
  861. + "_rx_state_",
  862. _var_type=type_,
  863. _var_data=VarData.from_state(cls, name),
  864. ).guess_type()
  865. # add the pydantic field dynamically (must be done before _init_var)
  866. cls.add_field(name, var, default_value)
  867. cls._init_var(name, var)
  868. # update the internal dicts so the new variable is correctly handled
  869. cls.base_vars.update({name: var})
  870. cls.vars.update({name: var})
  871. # let substates know about the new variable
  872. for substate_class in cls.class_subclasses:
  873. substate_class.vars.setdefault(name, var)
  874. # Reinitialize dependency tracking dicts.
  875. cls._init_var_dependency_dicts()
  876. @classmethod
  877. def _set_var(cls, name: str, prop: Var):
  878. """Set the var as a class member.
  879. Args:
  880. name: The name of the var.
  881. prop: The var instance to set.
  882. """
  883. setattr(cls, name, prop)
  884. @classmethod
  885. def _create_event_handler(cls, fn: Any):
  886. """Create an event handler for the given function.
  887. Args:
  888. fn: The function to create an event handler for.
  889. Returns:
  890. The event handler.
  891. """
  892. return EventHandler(fn=fn, state_full_name=cls.get_full_name())
  893. @classmethod
  894. def _create_setvar(cls):
  895. """Create the setvar method for the state."""
  896. cls.setvar = cls.event_handlers["setvar"] = EventHandlerSetVar(state_cls=cls)
  897. @classmethod
  898. def _create_setter(cls, name: str, prop: Var):
  899. """Create a setter for the var.
  900. Args:
  901. name: The name of the var.
  902. prop: The var to create a setter for.
  903. """
  904. setter_name = Var._get_setter_name_for_name(name)
  905. if setter_name not in cls.__dict__:
  906. event_handler = cls._create_event_handler(prop._get_setter(name))
  907. cls.event_handlers[setter_name] = event_handler
  908. setattr(cls, setter_name, event_handler)
  909. @classmethod
  910. def _set_default_value(cls, name: str, prop: Var):
  911. """Set the default value for the var.
  912. Args:
  913. name: The name of the var.
  914. prop: The var to set the default value for.
  915. """
  916. # Get the pydantic field for the var.
  917. field = cls.get_fields()[name]
  918. if field.required:
  919. default_value = prop._get_default_value()
  920. if default_value is not None:
  921. field.required = False
  922. field.default = default_value
  923. if (
  924. not field.required
  925. and field.default is None
  926. and field.default_factory is None
  927. and not types.is_optional(prop._var_type)
  928. ):
  929. # Ensure frontend uses null coalescing when accessing.
  930. object.__setattr__(prop, "_var_type", prop._var_type | None)
  931. @classmethod
  932. def _get_var_default(cls, name: str, annotation_value: Any) -> Any:
  933. """Get the default value of a (backend) var.
  934. Args:
  935. name: The name of the var.
  936. annotation_value: The annotation value of the var.
  937. Returns:
  938. The default value of the var or None.
  939. """
  940. try:
  941. return getattr(cls, name)
  942. except AttributeError:
  943. try:
  944. return Var("", _var_type=annotation_value)._get_default_value()
  945. except TypeError:
  946. pass
  947. return None
  948. @staticmethod
  949. def _get_base_functions() -> dict[str, FunctionType]:
  950. """Get all functions of the state class excluding dunder methods.
  951. Returns:
  952. The functions of rx.State class as a dict.
  953. """
  954. return {
  955. func[0]: func[1]
  956. for func in inspect.getmembers(BaseState, predicate=inspect.isfunction)
  957. if not func[0].startswith("__")
  958. }
  959. @classmethod
  960. def _update_substate_inherited_vars(cls, vars_to_add: dict[str, Var]):
  961. """Update the inherited vars of substates recursively when new vars are added.
  962. Also updates the var dependency tracking dicts after adding vars.
  963. Args:
  964. vars_to_add: names to Var instances to add to substates
  965. """
  966. for substate_class in cls.class_subclasses:
  967. for name, var in vars_to_add.items():
  968. if types.is_backend_base_variable(name, cls):
  969. substate_class.backend_vars.setdefault(name, var)
  970. substate_class.inherited_backend_vars.setdefault(name, var)
  971. else:
  972. substate_class.vars.setdefault(name, var)
  973. substate_class.inherited_vars.setdefault(name, var)
  974. substate_class._update_substate_inherited_vars(vars_to_add)
  975. # Reinitialize dependency tracking dicts.
  976. cls._init_var_dependency_dicts()
  977. @classmethod
  978. def setup_dynamic_args(cls, args: dict[str, str]):
  979. """Set up args for easy access in renderer.
  980. Args:
  981. args: a dict of args
  982. """
  983. if not args:
  984. return
  985. cls._check_overwritten_dynamic_args(list(args.keys()))
  986. def argsingle_factory(param: str):
  987. def inner_func(self: BaseState) -> str:
  988. return self.router.page.params.get(param, "")
  989. return inner_func
  990. def arglist_factory(param: str):
  991. def inner_func(self: BaseState) -> list[str]:
  992. return self.router.page.params.get(param, [])
  993. return inner_func
  994. dynamic_vars = {}
  995. for param, value in args.items():
  996. if value == constants.RouteArgType.SINGLE:
  997. func = argsingle_factory(param)
  998. elif value == constants.RouteArgType.LIST:
  999. func = arglist_factory(param)
  1000. else:
  1001. continue
  1002. dynamic_vars[param] = DynamicRouteVar(
  1003. fget=func,
  1004. auto_deps=False,
  1005. deps=["router"],
  1006. _js_expr=param,
  1007. _var_data=VarData.from_state(cls),
  1008. )
  1009. setattr(cls, param, dynamic_vars[param])
  1010. # Update tracking dicts.
  1011. cls.computed_vars.update(dynamic_vars)
  1012. cls.vars.update(dynamic_vars)
  1013. cls._update_substate_inherited_vars(dynamic_vars)
  1014. @classmethod
  1015. def _check_overwritten_dynamic_args(cls, args: list[str]):
  1016. """Check if dynamic args are shadowing existing vars. Recursively checks all child states.
  1017. Args:
  1018. args: a dict of args
  1019. Raises:
  1020. DynamicRouteArgShadowsStateVarError: If a dynamic arg is shadowing an existing var.
  1021. """
  1022. for arg in args:
  1023. if (
  1024. arg in cls.computed_vars
  1025. and not isinstance(cls.computed_vars[arg], DynamicRouteVar)
  1026. ) or arg in cls.base_vars:
  1027. raise DynamicRouteArgShadowsStateVarError(
  1028. f"Dynamic route arg '{arg}' is shadowing an existing var in {cls.__module__}.{cls.__name__}"
  1029. )
  1030. for substate in cls.get_substates():
  1031. substate._check_overwritten_dynamic_args(args)
  1032. def __getattribute__(self, name: str) -> Any:
  1033. """Get the state var.
  1034. If the var is inherited, get the var from the parent state.
  1035. Args:
  1036. name: The name of the var.
  1037. Returns:
  1038. The value of the var.
  1039. """
  1040. # If the state hasn't been initialized yet, return the default value.
  1041. if not super().__getattribute__("__dict__"):
  1042. return super().__getattribute__(name)
  1043. # Fast path for dunder
  1044. if name.startswith("__"):
  1045. return super().__getattribute__(name)
  1046. # For now, handle router_data updates as a special case.
  1047. if (
  1048. name == constants.ROUTER_DATA
  1049. or name in super().__getattribute__("inherited_vars")
  1050. or name in super().__getattribute__("inherited_backend_vars")
  1051. ):
  1052. parent_state = super().__getattribute__("parent_state")
  1053. if parent_state is not None:
  1054. return getattr(parent_state, name)
  1055. # Allow event handlers to be called on the instance directly.
  1056. event_handlers = super().__getattribute__("event_handlers")
  1057. if name in event_handlers:
  1058. handler = event_handlers[name]
  1059. if handler.is_background:
  1060. fn = _no_chain_background_task(type(self), name, handler.fn)
  1061. else:
  1062. fn = functools.partial(handler.fn, self)
  1063. fn.__module__ = handler.fn.__module__
  1064. fn.__qualname__ = handler.fn.__qualname__
  1065. return fn
  1066. backend_vars = super().__getattribute__("_backend_vars")
  1067. if name in backend_vars:
  1068. value = backend_vars[name]
  1069. else:
  1070. value = super().__getattribute__(name)
  1071. if isinstance(value, EventHandler):
  1072. # The event handler is inherited from a parent, so let the parent convert
  1073. # it to a callable function.
  1074. parent_state = super().__getattribute__("parent_state")
  1075. if parent_state is not None:
  1076. return getattr(parent_state, name)
  1077. if MutableProxy._is_mutable_type(value) and (
  1078. name in super().__getattribute__("base_vars") or name in backend_vars
  1079. ):
  1080. # track changes in mutable containers (list, dict, set, etc)
  1081. return MutableProxy(wrapped=value, state=self, field_name=name)
  1082. return value
  1083. def __setattr__(self, name: str, value: Any):
  1084. """Set the attribute.
  1085. If the attribute is inherited, set the attribute on the parent state.
  1086. Args:
  1087. name: The name of the attribute.
  1088. value: The value of the attribute.
  1089. Raises:
  1090. SetUndefinedStateVarError: If a value of a var is set without first defining it.
  1091. """
  1092. if isinstance(value, MutableProxy):
  1093. # unwrap proxy objects when assigning back to the state
  1094. value = value.__wrapped__
  1095. # Set the var on the parent state.
  1096. if name in self.inherited_vars or name in self.inherited_backend_vars:
  1097. setattr(self.parent_state, name, value)
  1098. return
  1099. if name in self.backend_vars:
  1100. self._backend_vars.__setitem__(name, value)
  1101. self.dirty_vars.add(name)
  1102. self._mark_dirty()
  1103. return
  1104. if (
  1105. name not in self.vars
  1106. and name not in self.get_skip_vars()
  1107. and not name.startswith("__")
  1108. and not name.startswith(
  1109. f"_{getattr(type(self), '__original_name__', type(self).__name__)}__"
  1110. )
  1111. ):
  1112. raise SetUndefinedStateVarError(
  1113. f"The state variable '{name}' has not been defined in '{type(self).__name__}'. "
  1114. f"All state variables must be declared before they can be set."
  1115. )
  1116. fields = self.get_fields()
  1117. if name in fields:
  1118. field = fields[name]
  1119. field_type = _unwrap_field_type(true_type_for_pydantic_field(field))
  1120. if not _isinstance(value, field_type, nested=1, treat_var_as_type=False):
  1121. console.error(
  1122. f"Expected field '{type(self).__name__}.{name}' to receive type '{escape(str(field_type))}',"
  1123. f" but got '{value}' of type '{type(value)}'."
  1124. )
  1125. # Set the attribute.
  1126. super().__setattr__(name, value)
  1127. # Add the var to the dirty list.
  1128. if name in self.base_vars:
  1129. self.dirty_vars.add(name)
  1130. self._mark_dirty()
  1131. # For now, handle router_data updates as a special case
  1132. if name == constants.ROUTER_DATA:
  1133. self.dirty_vars.add(name)
  1134. self._mark_dirty()
  1135. def reset(self):
  1136. """Reset all the base vars to their default values."""
  1137. # Reset the base vars.
  1138. fields = self.get_fields()
  1139. for prop_name in self.base_vars:
  1140. if prop_name == constants.ROUTER:
  1141. continue # never reset the router data
  1142. field = fields[prop_name]
  1143. if default_factory := field.default_factory:
  1144. default = default_factory()
  1145. else:
  1146. default = copy.deepcopy(field.default)
  1147. setattr(self, prop_name, default)
  1148. # Reset the backend vars.
  1149. for prop_name, value in self.backend_vars.items():
  1150. setattr(self, prop_name, copy.deepcopy(value))
  1151. # Recursively reset the substates.
  1152. for substate in self.substates.values():
  1153. substate.reset()
  1154. def _reset_client_storage(self):
  1155. """Reset client storage base vars to their default values."""
  1156. # Client-side storage is reset during hydrate so that clearing cookies
  1157. # on the browser also resets the values on the backend.
  1158. fields = self.get_fields()
  1159. for prop_name in self.base_vars:
  1160. field = fields[prop_name]
  1161. if isinstance(field.default, ClientStorageBase) or (
  1162. isinstance(field.type_, type)
  1163. and issubclass(field.type_, ClientStorageBase)
  1164. ):
  1165. setattr(self, prop_name, copy.deepcopy(field.default))
  1166. # Recursively reset the substate client storage.
  1167. for substate in self.substates.values():
  1168. substate._reset_client_storage()
  1169. def get_substate(self, path: Sequence[str]) -> BaseState:
  1170. """Get the substate.
  1171. Args:
  1172. path: The path to the substate.
  1173. Returns:
  1174. The substate.
  1175. Raises:
  1176. ValueError: If the substate is not found.
  1177. """
  1178. if len(path) == 0:
  1179. return self
  1180. if path[0] == self.get_name():
  1181. if len(path) == 1:
  1182. return self
  1183. path = path[1:]
  1184. if path[0] not in self.substates:
  1185. raise ValueError(f"Invalid path: {path}")
  1186. return self.substates[path[0]].get_substate(path[1:])
  1187. @classmethod
  1188. def _get_potentially_dirty_states(cls) -> set[type[BaseState]]:
  1189. """Get substates which may have dirty vars due to dependencies.
  1190. Returns:
  1191. The set of potentially dirty substate classes.
  1192. """
  1193. return {
  1194. cls.get_class_substate(substate_name)
  1195. for substate_name in cls._always_dirty_substates
  1196. }.union(
  1197. {
  1198. cls.get_root_state().get_class_substate(substate_name)
  1199. for substate_name in cls._potentially_dirty_states
  1200. }
  1201. )
  1202. def _get_root_state(self) -> BaseState:
  1203. """Get the root state of the state tree.
  1204. Returns:
  1205. The root state of the state tree.
  1206. """
  1207. parent_state = self
  1208. while parent_state.parent_state is not None:
  1209. parent_state = parent_state.parent_state
  1210. return parent_state
  1211. async def _get_state_from_redis(self, state_cls: type[T_STATE]) -> T_STATE:
  1212. """Get a state instance from redis.
  1213. Args:
  1214. state_cls: The class of the state.
  1215. Returns:
  1216. The instance of state_cls associated with this state's client_token.
  1217. Raises:
  1218. RuntimeError: If redis is not used in this backend process.
  1219. StateMismatchError: If the state instance is not of the expected type.
  1220. """
  1221. # Then get the target state and all its substates.
  1222. state_manager = get_state_manager()
  1223. if not isinstance(state_manager, StateManagerRedis):
  1224. raise RuntimeError(
  1225. f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. "
  1226. "(All states should already be available -- this is likely a bug).",
  1227. )
  1228. state_in_redis = await state_manager.get_state(
  1229. token=_substate_key(self.router.session.client_token, state_cls),
  1230. top_level=False,
  1231. for_state_instance=self,
  1232. )
  1233. if not isinstance(state_in_redis, state_cls):
  1234. raise StateMismatchError(
  1235. f"Searched for state {state_cls.get_full_name()} but found {state_in_redis}."
  1236. )
  1237. return state_in_redis
  1238. def _get_state_from_cache(self, state_cls: type[T_STATE]) -> T_STATE:
  1239. """Get a state instance from the cache.
  1240. Args:
  1241. state_cls: The class of the state.
  1242. Returns:
  1243. The instance of state_cls associated with this state's client_token.
  1244. Raises:
  1245. StateMismatchError: If the state instance is not of the expected type.
  1246. """
  1247. root_state = self._get_root_state()
  1248. substate = root_state.get_substate(state_cls.get_full_name().split("."))
  1249. if not isinstance(substate, state_cls):
  1250. raise StateMismatchError(
  1251. f"Searched for state {state_cls.get_full_name()} but found {substate}."
  1252. )
  1253. return substate
  1254. async def get_state(self, state_cls: type[T_STATE]) -> T_STATE:
  1255. """Get an instance of the state associated with this token.
  1256. Allows for arbitrary access to sibling states from within an event handler.
  1257. Args:
  1258. state_cls: The class of the state.
  1259. Returns:
  1260. The instance of state_cls associated with this state's client_token.
  1261. """
  1262. # Fast case - if this state instance is already cached, get_substate from root state.
  1263. try:
  1264. return self._get_state_from_cache(state_cls)
  1265. except ValueError:
  1266. pass
  1267. # Slow case - fetch missing parent states from redis.
  1268. return await self._get_state_from_redis(state_cls)
  1269. async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE:
  1270. """Get the value of an rx.Var from another state.
  1271. Args:
  1272. var: The var to get the value for.
  1273. Returns:
  1274. The value of the var.
  1275. Raises:
  1276. UnretrievableVarValueError: If the var does not have a literal value
  1277. or associated state.
  1278. """
  1279. # Oopsie case: you didn't give me a Var... so get what you give.
  1280. if not isinstance(var, Var):
  1281. return var
  1282. unset = object()
  1283. # Fast case: this is a literal var and the value is known.
  1284. if (
  1285. var_value := getattr(var, "_var_value", unset)
  1286. ) is not unset and not isinstance(var_value, Var):
  1287. return var_value # pyright: ignore [reportReturnType]
  1288. var_data = var._get_all_var_data()
  1289. if var_data is None or not var_data.state:
  1290. raise UnretrievableVarValueError(
  1291. f"Unable to retrieve value for {var._js_expr}: not associated with any state."
  1292. )
  1293. # Fastish case: this var belongs to this state
  1294. if var_data.state == self.get_full_name():
  1295. return getattr(self, var_data.field_name)
  1296. # Slow case: this var belongs to another state
  1297. other_state = await self.get_state(
  1298. self._get_root_state().get_class_substate(var_data.state)
  1299. )
  1300. return getattr(other_state, var_data.field_name)
  1301. def _get_event_handler(
  1302. self, event: Event
  1303. ) -> tuple[BaseState | StateProxy, EventHandler]:
  1304. """Get the event handler for the given event.
  1305. Args:
  1306. event: The event to get the handler for.
  1307. Returns:
  1308. The event handler.
  1309. Raises:
  1310. ValueError: If the event handler or substate is not found.
  1311. """
  1312. # Get the event handler.
  1313. path = event.name.split(".")
  1314. path, name = path[:-1], path[-1]
  1315. substate = self.get_substate(path)
  1316. if not substate:
  1317. raise ValueError(
  1318. "The value of state cannot be None when processing an event."
  1319. )
  1320. handler = substate.event_handlers[name]
  1321. # For background tasks, proxy the state
  1322. if handler.is_background:
  1323. substate = StateProxy(substate)
  1324. return substate, handler
  1325. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  1326. """Obtain event info and process event.
  1327. Args:
  1328. event: The event to process.
  1329. Yields:
  1330. The state update after processing the event.
  1331. """
  1332. # Get the event handler.
  1333. substate, handler = self._get_event_handler(event)
  1334. # Run the event generator and yield state updates.
  1335. async for update in self._process_event(
  1336. handler=handler,
  1337. state=substate,
  1338. payload=event.payload,
  1339. ):
  1340. yield update
  1341. def _check_valid(self, handler: EventHandler, events: Any) -> Any:
  1342. """Check if the events yielded are valid. They must be EventHandlers or EventSpecs.
  1343. Args:
  1344. handler: EventHandler.
  1345. events: The events to be checked.
  1346. Raises:
  1347. TypeError: If any of the events are not valid.
  1348. Returns:
  1349. The events as they are if valid.
  1350. """
  1351. def _is_valid_type(events: Any) -> bool:
  1352. return isinstance(events, (Event, EventHandler, EventSpec))
  1353. if events is None or _is_valid_type(events):
  1354. return events
  1355. if not isinstance(events, Sequence):
  1356. events = [events]
  1357. try:
  1358. if all(_is_valid_type(e) for e in events):
  1359. return events
  1360. except TypeError:
  1361. pass
  1362. coroutines = [e for e in events if asyncio.iscoroutine(e)]
  1363. for coroutine in coroutines:
  1364. coroutine_name = coroutine.__qualname__
  1365. warnings.filterwarnings(
  1366. "ignore", message=f"coroutine '{coroutine_name}' was never awaited"
  1367. )
  1368. raise TypeError(
  1369. f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (i.e. using `type(self)` or other class references)."
  1370. f" Returned events of types {', '.join(map(str, map(type, events)))!s}."
  1371. )
  1372. async def _as_state_update(
  1373. self,
  1374. handler: EventHandler,
  1375. events: EventSpec | list[EventSpec] | None,
  1376. final: bool,
  1377. ) -> StateUpdate:
  1378. """Convert the events to a StateUpdate.
  1379. Fixes the events and checks for validity before converting.
  1380. Args:
  1381. handler: The handler where the events originated from.
  1382. events: The events to queue with the update.
  1383. final: Whether the handler is done processing.
  1384. Returns:
  1385. The valid StateUpdate containing the events and final flag.
  1386. """
  1387. # get the delta from the root of the state tree
  1388. state = self._get_root_state()
  1389. token = self.router.session.client_token
  1390. # Convert valid EventHandler and EventSpec into Event
  1391. fixed_events = fix_events(self._check_valid(handler, events), token)
  1392. try:
  1393. # Get the delta after processing the event.
  1394. delta = await state._get_resolved_delta()
  1395. state._clean()
  1396. return StateUpdate(
  1397. delta=delta,
  1398. events=fixed_events,
  1399. final=final if not handler.is_background else True,
  1400. )
  1401. except Exception as ex:
  1402. state._clean()
  1403. event_specs = (
  1404. prerequisites.get_and_validate_app().app.backend_exception_handler(ex)
  1405. )
  1406. if event_specs is None:
  1407. return StateUpdate()
  1408. event_specs_correct_type = cast(
  1409. list[EventSpec | EventHandler] | None,
  1410. [event_specs] if isinstance(event_specs, EventSpec) else event_specs,
  1411. )
  1412. fixed_events = fix_events(
  1413. event_specs_correct_type,
  1414. token,
  1415. router_data=state.router_data,
  1416. )
  1417. return StateUpdate(
  1418. events=fixed_events,
  1419. final=True,
  1420. )
  1421. async def _process_event(
  1422. self,
  1423. handler: EventHandler,
  1424. state: BaseState | StateProxy,
  1425. payload: builtins.dict,
  1426. ) -> AsyncIterator[StateUpdate]:
  1427. """Process event.
  1428. Args:
  1429. handler: EventHandler to process.
  1430. state: State to process the handler.
  1431. payload: The event payload.
  1432. Yields:
  1433. StateUpdate object
  1434. Raises:
  1435. ValueError: If a string value is received for an int or float type and cannot be converted.
  1436. """
  1437. from reflex.utils import telemetry
  1438. # Get the function to process the event.
  1439. fn = functools.partial(handler.fn, state)
  1440. try:
  1441. type_hints = typing.get_type_hints(handler.fn)
  1442. except Exception:
  1443. type_hints = {}
  1444. for arg, value in list(payload.items()):
  1445. hinted_args = type_hints.get(arg, Any)
  1446. if hinted_args is Any:
  1447. continue
  1448. if is_union(hinted_args):
  1449. if value is None:
  1450. continue
  1451. hinted_args = value_inside_optional(hinted_args)
  1452. if (
  1453. isinstance(value, dict)
  1454. and inspect.isclass(hinted_args)
  1455. and not types.is_generic_alias(hinted_args) # py3.10
  1456. ):
  1457. if issubclass(hinted_args, Model):
  1458. # Remove non-fields from the payload
  1459. payload[arg] = hinted_args(
  1460. **{
  1461. key: value
  1462. for key, value in value.items()
  1463. if key in hinted_args.__fields__
  1464. }
  1465. )
  1466. elif dataclasses.is_dataclass(hinted_args) or issubclass(
  1467. hinted_args, (Base, BaseModelV1, BaseModelV2)
  1468. ):
  1469. payload[arg] = hinted_args(**value)
  1470. elif isinstance(value, list) and (hinted_args is set or hinted_args is set):
  1471. payload[arg] = set(value)
  1472. elif isinstance(value, list) and (
  1473. hinted_args is tuple or hinted_args is tuple
  1474. ):
  1475. payload[arg] = tuple(value)
  1476. elif isinstance(value, str) and (
  1477. hinted_args is int or hinted_args is float
  1478. ):
  1479. try:
  1480. payload[arg] = hinted_args(value)
  1481. except ValueError:
  1482. raise ValueError(
  1483. f"Received a string value ({value}) for {arg} but expected a {hinted_args}"
  1484. ) from None
  1485. else:
  1486. console.warn(
  1487. f"Received a string value ({value}) for {arg} but expected a {hinted_args}. A simple conversion was successful."
  1488. )
  1489. # Wrap the function in a try/except block.
  1490. try:
  1491. # Handle async functions.
  1492. if asyncio.iscoroutinefunction(fn.func):
  1493. events = await fn(**payload)
  1494. # Handle regular functions.
  1495. else:
  1496. events = fn(**payload)
  1497. # Handle async generators.
  1498. if inspect.isasyncgen(events):
  1499. async for event in events:
  1500. yield await state._as_state_update(handler, event, final=False)
  1501. yield await state._as_state_update(handler, events=None, final=True)
  1502. # Handle regular generators.
  1503. elif inspect.isgenerator(events):
  1504. try:
  1505. while True:
  1506. yield await state._as_state_update(
  1507. handler, next(events), final=False
  1508. )
  1509. except StopIteration as si:
  1510. # the "return" value of the generator is not available
  1511. # in the loop, we must catch StopIteration to access it
  1512. if si.value is not None:
  1513. yield await state._as_state_update(
  1514. handler, si.value, final=False
  1515. )
  1516. yield await state._as_state_update(handler, events=None, final=True)
  1517. # Handle regular event chains.
  1518. else:
  1519. yield await state._as_state_update(handler, events, final=True)
  1520. # If an error occurs, throw a window alert.
  1521. except Exception as ex:
  1522. telemetry.send_error(ex, context="backend")
  1523. event_specs = (
  1524. prerequisites.get_and_validate_app().app.backend_exception_handler(ex)
  1525. )
  1526. yield await state._as_state_update(
  1527. handler,
  1528. event_specs,
  1529. final=True,
  1530. )
  1531. def _mark_dirty_computed_vars(self) -> None:
  1532. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  1533. # Append expired computed vars to dirty_vars to trigger recalculation
  1534. self.dirty_vars.update(self._expired_computed_vars())
  1535. # Append always dirty computed vars to dirty_vars to trigger recalculation
  1536. self.dirty_vars.update(self._always_dirty_computed_vars)
  1537. dirty_vars = self.dirty_vars
  1538. while dirty_vars:
  1539. calc_vars, dirty_vars = dirty_vars, set()
  1540. for state_name, cvar in self._dirty_computed_vars(from_vars=calc_vars):
  1541. if state_name == self.get_full_name():
  1542. defining_state = self
  1543. else:
  1544. defining_state = self._get_root_state().get_substate(
  1545. tuple(state_name.split("."))
  1546. )
  1547. defining_state.dirty_vars.add(cvar)
  1548. actual_var = defining_state.computed_vars.get(cvar)
  1549. if actual_var is not None:
  1550. actual_var.mark_dirty(instance=defining_state)
  1551. if defining_state is self:
  1552. dirty_vars.add(cvar)
  1553. else:
  1554. # mark dirty where this var is defined
  1555. defining_state._mark_dirty()
  1556. def _expired_computed_vars(self) -> set[str]:
  1557. """Determine ComputedVars that need to be recalculated based on the expiration time.
  1558. Returns:
  1559. Set of computed vars to include in the delta.
  1560. """
  1561. return {
  1562. cvar
  1563. for cvar in self.computed_vars
  1564. if self.computed_vars[cvar].needs_update(instance=self)
  1565. }
  1566. def _dirty_computed_vars(
  1567. self, from_vars: set[str] | None = None, include_backend: bool = True
  1568. ) -> set[tuple[str, str]]:
  1569. """Determine ComputedVars that need to be recalculated based on the given vars.
  1570. Args:
  1571. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  1572. include_backend: whether to include backend vars in the calculation.
  1573. Returns:
  1574. Set of computed vars to include in the delta.
  1575. """
  1576. return {
  1577. (state_name, cvar)
  1578. for dirty_var in from_vars or self.dirty_vars
  1579. for state_name, cvar in self._var_dependencies.get(dirty_var, set())
  1580. if include_backend or not self.computed_vars[cvar]._backend
  1581. }
  1582. def get_delta(self) -> Delta:
  1583. """Get the delta for the state.
  1584. Returns:
  1585. The delta for the state.
  1586. """
  1587. delta = {}
  1588. self._mark_dirty_computed_vars()
  1589. frontend_computed_vars: set[str] = {
  1590. name for name, cv in self.computed_vars.items() if not cv._backend
  1591. }
  1592. # Return the dirty vars for this instance, any cached/dependent computed vars,
  1593. # and always dirty computed vars (cache=False)
  1594. delta_vars = self.dirty_vars.intersection(self.base_vars).union(
  1595. self.dirty_vars.intersection(frontend_computed_vars)
  1596. )
  1597. subdelta: dict[str, Any] = {
  1598. prop + "_rx_state_": self.get_value(prop)
  1599. for prop in delta_vars
  1600. if not types.is_backend_base_variable(prop, type(self))
  1601. }
  1602. if len(subdelta) > 0:
  1603. delta[self.get_full_name()] = subdelta
  1604. # Recursively find the substate deltas.
  1605. substates = self.substates
  1606. for substate in self.dirty_substates.union(self._always_dirty_substates):
  1607. delta.update(substates[substate].get_delta())
  1608. # Return the delta.
  1609. return delta
  1610. async def _get_resolved_delta(self) -> Delta:
  1611. """Get the delta for the state after resolving all coroutines.
  1612. Returns:
  1613. The resolved delta for the state.
  1614. """
  1615. return await _resolve_delta(self.get_delta())
  1616. def _mark_dirty(self):
  1617. """Mark the substate and all parent states as dirty."""
  1618. state_name = self.get_name()
  1619. if (
  1620. self.parent_state is not None
  1621. and state_name not in self.parent_state.dirty_substates
  1622. ):
  1623. self.parent_state.dirty_substates.add(self.get_name())
  1624. self.parent_state._mark_dirty()
  1625. # have to mark computed vars dirty to allow access to newly computed
  1626. # values within the same ComputedVar function
  1627. self._mark_dirty_computed_vars()
  1628. def _update_was_touched(self):
  1629. """Update the _was_touched flag based on dirty_vars."""
  1630. if self.dirty_vars and not self._was_touched:
  1631. for var in self.dirty_vars:
  1632. if var in self.base_vars or var in self._backend_vars:
  1633. self._was_touched = True
  1634. break
  1635. if var == constants.ROUTER_DATA and self.parent_state is None:
  1636. self._was_touched = True
  1637. break
  1638. def _get_was_touched(self) -> bool:
  1639. """Check current dirty_vars and flag to determine if state instance was modified.
  1640. If any dirty vars belong to this state, mark _was_touched.
  1641. This flag determines whether this state instance should be persisted to redis.
  1642. Returns:
  1643. Whether this state instance was ever modified.
  1644. """
  1645. # Ensure the flag is up to date based on the current dirty_vars
  1646. self._update_was_touched()
  1647. return self._was_touched
  1648. def _clean(self):
  1649. """Reset the dirty vars."""
  1650. # Update touched status before cleaning dirty_vars.
  1651. self._update_was_touched()
  1652. # Recursively clean the substates.
  1653. for substate in self.dirty_substates:
  1654. if substate not in self.substates:
  1655. continue
  1656. self.substates[substate]._clean()
  1657. # Clean this state.
  1658. self.dirty_vars = set()
  1659. self.dirty_substates = set()
  1660. def get_value(self, key: str) -> Any:
  1661. """Get the value of a field (without proxying).
  1662. The returned value will NOT track dirty state updates.
  1663. Args:
  1664. key: The key of the field.
  1665. Returns:
  1666. The value of the field.
  1667. """
  1668. value = super().get_value(key)
  1669. if isinstance(value, MutableProxy):
  1670. return value.__wrapped__
  1671. return value
  1672. def dict(
  1673. self, include_computed: bool = True, initial: bool = False, **kwargs
  1674. ) -> dict[str, Any]:
  1675. """Convert the object to a dictionary.
  1676. Args:
  1677. include_computed: Whether to include computed vars.
  1678. initial: Whether to get the initial value of computed vars.
  1679. **kwargs: Kwargs to pass to the pydantic dict method.
  1680. Returns:
  1681. The object as a dictionary.
  1682. """
  1683. if include_computed:
  1684. self._mark_dirty_computed_vars()
  1685. base_vars = {
  1686. prop_name: self.get_value(prop_name) for prop_name in self.base_vars
  1687. }
  1688. if initial and include_computed:
  1689. computed_vars = {
  1690. # Include initial computed vars.
  1691. prop_name: (
  1692. cv._initial_value
  1693. if is_computed_var(cv)
  1694. and not isinstance(cv._initial_value, types.Unset)
  1695. else self.get_value(prop_name)
  1696. )
  1697. for prop_name, cv in self.computed_vars.items()
  1698. if not cv._backend
  1699. }
  1700. elif include_computed:
  1701. computed_vars = {
  1702. # Include the computed vars.
  1703. prop_name: self.get_value(prop_name)
  1704. for prop_name, cv in self.computed_vars.items()
  1705. if not cv._backend
  1706. }
  1707. else:
  1708. computed_vars = {}
  1709. variables = {**base_vars, **computed_vars}
  1710. d = {
  1711. self.get_full_name(): {
  1712. k + "_rx_state_": variables[k] for k in sorted(variables)
  1713. },
  1714. }
  1715. for substate_d in [
  1716. v.dict(include_computed=include_computed, initial=initial, **kwargs)
  1717. for v in self.substates.values()
  1718. ]:
  1719. d.update(substate_d)
  1720. return d
  1721. async def __aenter__(self) -> BaseState:
  1722. """Enter the async context manager protocol.
  1723. This should not be used for the State class, but exists for
  1724. type-compatibility with StateProxy.
  1725. Raises:
  1726. TypeError: always, because async contextmanager protocol is only supported for background task.
  1727. """
  1728. raise TypeError(
  1729. "Only background task should use `async with self` to modify state."
  1730. )
  1731. async def __aexit__(self, *exc_info: Any) -> None:
  1732. """Exit the async context manager protocol.
  1733. This should not be used for the State class, but exists for
  1734. type-compatibility with StateProxy.
  1735. Args:
  1736. exc_info: The exception info tuple.
  1737. """
  1738. pass
  1739. def __getstate__(self):
  1740. """Get the state for redis serialization.
  1741. This method is called by pickle to serialize the object.
  1742. It explicitly removes parent_state and substates because those are serialized separately
  1743. by the StateManagerRedis to allow for better horizontal scaling as state size increases.
  1744. Returns:
  1745. The state dict for serialization.
  1746. """
  1747. state = super().__getstate__()
  1748. state["__dict__"] = state["__dict__"].copy()
  1749. if state["__dict__"].get("parent_state") is not None:
  1750. # Do not serialize router data in substates (only the root state).
  1751. state["__dict__"].pop("router", None)
  1752. state["__dict__"].pop("router_data", None)
  1753. # Never serialize parent_state or substates.
  1754. state["__dict__"].pop("parent_state", None)
  1755. state["__dict__"].pop("substates", None)
  1756. state["__dict__"].pop("_was_touched", None)
  1757. # Remove all inherited vars.
  1758. for inherited_var_name in self.inherited_vars:
  1759. state["__dict__"].pop(inherited_var_name, None)
  1760. return state
  1761. def __setstate__(self, state: dict[str, Any]):
  1762. """Set the state from redis deserialization.
  1763. This method is called by pickle to deserialize the object.
  1764. Args:
  1765. state: The state dict for deserialization.
  1766. """
  1767. state["__dict__"]["parent_state"] = None
  1768. state["__dict__"]["substates"] = {}
  1769. super().__setstate__(state)
  1770. def _check_state_size(
  1771. self,
  1772. pickle_state_size: int,
  1773. ):
  1774. """Print a warning when the state is too large.
  1775. Args:
  1776. pickle_state_size: The size of the pickled state.
  1777. Raises:
  1778. StateTooLargeError: If the state is too large.
  1779. """
  1780. state_full_name = self.get_full_name()
  1781. if (
  1782. state_full_name not in _WARNED_ABOUT_STATE_SIZE
  1783. and pickle_state_size > TOO_LARGE_SERIALIZED_STATE
  1784. and self.substates
  1785. ):
  1786. msg = (
  1787. f"State {state_full_name} serializes to {pickle_state_size} bytes "
  1788. + "which may present performance issues. Consider reducing the size of this state."
  1789. )
  1790. if environment.REFLEX_PERF_MODE.get() == PerformanceMode.WARN:
  1791. console.warn(msg)
  1792. elif environment.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE:
  1793. raise StateTooLargeError(msg)
  1794. _WARNED_ABOUT_STATE_SIZE.add(state_full_name)
  1795. @classmethod
  1796. @functools.lru_cache
  1797. def _to_schema(cls) -> str:
  1798. """Convert a state to a schema.
  1799. Returns:
  1800. The hash of the schema.
  1801. """
  1802. def _field_tuple(
  1803. field_name: str,
  1804. ) -> tuple[str, str, Any, bool | None, Any]:
  1805. model_field = cls.__fields__[field_name]
  1806. return (
  1807. field_name,
  1808. model_field.name,
  1809. _serialize_type(model_field.type_),
  1810. (
  1811. model_field.required
  1812. if isinstance(model_field.required, bool)
  1813. else None
  1814. ),
  1815. (model_field.default if is_serializable(model_field.default) else None),
  1816. )
  1817. return md5(
  1818. pickle.dumps(
  1819. sorted(_field_tuple(field_name) for field_name in cls.base_vars)
  1820. )
  1821. ).hexdigest()
  1822. def _serialize(self) -> bytes:
  1823. """Serialize the state for redis.
  1824. Returns:
  1825. The serialized state.
  1826. Raises:
  1827. StateSerializationError: If the state cannot be serialized.
  1828. """
  1829. payload = b""
  1830. error = ""
  1831. try:
  1832. payload = pickle.dumps((self._to_schema(), self))
  1833. except HANDLED_PICKLE_ERRORS as og_pickle_error:
  1834. error = (
  1835. f"Failed to serialize state {self.get_full_name()} due to unpicklable object. "
  1836. "This state will not be persisted. "
  1837. )
  1838. try:
  1839. import dill
  1840. payload = dill.dumps((self._to_schema(), self))
  1841. except ImportError:
  1842. error += (
  1843. f"Pickle error: {og_pickle_error}. "
  1844. "Consider `pip install 'dill>=0.3.8'` for more exotic serialization support."
  1845. )
  1846. except HANDLED_PICKLE_ERRORS as ex:
  1847. error += f"Dill was also unable to pickle the state: {ex}"
  1848. console.warn(error)
  1849. if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF:
  1850. self._check_state_size(len(payload))
  1851. if not payload:
  1852. raise StateSerializationError(error)
  1853. return payload
  1854. @classmethod
  1855. def _deserialize(
  1856. cls, data: bytes | None = None, fp: BinaryIO | None = None
  1857. ) -> BaseState:
  1858. """Deserialize the state from redis/disk.
  1859. data and fp are mutually exclusive, but one must be provided.
  1860. Args:
  1861. data: The serialized state data.
  1862. fp: The file pointer to the serialized state data.
  1863. Returns:
  1864. The deserialized state.
  1865. Raises:
  1866. ValueError: If both data and fp are provided, or neither are provided.
  1867. StateSchemaMismatchError: If the state schema does not match the expected schema.
  1868. """
  1869. if data is not None and fp is None:
  1870. (substate_schema, state) = pickle.loads(data)
  1871. elif fp is not None and data is None:
  1872. (substate_schema, state) = pickle.load(fp)
  1873. else:
  1874. raise ValueError("Only one of `data` or `fp` must be provided")
  1875. if substate_schema != state._to_schema():
  1876. raise StateSchemaMismatchError()
  1877. return state
  1878. def _serialize_type(type_: Any) -> str:
  1879. """Serialize a type.
  1880. Args:
  1881. type_: The type to serialize.
  1882. Returns:
  1883. The serialized type.
  1884. """
  1885. if not inspect.isclass(type_):
  1886. return f"{type_}"
  1887. return f"{type_.__module__}.{type_.__qualname__}"
  1888. def is_serializable(value: Any) -> bool:
  1889. """Check if a value is serializable.
  1890. Args:
  1891. value: The value to check.
  1892. Returns:
  1893. Whether the value is serializable.
  1894. """
  1895. try:
  1896. return bool(pickle.dumps(value))
  1897. except Exception:
  1898. return False
  1899. T_STATE = TypeVar("T_STATE", bound=BaseState)
  1900. class State(BaseState):
  1901. """The app Base State."""
  1902. # The hydrated bool.
  1903. is_hydrated: bool = False
  1904. T = TypeVar("T", bound=BaseState)
  1905. def dynamic(func: Callable[[T], Component]):
  1906. """Create a dynamically generated components from a state class.
  1907. Args:
  1908. func: The function to generate the component.
  1909. Returns:
  1910. The dynamically generated component.
  1911. Raises:
  1912. DynamicComponentInvalidSignatureError: If the function does not have exactly one parameter or a type hint for the state class.
  1913. """
  1914. number_of_parameters = len(inspect.signature(func).parameters)
  1915. func_signature = get_type_hints(func)
  1916. if "return" in func_signature:
  1917. func_signature.pop("return")
  1918. values = list(func_signature.values())
  1919. if number_of_parameters != 1:
  1920. raise DynamicComponentInvalidSignatureError(
  1921. "The function must have exactly one parameter, which is the state class."
  1922. )
  1923. if len(values) != 1:
  1924. raise DynamicComponentInvalidSignatureError(
  1925. "You must provide a type hint for the state class in the function."
  1926. )
  1927. state_class: type[T] = values[0]
  1928. def wrapper() -> Component:
  1929. from reflex.components.base.fragment import fragment
  1930. return fragment(state_class._evaluate(lambda state: func(state)))
  1931. return wrapper
  1932. class FrontendEventExceptionState(State):
  1933. """Substate for handling frontend exceptions."""
  1934. @event
  1935. def handle_frontend_exception(self, stack: str, component_stack: str) -> None:
  1936. """Handle frontend exceptions.
  1937. If a frontend exception handler is provided, it will be called.
  1938. Otherwise, the default frontend exception handler will be called.
  1939. Args:
  1940. stack: The stack trace of the exception.
  1941. component_stack: The stack trace of the component where the exception occurred.
  1942. """
  1943. prerequisites.get_and_validate_app().app.frontend_exception_handler(
  1944. Exception(stack)
  1945. )
  1946. class UpdateVarsInternalState(State):
  1947. """Substate for handling internal state var updates."""
  1948. async def update_vars_internal(self, vars: dict[str, Any]) -> None:
  1949. """Apply updates to fully qualified state vars.
  1950. The keys in `vars` should be in the form of `{state.get_full_name()}.{var_name}`,
  1951. and each value will be set on the appropriate substate instance.
  1952. This function is primarily used to apply cookie and local storage
  1953. updates from the frontend to the appropriate substate.
  1954. Args:
  1955. vars: The fully qualified vars and values to update.
  1956. """
  1957. for var, value in vars.items():
  1958. state_name, _, var_name = var.rpartition(".")
  1959. var_state_cls = State.get_class_substate(state_name)
  1960. var_state = await self.get_state(var_state_cls)
  1961. setattr(var_state, var_name, value)
  1962. class OnLoadInternalState(State):
  1963. """Substate for handling on_load event enumeration.
  1964. This is a separate substate to avoid deserializing the entire state tree for every page navigation.
  1965. """
  1966. def on_load_internal(self) -> list[Event | EventSpec] | None:
  1967. """Queue on_load handlers for the current page.
  1968. Returns:
  1969. The list of events to queue for on load handling.
  1970. """
  1971. # Do not app._compile()! It should be already compiled by now.
  1972. load_events = prerequisites.get_and_validate_app().app.get_load_events(
  1973. self.router.page.path
  1974. )
  1975. if not load_events:
  1976. self.is_hydrated = True
  1977. return # Fast path for navigation with no on_load events defined.
  1978. self.is_hydrated = False
  1979. return [
  1980. *fix_events(
  1981. cast(list[EventSpec | EventHandler], load_events),
  1982. self.router.session.client_token,
  1983. router_data=self.router_data,
  1984. ),
  1985. State.set_is_hydrated(True), # pyright: ignore [reportAttributeAccessIssue]
  1986. ]
  1987. class ComponentState(State, mixin=True):
  1988. """Base class to allow for the creation of a state instance per component.
  1989. This allows for the bundling of UI and state logic into a single class,
  1990. where each instance has a separate instance of the state.
  1991. Subclass this class and define vars and event handlers in the traditional way.
  1992. Then define a `get_component` method that returns the UI for the component instance.
  1993. See the full [docs](https://reflex.dev/docs/substates/component-state/) for more.
  1994. Basic example:
  1995. ```python
  1996. # Subclass ComponentState and define vars and event handlers.
  1997. class Counter(rx.ComponentState):
  1998. # Define vars that change.
  1999. count: int = 0
  2000. # Define event handlers.
  2001. def increment(self):
  2002. self.count += 1
  2003. def decrement(self):
  2004. self.count -= 1
  2005. @classmethod
  2006. def get_component(cls, **props):
  2007. # Access the state vars and event handlers using `cls`.
  2008. return rx.hstack(
  2009. rx.button("Decrement", on_click=cls.decrement),
  2010. rx.text(cls.count),
  2011. rx.button("Increment", on_click=cls.increment),
  2012. **props,
  2013. )
  2014. counter = Counter.create()
  2015. ```
  2016. """
  2017. # The number of components created from this class.
  2018. _per_component_state_instance_count: ClassVar[int] = 0
  2019. def __init__(self, *args, **kwargs):
  2020. """Do not allow direct initialization of the ComponentState.
  2021. Args:
  2022. *args: The args to pass to the State init method.
  2023. **kwargs: The kwargs to pass to the State init method.
  2024. Raises:
  2025. ReflexRuntimeError: If the ComponentState is initialized directly.
  2026. """
  2027. if type(self)._mixin:
  2028. raise ReflexRuntimeError(
  2029. f"{ComponentState.__name__} {type(self).__name__} is not meant to be initialized directly. "
  2030. + "Use the `create` method to create a new instance and access the state via the `State` attribute."
  2031. )
  2032. super().__init__(*args, **kwargs)
  2033. @classmethod
  2034. def __init_subclass__(cls, mixin: bool = True, **kwargs):
  2035. """Overwrite mixin default to True.
  2036. Args:
  2037. mixin: Whether the subclass is a mixin and should not be initialized.
  2038. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  2039. """
  2040. super().__init_subclass__(mixin=mixin, **kwargs)
  2041. @classmethod
  2042. def get_component(cls, *children, **props) -> Component:
  2043. """Get the component instance.
  2044. Args:
  2045. children: The children of the component.
  2046. props: The props of the component.
  2047. Raises:
  2048. NotImplementedError: if the subclass does not override this method.
  2049. """
  2050. raise NotImplementedError(
  2051. f"{cls.__name__} must implement get_component to return the component instance."
  2052. )
  2053. @classmethod
  2054. def create(cls, *children, **props) -> Component:
  2055. """Create a new instance of the Component.
  2056. Args:
  2057. children: The children of the component.
  2058. props: The props of the component.
  2059. Returns:
  2060. A new instance of the Component with an independent copy of the State.
  2061. """
  2062. from reflex.compiler.compiler import into_component
  2063. cls._per_component_state_instance_count += 1
  2064. state_cls_name = f"{cls.__name__}_n{cls._per_component_state_instance_count}"
  2065. component_state = type(
  2066. state_cls_name,
  2067. (cls, State),
  2068. {"__module__": reflex.istate.dynamic.__name__},
  2069. mixin=False,
  2070. )
  2071. # Save a reference to the dynamic state for pickle/unpickle.
  2072. setattr(reflex.istate.dynamic, state_cls_name, component_state)
  2073. component = component_state.get_component(*children, **props)
  2074. component = into_component(component)
  2075. component.State = component_state
  2076. return component
  2077. @dataclasses.dataclass(
  2078. frozen=True,
  2079. )
  2080. class StateUpdate:
  2081. """A state update sent to the frontend."""
  2082. # The state delta.
  2083. delta: Delta = dataclasses.field(default_factory=dict)
  2084. # Events to be added to the event queue.
  2085. events: list[Event] = dataclasses.field(default_factory=list)
  2086. # Whether this is the final state update for the event.
  2087. final: bool = True
  2088. def json(self) -> str:
  2089. """Convert the state update to a JSON string.
  2090. Returns:
  2091. The state update as a JSON string.
  2092. """
  2093. return format.json_dumps(self)
  2094. def code_uses_state_contexts(javascript_code: str) -> bool:
  2095. """Check if the rendered Javascript uses state contexts.
  2096. Args:
  2097. javascript_code: The Javascript code to check.
  2098. Returns:
  2099. True if the code attempts to access a member of StateContexts.
  2100. """
  2101. return bool("useContext(StateContexts" in javascript_code)
  2102. def reload_state_module(
  2103. module: str,
  2104. state: type[BaseState] = State,
  2105. ) -> None:
  2106. """Reset rx.State subclasses to avoid conflict when reloading.
  2107. Args:
  2108. module: The module to reload.
  2109. state: Recursive argument for the state class to reload.
  2110. """
  2111. # Clean out all potentially dirty states of reloaded modules.
  2112. for pd_state in tuple(state._potentially_dirty_states):
  2113. with contextlib.suppress(ValueError):
  2114. if (
  2115. state.get_root_state().get_class_substate(pd_state).__module__ == module
  2116. and module is not None
  2117. ):
  2118. state._potentially_dirty_states.remove(pd_state)
  2119. for subclass in tuple(state.class_subclasses):
  2120. reload_state_module(module=module, state=subclass)
  2121. if subclass.__module__ == module and module is not None:
  2122. all_base_state_classes.pop(subclass.get_full_name(), None)
  2123. state.class_subclasses.remove(subclass)
  2124. state._always_dirty_substates.discard(subclass.get_name())
  2125. state._var_dependencies = {}
  2126. state._init_var_dependency_dicts()
  2127. state.get_class_substate.cache_clear()
  2128. from reflex.istate.manager import LockExpiredError as LockExpiredError # noqa: E402
  2129. from reflex.istate.manager import StateManager as StateManager # noqa: E402
  2130. from reflex.istate.manager import StateManagerDisk as StateManagerDisk # noqa: E402
  2131. from reflex.istate.manager import StateManagerMemory as StateManagerMemory # noqa: E402
  2132. from reflex.istate.manager import StateManagerRedis as StateManagerRedis # noqa: E402
  2133. from reflex.istate.manager import get_state_manager as get_state_manager # noqa: E402
  2134. from reflex.istate.manager import ( # noqa: E402
  2135. reset_disk_state_manager as reset_disk_state_manager,
  2136. )