state.py 107 KB

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