state.py 101 KB

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