Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(volo-http): use HashMap and FastStr for Params #329

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ motore = "0.4"

metainfo = "0.7"

ahash = "0.8"
anyhow = "1"
async-broadcast = "0.6"
async-stream = "0.3"
Expand Down
8 changes: 4 additions & 4 deletions examples/src/http/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use volo_http::{
middleware::{self, Next},
response::IntoResponse,
route::{from_handler, get, post, service_fn, MethodRouter, Router},
Address, BodyIncoming, Bytes, ConnectionInfo, CookieJar, HttpContext, Json, MaybeInvalid,
Method, Params, Response, Server, StatusCode, Uri,
Address, BodyIncoming, ConnectionInfo, CookieJar, HttpContext, Json, MaybeInvalid, Method,
Params, Response, Server, StatusCode, Uri,
};

async fn hello() -> &'static str {
Expand Down Expand Up @@ -103,9 +103,9 @@ async fn timeout_test() {
tokio::time::sleep(Duration::from_secs(10)).await
}

async fn echo(params: Params) -> Result<Bytes, StatusCode> {
async fn echo(params: Params) -> Result<FastStr, StatusCode> {
if let Some(echo) = params.get("echo") {
return Ok(echo.clone());
return Ok(echo.to_owned());
}
Err(StatusCode::BAD_REQUEST)
}
Expand Down
3 changes: 2 additions & 1 deletion volo-http/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "volo-http"
version = "0.1.12"
version = "0.1.13"
edition.workspace = true
homepage.workspace = true
repository.workspace = true
Expand All @@ -24,6 +24,7 @@ http-body-util = "0.1"
hyper = { version = "1", features = ["server", "http1", "http2"] }
hyper-util = { version = "0.1", features = ["tokio"] }

ahash.workspace = true
bytes.workspace = true
cookie = { workspace = true, optional = true, features = ["percent-encode"] }
faststr.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion volo-http/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::param::Params;
static X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host");
static X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto");

#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct HttpContext {
pub peer: Address,
pub method: Method,
Expand Down
47 changes: 21 additions & 26 deletions volo-http/src/param.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,34 @@
use std::slice::Iter;
use std::collections::{hash_map::Iter, HashMap};

use bytes::{BufMut, Bytes, BytesMut};
use ahash::RandomState;
use bytes::{BufMut, BytesMut};
use faststr::FastStr;

#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct Params {
pub(crate) inner: Vec<(Bytes, Bytes)>,
inner: HashMap<FastStr, FastStr, RandomState>,
}

impl From<matchit::Params<'_, '_>> for Params {
fn from(params: matchit::Params) -> Self {
let mut inner = Vec::with_capacity(params.len());
let mut capacity = 0;
for (k, v) in params.iter() {
capacity += k.len();
capacity += v.len();
}
impl Params {
pub(crate) fn extend(&mut self, params: matchit::Params<'_, '_>) {
self.inner.reserve(params.len());

let mut buf = BytesMut::with_capacity(capacity);
let cap = params.iter().map(|(k, v)| k.len() + v.len()).sum();
let mut buf = BytesMut::with_capacity(cap);

for (k, v) in params.iter() {
buf.put(k.as_bytes());
let k = buf.split().freeze();
// SAFETY: The key is from a valid string as path of router
let k = unsafe { FastStr::from_bytes_unchecked(buf.split().freeze()) };
buf.put(v.as_bytes());
let v = buf.split().freeze();
inner.push((k, v));
// SAFETY: The value is from a valid string as requested uri
let v = unsafe { FastStr::from_bytes_unchecked(buf.split().freeze()) };
if self.inner.insert(k, v).is_some() {
tracing::info!("[VOLO-HTTP] Conflicting key in param");
}
}

Self { inner }
}
}

impl Params {
pub fn len(&self) -> usize {
self.inner.len()
}
Expand All @@ -39,14 +37,11 @@ impl Params {
self.len() == 0
}

pub fn iter(&self) -> Iter<'_, (Bytes, Bytes)> {
pub fn iter(&self) -> Iter<'_, FastStr, FastStr> {
self.inner.iter()
}

pub fn get<K: AsRef<[u8]>>(&self, k: K) -> Option<&Bytes> {
self.iter()
.filter(|(ik, _)| ik.as_ref() == k.as_ref())
.map(|(_, v)| v)
.next()
pub fn get<K: Into<FastStr>>(&self, k: K) -> Option<&FastStr> {
self.inner.get(&k.into())
}
}
9 changes: 9 additions & 0 deletions volo-http/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
task::{Context, Poll},
};

use faststr::FastStr;
use futures_util::ready;
use http_body_util::Full;
use hyper::{
Expand Down Expand Up @@ -57,6 +58,14 @@ impl From<Bytes> for RespBody {
}
}

impl From<FastStr> for RespBody {
fn from(value: FastStr) -> Self {
Self {
inner: Full::new(value.into()),
}
}
}

impl From<String> for RespBody {
fn from(value: String) -> Self {
Self {
Expand Down
2 changes: 1 addition & 1 deletion volo-http/src/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ impl Service<HttpContext, Incoming> for Router<()> {
) -> Result<Self::Response, Self::Error> {
if let Ok(matched) = self.matcher.at(cx.uri.path()) {
if let Some(srv) = self.routes.get(matched.value) {
cx.params = matched.params.into();
cx.params.extend(matched.params);
return srv.call_with_state(cx, req, ()).await;
}
}
Expand Down
4 changes: 1 addition & 3 deletions volo-http/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,7 @@ async fn handle_conn<S>(
version: parts.version,
headers: parts.headers,
extensions: parts.extensions,
params: Params {
inner: Vec::with_capacity(0),
},
params: Params::default(),
};
let resp = match service.call(&mut cx, req).await {
Ok(resp) => resp,
Expand Down
Loading