state.py 137 KB

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