state.py 139 KB

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