state.py 139 KB

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