app.py 63 KB

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