state.py 138 KB

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