app.py 59 KB

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