bump server functions
This commit is contained in:
1 parent
6879507652
commit
e745212157
13 files changed
+297
-616
No files matched your search
@@ -57,61 +57,25 @@
|
||||
use axum::{
|
||||
body::{self, Body},
|
||||
extract::State,
|
||||
handler::Handler,
|
||||
http::{Request, Response, StatusCode},
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use dioxus_lib::prelude::VirtualDom;
|
||||
use server_fn::{Encoding, ServerFunctionRegistry};
|
||||
use server_fn::error::NoCustomError;
|
||||
use server_fn::error::ServerFnErrorSerde;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
use axum::routing::*;
|
||||
use http::header::*;
|
||||
|
||||
use crate::{
|
||||
prelude::*, render::SSRState, serve_config::ServeConfig, server_context::DioxusServerContext,
|
||||
server_fn::collection::DioxusServerFnRegistry,
|
||||
};
|
||||
|
||||
/// A extension trait with utilities for integrating Dioxus with your Axum router.
|
||||
pub trait DioxusRouterExt<S> {
|
||||
/// 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.
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// use dioxus_lib::prelude::*;
|
||||
/// use dioxus_fullstack::prelude::*;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
/// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
|
||||
/// axum::Server::bind(&addr)
|
||||
/// .serve(
|
||||
/// axum::Router::new()
|
||||
/// .register_server_fns_with_handler("", |func| {
|
||||
/// move |req: Request<Body>| async move {
|
||||
/// let (parts, body) = req.into_parts();
|
||||
/// let parts: Arc<http::request::Parts> = Arc::new(parts.into());
|
||||
/// let server_context = DioxusServerContext::new(parts.clone());
|
||||
/// server_fn_handler(server_context, func.clone(), parts, body).await
|
||||
/// }
|
||||
/// })
|
||||
/// .into_make_service(),
|
||||
/// )
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
fn register_server_fns_with_handler<H, T>(
|
||||
self,
|
||||
server_fn_route: &'static str,
|
||||
handler: impl FnMut(server_fn::ServerFnTraitObj<()>) -> H,
|
||||
) -> Self
|
||||
where
|
||||
H: Handler<T, S>,
|
||||
T: 'static,
|
||||
S: Clone + Send + Sync + 'static;
|
||||
|
||||
/// Registers server functions with the default handler. This handler function will pass an empty [`DioxusServerContext`] to your server functions.
|
||||
///
|
||||
/// # Example
|
||||
@@ -133,7 +97,7 @@ pub trait DioxusRouterExt<S> {
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
fn register_server_fns(self, server_fn_route: &'static str) -> Self;
|
||||
fn register_server_fns(self) -> Self;
|
||||
|
||||
/// 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`].
|
||||
///
|
||||
@@ -218,7 +182,6 @@ pub trait DioxusRouterExt<S> {
|
||||
/// ```
|
||||
fn serve_dioxus_application(
|
||||
self,
|
||||
server_fn_route: &'static str,
|
||||
cfg: impl Into<ServeConfig>,
|
||||
build_virtual_dom: impl Fn() -> VirtualDom + Send + Sync + 'static,
|
||||
) -> Self;
|
||||
@@ -228,51 +191,20 @@ impl<S> DioxusRouterExt<S> for Router<S>
|
||||
where
|
||||
S: Send + Sync + Clone + 'static,
|
||||
{
|
||||
fn register_server_fns_with_handler<H, T>(
|
||||
self,
|
||||
server_fn_route: &'static str,
|
||||
mut handler: impl FnMut(server_fn::ServerFnTraitObj<()>) -> H,
|
||||
) -> Self
|
||||
where
|
||||
H: Handler<T, S>,
|
||||
T: 'static,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
let mut router = self;
|
||||
for server_fn_path in DioxusServerFnRegistry::paths_registered() {
|
||||
let func = DioxusServerFnRegistry::get(server_fn_path).unwrap();
|
||||
let full_route = format!("{server_fn_route}/{server_fn_path}");
|
||||
match func.encoding() {
|
||||
Encoding::Url | Encoding::Cbor => {
|
||||
router = router.route(&full_route, post(handler(func)));
|
||||
}
|
||||
Encoding::GetJSON | Encoding::GetCBOR => {
|
||||
router = router.route(&full_route, get(handler(func)));
|
||||
}
|
||||
}
|
||||
}
|
||||
router
|
||||
}
|
||||
fn register_server_fns(mut self) -> Self {
|
||||
use http::method::Method;
|
||||
|
||||
fn register_server_fns(self, server_fn_route: &'static str) -> Self {
|
||||
self.register_server_fns_with_handler(server_fn_route, |func| {
|
||||
move |req: Request<Body>| {
|
||||
let mut service = crate::server_fn_service(Default::default(), func);
|
||||
async move {
|
||||
let (req, body) = req.into_parts();
|
||||
let req = Request::from_parts(req, body);
|
||||
let res = service.run(req);
|
||||
match res.await {
|
||||
Ok(res) => Ok::<_, std::convert::Infallible>(res.map(|b| b.into())),
|
||||
Err(e) => {
|
||||
let mut res = Response::new(Body::from(e.to_string()));
|
||||
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
for (path, method) in server_fn::axum::server_fn_paths() {
|
||||
let handler = move |req| handle_server_fns_inner(path, ||{}, req);
|
||||
self = match method {
|
||||
Method::GET => self.route(path, get(handler)),
|
||||
Method::POST => self.route(path, post(handler)),
|
||||
Method::PUT => self.route(path, put(handler)),
|
||||
_ => todo!()
|
||||
};
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
fn serve_static_assets(mut self, assets_path: impl Into<std::path::PathBuf>) -> Self {
|
||||
@@ -317,7 +249,6 @@ where
|
||||
|
||||
fn serve_dioxus_application(
|
||||
self,
|
||||
server_fn_route: &'static str,
|
||||
cfg: impl Into<ServeConfig>,
|
||||
build_virtual_dom: impl Fn() -> VirtualDom + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
@@ -327,7 +258,7 @@ where
|
||||
// Add server functions and render index.html
|
||||
self.serve_static_assets(cfg.assets_path.clone())
|
||||
.connect_hot_reload()
|
||||
.register_server_fns(server_fn_route)
|
||||
.register_server_fns()
|
||||
.fallback(get(render_handler).with_state((cfg, Arc::new(build_virtual_dom), ssr_state)))
|
||||
}
|
||||
|
||||
@@ -516,3 +447,104 @@ pub async fn hot_reload_handler(ws: axum::extract::WebSocketUpgrade) -> impl Int
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn get_local_pool() -> tokio_util::task::LocalPoolHandle {
|
||||
use once_cell::sync::OnceCell;
|
||||
static LOCAL_POOL: OnceCell<tokio_util::task::LocalPoolHandle> = OnceCell::new();
|
||||
LOCAL_POOL
|
||||
.get_or_init(|| {
|
||||
tokio_util::task::LocalPoolHandle::new(
|
||||
std::thread::available_parallelism()
|
||||
.map(Into::into)
|
||||
.unwrap_or(1),
|
||||
)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A handler for Dioxus server functions. This will run the server function and return the result.
|
||||
async fn handle_server_fns_inner(
|
||||
path: &str,
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
req: Request<Body>,
|
||||
) -> impl IntoResponse {
|
||||
use server_fn::middleware::Service;
|
||||
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let path_string = path.to_string();
|
||||
|
||||
get_local_pool().spawn_pinned(move || async move {
|
||||
let (parts, body) = req.into_parts();
|
||||
let req = Request::from_parts(parts.clone(), body);
|
||||
|
||||
|
||||
let res = if let Some(mut service) =
|
||||
server_fn::axum::get_server_fn_service(&path_string)
|
||||
{
|
||||
|
||||
let server_context = DioxusServerContext::new(Arc::new(RwLock::new(parts)));
|
||||
additional_context();
|
||||
|
||||
// store Accepts and Referrer in case we need them for redirect (below)
|
||||
let accepts_html = req
|
||||
.headers()
|
||||
.get(ACCEPT)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|v| v.contains("text/html"))
|
||||
.unwrap_or(false);
|
||||
let referrer = req.headers().get(REFERER).cloned();
|
||||
|
||||
// actually run the server fn
|
||||
let mut res = service.run(req).await;
|
||||
|
||||
|
||||
// it it accepts text/html (i.e., is a plain form post) and doesn't already have a
|
||||
// Location set, then redirect to 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// apply the response parts from the server context to the response
|
||||
let mut res_options = server_context.response_parts_mut().unwrap();
|
||||
res.headers_mut().extend(res_options.headers.drain());
|
||||
|
||||
Ok(res)
|
||||
} else {
|
||||
Response::builder().status(StatusCode::BAD_REQUEST).body(
|
||||
{
|
||||
#[cfg(target_family = "wasm")]
|
||||
{
|
||||
Body::from(format!(
|
||||
"No server function found for path: {path_string}\nYou may need to explicitly register the server function with `register_explicit`, rebuild your wasm binary to update a server function link or make sure the prefix your server and client use for server functions match.",
|
||||
))
|
||||
}
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
{
|
||||
Body::from(format!(
|
||||
"No server function found for path: {path_string}\nYou may need to rebuild your wasm binary to update a server function link or make sure the prefix your server and client use for server functions match.",
|
||||
))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
.expect("could not build Response");
|
||||
|
||||
_ = tx.send(res);
|
||||
});
|
||||
|
||||
rx.await.unwrap_or_else(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
ServerFnError::<NoCustomError>::ServerError(e.to_string())
|
||||
.ser()
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.into_response()
|
||||
})
|
||||
}
|
||||
@@ -129,7 +129,7 @@ impl Config {
|
||||
use tower::ServiceBuilder;
|
||||
|
||||
let ssr_state = SSRState::new(&cfg);
|
||||
let router = axum::Router::new().register_server_fns(server_fn_route);
|
||||
let router = axum::Router::new().register_server_fns();
|
||||
#[cfg(not(any(feature = "desktop", feature = "mobile")))]
|
||||
let router = router
|
||||
.serve_static_assets(cfg.assets_path.clone())
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
use std::pin::Pin;
|
||||
use tracing_futures::Instrument;
|
||||
|
||||
use http::{Request, Response};
|
||||
|
||||
/// A layer that wraps a service. This can be used to add additional information to the request, or response on top of some other service
|
||||
pub trait Layer: Send + Sync + 'static {
|
||||
/// Wrap a boxed service with this layer
|
||||
fn layer(&self, inner: BoxedService) -> BoxedService;
|
||||
}
|
||||
|
||||
impl<L> Layer for L
|
||||
where
|
||||
L: tower_layer::Layer<BoxedService> + Sync + Send + 'static,
|
||||
L::Service: Service + Send + 'static,
|
||||
{
|
||||
fn layer(&self, inner: BoxedService) -> BoxedService {
|
||||
BoxedService(Box::new(self.layer(inner)))
|
||||
}
|
||||
}
|
||||
|
||||
type MyBody = axum::body::Body;
|
||||
|
||||
/// A service is a function that takes a request and returns an async response
|
||||
pub trait Service {
|
||||
/// Run the service and produce a future that resolves to a response
|
||||
fn run(
|
||||
&mut self,
|
||||
req: http::Request<MyBody>,
|
||||
) -> Pin<
|
||||
Box<
|
||||
dyn std::future::Future<Output = Result<Response<MyBody>, server_fn::ServerFnError>>
|
||||
+ Send,
|
||||
>,
|
||||
>;
|
||||
}
|
||||
|
||||
impl<S> Service for S
|
||||
where
|
||||
S: tower::Service<http::Request<MyBody>, Response = Response<MyBody>>,
|
||||
S::Future: Send + 'static,
|
||||
S::Error: Into<server_fn::ServerFnError>,
|
||||
{
|
||||
fn run(
|
||||
&mut self,
|
||||
req: http::Request<MyBody>,
|
||||
) -> Pin<
|
||||
Box<
|
||||
dyn std::future::Future<Output = Result<Response<MyBody>, server_fn::ServerFnError>>
|
||||
+ Send,
|
||||
>,
|
||||
> {
|
||||
let fut = self.call(req).instrument(tracing::trace_span!(
|
||||
"service",
|
||||
"{}",
|
||||
std::any::type_name::<S>()
|
||||
));
|
||||
Box::pin(async move { fut.await.map_err(|err| err.into()) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A boxed service is a type-erased service that can be used without knowing the underlying type
|
||||
pub struct BoxedService(pub Box<dyn Service + Send>);
|
||||
|
||||
impl tower::Service<http::Request<MyBody>> for BoxedService {
|
||||
type Response = http::Response<MyBody>;
|
||||
type Error = server_fn::ServerFnError;
|
||||
type Future = Pin<
|
||||
Box<
|
||||
dyn std::future::Future<
|
||||
Output = Result<http::Response<MyBody>, server_fn::ServerFnError>,
|
||||
> + Send,
|
||||
>,
|
||||
>;
|
||||
|
||||
fn poll_ready(
|
||||
&mut self,
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Result<(), Self::Error>> {
|
||||
Ok(()).into()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<MyBody>) -> Self::Future {
|
||||
self.0.run(req)
|
||||
}
|
||||
}
|
||||
@@ -12,21 +12,14 @@ mod html_storage;
|
||||
#[cfg(feature = "axum")]
|
||||
mod axum_adapter;
|
||||
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
#[cfg(feature = "server")]
|
||||
pub use server_fn::service::{server_fn_service, ServerFnHandler};
|
||||
|
||||
mod config;
|
||||
mod hooks;
|
||||
pub mod launch;
|
||||
mod server_fn;
|
||||
|
||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
||||
mod hot_reload;
|
||||
pub use config::*;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod layer;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod render;
|
||||
@@ -50,10 +43,6 @@ pub mod prelude {
|
||||
#[cfg_attr(docsrs, doc(cfg(not(feature = "server"))))]
|
||||
pub use crate::html_storage::deserialize::get_root_props_from_document;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
pub use crate::layer::{Layer, Service};
|
||||
|
||||
#[cfg(all(feature = "server", feature = "router"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "server", feature = "router"))))]
|
||||
pub use crate::render::pre_cache_static_routes_with_props;
|
||||
@@ -79,17 +68,13 @@ pub mod prelude {
|
||||
pub use crate::server_context::{
|
||||
extract, server_context, DioxusServerContext, FromServerContext, ProvideServerContext,
|
||||
};
|
||||
pub use crate::server_fn::DioxusServerFn;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
pub use crate::server_fn::collection::{ServerFnMiddleware, ServerFnTraitObj, ServerFunction};
|
||||
pub use dioxus_server_macro::*;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
pub use dioxus_ssr::incremental::IncrementalRendererConfig;
|
||||
|
||||
pub use server_fn::{self, ServerFn as _, ServerFnError};
|
||||
pub use dioxus_server_macro::*;
|
||||
}
|
||||
|
||||
// // Warn users about overlapping features
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
#[cfg(feature = "server")]
|
||||
pub(crate)mod collection;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod service;
|
||||
|
||||
/// Defines a "server function." A server function can be called from the server or the client,
|
||||
/// but the body of its code will only be run on the server, i.e., if a crate feature `ssr` is enabled.
|
||||
///
|
||||
/// Server functions are created using the `server` macro.
|
||||
///
|
||||
/// The set of server functions
|
||||
/// can be queried on the server for routing purposes by calling [server_fn::ServerFunctionRegistry::get].
|
||||
///
|
||||
/// Technically, the trait is implemented on a type that describes the server function's arguments, not the function itself.
|
||||
pub trait DioxusServerFn: server_fn::ServerFn<()> {
|
||||
/// Registers the server function, allowing the client to query it by URL.
|
||||
#[cfg(feature = "server")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
|
||||
fn register_explicit() -> Result<(), server_fn::ServerFnError> {
|
||||
Self::register_in_explicit::<crate::server_fn::collection::DioxusServerFnRegistry>()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DioxusServerFn for T where T: server_fn::ServerFn<()> {}
|
||||
@@ -1,154 +0,0 @@
|
||||
//! # Server function Service
|
||||
|
||||
//! This module defines a service that can be used to handle server functions.
|
||||
|
||||
use http::StatusCode;
|
||||
use server_fn::{Encoding, Payload};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use crate::server_fn::collection::MIDDLEWARE;
|
||||
use crate::{
|
||||
layer::{BoxedService, Service},
|
||||
prelude::{DioxusServerContext, ProvideServerContext},
|
||||
};
|
||||
|
||||
type AxumBody = axum::body::Body;
|
||||
|
||||
/// Create a server function handler with the given server context and server function.
|
||||
pub fn server_fn_service(
|
||||
context: DioxusServerContext,
|
||||
function: server_fn::ServerFnTraitObj<()>,
|
||||
) -> crate::layer::BoxedService {
|
||||
let prefix = function.prefix().to_string();
|
||||
let url = function.url().to_string();
|
||||
if let Some(middleware) = MIDDLEWARE.get(&(&prefix, &url)) {
|
||||
let mut service = BoxedService(Box::new(ServerFnHandler::new(context, function)));
|
||||
for middleware in middleware {
|
||||
service = middleware.layer(service);
|
||||
}
|
||||
service
|
||||
} else {
|
||||
BoxedService(Box::new(ServerFnHandler::new(context, function)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
/// A default handler for server functions. It will deserialize the request body, call the server function, and serialize the response.
|
||||
pub struct ServerFnHandler {
|
||||
server_context: DioxusServerContext,
|
||||
function: server_fn::ServerFnTraitObj<()>,
|
||||
}
|
||||
|
||||
impl ServerFnHandler {
|
||||
/// Create a new server function handler with the given server context and server function.
|
||||
pub fn new(
|
||||
server_context: impl Into<DioxusServerContext>,
|
||||
function: server_fn::ServerFnTraitObj<()>,
|
||||
) -> Self {
|
||||
let server_context = server_context.into();
|
||||
Self {
|
||||
server_context,
|
||||
function,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service for ServerFnHandler {
|
||||
fn run(
|
||||
&mut self,
|
||||
req: http::Request<AxumBody>,
|
||||
) -> std::pin::Pin<
|
||||
Box<
|
||||
dyn std::future::Future<
|
||||
Output = Result<http::Response<AxumBody>, server_fn::ServerFnError>,
|
||||
> + Send,
|
||||
>,
|
||||
> {
|
||||
let Self {
|
||||
server_context,
|
||||
function,
|
||||
} = self.clone();
|
||||
Box::pin(async move {
|
||||
let query = req.uri().query().unwrap_or_default().as_bytes().to_vec();
|
||||
let (parts, body) = req.into_parts();
|
||||
let body = axum::body::to_bytes(body, usize::MAX).await?.to_vec();
|
||||
let headers = &parts.headers;
|
||||
let accept_header = headers.get("Accept").cloned();
|
||||
let parts = Arc::new(RwLock::new(parts));
|
||||
|
||||
// Because the future returned by `server_fn_handler` is `Send`, and the future returned by this function must be send, we need to spawn a new runtime
|
||||
let pool = get_local_pool();
|
||||
let result = pool
|
||||
.spawn_pinned({
|
||||
let function = function.clone();
|
||||
let mut server_context = server_context.clone();
|
||||
server_context.parts = parts;
|
||||
move || async move {
|
||||
let data = match function.encoding() {
|
||||
Encoding::Url | Encoding::Cbor => &body,
|
||||
Encoding::GetJSON | Encoding::GetCBOR => &query,
|
||||
};
|
||||
let server_function_future = function.call((), data);
|
||||
let server_function_future = ProvideServerContext::new(
|
||||
server_function_future,
|
||||
server_context.clone(),
|
||||
);
|
||||
server_function_future.await
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
let mut res = http::Response::builder();
|
||||
|
||||
// Set the headers from the server context
|
||||
let parts = server_context.response_parts().unwrap();
|
||||
*res.headers_mut().expect("empty headers should be valid") = parts.headers.clone();
|
||||
|
||||
let serialized = result?;
|
||||
// if this is Accept: application/json then send a serialized JSON response
|
||||
let accept_header = accept_header.as_ref().and_then(|value| value.to_str().ok());
|
||||
if accept_header == Some("application/json")
|
||||
|| accept_header
|
||||
== Some(
|
||||
"application/\
|
||||
x-www-form-urlencoded",
|
||||
)
|
||||
|| accept_header == Some("application/cbor")
|
||||
{
|
||||
res = res.status(StatusCode::OK);
|
||||
}
|
||||
|
||||
Ok(match serialized {
|
||||
Payload::Binary(data) => {
|
||||
res = res.header("Content-Type", "application/cbor");
|
||||
res.body(data.into())?
|
||||
}
|
||||
Payload::Url(data) => {
|
||||
res = res.header(
|
||||
"Content-Type",
|
||||
"application/\
|
||||
x-www-form-urlencoded",
|
||||
);
|
||||
res.body(data.into())?
|
||||
}
|
||||
Payload::Json(data) => {
|
||||
res = res.header("Content-Type", "application/json");
|
||||
res.body(data.into())?
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn get_local_pool() -> tokio_util::task::LocalPoolHandle {
|
||||
use once_cell::sync::OnceCell;
|
||||
static LOCAL_POOL: OnceCell<tokio_util::task::LocalPoolHandle> = OnceCell::new();
|
||||
LOCAL_POOL
|
||||
.get_or_init(|| {
|
||||
tokio_util::task::LocalPoolHandle::new(
|
||||
std::thread::available_parallelism()
|
||||
.map(Into::into)
|
||||
.unwrap_or(1),
|
||||
)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
Reference in new issue
Block a user