Skip to content

Commit

Permalink
[xitca-web] add missing bench category. (#8607)
Browse files Browse the repository at this point in the history
  • Loading branch information
fakeshadow authored Dec 11, 2023
1 parent 8edadc3 commit 644b886
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 50 deletions.
18 changes: 9 additions & 9 deletions frameworks/Rust/xitca-web/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 14 additions & 12 deletions frameworks/Rust/xitca-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ required-features = ["web"]
[[bin]]
name = "xitca-web-axum"
path = "./src/main_axum.rs"
required-features = ["axum", "io-uring"]
required-features = ["axum", "io-uring", "pg-sync", "template"]

[features]
# pg optional
pg = ["xitca-postgres"]
pg = ["xitca-postgres/single-thread"]
# pg send/sync optional
pg-sync = ["xitca-postgres"]
# pg io_uring optional
pg-iou = ["xitca-postgres/io-uring"]
pg-iou = ["pg", "xitca-postgres/io-uring"]
# http router optional
router = ["xitca-http/router"]
# web optional
Expand All @@ -54,7 +56,7 @@ serde_json = { version = "1" }
xitca-web = { version = "0.1", features = ["json"], optional = true }

# raw-pg optional
xitca-postgres = { version = "0.1", features = ["single-thread"], optional = true }
xitca-postgres = { version = "0.1", optional = true }

# template optional
sailfish = { version = "0.8", default-features = false, features = ["derive", "perf-inline"], optional = true }
Expand All @@ -80,13 +82,13 @@ codegen-units = 1
panic = "abort"

[patch.crates-io]
xitca-http = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-io = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-postgres = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-router = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-server = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-service = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-unsafe-collection = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-web = { git = "https://github.com/HFQR/xitca-web.git", rev = "23ad63cbb3a853a548bd447cc59625a5d7c5833e" }
xitca-http = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-io = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-postgres = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-router = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-server = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-service = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-unsafe-collection = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }
xitca-web = { git = "https://github.com/HFQR/xitca-web.git", rev = "263ea4e01f8f840dfdb3b82ba804d7b0912d5e7f" }

