state.py 131 KB

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