state.py 127 KB

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