Skip to content

Commit

Permalink
Merge pull request #87 from kana-rus/global_fangs
Browse files Browse the repository at this point in the history
Global fangs
  • Loading branch information
kanarus authored Feb 12, 2024
2 parents fd64845 + b8f9e4f commit eae0da1
Show file tree
Hide file tree
Showing 25 changed files with 718 additions and 333 deletions.
16 changes: 6 additions & 10 deletions examples/form/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,19 @@ async fn post_submit(form_data: FormData) -> Status {
}

struct Logger;
impl FrontFang for Logger {
fn bite(&self, req: &mut Request) -> impl std::future::Future<Output = Result<(), Response>> + Send {
println!("[request] {} {}", req.method(), req.path());

if let Some(body) = req.payload() {
let content_type = req.headers.ContentType().unwrap_or("");
println!("[payload] {content_type:?}\n{}", body.escape_ascii());
}
impl BackFang for Logger {
fn bite(&self, res: &mut Response, req: &Request) -> impl std::future::Future<Output = Result<(), Response>> + Send {
println!("[request ] {:?}", req);
println!("[response] {:?}", res);

async {Ok(())}
}
}

#[tokio::main]
async fn main() {
Ohkami::with(Logger, (
Ohkami::new((
"/form" .GET(get_form),
"/submit".POST(post_submit),
)).howl("localhost:5000").await
)).howl_with(Logger, "localhost:5000").await
}
6 changes: 3 additions & 3 deletions examples/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ async fn main() {
.with_max_level(tracing::Level::INFO)
.init();

let hello_ohkami = Ohkami::with((SetServer, LogRequest), (
let hello_ohkami = Ohkami::with(SetServer, (
"/query".
GET(hello_handler::hello_by_query),
"/json".
Expand All @@ -116,8 +116,8 @@ async fn main() {

tracing::info!("Started listening on http://localhost:3000");

Ohkami::with((LogRequest,), (
Ohkami::new((
"/hc" .GET(health_handler::health_check),
"/api".By(hello_ohkami),
)).howl("localhost:3000").await
)).howl_with(LogRequest, "localhost:3000").await
}
8 changes: 4 additions & 4 deletions examples/quick_start/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ async fn hello(name: &str) -> OK<String> {
#[tokio::main]
async fn main() {
Ohkami::new((
"/healthz".
GET(health_check),
"/hello/:name".
GET(hello),
"/healthz"
.GET(health_check),
"/hello/:name"
.GET(hello),
)).howl("localhost:3000").await
}
6 changes: 3 additions & 3 deletions examples/realworld/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ mod tags;

use sqlx::PgPool;
use ohkami::{Ohkami, Route};
use crate::fangs::{LogRequest, LogResponse, ConnectionPool};
use crate::fangs::ConnectionPool;


pub fn realworld_ohkami(
pool: PgPool,
) -> Ohkami {
Ohkami::with((LogRequest, LogResponse, ConnectionPool::from(pool)),
"/api".By(Ohkami::new((
Ohkami::new(
"/api".By(Ohkami::with(ConnectionPool::from(pool), (
"/users" .By(users::users_ohkami()),
"/user" .By(user::user_ohkami()),
"/profiles".By(profiles::profiles_ohkami()),
Expand Down
7 changes: 5 additions & 2 deletions examples/realworld/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ mod handlers;
#[cfg(test)]
mod _test;

use fangs::{LogRequest, LogResponse};
use errors::RealWorldError;

use sqlx::postgres::PgPoolOptions;


#[tokio::main]
async fn main() -> Result<(), errors::RealWorldError> {
dotenvy::dotenv().map_err(|e| RealWorldError::Config(format!("Failed to load .env: {e}")))?;
dotenvy::dotenv()
.map_err(|e| RealWorldError::Config(format!("Failed to load .env: {e}")))?;
tracing_subscriber::fmt()
.with_max_level(tracing_subscriber::filter::LevelFilter::DEBUG)
.init();
Expand All @@ -26,7 +29,7 @@ async fn main() -> Result<(), errors::RealWorldError> {
.map_err(|e| RealWorldError::DB(e))?;

handlers::realworld_ohkami(pool)
.howl("localhost:8080").await;
.howl_with((LogRequest, LogResponse), "localhost:8080").await;

Ok(())
}
8 changes: 4 additions & 4 deletions ohkami/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ license = "MIT"
features = ["rt_tokio", "custom-header"]

[dependencies]
ohkami_lib = { version = "=0.1.0", path = "../ohkami_lib" }
ohkami_lib = { version = "=0.1.1", path = "../ohkami_lib" }
ohkami_macros = { version = "=0.5.1", path = "../ohkami_macros" }
tokio = { version = "1", optional = true, features = ["net", "rt", "io-util", "sync"] }
async-std = { version = "1", optional = true }
byte_reader = { version = "2.0.0", features = ["text"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
sha1 = { version = "=0.11.0-pre.0", optional = true, default-features = false }
sha2 = { version = "=0.11.0-pre.0", default-features = false }
hmac = { version = "=0.13.0-pre.0", default-features = false }
#sha1 = { version = "0.10.6", optional = true, default-features = false }
sha2 = { version = "0.10.8", default-features = false }
hmac = { version = "0.12.1", default-features = false }
rustc-hash = { version = "1.1", optional = true }

[features]
Expand Down
10 changes: 5 additions & 5 deletions ohkami/src/fang/builtin/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ impl JWT {

let signature = {
use ::sha2::{Sha256};
use ::hmac::{Hmac, KeyInit, Mac};
use ::hmac::{Hmac, Mac};

let mut s = Hmac::<Sha256>::new_from_slice(self.secret.as_bytes()).unwrap();
s.update(unsigned_token.as_bytes());
Expand Down Expand Up @@ -224,29 +224,29 @@ impl JWT {

let is_correct_signature = {
use ::sha2::{Sha256, Sha384, Sha512};
use ::hmac::{Hmac, KeyInit, Mac};
use ::hmac::{Hmac, Mac};

match self.alg {
VerifyingAlgorithm::HS256 => {
let mut hs = Hmac::<Sha256>::new_from_slice(self.secret.as_bytes()).unwrap();
hs.update(header_part.as_bytes());
hs.update(b".");
hs.update(payload_part.as_bytes());
hs.finalize().into_bytes().0 == *requested_signature
hs.finalize().into_bytes().as_slice() == &requested_signature
}
VerifyingAlgorithm::HS384 => {
let mut hs = Hmac::<Sha384>::new_from_slice(self.secret.as_bytes()).unwrap();
hs.update(header_part.as_bytes());
hs.update(b".");
hs.update(payload_part.as_bytes());
hs.finalize().into_bytes().0 == *requested_signature
hs.finalize().into_bytes().as_slice() == &requested_signature
}
VerifyingAlgorithm::HS512 => {
let mut hs = Hmac::<Sha512>::new_from_slice(self.secret.as_bytes()).unwrap();
hs.update(header_part.as_bytes());
hs.update(b".");
hs.update(payload_part.as_bytes());
hs.finalize().into_bytes().0 == *requested_signature
hs.finalize().into_bytes().as_slice() == &requested_signature
}
}
};
Expand Down
8 changes: 4 additions & 4 deletions ohkami/src/fang/fangs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{Response, Request, Method::{self, *}, fang::Fang};


/// Represents "can be used as a front fang", e.g. executed before `req` is passed to a handler.\
/// You can register this fang only for several request methods using `METHODS` const parameter.
/// You can register this fang only for some request methods you like using `METHODS` const parameter.
///
/// <br>
///
Expand Down Expand Up @@ -35,13 +35,13 @@ impl<FF: FrontFang + Send + Sync> FrontFangCaller for FF {
fn call<'c>(&'c self, req: &'c mut Request) -> Pin<Box<dyn Future<Output = Result<(), Response>> + Send + 'c>>
where Self: Sync + 'c
{
Box::pin(async move {self.bite(req).await})
Box::pin(self.bite(req))
}
}


/// Represents "can be used as a back fang", e.g. executed after a handler generates `res`.\
/// You can register this fang only for several request methods using `METHODS` const parameter.
/// You can register this fang only for some request methods you like using `METHODS` const parameter.
///
/// <br>
///
Expand Down Expand Up @@ -73,7 +73,7 @@ impl<BF: BackFang + Send + Sync> BackFangCaller for BF {
fn call<'c>(&'c self, res: &'c mut Response, _req: &'c Request) -> Pin<Box<dyn Future<Output = Result<(), Response>> + Send + 'c>>
where Self: Sync + 'c
{
Box::pin(async move {self.bite(res, _req).await})
Box::pin(self.bite(res, _req))
}
}

Expand Down
22 changes: 14 additions & 8 deletions ohkami/src/fang/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,6 @@ pub struct Fang {
id: TypeId,
pub(crate) proc: proc::FangProc,
}
impl Fang {
pub(crate) fn is_front(&self) -> bool {
matches!(self.proc, proc::FangProc::Front(_))
}
}
const _: () = {
impl<'f> PartialEq for &'f Fang {
fn eq(&self, other: &Self) -> bool {
Expand All @@ -70,8 +65,9 @@ const _: () = {
};

pub(crate) mod proc {
use std::sync::Arc;
use super::{BackFangCaller, FrontFangCaller};
use std::{future::Future, pin::Pin, sync::Arc};
use crate::{Request, Response};


#[derive(Clone)]
Expand All @@ -81,8 +77,18 @@ pub(crate) mod proc {
}

#[derive(Clone)]
pub struct FrontFang(pub(crate) Arc<dyn FrontFangCaller>);
pub struct FrontFang(pub(super) Arc<dyn FrontFangCaller>);
impl FrontFang {
pub fn call<'c>(&'c self, req: &'c mut Request) -> Pin<Box<dyn Future<Output = Result<(), Response>> + Send + 'c>> {
self.0.call(req)
}
}

#[derive(Clone)]
pub struct BackFang(pub(crate) Arc<dyn BackFangCaller>);
pub struct BackFang(pub(super) Arc<dyn BackFangCaller>);
impl BackFang {
pub fn call<'c>(&'c self, res: &'c mut Response, req: &'c Request) -> Pin<Box<dyn Future<Output = Result<(), Response>> + Send + 'c>> {
self.0.call(res, req)
}
}
}
37 changes: 17 additions & 20 deletions ohkami/src/ohkami/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ use crate::handler::{Handlers, ByAnother};


trait RoutingItem {
fn apply(self, routes: TrieRouter) -> TrieRouter;
fn apply(self, router: &mut TrieRouter);
} const _: () = {
impl RoutingItem for Handlers {
fn apply(self, routes: TrieRouter) -> TrieRouter {
routes.register_handlers(self)
fn apply(self, router: &mut TrieRouter) {
router.register_handlers(self)
}
}
impl RoutingItem for ByAnother {
fn apply(self, routes: TrieRouter) -> TrieRouter {
routes.merge_another(self)
fn apply(self, router: &mut TrieRouter) {
router.merge_another(self)
}
}

Expand All @@ -38,33 +38,30 @@ trait RoutingItem {
/// // This must be so annoying!!!
/// ```
impl RoutingItem for &'static str {
fn apply(self, routes: TrieRouter) -> TrieRouter {
routes
}
fn apply(self, _router: &mut TrieRouter) {}
}
};

pub trait Routes {
fn apply(self, routes: TrieRouter) -> TrieRouter;
fn apply(self, router: &mut TrieRouter);
} impl<R: RoutingItem> Routes for R {
fn apply(self, mut routes: TrieRouter) -> TrieRouter {
routes = <R as RoutingItem>::apply(self, routes);
routes
fn apply(self, router: &mut TrieRouter) {
<R as RoutingItem>::apply(self, router)
}
} macro_rules! impl_for_tuple {
( $( $item:ident ),* ) => {
impl<$( $item: RoutingItem ),*> Routes for ( $($item,)* ) {
fn apply(self, mut routes: TrieRouter) -> TrieRouter {
let ( $( $item, )* ) = self;
( $( $item:ident ),+ ) => {
impl<$( $item: RoutingItem ),+> Routes for ( $($item,)+ ) {
fn apply(self, router: &mut TrieRouter) {
let ( $( $item, )+ ) = self;
$(
routes = <$item as RoutingItem>::apply($item, routes);
)*
routes
<$item as RoutingItem>::apply($item, router);
)+
}
}
};
} const _: () = {
impl_for_tuple!();
impl Routes for () {fn apply(self, _router: &mut TrieRouter) {}}

impl_for_tuple!(R1);
impl_for_tuple!(R1, R2);
impl_for_tuple!(R1, R2, R3);
Expand Down
Loading

0 comments on commit eae0da1

Please sign in to comment.