state.py 134 KB

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