state.py 139 KB

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