app.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. """The main Reflex app."""
  2. import asyncio
  3. import inspect
  4. import os
  5. from multiprocessing.pool import ThreadPool
  6. from typing import (
  7. Any,
  8. AsyncIterator,
  9. Callable,
  10. Coroutine,
  11. Dict,
  12. List,
  13. Optional,
  14. Tuple,
  15. Type,
  16. Union,
  17. )
  18. from fastapi import FastAPI, UploadFile
  19. from fastapi.middleware import cors
  20. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  21. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  22. from starlette_admin.contrib.sqla.admin import Admin
  23. from starlette_admin.contrib.sqla.view import ModelView
  24. from reflex import constants
  25. from reflex.admin import AdminDash
  26. from reflex.base import Base
  27. from reflex.compiler import compiler
  28. from reflex.compiler import utils as compiler_utils
  29. from reflex.components.component import Component, ComponentStyle
  30. from reflex.components.layout.fragment import Fragment
  31. from reflex.config import get_config
  32. from reflex.event import Event, EventHandler, EventSpec
  33. from reflex.middleware import HydrateMiddleware, Middleware
  34. from reflex.model import Model
  35. from reflex.page import (
  36. DECORATED_PAGES,
  37. )
  38. from reflex.route import (
  39. catchall_in_route,
  40. catchall_prefix,
  41. get_route_args,
  42. verify_route_validity,
  43. )
  44. from reflex.state import DefaultState, State, StateManager, StateUpdate
  45. from reflex.utils import console, format, types
  46. # Define custom types.
  47. ComponentCallable = Callable[[], Component]
  48. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  49. class App(Base):
  50. """A Reflex application."""
  51. # A map from a page route to the component to render.
  52. pages: Dict[str, Component] = {}
  53. # A list of URLs to stylesheets to include in the app.
  54. stylesheets: List[str] = []
  55. # The backend API object.
  56. api: FastAPI = None # type: ignore
  57. # The Socket.IO AsyncServer.
  58. sio: Optional[AsyncServer] = None
  59. # The socket app.
  60. socket_app: Optional[ASGIApp] = None
  61. # The state class to use for the app.
  62. state: Type[State] = DefaultState
  63. # Class to manage many client states.
  64. state_manager: StateManager = StateManager()
  65. # The styling to apply to each component.
  66. style: ComponentStyle = {}
  67. # Middleware to add to the app.
  68. middleware: List[Middleware] = []
  69. # List of event handlers to trigger when a page loads.
  70. load_events: Dict[str, List[Union[EventHandler, EventSpec]]] = {}
  71. # Admin dashboard
  72. admin_dash: Optional[AdminDash] = None
  73. # The component to render if there is a connection error to the server.
  74. connect_error_component: Optional[Component] = None
  75. # The async server name space
  76. event_namespace: Optional[AsyncNamespace] = None
  77. def __init__(self, *args, **kwargs):
  78. """Initialize the app.
  79. Args:
  80. *args: Args to initialize the app with.
  81. **kwargs: Kwargs to initialize the app with.
  82. Raises:
  83. ValueError: If the event namespace is not provided in the config.
  84. Also, if there are multiple client subclasses of rx.State(Subclasses of rx.State should consist
  85. of the DefaultState and the client app state).
  86. """
  87. super().__init__(*args, **kwargs)
  88. state_subclasses = State.__subclasses__()
  89. inferred_state = state_subclasses[-1]
  90. is_testing_env = constants.PYTEST_CURRENT_TEST in os.environ
  91. # Special case to allow test cases have multiple subclasses of rx.State.
  92. if not is_testing_env:
  93. # Only the default state and the client state should be allowed as subclasses.
  94. if len(state_subclasses) > 2:
  95. raise ValueError(
  96. "rx.State has been subclassed multiple times. Only one subclass is allowed"
  97. )
  98. # verify that provided state is valid
  99. if self.state not in [DefaultState, inferred_state]:
  100. console.warn(
  101. f"Using substate ({self.state.__name__}) as root state in `rx.App` is currently not supported."
  102. f" Defaulting to root state: ({inferred_state.__name__})"
  103. )
  104. self.state = inferred_state
  105. # Get the config
  106. config = get_config()
  107. # Add middleware.
  108. self.middleware.append(HydrateMiddleware())
  109. # Set up the state manager.
  110. self.state_manager.setup(state=self.state)
  111. # Set up the API.
  112. self.api = FastAPI()
  113. self.add_cors()
  114. self.add_default_endpoints()
  115. # Set up the Socket.IO AsyncServer.
  116. self.sio = AsyncServer(
  117. async_mode="asgi",
  118. cors_allowed_origins="*"
  119. if config.cors_allowed_origins == constants.CORS_ALLOWED_ORIGINS
  120. else config.cors_allowed_origins,
  121. cors_credentials=config.cors_credentials,
  122. max_http_buffer_size=config.polling_max_http_buffer_size,
  123. ping_interval=constants.PING_INTERVAL,
  124. ping_timeout=constants.PING_TIMEOUT,
  125. )
  126. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  127. self.socket_app = ASGIApp(self.sio, socketio_path="")
  128. namespace = config.get_event_namespace()
  129. if not namespace:
  130. raise ValueError("event namespace must be provided in the config.")
  131. # Create the event namespace and attach the main app. Not related to any paths.
  132. self.event_namespace = EventNamespace(namespace, self)
  133. # Register the event namespace with the socket.
  134. self.sio.register_namespace(self.event_namespace)
  135. # Mount the socket app with the API.
  136. self.api.mount(str(constants.Endpoint.EVENT), self.socket_app)
  137. # Set up the admin dash.
  138. self.setup_admin_dash()
  139. def __repr__(self) -> str:
  140. """Get the string representation of the app.
  141. Returns:
  142. The string representation of the app.
  143. """
  144. return f"<App state={self.state.__name__}>"
  145. def __call__(self) -> FastAPI:
  146. """Run the backend api instance.
  147. Returns:
  148. The backend api.
  149. """
  150. return self.api
  151. def add_default_endpoints(self):
  152. """Add the default endpoints."""
  153. # To test the server.
  154. self.api.get(str(constants.Endpoint.PING))(ping)
  155. # To upload files.
  156. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  157. def add_cors(self):
  158. """Add CORS middleware to the app."""
  159. self.api.add_middleware(
  160. cors.CORSMiddleware,
  161. allow_credentials=True,
  162. allow_methods=["*"],
  163. allow_headers=["*"],
  164. allow_origins=["*"],
  165. )
  166. async def preprocess(self, state: State, event: Event) -> Optional[StateUpdate]:
  167. """Preprocess the event.
  168. This is where middleware can modify the event before it is processed.
  169. Each middleware is called in the order it was added to the app.
  170. If a middleware returns an update, the event is not processed and the
  171. update is returned.
  172. Args:
  173. state: The state to preprocess.
  174. event: The event to preprocess.
  175. Returns:
  176. An optional state to return.
  177. """
  178. for middleware in self.middleware:
  179. if asyncio.iscoroutinefunction(middleware.preprocess):
  180. out = await middleware.preprocess(app=self, state=state, event=event)
  181. else:
  182. out = middleware.preprocess(app=self, state=state, event=event)
  183. if out is not None:
  184. return out # type: ignore
  185. async def postprocess(
  186. self, state: State, event: Event, update: StateUpdate
  187. ) -> StateUpdate:
  188. """Postprocess the event.
  189. This is where middleware can modify the delta after it is processed.
  190. Each middleware is called in the order it was added to the app.
  191. Args:
  192. state: The state to postprocess.
  193. event: The event to postprocess.
  194. update: The current state update.
  195. Returns:
  196. The state update to return.
  197. """
  198. for middleware in self.middleware:
  199. if asyncio.iscoroutinefunction(middleware.postprocess):
  200. out = await middleware.postprocess(
  201. app=self, state=state, event=event, update=update
  202. )
  203. else:
  204. out = middleware.postprocess(
  205. app=self, state=state, event=event, update=update
  206. )
  207. if out is not None:
  208. return out # type: ignore
  209. return update
  210. def add_middleware(self, middleware: Middleware, index: Optional[int] = None):
  211. """Add middleware to the app.
  212. Args:
  213. middleware: The middleware to add.
  214. index: The index to add the middleware at.
  215. """
  216. if index is None:
  217. self.middleware.append(middleware)
  218. else:
  219. self.middleware.insert(index, middleware)
  220. def add_page(
  221. self,
  222. component: Union[Component, ComponentCallable],
  223. route: Optional[str] = None,
  224. title: str = constants.DEFAULT_TITLE,
  225. description: str = constants.DEFAULT_DESCRIPTION,
  226. image=constants.DEFAULT_IMAGE,
  227. on_load: Optional[
  228. Union[EventHandler, EventSpec, List[Union[EventHandler, EventSpec]]]
  229. ] = None,
  230. meta: List[Dict] = constants.DEFAULT_META_LIST,
  231. script_tags: Optional[List[Component]] = None,
  232. ):
  233. """Add a page to the app.
  234. If the component is a callable, by default the route is the name of the
  235. function. Otherwise, a route must be provided.
  236. Args:
  237. component: The component to display at the page.
  238. route: The route to display the component at.
  239. title: The title of the page.
  240. description: The description of the page.
  241. image: The image to display on the page.
  242. on_load: The event handler(s) that will be called each time the page load.
  243. meta: The metadata of the page.
  244. script_tags: List of script tags to be added to component
  245. Raises:
  246. TypeError: If an invalid var operation is used.
  247. """
  248. # If the route is not set, get it from the callable.
  249. if route is None:
  250. assert isinstance(
  251. component, Callable
  252. ), "Route must be set if component is not a callable."
  253. route = component.__name__
  254. # Check if the route given is valid
  255. verify_route_validity(route)
  256. # Apply dynamic args to the route.
  257. self.state.setup_dynamic_args(get_route_args(route))
  258. # Generate the component if it is a callable.
  259. try:
  260. component = component if isinstance(component, Component) else component()
  261. except TypeError as e:
  262. message = str(e)
  263. if "BaseVar" in message or "ComputedVar" in message:
  264. raise TypeError(
  265. "You may be trying to use an invalid Python function on a state var. "
  266. "When referencing a var inside your render code, only limited var operations are supported. "
  267. "See the var operation docs here: https://reflex.dev/docs/state/vars/#var-operations"
  268. ) from e
  269. raise e
  270. # Wrap the component in a fragment.
  271. component = Fragment.create(component)
  272. # Add meta information to the component.
  273. compiler_utils.add_meta(
  274. component,
  275. title=title,
  276. image=image,
  277. description=description,
  278. meta=meta,
  279. )
  280. # Add script tags if given
  281. if script_tags:
  282. component.children.extend(script_tags)
  283. # Format the route.
  284. route = format.format_route(route)
  285. # Add the page.
  286. self._check_routes_conflict(route)
  287. self.pages[route] = component
  288. # Add the load events.
  289. if on_load:
  290. if not isinstance(on_load, list):
  291. on_load = [on_load]
  292. self.load_events[route] = on_load
  293. def get_load_events(self, route: str) -> List[Union[EventHandler, EventSpec]]:
  294. """Get the load events for a route.
  295. Args:
  296. route: The route to get the load events for.
  297. Returns:
  298. The load events for the route.
  299. """
  300. route = route.lstrip("/")
  301. if route == "":
  302. route = constants.INDEX_ROUTE
  303. return self.load_events.get(route, [])
  304. def _check_routes_conflict(self, new_route: str):
  305. """Verify if there is any conflict between the new route and any existing route.
  306. Based on conflicts that NextJS would throw if not intercepted.
  307. Raises:
  308. ValueError: exception showing which conflict exist with the route to be added
  309. Args:
  310. new_route: the route being newly added.
  311. """
  312. newroute_catchall = catchall_in_route(new_route)
  313. if not newroute_catchall:
  314. return
  315. for route in self.pages:
  316. route = "" if route == "index" else route
  317. if new_route.startswith(f"{route}/[[..."):
  318. raise ValueError(
  319. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  320. )
  321. route_catchall = catchall_in_route(route)
  322. if (
  323. route_catchall
  324. and newroute_catchall
  325. and catchall_prefix(route) == catchall_prefix(new_route)
  326. ):
  327. raise ValueError(
  328. f"You cannot use multiple catchall for the same dynamic route ({route} !== {new_route})"
  329. )
  330. def add_custom_404_page(
  331. self,
  332. component: Optional[Union[Component, ComponentCallable]] = None,
  333. title: str = constants.TITLE_404,
  334. image: str = constants.FAVICON_404,
  335. description: str = constants.DESCRIPTION_404,
  336. on_load: Optional[
  337. Union[EventHandler, EventSpec, List[Union[EventHandler, EventSpec]]]
  338. ] = None,
  339. meta: List[Dict] = constants.DEFAULT_META_LIST,
  340. ):
  341. """Define a custom 404 page for any url having no match.
  342. If there is no page defined on 'index' route, add the 404 page to it.
  343. If there is no global catchall defined, add the 404 page with a catchall
  344. Args:
  345. component: The component to display at the page.
  346. title: The title of the page.
  347. description: The description of the page.
  348. image: The image to display on the page.
  349. on_load: The event handler(s) that will be called each time the page load.
  350. meta: The metadata of the page.
  351. """
  352. self.add_page(
  353. component=component if component else Fragment.create(),
  354. route=constants.SLUG_404,
  355. title=title or constants.TITLE_404,
  356. image=image or constants.FAVICON_404,
  357. description=description or constants.DESCRIPTION_404,
  358. on_load=on_load,
  359. meta=meta,
  360. )
  361. def setup_admin_dash(self):
  362. """Setup the admin dash."""
  363. # Get the config.
  364. config = get_config()
  365. if config.admin_dash and config.admin_dash.models:
  366. # Build the admin dashboard
  367. admin = (
  368. config.admin_dash.admin
  369. if config.admin_dash.admin
  370. else Admin(
  371. engine=Model.get_db_engine(),
  372. title="Reflex Admin Dashboard",
  373. logo_url="https://reflex.dev/Reflex.svg",
  374. )
  375. )
  376. for model in config.admin_dash.models:
  377. view = config.admin_dash.view_overrides.get(model, ModelView)
  378. admin.add_view(view(model))
  379. admin.mount_to(self.api)
  380. def compile(self):
  381. """Compile the app and output it to the pages folder."""
  382. # Create a progress bar.
  383. progress = Progress(
  384. *Progress.get_default_columns()[:-1],
  385. MofNCompleteColumn(),
  386. TimeElapsedColumn(),
  387. )
  388. task = progress.add_task("Compiling: ", total=len(self.pages))
  389. # TODO: include all work done in progress indicator, not just self.pages
  390. for render, kwargs in DECORATED_PAGES:
  391. self.add_page(render, **kwargs)
  392. # Get the env mode.
  393. config = get_config()
  394. # Store the compile results.
  395. compile_results = []
  396. # Compile the pages in parallel.
  397. custom_components = set()
  398. # TODO Anecdotally, processes=2 works 10% faster (cpu_count=12)
  399. thread_pool = ThreadPool()
  400. with progress:
  401. for route, component in self.pages.items():
  402. # TODO: this progress does not reflect actual threaded task completion
  403. progress.advance(task)
  404. component.add_style(self.style)
  405. compile_results.append(
  406. thread_pool.apply_async(
  407. compiler.compile_page,
  408. args=(
  409. route,
  410. component,
  411. self.state,
  412. self.connect_error_component,
  413. ),
  414. )
  415. )
  416. # Add the custom components from the page to the set.
  417. custom_components |= component.get_custom_components()
  418. thread_pool.close()
  419. thread_pool.join()
  420. # Get the results.
  421. compile_results = [result.get() for result in compile_results]
  422. # TODO the compile tasks below may also benefit from parallelization too
  423. # Compile the custom components.
  424. compile_results.append(compiler.compile_components(custom_components))
  425. # Compile the root document with base styles and fonts.
  426. compile_results.append(compiler.compile_document_root(self.stylesheets))
  427. # Compile the theme.
  428. compile_results.append(compiler.compile_theme(self.style))
  429. # Compile the contexts.
  430. compile_results.append(compiler.compile_contexts(self.state))
  431. # Compile the Tailwind config.
  432. if config.tailwind is not None:
  433. config.tailwind["content"] = config.tailwind.get(
  434. "content", constants.TAILWIND_CONTENT
  435. )
  436. compile_results.append(compiler.compile_tailwind(config.tailwind))
  437. # Empty the .web pages directory
  438. compiler.purge_web_pages_dir()
  439. # Write the pages at the end to trigger the NextJS hot reload only once.
  440. thread_pool = ThreadPool()
  441. for output_path, code in compile_results:
  442. thread_pool.apply_async(compiler_utils.write_page, args=(output_path, code))
  443. thread_pool.close()
  444. thread_pool.join()
  445. async def process(
  446. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  447. ) -> AsyncIterator[StateUpdate]:
  448. """Process an event.
  449. Args:
  450. app: The app to process the event for.
  451. event: The event to process.
  452. sid: The Socket.IO session id.
  453. headers: The client headers.
  454. client_ip: The client_ip.
  455. Yields:
  456. The state updates after processing the event.
  457. """
  458. # Get the state for the session.
  459. state = app.state_manager.get_state(event.token)
  460. # Add request data to the state.
  461. router_data = event.router_data
  462. router_data.update(
  463. {
  464. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  465. constants.RouteVar.CLIENT_TOKEN: event.token,
  466. constants.RouteVar.SESSION_ID: sid,
  467. constants.RouteVar.HEADERS: headers,
  468. constants.RouteVar.CLIENT_IP: client_ip,
  469. }
  470. )
  471. # re-assign only when the value is different
  472. if state.router_data != router_data:
  473. # assignment will recurse into substates and force recalculation of
  474. # dependent ComputedVar (dynamic route variables)
  475. state.router_data = router_data
  476. # Preprocess the event.
  477. update = await app.preprocess(state, event)
  478. # If there was an update, yield it.
  479. if update is not None:
  480. yield update
  481. # Only process the event if there is no update.
  482. else:
  483. # Process the event.
  484. async for update in state._process(event):
  485. # Postprocess the event.
  486. update = await app.postprocess(state, event, update)
  487. # Yield the update.
  488. yield update
  489. # Set the state for the session.
  490. app.state_manager.set_state(event.token, state)
  491. async def ping() -> str:
  492. """Test API endpoint.
  493. Returns:
  494. The response.
  495. """
  496. return "pong"
  497. def upload(app: App):
  498. """Upload a file.
  499. Args:
  500. app: The app to upload the file for.
  501. Returns:
  502. The upload function.
  503. """
  504. async def upload_file(files: List[UploadFile]):
  505. """Upload a file.
  506. Args:
  507. files: The file(s) to upload.
  508. Raises:
  509. ValueError: if there are no args with supported annotation.
  510. """
  511. assert files[0].filename is not None
  512. token, handler = files[0].filename.split(":")[:2]
  513. for file in files:
  514. assert file.filename is not None
  515. file.filename = file.filename.split(":")[-1]
  516. # Get the state for the session.
  517. state = app.state_manager.get_state(token)
  518. # get the current session ID
  519. sid = state.get_sid()
  520. # get the current state(parent state/substate)
  521. path = handler.split(".")[:-1]
  522. current_state = state.get_substate(path)
  523. handler_upload_param: Tuple = ()
  524. # get handler function
  525. func = getattr(current_state, handler.split(".")[-1])
  526. # check if there exists any handler args with annotation, List[UploadFile]
  527. for k, v in inspect.getfullargspec(
  528. func.fn if isinstance(func, EventHandler) else func
  529. ).annotations.items():
  530. if types.is_generic_alias(v) and types._issubclass(
  531. v.__args__[0], UploadFile
  532. ):
  533. handler_upload_param = (k, v)
  534. break
  535. if not handler_upload_param:
  536. raise ValueError(
  537. f"`{handler}` handler should have a parameter annotated as List["
  538. f"rx.UploadFile]"
  539. )
  540. event = Event(
  541. token=token,
  542. name=handler,
  543. payload={handler_upload_param[0]: files},
  544. )
  545. async for update in state._process(event):
  546. # Postprocess the event.
  547. update = await app.postprocess(state, event, update)
  548. # Send update to client
  549. await asyncio.create_task(
  550. app.event_namespace.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid) # type: ignore
  551. )
  552. # Set the state for the session.
  553. app.state_manager.set_state(event.token, state)
  554. return upload_file
  555. class EventNamespace(AsyncNamespace):
  556. """The event namespace."""
  557. # The application object.
  558. app: App
  559. def __init__(self, namespace: str, app: App):
  560. """Initialize the event namespace.
  561. Args:
  562. namespace: The namespace.
  563. app: The application object.
  564. """
  565. super().__init__(namespace)
  566. self.app = app
  567. def on_connect(self, sid, environ):
  568. """Event for when the websocket disconnects.
  569. Args:
  570. sid: The Socket.IO session id.
  571. environ: The request information, including HTTP headers.
  572. """
  573. pass
  574. def on_disconnect(self, sid):
  575. """Event for when the websocket disconnects.
  576. Args:
  577. sid: The Socket.IO session id.
  578. """
  579. pass
  580. async def on_event(self, sid, data):
  581. """Event for receiving front-end websocket events.
  582. Args:
  583. sid: The Socket.IO session id.
  584. data: The event data.
  585. """
  586. # Get the event.
  587. event = Event.parse_raw(data)
  588. # Get the event environment.
  589. assert self.app.sio is not None
  590. environ = self.app.sio.get_environ(sid, self.namespace)
  591. assert environ is not None
  592. # Get the client headers.
  593. headers = {
  594. k.decode("utf-8"): v.decode("utf-8")
  595. for (k, v) in environ["asgi.scope"]["headers"]
  596. }
  597. # Get the client IP
  598. client_ip = environ["REMOTE_ADDR"]
  599. # Process the events.
  600. async for update in process(self.app, event, sid, headers, client_ip):
  601. # Emit the event.
  602. await asyncio.create_task(
  603. self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  604. )
  605. async def on_ping(self, sid):
  606. """Event for testing the API endpoint.
  607. Args:
  608. sid: The Socket.IO session id.
  609. """
  610. # Emit the test event.
  611. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)