app.py 35 KB

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