From 7e1f8500dbe758657a85bfc5bbd496de286a65ac Mon Sep 17 00:00:00 2001 From: Antonio Pitasi Date: Fri, 8 Sep 2023 15:28:01 +0200 Subject: [PATCH] axum integration --- Cargo.toml | 6 +++--- rscx/Cargo.toml | 5 +++++ rscx/src/axum.rs | 26 ++++++++++++++++++++++++++ rscx/src/lib.rs | 2 ++ 4 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 rscx/src/axum.rs diff --git a/Cargo.toml b/Cargo.toml index b52756f..70207e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,8 +7,8 @@ members = [ ] [workspace.package] -version = "0.1.3" +version = "0.1.4" [workspace.dependencies] -rscx = { path = "./rscx", version = "0.1.3" } -rscx-macros = { path = "./rscx-macros", version = "0.1.3" } +rscx = { path = "./rscx", version = "0.1.4" } +rscx-macros = { path = "./rscx-macros", version = "0.1.4" } diff --git a/rscx/Cargo.toml b/rscx/Cargo.toml index 965560f..cd48558 100644 --- a/rscx/Cargo.toml +++ b/rscx/Cargo.toml @@ -11,7 +11,12 @@ readme = "../README.md" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +axum = { version = "0.6.20", features = ["macros"], optional = true } rscx-macros = { workspace = true } tokio = { version = "1.32.0", features = ["full"] } +tokio-util = { version = "0.7.8", features = ["rt"], optional = true } typed-builder = "0.16.0" +[features] +default = [] +axum = ["dep:axum", "dep:tokio-util"] diff --git a/rscx/src/axum.rs b/rscx/src/axum.rs new file mode 100644 index 0000000..abf8139 --- /dev/null +++ b/rscx/src/axum.rs @@ -0,0 +1,26 @@ +use axum::response::Html; +use std::{future::Future, sync::OnceLock, thread::available_parallelism}; +use tokio_util::task::LocalPoolHandle; + +use crate::context; + +fn get_rendering_pool() -> LocalPoolHandle { + static LOCAL_POOL: OnceLock = OnceLock::new(); + LOCAL_POOL + .get_or_init(|| LocalPoolHandle::new(available_parallelism().map(Into::into).unwrap_or(1))) + .clone() +} + +pub async fn render(f: F) -> Html +where + F: Future + Send + 'static, + O: Send + 'static, +{ + get_rendering_pool() + .spawn_pinned(move || async { + let h = context::spawn_local(f).await.unwrap(); + Html(h) + }) + .await + .unwrap() +} diff --git a/rscx/src/lib.rs b/rscx/src/lib.rs index 45c9523..c0a2cd5 100644 --- a/rscx/src/lib.rs +++ b/rscx/src/lib.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "axum")] +pub mod axum; pub mod context; pub extern crate rscx_macros;