app.py 38 KB

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