app.py 39 KB

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