-
-
Notifications
You must be signed in to change notification settings - Fork 273
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
Router refactor #307
Merged
Merged
Router refactor #307
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
use std::sync::RwLock; | ||
use std::{collections::HashMap, str::FromStr}; | ||
// pyo3 modules | ||
use crate::types::PyFunction; | ||
use pyo3::prelude::*; | ||
use pyo3::types::PyAny; | ||
|
||
use actix_web::http::Method; | ||
use matchit::Router as MatchItRouter; | ||
|
||
use anyhow::{Context, Result}; | ||
|
||
use super::Router; | ||
|
||
type RouteMap = RwLock<MatchItRouter<(PyFunction, u8)>>; | ||
|
||
/// Contains the thread safe hashmaps of different routes | ||
pub struct HttpRouter { | ||
routes: HashMap<Method, RouteMap>, | ||
} | ||
|
||
impl Router<((PyFunction, u8), HashMap<String, String>), Method> for HttpRouter { | ||
fn add_route( | ||
&self, | ||
route_type: &str, // We can just have route type as WS | ||
route: &str, | ||
handler: Py<PyAny>, | ||
is_async: bool, | ||
number_of_params: u8, | ||
_event_loop: Option<&PyAny>, | ||
) -> Result<()> { | ||
let table = self | ||
.get_relevant_map_str(route_type) | ||
.context("No relevant map")?; | ||
|
||
let function = match is_async { | ||
true => PyFunction::CoRoutine(handler), | ||
false => PyFunction::SyncFunction(handler), | ||
}; | ||
|
||
// try removing unwrap here | ||
table | ||
.write() | ||
.unwrap() | ||
.insert(route.to_string(), (function, number_of_params))?; | ||
|
||
Ok(()) | ||
} | ||
|
||
fn get_route( | ||
&self, | ||
route_method: Method, | ||
route: &str, | ||
) -> Option<((PyFunction, u8), HashMap<String, String>)> { | ||
let table = self.routes.get(&route_method)?; | ||
|
||
let table_lock = table.read().ok()?; | ||
let res = table_lock.at(route).ok()?; | ||
let mut route_params = HashMap::new(); | ||
for (key, value) in res.params.iter() { | ||
route_params.insert(key.to_string(), value.to_string()); | ||
} | ||
|
||
Some((res.value.to_owned(), route_params)) | ||
} | ||
} | ||
|
||
impl HttpRouter { | ||
pub fn new() -> Self { | ||
let mut routes = HashMap::new(); | ||
routes.insert(Method::GET, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::POST, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::PUT, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::DELETE, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::PATCH, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::HEAD, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::OPTIONS, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::CONNECT, RwLock::new(MatchItRouter::new())); | ||
routes.insert(Method::TRACE, RwLock::new(MatchItRouter::new())); | ||
Self { routes } | ||
} | ||
|
||
#[inline] | ||
fn get_relevant_map_str( | ||
&self, | ||
route: &str, | ||
) -> Option<&RwLock<MatchItRouter<(PyFunction, u8)>>> { | ||
match route { | ||
"WS" => None, | ||
_ => self.routes.get(&Method::from_str(route).ok()?), | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @AntoineRR ,
I am a bit unfamiliar with
traits
in rust. Can you please explain this statement to me? And the benefits associated with it?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure !
About traits
Traits are a way in Rust to share behavior between structs. There is no inheritance in Rust as in a truly object oriented language like C++, so traits are more similar to interfaces in Java for example.
Here, defining the
Router
trait allows to specify what methods should be in a router :add_route
andget_route
. For every router we want to define, we have to implement this trait using the line above. This will force us to provide a definition for theadd_route
andget_route
method that is specific to our struct, which isConstRouter
here.About the generics
I didn't want to change the code too much so I kept the same return types and parameter types in every router struct. The return type of the
get_route
method is different across the routers (DynRouter
andMiddlewareRouter
return anOption<((PyFunction, u8), HashMap<String, String>)>
whileConstRouter
return anOption<String>
), so I used a generic type to unify their behavior in the trait. Similarly, theroute_type
parameter of theget_route
method can either be aMiddlewareRoute
or aMethod
. I needed two different generic types to handle those differences: this isT
andU
in the definition of the trait :pub trait Router<T, U>
. ForConstRouter
,T
isString
andU
isMethod
.Benefits of using traits
With this PR,
DynRouter
,ConstRouter
andMiddlewareRouter
all implement theRouter
trait (I wanted to include theWebSocketRouter
too but it seems too different from the others). This means the compiler is aware those share some behavior. We could now do some cool things like:Vec<dyn Router>
containing the routersRouter
trait as parameter ->fn method<T: Router>(router: T)
add_route
andget_route
methods if we can make it the same for all structs (which I may try to do later)Router
trait instead of in each structI hope this makes things clearer! In this PR I didn't take advantage of the trait for now, I wanted to do small iterations on the code instead of a really big one. I will try to improve things further if I have some time 😉
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you @AntoineRR . This an excellent explanation 😄
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're welcome ! 😉