axum_adapter.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //! Dioxus utilities for the [Axum](https://docs.rs/axum/latest/axum/index.html) server framework.
  2. //!
  3. //! # Example
  4. //! ```rust
  5. //! #![allow(non_snake_case)]
  6. //! use dioxus::prelude::*;
  7. //! use dioxus_fullstack::prelude::*;
  8. //!
  9. //! fn main() {
  10. //! #[cfg(feature = "web")]
  11. //! // Hydrate the application on the client
  12. //! dioxus_web::launch_cfg(app, dioxus_web::Config::new().hydrate(true));
  13. //! #[cfg(feature = "ssr")]
  14. //! {
  15. //! tokio::runtime::Runtime::new()
  16. //! .unwrap()
  17. //! .block_on(async move {
  18. //! let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  19. //! axum::Server::bind(&addr)
  20. //! .serve(
  21. //! axum::Router::new()
  22. //! // Server side render the application, serve static assets, and register server functions
  23. //! .serve_dioxus_application("", ServeConfigBuilder::new(app, ()))
  24. //! .into_make_service(),
  25. //! )
  26. //! .await
  27. //! .unwrap();
  28. //! });
  29. //! }
  30. //! }
  31. //!
  32. //! fn app(cx: Scope) -> Element {
  33. //! let text = use_state(cx, || "...".to_string());
  34. //!
  35. //! cx.render(rsx! {
  36. //! button {
  37. //! onclick: move |_| {
  38. //! to_owned![text];
  39. //! async move {
  40. //! if let Ok(data) = get_server_data().await {
  41. //! text.set(data);
  42. //! }
  43. //! }
  44. //! },
  45. //! "Run a server function"
  46. //! }
  47. //! "Server said: {text}"
  48. //! })
  49. //! }
  50. //!
  51. //! #[server(GetServerData)]
  52. //! async fn get_server_data() -> Result<String, ServerFnError> {
  53. //! Ok("Hello from the server!".to_string())
  54. //! }
  55. //! ```
  56. use axum::{
  57. body::{self, Body, BoxBody, Full},
  58. extract::State,
  59. handler::Handler,
  60. http::{Request, Response, StatusCode},
  61. response::IntoResponse,
  62. routing::{get, post},
  63. Router,
  64. };
  65. use server_fn::{Encoding, Payload, ServerFunctionRegistry};
  66. use std::sync::Arc;
  67. use std::sync::RwLock;
  68. use tokio::task::spawn_blocking;
  69. use crate::{
  70. prelude::*, render::SSRState, serve_config::ServeConfig, server_context::DioxusServerContext,
  71. server_fn::DioxusServerFnRegistry,
  72. };
  73. /// A extension trait with utilities for integrating Dioxus with your Axum router.
  74. pub trait DioxusRouterExt<S> {
  75. /// Registers server functions with a custom handler function. This allows you to pass custom context to your server functions by generating a [`DioxusServerContext`] from the request.
  76. ///
  77. /// # Example
  78. /// ```rust
  79. /// use dioxus::prelude::*;
  80. /// use dioxus_fullstack::prelude::*;
  81. ///
  82. /// #[tokio::main]
  83. /// async fn main() {
  84. /// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  85. /// axum::Server::bind(&addr)
  86. /// .serve(
  87. /// axum::Router::new()
  88. /// .register_server_fns_with_handler("", |func| {
  89. /// move |req: Request<Body>| async move {
  90. /// let (parts, body) = req.into_parts();
  91. /// let parts: Arc<http::request::Parts> = Arc::new(parts.into());
  92. /// let server_context = DioxusServerContext::new(parts.clone());
  93. /// server_fn_handler(server_context, func.clone(), parts, body).await
  94. /// }
  95. /// })
  96. /// .into_make_service(),
  97. /// )
  98. /// .await
  99. /// .unwrap();
  100. /// }
  101. /// ```
  102. fn register_server_fns_with_handler<H, T>(
  103. self,
  104. server_fn_route: &'static str,
  105. handler: impl FnMut(server_fn::ServerFnTraitObj<()>) -> H,
  106. ) -> Self
  107. where
  108. H: Handler<T, S>,
  109. T: 'static,
  110. S: Clone + Send + Sync + 'static;
  111. /// Registers server functions with the default handler. This handler function will pass an empty [`DioxusServerContext`] to your server functions.
  112. ///
  113. /// # Example
  114. /// ```rust
  115. /// use dioxus::prelude::*;
  116. /// use dioxus_fullstack::prelude::*;
  117. ///
  118. /// #[tokio::main]
  119. /// async fn main() {
  120. /// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  121. /// axum::Server::bind(&addr)
  122. /// .serve(
  123. /// axum::Router::new()
  124. /// // Register server functions routes with the default handler
  125. /// .register_server_fns("")
  126. /// .into_make_service(),
  127. /// )
  128. /// .await
  129. /// .unwrap();
  130. /// }
  131. /// ```
  132. fn register_server_fns(self, server_fn_route: &'static str) -> Self;
  133. /// Register the web RSX hot reloading endpoint. This will enable hot reloading for your application in debug mode when you call [`dioxus_hot_reload::hot_reload_init`].
  134. ///
  135. /// # Example
  136. /// ```rust
  137. /// #![allow(non_snake_case)]
  138. /// use dioxus_fullstack::prelude::*;
  139. ///
  140. /// #[tokio::main]
  141. /// async fn main() {
  142. /// hot_reload_init!();
  143. /// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  144. /// axum::Server::bind(&addr)
  145. /// .serve(
  146. /// axum::Router::new()
  147. /// // Connect to hot reloading in debug mode
  148. /// .connect_hot_reload()
  149. /// .into_make_service(),
  150. /// )
  151. /// .await
  152. /// .unwrap();
  153. /// }
  154. /// ```
  155. fn connect_hot_reload(self) -> Self;
  156. /// Serves the static WASM for your Dioxus application (except the generated index.html).
  157. ///
  158. /// # Example
  159. /// ```rust
  160. /// #![allow(non_snake_case)]
  161. /// use dioxus::prelude::*;
  162. /// use dioxus_fullstack::prelude::*;
  163. ///
  164. /// #[tokio::main]
  165. /// async fn main() {
  166. /// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  167. /// axum::Server::bind(&addr)
  168. /// .serve(
  169. /// axum::Router::new()
  170. /// // Server side render the application, serve static assets, and register server functions
  171. /// .serve_static_assets(ServeConfigBuilder::new(app, ()))
  172. /// // Server render the application
  173. /// // ...
  174. /// .into_make_service(),
  175. /// )
  176. /// .await
  177. /// .unwrap();
  178. /// }
  179. ///
  180. /// fn app(cx: Scope) -> Element {
  181. /// todo!()
  182. /// }
  183. /// ```
  184. fn serve_static_assets(self, assets_path: impl Into<std::path::PathBuf>) -> Self;
  185. /// Serves the Dioxus application. This will serve a complete server side rendered application.
  186. /// This will serve static assets, server render the application, register server functions, and intigrate with hot reloading.
  187. ///
  188. /// # Example
  189. /// ```rust
  190. /// #![allow(non_snake_case)]
  191. /// use dioxus::prelude::*;
  192. /// use dioxus_fullstack::prelude::*;
  193. ///
  194. /// #[tokio::main]
  195. /// async fn main() {
  196. /// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  197. /// axum::Server::bind(&addr)
  198. /// .serve(
  199. /// axum::Router::new()
  200. /// // Server side render the application, serve static assets, and register server functions
  201. /// .serve_dioxus_application("", ServeConfigBuilder::new(app, ()))
  202. /// .into_make_service(),
  203. /// )
  204. /// .await
  205. /// .unwrap();
  206. /// }
  207. ///
  208. /// fn app(cx: Scope) -> Element {
  209. /// todo!()
  210. /// }
  211. /// ```
  212. fn serve_dioxus_application<P: Clone + serde::Serialize + Send + Sync + 'static>(
  213. self,
  214. server_fn_route: &'static str,
  215. cfg: impl Into<ServeConfig<P>>,
  216. ) -> Self;
  217. }
  218. impl<S> DioxusRouterExt<S> for Router<S>
  219. where
  220. S: Send + Sync + Clone + 'static,
  221. {
  222. fn register_server_fns_with_handler<H, T>(
  223. self,
  224. server_fn_route: &'static str,
  225. mut handler: impl FnMut(server_fn::ServerFnTraitObj<()>) -> H,
  226. ) -> Self
  227. where
  228. H: Handler<T, S, Body>,
  229. T: 'static,
  230. S: Clone + Send + Sync + 'static,
  231. {
  232. let mut router = self;
  233. for server_fn_path in DioxusServerFnRegistry::paths_registered() {
  234. let func = DioxusServerFnRegistry::get(server_fn_path).unwrap();
  235. let full_route = format!("{server_fn_route}/{server_fn_path}");
  236. match func.encoding() {
  237. Encoding::Url | Encoding::Cbor => {
  238. router = router.route(&full_route, post(handler(func)));
  239. }
  240. Encoding::GetJSON | Encoding::GetCBOR => {
  241. router = router.route(&full_route, get(handler(func)));
  242. }
  243. }
  244. }
  245. router
  246. }
  247. fn register_server_fns(self, server_fn_route: &'static str) -> Self {
  248. self.register_server_fns_with_handler(server_fn_route, |func| {
  249. use crate::layer::Service;
  250. move |req: Request<Body>| {
  251. let mut service = crate::server_fn_service(Default::default(), func);
  252. async move {
  253. let (req, body) = req.into_parts();
  254. let req = Request::from_parts(req, body);
  255. let res = service.run(req);
  256. match res.await {
  257. Ok(res) => Ok::<_, std::convert::Infallible>(res.map(|b| b.into())),
  258. Err(e) => {
  259. let mut res = Response::new(Body::empty());
  260. *res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
  261. Ok(res)
  262. }
  263. }
  264. }
  265. }
  266. })
  267. }
  268. fn serve_static_assets(mut self, assets_path: impl Into<std::path::PathBuf>) -> Self {
  269. use tower_http::services::{ServeDir, ServeFile};
  270. let assets_path = assets_path.into();
  271. // Serve all files in dist folder except index.html
  272. let dir = std::fs::read_dir(&assets_path).unwrap_or_else(|e| {
  273. panic!(
  274. "Couldn't read assets directory at {:?}: {}",
  275. &assets_path, e
  276. )
  277. });
  278. for entry in dir.flatten() {
  279. let path = entry.path();
  280. if path.ends_with("index.html") {
  281. continue;
  282. }
  283. let route = path
  284. .strip_prefix(&assets_path)
  285. .unwrap()
  286. .iter()
  287. .map(|segment| {
  288. segment.to_str().unwrap_or_else(|| {
  289. panic!("Failed to convert path segment {:?} to string", segment)
  290. })
  291. })
  292. .collect::<Vec<_>>()
  293. .join("/");
  294. let route = format!("/{}", route);
  295. if path.is_dir() {
  296. self = self.nest_service(&route, ServeDir::new(path));
  297. } else {
  298. self = self.nest_service(&route, ServeFile::new(path));
  299. }
  300. }
  301. self
  302. }
  303. fn serve_dioxus_application<P: Clone + serde::Serialize + Send + Sync + 'static>(
  304. self,
  305. server_fn_route: &'static str,
  306. cfg: impl Into<ServeConfig<P>>,
  307. ) -> Self {
  308. let cfg = cfg.into();
  309. let ssr_state = SSRState::new(&cfg);
  310. // Add server functions and render index.html
  311. self.serve_static_assets(cfg.assets_path)
  312. .connect_hot_reload()
  313. .register_server_fns(server_fn_route)
  314. .fallback(get(render_handler).with_state((cfg, ssr_state)))
  315. }
  316. fn connect_hot_reload(self) -> Self {
  317. #[cfg(all(debug_assertions, feature = "hot-reload", feature = "ssr"))]
  318. {
  319. self.nest(
  320. "/_dioxus",
  321. Router::new()
  322. .route(
  323. "/disconnect",
  324. get(|ws: axum::extract::WebSocketUpgrade| async {
  325. ws.on_upgrade(|mut ws| async move {
  326. use axum::extract::ws::Message;
  327. let _ = ws.send(Message::Text("connected".into())).await;
  328. loop {
  329. if ws.recv().await.is_none() {
  330. break;
  331. }
  332. }
  333. })
  334. }),
  335. )
  336. .route("/hot_reload", get(hot_reload_handler)),
  337. )
  338. }
  339. #[cfg(not(all(debug_assertions, feature = "hot-reload", feature = "ssr")))]
  340. {
  341. self
  342. }
  343. }
  344. }
  345. fn apply_request_parts_to_response<B>(
  346. headers: hyper::header::HeaderMap,
  347. response: &mut axum::response::Response<B>,
  348. ) {
  349. let mut_headers = response.headers_mut();
  350. for (key, value) in headers.iter() {
  351. mut_headers.insert(key, value.clone());
  352. }
  353. }
  354. async fn render_handler<P: Clone + serde::Serialize + Send + Sync + 'static>(
  355. State((cfg, ssr_state)): State<(ServeConfig<P>, SSRState)>,
  356. request: Request<Body>,
  357. ) -> impl IntoResponse {
  358. let (parts, _) = request.into_parts();
  359. let url = parts.uri.path_and_query().unwrap().to_string();
  360. let parts: Arc<RwLock<http::request::Parts>> = Arc::new(RwLock::new(parts.into()));
  361. let server_context = DioxusServerContext::new(parts.clone());
  362. match ssr_state.render(url, &cfg, &server_context).await {
  363. Ok(rendered) => {
  364. let crate::render::RenderResponse { html, freshness } = rendered;
  365. let mut response = axum::response::Html::from(html).into_response();
  366. freshness.write(response.headers_mut());
  367. let headers = server_context.response_parts().unwrap().headers.clone();
  368. apply_request_parts_to_response(headers, &mut response);
  369. response
  370. }
  371. Err(e) => {
  372. log::error!("Failed to render page: {}", e);
  373. report_err(e).into_response()
  374. }
  375. }
  376. }
  377. fn report_err<E: std::fmt::Display>(e: E) -> Response<BoxBody> {
  378. Response::builder()
  379. .status(StatusCode::INTERNAL_SERVER_ERROR)
  380. .body(body::boxed(format!("Error: {}", e)))
  381. .unwrap()
  382. }
  383. /// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
  384. #[cfg(all(debug_assertions, feature = "hot-reload", feature = "ssr"))]
  385. pub async fn hot_reload_handler(ws: axum::extract::WebSocketUpgrade) -> impl IntoResponse {
  386. use axum::extract::ws::Message;
  387. use futures_util::StreamExt;
  388. let state = crate::hot_reload::spawn_hot_reload().await;
  389. ws.on_upgrade(move |mut socket| async move {
  390. println!("🔥 Hot Reload WebSocket connected");
  391. {
  392. // update any rsx calls that changed before the websocket connected.
  393. {
  394. println!("🔮 Finding updates since last compile...");
  395. let templates_read = state.templates.read().await;
  396. for template in &*templates_read {
  397. if socket
  398. .send(Message::Text(serde_json::to_string(&template).unwrap()))
  399. .await
  400. .is_err()
  401. {
  402. return;
  403. }
  404. }
  405. }
  406. println!("finished");
  407. }
  408. let mut rx =
  409. tokio_stream::wrappers::WatchStream::from_changes(state.message_receiver.clone());
  410. while let Some(change) = rx.next().await {
  411. if let Some(template) = change {
  412. let template = { serde_json::to_string(&template).unwrap() };
  413. if socket.send(Message::Text(template)).await.is_err() {
  414. break;
  415. };
  416. }
  417. }
  418. })
  419. }