state.py 97 KB

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