state.py 141 KB

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