state.py 126 KB

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