state.py 106 KB

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