state.py 133 KB

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