app.py 39 KB

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