state.py 126 KB

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