state.py 105 KB

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