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