app.py 68 KB

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