state.py 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365
  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. @classmethod
  922. @functools.lru_cache
  923. def _is_client_storage(cls, prop_name_or_field: str | ModelField) -> bool:
  924. """Check if the var is a client storage var.
  925. Args:
  926. prop_name_or_field: The name of the var or the field itself.
  927. Returns:
  928. Whether the var is a client storage var.
  929. """
  930. if isinstance(prop_name_or_field, str):
  931. field = cls.get_fields().get(prop_name_or_field)
  932. else:
  933. field = prop_name_or_field
  934. return field is not None and (
  935. isinstance(field.default, ClientStorageBase)
  936. or (
  937. isinstance(field.type_, type)
  938. and issubclass(field.type_, ClientStorageBase)
  939. )
  940. )
  941. def _reset_client_storage(self):
  942. """Reset client storage base vars to their default values."""
  943. # Client-side storage is reset during hydrate so that clearing cookies
  944. # on the browser also resets the values on the backend.
  945. fields = self.get_fields()
  946. for prop_name in self.base_vars:
  947. field = fields[prop_name]
  948. if self._is_client_storage(field):
  949. setattr(self, prop_name, copy.deepcopy(field.default))
  950. # Recursively reset the substate client storage.
  951. for substate in self.substates.values():
  952. substate._reset_client_storage()
  953. def get_substate(self, path: Sequence[str]) -> BaseState:
  954. """Get the substate.
  955. Args:
  956. path: The path to the substate.
  957. Returns:
  958. The substate.
  959. Raises:
  960. ValueError: If the substate is not found.
  961. """
  962. if len(path) == 0:
  963. return self
  964. if path[0] == self.get_name():
  965. if len(path) == 1:
  966. return self
  967. path = path[1:]
  968. if path[0] not in self.substates:
  969. raise ValueError(f"Invalid path: {path}")
  970. return self.substates[path[0]].get_substate(path[1:])
  971. @classmethod
  972. def _get_common_ancestor(cls, other: Type[BaseState]) -> str:
  973. """Find the name of the nearest common ancestor shared by this and the other state.
  974. Args:
  975. other: The other state.
  976. Returns:
  977. Full name of the nearest common ancestor.
  978. """
  979. common_ancestor_parts = []
  980. for part1, part2 in zip(
  981. cls.get_full_name().split("."),
  982. other.get_full_name().split("."),
  983. ):
  984. if part1 != part2:
  985. break
  986. common_ancestor_parts.append(part1)
  987. return ".".join(common_ancestor_parts)
  988. @classmethod
  989. def _determine_missing_parent_states(
  990. cls, target_state_cls: Type[BaseState]
  991. ) -> tuple[str, list[str]]:
  992. """Determine the missing parent states between the target_state_cls and common ancestor of this state.
  993. Args:
  994. target_state_cls: The class of the state to find missing parent states for.
  995. Returns:
  996. The name of the common ancestor and the list of missing parent states.
  997. """
  998. common_ancestor_name = cls._get_common_ancestor(target_state_cls)
  999. common_ancestor_parts = common_ancestor_name.split(".")
  1000. target_state_parts = tuple(target_state_cls.get_full_name().split("."))
  1001. relative_target_state_parts = target_state_parts[len(common_ancestor_parts) :]
  1002. # Determine which parent states to fetch from the common ancestor down to the target_state_cls.
  1003. fetch_parent_states = [common_ancestor_name]
  1004. for relative_parent_state_name in relative_target_state_parts:
  1005. fetch_parent_states.append(
  1006. ".".join((fetch_parent_states[-1], relative_parent_state_name))
  1007. )
  1008. return common_ancestor_name, fetch_parent_states[1:-1]
  1009. def _get_parent_states(self) -> list[tuple[str, BaseState]]:
  1010. """Get all parent state instances up to the root of the state tree.
  1011. Returns:
  1012. A list of tuples containing the name and the instance of each parent state.
  1013. """
  1014. parent_states_with_name = []
  1015. parent_state = self
  1016. while parent_state.parent_state is not None:
  1017. parent_state = parent_state.parent_state
  1018. parent_states_with_name.append((parent_state.get_full_name(), parent_state))
  1019. return parent_states_with_name
  1020. def _get_root_state(self) -> BaseState:
  1021. """Get the root state of the state tree.
  1022. Returns:
  1023. The root state of the state tree.
  1024. """
  1025. parent_state = self
  1026. while parent_state.parent_state is not None:
  1027. parent_state = parent_state.parent_state
  1028. return parent_state
  1029. async def _populate_parent_states(self, target_state_cls: Type[BaseState]):
  1030. """Populate substates in the tree between the target_state_cls and common ancestor of this state.
  1031. Args:
  1032. target_state_cls: The class of the state to populate parent states for.
  1033. Returns:
  1034. The parent state instance of target_state_cls.
  1035. Raises:
  1036. RuntimeError: If redis is not used in this backend process.
  1037. """
  1038. state_manager = get_state_manager()
  1039. if not isinstance(state_manager, StateManagerRedis):
  1040. raise RuntimeError(
  1041. f"Cannot populate parent states of {target_state_cls.get_full_name()} without redis. "
  1042. "(All states should already be available -- this is likely a bug).",
  1043. )
  1044. # Find the missing parent states up to the common ancestor.
  1045. (
  1046. common_ancestor_name,
  1047. missing_parent_states,
  1048. ) = self._determine_missing_parent_states(target_state_cls)
  1049. # Fetch all missing parent states and link them up to the common ancestor.
  1050. parent_states_tuple = self._get_parent_states()
  1051. root_state = parent_states_tuple[-1][1]
  1052. parent_states_by_name = dict(parent_states_tuple)
  1053. parent_state = parent_states_by_name[common_ancestor_name]
  1054. for parent_state_name in missing_parent_states:
  1055. try:
  1056. parent_state = root_state.get_substate(parent_state_name.split("."))
  1057. # The requested state is already cached, do NOT fetch it again.
  1058. continue
  1059. except ValueError:
  1060. # The requested state is missing, fetch from redis.
  1061. pass
  1062. parent_state = await state_manager.get_state(
  1063. token=_substate_key(
  1064. self.router.session.client_token, parent_state_name
  1065. ),
  1066. top_level=False,
  1067. get_substates=False,
  1068. parent_state=parent_state,
  1069. )
  1070. # Return the direct parent of target_state_cls for subsequent linking.
  1071. return parent_state
  1072. def _get_state_from_cache(self, state_cls: Type[BaseState]) -> BaseState:
  1073. """Get a state instance from the cache.
  1074. Args:
  1075. state_cls: The class of the state.
  1076. Returns:
  1077. The instance of state_cls associated with this state's client_token.
  1078. """
  1079. root_state = self._get_root_state()
  1080. return root_state.get_substate(state_cls.get_full_name().split("."))
  1081. async def _get_state_from_redis(self, state_cls: Type[BaseState]) -> BaseState:
  1082. """Get a state instance from redis.
  1083. Args:
  1084. state_cls: The class of the state.
  1085. Returns:
  1086. The instance of state_cls associated with this state's client_token.
  1087. Raises:
  1088. RuntimeError: If redis is not used in this backend process.
  1089. """
  1090. # Fetch all missing parent states from redis.
  1091. parent_state_of_state_cls = await self._populate_parent_states(state_cls)
  1092. # Then get the target state and all its substates.
  1093. state_manager = get_state_manager()
  1094. if not isinstance(state_manager, StateManagerRedis):
  1095. raise RuntimeError(
  1096. f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. "
  1097. "(All states should already be available -- this is likely a bug).",
  1098. )
  1099. return await state_manager.get_state(
  1100. token=_substate_key(self.router.session.client_token, state_cls),
  1101. top_level=False,
  1102. get_substates=True,
  1103. parent_state=parent_state_of_state_cls,
  1104. )
  1105. async def get_state(self, state_cls: Type[BaseState]) -> BaseState:
  1106. """Get an instance of the state associated with this token.
  1107. Allows for arbitrary access to sibling states from within an event handler.
  1108. Args:
  1109. state_cls: The class of the state.
  1110. Returns:
  1111. The instance of state_cls associated with this state's client_token.
  1112. """
  1113. # Fast case - if this state instance is already cached, get_substate from root state.
  1114. try:
  1115. return self._get_state_from_cache(state_cls)
  1116. except ValueError:
  1117. pass
  1118. # Slow case - fetch missing parent states from redis.
  1119. return await self._get_state_from_redis(state_cls)
  1120. def _get_event_handler(
  1121. self, event: Event
  1122. ) -> tuple[BaseState | StateProxy, EventHandler]:
  1123. """Get the event handler for the given event.
  1124. Args:
  1125. event: The event to get the handler for.
  1126. Returns:
  1127. The event handler.
  1128. Raises:
  1129. ValueError: If the event handler or substate is not found.
  1130. """
  1131. # Get the event handler.
  1132. path = event.name.split(".")
  1133. path, name = path[:-1], path[-1]
  1134. substate = self.get_substate(path)
  1135. if not substate:
  1136. raise ValueError(
  1137. "The value of state cannot be None when processing an event."
  1138. )
  1139. handler = substate.event_handlers[name]
  1140. # For background tasks, proxy the state
  1141. if handler.is_background:
  1142. substate = StateProxy(substate)
  1143. return substate, handler
  1144. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  1145. """Obtain event info and process event.
  1146. Args:
  1147. event: The event to process.
  1148. Yields:
  1149. The state update after processing the event.
  1150. """
  1151. # Get the event handler.
  1152. substate, handler = self._get_event_handler(event)
  1153. # Run the event generator and yield state updates.
  1154. async for update in self._process_event(
  1155. handler=handler,
  1156. state=substate,
  1157. payload=event.payload,
  1158. ):
  1159. yield update
  1160. def _check_valid(self, handler: EventHandler, events: Any) -> Any:
  1161. """Check if the events yielded are valid. They must be EventHandlers or EventSpecs.
  1162. Args:
  1163. handler: EventHandler.
  1164. events: The events to be checked.
  1165. Raises:
  1166. TypeError: If any of the events are not valid.
  1167. Returns:
  1168. The events as they are if valid.
  1169. """
  1170. def _is_valid_type(events: Any) -> bool:
  1171. return isinstance(events, (Event, EventHandler, EventSpec))
  1172. if events is None or _is_valid_type(events):
  1173. return events
  1174. try:
  1175. if all(_is_valid_type(e) for e in events):
  1176. return events
  1177. except TypeError:
  1178. pass
  1179. raise TypeError(
  1180. f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`)"
  1181. )
  1182. def _as_state_update(
  1183. self,
  1184. handler: EventHandler,
  1185. events: EventSpec | list[EventSpec] | None,
  1186. final: bool,
  1187. ) -> StateUpdate:
  1188. """Convert the events to a StateUpdate.
  1189. Fixes the events and checks for validity before converting.
  1190. Args:
  1191. handler: The handler where the events originated from.
  1192. events: The events to queue with the update.
  1193. final: Whether the handler is done processing.
  1194. Returns:
  1195. The valid StateUpdate containing the events and final flag.
  1196. """
  1197. # get the delta from the root of the state tree
  1198. state = self._get_root_state()
  1199. token = self.router.session.client_token
  1200. # Convert valid EventHandler and EventSpec into Event
  1201. fixed_events = fix_events(self._check_valid(handler, events), token)
  1202. try:
  1203. # Get the delta after processing the event.
  1204. delta = state.get_delta()
  1205. state._clean()
  1206. return StateUpdate(
  1207. delta=delta,
  1208. events=fixed_events,
  1209. final=final if not handler.is_background else True,
  1210. )
  1211. except Exception as ex:
  1212. state._clean()
  1213. app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1214. event_specs = app_instance.backend_exception_handler(ex)
  1215. if event_specs is None:
  1216. return StateUpdate()
  1217. event_specs_correct_type = cast(
  1218. Union[List[Union[EventSpec, EventHandler]], None],
  1219. [event_specs] if isinstance(event_specs, EventSpec) else event_specs,
  1220. )
  1221. fixed_events = fix_events(
  1222. event_specs_correct_type,
  1223. token,
  1224. router_data=state.router_data,
  1225. )
  1226. return StateUpdate(
  1227. events=fixed_events,
  1228. final=True,
  1229. )
  1230. async def _process_event(
  1231. self, handler: EventHandler, state: BaseState | StateProxy, payload: Dict
  1232. ) -> AsyncIterator[StateUpdate]:
  1233. """Process event.
  1234. Args:
  1235. handler: EventHandler to process.
  1236. state: State to process the handler.
  1237. payload: The event payload.
  1238. Yields:
  1239. StateUpdate object
  1240. """
  1241. from reflex.utils import telemetry
  1242. # Get the function to process the event.
  1243. fn = functools.partial(handler.fn, state)
  1244. # Wrap the function in a try/except block.
  1245. try:
  1246. # Handle async functions.
  1247. if asyncio.iscoroutinefunction(fn.func):
  1248. events = await fn(**payload)
  1249. # Handle regular functions.
  1250. else:
  1251. events = fn(**payload)
  1252. # Handle async generators.
  1253. if inspect.isasyncgen(events):
  1254. async for event in events:
  1255. yield state._as_state_update(handler, event, final=False)
  1256. yield state._as_state_update(handler, events=None, final=True)
  1257. # Handle regular generators.
  1258. elif inspect.isgenerator(events):
  1259. try:
  1260. while True:
  1261. yield state._as_state_update(handler, next(events), final=False)
  1262. except StopIteration as si:
  1263. # the "return" value of the generator is not available
  1264. # in the loop, we must catch StopIteration to access it
  1265. if si.value is not None:
  1266. yield state._as_state_update(handler, si.value, final=False)
  1267. yield state._as_state_update(handler, events=None, final=True)
  1268. # Handle regular event chains.
  1269. else:
  1270. yield state._as_state_update(handler, events, final=True)
  1271. # If an error occurs, throw a window alert.
  1272. except Exception as ex:
  1273. telemetry.send_error(ex, context="backend")
  1274. app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1275. event_specs = app_instance.backend_exception_handler(ex)
  1276. yield state._as_state_update(
  1277. handler,
  1278. event_specs,
  1279. final=True,
  1280. )
  1281. def _mark_dirty_computed_vars(self) -> None:
  1282. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  1283. dirty_vars = self.dirty_vars
  1284. while dirty_vars:
  1285. calc_vars, dirty_vars = dirty_vars, set()
  1286. for cvar in self._dirty_computed_vars(from_vars=calc_vars):
  1287. self.dirty_vars.add(cvar)
  1288. dirty_vars.add(cvar)
  1289. actual_var = self.computed_vars.get(cvar)
  1290. if actual_var is not None:
  1291. actual_var.mark_dirty(instance=self)
  1292. def _expired_computed_vars(self) -> set[str]:
  1293. """Determine ComputedVars that need to be recalculated based on the expiration time.
  1294. Returns:
  1295. Set of computed vars to include in the delta.
  1296. """
  1297. return set(
  1298. cvar
  1299. for cvar in self.computed_vars
  1300. if self.computed_vars[cvar].needs_update(instance=self)
  1301. )
  1302. def _dirty_computed_vars(
  1303. self, from_vars: set[str] | None = None, include_backend: bool = True
  1304. ) -> set[str]:
  1305. """Determine ComputedVars that need to be recalculated based on the given vars.
  1306. Args:
  1307. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  1308. include_backend: whether to include backend vars in the calculation.
  1309. Returns:
  1310. Set of computed vars to include in the delta.
  1311. """
  1312. return set(
  1313. cvar
  1314. for dirty_var in from_vars or self.dirty_vars
  1315. for cvar in self._computed_var_dependencies[dirty_var]
  1316. if include_backend or not self.computed_vars[cvar]._backend
  1317. )
  1318. @classmethod
  1319. def _potentially_dirty_substates(cls) -> set[Type[BaseState]]:
  1320. """Determine substates which could be affected by dirty vars in this state.
  1321. Returns:
  1322. Set of State classes that may need to be fetched to recalc computed vars.
  1323. """
  1324. # _always_dirty_substates need to be fetched to recalc computed vars.
  1325. fetch_substates = set(
  1326. cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
  1327. for substate_name in cls._always_dirty_substates
  1328. )
  1329. for dependent_substates in cls._substate_var_dependencies.values():
  1330. fetch_substates.update(
  1331. set(
  1332. cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
  1333. for substate_name in dependent_substates
  1334. )
  1335. )
  1336. return fetch_substates
  1337. def get_delta(self) -> Delta:
  1338. """Get the delta for the state.
  1339. Returns:
  1340. The delta for the state.
  1341. """
  1342. delta = {}
  1343. # Apply dirty variables down into substates
  1344. self.dirty_vars.update(self._always_dirty_computed_vars)
  1345. self._mark_dirty()
  1346. frontend_computed_vars: set[str] = {
  1347. name for name, cv in self.computed_vars.items() if not cv._backend
  1348. }
  1349. # Return the dirty vars for this instance, any cached/dependent computed vars,
  1350. # and always dirty computed vars (cache=False)
  1351. delta_vars = (
  1352. self.dirty_vars.intersection(self.base_vars)
  1353. .union(self.dirty_vars.intersection(frontend_computed_vars))
  1354. .union(self._dirty_computed_vars(include_backend=False))
  1355. .union(self._always_dirty_computed_vars)
  1356. )
  1357. subdelta = {
  1358. prop: getattr(self, prop)
  1359. for prop in delta_vars
  1360. if not types.is_backend_base_variable(prop, type(self))
  1361. }
  1362. if len(subdelta) > 0:
  1363. delta[self.get_full_name()] = subdelta
  1364. # Recursively find the substate deltas.
  1365. substates = self.substates
  1366. for substate in self.dirty_substates.union(self._always_dirty_substates):
  1367. delta.update(substates[substate].get_delta())
  1368. # Format the delta.
  1369. delta = format.format_state(delta)
  1370. # Return the delta.
  1371. return delta
  1372. def _mark_dirty(self):
  1373. """Mark the substate and all parent states as dirty."""
  1374. state_name = self.get_name()
  1375. if (
  1376. self.parent_state is not None
  1377. and state_name not in self.parent_state.dirty_substates
  1378. ):
  1379. self.parent_state.dirty_substates.add(self.get_name())
  1380. self.parent_state._mark_dirty()
  1381. # Append expired computed vars to dirty_vars to trigger recalculation
  1382. self.dirty_vars.update(self._expired_computed_vars())
  1383. # have to mark computed vars dirty to allow access to newly computed
  1384. # values within the same ComputedVar function
  1385. self._mark_dirty_computed_vars()
  1386. self._mark_dirty_substates()
  1387. def _mark_dirty_substates(self):
  1388. """Propagate dirty var / computed var status into substates."""
  1389. substates = self.substates
  1390. for var in self.dirty_vars:
  1391. for substate_name in self._substate_var_dependencies[var]:
  1392. self.dirty_substates.add(substate_name)
  1393. substate = substates[substate_name]
  1394. substate.dirty_vars.add(var)
  1395. substate._mark_dirty()
  1396. def _update_was_touched(self):
  1397. """Update the _was_touched flag based on dirty_vars."""
  1398. if self.dirty_vars and not self._was_touched:
  1399. for var in self.dirty_vars:
  1400. if var in self.base_vars or var in self._backend_vars:
  1401. self._was_touched = True
  1402. break
  1403. def _get_was_touched(self) -> bool:
  1404. """Check current dirty_vars and flag to determine if state instance was modified.
  1405. If any dirty vars belong to this state, mark _was_touched.
  1406. This flag determines whether this state instance should be persisted to redis.
  1407. Returns:
  1408. Whether this state instance was ever modified.
  1409. """
  1410. # Ensure the flag is up to date based on the current dirty_vars
  1411. self._update_was_touched()
  1412. return self._was_touched
  1413. def _clean(self):
  1414. """Reset the dirty vars."""
  1415. # Update touched status before cleaning dirty_vars.
  1416. self._update_was_touched()
  1417. # Recursively clean the substates.
  1418. for substate in self.dirty_substates:
  1419. if substate not in self.substates:
  1420. continue
  1421. self.substates[substate]._clean()
  1422. # Clean this state.
  1423. self.dirty_vars = set()
  1424. self.dirty_substates = set()
  1425. def get_value(self, key: str) -> Any:
  1426. """Get the value of a field (without proxying).
  1427. The returned value will NOT track dirty state updates.
  1428. Args:
  1429. key: The key of the field.
  1430. Returns:
  1431. The value of the field.
  1432. """
  1433. if isinstance(key, MutableProxy):
  1434. return super().get_value(key.__wrapped__)
  1435. return super().get_value(key)
  1436. def dict(
  1437. self, include_computed: bool = True, initial: bool = False, **kwargs
  1438. ) -> dict[str, Any]:
  1439. """Convert the object to a dictionary.
  1440. Args:
  1441. include_computed: Whether to include computed vars.
  1442. initial: Whether to get the initial value of computed vars.
  1443. **kwargs: Kwargs to pass to the pydantic dict method.
  1444. Returns:
  1445. The object as a dictionary.
  1446. """
  1447. if include_computed:
  1448. # Apply dirty variables down into substates to allow never-cached ComputedVar to
  1449. # trigger recalculation of dependent vars
  1450. self.dirty_vars.update(self._always_dirty_computed_vars)
  1451. self._mark_dirty()
  1452. base_vars = {
  1453. prop_name: self.get_value(getattr(self, prop_name))
  1454. for prop_name in self.base_vars
  1455. }
  1456. if initial:
  1457. computed_vars = {
  1458. # Include initial computed vars.
  1459. prop_name: (
  1460. cv._initial_value
  1461. if isinstance(cv, ComputedVar)
  1462. and not isinstance(cv._initial_value, types.Unset)
  1463. else self.get_value(getattr(self, prop_name))
  1464. )
  1465. for prop_name, cv in self.computed_vars.items()
  1466. if not cv._backend
  1467. }
  1468. elif include_computed:
  1469. computed_vars = {
  1470. # Include the computed vars.
  1471. prop_name: self.get_value(getattr(self, prop_name))
  1472. for prop_name, cv in self.computed_vars.items()
  1473. if not cv._backend
  1474. }
  1475. else:
  1476. computed_vars = {}
  1477. variables = {**base_vars, **computed_vars}
  1478. d = {
  1479. self.get_full_name(): {k: variables[k] for k in sorted(variables)},
  1480. }
  1481. for substate_d in [
  1482. v.dict(include_computed=include_computed, initial=initial, **kwargs)
  1483. for v in self.substates.values()
  1484. ]:
  1485. d.update(substate_d)
  1486. return d
  1487. async def __aenter__(self) -> BaseState:
  1488. """Enter the async context manager protocol.
  1489. This should not be used for the State class, but exists for
  1490. type-compatibility with StateProxy.
  1491. Raises:
  1492. TypeError: always, because async contextmanager protocol is only supported for background task.
  1493. """
  1494. raise TypeError(
  1495. "Only background task should use `async with self` to modify state."
  1496. )
  1497. async def __aexit__(self, *exc_info: Any) -> None:
  1498. """Exit the async context manager protocol.
  1499. This should not be used for the State class, but exists for
  1500. type-compatibility with StateProxy.
  1501. Args:
  1502. exc_info: The exception info tuple.
  1503. """
  1504. pass
  1505. def __getstate__(self):
  1506. """Get the state for redis serialization.
  1507. This method is called by cloudpickle to serialize the object.
  1508. It explicitly removes parent_state and substates because those are serialized separately
  1509. by the StateManagerRedis to allow for better horizontal scaling as state size increases.
  1510. Returns:
  1511. The state dict for serialization.
  1512. """
  1513. state = super().__getstate__()
  1514. # Never serialize parent_state or substates
  1515. state["__dict__"] = state["__dict__"].copy()
  1516. state["__dict__"]["parent_state"] = None
  1517. state["__dict__"]["substates"] = {}
  1518. state["__dict__"].pop("_was_touched", None)
  1519. return state
  1520. EventHandlerSetVar.update_forward_refs()
  1521. class State(BaseState):
  1522. """The app Base State."""
  1523. # The hydrated bool.
  1524. is_hydrated: bool = False
  1525. class FrontendEventExceptionState(State):
  1526. """Substate for handling frontend exceptions."""
  1527. def handle_frontend_exception(self, stack: str) -> None:
  1528. """Handle frontend exceptions.
  1529. If a frontend exception handler is provided, it will be called.
  1530. Otherwise, the default frontend exception handler will be called.
  1531. Args:
  1532. stack: The stack trace of the exception.
  1533. """
  1534. app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1535. app_instance.frontend_exception_handler(Exception(stack))
  1536. class UpdateVarsInternalState(State):
  1537. """Substate for handling internal state var updates."""
  1538. async def update_vars_internal(self, vars: dict[str, Any]) -> None:
  1539. """Apply updates to fully qualified state vars.
  1540. The keys in `vars` should be in the form of `{state.get_full_name()}.{var_name}`,
  1541. and each value will be set on the appropriate substate instance.
  1542. This function is primarily used to apply cookie and local storage
  1543. updates from the frontend to the appropriate substate.
  1544. Args:
  1545. vars: The fully qualified vars and values to update.
  1546. """
  1547. for var, value in vars.items():
  1548. state_name, _, var_name = var.rpartition(".")
  1549. var_state_cls = State.get_class_substate(state_name)
  1550. if var_state_cls._is_client_storage(var_name):
  1551. var_state = await self.get_state(var_state_cls)
  1552. setattr(var_state, var_name, value)
  1553. class OnLoadInternalState(State):
  1554. """Substate for handling on_load event enumeration.
  1555. This is a separate substate to avoid deserializing the entire state tree for every page navigation.
  1556. """
  1557. def on_load_internal(self) -> list[Event | EventSpec] | None:
  1558. """Queue on_load handlers for the current page.
  1559. Returns:
  1560. The list of events to queue for on load handling.
  1561. """
  1562. # Do not app._compile()! It should be already compiled by now.
  1563. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1564. load_events = app.get_load_events(self.router.page.path)
  1565. if not load_events:
  1566. self.is_hydrated = True
  1567. return # Fast path for navigation with no on_load events defined.
  1568. self.is_hydrated = False
  1569. return [
  1570. *fix_events(
  1571. load_events,
  1572. self.router.session.client_token,
  1573. router_data=self.router_data,
  1574. ),
  1575. State.set_is_hydrated(True), # type: ignore
  1576. ]
  1577. class ComponentState(State, mixin=True):
  1578. """Base class to allow for the creation of a state instance per component.
  1579. This allows for the bundling of UI and state logic into a single class,
  1580. where each instance has a separate instance of the state.
  1581. Subclass this class and define vars and event handlers in the traditional way.
  1582. Then define a `get_component` method that returns the UI for the component instance.
  1583. See the full [docs](https://reflex.dev/docs/substates/component-state/) for more.
  1584. Basic example:
  1585. ```python
  1586. # Subclass ComponentState and define vars and event handlers.
  1587. class Counter(rx.ComponentState):
  1588. # Define vars that change.
  1589. count: int = 0
  1590. # Define event handlers.
  1591. def increment(self):
  1592. self.count += 1
  1593. def decrement(self):
  1594. self.count -= 1
  1595. @classmethod
  1596. def get_component(cls, **props):
  1597. # Access the state vars and event handlers using `cls`.
  1598. return rx.hstack(
  1599. rx.button("Decrement", on_click=cls.decrement),
  1600. rx.text(cls.count),
  1601. rx.button("Increment", on_click=cls.increment),
  1602. **props,
  1603. )
  1604. counter = Counter.create()
  1605. ```
  1606. """
  1607. # The number of components created from this class.
  1608. _per_component_state_instance_count: ClassVar[int] = 0
  1609. @classmethod
  1610. def __init_subclass__(cls, mixin: bool = True, **kwargs):
  1611. """Overwrite mixin default to True.
  1612. Args:
  1613. mixin: Whether the subclass is a mixin and should not be initialized.
  1614. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  1615. """
  1616. super().__init_subclass__(mixin=mixin, **kwargs)
  1617. @classmethod
  1618. def get_component(cls, *children, **props) -> "Component":
  1619. """Get the component instance.
  1620. Args:
  1621. children: The children of the component.
  1622. props: The props of the component.
  1623. Raises:
  1624. NotImplementedError: if the subclass does not override this method.
  1625. """
  1626. raise NotImplementedError(
  1627. f"{cls.__name__} must implement get_component to return the component instance."
  1628. )
  1629. @classmethod
  1630. def create(cls, *children, **props) -> "Component":
  1631. """Create a new instance of the Component.
  1632. Args:
  1633. children: The children of the component.
  1634. props: The props of the component.
  1635. Returns:
  1636. A new instance of the Component with an independent copy of the State.
  1637. """
  1638. cls._per_component_state_instance_count += 1
  1639. state_cls_name = f"{cls.__name__}_n{cls._per_component_state_instance_count}"
  1640. component_state = type(state_cls_name, (cls, State), {}, mixin=False)
  1641. component = component_state.get_component(*children, **props)
  1642. component.State = component_state
  1643. return component
  1644. class StateProxy(wrapt.ObjectProxy):
  1645. """Proxy of a state instance to control mutability of vars for a background task.
  1646. Since a background task runs against a state instance without holding the
  1647. state_manager lock for the token, the reference may become stale if the same
  1648. state is modified by another event handler.
  1649. The proxy object ensures that writes to the state are blocked unless
  1650. explicitly entering a context which refreshes the state from state_manager
  1651. and holds the lock for the token until exiting the context. After exiting
  1652. the context, a StateUpdate may be emitted to the frontend to notify the
  1653. client of the state change.
  1654. A background task will be passed the `StateProxy` as `self`, so mutability
  1655. can be safely performed inside an `async with self` block.
  1656. class State(rx.State):
  1657. counter: int = 0
  1658. @rx.background
  1659. async def bg_increment(self):
  1660. await asyncio.sleep(1)
  1661. async with self:
  1662. self.counter += 1
  1663. """
  1664. def __init__(
  1665. self, state_instance, parent_state_proxy: Optional["StateProxy"] = None
  1666. ):
  1667. """Create a proxy for a state instance.
  1668. If `get_state` is used on a StateProxy, the resulting state will be
  1669. linked to the given state via parent_state_proxy. The first state in the
  1670. chain is the state that initiated the background task.
  1671. Args:
  1672. state_instance: The state instance to proxy.
  1673. parent_state_proxy: The parent state proxy, for linked mutability and context tracking.
  1674. """
  1675. super().__init__(state_instance)
  1676. # compile is not relevant to backend logic
  1677. self._self_app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  1678. self._self_substate_path = tuple(state_instance.get_full_name().split("."))
  1679. self._self_actx = None
  1680. self._self_mutable = False
  1681. self._self_actx_lock = asyncio.Lock()
  1682. self._self_actx_lock_holder = None
  1683. self._self_parent_state_proxy = parent_state_proxy
  1684. def _is_mutable(self) -> bool:
  1685. """Check if the state is mutable.
  1686. Returns:
  1687. Whether the state is mutable.
  1688. """
  1689. if self._self_parent_state_proxy is not None:
  1690. return self._self_parent_state_proxy._is_mutable() or self._self_mutable
  1691. return self._self_mutable
  1692. async def __aenter__(self) -> StateProxy:
  1693. """Enter the async context manager protocol.
  1694. Sets mutability to True and enters the `App.modify_state` async context,
  1695. which refreshes the state from state_manager and holds the lock for the
  1696. given state token until exiting the context.
  1697. Background tasks should avoid blocking calls while inside the context.
  1698. Returns:
  1699. This StateProxy instance in mutable mode.
  1700. Raises:
  1701. ImmutableStateError: If the state is already mutable.
  1702. """
  1703. if self._self_parent_state_proxy is not None:
  1704. parent_state = (
  1705. await self._self_parent_state_proxy.__aenter__()
  1706. ).__wrapped__
  1707. super().__setattr__(
  1708. "__wrapped__",
  1709. await parent_state.get_state(
  1710. State.get_class_substate(self._self_substate_path)
  1711. ),
  1712. )
  1713. return self
  1714. current_task = asyncio.current_task()
  1715. if (
  1716. self._self_actx_lock.locked()
  1717. and current_task == self._self_actx_lock_holder
  1718. ):
  1719. raise ImmutableStateError(
  1720. "The state is already mutable. Do not nest `async with self` blocks."
  1721. )
  1722. await self._self_actx_lock.acquire()
  1723. self._self_actx_lock_holder = current_task
  1724. self._self_actx = self._self_app.modify_state(
  1725. token=_substate_key(
  1726. self.__wrapped__.router.session.client_token,
  1727. self._self_substate_path,
  1728. )
  1729. )
  1730. mutable_state = await self._self_actx.__aenter__()
  1731. super().__setattr__(
  1732. "__wrapped__", mutable_state.get_substate(self._self_substate_path)
  1733. )
  1734. self._self_mutable = True
  1735. return self
  1736. async def __aexit__(self, *exc_info: Any) -> None:
  1737. """Exit the async context manager protocol.
  1738. Sets proxy mutability to False and persists any state changes.
  1739. Args:
  1740. exc_info: The exception info tuple.
  1741. """
  1742. if self._self_parent_state_proxy is not None:
  1743. await self._self_parent_state_proxy.__aexit__(*exc_info)
  1744. return
  1745. if self._self_actx is None:
  1746. return
  1747. self._self_mutable = False
  1748. try:
  1749. await self._self_actx.__aexit__(*exc_info)
  1750. finally:
  1751. self._self_actx_lock_holder = None
  1752. self._self_actx_lock.release()
  1753. self._self_actx = None
  1754. def __enter__(self):
  1755. """Enter the regular context manager protocol.
  1756. This is not supported for background tasks, and exists only to raise a more useful exception
  1757. when the StateProxy is used incorrectly.
  1758. Raises:
  1759. TypeError: always, because only async contextmanager protocol is supported.
  1760. """
  1761. raise TypeError("Background task must use `async with self` to modify state.")
  1762. def __exit__(self, *exc_info: Any) -> None:
  1763. """Exit the regular context manager protocol.
  1764. Args:
  1765. exc_info: The exception info tuple.
  1766. """
  1767. pass
  1768. def __getattr__(self, name: str) -> Any:
  1769. """Get the attribute from the underlying state instance.
  1770. Args:
  1771. name: The name of the attribute.
  1772. Returns:
  1773. The value of the attribute.
  1774. Raises:
  1775. ImmutableStateError: If the state is not in mutable mode.
  1776. """
  1777. if name in ["substates", "parent_state"] and not self._is_mutable():
  1778. raise ImmutableStateError(
  1779. "Background task StateProxy is immutable outside of a context "
  1780. "manager. Use `async with self` to modify state."
  1781. )
  1782. value = super().__getattr__(name)
  1783. if not name.startswith("_self_") and isinstance(value, MutableProxy):
  1784. # ensure mutations to these containers are blocked unless proxy is _mutable
  1785. return ImmutableMutableProxy(
  1786. wrapped=value.__wrapped__,
  1787. state=self, # type: ignore
  1788. field_name=value._self_field_name,
  1789. )
  1790. if isinstance(value, functools.partial) and value.args[0] is self.__wrapped__:
  1791. # Rebind event handler to the proxy instance
  1792. value = functools.partial(
  1793. value.func,
  1794. self,
  1795. *value.args[1:],
  1796. **value.keywords,
  1797. )
  1798. if isinstance(value, MethodType) and value.__self__ is self.__wrapped__:
  1799. # Rebind methods to the proxy instance
  1800. value = type(value)(value.__func__, self) # type: ignore
  1801. return value
  1802. def __setattr__(self, name: str, value: Any) -> None:
  1803. """Set the attribute on the underlying state instance.
  1804. If the attribute is internal, set it on the proxy instance instead.
  1805. Args:
  1806. name: The name of the attribute.
  1807. value: The value of the attribute.
  1808. Raises:
  1809. ImmutableStateError: If the state is not in mutable mode.
  1810. """
  1811. if (
  1812. name.startswith("_self_") # wrapper attribute
  1813. or self._is_mutable() # lock held
  1814. # non-persisted state attribute
  1815. or name in self.__wrapped__.get_skip_vars()
  1816. ):
  1817. super().__setattr__(name, value)
  1818. return
  1819. raise ImmutableStateError(
  1820. "Background task StateProxy is immutable outside of a context "
  1821. "manager. Use `async with self` to modify state."
  1822. )
  1823. def get_substate(self, path: Sequence[str]) -> BaseState:
  1824. """Only allow substate access with lock held.
  1825. Args:
  1826. path: The path to the substate.
  1827. Returns:
  1828. The substate.
  1829. Raises:
  1830. ImmutableStateError: If the state is not in mutable mode.
  1831. """
  1832. if not self._is_mutable():
  1833. raise ImmutableStateError(
  1834. "Background task StateProxy is immutable outside of a context "
  1835. "manager. Use `async with self` to modify state."
  1836. )
  1837. return self.__wrapped__.get_substate(path)
  1838. async def get_state(self, state_cls: Type[BaseState]) -> BaseState:
  1839. """Get an instance of the state associated with this token.
  1840. Args:
  1841. state_cls: The class of the state.
  1842. Returns:
  1843. The state.
  1844. Raises:
  1845. ImmutableStateError: If the state is not in mutable mode.
  1846. """
  1847. if not self._is_mutable():
  1848. raise ImmutableStateError(
  1849. "Background task StateProxy is immutable outside of a context "
  1850. "manager. Use `async with self` to modify state."
  1851. )
  1852. return type(self)(
  1853. await self.__wrapped__.get_state(state_cls), parent_state_proxy=self
  1854. )
  1855. def _as_state_update(self, *args, **kwargs) -> StateUpdate:
  1856. """Temporarily allow mutability to access parent_state.
  1857. Args:
  1858. *args: The args to pass to the underlying state instance.
  1859. **kwargs: The kwargs to pass to the underlying state instance.
  1860. Returns:
  1861. The state update.
  1862. """
  1863. self._self_mutable = True
  1864. try:
  1865. return self.__wrapped__._as_state_update(*args, **kwargs)
  1866. finally:
  1867. self._self_mutable = False
  1868. class StateUpdate(Base):
  1869. """A state update sent to the frontend."""
  1870. # The state delta.
  1871. delta: Delta = {}
  1872. # Events to be added to the event queue.
  1873. events: List[Event] = []
  1874. # Whether this is the final state update for the event.
  1875. final: bool = True
  1876. class StateManager(Base, ABC):
  1877. """A class to manage many client states."""
  1878. # The state class to use.
  1879. state: Type[BaseState]
  1880. @classmethod
  1881. def create(cls, state: Type[BaseState]):
  1882. """Create a new state manager.
  1883. Args:
  1884. state: The state class to use.
  1885. Returns:
  1886. The state manager (either memory or redis).
  1887. """
  1888. redis = prerequisites.get_redis()
  1889. if redis is not None:
  1890. # make sure expiration values are obtained only from the config object on creation
  1891. config = get_config()
  1892. return StateManagerRedis(
  1893. state=state,
  1894. redis=redis,
  1895. token_expiration=config.redis_token_expiration,
  1896. lock_expiration=config.redis_lock_expiration,
  1897. )
  1898. return StateManagerMemory(state=state)
  1899. @abstractmethod
  1900. async def get_state(self, token: str) -> BaseState:
  1901. """Get the state for a token.
  1902. Args:
  1903. token: The token to get the state for.
  1904. Returns:
  1905. The state for the token.
  1906. """
  1907. pass
  1908. @abstractmethod
  1909. async def set_state(self, token: str, state: BaseState):
  1910. """Set the state for a token.
  1911. Args:
  1912. token: The token to set the state for.
  1913. state: The state to set.
  1914. """
  1915. pass
  1916. @abstractmethod
  1917. @contextlib.asynccontextmanager
  1918. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1919. """Modify the state for a token while holding exclusive lock.
  1920. Args:
  1921. token: The token to modify the state for.
  1922. Yields:
  1923. The state for the token.
  1924. """
  1925. yield self.state()
  1926. class StateManagerMemory(StateManager):
  1927. """A state manager that stores states in memory."""
  1928. # The mapping of client ids to states.
  1929. states: Dict[str, BaseState] = {}
  1930. # The mutex ensures the dict of mutexes is updated exclusively
  1931. _state_manager_lock = asyncio.Lock()
  1932. # The dict of mutexes for each client
  1933. _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({})
  1934. class Config:
  1935. """The Pydantic config."""
  1936. fields = {
  1937. "_states_locks": {"exclude": True},
  1938. }
  1939. @override
  1940. async def get_state(self, token: str) -> BaseState:
  1941. """Get the state for a token.
  1942. Args:
  1943. token: The token to get the state for.
  1944. Returns:
  1945. The state for the token.
  1946. """
  1947. # Memory state manager ignores the substate suffix and always returns the top-level state.
  1948. token = _split_substate_key(token)[0]
  1949. if token not in self.states:
  1950. self.states[token] = self.state(_reflex_internal_init=True)
  1951. return self.states[token]
  1952. @override
  1953. async def set_state(self, token: str, state: BaseState):
  1954. """Set the state for a token.
  1955. Args:
  1956. token: The token to set the state for.
  1957. state: The state to set.
  1958. """
  1959. pass
  1960. @override
  1961. @contextlib.asynccontextmanager
  1962. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1963. """Modify the state for a token while holding exclusive lock.
  1964. Args:
  1965. token: The token to modify the state for.
  1966. Yields:
  1967. The state for the token.
  1968. """
  1969. # Memory state manager ignores the substate suffix and always returns the top-level state.
  1970. token = _split_substate_key(token)[0]
  1971. if token not in self._states_locks:
  1972. async with self._state_manager_lock:
  1973. if token not in self._states_locks:
  1974. self._states_locks[token] = asyncio.Lock()
  1975. async with self._states_locks[token]:
  1976. state = await self.get_state(token)
  1977. yield state
  1978. await self.set_state(token, state)
  1979. # Workaround https://github.com/cloudpipe/cloudpickle/issues/408 for dynamic pydantic classes
  1980. if not isinstance(State.validate.__func__, FunctionType):
  1981. cython_function_or_method = type(State.validate.__func__)
  1982. @dill.register(cython_function_or_method)
  1983. def _dill_reduce_cython_function_or_method(pickler, obj):
  1984. # Ignore cython function when pickling.
  1985. pass
  1986. @dill.register(type(State))
  1987. def _dill_reduce_state(pickler, obj):
  1988. if obj is not State and issubclass(obj, State):
  1989. # Avoid serializing subclasses of State, instead get them by reference from the State class.
  1990. pickler.save_reduce(State.get_class_substate, (obj.get_full_name(),), obj=obj)
  1991. else:
  1992. dill.Pickler.dispatch[type](pickler, obj)
  1993. def _default_lock_expiration() -> int:
  1994. """Get the default lock expiration time.
  1995. Returns:
  1996. The default lock expiration time.
  1997. """
  1998. return get_config().redis_lock_expiration
  1999. def _default_token_expiration() -> int:
  2000. """Get the default token expiration time.
  2001. Returns:
  2002. The default token expiration time.
  2003. """
  2004. return get_config().redis_token_expiration
  2005. class StateManagerRedis(StateManager):
  2006. """A state manager that stores states in redis."""
  2007. # The redis client to use.
  2008. redis: Redis
  2009. # The token expiration time (s).
  2010. token_expiration: int = pydantic.Field(default_factory=_default_token_expiration)
  2011. # The maximum time to hold a lock (ms).
  2012. lock_expiration: int = pydantic.Field(default_factory=_default_lock_expiration)
  2013. # The keyspace subscription string when redis is waiting for lock to be released
  2014. _redis_notify_keyspace_events: str = (
  2015. "K" # Enable keyspace notifications (target a particular key)
  2016. "g" # For generic commands (DEL, EXPIRE, etc)
  2017. "x" # For expired events
  2018. "e" # For evicted events (i.e. maxmemory exceeded)
  2019. )
  2020. # These events indicate that a lock is no longer held
  2021. _redis_keyspace_lock_release_events: Set[bytes] = {
  2022. b"del",
  2023. b"expire",
  2024. b"expired",
  2025. b"evicted",
  2026. }
  2027. # Only warn about each state class size once.
  2028. _warned_about_state_size: ClassVar[Set[str]] = set()
  2029. async def _get_parent_state(self, token: str) -> BaseState | None:
  2030. """Get the parent state for the state requested in the token.
  2031. Args:
  2032. token: The token to get the state for (_substate_key).
  2033. Returns:
  2034. The parent state for the state requested by the token or None if there is no such parent.
  2035. """
  2036. parent_state = None
  2037. client_token, state_path = _split_substate_key(token)
  2038. parent_state_name = state_path.rpartition(".")[0]
  2039. if parent_state_name:
  2040. # Retrieve the parent state to populate event handlers onto this substate.
  2041. parent_state = await self.get_state(
  2042. token=_substate_key(client_token, parent_state_name),
  2043. top_level=False,
  2044. get_substates=False,
  2045. )
  2046. return parent_state
  2047. async def _populate_substates(
  2048. self,
  2049. token: str,
  2050. state: BaseState,
  2051. all_substates: bool = False,
  2052. ):
  2053. """Fetch and link substates for the given state instance.
  2054. There is no return value; the side-effect is that `state` will have `substates` populated,
  2055. and each substate will have its `parent_state` set to `state`.
  2056. Args:
  2057. token: The token to get the state for.
  2058. state: The state instance to populate substates for.
  2059. all_substates: Whether to fetch all substates or just required substates.
  2060. """
  2061. client_token, _ = _split_substate_key(token)
  2062. if all_substates:
  2063. # All substates are requested.
  2064. fetch_substates = state.get_substates()
  2065. else:
  2066. # Only _potentially_dirty_substates need to be fetched to recalc computed vars.
  2067. fetch_substates = state._potentially_dirty_substates()
  2068. tasks = {}
  2069. # Retrieve the necessary substates from redis.
  2070. for substate_cls in fetch_substates:
  2071. substate_name = substate_cls.get_name()
  2072. tasks[substate_name] = asyncio.create_task(
  2073. self.get_state(
  2074. token=_substate_key(client_token, substate_cls),
  2075. top_level=False,
  2076. get_substates=all_substates,
  2077. parent_state=state,
  2078. )
  2079. )
  2080. for substate_name, substate_task in tasks.items():
  2081. state.substates[substate_name] = await substate_task
  2082. @override
  2083. async def get_state(
  2084. self,
  2085. token: str,
  2086. top_level: bool = True,
  2087. get_substates: bool = True,
  2088. parent_state: BaseState | None = None,
  2089. ) -> BaseState:
  2090. """Get the state for a token.
  2091. Args:
  2092. token: The token to get the state for.
  2093. top_level: If true, return an instance of the top-level state (self.state).
  2094. get_substates: If true, also retrieve substates.
  2095. parent_state: If provided, use this parent_state instead of getting it from redis.
  2096. Returns:
  2097. The state for the token.
  2098. Raises:
  2099. RuntimeError: when the state_cls is not specified in the token
  2100. """
  2101. # Split the actual token from the fully qualified substate name.
  2102. _, state_path = _split_substate_key(token)
  2103. if state_path:
  2104. # Get the State class associated with the given path.
  2105. state_cls = self.state.get_class_substate(state_path)
  2106. else:
  2107. raise RuntimeError(
  2108. "StateManagerRedis requires token to be specified in the form of {token}_{state_full_name}"
  2109. )
  2110. # Fetch the serialized substate from redis.
  2111. redis_state = await self.redis.get(token)
  2112. if redis_state is not None:
  2113. # Deserialize the substate.
  2114. state = dill.loads(redis_state)
  2115. # Populate parent state if missing and requested.
  2116. if parent_state is None:
  2117. parent_state = await self._get_parent_state(token)
  2118. # Set up Bidirectional linkage between this state and its parent.
  2119. if parent_state is not None:
  2120. parent_state.substates[state.get_name()] = state
  2121. state.parent_state = parent_state
  2122. # Populate substates if requested.
  2123. await self._populate_substates(token, state, all_substates=get_substates)
  2124. # To retain compatibility with previous implementation, by default, we return
  2125. # the top-level state by chasing `parent_state` pointers up the tree.
  2126. if top_level:
  2127. return state._get_root_state()
  2128. return state
  2129. # TODO: dedupe the following logic with the above block
  2130. # Key didn't exist so we have to create a new instance for this token.
  2131. if parent_state is None:
  2132. parent_state = await self._get_parent_state(token)
  2133. # Instantiate the new state class (but don't persist it yet).
  2134. state = state_cls(
  2135. parent_state=parent_state,
  2136. init_substates=False,
  2137. _reflex_internal_init=True,
  2138. )
  2139. # Set up Bidirectional linkage between this state and its parent.
  2140. if parent_state is not None:
  2141. parent_state.substates[state.get_name()] = state
  2142. state.parent_state = parent_state
  2143. # Populate substates for the newly created state.
  2144. await self._populate_substates(token, state, all_substates=get_substates)
  2145. # To retain compatibility with previous implementation, by default, we return
  2146. # the top-level state by chasing `parent_state` pointers up the tree.
  2147. if top_level:
  2148. return state._get_root_state()
  2149. return state
  2150. def _warn_if_too_large(
  2151. self,
  2152. state: BaseState,
  2153. pickle_state_size: int,
  2154. ):
  2155. """Print a warning when the state is too large.
  2156. Args:
  2157. state: The state to check.
  2158. pickle_state_size: The size of the pickled state.
  2159. """
  2160. state_full_name = state.get_full_name()
  2161. if (
  2162. state_full_name not in self._warned_about_state_size
  2163. and pickle_state_size > TOO_LARGE_SERIALIZED_STATE
  2164. and state.substates
  2165. ):
  2166. console.warn(
  2167. f"State {state_full_name} serializes to {pickle_state_size} bytes "
  2168. "which may present performance issues. Consider reducing the size of this state."
  2169. )
  2170. self._warned_about_state_size.add(state_full_name)
  2171. @override
  2172. async def set_state(
  2173. self,
  2174. token: str,
  2175. state: BaseState,
  2176. lock_id: bytes | None = None,
  2177. ):
  2178. """Set the state for a token.
  2179. Args:
  2180. token: The token to set the state for.
  2181. state: The state to set.
  2182. lock_id: If provided, the lock_key must be set to this value to set the state.
  2183. Raises:
  2184. LockExpiredError: If lock_id is provided and the lock for the token is not held by that ID.
  2185. RuntimeError: If the state instance doesn't match the state name in the token.
  2186. """
  2187. # Check that we're holding the lock.
  2188. if (
  2189. lock_id is not None
  2190. and await self.redis.get(self._lock_key(token)) != lock_id
  2191. ):
  2192. raise LockExpiredError(
  2193. f"Lock expired for token {token} while processing. Consider increasing "
  2194. f"`app.state_manager.lock_expiration` (currently {self.lock_expiration}) "
  2195. "or use `@rx.background` decorator for long-running tasks."
  2196. )
  2197. client_token, substate_name = _split_substate_key(token)
  2198. # If the substate name on the token doesn't match the instance name, it cannot have a parent.
  2199. if state.parent_state is not None and state.get_full_name() != substate_name:
  2200. raise RuntimeError(
  2201. f"Cannot `set_state` with mismatching token {token} and substate {state.get_full_name()}."
  2202. )
  2203. # Recursively set_state on all known substates.
  2204. tasks = []
  2205. for substate in state.substates.values():
  2206. tasks.append(
  2207. asyncio.create_task(
  2208. self.set_state(
  2209. token=_substate_key(client_token, substate),
  2210. state=substate,
  2211. lock_id=lock_id,
  2212. )
  2213. )
  2214. )
  2215. # Persist only the given state (parents or substates are excluded by BaseState.__getstate__).
  2216. if state._get_was_touched():
  2217. pickle_state = dill.dumps(state, byref=True)
  2218. self._warn_if_too_large(state, len(pickle_state))
  2219. await self.redis.set(
  2220. _substate_key(client_token, state),
  2221. pickle_state,
  2222. ex=self.token_expiration,
  2223. )
  2224. # Wait for substates to be persisted.
  2225. for t in tasks:
  2226. await t
  2227. @override
  2228. @contextlib.asynccontextmanager
  2229. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  2230. """Modify the state for a token while holding exclusive lock.
  2231. Args:
  2232. token: The token to modify the state for.
  2233. Yields:
  2234. The state for the token.
  2235. """
  2236. async with self._lock(token) as lock_id:
  2237. state = await self.get_state(token)
  2238. yield state
  2239. await self.set_state(token, state, lock_id)
  2240. @staticmethod
  2241. def _lock_key(token: str) -> bytes:
  2242. """Get the redis key for a token's lock.
  2243. Args:
  2244. token: The token to get the lock key for.
  2245. Returns:
  2246. The redis lock key for the token.
  2247. """
  2248. # All substates share the same lock domain, so ignore any substate path suffix.
  2249. client_token = _split_substate_key(token)[0]
  2250. return f"{client_token}_lock".encode()
  2251. async def _try_get_lock(self, lock_key: bytes, lock_id: bytes) -> bool | None:
  2252. """Try to get a redis lock for a token.
  2253. Args:
  2254. lock_key: The redis key for the lock.
  2255. lock_id: The ID of the lock.
  2256. Returns:
  2257. True if the lock was obtained.
  2258. """
  2259. return await self.redis.set(
  2260. lock_key,
  2261. lock_id,
  2262. px=self.lock_expiration,
  2263. nx=True, # only set if it doesn't exist
  2264. )
  2265. async def _wait_lock(self, lock_key: bytes, lock_id: bytes) -> None:
  2266. """Wait for a redis lock to be released via pubsub.
  2267. Coroutine will not return until the lock is obtained.
  2268. Args:
  2269. lock_key: The redis key for the lock.
  2270. lock_id: The ID of the lock.
  2271. Raises:
  2272. ResponseError: when the keyspace config cannot be set.
  2273. """
  2274. state_is_locked = False
  2275. lock_key_channel = f"__keyspace@0__:{lock_key.decode()}"
  2276. # Enable keyspace notifications for the lock key, so we know when it is available.
  2277. try:
  2278. await self.redis.config_set(
  2279. "notify-keyspace-events",
  2280. self._redis_notify_keyspace_events,
  2281. )
  2282. except ResponseError:
  2283. # Some redis servers only allow out-of-band configuration, so ignore errors here.
  2284. ignore_config_error = os.environ.get(
  2285. "REFLEX_IGNORE_REDIS_CONFIG_ERROR",
  2286. None,
  2287. )
  2288. if not ignore_config_error:
  2289. raise
  2290. async with self.redis.pubsub() as pubsub:
  2291. await pubsub.psubscribe(lock_key_channel)
  2292. while not state_is_locked:
  2293. # wait for the lock to be released
  2294. while True:
  2295. if not await self.redis.exists(lock_key):
  2296. break # key was removed, try to get the lock again
  2297. message = await pubsub.get_message(
  2298. ignore_subscribe_messages=True,
  2299. timeout=self.lock_expiration / 1000.0,
  2300. )
  2301. if message is None:
  2302. continue
  2303. if message["data"] in self._redis_keyspace_lock_release_events:
  2304. break
  2305. state_is_locked = await self._try_get_lock(lock_key, lock_id)
  2306. @contextlib.asynccontextmanager
  2307. async def _lock(self, token: str):
  2308. """Obtain a redis lock for a token.
  2309. Args:
  2310. token: The token to obtain a lock for.
  2311. Yields:
  2312. The ID of the lock (to be passed to set_state).
  2313. Raises:
  2314. LockExpiredError: If the lock has expired while processing the event.
  2315. """
  2316. lock_key = self._lock_key(token)
  2317. lock_id = uuid.uuid4().hex.encode()
  2318. if not await self._try_get_lock(lock_key, lock_id):
  2319. # Missed the fast-path to get lock, subscribe for lock delete/expire events
  2320. await self._wait_lock(lock_key, lock_id)
  2321. state_is_locked = True
  2322. try:
  2323. yield lock_id
  2324. except LockExpiredError:
  2325. state_is_locked = False
  2326. raise
  2327. finally:
  2328. if state_is_locked:
  2329. # only delete our lock
  2330. await self.redis.delete(lock_key)
  2331. async def close(self):
  2332. """Explicitly close the redis connection and connection_pool.
  2333. It is necessary in testing scenarios to close between asyncio test cases
  2334. to avoid having lingering redis connections associated with event loops
  2335. that will be closed (each test case uses its own event loop).
  2336. Note: Connections will be automatically reopened when needed.
  2337. """
  2338. await self.redis.aclose(close_connection_pool=True)
  2339. def get_state_manager() -> StateManager:
  2340. """Get the state manager for the app that is currently running.
  2341. Returns:
  2342. The state manager.
  2343. """
  2344. app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
  2345. return app.state_manager
  2346. class ClientStorageBase:
  2347. """Base class for client-side storage."""
  2348. def options(self) -> dict[str, Any]:
  2349. """Get the options for the storage.
  2350. Returns:
  2351. All set options for the storage (not None).
  2352. """
  2353. return {
  2354. format.to_camel_case(k): v for k, v in vars(self).items() if v is not None
  2355. }
  2356. class Cookie(ClientStorageBase, str):
  2357. """Represents a state Var that is stored as a cookie in the browser."""
  2358. name: str | None
  2359. path: str
  2360. max_age: int | None
  2361. domain: str | None
  2362. secure: bool | None
  2363. same_site: str
  2364. def __new__(
  2365. cls,
  2366. object: Any = "",
  2367. encoding: str | None = None,
  2368. errors: str | None = None,
  2369. /,
  2370. name: str | None = None,
  2371. path: str = "/",
  2372. max_age: int | None = None,
  2373. domain: str | None = None,
  2374. secure: bool | None = None,
  2375. same_site: str = "lax",
  2376. ):
  2377. """Create a client-side Cookie (str).
  2378. Args:
  2379. object: The initial object.
  2380. encoding: The encoding to use.
  2381. errors: The error handling scheme to use.
  2382. name: The name of the cookie on the client side.
  2383. path: Cookie path. Use / as the path if the cookie should be accessible on all pages.
  2384. max_age: Relative max age of the cookie in seconds from when the client receives it.
  2385. domain: Domain for the cookie (sub.domain.com or .allsubdomains.com).
  2386. secure: Is the cookie only accessible through HTTPS?
  2387. same_site: Whether the cookie is sent with third party requests.
  2388. One of (true|false|none|lax|strict)
  2389. Returns:
  2390. The client-side Cookie object.
  2391. Note: expires (absolute Date) is not supported at this time.
  2392. """
  2393. if encoding or errors:
  2394. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  2395. else:
  2396. inst = super().__new__(cls, object)
  2397. inst.name = name
  2398. inst.path = path
  2399. inst.max_age = max_age
  2400. inst.domain = domain
  2401. inst.secure = secure
  2402. inst.same_site = same_site
  2403. return inst
  2404. class LocalStorage(ClientStorageBase, str):
  2405. """Represents a state Var that is stored in localStorage in the browser."""
  2406. name: str | None
  2407. sync: bool = False
  2408. def __new__(
  2409. cls,
  2410. object: Any = "",
  2411. encoding: str | None = None,
  2412. errors: str | None = None,
  2413. /,
  2414. name: str | None = None,
  2415. sync: bool = False,
  2416. ) -> "LocalStorage":
  2417. """Create a client-side localStorage (str).
  2418. Args:
  2419. object: The initial object.
  2420. encoding: The encoding to use.
  2421. errors: The error handling scheme to use.
  2422. name: The name of the storage key on the client side.
  2423. sync: Whether changes should be propagated to other tabs.
  2424. Returns:
  2425. The client-side localStorage object.
  2426. """
  2427. if encoding or errors:
  2428. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  2429. else:
  2430. inst = super().__new__(cls, object)
  2431. inst.name = name
  2432. inst.sync = sync
  2433. return inst
  2434. class SessionStorage(ClientStorageBase, str):
  2435. """Represents a state Var that is stored in sessionStorage in the browser."""
  2436. name: str | None
  2437. def __new__(
  2438. cls,
  2439. object: Any = "",
  2440. encoding: str | None = None,
  2441. errors: str | None = None,
  2442. /,
  2443. name: str | None = None,
  2444. ) -> "SessionStorage":
  2445. """Create a client-side sessionStorage (str).
  2446. Args:
  2447. object: The initial object.
  2448. encoding: The encoding to use.
  2449. errors: The error handling scheme to use
  2450. name: The name of the storage on the client side
  2451. Returns:
  2452. The client-side sessionStorage object.
  2453. """
  2454. if encoding or errors:
  2455. inst = super().__new__(cls, object, encoding or "utf-8", errors or "strict")
  2456. else:
  2457. inst = super().__new__(cls, object)
  2458. inst.name = name
  2459. return inst
  2460. class MutableProxy(wrapt.ObjectProxy):
  2461. """A proxy for a mutable object that tracks changes."""
  2462. # Methods on wrapped objects which should mark the state as dirty.
  2463. __mark_dirty_attrs__ = set(
  2464. [
  2465. "add",
  2466. "append",
  2467. "clear",
  2468. "difference_update",
  2469. "discard",
  2470. "extend",
  2471. "insert",
  2472. "intersection_update",
  2473. "pop",
  2474. "popitem",
  2475. "remove",
  2476. "reverse",
  2477. "setdefault",
  2478. "sort",
  2479. "symmetric_difference_update",
  2480. "update",
  2481. ]
  2482. )
  2483. # Methods on wrapped objects might return mutable objects that should be tracked.
  2484. __wrap_mutable_attrs__ = set(
  2485. [
  2486. "get",
  2487. "setdefault",
  2488. ]
  2489. )
  2490. # These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
  2491. __never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
  2492. pydantic.BaseModel.__dict__
  2493. )
  2494. __mutable_types__ = (list, dict, set, Base, DeclarativeBase)
  2495. def __init__(self, wrapped: Any, state: BaseState, field_name: str):
  2496. """Create a proxy for a mutable object that tracks changes.
  2497. Args:
  2498. wrapped: The object to proxy.
  2499. state: The state to mark dirty when the object is changed.
  2500. field_name: The name of the field on the state associated with the
  2501. wrapped object.
  2502. """
  2503. super().__init__(wrapped)
  2504. self._self_state = state
  2505. self._self_field_name = field_name
  2506. def _mark_dirty(
  2507. self,
  2508. wrapped=None,
  2509. instance=None,
  2510. args=tuple(),
  2511. kwargs=None,
  2512. ) -> Any:
  2513. """Mark the state as dirty, then call a wrapped function.
  2514. Intended for use with `FunctionWrapper` from the `wrapt` library.
  2515. Args:
  2516. wrapped: The wrapped function.
  2517. instance: The instance of the wrapped function.
  2518. args: The args for the wrapped function.
  2519. kwargs: The kwargs for the wrapped function.
  2520. Returns:
  2521. The result of the wrapped function.
  2522. """
  2523. self._self_state.dirty_vars.add(self._self_field_name)
  2524. self._self_state._mark_dirty()
  2525. if wrapped is not None:
  2526. return wrapped(*args, **(kwargs or {}))
  2527. def _wrap_recursive(self, value: Any) -> Any:
  2528. """Wrap a value recursively if it is mutable.
  2529. Args:
  2530. value: The value to wrap.
  2531. Returns:
  2532. The wrapped value.
  2533. """
  2534. # Recursively wrap mutable types, but do not re-wrap MutableProxy instances.
  2535. if isinstance(value, self.__mutable_types__) and not isinstance(
  2536. value, MutableProxy
  2537. ):
  2538. return type(self)(
  2539. wrapped=value,
  2540. state=self._self_state,
  2541. field_name=self._self_field_name,
  2542. )
  2543. return value
  2544. def _wrap_recursive_decorator(self, wrapped, instance, args, kwargs) -> Any:
  2545. """Wrap a function that returns a possibly mutable value.
  2546. Intended for use with `FunctionWrapper` from the `wrapt` library.
  2547. Args:
  2548. wrapped: The wrapped function.
  2549. instance: The instance of the wrapped function.
  2550. args: The args for the wrapped function.
  2551. kwargs: The kwargs for the wrapped function.
  2552. Returns:
  2553. The result of the wrapped function (possibly wrapped in a MutableProxy).
  2554. """
  2555. return self._wrap_recursive(wrapped(*args, **kwargs))
  2556. def __getattr__(self, __name: str) -> Any:
  2557. """Get the attribute on the proxied object and return a proxy if mutable.
  2558. Args:
  2559. __name: The name of the attribute.
  2560. Returns:
  2561. The attribute value.
  2562. """
  2563. value = super().__getattr__(__name)
  2564. if callable(value):
  2565. if __name in self.__mark_dirty_attrs__:
  2566. # Wrap special callables, like "append", which should mark state dirty.
  2567. value = wrapt.FunctionWrapper(value, self._mark_dirty)
  2568. if __name in self.__wrap_mutable_attrs__:
  2569. # Wrap methods that may return mutable objects tied to the state.
  2570. value = wrapt.FunctionWrapper(
  2571. value,
  2572. self._wrap_recursive_decorator,
  2573. )
  2574. if (
  2575. isinstance(self.__wrapped__, Base)
  2576. and __name not in self.__never_wrap_base_attrs__
  2577. and hasattr(value, "__func__")
  2578. ):
  2579. # Wrap methods called on Base subclasses, which might do _anything_
  2580. return wrapt.FunctionWrapper(
  2581. functools.partial(value.__func__, self),
  2582. self._wrap_recursive_decorator,
  2583. )
  2584. if isinstance(value, self.__mutable_types__) and __name not in (
  2585. "__wrapped__",
  2586. "_self_state",
  2587. ):
  2588. # Recursively wrap mutable attribute values retrieved through this proxy.
  2589. return self._wrap_recursive(value)
  2590. return value
  2591. def __getitem__(self, key) -> Any:
  2592. """Get the item on the proxied object and return a proxy if mutable.
  2593. Args:
  2594. key: The key of the item.
  2595. Returns:
  2596. The item value.
  2597. """
  2598. value = super().__getitem__(key)
  2599. # Recursively wrap mutable items retrieved through this proxy.
  2600. return self._wrap_recursive(value)
  2601. def __iter__(self) -> Any:
  2602. """Iterate over the proxied object and return a proxy if mutable.
  2603. Yields:
  2604. Each item value (possibly wrapped in MutableProxy).
  2605. """
  2606. for value in super().__iter__():
  2607. # Recursively wrap mutable items retrieved through this proxy.
  2608. yield self._wrap_recursive(value)
  2609. def __delattr__(self, name):
  2610. """Delete the attribute on the proxied object and mark state dirty.
  2611. Args:
  2612. name: The name of the attribute.
  2613. """
  2614. self._mark_dirty(super().__delattr__, args=(name,))
  2615. def __delitem__(self, key):
  2616. """Delete the item on the proxied object and mark state dirty.
  2617. Args:
  2618. key: The key of the item.
  2619. """
  2620. self._mark_dirty(super().__delitem__, args=(key,))
  2621. def __setitem__(self, key, value):
  2622. """Set the item on the proxied object and mark state dirty.
  2623. Args:
  2624. key: The key of the item.
  2625. value: The value of the item.
  2626. """
  2627. self._mark_dirty(super().__setitem__, args=(key, value))
  2628. def __setattr__(self, name, value):
  2629. """Set the attribute on the proxied object and mark state dirty.
  2630. If the attribute starts with "_self_", then the state is NOT marked
  2631. dirty as these are internal proxy attributes.
  2632. Args:
  2633. name: The name of the attribute.
  2634. value: The value of the attribute.
  2635. """
  2636. if name.startswith("_self_"):
  2637. # Special case attributes of the proxy itself, not applied to the wrapped object.
  2638. super().__setattr__(name, value)
  2639. return
  2640. self._mark_dirty(super().__setattr__, args=(name, value))
  2641. def __copy__(self) -> Any:
  2642. """Return a copy of the proxy.
  2643. Returns:
  2644. A copy of the wrapped object, unconnected to the proxy.
  2645. """
  2646. return copy.copy(self.__wrapped__)
  2647. def __deepcopy__(self, memo=None) -> Any:
  2648. """Return a deepcopy of the proxy.
  2649. Args:
  2650. memo: The memo dict to use for the deepcopy.
  2651. Returns:
  2652. A deepcopy of the wrapped object, unconnected to the proxy.
  2653. """
  2654. return copy.deepcopy(self.__wrapped__, memo=memo)
  2655. def __reduce_ex__(self, protocol_version):
  2656. """Get the state for redis serialization.
  2657. This method is called by cloudpickle to serialize the object.
  2658. It explicitly serializes the wrapped object, stripping off the mutable proxy.
  2659. Args:
  2660. protocol_version: The protocol version.
  2661. Returns:
  2662. Tuple of (wrapped class, empty args, class __getstate__)
  2663. """
  2664. return self.__wrapped__.__reduce_ex__(protocol_version)
  2665. @serializer
  2666. def serialize_mutable_proxy(mp: MutableProxy) -> SerializedType:
  2667. """Serialize the wrapped value of a MutableProxy.
  2668. Args:
  2669. mp: The MutableProxy to serialize.
  2670. Returns:
  2671. The serialized wrapped object.
  2672. Raises:
  2673. ValueError: when the wrapped object is not serializable.
  2674. """
  2675. value = serialize(mp.__wrapped__)
  2676. if value is None:
  2677. raise ValueError(f"Cannot serialize {type(mp.__wrapped__)}")
  2678. return value
  2679. class ImmutableMutableProxy(MutableProxy):
  2680. """A proxy for a mutable object that tracks changes.
  2681. This wrapper comes from StateProxy, and will raise an exception if an attempt is made
  2682. to modify the wrapped object when the StateProxy is immutable.
  2683. """
  2684. def _mark_dirty(
  2685. self,
  2686. wrapped=None,
  2687. instance=None,
  2688. args=tuple(),
  2689. kwargs=None,
  2690. ) -> Any:
  2691. """Raise an exception when an attempt is made to modify the object.
  2692. Intended for use with `FunctionWrapper` from the `wrapt` library.
  2693. Args:
  2694. wrapped: The wrapped function.
  2695. instance: The instance of the wrapped function.
  2696. args: The args for the wrapped function.
  2697. kwargs: The kwargs for the wrapped function.
  2698. Returns:
  2699. The result of the wrapped function.
  2700. Raises:
  2701. ImmutableStateError: if the StateProxy is not mutable.
  2702. """
  2703. if not self._self_state._is_mutable():
  2704. raise ImmutableStateError(
  2705. "Background task StateProxy is immutable outside of a context "
  2706. "manager. Use `async with self` to modify state."
  2707. )
  2708. return super()._mark_dirty(
  2709. wrapped=wrapped, instance=instance, args=args, kwargs=kwargs
  2710. )
  2711. def code_uses_state_contexts(javascript_code: str) -> bool:
  2712. """Check if the rendered Javascript uses state contexts.
  2713. Args:
  2714. javascript_code: The Javascript code to check.
  2715. Returns:
  2716. True if the code attempts to access a member of StateContexts.
  2717. """
  2718. return bool("useContext(StateContexts" in javascript_code)
  2719. def reload_state_module(
  2720. module: str,
  2721. state: Type[BaseState] = State,
  2722. ) -> None:
  2723. """Reset rx.State subclasses to avoid conflict when reloading.
  2724. Args:
  2725. module: The module to reload.
  2726. state: Recursive argument for the state class to reload.
  2727. """
  2728. for subclass in tuple(state.class_subclasses):
  2729. reload_state_module(module=module, state=subclass)
  2730. if subclass.__module__ == module and module is not None:
  2731. state.class_subclasses.remove(subclass)
  2732. state._always_dirty_substates.discard(subclass.get_name())
  2733. state._init_var_dependency_dicts()
  2734. state.get_class_substate.cache_clear()