state.py 100 KB

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