1
0

state.py 80 KB

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