state.py 66 KB

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