state.py 98 KB

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