Skip to content

Commit

Permalink
bump: v0.4.2
Browse files Browse the repository at this point in the history
  • Loading branch information
fundon committed Oct 4, 2022
1 parent 3ea0124 commit 4c7a0e9
Show file tree
Hide file tree
Showing 14 changed files with 107 additions and 94 deletions.
2 changes: 1 addition & 1 deletion examples/websocket-chat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"
publish = false

[dependencies]
viz = { path = "../../viz", features = ["params", "websocket"] }
viz = { path = "../../viz", features = ["websocket"] }

tokio = { version = "1.0", features = ["rt", "rt-multi-thread", "macros"] }
futures-util = "0.3.21"
2 changes: 1 addition & 1 deletion viz-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "viz-core"
version = "0.4.1"
version = "0.4.2"
edition = "2021"
rust-version = "1.60"
license = "MIT OR Apache-2.0"
Expand Down
2 changes: 1 addition & 1 deletion viz-core/src/middleware/otel/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ where
async fn call(&self, req: Request) -> Self::Output {
let timer = SystemTime::now();
let cx = Context::current();
let mut attributes = build_attributes(&req, &req.route().path);
let mut attributes = build_attributes(&req, &req.route_info().pattern);

self.active_requests.add(&cx, 1, &attributes);

Expand Down
2 changes: 1 addition & 1 deletion viz-core/src/middleware/otel/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ where
propagator.extract(&RequestHeaderCarrier::new(req.headers()))
});

let http_route = &req.route().path;
let http_route = &req.route_info().pattern;
let attributes = build_attributes(&req, http_route);

let mut span = self
Expand Down
22 changes: 7 additions & 15 deletions viz-core/src/request.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::mem::replace;
use std::{mem::replace, sync::Arc};

use crate::{
async_trait, header,
types::{PayloadError, Route},
types::{PayloadError, RouteInfo},
Body, Bytes, FromRequest, Request, Result,
};

Expand Down Expand Up @@ -30,7 +30,7 @@ use crate::types::{Cookie, Cookies, CookiesError};
use crate::types::Session;

#[cfg(feature = "params")]
use crate::types::{Params, ParamsError, PathDeserializer};
use crate::types::{ParamsError, PathDeserializer};

