state.py 97 KB

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