state.py 139 KB

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