app.py 60 KB

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