app.py 37 KB

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