app.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 functools
  8. import os
  9. from typing import (
  10. Any,
  11. AsyncIterator,
  12. Callable,
  13. Coroutine,
  14. Dict,
  15. List,
  16. Optional,
  17. Set,
  18. Type,
  19. Union,
  20. get_args,
  21. get_type_hints,
  22. )
  23. from fastapi import FastAPI, HTTPException, Request, UploadFile
  24. from fastapi.middleware import cors
  25. from fastapi.responses import StreamingResponse
  26. from fastapi.staticfiles import StaticFiles
  27. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  28. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  29. from starlette_admin.contrib.sqla.admin import Admin
  30. from starlette_admin.contrib.sqla.view import ModelView
  31. from reflex import constants
  32. from reflex.admin import AdminDash
  33. from reflex.base import Base
  34. from reflex.compiler import compiler
  35. from reflex.compiler import utils as compiler_utils
  36. from reflex.components import connection_modal, connection_pulser
  37. from reflex.components.base.app_wrap import AppWrap
  38. from reflex.components.base.fragment import Fragment
  39. from reflex.components.component import (
  40. Component,
  41. ComponentStyle,
  42. evaluate_style_namespaces,
  43. )
  44. from reflex.components.core.client_side_routing import (
  45. Default404Page,
  46. wait_for_client_redirect,
  47. )
  48. from reflex.components.core.upload import Upload, get_upload_dir
  49. from reflex.components.radix import themes
  50. from reflex.config import get_config
  51. from reflex.event import Event, EventHandler, EventSpec
  52. from reflex.middleware import HydrateMiddleware, Middleware
  53. from reflex.model import Model
  54. from reflex.page import (
  55. DECORATED_PAGES,
  56. )
  57. from reflex.route import (
  58. catchall_in_route,
  59. catchall_prefix,
  60. get_route_args,
  61. verify_route_validity,
  62. )
  63. from reflex.state import (
  64. BaseState,
  65. RouterData,
  66. State,
  67. StateManager,
  68. StateUpdate,
  69. _substate_key,
  70. code_uses_state_contexts,
  71. )
  72. from reflex.utils import console, exceptions, format, prerequisites, types
  73. from reflex.utils.exec import is_testing_env
  74. from reflex.utils.imports import ImportVar
  75. # Define custom types.
  76. ComponentCallable = Callable[[], Component]
  77. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  78. def default_overlay_component() -> Component:
  79. """Default overlay_component attribute for App.
  80. Returns:
  81. The default overlay_component, which is a connection_modal.
  82. """
  83. return Fragment.create(connection_pulser(), connection_modal())
  84. class App(Base):
  85. """A Reflex application."""
  86. # A map from a page route to the component to render.
  87. pages: Dict[str, Component] = {}
  88. # A list of URLs to stylesheets to include in the app.
  89. stylesheets: List[str] = []
  90. # The backend API object.
  91. api: FastAPI = None # type: ignore
  92. # The Socket.IO AsyncServer.
  93. sio: Optional[AsyncServer] = None
  94. # The socket app.
  95. socket_app: Optional[ASGIApp] = None
  96. # The state class to use for the app.
  97. state: Optional[Type[BaseState]] = None
  98. # Class to manage many client states.
  99. _state_manager: Optional[StateManager] = None
  100. # The styling to apply to each component.
  101. style: ComponentStyle = {}
  102. # Middleware to add to the app.
  103. middleware: List[Middleware] = []
  104. # List of event handlers to trigger when a page loads.
  105. load_events: Dict[str, List[Union[EventHandler, EventSpec]]] = {}
  106. # Admin dashboard
  107. admin_dash: Optional[AdminDash] = None
  108. # The async server name space
  109. event_namespace: Optional[EventNamespace] = None
  110. # Components to add to the head of every page.
  111. head_components: List[Component] = []
  112. # The language to add to the html root tag of every page.
  113. html_lang: Optional[str] = None
  114. # Attributes to add to the html root tag of every page.
  115. html_custom_attrs: Optional[Dict[str, str]] = None
  116. # A component that is present on every page.
  117. overlay_component: Optional[
  118. Union[Component, ComponentCallable]
  119. ] = default_overlay_component
  120. # Background tasks that are currently running
  121. background_tasks: Set[asyncio.Task] = set()
  122. # The radix theme for the entire app
  123. theme: Optional[Component] = themes.theme(accent_color="blue")
  124. def __init__(self, *args, **kwargs):
  125. """Initialize the app.
  126. Args:
  127. *args: Args to initialize the app with.
  128. **kwargs: Kwargs to initialize the app with.
  129. Raises:
  130. ValueError: If the event namespace is not provided in the config.
  131. Also, if there are multiple client subclasses of rx.State(Subclasses of rx.State should consist
  132. of the DefaultState and the client app state).
  133. """
  134. if "connect_error_component" in kwargs:
  135. raise ValueError(
  136. "`connect_error_component` is deprecated, use `overlay_component` instead"
  137. )
  138. super().__init__(*args, **kwargs)
  139. state_subclasses = BaseState.__subclasses__()
  140. # Special case to allow test cases have multiple subclasses of rx.BaseState.
  141. if not is_testing_env():
  142. # Only one Base State class is allowed.
  143. if len(state_subclasses) > 1:
  144. raise ValueError(
  145. "rx.BaseState cannot be subclassed multiple times. use rx.State instead"
  146. )
  147. if "state" in kwargs:
  148. console.deprecate(
  149. feature_name="`state` argument for App()",
  150. reason="due to all `rx.State` subclasses being inferred.",
  151. deprecation_version="0.3.5",
  152. removal_version="0.5.0",
  153. )
  154. # 2 substates are built-in and not considered when determining if app is stateless.
  155. if len(State.class_subclasses) > 2:
  156. self.state = State
  157. # Get the config
  158. config = get_config()
  159. # Add middleware.
  160. self.middleware.append(HydrateMiddleware())
  161. # Set up the API.
  162. self.api = FastAPI()
  163. self.add_cors()
  164. self.add_default_endpoints()
  165. if self.state:
  166. # Set up the state manager.
  167. self._state_manager = StateManager.create(state=self.state)
  168. # Set up the Socket.IO AsyncServer.
  169. self.sio = AsyncServer(
  170. async_mode="asgi",
  171. cors_allowed_origins=(
  172. "*"
  173. if config.cors_allowed_origins == ["*"]
  174. else config.cors_allowed_origins
  175. ),
  176. cors_credentials=True,
  177. max_http_buffer_size=constants.POLLING_MAX_HTTP_BUFFER_SIZE,
  178. ping_interval=constants.Ping.INTERVAL,
  179. ping_timeout=constants.Ping.TIMEOUT,
  180. )
  181. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  182. self.socket_app = ASGIApp(self.sio, socketio_path="")
  183. namespace = config.get_event_namespace()
  184. if not namespace:
  185. raise ValueError("event namespace must be provided in the config.")
  186. # Create the event namespace and attach the main app. Not related to any paths.
  187. self.event_namespace = EventNamespace(namespace, self)
  188. # Register the event namespace with the socket.
  189. self.sio.register_namespace(self.event_namespace)
  190. # Mount the socket app with the API.
  191. self.api.mount(str(constants.Endpoint.EVENT), self.socket_app)
  192. # Set up the admin dash.
  193. self.setup_admin_dash()
  194. # If a State is not used and no overlay_component is specified, do not render the connection modal
  195. if self.state is None and self.overlay_component is default_overlay_component:
  196. self.overlay_component = None
  197. def __repr__(self) -> str:
  198. """Get the string representation of the app.
  199. Returns:
  200. The string representation of the app.
  201. """
  202. return f"<App state={self.state.__name__ if self.state else None}>"
  203. def __call__(self) -> FastAPI:
  204. """Run the backend api instance.
  205. Returns:
  206. The backend api.
  207. """
  208. return self.api
  209. def add_default_endpoints(self):
  210. """Add default api endpoints (ping)."""
  211. # To test the server.
  212. self.api.get(str(constants.Endpoint.PING))(ping)
  213. def add_optional_endpoints(self):
  214. """Add optional api endpoints (_upload)."""
  215. # To upload files.
  216. if Upload.is_used:
  217. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  218. # To access uploaded files.
  219. self.api.mount(
  220. str(constants.Endpoint.UPLOAD),
  221. StaticFiles(directory=get_upload_dir()),
  222. name="uploaded_files",
  223. )
  224. def add_cors(self):
  225. """Add CORS middleware to the app."""
  226. self.api.add_middleware(
  227. cors.CORSMiddleware,
  228. allow_credentials=True,
  229. allow_methods=["*"],
  230. allow_headers=["*"],
  231. allow_origins=["*"],
  232. )
  233. @property
  234. def state_manager(self) -> StateManager:
  235. """Get the state manager.
  236. Returns:
  237. The initialized state manager.
  238. Raises:
  239. ValueError: if the state has not been initialized.
  240. """
  241. if self._state_manager is None:
  242. raise ValueError("The state manager has not been initialized.")
  243. return self._state_manager
  244. async def preprocess(self, state: BaseState, event: Event) -> StateUpdate | None:
  245. """Preprocess the event.
  246. This is where middleware can modify the event before it is processed.
  247. Each middleware is called in the order it was added to the app.
  248. If a middleware returns an update, the event is not processed and the
  249. update is returned.
  250. Args:
  251. state: The state to preprocess.
  252. event: The event to preprocess.
  253. Returns:
  254. An optional state to return.
  255. """
  256. for middleware in self.middleware:
  257. if asyncio.iscoroutinefunction(middleware.preprocess):
  258. out = await middleware.preprocess(app=self, state=state, event=event) # type: ignore
  259. else:
  260. out = middleware.preprocess(app=self, state=state, event=event) # type: ignore
  261. if out is not None:
  262. return out # type: ignore
  263. async def postprocess(
  264. self, state: BaseState, event: Event, update: StateUpdate
  265. ) -> StateUpdate:
  266. """Postprocess the event.
  267. This is where middleware can modify the delta after it is processed.
  268. Each middleware is called in the order it was added to the app.
  269. Args:
  270. state: The state to postprocess.
  271. event: The event to postprocess.
  272. update: The current state update.
  273. Returns:
  274. The state update to return.
  275. """
  276. for middleware in self.middleware:
  277. if asyncio.iscoroutinefunction(middleware.postprocess):
  278. out = await middleware.postprocess(
  279. app=self, state=state, event=event, update=update # type: ignore
  280. )
  281. else:
  282. out = middleware.postprocess(
  283. app=self, state=state, event=event, update=update # type: ignore
  284. )
  285. if out is not None:
  286. return out # type: ignore
  287. return update
  288. def add_middleware(self, middleware: Middleware, index: int | None = None):
  289. """Add middleware to the app.
  290. Args:
  291. middleware: The middleware to add.
  292. index: The index to add the middleware at.
  293. """
  294. if index is None:
  295. self.middleware.append(middleware)
  296. else:
  297. self.middleware.insert(index, middleware)
  298. @staticmethod
  299. def _generate_component(component: Component | ComponentCallable) -> Component:
  300. """Generate a component from a callable.
  301. Args:
  302. component: The component function to call or Component to return as-is.
  303. Returns:
  304. The generated component.
  305. Raises:
  306. TypeError: When an invalid component function is passed.
  307. exceptions.MatchTypeError: If the return types of match cases in rx.match are different.
  308. """
  309. try:
  310. return component if isinstance(component, Component) else component()
  311. except exceptions.MatchTypeError:
  312. raise
  313. except TypeError as e:
  314. message = str(e)
  315. if "BaseVar" in message or "ComputedVar" in message:
  316. raise TypeError(
  317. "You may be trying to use an invalid Python function on a state var. "
  318. "When referencing a var inside your render code, only limited var operations are supported. "
  319. "See the var operation docs here: https://reflex.dev/docs/vars/var-operations/"
  320. ) from e
  321. raise e
  322. def add_page(
  323. self,
  324. component: Component | ComponentCallable,
  325. route: str | None = None,
  326. title: str = constants.DefaultPage.TITLE,
  327. description: str = constants.DefaultPage.DESCRIPTION,
  328. image: str = constants.DefaultPage.IMAGE,
  329. on_load: (
  330. EventHandler | EventSpec | list[EventHandler | EventSpec] | None
  331. ) = None,
  332. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  333. script_tags: list[Component] | None = None,
  334. ):
  335. """Add a page to the app.
  336. If the component is a callable, by default the route is the name of the
  337. function. Otherwise, a route must be provided.
  338. Args:
  339. component: The component to display at the page.
  340. route: The route to display the component at.
  341. title: The title of the page.
  342. description: The description of the page.
  343. image: The image to display on the page.
  344. on_load: The event handler(s) that will be called each time the page load.
  345. meta: The metadata of the page.
  346. script_tags: List of script tags to be added to component
  347. """
  348. # If the route is not set, get it from the callable.
  349. if route is None:
  350. assert isinstance(
  351. component, Callable
  352. ), "Route must be set if component is not a callable."
  353. # Format the route.
  354. route = format.format_route(component.__name__)
  355. else:
  356. route = format.format_route(route, format_case=False)
  357. # Check if the route given is valid
  358. verify_route_validity(route)
  359. # Apply dynamic args to the route.
  360. if self.state:
  361. self.state.setup_dynamic_args(get_route_args(route))
  362. # Generate the component if it is a callable.
  363. component = self._generate_component(component)
  364. # Wrap the component in a fragment with optional overlay.
  365. if self.overlay_component is not None:
  366. component = Fragment.create(
  367. self._generate_component(self.overlay_component),
  368. component,
  369. )
  370. else:
  371. component = Fragment.create(component)
  372. # Add meta information to the component.
  373. compiler_utils.add_meta(
  374. component,
  375. title=title,
  376. image=image,
  377. description=description,
  378. meta=meta,
  379. )
  380. # Add script tags if given
  381. if script_tags:
  382. console.deprecate(
  383. feature_name="Passing script tags to add_page",
  384. reason="Add script components as children to the page component instead",
  385. deprecation_version="0.2.9",
  386. removal_version="0.5.0",
  387. )
  388. component.children.extend(script_tags)
  389. # Add the page.
  390. self._check_routes_conflict(route)
  391. self.pages[route] = component
  392. # Add the load events.
  393. if on_load:
  394. if not isinstance(on_load, list):
  395. on_load = [on_load]
  396. self.load_events[route] = on_load
  397. def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
  398. """Get the load events for a route.
  399. Args:
  400. route: The route to get the load events for.
  401. Returns:
  402. The load events for the route.
  403. """
  404. route = route.lstrip("/")
  405. if route == "":
  406. route = constants.PageNames.INDEX_ROUTE
  407. return self.load_events.get(route, [])
  408. def _check_routes_conflict(self, new_route: str):
  409. """Verify if there is any conflict between the new route and any existing route.
  410. Based on conflicts that NextJS would throw if not intercepted.
  411. Raises:
  412. ValueError: exception showing which conflict exist with the route to be added
  413. Args:
  414. new_route: the route being newly added.
  415. """
  416. newroute_catchall = catchall_in_route(new_route)
  417. if not newroute_catchall:
  418. return
  419. for route in self.pages:
  420. route = "" if route == "index" else route
  421. if new_route.startswith(f"{route}/[[..."):
  422. raise ValueError(
  423. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  424. )
  425. route_catchall = catchall_in_route(route)
  426. if (
  427. route_catchall
  428. and newroute_catchall
  429. and catchall_prefix(route) == catchall_prefix(new_route)
  430. ):
  431. raise ValueError(
  432. f"You cannot use multiple catchall for the same dynamic route ({route} !== {new_route})"
  433. )
  434. def add_custom_404_page(
  435. self,
  436. component: Component | ComponentCallable | None = None,
  437. title: str = constants.Page404.TITLE,
  438. image: str = constants.Page404.IMAGE,
  439. description: str = constants.Page404.DESCRIPTION,
  440. on_load: (
  441. EventHandler | EventSpec | list[EventHandler | EventSpec] | None
  442. ) = None,
  443. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  444. ):
  445. """Define a custom 404 page for any url having no match.
  446. If there is no page defined on 'index' route, add the 404 page to it.
  447. If there is no global catchall defined, add the 404 page with a catchall
  448. Args:
  449. component: The component to display at the page.
  450. title: The title of the page.
  451. description: The description of the page.
  452. image: The image to display on the page.
  453. on_load: The event handler(s) that will be called each time the page load.
  454. meta: The metadata of the page.
  455. """
  456. if component is None:
  457. component = Default404Page.create()
  458. self.add_page(
  459. component=wait_for_client_redirect(self._generate_component(component)),
  460. route=constants.Page404.SLUG,
  461. title=title or constants.Page404.TITLE,
  462. image=image or constants.Page404.IMAGE,
  463. description=description or constants.Page404.DESCRIPTION,
  464. on_load=on_load,
  465. meta=meta,
  466. )
  467. def setup_admin_dash(self):
  468. """Setup the admin dash."""
  469. # Get the admin dash.
  470. admin_dash = self.admin_dash
  471. if admin_dash and admin_dash.models:
  472. # Build the admin dashboard
  473. admin = (
  474. admin_dash.admin
  475. if admin_dash.admin
  476. else Admin(
  477. engine=Model.get_db_engine(),
  478. title="Reflex Admin Dashboard",
  479. logo_url="https://reflex.dev/Reflex.svg",
  480. )
  481. )
  482. for model in admin_dash.models:
  483. view = admin_dash.view_overrides.get(model, ModelView)
  484. admin.add_view(view(model))
  485. admin.mount_to(self.api)
  486. def get_frontend_packages(self, imports: Dict[str, set[ImportVar]]):
  487. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  488. Args:
  489. imports: A dictionary containing the imports used in the current page.
  490. Example:
  491. >>> get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  492. """
  493. page_imports = {
  494. i
  495. for i, tags in imports.items()
  496. if i
  497. not in [
  498. *constants.PackageJson.DEPENDENCIES.keys(),
  499. *constants.PackageJson.DEV_DEPENDENCIES.keys(),
  500. ]
  501. and not any(i.startswith(prefix) for prefix in ["/", ".", "next/"])
  502. and i != ""
  503. and any(tag.install for tag in tags)
  504. }
  505. frontend_packages = get_config().frontend_packages
  506. _frontend_packages = []
  507. for package in frontend_packages:
  508. if package in (get_config().tailwind or {}).get("plugins", []): # type: ignore
  509. console.warn(
  510. f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`"
  511. )
  512. continue
  513. if package in page_imports:
  514. console.warn(
  515. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  516. )
  517. continue
  518. _frontend_packages.append(package)
  519. page_imports.update(_frontend_packages)
  520. prerequisites.install_frontend_packages(page_imports, get_config())
  521. def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component:
  522. for component in tuple(app_wrappers.values()):
  523. app_wrappers.update(component.get_app_wrap_components())
  524. order = sorted(app_wrappers, key=lambda k: k[0], reverse=True)
  525. root = parent = copy.deepcopy(app_wrappers[order[0]])
  526. for key in order[1:]:
  527. child = copy.deepcopy(app_wrappers[key])
  528. parent.children.append(child)
  529. parent = child
  530. return root
  531. def _should_compile(self) -> bool:
  532. """Check if the app should be compiled.
  533. Returns:
  534. Whether the app should be compiled.
  535. """
  536. # Check the environment variable.
  537. if os.environ.get(constants.SKIP_COMPILE_ENV_VAR) == "yes":
  538. return False
  539. # Check the nocompile file.
  540. if os.path.exists(constants.NOCOMPILE_FILE):
  541. # Delete the nocompile file
  542. os.remove(constants.NOCOMPILE_FILE)
  543. return False
  544. # By default, compile the app.
  545. return True
  546. def compile(self):
  547. """compile_() is the new function for performing compilation.
  548. Reflex framework will call it automatically as needed.
  549. """
  550. console.deprecate(
  551. feature_name="app.compile()",
  552. reason="Explicit calls to app.compile() are not needed."
  553. " Method will be removed in 0.4.0",
  554. deprecation_version="0.3.8",
  555. removal_version="0.5.0",
  556. )
  557. return
  558. def compile_(self):
  559. """Compile the app and output it to the pages folder.
  560. Raises:
  561. RuntimeError: When any page uses state, but no rx.State subclass is defined.
  562. """
  563. # add the pages before the compile check so App know onload methods
  564. for render, kwargs in DECORATED_PAGES:
  565. self.add_page(render, **kwargs)
  566. # Render a default 404 page if the user didn't supply one
  567. if constants.Page404.SLUG not in self.pages:
  568. self.add_custom_404_page()
  569. # Add the optional endpoints (_upload)
  570. self.add_optional_endpoints()
  571. if not self._should_compile():
  572. return
  573. # Create a progress bar.
  574. progress = Progress(
  575. *Progress.get_default_columns()[:-1],
  576. MofNCompleteColumn(),
  577. TimeElapsedColumn(),
  578. )
  579. # Get the env mode.
  580. config = get_config()
  581. # Store the compile results.
  582. compile_results = []
  583. # Add the app wrappers.
  584. app_wrappers: Dict[tuple[int, str], Component] = {
  585. # Default app wrap component renders {children}
  586. (0, "AppWrap"): AppWrap.create()
  587. }
  588. if self.theme is not None:
  589. # If a theme component was provided, wrap the app with it
  590. app_wrappers[(20, "Theme")] = self.theme
  591. # Fix up the style.
  592. self.style = evaluate_style_namespaces(self.style)
  593. # Track imports and custom components found.
  594. all_imports = {}
  595. custom_components = set()
  596. # Compile the pages in parallel.
  597. with progress, concurrent.futures.ThreadPoolExecutor() as thread_pool:
  598. fixed_pages = 7
  599. task = progress.add_task("Compiling:", total=len(self.pages) + fixed_pages)
  600. def mark_complete(_=None):
  601. progress.advance(task)
  602. for _route, component in self.pages.items():
  603. # Merge the component style with the app style.
  604. component.add_style(self.style)
  605. component.apply_theme(self.theme)
  606. # Add component.get_imports() to all_imports.
  607. all_imports.update(component.get_imports())
  608. # Add the app wrappers from this component.
  609. app_wrappers.update(component.get_app_wrap_components())
  610. # Add the custom components from the page to the set.
  611. custom_components |= component.get_custom_components()
  612. # Perform auto-memoization of stateful components.
  613. (
  614. stateful_components_path,
  615. stateful_components_code,
  616. page_components,
  617. ) = compiler.compile_stateful_components(self.pages.values())
  618. # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State.
  619. if (
  620. code_uses_state_contexts(stateful_components_code)
  621. and self.state is None
  622. ):
  623. raise RuntimeError(
  624. "To access rx.State in frontend components, at least one "
  625. "subclass of rx.State must be defined in the app."
  626. )
  627. compile_results.append((stateful_components_path, stateful_components_code))
  628. result_futures = []
  629. def submit_work(fn, *args, **kwargs):
  630. """Submit work to the thread pool and add a callback to mark the task as complete.
  631. The Future will be added to the `result_futures` list.
  632. Args:
  633. fn: The function to submit.
  634. *args: The args to submit.
  635. **kwargs: The kwargs to submit.
  636. """
  637. f = thread_pool.submit(fn, *args, **kwargs)
  638. f.add_done_callback(mark_complete)
  639. result_futures.append(f)
  640. # Compile all page components.
  641. for route, component in zip(self.pages, page_components):
  642. submit_work(
  643. compiler.compile_page,
  644. route,
  645. component,
  646. self.state,
  647. )
  648. # Compile the app wrapper.
  649. app_root = self._app_root(app_wrappers=app_wrappers)
  650. submit_work(compiler.compile_app, app_root)
  651. # Compile the custom components.
  652. submit_work(compiler.compile_components, custom_components)
  653. # Compile the root stylesheet with base styles.
  654. submit_work(compiler.compile_root_stylesheet, self.stylesheets)
  655. # Compile the root document.
  656. submit_work(
  657. compiler.compile_document_root,
  658. self.head_components,
  659. html_lang=self.html_lang,
  660. html_custom_attrs=self.html_custom_attrs,
  661. )
  662. # Compile the theme.
  663. submit_work(compiler.compile_theme, style=self.style)
  664. # Compile the contexts.
  665. submit_work(compiler.compile_contexts, self.state, self.theme)
  666. # Compile the Tailwind config.
  667. if config.tailwind is not None:
  668. config.tailwind["content"] = config.tailwind.get(
  669. "content", constants.Tailwind.CONTENT
  670. )
  671. submit_work(compiler.compile_tailwind, config.tailwind)
  672. else:
  673. submit_work(compiler.remove_tailwind_from_postcss)
  674. # Get imports from AppWrap components.
  675. all_imports.update(app_root.get_imports())
  676. # Iterate through all the custom components and add their imports to the all_imports.
  677. for component in custom_components:
  678. all_imports.update(component.get_imports())
  679. # Wait for all compilation tasks to complete.
  680. for future in concurrent.futures.as_completed(result_futures):
  681. compile_results.append(future.result())
  682. # Empty the .web pages directory.
  683. compiler.purge_web_pages_dir()
  684. # Avoid flickering when installing frontend packages
  685. progress.stop()
  686. # Install frontend packages.
  687. self.get_frontend_packages(all_imports)
  688. # Write the pages at the end to trigger the NextJS hot reload only once.
  689. write_page_futures = []
  690. for output_path, code in compile_results:
  691. write_page_futures.append(
  692. thread_pool.submit(compiler_utils.write_page, output_path, code)
  693. )
  694. for future in concurrent.futures.as_completed(write_page_futures):
  695. future.result()
  696. @contextlib.asynccontextmanager
  697. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  698. """Modify the state out of band.
  699. Args:
  700. token: The token to modify the state for.
  701. Yields:
  702. The state to modify.
  703. Raises:
  704. RuntimeError: If the app has not been initialized yet.
  705. """
  706. if self.event_namespace is None:
  707. raise RuntimeError("App has not been initialized yet.")
  708. # Get exclusive access to the state.
  709. async with self.state_manager.modify_state(token) as state:
  710. # No other event handler can modify the state while in this context.
  711. yield state
  712. delta = state.get_delta()
  713. if delta:
  714. # When the state is modified reset dirty status and emit the delta to the frontend.
  715. state._clean()
  716. await self.event_namespace.emit_update(
  717. update=StateUpdate(delta=delta),
  718. sid=state.router.session.session_id,
  719. )
  720. def _process_background(
  721. self, state: BaseState, event: Event
  722. ) -> asyncio.Task | None:
  723. """Process an event in the background and emit updates as they arrive.
  724. Args:
  725. state: The state to process the event for.
  726. event: The event to process.
  727. Returns:
  728. Task if the event was backgroundable, otherwise None
  729. """
  730. substate, handler = state._get_event_handler(event)
  731. if not handler.is_background:
  732. return None
  733. async def _coro():
  734. """Coroutine to process the event and emit updates inside an asyncio.Task.
  735. Raises:
  736. RuntimeError: If the app has not been initialized yet.
  737. """
  738. if self.event_namespace is None:
  739. raise RuntimeError("App has not been initialized yet.")
  740. # Process the event.
  741. async for update in state._process_event(
  742. handler=handler, state=substate, payload=event.payload
  743. ):
  744. # Postprocess the event.
  745. update = await self.postprocess(state, event, update)
  746. # Send the update to the client.
  747. await self.event_namespace.emit_update(
  748. update=update,
  749. sid=state.router.session.session_id,
  750. )
  751. task = asyncio.create_task(_coro())
  752. self.background_tasks.add(task)
  753. # Clean up task from background_tasks set when complete.
  754. task.add_done_callback(self.background_tasks.discard)
  755. return task
  756. async def process(
  757. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  758. ) -> AsyncIterator[StateUpdate]:
  759. """Process an event.
  760. Args:
  761. app: The app to process the event for.
  762. event: The event to process.
  763. sid: The Socket.IO session id.
  764. headers: The client headers.
  765. client_ip: The client_ip.
  766. Yields:
  767. The state updates after processing the event.
  768. """
  769. # Add request data to the state.
  770. router_data = event.router_data
  771. router_data.update(
  772. {
  773. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  774. constants.RouteVar.CLIENT_TOKEN: event.token,
  775. constants.RouteVar.SESSION_ID: sid,
  776. constants.RouteVar.HEADERS: headers,
  777. constants.RouteVar.CLIENT_IP: client_ip,
  778. }
  779. )
  780. # Get the state for the session exclusively.
  781. async with app.state_manager.modify_state(event.substate_token) as state:
  782. # re-assign only when the value is different
  783. if state.router_data != router_data:
  784. # assignment will recurse into substates and force recalculation of
  785. # dependent ComputedVar (dynamic route variables)
  786. state.router_data = router_data
  787. state.router = RouterData(router_data)
  788. # Preprocess the event.
  789. update = await app.preprocess(state, event)
  790. # If there was an update, yield it.
  791. if update is not None:
  792. yield update
  793. # Only process the event if there is no update.
  794. else:
  795. if app._process_background(state, event) is not None:
  796. # `final=True` allows the frontend send more events immediately.
  797. yield StateUpdate(final=True)
  798. return
  799. # Process the event synchronously.
  800. async for update in state._process(event):
  801. # Postprocess the event.
  802. update = await app.postprocess(state, event, update)
  803. # Yield the update.
  804. yield update
  805. async def ping() -> str:
  806. """Test API endpoint.
  807. Returns:
  808. The response.
  809. """
  810. return "pong"
  811. def upload(app: App):
  812. """Upload a file.
  813. Args:
  814. app: The app to upload the file for.
  815. Returns:
  816. The upload function.
  817. """
  818. async def upload_file(request: Request, files: List[UploadFile]):
  819. """Upload a file.
  820. Args:
  821. request: The FastAPI request object.
  822. files: The file(s) to upload.
  823. Returns:
  824. StreamingResponse yielding newline-delimited JSON of StateUpdate
  825. emitted by the upload handler.
  826. Raises:
  827. ValueError: if there are no args with supported annotation.
  828. TypeError: if a background task is used as the handler.
  829. HTTPException: when the request does not include token / handler headers.
  830. """
  831. token = request.headers.get("reflex-client-token")
  832. handler = request.headers.get("reflex-event-handler")
  833. if not token or not handler:
  834. raise HTTPException(
  835. status_code=400,
  836. detail="Missing reflex-client-token or reflex-event-handler header.",
  837. )
  838. # Get the state for the session.
  839. substate_token = _substate_key(token, handler.rpartition(".")[0])
  840. state = await app.state_manager.get_state(substate_token)
  841. # get the current session ID
  842. # get the current state(parent state/substate)
  843. path = handler.split(".")[:-1]
  844. current_state = state.get_substate(path)
  845. handler_upload_param = ()
  846. # get handler function
  847. func = getattr(type(current_state), handler.split(".")[-1])
  848. # check if there exists any handler args with annotation, List[UploadFile]
  849. if isinstance(func, EventHandler):
  850. if func.is_background:
  851. raise TypeError(
  852. f"@rx.background is not supported for upload handler `{handler}`.",
  853. )
  854. func = func.fn
  855. if isinstance(func, functools.partial):
  856. func = func.func
  857. for k, v in get_type_hints(func).items():
  858. if types.is_generic_alias(v) and types._issubclass(
  859. get_args(v)[0],
  860. UploadFile,
  861. ):
  862. handler_upload_param = (k, v)
  863. break
  864. if not handler_upload_param:
  865. raise ValueError(
  866. f"`{handler}` handler should have a parameter annotated as "
  867. "List[rx.UploadFile]"
  868. )
  869. event = Event(
  870. token=token,
  871. name=handler,
  872. payload={handler_upload_param[0]: files},
  873. )
  874. async def _ndjson_updates():
  875. """Process the upload event, generating ndjson updates.
  876. Yields:
  877. Each state update as JSON followed by a new line.
  878. """
  879. # Process the event.
  880. async with app.state_manager.modify_state(event.substate_token) as state:
  881. async for update in state._process(event):
  882. # Postprocess the event.
  883. update = await app.postprocess(state, event, update)
  884. yield update.json() + "\n"
  885. # Stream updates to client
  886. return StreamingResponse(
  887. _ndjson_updates(),
  888. media_type="application/x-ndjson",
  889. )
  890. return upload_file
  891. class EventNamespace(AsyncNamespace):
  892. """The event namespace."""
  893. # The application object.
  894. app: App
  895. def __init__(self, namespace: str, app: App):
  896. """Initialize the event namespace.
  897. Args:
  898. namespace: The namespace.
  899. app: The application object.
  900. """
  901. super().__init__(namespace)
  902. self.app = app
  903. def on_connect(self, sid, environ):
  904. """Event for when the websocket is connected.
  905. Args:
  906. sid: The Socket.IO session id.
  907. environ: The request information, including HTTP headers.
  908. """
  909. pass
  910. def on_disconnect(self, sid):
  911. """Event for when the websocket disconnects.
  912. Args:
  913. sid: The Socket.IO session id.
  914. """
  915. pass
  916. async def emit_update(self, update: StateUpdate, sid: str) -> None:
  917. """Emit an update to the client.
  918. Args:
  919. update: The state update to send.
  920. sid: The Socket.IO session id.
  921. """
  922. # Creating a task prevents the update from being blocked behind other coroutines.
  923. await asyncio.create_task(
  924. self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  925. )
  926. async def on_event(self, sid, data):
  927. """Event for receiving front-end websocket events.
  928. Args:
  929. sid: The Socket.IO session id.
  930. data: The event data.
  931. """
  932. # Get the event.
  933. event = Event.parse_raw(data)
  934. # Get the event environment.
  935. assert self.app.sio is not None
  936. environ = self.app.sio.get_environ(sid, self.namespace)
  937. assert environ is not None
  938. # Get the client headers.
  939. headers = {
  940. k.decode("utf-8"): v.decode("utf-8")
  941. for (k, v) in environ["asgi.scope"]["headers"]
  942. }
  943. # Get the client IP
  944. client_ip = environ["REMOTE_ADDR"]
  945. # Process the events.
  946. async for update in process(self.app, event, sid, headers, client_ip):
  947. # Emit the update from processing the event.
  948. await self.emit_update(update=update, sid=sid)
  949. async def on_ping(self, sid):
  950. """Event for testing the API endpoint.
  951. Args:
  952. sid: The Socket.IO session id.
  953. """
  954. # Emit the test event.
  955. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)