state.py 70 KB

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