multiple fullstack nits/cleanups before release (#4852)

* feat: `:arg` syntax for serverfn

* add better decode/encode verify message

* allow catch-all query args

* add rebind

* implement websocket frames for `Streaming`

* fix lazy init

* wip... serverfnstate

* wip...

* wip: serverfns require Send/Sync, let's fix that

* wip...

* small cleanup

* fix hang by actually spawning the tokio task

* clippy

* fix parameter catchall binding

* fix lychee

* doc tests
This commit is contained in:
Jonathan Kelley authored and GitHub committed 2025-10-30 18:52:47 -07:00
1 parent 43373f0be7
commit 5559e463c8
27 files changed
+1395 -1097

No files matched your search

+211 -242
View File
@@ -1,6 +1,6 @@
//! A launch function that creates an axum router for the LaunchBuilder
use crate::{server::DioxusRouterExt, RenderHandleState, ServeConfig};
use crate::{server::DioxusRouterExt, FullstackState, ServeConfig};
use anyhow::Context;
use axum::{
body::Body,
@@ -9,10 +9,9 @@ use axum::{
Router,
};
use dioxus_cli_config::base_path;
use dioxus_core::Element;
#[cfg(not(target_arch = "wasm32"))]
use dioxus_core::{RenderError, VNode};
use dioxus_devtools::DevserverMsg;
use dioxus_core::{ComponentFunction, Element};
use dioxus_devtools::{DevserverMsg, HotReloadMsg};
use futures_util::{stream::FusedStream, StreamExt};
use hyper::body::Incoming;
use hyper_util::server::conn::auto::Builder as HyperBuilder;
@@ -20,14 +19,19 @@ use hyper_util::{
rt::{TokioExecutor, TokioIo},
service::TowerToHyperService,
};
use std::sync::Arc;
use std::{any::Any, collections::HashMap, net::SocketAddr, prelude::rust_2024::Future};
use tokio::net::TcpStream;
use tokio_util::task::LocalPoolHandle;
use std::{any::Any, net::SocketAddr, prelude::rust_2024::Future};
use std::{pin::Pin, sync::Arc};
use subsecond::HotFn;
use tokio_util::either::Either;
use tower::{Service, ServiceExt as _};
type ContextList = Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>;
#[cfg(not(target_arch = "wasm32"))]
use {
dioxus_core::{RenderError, VNode},
tokio::net::TcpListener,
};
type ContextList = Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>;
type BaseComp = fn() -> Element;
/// Launch a fullstack app with the given root component.
@@ -52,10 +56,6 @@ async fn serve_server(
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
platform_config: Vec<Box<dyn Any>>,
) {
let (devtools_tx, mut devtools_rx) = futures_channel::mpsc::unbounded();
dioxus_devtools::connect(move |msg| _ = devtools_tx.unbounded_send(msg));
let mut cfg = platform_config
.into_iter()
.find_map(|cfg| cfg.downcast::<ServeConfig>().ok().map(|b| *b))
@@ -67,236 +67,19 @@ async fn serve_server(
cfg.context_providers.push(arced);
}
// Get the address the server should run on. If the CLI is running, the CLI proxies fullstack into the main address
// and we use the generated address the CLI gives us
let address = dioxus_cli_config::fullstack_address_or_localhost();
// Create the router and register the server functions under the basepath.
let router = apply_base_path(
Router::new().serve_dioxus_application(cfg.clone(), original_root),
original_root,
cfg.clone(),
base_path().map(|s| s.to_string()),
);
let task_pool = LocalPoolHandle::new(
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
);
let mut make_service = router.into_make_service();
let listener = tokio::net::TcpListener::bind(address).await.unwrap();
enum Msg {
TcpStream(std::io::Result<(TcpStream, SocketAddr)>),
Devtools(DevserverMsg),
}
let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(0);
let mut hr_idx = 0;
// Manually loop on accepting connections so we can also respond to devtools messages
loop {
let res = tokio::select! {
res = listener.accept() => Msg::TcpStream(res),
msg = devtools_rx.next(), if !devtools_rx.is_terminated() => {
if let Some(msg) = msg {
Msg::Devtools(msg)
} else {
continue;
}
}
};
match res {
Msg::TcpStream(Ok((tcp_stream, _remote_addr))) => {
let this_hr_index = hr_idx;
let mut make_service = make_service.clone();
let mut shutdown_rx = shutdown_rx.clone();
task_pool.spawn_pinned(move || async move {
let tcp_stream = TokioIo::new(tcp_stream);
std::future::poll_fn(|cx| {
<IntoMakeService<Router> as tower::Service<Request>>::poll_ready(
&mut make_service,
cx,
)
})
.await
.unwrap();
let tower_service = make_service
.call(())
.await
.unwrap()
.map_request(|req: Request<Incoming>| req.map(Body::new));
// upgrades needed for websockets
let builder = HyperBuilder::new(TokioExecutor::new());
let connection = builder.serve_connection_with_upgrades(
tcp_stream,
TowerToHyperService::new(tower_service),
);
tokio::select! {
res = connection => {
if let Err(_err) = res {
// This error only appears when the client doesn't send a request and
// terminate the connection.
//
// If client sends one request then terminate connection whenever, it doesn't
// appear.
}
}
_res = shutdown_rx.wait_for(|i| *i == this_hr_index + 1) => {}
}
});
}
Msg::TcpStream(Err(_)) => {}
// We need to delete our old router and build a new one
//
// one challenge is that the server functions are sitting in the dlopened lib and no longer
// accessible by us (the original process)
//
// We need to somehow get them out... ?
//
// for now we just support editing existing server functions
Msg::Devtools(devserver_msg) => {
match devserver_msg {
DevserverMsg::HotReload(hot_reload_msg) => {
if hot_reload_msg.for_build_id == Some(dioxus_cli_config::build_id()) {
if let Some(table) = hot_reload_msg.jump_table {
use crate::ServerFunction;
unsafe { dioxus_devtools::subsecond::apply_patch(table).unwrap() };
let mut new_router = Router::new().serve_static_assets();
let new_cfg = ServeConfig::new();
let server_fn_iter = ServerFunction::collect();
// de-duplicate iteratively by preferring the most recent (first, since it's linked)
let mut server_fn_map: HashMap<_, _> = HashMap::new();
for f in server_fn_iter.into_iter().rev() {
server_fn_map.insert(f.path(), f);
}
for (_, fn_) in server_fn_map {
tracing::trace!(
"Registering server function: {:?} {:?}",
fn_.path(),
fn_.method()
);
new_router = fn_.register_server_fn_on_router(new_router);
}
let hot_root = subsecond::HotFn::current(original_root);
let new_root_addr = hot_root.ptr_address().0 as usize as *const ();
let new_root = unsafe {
std::mem::transmute::<*const (), fn() -> Element>(new_root_addr)
};
crate::document::reset_renderer();
let state = RenderHandleState::new(new_cfg.clone(), new_root);
let fallback_handler =
axum::routing::get(RenderHandleState::render_handler)
.with_state(state);
make_service = apply_base_path(
new_router.fallback(fallback_handler),
new_root,
new_cfg.clone(),
base_path().map(|s| s.to_string()),
)
.into_make_service();
shutdown_tx.send_modify(|i| {
*i += 1;
hr_idx += 1;
});
}
}
}
DevserverMsg::FullReloadStart => {}
DevserverMsg::FullReloadFailed => {}
DevserverMsg::FullReloadCommand => {}
DevserverMsg::Shutdown => {}
_ => {}
}
}
}
}
}
fn apply_base_path(
mut router: Router,
root: fn() -> Element,
cfg: ServeConfig,
base_path: Option<String>,
) -> Router {
if let Some(base_path) = base_path {
let base_path = base_path.trim_matches('/');
// If there is a base path, nest the router under it and serve the root route manually
// Nesting a route in axum only serves /base_path or /base_path/ not both
router = Router::new().nest(&format!("/{base_path}/"), router).route(
&format!("/{base_path}"),
axum::routing::method_routing::get(
|state: State<RenderHandleState>, mut request: Request<Body>| async move {
// The root of the base path always looks like the root from dioxus fullstack
*request.uri_mut() = "/".parse().unwrap();
RenderHandleState::render_handler(state, request).await
},
)
.with_state(RenderHandleState::new(cfg, root)),
)
}
router
}
/// Serve a fullstack dioxus application with a custom axum router.
///
/// This function sets up an async runtime, enables the default dioxus logger, runs the provided initializer,
/// and then starts an axum server with the returned router.
///
/// The axum router will be bound to the address specified by the `IP` and `PORT` environment variables,
/// defaulting to `127.0.0.1:8080` if not set.
pub fn serve<F>(mut serve_it: impl FnMut() -> F) -> !
where
F: Future<Output = Result<Router, anyhow::Error>>,
{
dioxus_logger::initialize_default();
let app_future = async move {
let router = serve_it().await.expect("Failed to create axum router");
let address = dioxus_cli_config::fullstack_address_or_localhost();
let listener = tokio::net::TcpListener::bind(address)
.await
.with_context(|| format!("Failed to bind app to given address: {address}"))
.unwrap();
tracing::trace!("Listening on {address}");
axum::serve::serve(listener, router)
.await
.expect("Failed to serve axum app");
let cb = move || {
let cfg = cfg.clone();
Box::pin(async move {
Ok(apply_base_path(
Router::new().serve_dioxus_application(cfg.clone(), original_root),
original_root,
cfg.clone(),
base_path().map(|s| s.to_string()),
))
}) as _
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.block_on(app_future);
} else {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(app_future);
}
unreachable!("Serving a fullstack app should never return")
serve_router(cb, dioxus_cli_config::fullstack_address_or_localhost()).await;
}
/// Create a router that serves the dioxus application at the appropriate base path.
@@ -319,3 +102,189 @@ pub fn router(app: fn() -> Element) -> Router {
base_path().map(|s| s.to_string()),
)
}
/// Serve a fullstack dioxus application with a custom axum router.
///
/// This function sets up an async runtime, enables the default dioxus logger, runs the provided initializer,
/// and then starts an axum server with the returned router.
///
/// The axum router will be bound to the address specified by the `IP` and `PORT` environment variables,
/// defaulting to `127.0.0.1:8080` if not set.
///
/// This function uses axum to block on serving the application, and will not return.
pub fn serve<F>(mut serve_it: impl FnMut() -> F) -> !
where
F: Future<Output = Result<Router, anyhow::Error>> + 'static,
{
let cb = move || Box::pin(serve_it()) as _;
block_on(
async move { serve_router(cb, dioxus_cli_config::fullstack_address_or_localhost()).await },
);
unreachable!("Serving a fullstack app should never return")
}
/// Serve a fullstack dioxus application with a custom axum router.
///
/// This function enables the dioxus logger and then serves the axum server with hot-reloading support.
///
/// To enable hot-reloading of the router, the provided `serve_callback` should return a new `Router`
/// each time it is called.
pub async fn serve_router(
mut serve_callback: impl FnMut() -> Pin<Box<dyn Future<Output = Result<Router, anyhow::Error>>>>,
addr: SocketAddr,
) {
dioxus_logger::initialize_default();
let listener = TcpListener::bind(addr)
.await
.with_context(|| format!("Failed to bind to address {addr}"))
.unwrap();
// If we're not in debug mode, just serve the app normally
if !cfg!(debug_assertions) {
axum::serve(listener, serve_callback().await.unwrap())
.await
.unwrap();
return;
}
// Wire up the devtools connection. The sender only sends messages in dev.
let (devtools_tx, mut devtools_rx) = futures_channel::mpsc::unbounded();
dioxus_devtools::connect(move |msg| _ = devtools_tx.unbounded_send(msg));
let mut hot_serve_callback = HotFn::current(serve_callback);
let mut make_service = hot_serve_callback
.call(())
.await
.map(|router| router.into_make_service())
.unwrap();
let (shutdown_tx, _) = tokio::sync::broadcast::channel(1);
let our_build_id = Some(dioxus_cli_config::build_id());
// Manually loop on accepting connections so we can also respond to devtools messages
loop {
let res = tokio::select! {
res = listener.accept() => Either::Left(res),
Some(msg) = devtools_rx.next(), if !devtools_rx.is_terminated() => Either::Right(msg),
else => continue
};
match res {
Either::Left(Ok((tcp_stream, _remote_addr))) => {
let mut make_service = make_service.clone();
let mut shutdown_rx = shutdown_tx.subscribe();
tokio::task::spawn(async move {
let tcp_stream = TokioIo::new(tcp_stream);
std::future::poll_fn(|cx| {
<IntoMakeService<Router> as tower::Service<Request>>::poll_ready(
&mut make_service,
cx,
)
})
.await
.expect("Infallible");
// upgrades needed for websockets
let builder = HyperBuilder::new(TokioExecutor::new());
let connection = builder.serve_connection_with_upgrades(
tcp_stream,
TowerToHyperService::new(
make_service
.call(())
.await
.unwrap()
.map_request(|req: Request<Incoming>| req.map(Body::new)),
),
);
tokio::select! {
res = connection => {
if let Err(_err) = res {
// This error only appears when the client doesn't send a request and
// terminate the connection.
//
// If client sends one request then terminate connection whenever, it doesn't
// appear.
}
}
_res = shutdown_rx.recv() => {}
}
});
}
// Handle just hot-patches for now.
// We don't do RSX hot-reload since usually the client handles that once the page is loaded.
//
// todo(jon): I *believe* SSR is resilient to RSX changes, but we should verify that...
Either::Right(DevserverMsg::HotReload(HotReloadMsg {
jump_table: Some(table),
for_build_id,
..
})) if for_build_id == our_build_id => {
// Apply the hot-reload patch to the dioxus devtools first
unsafe { dioxus_devtools::subsecond::apply_patch(table).unwrap() };
// Now recreate the router
// We panic here because we don't want their app to continue in a maybe-corrupted state
make_service = hot_serve_callback
.call(())
.await
.expect("Failed to create new router after hot-patch!")
.into_make_service();
// Make sure to wipe out the renderer state so we don't have stale elements
crate::document::reset_renderer();
_ = shutdown_tx.send(());
}
// Explicitly don't handle RSX hot-reloads on the server
// The client will handle that once the page is loaded. If we handled it here,
_ => {}
}
}
}
fn block_on<T>(app_future: impl Future<Output = T>) {
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.block_on(app_future);
} else {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(app_future);
}
}
fn apply_base_path<M: 'static>(
mut router: Router,
root: impl ComponentFunction<(), M> + Send + Sync,
cfg: ServeConfig,
base_path: Option<String>,
) -> Router {
if let Some(base_path) = base_path {
let base_path = base_path.trim_matches('/');
// If there is a base path, nest the router under it and serve the root route manually
// Nesting a route in axum only serves /base_path or /base_path/ not both
router = Router::new().nest(&format!("/{base_path}/"), router).route(
&format!("/{base_path}"),
axum::routing::method_routing::get(
|state: State<FullstackState>, mut request: Request<Body>| async move {
// The root of the base path always looks like the root from dioxus fullstack
*request.uri_mut() = "/".parse().unwrap();
FullstackState::render_handler(state, request).await
},
)
.with_state(FullstackState::new(cfg, root)),
)
}
router
}
+217 -175
View File
@@ -6,18 +6,177 @@ use axum::{
body::Body,
extract::State,
http::{Request, StatusCode},
response::IntoResponse,
response::Response,
response::{IntoResponse, Response},
routing::*,
};
use dioxus_core::{Element, VirtualDom};
use dioxus_core::{ComponentFunction, VirtualDom};
use http::header::*;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio_util::task::LocalPoolHandle;
use tower::util::MapResponse;
use tower::ServiceExt;
use tower_http::services::fs::ServeFileSystemResponseBody;
/// A extension trait with utilities for integrating Dioxus with your Axum router.
pub trait DioxusRouterExt {
/// Serves the static WASM for your Dioxus application (except the generated index.html).
///
/// # Example
/// ```rust, no_run
/// # #![allow(non_snake_case)]
/// # use dioxus::prelude::*;
/// use dioxus_server::DioxusRouterExt;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// let addr = dioxus::cli_config::fullstack_address_or_localhost();
/// let router = axum::Router::new()
/// // Server side render the application, serve static assets, and register server functions
/// .serve_static_assets()
/// // Server render the application
/// // ...
/// .with_state(dioxus_server::FullstackState::headless());
/// let listener = tokio::net::TcpListener::bind(addr).await?;
/// axum::serve(listener, router).await?;
/// Ok(())
/// }
/// ```
fn serve_static_assets(self) -> Router<FullstackState>;
/// Serves the Dioxus application. This will serve a complete server side rendered application.
/// This will serve static assets, server render the application, register server functions, and integrate with hot reloading.
///
/// # Example
/// ```rust, no_run
/// # #![allow(non_snake_case)]
/// # use dioxus::prelude::*;
/// use dioxus_server::{DioxusRouterExt, ServeConfig};
///
/// #[tokio::main]
/// async fn main() {
/// let addr = dioxus::cli_config::fullstack_address_or_localhost();
/// let router = axum::Router::new()
/// // Server side render the application, serve static assets, and register server functions
/// .serve_dioxus_application(ServeConfig::new(), app);
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
/// axum::serve(listener, router).await.unwrap();
/// }
///
/// fn app() -> Element {
/// rsx! { "Hello World" }
/// }
/// ```
fn serve_dioxus_application<M: 'static>(
self,
cfg: ServeConfig,
app: impl ComponentFunction<(), M> + Send + Sync,
) -> Router<()>;
/// Registers server functions with the default handler.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use dioxus_server::DioxusRouterExt;
/// #[tokio::main]
/// async fn main() {
/// let addr = dioxus::cli_config::fullstack_address_or_localhost();
/// let router = axum::Router::new()
/// // Register server functions routes with the default handler
/// .register_server_functions()
/// .with_state(dioxus_server::FullstackState::headless());
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
/// axum::serve(listener, router).await.unwrap();
/// }
/// ```
#[allow(dead_code)]
fn register_server_functions(self) -> Router<FullstackState>;
/// Serves a Dioxus application without static assets.
/// Sets up server function routes and rendering endpoints only.
///
/// Useful for WebAssembly environments or when static assets
/// are served by another system.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use dioxus_server::{DioxusRouterExt, ServeConfig};
/// #[tokio::main]
/// async fn main() {
/// let router = axum::Router::new()
/// .serve_api_application(ServeConfig::new(), app)
/// .into_make_service();
/// // ...
/// }
///
/// fn app() -> Element {
/// rsx! { "Hello World" }
/// }
/// ```
fn serve_api_application<M: 'static>(
self,
cfg: ServeConfig,
app: impl ComponentFunction<(), M> + Send + Sync,
) -> Router<()>
where
Self: Sized;
}
#[cfg(not(target_arch = "wasm32"))]
impl DioxusRouterExt for Router<FullstackState> {
fn register_server_functions(mut self) -> Router<FullstackState> {
use std::collections::HashSet;
let mut seen = HashSet::new();
for func in ServerFunction::collect() {
if seen.insert(format!("{} {}", func.method(), func.path())) {
tracing::info!(
"Registering server function: {} {}",
func.method(),
func.path()
);
self = self.route(func.path(), func.method_router())
}
}
self
}
fn serve_static_assets(self) -> Router<FullstackState> {
let Some(public_path) = public_path() else {
return self;
};
// Serve all files in public folder except index.html
serve_dir_cached(self, &public_path, &public_path)
}
fn serve_api_application<M: 'static>(
self,
cfg: ServeConfig,
app: impl ComponentFunction<(), M> + Send + Sync,
) -> Router<()> {
self.register_server_functions()
.fallback(get(FullstackState::render_handler))
.with_state(FullstackState::new(cfg, app))
}
fn serve_dioxus_application<M: 'static>(
self,
cfg: ServeConfig,
app: impl ComponentFunction<(), M> + Send + Sync,
) -> Router<()> {
self.register_server_functions()
.serve_static_assets()
.fallback(get(FullstackState::render_handler))
.with_state(FullstackState::new(cfg, app))
}
}
/// SSR renderer handler for Axum with added context injection.
///
/// # Example
@@ -27,7 +186,7 @@ use tower_http::services::fs::ServeFileSystemResponseBody;
///
/// use axum::routing::get;
/// use dioxus::prelude::*;
/// use dioxus_server::{RenderHandleState, render_handler, ServeConfig};
/// use dioxus_server::{FullstackState, render_handler, ServeConfig};
///
/// fn app() -> Element {
/// rsx! {
@@ -44,206 +203,89 @@ use tower_http::services::fs::ServeFileSystemResponseBody;
/// // to inject the context into server functions running outside
/// // of an SSR render context.
/// .fallback(get(render_handler))
/// .with_state(RenderHandleState::new(ServeConfig::new(), app));
/// .with_state(FullstackState::new(ServeConfig::new(), app));
///
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
/// axum::serve(listener, router).await.unwrap();
/// }
/// ```
pub async fn render_handler(
State(state): State<RenderHandleState>,
State(state): State<FullstackState>,
request: Request<Body>,
) -> impl IntoResponse {
RenderHandleState::render_handler(State(state), request).await
FullstackState::render_handler(State(state), request).await
}
/// A extension trait with utilities for integrating Dioxus with your Axum router.
pub trait DioxusRouterExt<S>: DioxusRouterFnExt<S> {
/// Serves the static WASM for your Dioxus application (except the generated index.html).
///
/// # Example
/// ```rust, no_run
/// # #![allow(non_snake_case)]
/// # use dioxus::prelude::*;
/// use dioxus_server::{DioxusRouterExt, DioxusRouterFnExt};
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// let addr = dioxus::cli_config::fullstack_address_or_localhost();
/// let router = axum::Router::new()
/// // Server side render the application, serve static assets, and register server functions
/// .serve_static_assets()
/// // Server render the application
/// // ...
/// .into_make_service();
/// let listener = tokio::net::TcpListener::bind(addr).await?;
/// axum::serve(listener, router).await?;
/// Ok(())
/// }
/// ```
fn serve_static_assets(self) -> Self
where
Self: Sized;
/// Serves the Dioxus application. This will serve a complete server side rendered application.
/// This will serve static assets, server render the application, register server functions, and integrate with hot reloading.
///
/// # Example
/// ```rust, no_run
/// # #![allow(non_snake_case)]
/// # use dioxus::prelude::*;
/// use dioxus_server::{DioxusRouterExt, DioxusRouterFnExt, ServeConfig};
///
/// #[tokio::main]
/// async fn main() {
/// let addr = dioxus::cli_config::fullstack_address_or_localhost();
/// let router = axum::Router::new()
/// // Server side render the application, serve static assets, and register server functions
/// .serve_dioxus_application(ServeConfig::new(), app)
/// .into_make_service();
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
/// axum::serve(listener, router).await.unwrap();
/// }
///
/// fn app() -> Element {
/// rsx! { "Hello World" }
/// }
/// ```
fn serve_dioxus_application(self, cfg: ServeConfig, app: fn() -> Element) -> Self
where
Self: Sized;
}
#[cfg(not(target_arch = "wasm32"))]
impl<S> DioxusRouterExt<S> for Router<S>
where
S: Send + Sync + Clone + 'static,
{
fn serve_static_assets(self) -> Self {
let Some(public_path) = public_path() else {
return self;
};
// Serve all files in public folder except index.html
serve_dir_cached(self, &public_path, &public_path)
}
fn serve_dioxus_application(self, cfg: ServeConfig, app: fn() -> Element) -> Self {
self.register_server_functions()
.serve_static_assets()
.fallback(
get(RenderHandleState::render_handler).with_state(RenderHandleState::new(cfg, app)),
)
}
}
/// A extension trait with server function utilities for integrating Dioxus with your Axum router.
pub trait DioxusRouterFnExt<S> {
/// Registers server functions with the default handler.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use dioxus_server::DioxusRouterFnExt;
/// #[tokio::main]
/// async fn main() {
/// let addr = dioxus::cli_config::fullstack_address_or_localhost();
/// let router = axum::Router::new()
/// // Register server functions routes with the default handler
/// .register_server_functions()
/// .into_make_service();
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
/// axum::serve(listener, router).await.unwrap();
/// }
/// ```
#[allow(dead_code)]
fn register_server_functions(self) -> Self
where
Self: Sized;
/// Serves a Dioxus application without static assets.
/// Sets up server function routes and rendering endpoints only.
///
/// Useful for WebAssembly environments or when static assets
/// are served by another system.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use dioxus_server::{DioxusRouterFnExt, ServeConfig};
/// #[tokio::main]
/// async fn main() {
/// let router = axum::Router::new()
/// .serve_api_application(ServeConfig::new(), app)
/// .into_make_service();
/// // ...
/// }
///
/// fn app() -> Element {
/// rsx! { "Hello World" }
/// }
/// ```
fn serve_api_application(self, cfg: ServeConfig, app: fn() -> Element) -> Self
where
Self: Sized;
}
impl<S: Send + Sync + Clone + 'static> DioxusRouterFnExt<S> for Router<S> {
fn register_server_functions(mut self) -> Self {
for func in ServerFunction::collect() {
tracing::info!(
"Registering server function: {} {}",
func.method(),
func.path()
);
self = func.register_server_fn_on_router(self);
}
self
}
fn serve_api_application(self, cfg: ServeConfig, app: fn() -> Element) -> Self
where
Self: Sized,
{
self.register_server_functions().fallback(
get(RenderHandleState::render_handler).with_state(RenderHandleState::new(cfg, app)),
)
}
}
/// State used by [`RenderHandleState::render_handler`] to render a dioxus component with axum
/// State used by [`FullstackState::render_handler`] to render a dioxus component with axum
#[derive(Clone)]
pub struct RenderHandleState {
pub struct FullstackState {
config: ServeConfig,
build_virtual_dom: Arc<dyn Fn() -> VirtualDom + Send + Sync>,
renderers: Arc<SsrRendererPool>,
pub(crate) rt: LocalPoolHandle,
}
impl RenderHandleState {
/// Create a new [`RenderHandleState`]
pub fn new(config: ServeConfig, root: fn() -> Element) -> Self {
impl FullstackState {
/// Create a headless [`FullstackState`] without a root component.
///
/// This won't render pages, but can still be used to register server functions and serve static assets.
pub fn headless() -> Self {
let rt = LocalPoolHandle::new(
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
);
Self {
renderers: Arc::new(SsrRendererPool::new(4, config.incremental.clone())),
build_virtual_dom: Arc::new(move || VirtualDom::new(root)),
config,
renderers: Arc::new(SsrRendererPool::new(4, None)),
build_virtual_dom: Arc::new(|| {
panic!("No root component provided for headless FullstackState")
}),
config: ServeConfig::new(),
rt,
}
}
/// Create a new [`RenderHandleState`] with a custom [`VirtualDom`] factory. This method can be
/// Create a new [`FullstackState`]
pub fn new<M: 'static>(
config: ServeConfig,
root: impl ComponentFunction<(), M> + Send + Sync + 'static,
) -> Self {
let rt = LocalPoolHandle::new(
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
);
Self {
renderers: Arc::new(SsrRendererPool::new(4, config.incremental.clone())),
build_virtual_dom: Arc::new(move || VirtualDom::new_with_props(root.clone(), ())),
config,
rt,
}
}
/// Create a new [`FullstackState`] with a custom [`VirtualDom`] factory. This method can be
/// used to pass context into the root component of your application.
pub fn new_with_virtual_dom_factory(
config: ServeConfig,
build_virtual_dom: impl Fn() -> VirtualDom + Send + Sync + 'static,
) -> Self {
let rt = LocalPoolHandle::new(
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
);
Self {
renderers: Arc::new(SsrRendererPool::new(4, config.incremental.clone())),
config,
build_virtual_dom: Arc::new(build_virtual_dom),
rt,
}
}
/// Set the [`ServeConfig`] for this [`RenderHandleState`]
/// Set the [`ServeConfig`] for this [`FullstackState`]
pub fn with_config(mut self, config: ServeConfig) -> Self {
self.config = config;
self
@@ -258,7 +300,7 @@ impl RenderHandleState {
///
/// use axum::routing::get;
/// use dioxus::prelude::*;
/// use dioxus_server::{RenderHandleState, render_handler, ServeConfig};
/// use dioxus_server::{FullstackState, render_handler, ServeConfig};
///
/// fn app() -> Element {
/// rsx! {
@@ -275,7 +317,7 @@ impl RenderHandleState {
/// // to inject the context into server functions running outside
/// // of an SSR render context.
/// .fallback(get(render_handler))
/// .with_state(RenderHandleState::new(ServeConfig::new(), app))
/// .with_state(FullstackState::new(ServeConfig::new(), app))
/// .into_make_service();
///
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
@@ -288,7 +330,7 @@ impl RenderHandleState {
let response = state
.renderers
.clone()
.render_to(parts, &state.config, {
.render_to(parts, &state.config, &state.rt, {
let build_virtual_dom = state.build_virtual_dom.clone();
let context_providers = state.config.context_providers.clone();
move || {
+98 -84
View File
@@ -1,35 +1,33 @@
use axum::body::Body;
use axum::routing::MethodRouter;
use axum::Router;
use dashmap::DashMap;
use dioxus_fullstack_core::{DioxusServerState, FullstackContext};
use http::Method;
use std::{marker::PhantomData, sync::LazyLock};
pub type AxumRequest = http::Request<Body>;
pub type AxumResponse = http::Response<Body>;
use crate::FullstackState;
use axum::{
body::Body,
extract::{Request, State},
response::Response,
routing::MethodRouter,
};
use dioxus_fullstack_core::FullstackContext;
use http::{Method, StatusCode};
use std::{pin::Pin, prelude::rust_2024::Future};
/// A function endpoint that can be called from the client.
#[derive(Clone)]
pub struct ServerFunction<Caller = ()> {
pub struct ServerFunction {
path: &'static str,
method: Method,
handler: fn() -> MethodRouter<DioxusServerState>,
_phantom: PhantomData<Caller>,
handler: fn() -> MethodRouter<FullstackState>,
}
impl ServerFunction {
/// Create a new server function object.
/// Create a new server function object from a MethodRouter
pub const fn new(
method: Method,
path: &'static str,
handler: fn() -> MethodRouter<DioxusServerState>,
handler: fn() -> MethodRouter<FullstackState>,
) -> Self {
Self {
path,
method,
handler,
_phantom: PhantomData,
}
}
@@ -43,72 +41,103 @@ impl ServerFunction {
self.method.clone()
}
/// Collect all globally registered server functions
pub fn collect() -> Vec<&'static ServerFunction> {
inventory::iter::<ServerFunction>().collect()
}
pub fn handler(&self) -> fn() -> MethodRouter<DioxusServerState> {
self.handler
/// Create a `MethodRouter` for this server function that can be mounted on an `axum::Router`.
///
/// This runs the handler inside the required `FullstackContext` scope and populates
/// `FullstackContext` so that the handler can use those features.
///
/// It also runs the server function inside a tokio `LocalPool` to allow !Send futures.
pub fn method_router(&self) -> MethodRouter<FullstackState> {
(self.handler)()
}
pub fn register_server_fn_on_router<S>(&'static self, router: Router<S>) -> Router<S>
where
S: Send + Sync + Clone + 'static,
{
// // store Accepts and Referrer in case we need them for redirect (below)
// let referrer = req.headers().get(REFERER).cloned();
// let accepts_html = req
// .headers()
// .get(ACCEPT)
// .and_then(|v| v.to_str().ok())
// .map(|v| v.contains("text/html"))
// .unwrap_or(false);
/// Creates a new `MethodRouter` for the given method and !Send handler.
///
/// This is used internally by the `ServerFunction` to create the method router that this
/// server function uses.
#[allow(clippy::type_complexity)]
pub fn make_handler(
method: Method,
handler: fn(State<FullstackContext>, Request) -> Pin<Box<dyn Future<Output = Response>>>,
) -> MethodRouter<FullstackState> {
axum::routing::method_routing::on(
method
.try_into()
.expect("MethodFilter only supports standard HTTP methods"),
move |state: State<FullstackState>, request: Request| async move {
// Allow !Send futures by running in the render handlers pinned local pool
let result = state.rt.spawn_pinned(move || async move {
use dioxus_fullstack_core::FullstackContext;
use http::header::{ACCEPT, LOCATION, REFERER};
use http::StatusCode;
// // it it accepts text/html (i.e., is a plain form post) and doesn't already have a
// // Location set, then redirect to Referer
// if accepts_html {
// if let Some(referrer) = referrer {
// let has_location = res.headers().get(LOCATION).is_some();
// if !has_location {
// *res.status_mut() = StatusCode::FOUND;
// res.headers_mut().insert(LOCATION, referrer);
// }
// }
// }
// todo: we're copying the parts here, but it'd be ideal if we didn't.
// We can probably just pass the URI in so the matching logic can work and then
// in the server function, do all extraction via FullstackContext. This ensures
// calls to `.remove()` work as expected.
let (parts, body) = request.into_parts();
let server_context = FullstackContext::new(parts.clone());
let request = axum::extract::Request::from_parts(parts, body);
async fn server_context_middleware(
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
let (parts, body) = request.into_parts();
let server_context = FullstackContext::new(parts.clone());
let request = axum::extract::Request::from_parts(parts, body);
// store Accepts and Referrer in case we need them for redirect (below)
let referrer = request.headers().get(REFERER).cloned();
let accepts_html = request
.headers()
.get(ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|v| v.contains("text/html"))
.unwrap_or(false);
server_context
.scope(async move {
// Run the next middleware / handler inside the server context
let mut response = next.run(request).await;
server_context
.clone()
.scope(async move {
// Run the next middleware / handler inside the server context
let mut response = handler(State(server_context), request).await;
let server_context = FullstackContext::current().expect(
"Server context should be available inside the server context scope",
);
let server_context = FullstackContext::current().expect(
"Server context should be available inside the server context scope",
);
// Get the extra response headers set during the handler and add them to the response
let headers = server_context.take_response_headers();
if let Some(headers) = headers {
response.headers_mut().extend(headers);
}
// Get the extra response headers set during the handler and add them to the response
let headers = server_context.take_response_headers();
if let Some(headers) = headers {
response.headers_mut().extend(headers);
}
response
})
.await
}
// it it accepts text/html (i.e., is a plain form post) and doesn't already have a
// Location set, then redirect to Referer
if accepts_html {
if let Some(referrer) = referrer {
let has_location = response.headers().get(LOCATION).is_some();
if !has_location {
*response.status_mut() = StatusCode::FOUND;
response.headers_mut().insert(LOCATION, referrer);
}
}
}
router.route(
self.path(),
((self.handler)())
.with_state(DioxusServerState {})
.layer(axum::middleware::from_fn(server_context_middleware)),
response
})
.await
}).await;
match result {
Ok(response) => response,
Err(err) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::new(if cfg!(debug_assertions) {
format!("Server function panicked: {}", err)
} else {
"Internal Server Error".to_string()
}))
.unwrap(),
}
},
)
}
}
@@ -120,18 +149,3 @@ impl inventory::Collect for ServerFunction {
&REGISTRY
}
}
/// The set of all registered server function paths.
pub fn server_fn_paths() -> impl Iterator<Item = (&'static str, Method)> {
REGISTERED_SERVER_FUNCTIONS
.iter()
.map(|item| (item.path(), item.method()))
}
type LazyServerFnMap = LazyLock<DashMap<(String, Method), ServerFunction>>;
static REGISTERED_SERVER_FUNCTIONS: LazyServerFnMap = std::sync::LazyLock::new(|| {
inventory::iter::<ServerFunction>
.into_iter()
.map(|obj| ((obj.path().to_string(), obj.method()), obj.clone()))
.collect()
});
+4 -31
View File
@@ -21,12 +21,11 @@ use http::{request::Parts, HeaderMap, StatusCode};
use std::{
collections::HashMap,
fmt::Write,
future::Future,
iter::Peekable,
rc::Rc,
sync::{Arc, RwLock},
};
use tokio::task::JoinHandle;
use tokio_util::task::LocalPoolHandle;
use crate::StreamingMode;
@@ -99,6 +98,7 @@ impl SsrRendererPool {
self: Arc<Self>,
parts: Parts,
cfg: &ServeConfig,
rt: &LocalPoolHandle,
virtual_dom_factory: impl FnOnce() -> VirtualDom + Send + Sync + 'static,
) -> Result<
(
@@ -420,7 +420,8 @@ impl SsrRendererPool {
myself.renderers.write().unwrap().push(renderer);
};
let join_handle = Self::spawn_platform(create_render_future);
// Spawn the render future onto the local pool
let join_handle = rt.spawn_pinned(create_render_future);
// Wait for the initial result which determines the status code
let (status, headers) = initial_result_rx
@@ -763,32 +764,4 @@ impl SsrRendererPool {
Ok(())
}
/// Spawn a task in the background. If wasm is enabled, this will use the single threaded tokio runtime
fn spawn_platform<Fut>(f: impl FnOnce() -> Fut + Send + 'static) -> JoinHandle<Fut::Output>
where
Fut: Future + 'static,
Fut::Output: Send + 'static,
{
#[cfg(not(target_arch = "wasm32"))]
{
use tokio_util::task::LocalPoolHandle;
static TASK_POOL: std::sync::OnceLock<LocalPoolHandle> = std::sync::OnceLock::new();
let pool = TASK_POOL.get_or_init(|| {
LocalPoolHandle::new(
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
)
});
pool.spawn_pinned(f)
}
#[cfg(target_arch = "wasm32")]
{
tokio::task::spawn_local(f())
}
}
}