1
0

state.py 142 KB

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