state.py 97 KB

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