app.py 38 KB

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