1
0

state.py 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138
  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. def _reset_client_storage(self):
  1136. """Reset client storage base vars to their default values."""
  1137. # Client-side storage is reset during hydrate so that clearing cookies
  1138. # on the browser also resets the values on the backend.
  1139. fields = self.get_fields()
  1140. for prop_name in self.base_vars:
  1141. field = fields[prop_name]
  1142. if isinstance(field.default, ClientStorageBase) or (
  1143. isinstance(field.type_, type)
  1144. and issubclass(field.type_, ClientStorageBase)
  1145. ):
  1146. setattr(self, prop_name, copy.deepcopy(field.default))
  1147. # Recursively reset the substate client storage.
  1148. for substate in self.substates.values():
  1149. substate._reset_client_storage()
  1150. def get_substate(self, path: Sequence[str]) -> BaseState:
  1151. """Get the substate.
  1152. Args:
  1153. path: The path to the substate.
  1154. Returns:
  1155. The substate.
  1156. Raises:
  1157. ValueError: If the substate is not found.
  1158. """
  1159. if len(path) == 0:
  1160. return self
  1161. if path[0] == self.get_name():
  1162. if len(path) == 1:
  1163. return self
  1164. path = path[1:]
  1165. if path[0] not in self.substates:
  1166. raise ValueError(f"Invalid path: {path}")
  1167. return self.substates[path[0]].get_substate(path[1:])
  1168. @classmethod
  1169. def _get_common_ancestor(cls, other: Type[BaseState]) -> str:
  1170. """Find the name of the nearest common ancestor shared by this and the other state.
  1171. Args:
  1172. other: The other state.
  1173. Returns:
  1174. Full name of the nearest common ancestor.
  1175. """
  1176. common_ancestor_parts = []
  1177. for part1, part2 in zip(
  1178. cls.get_full_name().split("."),
  1179. other.get_full_name().split("."),
  1180. ):
  1181. if part1 != part2:
  1182. break
  1183. common_ancestor_parts.append(part1)
  1184. return ".".join(common_ancestor_parts)
  1185. @classmethod
  1186. def _determine_missing_parent_states(
  1187. cls, target_state_cls: Type[BaseState]
  1188. ) -> tuple[str, list[str]]:
  1189. """Determine the missing parent states between the target_state_cls and common ancestor of this state.
  1190. Args:
  1191. target_state_cls: The class of the state to find missing parent states for.
  1192. Returns:
  1193. The name of the common ancestor and the list of missing parent states.
  1194. """
  1195. common_ancestor_name = cls._get_common_ancestor(target_state_cls)
  1196. common_ancestor_parts = common_ancestor_name.split(".")
  1197. target_state_parts = tuple(target_state_cls.get_full_name().split("."))
  1198. relative_target_state_parts = target_state_parts[len(common_ancestor_parts) :]
  1199. # Determine which parent states to fetch from the common ancestor down to the target_state_cls.
  1200. fetch_parent_states = [common_ancestor_name]
  1201. for relative_parent_state_name in relative_target_state_parts:
  1202. fetch_parent_states.append(
  1203. ".".join((fetch_parent_states[-1], relative_parent_state_name))
  1204. )
  1205. return common_ancestor_name, fetch_parent_states[1:-1]
  1206. def _get_parent_states(self) -> list[tuple[str, BaseState]]:
  1207. """Get all parent state instances up to the root of the state tree.
  1208. Returns:
  1209. A list of tuples containing the name and the instance of each parent state.
  1210. """
  1211. parent_states_with_name = []
  1212. parent_state = self
  1213. while parent_state.parent_state is not None:
  1214. parent_state = parent_state.parent_state
  1215. parent_states_with_name.append((parent_state.get_full_name(), parent_state))
  1216. return parent_states_with_name
  1217. def _get_root_state(self) -> BaseState:
  1218. """Get the root state of the state tree.
  1219. Returns:
  1220. The root state of the state tree.
  1221. """
  1222. parent_state = self
  1223. while parent_state.parent_state is not None:
  1224. parent_state = parent_state.parent_state
  1225. return parent_state
  1226. async def _populate_parent_states(self, target_state_cls: Type[BaseState]):
  1227. """Populate substates in the tree between the target_state_cls and common ancestor of this state.
  1228. Args:
  1229. target_state_cls: The class of the state to populate parent states for.
  1230. Returns:
  1231. The parent state instance of target_state_cls.
  1232. Raises:
  1233. RuntimeError: If redis is not used in this backend process.
  1234. """
  1235. state_manager = get_state_manager()
  1236. if not isinstance(state_manager, StateManagerRedis):
  1237. raise RuntimeError(
  1238. f"Cannot populate parent states of {target_state_cls.get_full_name()} without redis. "
  1239. "(All states should already be available -- this is likely a bug).",
  1240. )
  1241. # Find the missing parent states up to the common ancestor.
  1242. (
  1243. common_ancestor_name,
  1244. missing_parent_states,
  1245. ) = self._determine_missing_parent_states(target_state_cls)
  1246. # Fetch all missing parent states and link them up to the common ancestor.
  1247. parent_states_tuple = self._get_parent_states()
  1248. root_state = parent_states_tuple[-1][1]
  1249. parent_states_by_name = dict(parent_states_tuple)
  1250. parent_state = parent_states_by_name[common_ancestor_name]
  1251. for parent_state_name in missing_parent_states:
  1252. try:
  1253. parent_state = root_state.get_substate(parent_state_name.split("."))
  1254. # The requested state is already cached, do NOT fetch it again.
  1255. continue
  1256. except ValueError:
  1257. # The requested state is missing, fetch from redis.
  1258. pass
  1259. parent_state = await state_manager.get_state(
  1260. token=_substate_key(
  1261. self.router.session.client_token, parent_state_name
  1262. ),
  1263. top_level=False,
  1264. get_substates=False,
  1265. parent_state=parent_state,
  1266. )
  1267. # Return the direct parent of target_state_cls for subsequent linking.
  1268. return parent_state
  1269. def _get_state_from_cache(self, state_cls: Type[BaseState]) -> BaseState:
  1270. """Get a state instance from the cache.
  1271. Args:
  1272. state_cls: The class of the state.
  1273. Returns:
  1274. The instance of state_cls associated with this state's client_token.
  1275. """
  1276. root_state = self._get_root_state()
  1277. return root_state.get_substate(state_cls.get_full_name().split("."))
  1278. async def _get_state_from_redis(self, state_cls: Type[BaseState]) -> BaseState:
  1279. """Get a state instance from redis.
  1280. Args:
  1281. state_cls: The class of the state.
  1282. Returns:
  1283. The instance of state_cls associated with this state's client_token.
  1284. Raises:
  1285. RuntimeError: If redis is not used in this backend process.
  1286. """
  1287. # Fetch all missing parent states from redis.
  1288. parent_state_of_state_cls = await self._populate_parent_states(state_cls)
  1289. # Then get the target state and all its substates.
  1290. state_manager = get_state_manager()
  1291. if not isinstance(state_manager, StateManagerRedis):
  1292. raise RuntimeError(
  1293. f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. "
  1294. "(All states should already be available -- this is likely a bug).",
  1295. )
  1296. return await state_manager.get_state(
  1297. token=_substate_key(self.router.session.client_token, state_cls),
  1298. top_level=False,
  1299. get_substates=True,
  1300. parent_state=parent_state_of_state_cls,
  1301. )
  1302. async def get_state(self, state_cls: Type[BaseState]) -> BaseState:
  1303. """Get an instance of the state associated with this token.
  1304. Allows for arbitrary access to sibling states from within an event handler.
  1305. Args:
  1306. state_cls: The class of the state.
  1307. Returns:
  1308. The instance of state_cls associated with this state's client_token.
  1309. """
  1310. # Fast case - if this state instance is already cached, get_substate from root state.
  1311. try:
  1312. return self._get_state_from_cache(state_cls)
  1313. except ValueError:
  1314. pass
  1315. # Slow case - fetch missing parent states from redis.
  1316. return await self._get_state_from_redis(state_cls)
  1317. async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE:
  1318. """Get the value of an rx.Var from another state.
  1319. Args:
  1320. var: The var to get the value for.
  1321. Returns:
  1322. The value of the var.
  1323. Raises:
  1324. UnretrievableVarValueError: If the var does not have a literal value
  1325. or associated state.
  1326. """
  1327. # Oopsie case: you didn't give me a Var... so get what you give.
  1328. if not isinstance(var, Var):
  1329. return var # type: ignore
  1330. # Fast case: this is a literal var and the value is known.
  1331. if hasattr(var, "_var_value"):
  1332. return var._var_value
  1333. var_data = var._get_all_var_data()
  1334. if var_data is None or not var_data.state:
  1335. raise UnretrievableVarValueError(
  1336. f"Unable to retrieve value for {var._js_expr}: not associated with any state."
  1337. )
  1338. # Fastish case: this var belongs to this state
  1339. if var_data.state == self.get_full_name():
  1340. return getattr(self, var_data.field_name)
  1341. # Slow case: this var belongs to another state
  1342. other_state = await self.get_state(
  1343. self._get_root_state().get_class_substate(var_data.state)
  1344. )
  1345. return getattr(other_state, var_data.field_name)
  1346. def _get_event_handler(
  1347. self, event: Event
  1348. ) -> tuple[BaseState | StateProxy, EventHandler]:
  1349. """Get the event handler for the given event.
  1350. Args:
  1351. event: The event to get the handler for.
  1352. Returns:
  1353. The event handler.
  1354. Raises:
  1355. ValueError: If the event handler or substate is not found.
  1356. """
  1357. # Get the event handler.
  1358. path = event.name.split(".")
  1359. path, name = path[:-1], path[-1]
  1360. substate = self.get_substate(path)
  1361. if not substate:
  1362. raise ValueError(
  1363. "The value of state cannot be None when processing an event."
  1364. )
  1365. handler = substate.event_handlers[name]
  1366. # For background tasks, proxy the state
  1367. if handler.is_background:
  1368. substate = StateProxy(substate)
  1369. return substate, handler
  1370. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  1371. """Obtain event info and process event.
  1372. Args:
  1373. event: The event to process.
  1374. Yields:
  1375. The state update after processing the event.
  1376. """
  1377. # Get the event handler.
  1378. substate, handler = self._get_event_handler(event)
  1379. # Run the event generator and yield state updates.
  1380. async for update in self._process_event(
  1381. handler=handler,
  1382. state=substate,
  1383. payload=event.payload,
  1384. ):
  1385. yield update
  1386. def _check_valid(self, handler: EventHandler, events: Any) -> Any:
  1387. """Check if the events yielded are valid. They must be EventHandlers or EventSpecs.
  1388. Args:
  1389. handler: EventHandler.
  1390. events: The events to be checked.
  1391. Raises:
  1392. TypeError: If any of the events are not valid.
  1393. Returns:
  1394. The events as they are if valid.
  1395. """
  1396. def _is_valid_type(events: Any) -> bool:
  1397. return isinstance(events, (Event, EventHandler, EventSpec))
  1398. if events is None or _is_valid_type(events):
  1399. return events
  1400. try:
  1401. if all(_is_valid_type(e) for e in events):
  1402. return events
  1403. except TypeError:
  1404. pass
  1405. raise TypeError(
  1406. f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`)"
  1407. )
  1408. def _as_state_update(
  1409. self,
  1410. handler: EventHandler,
  1411. events: EventSpec | list[EventSpec] | None,
  1412. final: bool,
  1413. ) -> StateUpdate:
  1414. """Convert the events to a StateUpdate.
  1415. Fixes the events and checks for validity before converting.
  1416. Args:
  1417. handler: The handler where the events originated from.
  1418. events: The events to queue with the update.
  1419. final: Whether the handler is done processing.
  1420. Returns:
  1421. The valid StateUpdate containing the events and final flag.
  1422. """
  1423. # get the delta from the root of the state tree
  1424. state = self._get_root_state()
  1425. token = self.router.session.client_token
  1426. # Convert valid EventHandler and EventSpec into Event
  1427. fixed_events = fix_events(self._check_valid(handler, events), token)
  1428. try:
  1429. # Get the delta after processing the event.
  1430. delta = state.get_delta()
  1431. state._clean()
  1432. return StateUpdate(
  1433. delta=delta,
  1434. events=fixed_events,
  1435. final=final if not handler.is_background else True,
  1436. )
  1437. except Exception as ex:
  1438. state._clean()
  1439. app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1440. event_specs = app_instance.backend_exception_handler(ex)
  1441. if event_specs is None:
  1442. return StateUpdate()
  1443. event_specs_correct_type = cast(
  1444. Union[List[Union[EventSpec, EventHandler]], None],
  1445. [event_specs] if isinstance(event_specs, EventSpec) else event_specs,
  1446. )
  1447. fixed_events = fix_events(
  1448. event_specs_correct_type,
  1449. token,
  1450. router_data=state.router_data,
  1451. )
  1452. return StateUpdate(
  1453. events=fixed_events,
  1454. final=True,
  1455. )
  1456. async def _process_event(
  1457. self, handler: EventHandler, state: BaseState | StateProxy, payload: Dict
  1458. ) -> AsyncIterator[StateUpdate]:
  1459. """Process event.
  1460. Args:
  1461. handler: EventHandler to process.
  1462. state: State to process the handler.
  1463. payload: The event payload.
  1464. Yields:
  1465. StateUpdate object
  1466. """
  1467. from reflex.utils import telemetry
  1468. # Get the function to process the event.
  1469. fn = functools.partial(handler.fn, state)
  1470. try:
  1471. type_hints = typing.get_type_hints(handler.fn)
  1472. except Exception:
  1473. type_hints = {}
  1474. for arg, value in list(payload.items()):
  1475. hinted_args = type_hints.get(arg, Any)
  1476. if hinted_args is Any:
  1477. continue
  1478. if is_union(hinted_args):
  1479. if value is None:
  1480. continue
  1481. hinted_args = value_inside_optional(hinted_args)
  1482. if (
  1483. isinstance(value, dict)
  1484. and inspect.isclass(hinted_args)
  1485. and not types.is_generic_alias(hinted_args) # py3.9-py3.10
  1486. ):
  1487. if issubclass(hinted_args, Model):
  1488. # Remove non-fields from the payload
  1489. payload[arg] = hinted_args(
  1490. **{
  1491. key: value
  1492. for key, value in value.items()
  1493. if key in hinted_args.__fields__
  1494. }
  1495. )
  1496. elif dataclasses.is_dataclass(hinted_args) or issubclass(
  1497. hinted_args, (Base, BaseModelV1, BaseModelV2)
  1498. ):
  1499. payload[arg] = hinted_args(**value)
  1500. if isinstance(value, list) and (hinted_args is set or hinted_args is Set):
  1501. payload[arg] = set(value)
  1502. if isinstance(value, list) and (
  1503. hinted_args is tuple or hinted_args is Tuple
  1504. ):
  1505. payload[arg] = tuple(value)
  1506. # Wrap the function in a try/except block.
  1507. try:
  1508. # Handle async functions.
  1509. if asyncio.iscoroutinefunction(fn.func):
  1510. events = await fn(**payload)
  1511. # Handle regular functions.
  1512. else:
  1513. events = fn(**payload)
  1514. # Handle async generators.
  1515. if inspect.isasyncgen(events):
  1516. async for event in events:
  1517. yield state._as_state_update(handler, event, final=False)
  1518. yield state._as_state_update(handler, events=None, final=True)
  1519. # Handle regular generators.
  1520. elif inspect.isgenerator(events):
  1521. try:
  1522. while True:
  1523. yield state._as_state_update(handler, next(events), final=False)
  1524. except StopIteration as si:
  1525. # the "return" value of the generator is not available
  1526. # in the loop, we must catch StopIteration to access it
  1527. if si.value is not None:
  1528. yield state._as_state_update(handler, si.value, final=False)
  1529. yield state._as_state_update(handler, events=None, final=True)
  1530. # Handle regular event chains.
  1531. else:
  1532. yield state._as_state_update(handler, events, final=True)
  1533. # If an error occurs, throw a window alert.
  1534. except Exception as ex:
  1535. telemetry.send_error(ex, context="backend")
  1536. app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1537. event_specs = app_instance.backend_exception_handler(ex)
  1538. yield state._as_state_update(
  1539. handler,
  1540. event_specs,
  1541. final=True,
  1542. )
  1543. def _mark_dirty_computed_vars(self) -> None:
  1544. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  1545. dirty_vars = self.dirty_vars
  1546. while dirty_vars:
  1547. calc_vars, dirty_vars = dirty_vars, set()
  1548. for cvar in self._dirty_computed_vars(from_vars=calc_vars):
  1549. self.dirty_vars.add(cvar)
  1550. dirty_vars.add(cvar)
  1551. actual_var = self.computed_vars.get(cvar)
  1552. if actual_var is not None:
  1553. actual_var.mark_dirty(instance=self)
  1554. def _expired_computed_vars(self) -> set[str]:
  1555. """Determine ComputedVars that need to be recalculated based on the expiration time.
  1556. Returns:
  1557. Set of computed vars to include in the delta.
  1558. """
  1559. return {
  1560. cvar
  1561. for cvar in self.computed_vars
  1562. if self.computed_vars[cvar].needs_update(instance=self)
  1563. }
  1564. def _dirty_computed_vars(
  1565. self, from_vars: set[str] | None = None, include_backend: bool = True
  1566. ) -> set[str]:
  1567. """Determine ComputedVars that need to be recalculated based on the given vars.
  1568. Args:
  1569. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  1570. include_backend: whether to include backend vars in the calculation.
  1571. Returns:
  1572. Set of computed vars to include in the delta.
  1573. """
  1574. return {
  1575. cvar
  1576. for dirty_var in from_vars or self.dirty_vars
  1577. for cvar in self._computed_var_dependencies[dirty_var]
  1578. if include_backend or not self.computed_vars[cvar]._backend
  1579. }
  1580. @classmethod
  1581. def _potentially_dirty_substates(cls) -> set[Type[BaseState]]:
  1582. """Determine substates which could be affected by dirty vars in this state.
  1583. Returns:
  1584. Set of State classes that may need to be fetched to recalc computed vars.
  1585. """
  1586. # _always_dirty_substates need to be fetched to recalc computed vars.
  1587. fetch_substates = {
  1588. cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
  1589. for substate_name in cls._always_dirty_substates
  1590. }
  1591. for dependent_substates in cls._substate_var_dependencies.values():
  1592. fetch_substates.update(
  1593. {
  1594. cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
  1595. for substate_name in dependent_substates
  1596. }
  1597. )
  1598. return fetch_substates
  1599. def get_delta(self) -> Delta:
  1600. """Get the delta for the state.
  1601. Returns:
  1602. The delta for the state.
  1603. """
  1604. delta = {}
  1605. # Apply dirty variables down into substates
  1606. self.dirty_vars.update(self._always_dirty_computed_vars)
  1607. self._mark_dirty()
  1608. frontend_computed_vars: set[str] = {
  1609. name for name, cv in self.computed_vars.items() if not cv._backend
  1610. }
  1611. # Return the dirty vars for this instance, any cached/dependent computed vars,
  1612. # and always dirty computed vars (cache=False)
  1613. delta_vars = (
  1614. self.dirty_vars.intersection(self.base_vars)
  1615. .union(self.dirty_vars.intersection(frontend_computed_vars))
  1616. .union(self._dirty_computed_vars(include_backend=False))
  1617. .union(self._always_dirty_computed_vars)
  1618. )
  1619. subdelta: Dict[str, Any] = {
  1620. prop: self.get_value(prop)
  1621. for prop in delta_vars
  1622. if not types.is_backend_base_variable(prop, type(self))
  1623. }
  1624. if len(subdelta) > 0:
  1625. delta[self.get_full_name()] = subdelta
  1626. # Recursively find the substate deltas.
  1627. substates = self.substates
  1628. for substate in self.dirty_substates.union(self._always_dirty_substates):
  1629. delta.update(substates[substate].get_delta())
  1630. # Return the delta.
  1631. return delta
  1632. def _mark_dirty(self):
  1633. """Mark the substate and all parent states as dirty."""
  1634. state_name = self.get_name()
  1635. if (
  1636. self.parent_state is not None
  1637. and state_name not in self.parent_state.dirty_substates
  1638. ):
  1639. self.parent_state.dirty_substates.add(self.get_name())
  1640. self.parent_state._mark_dirty()
  1641. # Append expired computed vars to dirty_vars to trigger recalculation
  1642. self.dirty_vars.update(self._expired_computed_vars())
  1643. # have to mark computed vars dirty to allow access to newly computed
  1644. # values within the same ComputedVar function
  1645. self._mark_dirty_computed_vars()
  1646. self._mark_dirty_substates()
  1647. def _mark_dirty_substates(self):
  1648. """Propagate dirty var / computed var status into substates."""
  1649. substates = self.substates
  1650. for var in self.dirty_vars:
  1651. for substate_name in self._substate_var_dependencies[var]:
  1652. self.dirty_substates.add(substate_name)
  1653. substate = substates[substate_name]
  1654. substate.dirty_vars.add(var)
  1655. substate._mark_dirty()
  1656. def _update_was_touched(self):
  1657. """Update the _was_touched flag based on dirty_vars."""
  1658. if self.dirty_vars and not self._was_touched:
  1659. for var in self.dirty_vars:
  1660. if var in self.base_vars or var in self._backend_vars:
  1661. self._was_touched = True
  1662. break
  1663. if var == constants.ROUTER_DATA and self.parent_state is None:
  1664. self._was_touched = True
  1665. break
  1666. def _get_was_touched(self) -> bool:
  1667. """Check current dirty_vars and flag to determine if state instance was modified.
  1668. If any dirty vars belong to this state, mark _was_touched.
  1669. This flag determines whether this state instance should be persisted to redis.
  1670. Returns:
  1671. Whether this state instance was ever modified.
  1672. """
  1673. # Ensure the flag is up to date based on the current dirty_vars
  1674. self._update_was_touched()
  1675. return self._was_touched
  1676. def _clean(self):
  1677. """Reset the dirty vars."""
  1678. # Update touched status before cleaning dirty_vars.
  1679. self._update_was_touched()
  1680. # Recursively clean the substates.
  1681. for substate in self.dirty_substates:
  1682. if substate not in self.substates:
  1683. continue
  1684. self.substates[substate]._clean()
  1685. # Clean this state.
  1686. self.dirty_vars = set()
  1687. self.dirty_substates = set()
  1688. def get_value(self, key: str) -> Any:
  1689. """Get the value of a field (without proxying).
  1690. The returned value will NOT track dirty state updates.
  1691. Args:
  1692. key: The key of the field.
  1693. Returns:
  1694. The value of the field.
  1695. """
  1696. value = super().get_value(key)
  1697. if isinstance(value, MutableProxy):
  1698. return value.__wrapped__
  1699. return value
  1700. def dict(
  1701. self, include_computed: bool = True, initial: bool = False, **kwargs
  1702. ) -> dict[str, Any]:
  1703. """Convert the object to a dictionary.
  1704. Args:
  1705. include_computed: Whether to include computed vars.
  1706. initial: Whether to get the initial value of computed vars.
  1707. **kwargs: Kwargs to pass to the pydantic dict method.
  1708. Returns:
  1709. The object as a dictionary.
  1710. """
  1711. if include_computed:
  1712. # Apply dirty variables down into substates to allow never-cached ComputedVar to
  1713. # trigger recalculation of dependent vars
  1714. self.dirty_vars.update(self._always_dirty_computed_vars)
  1715. self._mark_dirty()
  1716. base_vars = {
  1717. prop_name: self.get_value(prop_name) for prop_name in self.base_vars
  1718. }
  1719. if initial and include_computed:
  1720. computed_vars = {
  1721. # Include initial computed vars.
  1722. prop_name: (
  1723. cv._initial_value
  1724. if is_computed_var(cv)
  1725. and not isinstance(cv._initial_value, types.Unset)
  1726. else self.get_value(prop_name)
  1727. )
  1728. for prop_name, cv in self.computed_vars.items()
  1729. if not cv._backend
  1730. }
  1731. elif include_computed:
  1732. computed_vars = {
  1733. # Include the computed vars.
  1734. prop_name: self.get_value(prop_name)
  1735. for prop_name, cv in self.computed_vars.items()
  1736. if not cv._backend
  1737. }
  1738. else:
  1739. computed_vars = {}
  1740. variables = {**base_vars, **computed_vars}
  1741. d = {
  1742. self.get_full_name(): {k: variables[k] for k in sorted(variables)},
  1743. }
  1744. for substate_d in [
  1745. v.dict(include_computed=include_computed, initial=initial, **kwargs)
  1746. for v in self.substates.values()
  1747. ]:
  1748. d.update(substate_d)
  1749. return d
  1750. async def __aenter__(self) -> BaseState:
  1751. """Enter the async context manager protocol.
  1752. This should not be used for the State class, but exists for
  1753. type-compatibility with StateProxy.
  1754. Raises:
  1755. TypeError: always, because async contextmanager protocol is only supported for background task.
  1756. """
  1757. raise TypeError(
  1758. "Only background task should use `async with self` to modify state."
  1759. )
  1760. async def __aexit__(self, *exc_info: Any) -> None:
  1761. """Exit the async context manager protocol.
  1762. This should not be used for the State class, but exists for
  1763. type-compatibility with StateProxy.
  1764. Args:
  1765. exc_info: The exception info tuple.
  1766. """
  1767. pass
  1768. def __getstate__(self):
  1769. """Get the state for redis serialization.
  1770. This method is called by pickle to serialize the object.
  1771. It explicitly removes parent_state and substates because those are serialized separately
  1772. by the StateManagerRedis to allow for better horizontal scaling as state size increases.
  1773. Returns:
  1774. The state dict for serialization.
  1775. """
  1776. state = super().__getstate__()
  1777. state["__dict__"] = state["__dict__"].copy()
  1778. if state["__dict__"].get("parent_state") is not None:
  1779. # Do not serialize router data in substates (only the root state).
  1780. state["__dict__"].pop("router", None)
  1781. state["__dict__"].pop("router_data", None)
  1782. # Never serialize parent_state or substates.
  1783. state["__dict__"].pop("parent_state", None)
  1784. state["__dict__"].pop("substates", None)
  1785. state["__dict__"].pop("_was_touched", None)
  1786. # Remove all inherited vars.
  1787. for inherited_var_name in self.inherited_vars:
  1788. state["__dict__"].pop(inherited_var_name, None)
  1789. return state
  1790. def __setstate__(self, state: dict[str, Any]):
  1791. """Set the state from redis deserialization.
  1792. This method is called by pickle to deserialize the object.
  1793. Args:
  1794. state: The state dict for deserialization.
  1795. """
  1796. state["__dict__"]["parent_state"] = None
  1797. state["__dict__"]["substates"] = {}
  1798. super().__setstate__(state)
  1799. def _check_state_size(
  1800. self,
  1801. pickle_state_size: int,
  1802. ):
  1803. """Print a warning when the state is too large.
  1804. Args:
  1805. pickle_state_size: The size of the pickled state.
  1806. Raises:
  1807. StateTooLargeError: If the state is too large.
  1808. """
  1809. state_full_name = self.get_full_name()
  1810. if (
  1811. state_full_name not in _WARNED_ABOUT_STATE_SIZE
  1812. and pickle_state_size > TOO_LARGE_SERIALIZED_STATE
  1813. and self.substates
  1814. ):
  1815. msg = (
  1816. f"State {state_full_name} serializes to {pickle_state_size} bytes "
  1817. + "which may present performance issues. Consider reducing the size of this state."
  1818. )
  1819. if environment.REFLEX_PERF_MODE.get() == PerformanceMode.WARN:
  1820. console.warn(msg)
  1821. elif environment.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE:
  1822. raise StateTooLargeError(msg)
  1823. _WARNED_ABOUT_STATE_SIZE.add(state_full_name)
  1824. @classmethod
  1825. @functools.lru_cache()
  1826. def _to_schema(cls) -> str:
  1827. """Convert a state to a schema.
  1828. Returns:
  1829. The hash of the schema.
  1830. """
  1831. def _field_tuple(
  1832. field_name: str,
  1833. ) -> Tuple[str, str, Any, Union[bool, None], Any]:
  1834. model_field = cls.__fields__[field_name]
  1835. return (
  1836. field_name,
  1837. model_field.name,
  1838. _serialize_type(model_field.type_),
  1839. (
  1840. model_field.required
  1841. if isinstance(model_field.required, bool)
  1842. else None
  1843. ),
  1844. (model_field.default if is_serializable(model_field.default) else None),
  1845. )
  1846. return md5(
  1847. pickle.dumps(
  1848. sorted(_field_tuple(field_name) for field_name in cls.base_vars)
  1849. )
  1850. ).hexdigest()
  1851. def _serialize(self) -> bytes:
  1852. """Serialize the state for redis.
  1853. Returns:
  1854. The serialized state.
  1855. Raises:
  1856. StateSerializationError: If the state cannot be serialized.
  1857. """
  1858. payload = b""
  1859. error = ""
  1860. try:
  1861. payload = pickle.dumps((self._to_schema(), self))
  1862. except HANDLED_PICKLE_ERRORS as og_pickle_error:
  1863. error = (
  1864. f"Failed to serialize state {self.get_full_name()} due to unpicklable object. "
  1865. "This state will not be persisted. "
  1866. )
  1867. try:
  1868. import dill
  1869. payload = dill.dumps((self._to_schema(), self))
  1870. except ImportError:
  1871. error += (
  1872. f"Pickle error: {og_pickle_error}. "
  1873. "Consider `pip install 'dill>=0.3.8'` for more exotic serialization support."
  1874. )
  1875. except HANDLED_PICKLE_ERRORS as ex:
  1876. error += f"Dill was also unable to pickle the state: {ex}"
  1877. console.warn(error)
  1878. if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF:
  1879. self._check_state_size(len(payload))
  1880. if not payload:
  1881. raise StateSerializationError(error)
  1882. return payload
  1883. @classmethod
  1884. def _deserialize(
  1885. cls, data: bytes | None = None, fp: BinaryIO | None = None
  1886. ) -> BaseState:
  1887. """Deserialize the state from redis/disk.
  1888. data and fp are mutually exclusive, but one must be provided.
  1889. Args:
  1890. data: The serialized state data.
  1891. fp: The file pointer to the serialized state data.
  1892. Returns:
  1893. The deserialized state.
  1894. Raises:
  1895. ValueError: If both data and fp are provided, or neither are provided.
  1896. StateSchemaMismatchError: If the state schema does not match the expected schema.
  1897. """
  1898. if data is not None and fp is None:
  1899. (substate_schema, state) = pickle.loads(data)
  1900. elif fp is not None and data is None:
  1901. (substate_schema, state) = pickle.load(fp)
  1902. else:
  1903. raise ValueError("Only one of `data` or `fp` must be provided")
  1904. if substate_schema != state._to_schema():
  1905. raise StateSchemaMismatchError()
  1906. return state
  1907. class State(BaseState):
  1908. """The app Base State."""
  1909. # The hydrated bool.
  1910. is_hydrated: bool = False
  1911. T = TypeVar("T", bound=BaseState)
  1912. def dynamic(func: Callable[[T], Component]):
  1913. """Create a dynamically generated components from a state class.
  1914. Args:
  1915. func: The function to generate the component.
  1916. Returns:
  1917. The dynamically generated component.
  1918. Raises:
  1919. DynamicComponentInvalidSignature: If the function does not have exactly one parameter.
  1920. DynamicComponentInvalidSignature: If the function does not have a type hint for the state class.
  1921. """
  1922. number_of_parameters = len(inspect.signature(func).parameters)
  1923. func_signature = get_type_hints(func)
  1924. if "return" in func_signature:
  1925. func_signature.pop("return")
  1926. values = list(func_signature.values())
  1927. if number_of_parameters != 1:
  1928. raise DynamicComponentInvalidSignature(
  1929. "The function must have exactly one parameter, which is the state class."
  1930. )
  1931. if len(values) != 1:
  1932. raise DynamicComponentInvalidSignature(
  1933. "You must provide a type hint for the state class in the function."
  1934. )
  1935. state_class: Type[T] = values[0]
  1936. def wrapper() -> Component:
  1937. from reflex.components.base.fragment import fragment
  1938. return fragment(state_class._evaluate(lambda state: func(state)))
  1939. return wrapper
  1940. class FrontendEventExceptionState(State):
  1941. """Substate for handling frontend exceptions."""
  1942. @event
  1943. def handle_frontend_exception(self, stack: str, component_stack: str) -> None:
  1944. """Handle frontend exceptions.
  1945. If a frontend exception handler is provided, it will be called.
  1946. Otherwise, the default frontend exception handler will be called.
  1947. Args:
  1948. stack: The stack trace of the exception.
  1949. component_stack: The stack trace of the component where the exception occurred.
  1950. """
  1951. app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1952. app_instance.frontend_exception_handler(Exception(stack))
  1953. class UpdateVarsInternalState(State):
  1954. """Substate for handling internal state var updates."""
  1955. async def update_vars_internal(self, vars: dict[str, Any]) -> None:
  1956. """Apply updates to fully qualified state vars.
  1957. The keys in `vars` should be in the form of `{state.get_full_name()}.{var_name}`,
  1958. and each value will be set on the appropriate substate instance.
  1959. This function is primarily used to apply cookie and local storage
  1960. updates from the frontend to the appropriate substate.
  1961. Args:
  1962. vars: The fully qualified vars and values to update.
  1963. """
  1964. for var, value in vars.items():
  1965. state_name, _, var_name = var.rpartition(".")
  1966. var_state_cls = State.get_class_substate(state_name)
  1967. var_state = await self.get_state(var_state_cls)
  1968. setattr(var_state, var_name, value)
  1969. class OnLoadInternalState(State):
  1970. """Substate for handling on_load event enumeration.
  1971. This is a separate substate to avoid deserializing the entire state tree for every page navigation.
  1972. """
  1973. def on_load_internal(self) -> list[Event | EventSpec] | None:
  1974. """Queue on_load handlers for the current page.
  1975. Returns:
  1976. The list of events to queue for on load handling.
  1977. """
  1978. # Do not app._compile()! It should be already compiled by now.
  1979. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1980. load_events = app.get_load_events(self.router.page.path)
  1981. if not load_events:
  1982. self.is_hydrated = True
  1983. return # Fast path for navigation with no on_load events defined.
  1984. self.is_hydrated = False
  1985. return [
  1986. *fix_events(
  1987. load_events,
  1988. self.router.session.client_token,
  1989. router_data=self.router_data,
  1990. ),
  1991. State.set_is_hydrated(True), # type: ignore
  1992. ]
  1993. class ComponentState(State, mixin=True):
  1994. """Base class to allow for the creation of a state instance per component.
  1995. This allows for the bundling of UI and state logic into a single class,
  1996. where each instance has a separate instance of the state.
  1997. Subclass this class and define vars and event handlers in the traditional way.
  1998. Then define a `get_component` method that returns the UI for the component instance.
  1999. See the full [docs](https://reflex.dev/docs/substates/component-state/) for more.
  2000. Basic example:
  2001. ```python
  2002. # Subclass ComponentState and define vars and event handlers.
  2003. class Counter(rx.ComponentState):
  2004. # Define vars that change.
  2005. count: int = 0
  2006. # Define event handlers.
  2007. def increment(self):
  2008. self.count += 1
  2009. def decrement(self):
  2010. self.count -= 1
  2011. @classmethod
  2012. def get_component(cls, **props):
  2013. # Access the state vars and event handlers using `cls`.
  2014. return rx.hstack(
  2015. rx.button("Decrement", on_click=cls.decrement),
  2016. rx.text(cls.count),
  2017. rx.button("Increment", on_click=cls.increment),
  2018. **props,
  2019. )
  2020. counter = Counter.create()
  2021. ```
  2022. """
  2023. # The number of components created from this class.
  2024. _per_component_state_instance_count: ClassVar[int] = 0
  2025. def __init__(self, *args, **kwargs):
  2026. """Do not allow direct initialization of the ComponentState.
  2027. Args:
  2028. *args: The args to pass to the State init method.
  2029. **kwargs: The kwargs to pass to the State init method.
  2030. Raises:
  2031. ReflexRuntimeError: If the ComponentState is initialized directly.
  2032. """
  2033. if type(self)._mixin:
  2034. raise ReflexRuntimeError(
  2035. f"{ComponentState.__name__} {type(self).__name__} is not meant to be initialized directly. "
  2036. + "Use the `create` method to create a new instance and access the state via the `State` attribute."
  2037. )
  2038. super().__init__(*args, **kwargs)
  2039. @classmethod
  2040. def __init_subclass__(cls, mixin: bool = True, **kwargs):
  2041. """Overwrite mixin default to True.
  2042. Args:
  2043. mixin: Whether the subclass is a mixin and should not be initialized.
  2044. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  2045. """
  2046. super().__init_subclass__(mixin=mixin, **kwargs)
  2047. @classmethod
  2048. def get_component(cls, *children, **props) -> "Component":
  2049. """Get the component instance.
  2050. Args:
  2051. children: The children of the component.
  2052. props: The props of the component.
  2053. Raises:
  2054. NotImplementedError: if the subclass does not override this method.
  2055. """
  2056. raise NotImplementedError(
  2057. f"{cls.__name__} must implement get_component to return the component instance."
  2058. )
  2059. @classmethod
  2060. def create(cls, *children, **props) -> "Component":
  2061. """Create a new instance of the Component.
  2062. Args:
  2063. children: The children of the component.
  2064. props: The props of the component.
  2065. Returns:
  2066. A new instance of the Component with an independent copy of the State.
  2067. """
  2068. cls._per_component_state_instance_count += 1
  2069. state_cls_name = f"{cls.__name__}_n{cls._per_component_state_instance_count}"
  2070. component_state = type(
  2071. state_cls_name,
  2072. (cls, State),
  2073. {"__module__": reflex.istate.dynamic.__name__},
  2074. mixin=False,
  2075. )
  2076. # Save a reference to the dynamic state for pickle/unpickle.
  2077. setattr(reflex.istate.dynamic, state_cls_name, component_state)
  2078. component = component_state.get_component(*children, **props)
  2079. component.State = component_state
  2080. return component
  2081. class StateProxy(wrapt.ObjectProxy):
  2082. """Proxy of a state instance to control mutability of vars for a background task.
  2083. Since a background task runs against a state instance without holding the
  2084. state_manager lock for the token, the reference may become stale if the same
  2085. state is modified by another event handler.
  2086. The proxy object ensures that writes to the state are blocked unless
  2087. explicitly entering a context which refreshes the state from state_manager
  2088. and holds the lock for the token until exiting the context. After exiting
  2089. the context, a StateUpdate may be emitted to the frontend to notify the
  2090. client of the state change.
  2091. A background task will be passed the `StateProxy` as `self`, so mutability
  2092. can be safely performed inside an `async with self` block.
  2093. class State(rx.State):
  2094. counter: int = 0
  2095. @rx.event(background=True)
  2096. async def bg_increment(self):
  2097. await asyncio.sleep(1)
  2098. async with self:
  2099. self.counter += 1
  2100. """
  2101. def __init__(
  2102. self, state_instance, parent_state_proxy: Optional["StateProxy"] = None
  2103. ):
  2104. """Create a proxy for a state instance.
  2105. If `get_state` is used on a StateProxy, the resulting state will be
  2106. linked to the given state via parent_state_proxy. The first state in the
  2107. chain is the state that initiated the background task.
  2108. Args:
  2109. state_instance: The state instance to proxy.
  2110. parent_state_proxy: The parent state proxy, for linked mutability and context tracking.
  2111. """
  2112. super().__init__(state_instance)
  2113. # compile is not relevant to backend logic
  2114. self._self_app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  2115. self._self_substate_path = tuple(state_instance.get_full_name().split("."))
  2116. self._self_actx = None
  2117. self._self_mutable = False
  2118. self._self_actx_lock = asyncio.Lock()
  2119. self._self_actx_lock_holder = None
  2120. self._self_parent_state_proxy = parent_state_proxy
  2121. def _is_mutable(self) -> bool:
  2122. """Check if the state is mutable.
  2123. Returns:
  2124. Whether the state is mutable.
  2125. """
  2126. if self._self_parent_state_proxy is not None:
  2127. return self._self_parent_state_proxy._is_mutable() or self._self_mutable
  2128. return self._self_mutable
  2129. async def __aenter__(self) -> StateProxy:
  2130. """Enter the async context manager protocol.
  2131. Sets mutability to True and enters the `App.modify_state` async context,
  2132. which refreshes the state from state_manager and holds the lock for the
  2133. given state token until exiting the context.
  2134. Background tasks should avoid blocking calls while inside the context.
  2135. Returns:
  2136. This StateProxy instance in mutable mode.
  2137. Raises:
  2138. ImmutableStateError: If the state is already mutable.
  2139. """
  2140. if self._self_parent_state_proxy is not None:
  2141. parent_state = (
  2142. await self._self_parent_state_proxy.__aenter__()
  2143. ).__wrapped__
  2144. super().__setattr__(
  2145. "__wrapped__",
  2146. await parent_state.get_state(
  2147. State.get_class_substate(self._self_substate_path)
  2148. ),
  2149. )
  2150. return self
  2151. current_task = asyncio.current_task()
  2152. if (
  2153. self._self_actx_lock.locked()
  2154. and current_task == self._self_actx_lock_holder
  2155. ):
  2156. raise ImmutableStateError(
  2157. "The state is already mutable. Do not nest `async with self` blocks."
  2158. )
  2159. await self._self_actx_lock.acquire()
  2160. self._self_actx_lock_holder = current_task
  2161. self._self_actx = self._self_app.modify_state(
  2162. token=_substate_key(
  2163. self.__wrapped__.router.session.client_token,
  2164. self._self_substate_path,
  2165. )
  2166. )
  2167. mutable_state = await self._self_actx.__aenter__()
  2168. super().__setattr__(
  2169. "__wrapped__", mutable_state.get_substate(self._self_substate_path)
  2170. )
  2171. self._self_mutable = True
  2172. return self
  2173. async def __aexit__(self, *exc_info: Any) -> None:
  2174. """Exit the async context manager protocol.
  2175. Sets proxy mutability to False and persists any state changes.
  2176. Args:
  2177. exc_info: The exception info tuple.
  2178. """
  2179. if self._self_parent_state_proxy is not None:
  2180. await self._self_parent_state_proxy.__aexit__(*exc_info)
  2181. return
  2182. if self._self_actx is None:
  2183. return
  2184. self._self_mutable = False
  2185. try:
  2186. await self._self_actx.__aexit__(*exc_info)
  2187. finally:
  2188. self._self_actx_lock_holder = None
  2189. self._self_actx_lock.release()
  2190. self._self_actx = None
  2191. def __enter__(self):
  2192. """Enter the regular context manager protocol.
  2193. This is not supported for background tasks, and exists only to raise a more useful exception
  2194. when the StateProxy is used incorrectly.
  2195. Raises:
  2196. TypeError: always, because only async contextmanager protocol is supported.
  2197. """
  2198. raise TypeError("Background task must use `async with self` to modify state.")
  2199. def __exit__(self, *exc_info: Any) -> None:
  2200. """Exit the regular context manager protocol.
  2201. Args:
  2202. exc_info: The exception info tuple.
  2203. """
  2204. pass
  2205. def __getattr__(self, name: str) -> Any:
  2206. """Get the attribute from the underlying state instance.
  2207. Args:
  2208. name: The name of the attribute.
  2209. Returns:
  2210. The value of the attribute.
  2211. Raises:
  2212. ImmutableStateError: If the state is not in mutable mode.
  2213. """
  2214. if name in ["substates", "parent_state"] and not self._is_mutable():
  2215. raise ImmutableStateError(
  2216. "Background task StateProxy is immutable outside of a context "
  2217. "manager. Use `async with self` to modify state."
  2218. )
  2219. value = super().__getattr__(name)
  2220. if not name.startswith("_self_") and isinstance(value, MutableProxy):
  2221. # ensure mutations to these containers are blocked unless proxy is _mutable
  2222. return ImmutableMutableProxy(
  2223. wrapped=value.__wrapped__,
  2224. state=self, # type: ignore
  2225. field_name=value._self_field_name,
  2226. )
  2227. if isinstance(value, functools.partial) and value.args[0] is self.__wrapped__:
  2228. # Rebind event handler to the proxy instance
  2229. value = functools.partial(
  2230. value.func,
  2231. self,
  2232. *value.args[1:],
  2233. **value.keywords,
  2234. )
  2235. if isinstance(value, MethodType) and value.__self__ is self.__wrapped__:
  2236. # Rebind methods to the proxy instance
  2237. value = type(value)(value.__func__, self) # type: ignore
  2238. return value
  2239. def __setattr__(self, name: str, value: Any) -> None:
  2240. """Set the attribute on the underlying state instance.
  2241. If the attribute is internal, set it on the proxy instance instead.
  2242. Args:
  2243. name: The name of the attribute.
  2244. value: The value of the attribute.
  2245. Raises:
  2246. ImmutableStateError: If the state is not in mutable mode.
  2247. """
  2248. if (
  2249. name.startswith("_self_") # wrapper attribute
  2250. or self._is_mutable() # lock held
  2251. # non-persisted state attribute
  2252. or name in self.__wrapped__.get_skip_vars()
  2253. ):
  2254. super().__setattr__(name, value)
  2255. return
  2256. raise ImmutableStateError(
  2257. "Background task StateProxy is immutable outside of a context "
  2258. "manager. Use `async with self` to modify state."
  2259. )
  2260. def get_substate(self, path: Sequence[str]) -> BaseState:
  2261. """Only allow substate access with lock held.
  2262. Args:
  2263. path: The path to the substate.
  2264. Returns:
  2265. The substate.
  2266. Raises:
  2267. ImmutableStateError: If the state is not in mutable mode.
  2268. """
  2269. if not self._is_mutable():
  2270. raise ImmutableStateError(
  2271. "Background task StateProxy is immutable outside of a context "
  2272. "manager. Use `async with self` to modify state."
  2273. )
  2274. return self.__wrapped__.get_substate(path)
  2275. async def get_state(self, state_cls: Type[BaseState]) -> BaseState:
  2276. """Get an instance of the state associated with this token.
  2277. Args:
  2278. state_cls: The class of the state.
  2279. Returns:
  2280. The state.
  2281. Raises:
  2282. ImmutableStateError: If the state is not in mutable mode.
  2283. """
  2284. if not self._is_mutable():
  2285. raise ImmutableStateError(
  2286. "Background task StateProxy is immutable outside of a context "
  2287. "manager. Use `async with self` to modify state."
  2288. )
  2289. return type(self)(
  2290. await self.__wrapped__.get_state(state_cls), parent_state_proxy=self
  2291. )
  2292. def _as_state_update(self, *args, **kwargs) -> StateUpdate:
  2293. """Temporarily allow mutability to access parent_state.
  2294. Args:
  2295. *args: The args to pass to the underlying state instance.
  2296. **kwargs: The kwargs to pass to the underlying state instance.
  2297. Returns:
  2298. The state update.
  2299. """
  2300. original_mutable = self._self_mutable
  2301. self._self_mutable = True
  2302. try:
  2303. return self.__wrapped__._as_state_update(*args, **kwargs)
  2304. finally:
  2305. self._self_mutable = original_mutable
  2306. @dataclasses.dataclass(
  2307. frozen=True,
  2308. )
  2309. class StateUpdate:
  2310. """A state update sent to the frontend."""
  2311. # The state delta.
  2312. delta: Delta = dataclasses.field(default_factory=dict)
  2313. # Events to be added to the event queue.
  2314. events: List[Event] = dataclasses.field(default_factory=list)
  2315. # Whether this is the final state update for the event.
  2316. final: bool = True
  2317. def json(self) -> str:
  2318. """Convert the state update to a JSON string.
  2319. Returns:
  2320. The state update as a JSON string.
  2321. """
  2322. return format.json_dumps(self)
  2323. class StateManager(Base, ABC):
  2324. """A class to manage many client states."""
  2325. # The state class to use.
  2326. state: Type[BaseState]
  2327. @classmethod
  2328. def create(cls, state: Type[BaseState]):
  2329. """Create a new state manager.
  2330. Args:
  2331. state: The state class to use.
  2332. Raises:
  2333. InvalidStateManagerMode: If the state manager mode is invalid.
  2334. Returns:
  2335. The state manager (either disk, memory or redis).
  2336. """
  2337. config = get_config()
  2338. if prerequisites.parse_redis_url() is not None:
  2339. config.state_manager_mode = constants.StateManagerMode.REDIS
  2340. if config.state_manager_mode == constants.StateManagerMode.MEMORY:
  2341. return StateManagerMemory(state=state)
  2342. if config.state_manager_mode == constants.StateManagerMode.DISK:
  2343. return StateManagerDisk(state=state)
  2344. if config.state_manager_mode == constants.StateManagerMode.REDIS:
  2345. redis = prerequisites.get_redis()
  2346. if redis is not None:
  2347. # make sure expiration values are obtained only from the config object on creation
  2348. return StateManagerRedis(
  2349. state=state,
  2350. redis=redis,
  2351. token_expiration=config.redis_token_expiration,
  2352. lock_expiration=config.redis_lock_expiration,
  2353. lock_warning_threshold=config.redis_lock_warning_threshold,
  2354. )
  2355. raise InvalidStateManagerMode(
  2356. f"Expected one of: DISK, MEMORY, REDIS, got {config.state_manager_mode}"
  2357. )
  2358. @abstractmethod
  2359. async def get_state(self, token: str) -> BaseState:
  2360. """Get the state for a token.
  2361. Args:
  2362. token: The token to get the state for.
  2363. Returns:
  2364. The state for the token.
  2365. """
  2366. pass
  2367. @abstractmethod
  2368. async def set_state(self, token: str, state: BaseState):
  2369. """Set the state for a token.
  2370. Args:
  2371. token: The token to set the state for.
  2372. state: The state to set.
  2373. """
  2374. pass
  2375. @abstractmethod
  2376. @contextlib.asynccontextmanager
  2377. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  2378. """Modify the state for a token while holding exclusive lock.
  2379. Args:
  2380. token: The token to modify the state for.
  2381. Yields:
  2382. The state for the token.
  2383. """
  2384. yield self.state()
  2385. class StateManagerMemory(StateManager):
  2386. """A state manager that stores states in memory."""
  2387. # The mapping of client ids to states.
  2388. states: Dict[str, BaseState] = {}
  2389. # The mutex ensures the dict of mutexes is updated exclusively
  2390. _state_manager_lock = asyncio.Lock()
  2391. # The dict of mutexes for each client
  2392. _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({})
  2393. class Config:
  2394. """The Pydantic config."""
  2395. fields = {
  2396. "_states_locks": {"exclude": True},
  2397. }
  2398. @override
  2399. async def get_state(self, token: str) -> BaseState:
  2400. """Get the state for a token.
  2401. Args:
  2402. token: The token to get the state for.
  2403. Returns:
  2404. The state for the token.
  2405. """
  2406. # Memory state manager ignores the substate suffix and always returns the top-level state.
  2407. token = _split_substate_key(token)[0]
  2408. if token not in self.states:
  2409. self.states[token] = self.state(_reflex_internal_init=True)
  2410. return self.states[token]
  2411. @override
  2412. async def set_state(self, token: str, state: BaseState):
  2413. """Set the state for a token.
  2414. Args:
  2415. token: The token to set the state for.
  2416. state: The state to set.
  2417. """
  2418. pass
  2419. @override
  2420. @contextlib.asynccontextmanager
  2421. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  2422. """Modify the state for a token while holding exclusive lock.
  2423. Args:
  2424. token: The token to modify the state for.
  2425. Yields:
  2426. The state for the token.
  2427. """
  2428. # Memory state manager ignores the substate suffix and always returns the top-level state.
  2429. token = _split_substate_key(token)[0]
  2430. if token not in self._states_locks:
  2431. async with self._state_manager_lock:
  2432. if token not in self._states_locks:
  2433. self._states_locks[token] = asyncio.Lock()
  2434. async with self._states_locks[token]:
  2435. state = await self.get_state(token)
  2436. yield state
  2437. await self.set_state(token, state)
  2438. def _default_token_expiration() -> int:
  2439. """Get the default token expiration time.
  2440. Returns:
  2441. The default token expiration time.
  2442. """
  2443. return get_config().redis_token_expiration
  2444. def _serialize_type(type_: Any) -> str:
  2445. """Serialize a type.
  2446. Args:
  2447. type_: The type to serialize.
  2448. Returns:
  2449. The serialized type.
  2450. """
  2451. if not inspect.isclass(type_):
  2452. return f"{type_}"
  2453. return f"{type_.__module__}.{type_.__qualname__}"
  2454. def is_serializable(value: Any) -> bool:
  2455. """Check if a value is serializable.
  2456. Args:
  2457. value: The value to check.
  2458. Returns:
  2459. Whether the value is serializable.
  2460. """
  2461. try:
  2462. return bool(pickle.dumps(value))
  2463. except Exception:
  2464. return False
  2465. def reset_disk_state_manager():
  2466. """Reset the disk state manager."""
  2467. states_directory = prerequisites.get_web_dir() / constants.Dirs.STATES
  2468. if states_directory.exists():
  2469. for path in states_directory.iterdir():
  2470. path.unlink()
  2471. class StateManagerDisk(StateManager):
  2472. """A state manager that stores states in memory."""
  2473. # The mapping of client ids to states.
  2474. states: Dict[str, BaseState] = {}
  2475. # The mutex ensures the dict of mutexes is updated exclusively
  2476. _state_manager_lock = asyncio.Lock()
  2477. # The dict of mutexes for each client
  2478. _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({})
  2479. # The token expiration time (s).
  2480. token_expiration: int = pydantic.Field(default_factory=_default_token_expiration)
  2481. class Config:
  2482. """The Pydantic config."""
  2483. fields = {
  2484. "_states_locks": {"exclude": True},
  2485. }
  2486. keep_untouched = (functools.cached_property,)
  2487. def __init__(self, state: Type[BaseState]):
  2488. """Create a new state manager.
  2489. Args:
  2490. state: The state class to use.
  2491. """
  2492. super().__init__(state=state)
  2493. path_ops.mkdir(self.states_directory)
  2494. self._purge_expired_states()
  2495. @functools.cached_property
  2496. def states_directory(self) -> Path:
  2497. """Get the states directory.
  2498. Returns:
  2499. The states directory.
  2500. """
  2501. return prerequisites.get_web_dir() / constants.Dirs.STATES
  2502. def _purge_expired_states(self):
  2503. """Purge expired states from the disk."""
  2504. import time
  2505. for path in path_ops.ls(self.states_directory):
  2506. # check path is a pickle file
  2507. if path.suffix != ".pkl":
  2508. continue
  2509. # load last edited field from file
  2510. last_edited = path.stat().st_mtime
  2511. # check if the file is older than the token expiration time
  2512. if time.time() - last_edited > self.token_expiration:
  2513. # remove the file
  2514. path.unlink()
  2515. def token_path(self, token: str) -> Path:
  2516. """Get the path for a token.
  2517. Args:
  2518. token: The token to get the path for.
  2519. Returns:
  2520. The path for the token.
  2521. """
  2522. return (
  2523. self.states_directory / f"{md5(token.encode()).hexdigest()}.pkl"
  2524. ).absolute()
  2525. async def load_state(self, token: str) -> BaseState | None:
  2526. """Load a state object based on the provided token.
  2527. Args:
  2528. token: The token used to identify the state object.
  2529. Returns:
  2530. The loaded state object or None.
  2531. """
  2532. token_path = self.token_path(token)
  2533. if token_path.exists():
  2534. try:
  2535. with token_path.open(mode="rb") as file:
  2536. return BaseState._deserialize(fp=file)
  2537. except Exception:
  2538. pass
  2539. async def populate_substates(
  2540. self, client_token: str, state: BaseState, root_state: BaseState
  2541. ):
  2542. """Populate the substates of a state object.
  2543. Args:
  2544. client_token: The client token.
  2545. state: The state object to populate.
  2546. root_state: The root state object.
  2547. """
  2548. for substate in state.get_substates():
  2549. substate_token = _substate_key(client_token, substate)
  2550. fresh_instance = await root_state.get_state(substate)
  2551. instance = await self.load_state(substate_token)
  2552. if instance is not None:
  2553. # Ensure all substates exist, even if they weren't serialized previously.
  2554. instance.substates = fresh_instance.substates
  2555. else:
  2556. instance = fresh_instance
  2557. state.substates[substate.get_name()] = instance
  2558. instance.parent_state = state
  2559. await self.populate_substates(client_token, instance, root_state)
  2560. @override
  2561. async def get_state(
  2562. self,
  2563. token: str,
  2564. ) -> BaseState:
  2565. """Get the state for a token.
  2566. Args:
  2567. token: The token to get the state for.
  2568. Returns:
  2569. The state for the token.
  2570. """
  2571. client_token = _split_substate_key(token)[0]
  2572. root_state = self.states.get(client_token)
  2573. if root_state is not None:
  2574. # Retrieved state from memory.
  2575. return root_state
  2576. # Deserialize root state from disk.
  2577. root_state = await self.load_state(_substate_key(client_token, self.state))
  2578. # Create a new root state tree with all substates instantiated.
  2579. fresh_root_state = self.state(_reflex_internal_init=True)
  2580. if root_state is None:
  2581. root_state = fresh_root_state
  2582. else:
  2583. # Ensure all substates exist, even if they were not serialized previously.
  2584. root_state.substates = fresh_root_state.substates
  2585. self.states[client_token] = root_state
  2586. await self.populate_substates(client_token, root_state, root_state)
  2587. return root_state
  2588. async def set_state_for_substate(self, client_token: str, substate: BaseState):
  2589. """Set the state for a substate.
  2590. Args:
  2591. client_token: The client token.
  2592. substate: The substate to set.
  2593. """
  2594. substate_token = _substate_key(client_token, substate)
  2595. if substate._get_was_touched():
  2596. substate._was_touched = False # Reset the touched flag after serializing.
  2597. pickle_state = substate._serialize()
  2598. if pickle_state:
  2599. if not self.states_directory.exists():
  2600. self.states_directory.mkdir(parents=True, exist_ok=True)
  2601. self.token_path(substate_token).write_bytes(pickle_state)
  2602. for substate_substate in substate.substates.values():
  2603. await self.set_state_for_substate(client_token, substate_substate)
  2604. @override
  2605. async def set_state(self, token: str, state: BaseState):
  2606. """Set the state for a token.
  2607. Args:
  2608. token: The token to set the state for.
  2609. state: The state to set.
  2610. """
  2611. client_token, substate = _split_substate_key(token)
  2612. await self.set_state_for_substate(client_token, state)
  2613. @override
  2614. @contextlib.asynccontextmanager
  2615. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  2616. """Modify the state for a token while holding exclusive lock.
  2617. Args:
  2618. token: The token to modify the state for.
  2619. Yields:
  2620. The state for the token.
  2621. """
  2622. # Memory state manager ignores the substate suffix and always returns the top-level state.
  2623. client_token, substate = _split_substate_key(token)
  2624. if client_token not in self._states_locks:
  2625. async with self._state_manager_lock:
  2626. if client_token not in self._states_locks:
  2627. self._states_locks[client_token] = asyncio.Lock()
  2628. async with self._states_locks[client_token]:
  2629. state = await self.get_state(token)
  2630. yield state
  2631. await self.set_state(token, state)
  2632. def _default_lock_expiration() -> int:
  2633. """Get the default lock expiration time.
  2634. Returns:
  2635. The default lock expiration time.
  2636. """
  2637. return get_config().redis_lock_expiration
  2638. def _default_lock_warning_threshold() -> int:
  2639. """Get the default lock warning threshold.
  2640. Returns:
  2641. The default lock warning threshold.
  2642. """
  2643. return get_config().redis_lock_warning_threshold
  2644. class StateManagerRedis(StateManager):
  2645. """A state manager that stores states in redis."""
  2646. # The redis client to use.
  2647. redis: Redis
  2648. # The token expiration time (s).
  2649. token_expiration: int = pydantic.Field(default_factory=_default_token_expiration)
  2650. # The maximum time to hold a lock (ms).
  2651. lock_expiration: int = pydantic.Field(default_factory=_default_lock_expiration)
  2652. # The maximum time to hold a lock (ms) before warning.
  2653. lock_warning_threshold: int = pydantic.Field(
  2654. default_factory=_default_lock_warning_threshold
  2655. )
  2656. # The keyspace subscription string when redis is waiting for lock to be released
  2657. _redis_notify_keyspace_events: str = (
  2658. "K" # Enable keyspace notifications (target a particular key)
  2659. "g" # For generic commands (DEL, EXPIRE, etc)
  2660. "x" # For expired events
  2661. "e" # For evicted events (i.e. maxmemory exceeded)
  2662. )
  2663. # These events indicate that a lock is no longer held
  2664. _redis_keyspace_lock_release_events: Set[bytes] = {
  2665. b"del",
  2666. b"expire",
  2667. b"expired",
  2668. b"evicted",
  2669. }
  2670. async def _get_parent_state(
  2671. self, token: str, state: BaseState | None = None
  2672. ) -> BaseState | None:
  2673. """Get the parent state for the state requested in the token.
  2674. Args:
  2675. token: The token to get the state for (_substate_key).
  2676. state: The state instance to get parent state for.
  2677. Returns:
  2678. The parent state for the state requested by the token or None if there is no such parent.
  2679. """
  2680. parent_state = None
  2681. client_token, state_path = _split_substate_key(token)
  2682. parent_state_name = state_path.rpartition(".")[0]
  2683. if parent_state_name:
  2684. cached_substates = None
  2685. if state is not None:
  2686. cached_substates = [state]
  2687. # Retrieve the parent state to populate event handlers onto this substate.
  2688. parent_state = await self.get_state(
  2689. token=_substate_key(client_token, parent_state_name),
  2690. top_level=False,
  2691. get_substates=False,
  2692. cached_substates=cached_substates,
  2693. )
  2694. return parent_state
  2695. async def _populate_substates(
  2696. self,
  2697. token: str,
  2698. state: BaseState,
  2699. all_substates: bool = False,
  2700. ):
  2701. """Fetch and link substates for the given state instance.
  2702. There is no return value; the side-effect is that `state` will have `substates` populated,
  2703. and each substate will have its `parent_state` set to `state`.
  2704. Args:
  2705. token: The token to get the state for.
  2706. state: The state instance to populate substates for.
  2707. all_substates: Whether to fetch all substates or just required substates.
  2708. """
  2709. client_token, _ = _split_substate_key(token)
  2710. if all_substates:
  2711. # All substates are requested.
  2712. fetch_substates = state.get_substates()
  2713. else:
  2714. # Only _potentially_dirty_substates need to be fetched to recalc computed vars.
  2715. fetch_substates = state._potentially_dirty_substates()
  2716. tasks = {}
  2717. # Retrieve the necessary substates from redis.
  2718. for substate_cls in fetch_substates:
  2719. if substate_cls.get_name() in state.substates:
  2720. continue
  2721. substate_name = substate_cls.get_name()
  2722. tasks[substate_name] = asyncio.create_task(
  2723. self.get_state(
  2724. token=_substate_key(client_token, substate_cls),
  2725. top_level=False,
  2726. get_substates=all_substates,
  2727. parent_state=state,
  2728. )
  2729. )
  2730. for substate_name, substate_task in tasks.items():
  2731. state.substates[substate_name] = await substate_task
  2732. @override
  2733. async def get_state(
  2734. self,
  2735. token: str,
  2736. top_level: bool = True,
  2737. get_substates: bool = True,
  2738. parent_state: BaseState | None = None,
  2739. cached_substates: list[BaseState] | None = None,
  2740. ) -> BaseState:
  2741. """Get the state for a token.
  2742. Args:
  2743. token: The token to get the state for.
  2744. top_level: If true, return an instance of the top-level state (self.state).
  2745. get_substates: If true, also retrieve substates.
  2746. parent_state: If provided, use this parent_state instead of getting it from redis.
  2747. cached_substates: If provided, attach these substates to the state.
  2748. Returns:
  2749. The state for the token.
  2750. Raises:
  2751. RuntimeError: when the state_cls is not specified in the token
  2752. """
  2753. # Split the actual token from the fully qualified substate name.
  2754. _, state_path = _split_substate_key(token)
  2755. if state_path:
  2756. # Get the State class associated with the given path.
  2757. state_cls = self.state.get_class_substate(state_path)
  2758. else:
  2759. raise RuntimeError(
  2760. f"StateManagerRedis requires token to be specified in the form of {{token}}_{{state_full_name}}, but got {token}"
  2761. )
  2762. # The deserialized or newly created (sub)state instance.
  2763. state = None
  2764. # Fetch the serialized substate from redis.
  2765. redis_state = await self.redis.get(token)
  2766. if redis_state is not None:
  2767. # Deserialize the substate.
  2768. with contextlib.suppress(StateSchemaMismatchError):
  2769. state = BaseState._deserialize(data=redis_state)
  2770. if state is None:
  2771. # Key didn't exist or schema mismatch so create a new instance for this token.
  2772. state = state_cls(
  2773. init_substates=False,
  2774. _reflex_internal_init=True,
  2775. )
  2776. # Populate parent state if missing and requested.
  2777. if parent_state is None:
  2778. parent_state = await self._get_parent_state(token, state)
  2779. # Set up Bidirectional linkage between this state and its parent.
  2780. if parent_state is not None:
  2781. parent_state.substates[state.get_name()] = state
  2782. state.parent_state = parent_state
  2783. # Avoid fetching substates multiple times.
  2784. if cached_substates:
  2785. for substate in cached_substates:
  2786. state.substates[substate.get_name()] = substate
  2787. if substate.parent_state is None:
  2788. substate.parent_state = state
  2789. # Populate substates if requested.
  2790. await self._populate_substates(token, state, all_substates=get_substates)
  2791. # To retain compatibility with previous implementation, by default, we return
  2792. # the top-level state by chasing `parent_state` pointers up the tree.
  2793. if top_level:
  2794. return state._get_root_state()
  2795. return state
  2796. @override
  2797. async def set_state(
  2798. self,
  2799. token: str,
  2800. state: BaseState,
  2801. lock_id: bytes | None = None,
  2802. ):
  2803. """Set the state for a token.
  2804. Args:
  2805. token: The token to set the state for.
  2806. state: The state to set.
  2807. lock_id: If provided, the lock_key must be set to this value to set the state.
  2808. Raises:
  2809. LockExpiredError: If lock_id is provided and the lock for the token is not held by that ID.
  2810. RuntimeError: If the state instance doesn't match the state name in the token.
  2811. """
  2812. # Check that we're holding the lock.
  2813. if (
  2814. lock_id is not None
  2815. and await self.redis.get(self._lock_key(token)) != lock_id
  2816. ):
  2817. raise LockExpiredError(
  2818. f"Lock expired for token {token} while processing. Consider increasing "
  2819. f"`app.state_manager.lock_expiration` (currently {self.lock_expiration}) "
  2820. "or use `@rx.event(background=True)` decorator for long-running tasks."
  2821. )
  2822. elif lock_id is not None:
  2823. time_taken = self.lock_expiration / 1000 - (
  2824. await self.redis.ttl(self._lock_key(token))
  2825. )
  2826. if time_taken > self.lock_warning_threshold / 1000:
  2827. console.warn(
  2828. f"Lock for token {token} was held too long {time_taken=}s, "
  2829. f"use `@rx.event(background=True)` decorator for long-running tasks.",
  2830. dedupe=True,
  2831. )
  2832. client_token, substate_name = _split_substate_key(token)
  2833. # If the substate name on the token doesn't match the instance name, it cannot have a parent.
  2834. if state.parent_state is not None and state.get_full_name() != substate_name:
  2835. raise RuntimeError(
  2836. f"Cannot `set_state` with mismatching token {token} and substate {state.get_full_name()}."
  2837. )
  2838. # Recursively set_state on all known substates.
  2839. tasks = [
  2840. asyncio.create_task(
  2841. self.set_state(
  2842. _substate_key(client_token, substate),
  2843. substate,
  2844. lock_id,
  2845. )
  2846. )
  2847. for substate in state.substates.values()
  2848. ]
  2849. # Persist only the given state (parents or substates are excluded by BaseState.__getstate__).
  2850. if state._get_was_touched():
  2851. pickle_state = state._serialize()
  2852. if pickle_state:
  2853. await self.redis.set(
  2854. _substate_key(client_token, state),
  2855. pickle_state,
  2856. ex=self.token_expiration,
  2857. )
  2858. # Wait for substates to be persisted.
  2859. for t in tasks:
  2860. await t
  2861. @override
  2862. @contextlib.asynccontextmanager
  2863. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  2864. """Modify the state for a token while holding exclusive lock.
  2865. Args:
  2866. token: The token to modify the state for.
  2867. Yields:
  2868. The state for the token.
  2869. """
  2870. async with self._lock(token) as lock_id:
  2871. state = await self.get_state(token)
  2872. yield state
  2873. await self.set_state(token, state, lock_id)
  2874. @validator("lock_warning_threshold")
  2875. @classmethod
  2876. def validate_lock_warning_threshold(cls, lock_warning_threshold: int, values):
  2877. """Validate the lock warning threshold.
  2878. Args:
  2879. lock_warning_threshold: The lock warning threshold.
  2880. values: The validated attributes.
  2881. Returns:
  2882. The lock warning threshold.
  2883. Raises:
  2884. InvalidLockWarningThresholdError: If the lock warning threshold is invalid.
  2885. """
  2886. if lock_warning_threshold >= (lock_expiration := values["lock_expiration"]):
  2887. raise InvalidLockWarningThresholdError(
  2888. f"The lock warning threshold({lock_warning_threshold}) must be less than the lock expiration time({lock_expiration})."
  2889. )
  2890. return lock_warning_threshold
  2891. @staticmethod
  2892. def _lock_key(token: str) -> bytes:
  2893. """Get the redis key for a token's lock.
  2894. Args:
  2895. token: The token to get the lock key for.
  2896. Returns:
  2897. The redis lock key for the token.
  2898. """
  2899. # All substates share the same lock domain, so ignore any substate path suffix.
  2900. client_token = _split_substate_key(token)[0]
  2901. return f"{client_token}_lock".encode()
  2902. async def _try_get_lock(self, lock_key: bytes, lock_id: bytes) -> bool | None:
  2903. """Try to get a redis lock for a token.
  2904. Args:
  2905. lock_key: The redis key for the lock.
  2906. lock_id: The ID of the lock.
  2907. Returns:
  2908. True if the lock was obtained.
  2909. """
  2910. return await self.redis.set(
  2911. lock_key,
  2912. lock_id,
  2913. px=self.lock_expiration,
  2914. nx=True, # only set if it doesn't exist
  2915. )
  2916. async def _get_pubsub_message(
  2917. self, pubsub: PubSub, timeout: float | None = None
  2918. ) -> None:
  2919. """Get lock release events from the pubsub.
  2920. Args:
  2921. pubsub: The pubsub to get a message from.
  2922. timeout: Remaining time to wait for a message.
  2923. Returns:
  2924. The message.
  2925. """
  2926. if timeout is None:
  2927. timeout = self.lock_expiration / 1000.0
  2928. started = time.time()
  2929. message = await pubsub.get_message(
  2930. ignore_subscribe_messages=True,
  2931. timeout=timeout,
  2932. )
  2933. if (
  2934. message is None
  2935. or message["data"] not in self._redis_keyspace_lock_release_events
  2936. ):
  2937. remaining = timeout - (time.time() - started)
  2938. if remaining <= 0:
  2939. return
  2940. await self._get_pubsub_message(pubsub, timeout=remaining)
  2941. async def _wait_lock(self, lock_key: bytes, lock_id: bytes) -> None:
  2942. """Wait for a redis lock to be released via pubsub.
  2943. Coroutine will not return until the lock is obtained.
  2944. Args:
  2945. lock_key: The redis key for the lock.
  2946. lock_id: The ID of the lock.
  2947. Raises:
  2948. ResponseError: when the keyspace config cannot be set.
  2949. """
  2950. lock_key_channel = f"__keyspace@0__:{lock_key.decode()}"
  2951. # Enable keyspace notifications for the lock key, so we know when it is available.
  2952. try:
  2953. await self.redis.config_set(
  2954. "notify-keyspace-events",
  2955. self._redis_notify_keyspace_events,
  2956. )
  2957. except ResponseError:
  2958. # Some redis servers only allow out-of-band configuration, so ignore errors here.
  2959. if not environment.REFLEX_IGNORE_REDIS_CONFIG_ERROR.get():
  2960. raise
  2961. async with self.redis.pubsub() as pubsub:
  2962. await pubsub.psubscribe(lock_key_channel)
  2963. # wait for the lock to be released
  2964. while True:
  2965. # fast path
  2966. if await self._try_get_lock(lock_key, lock_id):
  2967. return
  2968. # wait for lock events
  2969. await self._get_pubsub_message(pubsub)
  2970. @contextlib.asynccontextmanager
  2971. async def _lock(self, token: str):
  2972. """Obtain a redis lock for a token.
  2973. Args:
  2974. token: The token to obtain a lock for.
  2975. Yields:
  2976. The ID of the lock (to be passed to set_state).
  2977. Raises:
  2978. LockExpiredError: If the lock has expired while processing the event.
  2979. """
  2980. lock_key = self._lock_key(token)
  2981. lock_id = uuid.uuid4().hex.encode()
  2982. if not await self._try_get_lock(lock_key, lock_id):
  2983. # Missed the fast-path to get lock, subscribe for lock delete/expire events
  2984. await self._wait_lock(lock_key, lock_id)
  2985. state_is_locked = True
  2986. try:
  2987. yield lock_id
  2988. except LockExpiredError:
  2989. state_is_locked = False
  2990. raise
  2991. finally:
  2992. if state_is_locked:
  2993. # only delete our lock
  2994. await self.redis.delete(lock_key)
  2995. async def close(self):
  2996. """Explicitly close the redis connection and connection_pool.
  2997. It is necessary in testing scenarios to close between asyncio test cases
  2998. to avoid having lingering redis connections associated with event loops
  2999. that will be closed (each test case uses its own event loop).
  3000. Note: Connections will be automatically reopened when needed.
  3001. """
  3002. await self.redis.aclose(close_connection_pool=True)
  3003. def get_state_manager() -> StateManager:
  3004. """Get the state manager for the app that is currently running.
  3005. Returns:
  3006. The state manager.
  3007. """
  3008. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  3009. return app.state_manager
  3010. class MutableProxy(wrapt.ObjectProxy):
  3011. """A proxy for a mutable object that tracks changes."""
  3012. # Hint for finding the base class of the proxy.
  3013. __base_proxy__ = "MutableProxy"
  3014. # Methods on wrapped objects which should mark the state as dirty.
  3015. __mark_dirty_attrs__ = {
  3016. "add",
  3017. "append",
  3018. "clear",
  3019. "difference_update",
  3020. "discard",
  3021. "extend",
  3022. "insert",
  3023. "intersection_update",
  3024. "pop",
  3025. "popitem",
  3026. "remove",
  3027. "reverse",
  3028. "setdefault",
  3029. "sort",
  3030. "symmetric_difference_update",
  3031. "update",
  3032. }
  3033. # Methods on wrapped objects might return mutable objects that should be tracked.
  3034. __wrap_mutable_attrs__ = {
  3035. "get",
  3036. "setdefault",
  3037. }
  3038. # These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
  3039. __never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
  3040. pydantic.BaseModel.__dict__
  3041. )
  3042. # These types will be wrapped in MutableProxy
  3043. __mutable_types__ = (
  3044. list,
  3045. dict,
  3046. set,
  3047. Base,
  3048. DeclarativeBase,
  3049. BaseModelV2,
  3050. BaseModelV1,
  3051. )
  3052. # Dynamically generated classes for tracking dataclass mutations.
  3053. __dataclass_proxies__: Dict[type, type] = {}
  3054. def __new__(cls, wrapped: Any, *args, **kwargs) -> MutableProxy:
  3055. """Create a proxy instance for a mutable object that tracks changes.
  3056. Args:
  3057. wrapped: The object to proxy.
  3058. *args: Other args passed to MutableProxy (ignored).
  3059. **kwargs: Other kwargs passed to MutableProxy (ignored).
  3060. Returns:
  3061. The proxy instance.
  3062. """
  3063. if dataclasses.is_dataclass(wrapped):
  3064. wrapped_cls = type(wrapped)
  3065. wrapper_cls_name = wrapped_cls.__name__ + cls.__name__
  3066. # Find the associated class
  3067. if wrapper_cls_name not in cls.__dataclass_proxies__:
  3068. # Create a new class that has the __dataclass_fields__ defined
  3069. cls.__dataclass_proxies__[wrapper_cls_name] = type(
  3070. wrapper_cls_name,
  3071. (cls,),
  3072. {
  3073. dataclasses._FIELDS: getattr( # pyright: ignore [reportGeneralTypeIssues]
  3074. wrapped_cls,
  3075. dataclasses._FIELDS, # pyright: ignore [reportGeneralTypeIssues]
  3076. ),
  3077. },
  3078. )
  3079. cls = cls.__dataclass_proxies__[wrapper_cls_name]
  3080. return super().__new__(cls)
  3081. def __init__(self, wrapped: Any, state: BaseState, field_name: str):
  3082. """Create a proxy for a mutable object that tracks changes.
  3083. Args:
  3084. wrapped: The object to proxy.
  3085. state: The state to mark dirty when the object is changed.
  3086. field_name: The name of the field on the state associated with the
  3087. wrapped object.
  3088. """
  3089. super().__init__(wrapped)
  3090. self._self_state = state
  3091. self._self_field_name = field_name
  3092. def __repr__(self) -> str:
  3093. """Get the representation of the wrapped object.
  3094. Returns:
  3095. The representation of the wrapped object.
  3096. """
  3097. return f"{type(self).__name__}({self.__wrapped__})"
  3098. def _mark_dirty(
  3099. self,
  3100. wrapped=None,
  3101. instance=None,
  3102. args=(),
  3103. kwargs=None,
  3104. ) -> Any:
  3105. """Mark the state as dirty, then call a wrapped function.
  3106. Intended for use with `FunctionWrapper` from the `wrapt` library.
  3107. Args:
  3108. wrapped: The wrapped function.
  3109. instance: The instance of the wrapped function.
  3110. args: The args for the wrapped function.
  3111. kwargs: The kwargs for the wrapped function.
  3112. Returns:
  3113. The result of the wrapped function.
  3114. """
  3115. self._self_state.dirty_vars.add(self._self_field_name)
  3116. self._self_state._mark_dirty()
  3117. if wrapped is not None:
  3118. return wrapped(*args, **(kwargs or {}))
  3119. @classmethod
  3120. def _is_mutable_type(cls, value: Any) -> bool:
  3121. """Check if a value is of a mutable type and should be wrapped.
  3122. Args:
  3123. value: The value to check.
  3124. Returns:
  3125. Whether the value is of a mutable type.
  3126. """
  3127. return isinstance(value, cls.__mutable_types__) or (
  3128. dataclasses.is_dataclass(value) and not isinstance(value, Var)
  3129. )
  3130. @staticmethod
  3131. def _is_called_from_dataclasses_internal() -> bool:
  3132. """Check if the current function is called from dataclasses helper.
  3133. Returns:
  3134. Whether the current function is called from dataclasses internal code.
  3135. """
  3136. # Walk up the stack a bit to see if we are called from dataclasses
  3137. # internal code, for example `asdict` or `astuple`.
  3138. frame = inspect.currentframe()
  3139. for _ in range(5):
  3140. # Why not `inspect.stack()` -- this is much faster!
  3141. if not (frame := frame and frame.f_back):
  3142. break
  3143. if inspect.getfile(frame) == dataclasses.__file__:
  3144. return True
  3145. return False
  3146. def _wrap_recursive(self, value: Any) -> Any:
  3147. """Wrap a value recursively if it is mutable.
  3148. Args:
  3149. value: The value to wrap.
  3150. Returns:
  3151. The wrapped value.
  3152. """
  3153. # When called from dataclasses internal code, return the unwrapped value
  3154. if self._is_called_from_dataclasses_internal():
  3155. return value
  3156. # Recursively wrap mutable types, but do not re-wrap MutableProxy instances.
  3157. if self._is_mutable_type(value) and not isinstance(value, MutableProxy):
  3158. base_cls = globals()[self.__base_proxy__]
  3159. return base_cls(
  3160. wrapped=value,
  3161. state=self._self_state,
  3162. field_name=self._self_field_name,
  3163. )
  3164. return value
  3165. def _wrap_recursive_decorator(self, wrapped, instance, args, kwargs) -> Any:
  3166. """Wrap a function that returns a possibly mutable value.
  3167. Intended for use with `FunctionWrapper` from the `wrapt` library.
  3168. Args:
  3169. wrapped: The wrapped function.
  3170. instance: The instance of the wrapped function.
  3171. args: The args for the wrapped function.
  3172. kwargs: The kwargs for the wrapped function.
  3173. Returns:
  3174. The result of the wrapped function (possibly wrapped in a MutableProxy).
  3175. """
  3176. return self._wrap_recursive(wrapped(*args, **kwargs))
  3177. def __getattr__(self, __name: str) -> Any:
  3178. """Get the attribute on the proxied object and return a proxy if mutable.
  3179. Args:
  3180. __name: The name of the attribute.
  3181. Returns:
  3182. The attribute value.
  3183. """
  3184. value = super().__getattr__(__name)
  3185. if callable(value):
  3186. if __name in self.__mark_dirty_attrs__:
  3187. # Wrap special callables, like "append", which should mark state dirty.
  3188. value = wrapt.FunctionWrapper(value, self._mark_dirty)
  3189. if __name in self.__wrap_mutable_attrs__:
  3190. # Wrap methods that may return mutable objects tied to the state.
  3191. value = wrapt.FunctionWrapper(
  3192. value,
  3193. self._wrap_recursive_decorator,
  3194. )
  3195. if (
  3196. isinstance(self.__wrapped__, Base)
  3197. and __name not in self.__never_wrap_base_attrs__
  3198. and hasattr(value, "__func__")
  3199. ):
  3200. # Wrap methods called on Base subclasses, which might do _anything_
  3201. return wrapt.FunctionWrapper(
  3202. functools.partial(value.__func__, self),
  3203. self._wrap_recursive_decorator,
  3204. )
  3205. if self._is_mutable_type(value) and __name not in (
  3206. "__wrapped__",
  3207. "_self_state",
  3208. ):
  3209. # Recursively wrap mutable attribute values retrieved through this proxy.
  3210. return self._wrap_recursive(value)
  3211. return value
  3212. def __getitem__(self, key) -> Any:
  3213. """Get the item on the proxied object and return a proxy if mutable.
  3214. Args:
  3215. key: The key of the item.
  3216. Returns:
  3217. The item value.
  3218. """
  3219. value = super().__getitem__(key)
  3220. # Recursively wrap mutable items retrieved through this proxy.
  3221. return self._wrap_recursive(value)
  3222. def __iter__(self) -> Any:
  3223. """Iterate over the proxied object and return a proxy if mutable.
  3224. Yields:
  3225. Each item value (possibly wrapped in MutableProxy).
  3226. """
  3227. for value in super().__iter__():
  3228. # Recursively wrap mutable items retrieved through this proxy.
  3229. yield self._wrap_recursive(value)
  3230. def __delattr__(self, name):
  3231. """Delete the attribute on the proxied object and mark state dirty.
  3232. Args:
  3233. name: The name of the attribute.
  3234. """
  3235. self._mark_dirty(super().__delattr__, args=(name,))
  3236. def __delitem__(self, key):
  3237. """Delete the item on the proxied object and mark state dirty.
  3238. Args:
  3239. key: The key of the item.
  3240. """
  3241. self._mark_dirty(super().__delitem__, args=(key,))
  3242. def __setitem__(self, key, value):
  3243. """Set the item on the proxied object and mark state dirty.
  3244. Args:
  3245. key: The key of the item.
  3246. value: The value of the item.
  3247. """
  3248. self._mark_dirty(super().__setitem__, args=(key, value))
  3249. def __setattr__(self, name, value):
  3250. """Set the attribute on the proxied object and mark state dirty.
  3251. If the attribute starts with "_self_", then the state is NOT marked
  3252. dirty as these are internal proxy attributes.
  3253. Args:
  3254. name: The name of the attribute.
  3255. value: The value of the attribute.
  3256. """
  3257. if name.startswith("_self_"):
  3258. # Special case attributes of the proxy itself, not applied to the wrapped object.
  3259. super().__setattr__(name, value)
  3260. return
  3261. self._mark_dirty(super().__setattr__, args=(name, value))
  3262. def __copy__(self) -> Any:
  3263. """Return a copy of the proxy.
  3264. Returns:
  3265. A copy of the wrapped object, unconnected to the proxy.
  3266. """
  3267. return copy.copy(self.__wrapped__)
  3268. def __deepcopy__(self, memo=None) -> Any:
  3269. """Return a deepcopy of the proxy.
  3270. Args:
  3271. memo: The memo dict to use for the deepcopy.
  3272. Returns:
  3273. A deepcopy of the wrapped object, unconnected to the proxy.
  3274. """
  3275. return copy.deepcopy(self.__wrapped__, memo=memo)
  3276. def __reduce_ex__(self, protocol_version):
  3277. """Get the state for redis serialization.
  3278. This method is called by cloudpickle to serialize the object.
  3279. It explicitly serializes the wrapped object, stripping off the mutable proxy.
  3280. Args:
  3281. protocol_version: The protocol version.
  3282. Returns:
  3283. Tuple of (wrapped class, empty args, class __getstate__)
  3284. """
  3285. return self.__wrapped__.__reduce_ex__(protocol_version)
  3286. @serializer
  3287. def serialize_mutable_proxy(mp: MutableProxy):
  3288. """Return the wrapped value of a MutableProxy.
  3289. Args:
  3290. mp: The MutableProxy to serialize.
  3291. Returns:
  3292. The wrapped object.
  3293. """
  3294. return mp.__wrapped__
  3295. _orig_json_JSONEncoder_default = json.JSONEncoder.default
  3296. def _json_JSONEncoder_default_wrapper(self: json.JSONEncoder, o: Any) -> Any:
  3297. """Wrap JSONEncoder.default to handle MutableProxy objects.
  3298. Args:
  3299. self: the JSONEncoder instance.
  3300. o: the object to serialize.
  3301. Returns:
  3302. A JSON-able object.
  3303. """
  3304. try:
  3305. return o.__wrapped__
  3306. except AttributeError:
  3307. pass
  3308. return _orig_json_JSONEncoder_default(self, o)
  3309. json.JSONEncoder.default = _json_JSONEncoder_default_wrapper
  3310. class ImmutableMutableProxy(MutableProxy):
  3311. """A proxy for a mutable object that tracks changes.
  3312. This wrapper comes from StateProxy, and will raise an exception if an attempt is made
  3313. to modify the wrapped object when the StateProxy is immutable.
  3314. """
  3315. # Ensure that recursively wrapped proxies use ImmutableMutableProxy as base.
  3316. __base_proxy__ = "ImmutableMutableProxy"
  3317. def _mark_dirty(
  3318. self,
  3319. wrapped=None,
  3320. instance=None,
  3321. args=(),
  3322. kwargs=None,
  3323. ) -> Any:
  3324. """Raise an exception when an attempt is made to modify the object.
  3325. Intended for use with `FunctionWrapper` from the `wrapt` library.
  3326. Args:
  3327. wrapped: The wrapped function.
  3328. instance: The instance of the wrapped function.
  3329. args: The args for the wrapped function.
  3330. kwargs: The kwargs for the wrapped function.
  3331. Returns:
  3332. The result of the wrapped function.
  3333. Raises:
  3334. ImmutableStateError: if the StateProxy is not mutable.
  3335. """
  3336. if not self._self_state._is_mutable():
  3337. raise ImmutableStateError(
  3338. "Background task StateProxy is immutable outside of a context "
  3339. "manager. Use `async with self` to modify state."
  3340. )
  3341. return super()._mark_dirty(
  3342. wrapped=wrapped, instance=instance, args=args, kwargs=kwargs
  3343. )
  3344. def code_uses_state_contexts(javascript_code: str) -> bool:
  3345. """Check if the rendered Javascript uses state contexts.
  3346. Args:
  3347. javascript_code: The Javascript code to check.
  3348. Returns:
  3349. True if the code attempts to access a member of StateContexts.
  3350. """
  3351. return bool("useContext(StateContexts" in javascript_code)
  3352. def reload_state_module(
  3353. module: str,
  3354. state: Type[BaseState] = State,
  3355. ) -> None:
  3356. """Reset rx.State subclasses to avoid conflict when reloading.
  3357. Args:
  3358. module: The module to reload.
  3359. state: Recursive argument for the state class to reload.
  3360. """
  3361. for subclass in tuple(state.class_subclasses):
  3362. reload_state_module(module=module, state=subclass)
  3363. if subclass.__module__ == module and module is not None:
  3364. state.class_subclasses.remove(subclass)
  3365. state._always_dirty_substates.discard(subclass.get_name())
  3366. state._computed_var_dependencies = defaultdict(set)
  3367. state._substate_var_dependencies = defaultdict(set)
  3368. state._init_var_dependency_dicts()
  3369. state.get_class_substate.cache_clear()