state.py 58 KB

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