state.py 112 KB

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