mio = { git = "https://github.com/fakeshadow/mio.git", rev = "52b72d372bfe5807755b7f5e3e1edf282954d6ba" }
10 changes: 7 additions & 3 deletions frameworks/Rust/xitca-web/benchmark_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,14 @@
"axum": {
"json_url": "/json",
"plaintext_url": "/plaintext",
"db_url": "/db",
"fortune_url": "/fortunes",
"query_url": "/queries?q=",
"update_url": "/updates?q=",
"port": 8080,
"approach": "Realistic",
"classification": "Micro",
"database": "none",
"approach": "realistic",
"classification": "micro",
"database": "postgres",
"framework": "axum [xitca]",
"language": "rust",
"orm": "raw",
Expand Down
30 changes: 23 additions & 7 deletions frameworks/Rust/xitca-web/src/db.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{cell::RefCell, collections::HashMap, fmt::Write, future::IntoFuture};
use std::{collections::HashMap, fmt::Write, future::IntoFuture};

use xitca_postgres::{statement::Statement, AsyncIterator, Postgres};
use xitca_unsafe_collection::no_hash::NoHashBuilder;
Expand All @@ -10,7 +10,10 @@ use super::{

pub struct Client {
client: xitca_postgres::Client,
rng: RefCell<Rand>,
#[cfg(not(feature = "pg-sync"))]
rng: std::cell::RefCell<Rand>,
#[cfg(feature = "pg-sync")]
rng: std::sync::Mutex<Rand>,
fortune: Statement,
world: Statement,
updates: HashMap<u16, Statement, NoHashBuilder>,
Expand All @@ -29,7 +32,7 @@ impl Drop for Client {
pub async fn create(config: &str) -> HandleResult<Client> {
let (client, driver) = Postgres::new(config.to_string()).connect().await?;

tokio::task::spawn_local(tokio::task::unconstrained(driver.into_future()));
tokio::spawn(tokio::task::unconstrained(driver.into_future()));

let fortune = client.prepare("SELECT * FROM fortune", &[]).await?.leak();

Expand Down Expand Up @@ -62,16 +65,29 @@ pub async fn create(config: &str) -> HandleResult<Client> {

Ok(Client {
client,
rng: RefCell::new(Rand::default()),
#[cfg(not(feature = "pg-sync"))]
rng: std::cell::RefCell::new(Rand::default()),
#[cfg(feature = "pg-sync")]
rng: std::sync::Mutex::new(Rand::default()),
fortune,
world,
updates,
})
}

impl Client {
#[cfg(not(feature = "pg-sync"))]
fn borrow_rng_mut(&self) -> std::cell::RefMut<'_, Rand> {
self.rng.borrow_mut()
}

#[cfg(feature = "pg-sync")]
fn borrow_rng_mut(&self) -> std::sync::MutexGuard<'_, Rand> {
self.rng.lock().unwrap()
}

pub async fn get_world(&self) -> HandleResult<World> {
let id = self.rng.borrow_mut().gen_id();
let id = self.borrow_rng_mut().gen_id();
self.client
.query_raw(&self.world, [id])
.await?
Expand All @@ -86,7 +102,7 @@ impl Client {
let mut pipe = self.client.pipeline();

{
let mut rng = self.rng.borrow_mut();
let mut rng = self.borrow_rng_mut();
(0..num).try_for_each(|_| pipe.query_raw(&self.world, [rng.gen_id()]))?;
}

Expand All @@ -112,7 +128,7 @@ impl Client {
let mut pipe = self.client.pipeline();

{
let mut rng = self.rng.borrow_mut();
let mut rng = self.borrow_rng_mut();
(0..num).try_for_each(|_| {
let w_id = rng.gen_id();
let r_id = rng.gen_id();
Expand Down
80 changes: 67 additions & 13 deletions frameworks/Rust/xitca-web/src/main_axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,47 @@
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

mod db;
mod ser;
mod util;

use std::sync::Arc;

use axum::{
http::header::{HeaderValue, SERVER},
response::IntoResponse,
body::Bytes,
extract::{Json, OriginalUri as Uri, State},
http::{
header::{HeaderValue, SERVER},
StatusCode,
},
response::{Html, IntoResponse, Response},
routing::{get, Router},
Json,
};
use tower_http::set_header::SetResponseHeaderLayer;

use crate::tower_compat::TowerHttp;
use crate::{
db::Client,
tower_compat::TowerHttp,
util::{QueryParse, DB_URL},
};

fn main() -> std::io::Result<()> {
let service = TowerHttp::service(|| async {
Router::new()
let cli = db::create(DB_URL).await?;
let service = Router::new()
.route("/plaintext", get(plain_text))
.route("/json", get(json))
.route("/db", get(db))
.route("/fortunes", get(fortunes))
.route("/queries", get(queries))
.route("/updates", get(updates))
.with_state(Arc::new(cli))
.layer(SetResponseHeaderLayer::if_not_present(
SERVER,
HeaderValue::from_static("A"),
))
));
Ok(service)
});

xitca_server::Builder::new()
.bind("xitca-axum", "0.0.0.0:8080", service)?
.build()
Expand All @@ -41,10 +58,48 @@ async fn json() -> impl IntoResponse {
Json(ser::Message::new())
}

async fn db(State(cli): State<Arc<Client>>) -> impl IntoResponse {
cli.get_world().await.map(Json).map_err(Error)
}

async fn fortunes(State(cli): State<Arc<Client>>) -> impl IntoResponse {
use sailfish::TemplateOnce;
cli.tell_fortune()
.await
.map_err(Error)?
.render_once()
.map(Html)
.map_err(|e| Error(Box::new(e)))
}

async fn queries(State(cli): State<Arc<Client>>, Uri(uri): Uri) -> impl IntoResponse {
cli.get_worlds(uri.query().parse_query())
.await
.map(Json)
.map_err(Error)
}

async fn updates(State(cli): State<Arc<Client>>, Uri(uri): Uri) -> impl IntoResponse {
cli.update(uri.query().parse_query())
.await
.map(Json)
.map_err(Error)
}

struct Error(util::Error);

impl IntoResponse for Error {
fn into_response(self) -> Response {
let mut res = Bytes::new().into_response();
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
res
}
}

// compat module between xitca-http and axum.
mod tower_compat {
use std::{
cell::RefCell,
convert::Infallible,
error, fmt,
future::Future,
io,
Expand Down Expand Up @@ -78,24 +133,23 @@ mod tower_compat {

impl<S, B> TowerHttp<S, B> {
pub fn service<F, Fut>(
service: F,
func: F,
) -> impl Service<
Response = impl ReadyService + Service<(TcpStream, SocketAddr)>,
Error = impl fmt::Debug,
>
where
F: Fn() -> Fut + Send + Sync + Clone,
Fut: Future<Output = S>,
Fut: Future<Output = Result<S, crate::util::Error>>,
S: tower::Service<Request<_RequestBody>, Response = Response<B>>,
S::Error: fmt::Debug,
B: Body<Data = Bytes> + Send + 'static,
B::Error: error::Error + Send + Sync,
{
fn_build(move |_| {
let service = service.clone();
let func = func.clone();
async move {
let service = service().await;
Ok::<_, Infallible>(TowerHttp {
func().await.map(|service| TowerHttp {
service: RefCell::new(service),
_p: PhantomData,
})
Expand Down
4 changes: 1 addition & 3 deletions frameworks/Rust/xitca-web/src/main_wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ use xitca_web::{
App,
};

use self::util::SERVER_HEADER_VALUE;

fn main() -> io::Result<()> {
let fd = env::var("FD_COUNT")
.ok()
Expand Down Expand Up @@ -44,7 +42,7 @@ where
S: for<'r> Service<WebRequest<'r>, Response = WebResponse, Error = E>,
{
service.call(ctx).await.map(|mut res| {
res.headers_mut().append(SERVER, SERVER_HEADER_VALUE);
res.headers_mut().append(SERVER, util::SERVER_HEADER_VALUE);
res
})
}
2 changes: 0 additions & 2 deletions frameworks/Rust/xitca-web/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
pub type HandleResult<T> = Result<T, Error>;

#[cfg(not(target_arch = "wasm32"))]
#[cfg(any(feature = "pg", feature = "pg-iou"))]
mod non_wasm {
use core::{cell::RefCell, future::Future, pin::Pin};

Expand Down Expand Up @@ -77,5 +76,4 @@ mod non_wasm {
}

#[cfg(not(target_arch = "wasm32"))]
#[cfg(any(feature = "pg", feature = "pg-iou"))]
pub use non_wasm::*;
2 changes: 1 addition & 1 deletion frameworks/Rust/xitca-web/xitca-web-axum.dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ FROM rust:1.74
ADD ./ /xitca-web
WORKDIR /xitca-web

RUN cargo build --release --bin xitca-web-axum --features axum,io-uring
RUN cargo build --release --bin xitca-web-axum --features axum,io-uring,pg-sync,template

EXPOSE 8080

Expand Down

0 comments on commit 644b886

Please sign in to comment.