app.py 32 KB

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