/// The [Request] Extension.
#[async_trait]
Expand Down Expand Up @@ -151,7 +151,7 @@ pub trait RequestExt: Sized {
T::Err: std::fmt::Display;

/// Get current route.
fn route(&self) -> &Route;
fn route_info(&self) -> &Arc<RouteInfo>;

/// Get remote addr.
fn remote_addr(&self) -> Option<&std::net::SocketAddr>;
Expand Down Expand Up @@ -341,12 +341,7 @@ impl RequestExt for Request<Body> {
where
T: serde::de::DeserializeOwned,
{
match self.extensions().get::<Params>() {
None => Err(ParamsError::Empty),
Some(params) => {
T::deserialize(PathDeserializer::new(params)).map_err(ParamsError::Parse)
}
}
T::deserialize(PathDeserializer::new(&self.route_info().params)).map_err(ParamsError::Parse)
}

#[cfg(feature = "params")]
Expand All @@ -355,17 +350,14 @@ impl RequestExt for Request<Body> {
T: std::str::FromStr,
T::Err: std::fmt::Display,
{
self.extensions()
.get::<Params>()
.ok_or(ParamsError::Empty)?
.find(name)
self.route_info().params.find(name)
}

fn remote_addr(&self) -> Option<&std::net::SocketAddr> {
self.extensions().get()
}

fn route(&self) -> &Route {
fn route_info(&self) -> &Arc<RouteInfo> {
self.extensions().get().expect("should get current route")
}
}
4 changes: 2 additions & 2 deletions viz-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ pub use websocket::{Message, WebSocket, WebSocketConfig, WebSocketError, WebSock
mod header;
mod payload;
mod realip;
mod route;
mod route_info;

pub use header::{Header, HeaderError};
pub use payload::{Payload, PayloadError};
pub use realip::RealIp;
pub use route::Route;
pub use route_info::RouteInfo;
15 changes: 0 additions & 15 deletions viz-core/src/types/route.rs

This file was deleted.

12 changes: 12 additions & 0 deletions viz-core/src/types/route_info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use crate::types::Params;

/// Current route information.
#[derive(Debug)]
pub struct RouteInfo {
/// Route ID
pub id: usize,
/// Route Pattern
pub pattern: String,
/// Route Params
pub params: Params,
}
4 changes: 2 additions & 2 deletions viz-handlers/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "viz-handlers"
version = "0.3.1"
version = "0.3.2"
edition = "2021"
rust-version = "1.60"
license = "MIT OR Apache-2.0"
Expand Down Expand Up @@ -28,7 +28,7 @@ embed = ["dep:hex", "dep:mime_guess", "dep:rust-embed"]
prometheus = ["opentelemetry/metrics", "dep:opentelemetry-prometheus"]

[dependencies]
viz-core = { path = "../viz-core", version = '0.4.1' }
viz-core = { path = "../viz-core", version = '0.4.2' }

# required!
thiserror = "1.0"
Expand Down
6 changes: 3 additions & 3 deletions viz-router/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "viz-router"
version = "0.4.1"
version = "0.4.2"
edition = "2021"
rust-version = "1.60"
license = "MIT OR Apache-2.0"
Expand All @@ -15,8 +15,8 @@ publish = true
default = []

[dependencies]
viz-core = { path = "../viz-core", version = "0.4.1" }
path-tree = { version = "0.6" }
viz-core = { path = "../viz-core", version = "0.4.2" }
path-tree = { version = "0.7" }
serde = "1.0"
thiserror = "1.0"

Expand Down
96 changes: 60 additions & 36 deletions viz-router/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,16 @@ impl Router {

#[cfg(test)]
mod tests {
use crate::{any, get, Resources, Route, Router, Tree};
use std::sync::Arc;
use viz_core::{
async_trait, types::Params, Body, Error, Handler, HandlerExt, IntoResponse, Method,
Request, RequestExt, Response, Result, StatusCode, Transform,
async_trait,
types::{Params, RouteInfo},
Body, Error, Handler, HandlerExt, IntoResponse, Method, Request, RequestExt, Response,
Result, StatusCode, Transform,
};

use crate::{any, get, Resources, Route, Router, Tree};

#[derive(Clone)]
struct Logger;

Expand Down Expand Up @@ -319,112 +323,132 @@ mod tests {
let (req, method, path) = client(Method::GET, "/posts");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
let (h, _) = node.unwrap();
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
""
);

// POST /posts
let (req, method, path) = client(Method::POST, "/posts");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
let (h, _) = node.unwrap();
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"posts: create"
);

// GET /posts/foo
let (mut req, method, path) = client(Method::GET, "/posts/foo");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
req.extensions_mut()
.insert(Into::<Params>::into(p.params()));
let (h, route) = node.unwrap();
req.extensions_mut().insert(Arc::from(RouteInfo {
id: *route.id,
pattern: route.pattern(),
params: Into::<Params>::into(route.params()),
}));
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"posts: show foo"
);

// PUT /posts/foo
let (mut req, method, path) = client(Method::PUT, "/posts/foo");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
req.extensions_mut()
.insert(Into::<Params>::into(p.params()));
let (h, route) = node.unwrap();
req.extensions_mut().insert(Arc::from(RouteInfo {
id: *route.id,
pattern: route.pattern(),
params: Into::<Params>::into(route.params()),
}));
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"posts: update foo"
);

// DELETE /posts/foo
let (mut req, method, path) = client(Method::DELETE, "/posts/foo");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
req.extensions_mut()
.insert(Into::<Params>::into(p.params()));
let (h, route) = node.unwrap();
req.extensions_mut().insert(Arc::from(RouteInfo {
id: *route.id,
pattern: route.pattern(),
params: Into::<Params>::into(route.params()),
}));
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"posts: delete foo"
);

// GET /posts/foo/users
let (req, method, path) = client(Method::GET, "/posts/foo/users");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
let (h, _) = node.unwrap();
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"users: index"
);

// POST /posts/users
let (req, method, path) = client(Method::POST, "/posts/foo/users");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
let (h, _) = node.unwrap();
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"users: create"
);

