state.py 124 KB

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