1
0

app.py 37 KB

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