state.py 137 KB

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