// GET /posts/foo/users/bar
let (mut req, method, path) = client(Method::GET, "/posts/foo/users/bar");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
req.extensions_mut()
.insert(Into::<Params>::into(p.params()));
let (h, route) = node.unwrap();
req.extensions_mut().insert(Arc::from(RouteInfo {
id: *route.id,
pattern: route.pattern(),
params: Into::<Params>::into(route.params()),
}));
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"users: show foo bar"
);

// PUT /posts/foo/users/bar
let (mut req, method, path) = client(Method::PUT, "/posts/foo/users/bar");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
req.extensions_mut()
.insert(Into::<Params>::into(p.params()));
let (h, route) = node.unwrap();
let route_info = Arc::from(RouteInfo {
id: *route.id,
pattern: route.pattern(),
params: Into::<Params>::into(route.params()),
});
assert_eq!(route.pattern(), "/posts/:post_id/users/:user_id");
assert_eq!(route_info.pattern, "/posts/:post_id/users/:user_id");
req.extensions_mut().insert(route_info);
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"users: update foo bar"
);
assert_eq!(p.pattern(), "/posts/:post_id/users/:user_id");

// DELETE /posts/foo/users/bar
let (mut req, method, path) = client(Method::DELETE, "/posts/foo/users/bar");
let node = tree.find(&method, &path);
assert!(node.is_some());
let p = node.unwrap();
req.extensions_mut()
.insert(Into::<Params>::into(p.params()));
let (h, route) = node.unwrap();
req.extensions_mut().insert(Arc::from(RouteInfo {
id: *route.id,
pattern: route.pattern(),
params: Into::<Params>::into(route.params()),
}));
assert_eq!(
hyper::body::to_bytes(p.value.call(req).await?.into_body()).await?,
hyper::body::to_bytes(h.call(req).await?.into_body()).await?,
"users: delete foo bar"
);

Expand Down
8 changes: 4 additions & 4 deletions viz-router/src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ pub struct Tree(Vec<(Method, PathTree<BoxHandler>)>);

impl Tree {
/// Find a handler by the HTTP method and the URI's path.
pub fn find<'a>(
pub fn find<'a, 'b>(
&'a self,
method: &'a Method,
path: &'a str,
) -> Option<Path<'_, 'a, BoxHandler>> {
method: &'b Method,
path: &'b str,
) -> Option<(&'a BoxHandler, Path<'a, 'b>)> {
self.0
.iter()
.find_map(|(m, t)| if m == method { t.find(path) } else { None })
Expand Down
8 changes: 4 additions & 4 deletions viz/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "viz"
version = "0.4.1"
version = "0.4.2"
edition = "2021"
rust-version = "1.60"
readme = "README.md"
Expand Down Expand Up @@ -68,9 +68,9 @@ rustls = ["dep:rustls-pemfile", "dep:tokio-rustls", "dep:futures-util"]
native-tls = ["dep:tokio-native-tls", "dep:futures-util"]

[dependencies]
viz-core = { path = "../viz-core", version = "0.4.1" }
viz-router = { path = "../viz-router", version = "0.4.1" }
viz-handlers = { path = "../viz-handlers", version = "0.3.1", default-features = false, optional = true }
viz-core = { path = "../viz-core", version = "0.4.2" }
viz-router = { path = "../viz-router", version = "0.4.2" }
viz-handlers = { path = "../viz-handlers", version = "0.3.2", default-features = false, optional = true }
viz-macros = { path = "../viz-macros", version = "0.1.0", optional = true }

hyper = { version = "0.14", features = ["server", "stream", "tcp"] }
Expand Down
Loading

0 comments on commit 4c7a0e9

Please sign in to comment.