app.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. """The main Reflex app."""
  2. from __future__ import annotations
  3. import asyncio
  4. import concurrent.futures
  5. import contextlib
  6. import copy
  7. import dataclasses
  8. import functools
  9. import inspect
  10. import json
  11. import multiprocessing
  12. import platform
  13. import sys
  14. import tempfile
  15. import traceback
  16. from datetime import datetime
  17. from pathlib import Path
  18. from types import SimpleNamespace
  19. from typing import (
  20. TYPE_CHECKING,
  21. Any,
  22. AsyncIterator,
  23. Callable,
  24. Coroutine,
  25. Dict,
  26. Generic,
  27. List,
  28. MutableMapping,
  29. Optional,
  30. Sequence,
  31. Set,
  32. Type,
  33. Union,
  34. get_args,
  35. get_type_hints,
  36. )
  37. from fastapi import FastAPI, HTTPException, Request, UploadFile
  38. from fastapi.middleware import cors
  39. from fastapi.responses import JSONResponse, StreamingResponse
  40. from fastapi.staticfiles import StaticFiles
  41. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  42. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  43. from starlette_admin.contrib.sqla.admin import Admin
  44. from starlette_admin.contrib.sqla.view import ModelView
  45. from reflex import constants
  46. from reflex.admin import AdminDash
  47. from reflex.app_mixins import AppMixin, LifespanMixin, MiddlewareMixin
  48. from reflex.compiler import compiler
  49. from reflex.compiler import utils as compiler_utils
  50. from reflex.compiler.compiler import ExecutorSafeFunctions, compile_theme
  51. from reflex.components.base.app_wrap import AppWrap
  52. from reflex.components.base.error_boundary import ErrorBoundary
  53. from reflex.components.base.fragment import Fragment
  54. from reflex.components.base.strict_mode import StrictMode
  55. from reflex.components.component import (
  56. Component,
  57. ComponentStyle,
  58. evaluate_style_namespaces,
  59. )
  60. from reflex.components.core.banner import (
  61. backend_disabled,
  62. connection_pulser,
  63. connection_toaster,
  64. )
  65. from reflex.components.core.breakpoints import set_breakpoints
  66. from reflex.components.core.client_side_routing import (
  67. Default404Page,
  68. wait_for_client_redirect,
  69. )
  70. from reflex.components.core.sticky import sticky
  71. from reflex.components.core.upload import Upload, get_upload_dir
  72. from reflex.components.radix import themes
  73. from reflex.config import environment, get_config
  74. from reflex.event import (
  75. _EVENT_FIELDS,
  76. BASE_STATE,
  77. Event,
  78. EventHandler,
  79. EventSpec,
  80. EventType,
  81. IndividualEventType,
  82. get_hydrate_event,
  83. window_alert,
  84. )
  85. from reflex.model import Model, get_db_status
  86. from reflex.page import DECORATED_PAGES
  87. from reflex.route import (
  88. get_route_args,
  89. replace_brackets_with_keywords,
  90. verify_route_validity,
  91. )
  92. from reflex.state import (
  93. BaseState,
  94. RouterData,
  95. State,
  96. StateManager,
  97. StateUpdate,
  98. _substate_key,
  99. code_uses_state_contexts,
  100. )
  101. from reflex.utils import codespaces, console, exceptions, format, prerequisites, types
  102. from reflex.utils.exec import is_prod_mode, is_testing_env
  103. from reflex.utils.imports import ImportVar
  104. if TYPE_CHECKING:
  105. from reflex.vars import Var
  106. # Define custom types.
  107. ComponentCallable = Callable[[], Component]
  108. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  109. def default_frontend_exception_handler(exception: Exception) -> None:
  110. """Default frontend exception handler function.
  111. Args:
  112. exception: The exception.
  113. """
  114. console.error(f"[Reflex Frontend Exception]\n {exception}\n")
  115. def default_backend_exception_handler(exception: Exception) -> EventSpec:
  116. """Default backend exception handler function.
  117. Args:
  118. exception: The exception.
  119. Returns:
  120. EventSpec: The window alert event.
  121. """
  122. from reflex.components.sonner.toast import Toaster, toast
  123. error = traceback.format_exc()
  124. console.error(f"[Reflex Backend Exception]\n {error}\n")
  125. error_message = (
  126. ["Contact the website administrator."]
  127. if is_prod_mode()
  128. else [f"{type(exception).__name__}: {exception}.", "See logs for details."]
  129. )
  130. if Toaster.is_used:
  131. return toast(
  132. "An error occurred.",
  133. level="error",
  134. description="<br/>".join(error_message),
  135. position="top-center",
  136. id="backend_error",
  137. style={"width": "500px"},
  138. )
  139. else:
  140. error_message.insert(0, "An error occurred.")
  141. return window_alert("\n".join(error_message))
  142. def default_overlay_component() -> Component:
  143. """Default overlay_component attribute for App.
  144. Returns:
  145. The default overlay_component, which is a connection_modal.
  146. """
  147. config = get_config()
  148. return Fragment.create(
  149. connection_pulser(),
  150. connection_toaster(),
  151. *([backend_disabled()] if config.is_reflex_cloud else []),
  152. *codespaces.codespaces_auto_redirect(),
  153. )
  154. def default_error_boundary(*children: Component) -> Component:
  155. """Default error_boundary attribute for App.
  156. Args:
  157. *children: The children to render in the error boundary.
  158. Returns:
  159. The default error_boundary, which is an ErrorBoundary.
  160. """
  161. return ErrorBoundary.create(*children)
  162. class OverlayFragment(Fragment):
  163. """Alias for Fragment, used to wrap the overlay_component."""
  164. pass
  165. @dataclasses.dataclass(
  166. frozen=True,
  167. )
  168. class UnevaluatedPage(Generic[BASE_STATE]):
  169. """An uncompiled page."""
  170. component: Union[Component, ComponentCallable]
  171. route: str
  172. title: Union[Var, str, None]
  173. description: Union[Var, str, None]
  174. image: str
  175. on_load: Union[EventType[[], BASE_STATE], None]
  176. meta: List[Dict[str, str]]
  177. @dataclasses.dataclass()
  178. class App(MiddlewareMixin, LifespanMixin):
  179. """The main Reflex app that encapsulates the backend and frontend.
  180. Every Reflex app needs an app defined in its main module.
  181. ```python
  182. # app.py
  183. import reflex as rx
  184. # Define state and pages
  185. ...
  186. app = rx.App(
  187. # Set global level style.
  188. style={...},
  189. # Set the top level theme.
  190. theme=rx.theme(accent_color="blue"),
  191. )
  192. ```
  193. """
  194. # The global [theme](https://reflex.dev/docs/styling/theming/#theme) for the entire app.
  195. theme: Optional[Component] = dataclasses.field(
  196. default_factory=lambda: themes.theme(accent_color="blue")
  197. )
  198. # The [global style](https://reflex.dev/docs/styling/overview/#global-styles}) for the app.
  199. style: ComponentStyle = dataclasses.field(default_factory=dict)
  200. # A list of URLs to [stylesheets](https://reflex.dev/docs/styling/custom-stylesheets/) to include in the app.
  201. stylesheets: List[str] = dataclasses.field(default_factory=list)
  202. # A component that is present on every page (defaults to the Connection Error banner).
  203. overlay_component: Optional[Union[Component, ComponentCallable]] = (
  204. dataclasses.field(default_factory=default_overlay_component)
  205. )
  206. # Error boundary component to wrap the app with.
  207. error_boundary: Optional[ComponentCallable] = default_error_boundary
  208. # Components to add to the head of every page.
  209. head_components: List[Component] = dataclasses.field(default_factory=list)
  210. # The Socket.IO AsyncServer instance.
  211. sio: Optional[AsyncServer] = None
  212. # The language to add to the html root tag of every page.
  213. html_lang: Optional[str] = None
  214. # Attributes to add to the html root tag of every page.
  215. html_custom_attrs: Optional[Dict[str, str]] = None
  216. # A map from a route to an unevaluated page.
  217. _unevaluated_pages: Dict[str, UnevaluatedPage] = dataclasses.field(
  218. default_factory=dict
  219. )
  220. # A map from a page route to the component to render. Users should use `add_page`.
  221. _pages: Dict[str, Component] = dataclasses.field(default_factory=dict)
  222. # The backend API object.
  223. _api: FastAPI | None = None
  224. # The state class to use for the app.
  225. _state: Optional[Type[BaseState]] = None
  226. # Class to manage many client states.
  227. _state_manager: Optional[StateManager] = None
  228. # Mapping from a route to event handlers to trigger when the page loads.
  229. _load_events: Dict[str, List[IndividualEventType[[], Any]]] = dataclasses.field(
  230. default_factory=dict
  231. )
  232. # Admin dashboard to view and manage the database.
  233. admin_dash: Optional[AdminDash] = None
  234. # The async server name space.
  235. _event_namespace: Optional[EventNamespace] = None
  236. # Background tasks that are currently running.
  237. _background_tasks: Set[asyncio.Task] = dataclasses.field(default_factory=set)
  238. # Frontend Error Handler Function
  239. frontend_exception_handler: Callable[[Exception], None] = (
  240. default_frontend_exception_handler
  241. )
  242. # Backend Error Handler Function
  243. backend_exception_handler: Callable[
  244. [Exception], Union[EventSpec, List[EventSpec], None]
  245. ] = default_backend_exception_handler
  246. @property
  247. def api(self) -> FastAPI | None:
  248. """Get the backend api.
  249. Returns:
  250. The backend api.
  251. """
  252. return self._api
  253. @property
  254. def event_namespace(self) -> EventNamespace | None:
  255. """Get the event namespace.
  256. Returns:
  257. The event namespace.
  258. """
  259. return self._event_namespace
  260. def __post_init__(self):
  261. """Initialize the app.
  262. Raises:
  263. ValueError: If the event namespace is not provided in the config.
  264. Also, if there are multiple client subclasses of rx.BaseState(Subclasses of rx.BaseState should consist
  265. of the DefaultState and the client app state).
  266. """
  267. # Special case to allow test cases have multiple subclasses of rx.BaseState.
  268. if not is_testing_env() and BaseState.__subclasses__() != [State]:
  269. # Only rx.State is allowed as Base State subclass.
  270. raise ValueError(
  271. "rx.BaseState cannot be subclassed directly. Use rx.State instead"
  272. )
  273. if "breakpoints" in self.style:
  274. set_breakpoints(self.style.pop("breakpoints"))
  275. # Set up the API.
  276. self._api = FastAPI(lifespan=self._run_lifespan_tasks)
  277. self._add_cors()
  278. self._add_default_endpoints()
  279. for clz in App.__mro__:
  280. if clz == App:
  281. continue
  282. if issubclass(clz, AppMixin):
  283. clz._init_mixin(self)
  284. self._setup_state()
  285. # Set up the admin dash.
  286. self._setup_admin_dash()
  287. if sys.platform == "win32" and not is_prod_mode():
  288. # Hack to fix Windows hot reload issue.
  289. from reflex.utils.compat import windows_hot_reload_lifespan_hack
  290. self.register_lifespan_task(windows_hot_reload_lifespan_hack)
  291. def _enable_state(self) -> None:
  292. """Enable state for the app."""
  293. if not self._state:
  294. self._state = State
  295. self._setup_state()
  296. def _setup_state(self) -> None:
  297. """Set up the state for the app.
  298. Raises:
  299. RuntimeError: If the socket server is invalid.
  300. """
  301. if not self._state:
  302. return
  303. config = get_config()
  304. # Set up the state manager.
  305. self._state_manager = StateManager.create(state=self._state)
  306. # Set up the Socket.IO AsyncServer.
  307. if not self.sio:
  308. self.sio = AsyncServer(
  309. async_mode="asgi",
  310. cors_allowed_origins=(
  311. "*"
  312. if config.cors_allowed_origins == ["*"]
  313. else config.cors_allowed_origins
  314. ),
  315. cors_credentials=True,
  316. max_http_buffer_size=constants.POLLING_MAX_HTTP_BUFFER_SIZE,
  317. ping_interval=constants.Ping.INTERVAL,
  318. ping_timeout=constants.Ping.TIMEOUT,
  319. json=SimpleNamespace(
  320. dumps=staticmethod(format.json_dumps),
  321. loads=staticmethod(json.loads),
  322. ),
  323. transports=["websocket"],
  324. )
  325. elif getattr(self.sio, "async_mode", "") != "asgi":
  326. raise RuntimeError(
  327. f"Custom `sio` must use `async_mode='asgi'`, not '{self.sio.async_mode}'."
  328. )
  329. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  330. socket_app = ASGIApp(self.sio, socketio_path="")
  331. namespace = config.get_event_namespace()
  332. # Create the event namespace and attach the main app. Not related to any paths.
  333. self._event_namespace = EventNamespace(namespace, self)
  334. # Register the event namespace with the socket.
  335. self.sio.register_namespace(self.event_namespace)
  336. # Mount the socket app with the API.
  337. if self.api:
  338. class HeaderMiddleware:
  339. def __init__(self, app: ASGIApp):
  340. self.app = app
  341. async def __call__(
  342. self, scope: MutableMapping[str, Any], receive: Any, send: Callable
  343. ):
  344. original_send = send
  345. async def modified_send(message: dict):
  346. if message["type"] == "websocket.accept":
  347. if scope.get("subprotocols"):
  348. # The following *does* say "subprotocol" instead of "subprotocols", intentionally.
  349. message["subprotocol"] = scope["subprotocols"][0]
  350. headers = dict(message.get("headers", []))
  351. header_key = b"sec-websocket-protocol"
  352. if subprotocol := headers.get(header_key):
  353. message["headers"] = [
  354. *message.get("headers", []),
  355. (header_key, subprotocol),
  356. ]
  357. return await original_send(message)
  358. return await self.app(scope, receive, modified_send)
  359. socket_app_with_headers = HeaderMiddleware(socket_app)
  360. self.api.mount(str(constants.Endpoint.EVENT), socket_app_with_headers)
  361. # Check the exception handlers
  362. self._validate_exception_handlers()
  363. def __repr__(self) -> str:
  364. """Get the string representation of the app.
  365. Returns:
  366. The string representation of the app.
  367. """
  368. return f"<App state={self._state.__name__ if self._state else None}>"
  369. def __call__(self) -> FastAPI:
  370. """Run the backend api instance.
  371. Raises:
  372. ValueError: If the app has not been initialized.
  373. Returns:
  374. The backend api.
  375. """
  376. if not self.api:
  377. raise ValueError("The app has not been initialized.")
  378. return self.api
  379. def _add_default_endpoints(self):
  380. """Add default api endpoints (ping)."""
  381. # To test the server.
  382. if not self.api:
  383. return
  384. self.api.get(str(constants.Endpoint.PING))(ping)
  385. self.api.get(str(constants.Endpoint.HEALTH))(health)
  386. def _add_optional_endpoints(self):
  387. """Add optional api endpoints (_upload)."""
  388. if not self.api:
  389. return
  390. if Upload.is_used:
  391. # To upload files.
  392. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  393. # To access uploaded files.
  394. self.api.mount(
  395. str(constants.Endpoint.UPLOAD),
  396. StaticFiles(directory=get_upload_dir()),
  397. name="uploaded_files",
  398. )
  399. if codespaces.is_running_in_codespaces():
  400. self.api.get(str(constants.Endpoint.AUTH_CODESPACE))(
  401. codespaces.auth_codespace
  402. )
  403. def _add_cors(self):
  404. """Add CORS middleware to the app."""
  405. if not self.api:
  406. return
  407. self.api.add_middleware(
  408. cors.CORSMiddleware,
  409. allow_credentials=True,
  410. allow_methods=["*"],
  411. allow_headers=["*"],
  412. allow_origins=get_config().cors_allowed_origins,
  413. )
  414. @property
  415. def state_manager(self) -> StateManager:
  416. """Get the state manager.
  417. Returns:
  418. The initialized state manager.
  419. Raises:
  420. ValueError: if the state has not been initialized.
  421. """
  422. if self._state_manager is None:
  423. raise ValueError("The state manager has not been initialized.")
  424. return self._state_manager
  425. @staticmethod
  426. def _generate_component(component: Component | ComponentCallable) -> Component:
  427. """Generate a component from a callable.
  428. Args:
  429. component: The component function to call or Component to return as-is.
  430. Returns:
  431. The generated component.
  432. """
  433. return component if isinstance(component, Component) else component()
  434. def add_page(
  435. self,
  436. component: Component | ComponentCallable | None = None,
  437. route: str | None = None,
  438. title: str | Var | None = None,
  439. description: str | Var | None = None,
  440. image: str = constants.DefaultPage.IMAGE,
  441. on_load: EventType[[], BASE_STATE] | None = None,
  442. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  443. ):
  444. """Add a page to the app.
  445. If the component is a callable, by default the route is the name of the
  446. function. Otherwise, a route must be provided.
  447. Args:
  448. component: The component to display at the page.
  449. route: The route to display the component at.
  450. title: The title of the page.
  451. description: The description of the page.
  452. image: The image to display on the page.
  453. on_load: The event handler(s) that will be called each time the page load.
  454. meta: The metadata of the page.
  455. Raises:
  456. PageValueError: When the component is not set for a non-404 page.
  457. RouteValueError: When the specified route name already exists.
  458. """
  459. # If the route is not set, get it from the callable.
  460. if route is None:
  461. if not isinstance(component, Callable):
  462. raise exceptions.RouteValueError(
  463. "Route must be set if component is not a callable."
  464. )
  465. # Format the route.
  466. route = format.format_route(component.__name__)
  467. else:
  468. route = format.format_route(route, format_case=False)
  469. if route == constants.Page404.SLUG:
  470. if component is None:
  471. component = Default404Page.create()
  472. component = wait_for_client_redirect(self._generate_component(component))
  473. title = title or constants.Page404.TITLE
  474. description = description or constants.Page404.DESCRIPTION
  475. image = image or constants.Page404.IMAGE
  476. else:
  477. if component is None:
  478. raise exceptions.PageValueError(
  479. "Component must be set for a non-404 page."
  480. )
  481. # Check if the route given is valid
  482. verify_route_validity(route)
  483. if route in self._unevaluated_pages and environment.RELOAD_CONFIG.is_set():
  484. # when the app is reloaded(typically for app harness tests), we should maintain
  485. # the latest render function of a route.This applies typically to decorated pages
  486. # since they are only added when app._compile is called.
  487. self._unevaluated_pages.pop(route)
  488. if route in self._unevaluated_pages:
  489. route_name = (
  490. f"`{route}` or `/`"
  491. if route == constants.PageNames.INDEX_ROUTE
  492. else f"`{route}`"
  493. )
  494. raise exceptions.RouteValueError(
  495. f"Duplicate page route {route_name} already exists. Make sure you do not have two"
  496. f" pages with the same route"
  497. )
  498. # Setup dynamic args for the route.
  499. # this state assignment is only required for tests using the deprecated state kwarg for App
  500. state = self._state if self._state else State
  501. state.setup_dynamic_args(get_route_args(route))
  502. if on_load:
  503. self._load_events[route] = (
  504. on_load if isinstance(on_load, list) else [on_load]
  505. )
  506. self._unevaluated_pages[route] = UnevaluatedPage(
  507. component=component,
  508. route=route,
  509. title=title,
  510. description=description,
  511. image=image,
  512. on_load=on_load,
  513. meta=meta,
  514. )
  515. def _compile_page(self, route: str, save_page: bool = True):
  516. """Compile a page.
  517. Args:
  518. route: The route of the page to compile.
  519. save_page: If True, the compiled page is saved to self._pages.
  520. """
  521. component, enable_state = compiler.compile_unevaluated_page(
  522. route, self._unevaluated_pages[route], self._state, self.style, self.theme
  523. )
  524. if enable_state:
  525. self._enable_state()
  526. # Add the page.
  527. self._check_routes_conflict(route)
  528. if save_page:
  529. self._pages[route] = component
  530. def get_load_events(self, route: str) -> list[IndividualEventType[[], Any]]:
  531. """Get the load events for a route.
  532. Args:
  533. route: The route to get the load events for.
  534. Returns:
  535. The load events for the route.
  536. """
  537. route = route.lstrip("/")
  538. if route == "":
  539. route = constants.PageNames.INDEX_ROUTE
  540. return self._load_events.get(route, [])
  541. def _check_routes_conflict(self, new_route: str):
  542. """Verify if there is any conflict between the new route and any existing route.
  543. Based on conflicts that NextJS would throw if not intercepted.
  544. Raises:
  545. RouteValueError: exception showing which conflict exist with the route to be added
  546. Args:
  547. new_route: the route being newly added.
  548. """
  549. from reflex.utils.exceptions import RouteValueError
  550. if "[" not in new_route:
  551. return
  552. segments = (
  553. constants.RouteRegex.SINGLE_SEGMENT,
  554. constants.RouteRegex.DOUBLE_SEGMENT,
  555. constants.RouteRegex.SINGLE_CATCHALL_SEGMENT,
  556. constants.RouteRegex.DOUBLE_CATCHALL_SEGMENT,
  557. )
  558. for route in self._pages:
  559. replaced_route = replace_brackets_with_keywords(route)
  560. for rw, r, nr in zip(
  561. replaced_route.split("/"),
  562. route.split("/"),
  563. new_route.split("/"),
  564. strict=False,
  565. ):
  566. if rw in segments and r != nr:
  567. # If the slugs in the segments of both routes are not the same, then the route is invalid
  568. raise RouteValueError(
  569. f"You cannot use different slug names for the same dynamic path in {route} and {new_route} ('{r}' != '{nr}')"
  570. )
  571. elif rw not in segments and r != nr:
  572. # if the section being compared in both routes is not a dynamic segment(i.e not wrapped in brackets)
  573. # then we are guaranteed that the route is valid and there's no need checking the rest.
  574. # eg. /posts/[id]/info/[slug1] and /posts/[id]/info1/[slug1] is always going to be valid since
  575. # info1 will break away into its own tree.
  576. break
  577. def add_custom_404_page(
  578. self,
  579. component: Component | ComponentCallable | None = None,
  580. title: str = constants.Page404.TITLE,
  581. image: str = constants.Page404.IMAGE,
  582. description: str = constants.Page404.DESCRIPTION,
  583. on_load: EventType[[], BASE_STATE] | None = None,
  584. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  585. ):
  586. """Define a custom 404 page for any url having no match.
  587. If there is no page defined on 'index' route, add the 404 page to it.
  588. If there is no global catchall defined, add the 404 page with a catchall.
  589. Args:
  590. component: The component to display at the page.
  591. title: The title of the page.
  592. image: The image to display on the page.
  593. description: The description of the page.
  594. on_load: The event handler(s) that will be called each time the page load.
  595. meta: The metadata of the page.
  596. """
  597. console.deprecate(
  598. feature_name="App.add_custom_404_page",
  599. reason=f"Use app.add_page(component, route='/{constants.Page404.SLUG}') instead.",
  600. deprecation_version="0.6.7",
  601. removal_version="0.8.0",
  602. )
  603. self.add_page(
  604. component=component,
  605. route=constants.Page404.SLUG,
  606. title=title or constants.Page404.TITLE,
  607. image=image or constants.Page404.IMAGE,
  608. description=description or constants.Page404.DESCRIPTION,
  609. on_load=on_load,
  610. meta=meta,
  611. )
  612. def _setup_admin_dash(self):
  613. """Setup the admin dash."""
  614. # Get the admin dash.
  615. if not self.api:
  616. return
  617. admin_dash = self.admin_dash
  618. if admin_dash and admin_dash.models:
  619. # Build the admin dashboard
  620. admin = (
  621. admin_dash.admin
  622. if admin_dash.admin
  623. else Admin(
  624. engine=Model.get_db_engine(),
  625. title="Reflex Admin Dashboard",
  626. logo_url="https://reflex.dev/Reflex.svg",
  627. )
  628. )
  629. for model in admin_dash.models:
  630. view = admin_dash.view_overrides.get(model, ModelView)
  631. admin.add_view(view(model))
  632. admin.mount_to(self.api)
  633. def _get_frontend_packages(self, imports: Dict[str, set[ImportVar]]):
  634. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  635. Args:
  636. imports: A dictionary containing the imports used in the current page.
  637. Example:
  638. >>> _get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  639. """
  640. page_imports = {
  641. i
  642. for i, tags in imports.items()
  643. if i not in constants.PackageJson.DEPENDENCIES
  644. and i not in constants.PackageJson.DEV_DEPENDENCIES
  645. and not any(i.startswith(prefix) for prefix in ["/", "$/", ".", "next/"])
  646. and i != ""
  647. and any(tag.install for tag in tags)
  648. }
  649. frontend_packages = get_config().frontend_packages
  650. _frontend_packages = []
  651. for package in frontend_packages:
  652. if package in (get_config().tailwind or {}).get("plugins", []):
  653. console.warn(
  654. f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`"
  655. )
  656. continue
  657. if package in page_imports:
  658. console.warn(
  659. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  660. )
  661. continue
  662. _frontend_packages.append(package)
  663. page_imports.update(_frontend_packages)
  664. prerequisites.install_frontend_packages(page_imports, get_config())
  665. def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component:
  666. for component in tuple(app_wrappers.values()):
  667. app_wrappers.update(component._get_all_app_wrap_components())
  668. order = sorted(app_wrappers, key=lambda k: k[0], reverse=True)
  669. root = parent = copy.deepcopy(app_wrappers[order[0]])
  670. for key in order[1:]:
  671. child = copy.deepcopy(app_wrappers[key])
  672. parent.children.append(child)
  673. parent = child
  674. return root
  675. def _should_compile(self) -> bool:
  676. """Check if the app should be compiled.
  677. Returns:
  678. Whether the app should be compiled.
  679. """
  680. # Check the environment variable.
  681. if environment.REFLEX_SKIP_COMPILE.get():
  682. return False
  683. nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
  684. # Check the nocompile file.
  685. if nocompile.exists():
  686. # Delete the nocompile file
  687. nocompile.unlink()
  688. return False
  689. # By default, compile the app.
  690. return True
  691. def _add_overlay_to_component(self, component: Component) -> Component:
  692. if self.overlay_component is None:
  693. return component
  694. children = component.children
  695. overlay_component = self._generate_component(self.overlay_component)
  696. if children[0] == overlay_component:
  697. return component
  698. # recreate OverlayFragment with overlay_component as first child
  699. component = OverlayFragment.create(overlay_component, *children)
  700. return component
  701. def _setup_overlay_component(self):
  702. """If a State is not used and no overlay_component is specified, do not render the connection modal."""
  703. if self._state is None and self.overlay_component is default_overlay_component:
  704. self.overlay_component = None
  705. for k, component in self._pages.items():
  706. self._pages[k] = self._add_overlay_to_component(component)
  707. def _add_error_boundary_to_component(self, component: Component) -> Component:
  708. if self.error_boundary is None:
  709. return component
  710. component = self.error_boundary(*component.children)
  711. return component
  712. def _setup_error_boundary(self):
  713. """If a State is not used and no error_boundary is specified, do not render the error boundary."""
  714. if self._state is None and self.error_boundary is default_error_boundary:
  715. self.error_boundary = None
  716. for k, component in self._pages.items():
  717. # Skip the 404 page
  718. if k == constants.Page404.SLUG:
  719. continue
  720. self._pages[k] = self._add_error_boundary_to_component(component)
  721. def _setup_sticky_badge(self):
  722. """Add the sticky badge to the app."""
  723. for k, component in self._pages.items():
  724. # Would be nice to share single sticky_badge across all pages, but
  725. # it bungles the StatefulComponent compile step.
  726. sticky_badge = sticky()
  727. sticky_badge._add_style_recursive({})
  728. self._pages[k] = Fragment.create(sticky_badge, component)
  729. def _apply_decorated_pages(self):
  730. """Add @rx.page decorated pages to the app.
  731. This has to be done in the MainThread for py38 and py39 compatibility, so the
  732. decorated pages are added to the app before the app is compiled (in a thread)
  733. to workaround REF-2172.
  734. This can move back into `compile_` when py39 support is dropped.
  735. """
  736. # Add the @rx.page decorated pages to collect on_load events.
  737. for render, kwargs in DECORATED_PAGES[get_config().app_name]:
  738. self.add_page(render, **kwargs)
  739. def _validate_var_dependencies(
  740. self, state: Optional[Type[BaseState]] = None
  741. ) -> None:
  742. """Validate the dependencies of the vars in the app.
  743. Args:
  744. state: The state to validate the dependencies for.
  745. Raises:
  746. VarDependencyError: When a computed var has an invalid dependency.
  747. """
  748. if not self._state:
  749. return
  750. if not state:
  751. state = self._state
  752. for var in state.computed_vars.values():
  753. if not var._cache:
  754. continue
  755. deps = var._deps(objclass=state)
  756. for state_name, dep_set in deps.items():
  757. state_cls = (
  758. state.get_root_state().get_class_substate(state_name)
  759. if state_name != state.get_full_name()
  760. else state
  761. )
  762. for dep in dep_set:
  763. if dep not in state_cls.vars and dep not in state_cls.backend_vars:
  764. raise exceptions.VarDependencyError(
  765. f"ComputedVar {var._js_expr} on state {state.__name__} has an invalid dependency {state_name}.{dep}"
  766. )
  767. for substate in state.class_subclasses:
  768. self._validate_var_dependencies(substate)
  769. def _compile(self, export: bool = False):
  770. """Compile the app and output it to the pages folder.
  771. Args:
  772. export: Whether to compile the app for export.
  773. Raises:
  774. ReflexRuntimeError: When any page uses state, but no rx.State subclass is defined.
  775. """
  776. from reflex.utils.exceptions import ReflexRuntimeError
  777. self._pages = {}
  778. def get_compilation_time() -> str:
  779. return str(datetime.now().time()).split(".")[0]
  780. # Render a default 404 page if the user didn't supply one
  781. if constants.Page404.SLUG not in self._unevaluated_pages:
  782. self.add_page(route=constants.Page404.SLUG)
  783. # Fix up the style.
  784. self.style = evaluate_style_namespaces(self.style)
  785. # Add the app wrappers.
  786. app_wrappers: Dict[tuple[int, str], Component] = {
  787. # Default app wrap component renders {children}
  788. (0, "AppWrap"): AppWrap.create()
  789. }
  790. if self.theme is not None:
  791. # If a theme component was provided, wrap the app with it
  792. app_wrappers[(20, "Theme")] = self.theme
  793. # Get the env mode.
  794. config = get_config()
  795. if config.react_strict_mode:
  796. app_wrappers[(200, "StrictMode")] = StrictMode.create()
  797. should_compile = self._should_compile()
  798. if not should_compile:
  799. for route in self._unevaluated_pages:
  800. console.debug(f"Evaluating page: {route}")
  801. self._compile_page(route, save_page=should_compile)
  802. # Add the optional endpoints (_upload)
  803. self._add_optional_endpoints()
  804. return
  805. # Create a progress bar.
  806. progress = Progress(
  807. *Progress.get_default_columns()[:-1],
  808. MofNCompleteColumn(),
  809. TimeElapsedColumn(),
  810. )
  811. # try to be somewhat accurate - but still not 100%
  812. adhoc_steps_without_executor = 7
  813. fixed_pages_within_executor = 5
  814. progress.start()
  815. task = progress.add_task(
  816. f"[{get_compilation_time()}] Compiling:",
  817. total=len(self._pages)
  818. + (len(self._unevaluated_pages) * 2)
  819. + fixed_pages_within_executor
  820. + adhoc_steps_without_executor,
  821. )
  822. for route in self._unevaluated_pages:
  823. console.debug(f"Evaluating page: {route}")
  824. self._compile_page(route, save_page=should_compile)
  825. progress.advance(task)
  826. # Add the optional endpoints (_upload)
  827. self._add_optional_endpoints()
  828. self._validate_var_dependencies()
  829. self._setup_overlay_component()
  830. self._setup_error_boundary()
  831. if config.show_built_with_reflex:
  832. self._setup_sticky_badge()
  833. progress.advance(task)
  834. # Store the compile results.
  835. compile_results = []
  836. progress.advance(task)
  837. # Track imports and custom components found.
  838. all_imports = {}
  839. custom_components = set()
  840. # This has to happen before compiling stateful components as that
  841. # prevents recursive functions from reaching all components.
  842. for component in self._pages.values():
  843. # Add component._get_all_imports() to all_imports.
  844. all_imports.update(component._get_all_imports())
  845. # Add the app wrappers from this component.
  846. app_wrappers.update(component._get_all_app_wrap_components())
  847. # Add the custom components from the page to the set.
  848. custom_components |= component._get_all_custom_components()
  849. # Perform auto-memoization of stateful components.
  850. (
  851. stateful_components_path,
  852. stateful_components_code,
  853. page_components,
  854. ) = compiler.compile_stateful_components(self._pages.values())
  855. progress.advance(task)
  856. # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State.
  857. if code_uses_state_contexts(stateful_components_code) and self._state is None:
  858. raise ReflexRuntimeError(
  859. "To access rx.State in frontend components, at least one "
  860. "subclass of rx.State must be defined in the app."
  861. )
  862. compile_results.append((stateful_components_path, stateful_components_code))
  863. progress.advance(task)
  864. # Compile the root document before fork.
  865. compile_results.append(
  866. compiler.compile_document_root(
  867. self.head_components,
  868. html_lang=self.html_lang,
  869. html_custom_attrs=self.html_custom_attrs, # pyright: ignore [reportArgumentType]
  870. )
  871. )
  872. progress.advance(task)
  873. # Use a forking process pool, if possible. Much faster, especially for large sites.
  874. # Fallback to ThreadPoolExecutor as something that will always work.
  875. executor = None
  876. if (
  877. platform.system() in ("Linux", "Darwin")
  878. and (number_of_processes := environment.REFLEX_COMPILE_PROCESSES.get())
  879. is not None
  880. ):
  881. executor = concurrent.futures.ProcessPoolExecutor(
  882. max_workers=number_of_processes or None,
  883. mp_context=multiprocessing.get_context("fork"),
  884. )
  885. else:
  886. executor = concurrent.futures.ThreadPoolExecutor(
  887. max_workers=environment.REFLEX_COMPILE_THREADS.get() or None
  888. )
  889. for route, component in zip(self._pages, page_components, strict=True):
  890. ExecutorSafeFunctions.COMPONENTS[route] = component
  891. ExecutorSafeFunctions.STATE = self._state
  892. with executor:
  893. result_futures = []
  894. def _submit_work(fn: Callable, *args, **kwargs):
  895. f = executor.submit(fn, *args, **kwargs)
  896. result_futures.append(f)
  897. # Compile the pre-compiled pages.
  898. for route in self._pages:
  899. _submit_work(
  900. ExecutorSafeFunctions.compile_page,
  901. route,
  902. )
  903. # Compile the root stylesheet with base styles.
  904. _submit_work(compiler.compile_root_stylesheet, self.stylesheets)
  905. # Compile the theme.
  906. _submit_work(compile_theme, self.style)
  907. # Compile the Tailwind config.
  908. if config.tailwind is not None:
  909. config.tailwind["content"] = config.tailwind.get(
  910. "content", constants.Tailwind.CONTENT
  911. )
  912. _submit_work(compiler.compile_tailwind, config.tailwind)
  913. else:
  914. _submit_work(compiler.remove_tailwind_from_postcss)
  915. # Wait for all compilation tasks to complete.
  916. for future in concurrent.futures.as_completed(result_futures):
  917. compile_results.append(future.result())
  918. progress.advance(task)
  919. app_root = self._app_root(app_wrappers=app_wrappers)
  920. # Get imports from AppWrap components.
  921. all_imports.update(app_root._get_all_imports())
  922. progress.advance(task)
  923. # Compile the contexts.
  924. compile_results.append(
  925. compiler.compile_contexts(self._state, self.theme),
  926. )
  927. if self.theme is not None:
  928. # Fix #2992 by removing the top-level appearance prop
  929. self.theme.appearance = None
  930. progress.advance(task)
  931. # Compile the app root.
  932. compile_results.append(
  933. compiler.compile_app(app_root),
  934. )
  935. progress.advance(task)
  936. # Compile custom components.
  937. *custom_components_result, custom_components_imports = (
  938. compiler.compile_components(custom_components)
  939. )
  940. compile_results.append(custom_components_result)
  941. all_imports.update(custom_components_imports)
  942. progress.advance(task)
  943. progress.stop()
  944. # Install frontend packages.
  945. self._get_frontend_packages(all_imports)
  946. # Setup the next.config.js
  947. transpile_packages = [
  948. package
  949. for package, import_vars in all_imports.items()
  950. if any(import_var.transpile for import_var in import_vars)
  951. ]
  952. prerequisites.update_next_config(
  953. export=export,
  954. transpile_packages=transpile_packages,
  955. )
  956. if is_prod_mode():
  957. # Empty the .web pages directory.
  958. compiler.purge_web_pages_dir()
  959. else:
  960. # In dev mode, delete removed pages and update existing pages.
  961. keep_files = [Path(output_path) for output_path, _ in compile_results]
  962. for p in Path(prerequisites.get_web_dir() / constants.Dirs.PAGES).rglob(
  963. "*"
  964. ):
  965. if p.is_file() and p not in keep_files:
  966. # Remove pages that are no longer in the app.
  967. p.unlink()
  968. for output_path, code in compile_results:
  969. compiler_utils.write_page(output_path, code)
  970. @contextlib.asynccontextmanager
  971. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  972. """Modify the state out of band.
  973. Args:
  974. token: The token to modify the state for.
  975. Yields:
  976. The state to modify.
  977. Raises:
  978. RuntimeError: If the app has not been initialized yet.
  979. """
  980. if self.event_namespace is None:
  981. raise RuntimeError("App has not been initialized yet.")
  982. # Get exclusive access to the state.
  983. async with self.state_manager.modify_state(token) as state:
  984. # No other event handler can modify the state while in this context.
  985. yield state
  986. delta = state.get_delta()
  987. if delta:
  988. # When the state is modified reset dirty status and emit the delta to the frontend.
  989. state._clean()
  990. await self.event_namespace.emit_update(
  991. update=StateUpdate(delta=delta),
  992. sid=state.router.session.session_id,
  993. )
  994. def _process_background(
  995. self, state: BaseState, event: Event
  996. ) -> asyncio.Task | None:
  997. """Process an event in the background and emit updates as they arrive.
  998. Args:
  999. state: The state to process the event for.
  1000. event: The event to process.
  1001. Returns:
  1002. Task if the event was backgroundable, otherwise None
  1003. """
  1004. substate, handler = state._get_event_handler(event)
  1005. if not handler.is_background:
  1006. return None
  1007. async def _coro():
  1008. """Coroutine to process the event and emit updates inside an asyncio.Task.
  1009. Raises:
  1010. RuntimeError: If the app has not been initialized yet.
  1011. """
  1012. if self.event_namespace is None:
  1013. raise RuntimeError("App has not been initialized yet.")
  1014. # Process the event.
  1015. async for update in state._process_event(
  1016. handler=handler, state=substate, payload=event.payload
  1017. ):
  1018. # Postprocess the event.
  1019. update = await self._postprocess(state, event, update)
  1020. # Send the update to the client.
  1021. await self.event_namespace.emit_update(
  1022. update=update,
  1023. sid=state.router.session.session_id,
  1024. )
  1025. task = asyncio.create_task(_coro())
  1026. self._background_tasks.add(task)
  1027. # Clean up task from background_tasks set when complete.
  1028. task.add_done_callback(self._background_tasks.discard)
  1029. return task
  1030. def _validate_exception_handlers(self):
  1031. """Validate the custom event exception handlers for front- and backend.
  1032. Raises:
  1033. ValueError: If the custom exception handlers are invalid.
  1034. """
  1035. frontend_arg_spec = {
  1036. "exception": Exception,
  1037. }
  1038. backend_arg_spec = {
  1039. "exception": Exception,
  1040. }
  1041. for handler_domain, handler_fn, handler_spec in zip(
  1042. ["frontend", "backend"],
  1043. [self.frontend_exception_handler, self.backend_exception_handler],
  1044. [
  1045. frontend_arg_spec,
  1046. backend_arg_spec,
  1047. ],
  1048. strict=True,
  1049. ):
  1050. if hasattr(handler_fn, "__name__"):
  1051. _fn_name = handler_fn.__name__
  1052. else:
  1053. _fn_name = type(handler_fn).__name__
  1054. if isinstance(handler_fn, functools.partial):
  1055. raise ValueError(
  1056. f"Provided custom {handler_domain} exception handler `{_fn_name}` is a partial function. Please provide a named function instead."
  1057. )
  1058. if not callable(handler_fn):
  1059. raise ValueError(
  1060. f"Provided custom {handler_domain} exception handler `{_fn_name}` is not a function."
  1061. )
  1062. # Allow named functions only as lambda functions cannot be introspected
  1063. if _fn_name == "<lambda>":
  1064. raise ValueError(
  1065. f"Provided custom {handler_domain} exception handler `{_fn_name}` is a lambda function. Please use a named function instead."
  1066. )
  1067. # Check if the function has the necessary annotations and types in the right order
  1068. argspec = inspect.getfullargspec(handler_fn)
  1069. arg_annotations = {
  1070. k: eval(v) if isinstance(v, str) else v
  1071. for k, v in argspec.annotations.items()
  1072. if k not in ["args", "kwargs", "return"]
  1073. }
  1074. for required_arg_index, required_arg in enumerate(handler_spec):
  1075. if required_arg not in arg_annotations:
  1076. raise ValueError(
  1077. f"Provided custom {handler_domain} exception handler `{_fn_name}` does not take the required argument `{required_arg}`"
  1078. )
  1079. elif (
  1080. not list(arg_annotations.keys())[required_arg_index] == required_arg
  1081. ):
  1082. raise ValueError(
  1083. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong argument order."
  1084. f"Expected `{required_arg}` as the {required_arg_index + 1} argument but got `{list(arg_annotations.keys())[required_arg_index]}`"
  1085. )
  1086. if not issubclass(arg_annotations[required_arg], Exception):
  1087. raise ValueError(
  1088. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong type for {required_arg} argument."
  1089. f"Expected to be `Exception` but got `{arg_annotations[required_arg]}`"
  1090. )
  1091. # Check if the return type is valid for backend exception handler
  1092. if handler_domain == "backend":
  1093. sig = inspect.signature(self.backend_exception_handler)
  1094. return_type = (
  1095. eval(sig.return_annotation)
  1096. if isinstance(sig.return_annotation, str)
  1097. else sig.return_annotation
  1098. )
  1099. valid = bool(
  1100. return_type == EventSpec
  1101. or return_type == Optional[EventSpec]
  1102. or return_type == List[EventSpec]
  1103. or return_type == inspect.Signature.empty
  1104. or return_type is None
  1105. )
  1106. if not valid:
  1107. raise ValueError(
  1108. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong return type."
  1109. f"Expected `Union[EventSpec, List[EventSpec], None]` but got `{return_type}`"
  1110. )
  1111. async def process(
  1112. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  1113. ) -> AsyncIterator[StateUpdate]:
  1114. """Process an event.
  1115. Args:
  1116. app: The app to process the event for.
  1117. event: The event to process.
  1118. sid: The Socket.IO session id.
  1119. headers: The client headers.
  1120. client_ip: The client_ip.
  1121. Raises:
  1122. Exception: If a reflex specific error occurs during processing the event.
  1123. Yields:
  1124. The state updates after processing the event.
  1125. """
  1126. from reflex.utils import telemetry
  1127. try:
  1128. # Add request data to the state.
  1129. router_data = event.router_data
  1130. router_data.update(
  1131. {
  1132. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  1133. constants.RouteVar.CLIENT_TOKEN: event.token,
  1134. constants.RouteVar.SESSION_ID: sid,
  1135. constants.RouteVar.HEADERS: headers,
  1136. constants.RouteVar.CLIENT_IP: client_ip,
  1137. }
  1138. )
  1139. # Get the state for the session exclusively.
  1140. async with app.state_manager.modify_state(event.substate_token) as state:
  1141. # When this is a brand new instance of the state, signal the
  1142. # frontend to reload before processing it.
  1143. if (
  1144. not state.router_data
  1145. and event.name != get_hydrate_event(state)
  1146. and app.event_namespace is not None
  1147. ):
  1148. await asyncio.create_task(
  1149. app.event_namespace.emit(
  1150. "reload",
  1151. data=event,
  1152. to=sid,
  1153. )
  1154. )
  1155. return
  1156. # re-assign only when the value is different
  1157. if state.router_data != router_data:
  1158. # assignment will recurse into substates and force recalculation of
  1159. # dependent ComputedVar (dynamic route variables)
  1160. state.router_data = router_data
  1161. state.router = RouterData(router_data)
  1162. # Preprocess the event.
  1163. update = await app._preprocess(state, event)
  1164. # If there was an update, yield it.
  1165. if update is not None:
  1166. yield update
  1167. # Only process the event if there is no update.
  1168. else:
  1169. if app._process_background(state, event) is not None:
  1170. # `final=True` allows the frontend send more events immediately.
  1171. yield StateUpdate(final=True)
  1172. else:
  1173. # Process the event synchronously.
  1174. async for update in state._process(event):
  1175. # Postprocess the event.
  1176. update = await app._postprocess(state, event, update)
  1177. # Yield the update.
  1178. yield update
  1179. except Exception as ex:
  1180. telemetry.send_error(ex, context="backend")
  1181. app.backend_exception_handler(ex)
  1182. raise
  1183. async def ping() -> str:
  1184. """Test API endpoint.
  1185. Returns:
  1186. The response.
  1187. """
  1188. return "pong"
  1189. async def health() -> JSONResponse:
  1190. """Health check endpoint to assess the status of the database and Redis services.
  1191. Returns:
  1192. JSONResponse: A JSON object with the health status:
  1193. - "status" (bool): Overall health, True if all checks pass.
  1194. - "db" (bool or str): Database status - True, False, or "NA".
  1195. - "redis" (bool or str): Redis status - True, False, or "NA".
  1196. """
  1197. health_status = {"status": True}
  1198. status_code = 200
  1199. tasks = []
  1200. if prerequisites.check_db_used():
  1201. tasks.append(get_db_status())
  1202. if prerequisites.check_redis_used():
  1203. tasks.append(prerequisites.get_redis_status())
  1204. results = await asyncio.gather(*tasks)
  1205. for result in results:
  1206. health_status |= result
  1207. if "redis" in health_status and health_status["redis"] is None:
  1208. health_status["redis"] = False
  1209. if not all(health_status.values()):
  1210. health_status["status"] = False
  1211. status_code = 503
  1212. return JSONResponse(content=health_status, status_code=status_code)
  1213. def _handle_temporary_upload_file(
  1214. upload_file: UploadFile, temp_root: tempfile.TemporaryDirectory
  1215. ) -> tempfile.SpooledTemporaryFile:
  1216. temp_file = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, dir=temp_root.name)
  1217. temp_file.write(upload_file.file.read())
  1218. temp_file.seek(0)
  1219. return temp_file
  1220. async def temporary_upload_tree(
  1221. token: str, files: List[UploadFile]
  1222. ) -> AsyncIterator[Sequence[tempfile.SpooledTemporaryFile]]:
  1223. """Write the uploaded files to a temporary directory structure.
  1224. Args:
  1225. token: The token to use for the temporary directory.
  1226. files: The files to write to the temporary directory.
  1227. Yields:
  1228. A list of the temporary files.
  1229. """
  1230. upload_dir = get_upload_dir()
  1231. upload_dir.mkdir(parents=True, exist_ok=True)
  1232. temp_root = tempfile.TemporaryDirectory(prefix=token, dir=upload_dir)
  1233. temp_files = []
  1234. loop = asyncio.get_running_loop()
  1235. temp_files = [
  1236. await loop.run_in_executor(None, _handle_temporary_upload_file, f, temp_root)
  1237. for f in files
  1238. ]
  1239. try:
  1240. yield temp_files
  1241. finally:
  1242. def _cleanup():
  1243. for temp_file in temp_files:
  1244. temp_file.close()
  1245. temp_root.cleanup()
  1246. await loop.run_in_executor(None, _cleanup)
  1247. def upload(app: App):
  1248. """Upload a file.
  1249. Args:
  1250. app: The app to upload the file for.
  1251. Returns:
  1252. The upload function.
  1253. """
  1254. async def upload_file(request: Request, files: List[UploadFile]):
  1255. """Upload a file.
  1256. Args:
  1257. request: The FastAPI request object.
  1258. files: The file(s) to upload.
  1259. Returns:
  1260. StreamingResponse yielding newline-delimited JSON of StateUpdate
  1261. emitted by the upload handler.
  1262. Raises:
  1263. UploadValueError: if there are no args with supported annotation.
  1264. UploadTypeError: if a background task is used as the handler.
  1265. HTTPException: when the request does not include token / handler headers.
  1266. """
  1267. from reflex.utils.exceptions import UploadTypeError, UploadValueError
  1268. token = request.headers.get("reflex-client-token")
  1269. handler = request.headers.get("reflex-event-handler")
  1270. if not token or not handler:
  1271. raise HTTPException(
  1272. status_code=400,
  1273. detail="Missing reflex-client-token or reflex-event-handler header.",
  1274. )
  1275. # Get the state for the session.
  1276. substate_token = _substate_key(token, handler.rpartition(".")[0])
  1277. state = await app.state_manager.get_state(substate_token)
  1278. # get the current session ID
  1279. # get the current state(parent state/substate)
  1280. path = handler.split(".")[:-1]
  1281. current_state = state.get_substate(path)
  1282. handler_upload_param = ()
  1283. # get handler function
  1284. func = getattr(type(current_state), handler.split(".")[-1])
  1285. # check if there exists any handler args with annotation, List[UploadFile]
  1286. if isinstance(func, EventHandler):
  1287. if func.is_background:
  1288. raise UploadTypeError(
  1289. f"@rx.event(background=True) is not supported for upload handler `{handler}`.",
  1290. )
  1291. func = func.fn
  1292. if isinstance(func, functools.partial):
  1293. func = func.func
  1294. for k, v in get_type_hints(func).items():
  1295. if types.is_generic_alias(v) and types._issubclass(
  1296. get_args(v)[0],
  1297. UploadFile,
  1298. ):
  1299. handler_upload_param = (k, v)
  1300. break
  1301. if not handler_upload_param:
  1302. raise UploadValueError(
  1303. f"`{handler}` handler should have a parameter annotated as "
  1304. "List[rx.UploadFile]"
  1305. )
  1306. # Make a copy of the files as they are closed after the request.
  1307. # This behaviour changed from fastapi 0.103.0 to 0.103.1 as the
  1308. # AsyncExitStack was removed from the request scope and is now
  1309. # part of the routing function which closes this before the
  1310. # event is handled.
  1311. file_ctx = temporary_upload_tree(token, files)
  1312. temp_files = [
  1313. UploadFile(
  1314. file=tmp, # pyright: ignore[reportArgumentType]
  1315. filename=file.filename,
  1316. size=file.size,
  1317. headers=file.headers,
  1318. )
  1319. for file, tmp in zip(files, await anext(file_ctx), strict=True)
  1320. ]
  1321. event = Event(
  1322. token=token,
  1323. name=handler,
  1324. payload={handler_upload_param[0]: temp_files},
  1325. )
  1326. async def _ndjson_updates():
  1327. """Process the upload event, generating ndjson updates.
  1328. Yields:
  1329. Each state update as JSON followed by a new line.
  1330. """
  1331. # Process the event.
  1332. async with app.state_manager.modify_state(event.substate_token) as state:
  1333. async for update in state._process(event):
  1334. # Postprocess the event.
  1335. update = await app._postprocess(state, event, update)
  1336. yield update.json() + "\n"
  1337. # Clean up the temporary files.
  1338. async for _ in file_ctx:
  1339. pass
  1340. # Stream updates to client
  1341. return StreamingResponse(
  1342. _ndjson_updates(),
  1343. media_type="application/x-ndjson",
  1344. )
  1345. return upload_file
  1346. class EventNamespace(AsyncNamespace):
  1347. """The event namespace."""
  1348. # The application object.
  1349. app: App
  1350. # Keep a mapping between socket ID and client token.
  1351. token_to_sid: dict[str, str]
  1352. # Keep a mapping between client token and socket ID.
  1353. sid_to_token: dict[str, str]
  1354. def __init__(self, namespace: str, app: App):
  1355. """Initialize the event namespace.
  1356. Args:
  1357. namespace: The namespace.
  1358. app: The application object.
  1359. """
  1360. super().__init__(namespace)
  1361. self.token_to_sid = {}
  1362. self.sid_to_token = {}
  1363. self.app = app
  1364. def on_connect(self, sid: str, environ: dict):
  1365. """Event for when the websocket is connected.
  1366. Args:
  1367. sid: The Socket.IO session id.
  1368. environ: The request information, including HTTP headers.
  1369. """
  1370. subprotocol = environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL")
  1371. if subprotocol and subprotocol != constants.Reflex.VERSION:
  1372. console.warn(
  1373. f"Frontend version {subprotocol} for session {sid} does not match the backend version {constants.Reflex.VERSION}."
  1374. )
  1375. def on_disconnect(self, sid: str):
  1376. """Event for when the websocket disconnects.
  1377. Args:
  1378. sid: The Socket.IO session id.
  1379. """
  1380. disconnect_token = self.sid_to_token.pop(sid, None)
  1381. if disconnect_token:
  1382. self.token_to_sid.pop(disconnect_token, None)
  1383. async def emit_update(self, update: StateUpdate, sid: str) -> None:
  1384. """Emit an update to the client.
  1385. Args:
  1386. update: The state update to send.
  1387. sid: The Socket.IO session id.
  1388. """
  1389. # Creating a task prevents the update from being blocked behind other coroutines.
  1390. await asyncio.create_task(
  1391. self.emit(str(constants.SocketEvent.EVENT), update, to=sid)
  1392. )
  1393. async def on_event(self, sid: str, data: Any):
  1394. """Event for receiving front-end websocket events.
  1395. Raises:
  1396. RuntimeError: If the Socket.IO is badly initialized.
  1397. Args:
  1398. sid: The Socket.IO session id.
  1399. data: The event data.
  1400. Raises:
  1401. EventDeserializationError: If the event data is not a dictionary.
  1402. """
  1403. fields = data
  1404. if isinstance(fields, str):
  1405. console.warn(
  1406. "Received event data as a string. This generally should not happen and may indicate a bug."
  1407. f" Event data: {fields}"
  1408. )
  1409. try:
  1410. fields = json.loads(fields)
  1411. except json.JSONDecodeError as ex:
  1412. raise exceptions.EventDeserializationError(
  1413. f"Failed to deserialize event data: {fields}."
  1414. ) from ex
  1415. if not isinstance(fields, dict):
  1416. raise exceptions.EventDeserializationError(
  1417. f"Event data must be a dictionary, but received {fields} of type {type(fields)}."
  1418. )
  1419. try:
  1420. # Get the event.
  1421. event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS})
  1422. except (TypeError, ValueError) as ex:
  1423. raise exceptions.EventDeserializationError(
  1424. f"Failed to deserialize event data: {fields}."
  1425. ) from ex
  1426. self.token_to_sid[event.token] = sid
  1427. self.sid_to_token[sid] = event.token
  1428. # Get the event environment.
  1429. if self.app.sio is None:
  1430. raise RuntimeError("Socket.IO is not initialized.")
  1431. environ = self.app.sio.get_environ(sid, self.namespace)
  1432. if environ is None:
  1433. raise RuntimeError("Socket.IO environ is not initialized.")
  1434. # Get the client headers.
  1435. headers = {
  1436. k.decode("utf-8"): v.decode("utf-8")
  1437. for (k, v) in environ["asgi.scope"]["headers"]
  1438. }
  1439. # Get the client IP
  1440. try:
  1441. client_ip = environ["asgi.scope"]["client"][0]
  1442. except (KeyError, IndexError):
  1443. client_ip = environ.get("REMOTE_ADDR", "0.0.0.0")
  1444. # Process the events.
  1445. async for update in process(self.app, event, sid, headers, client_ip):
  1446. # Emit the update from processing the event.
  1447. await self.emit_update(update=update, sid=sid)
  1448. async def on_ping(self, sid: str):
  1449. """Event for testing the API endpoint.
  1450. Args:
  1451. sid: The Socket.IO session id.
  1452. """
  1453. # Emit the test event.
  1454. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)