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

Add a const router #210

Merged
merged 6 commits into from
Jul 3, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
5 changes: 5 additions & 0 deletions integration_tests/base_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ def message():
callCount = 0


@app.get("/bruhh", const=True)
async def bruhh(request):
return "Hello world"


@app.get("/")
async def hello(request):
global callCount
Expand Down
8 changes: 4 additions & 4 deletions robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self, file_object):

self._config_logger()

def _add_route(self, route_type, endpoint, handler):
def _add_route(self, route_type, endpoint, handler, const=False):
"""
[This is base handler for all the decorators]

Expand All @@ -53,7 +53,7 @@ def _add_route(self, route_type, endpoint, handler):

""" We will add the status code here only
"""
self.router.add_route(route_type, endpoint, handler)
self.router.add_route(route_type, endpoint, handler, const)

def before_request(self, endpoint):
"""
Expand Down Expand Up @@ -152,15 +152,15 @@ def start(self, url="127.0.0.1", port=5000):
observer.stop()
observer.join()

def get(self, endpoint):
def get(self, endpoint, const=False):
"""
The @app.get decorator to add a get route

:param endpoint str: endpoint to server the route
"""

def inner(handler):
self._add_route("GET", endpoint, handler)
self._add_route("GET", endpoint, handler, const)

return inner

Expand Down
2 changes: 1 addition & 1 deletion robyn/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class Robyn:
"""

...
def get(self, endpoint: str) -> Callable[..., None]:
def get(self, endpoint: str, const: bool = False) -> Callable[..., None]:
"""
The @app.get decorator to add a get route

Expand Down
6 changes: 4 additions & 2 deletions robyn/processpool.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ def spawn_process(

server = Server()

# TODO: if we remove the dot access
# the startup time will improve in the server
for directory in directories:
route, directory_path, index_file, show_files_listing = directory
server.add_directory(route, directory_path, index_file, show_files_listing)
Expand All @@ -51,8 +53,8 @@ def spawn_process(
server.add_header(key, val)

for route in routes:
route_type, endpoint, handler, is_async, number_of_params = route
server.add_route(route_type, endpoint, handler, is_async, number_of_params)
route_type, endpoint, handler, is_async, number_of_params, const = route
server.add_route(route_type, endpoint, handler, is_async, number_of_params, const)

for route in middlewares:
route_type, endpoint, handler, is_async, number_of_params = route
Expand Down
4 changes: 3 additions & 1 deletion robyn/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def _format_response(self, res):

return response

def add_route(self, route_type, endpoint, handler):
def add_route(self, route_type, endpoint, handler, const):
async def async_inner_handler(*args):
response = self._format_response(await handler(*args))
return response
Expand All @@ -50,6 +50,7 @@ def inner_handler(*args):
async_inner_handler,
True,
number_of_params,
const
)
)
else:
Expand All @@ -60,6 +61,7 @@ def inner_handler(*args):
inner_handler,
False,
number_of_params,
const
)
)

Expand Down
2 changes: 1 addition & 1 deletion robyn/router.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class BaseRouter(ABC):
class Router(BaseRouter):
def __init__(self) -> None:
pass
def add_route(self, route_type: str, endpoint: str, handler: Callable) -> None:
def add_route(self, route_type: str, endpoint: str, handler: Callable, const: bool) -> None:
pass
def get_routes(self) -> list[Route]:
pass
Expand Down
75 changes: 75 additions & 0 deletions src/executors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,81 @@ pub async fn execute_middleware_function<'a>(
}
}

pub async fn execute_function(
function: Py<PyAny>,
// queries: Rc<RefCell<HashMap<String, String>>>,
number_of_params: u8,
is_async: bool,
) -> Result<HashMap<String, String>> {
let mut request: HashMap<String, String> = HashMap::new();

// let mut queries_clone: HashMap<String, String> = HashMap::new();

// for (key, value) in (*queries).borrow().clone() {
// queries_clone.insert(key, value);
// }

if is_async {
let output = Python::with_gil(|py| {
let handler = function.as_ref(py);
// request.insert("params", route_params.into_py(py));
// request.insert("queries", queries_clone.into_py(py));
// request.insert("headers", headers.into_py(py));
// request.insert("body", data);

// this makes the request object to be accessible across every route
let coro: PyResult<&PyAny> = match number_of_params {
0 => handler.call0(),
1 => handler.call1((request,)),
// this is done to accomodate any future params
2_u8..=u8::MAX => handler.call1((request,)),
};
pyo3_asyncio::tokio::into_future(coro?)
})?;
sansyrox marked this conversation as resolved.
Show resolved Hide resolved

let output = output.await?;
let res = Python::with_gil(|py| -> PyResult<HashMap<String, String>> {
debug!("This is the result of the code {:?}", output);

let mut res: HashMap<String, String> =
output.into_ref(py).downcast::<PyDict>()?.extract()?;

let response_type = res.get("type").unwrap();

if response_type == "static_file" {
let file_path = res.get("file_path").unwrap();
let contents = read_file(file_path).unwrap();
res.insert("body".to_owned(), contents);
}
Ok(res)
})?;

Ok(res)
} else {
tokio::task::spawn_blocking(move || {
Python::with_gil(|py| {
let handler = function.as_ref(py);
// request.insert("params", route_params.into_py(py));
// request.insert("headers", headers.into_py(py));
// let data = data.into_py(py);
// request.insert("body", data);

let output: PyResult<&PyAny> = match number_of_params {
0 => handler.call0(),
1 => handler.call1((request,)),
// this is done to accomodate any future params
2_u8..=u8::MAX => handler.call1((request,)),
};
let output: HashMap<String, String> = output?.extract()?;
// also convert to object here
// also check why don't sync functions have file handling enabled
Ok(output)
})
})
.await?
}
}

// Change this!
#[inline]
pub async fn execute_http_function(
Expand Down
129 changes: 129 additions & 0 deletions src/routers/const_router.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
use std::sync::RwLock;
use std::{collections::HashMap, sync::Arc};
// pyo3 modules
use crate::{executors::execute_function, types::PyFunction};
use log::debug;
use pyo3::prelude::*;
use pyo3::types::PyAny;

use actix_web::http::Method;
use matchit::Node;

use anyhow::{bail, Error, Result};

/// Contains the thread safe hashmaps of different routes

pub struct ConstRouter {
get_routes: Arc<RwLock<Node<String>>>,
post_routes: Arc<RwLock<Node<String>>>,
put_routes: Arc<RwLock<Node<String>>>,
delete_routes: Arc<RwLock<Node<String>>>,
patch_routes: Arc<RwLock<Node<String>>>,
head_routes: Arc<RwLock<Node<String>>>,
options_routes: Arc<RwLock<Node<String>>>,
connect_routes: Arc<RwLock<Node<String>>>,
trace_routes: Arc<RwLock<Node<String>>>,
}

impl ConstRouter {
pub fn new() -> Self {
Self {
get_routes: Arc::new(RwLock::new(Node::new())),
post_routes: Arc::new(RwLock::new(Node::new())),
put_routes: Arc::new(RwLock::new(Node::new())),
delete_routes: Arc::new(RwLock::new(Node::new())),
patch_routes: Arc::new(RwLock::new(Node::new())),
head_routes: Arc::new(RwLock::new(Node::new())),
options_routes: Arc::new(RwLock::new(Node::new())),
connect_routes: Arc::new(RwLock::new(Node::new())),
trace_routes: Arc::new(RwLock::new(Node::new())),
}
}

#[inline]
fn get_relevant_map(&self, route: Method) -> Option<Arc<RwLock<Node<String>>>> {
match route {
Method::GET => Some(self.get_routes.clone()),
Method::POST => Some(self.post_routes.clone()),
Method::PUT => Some(self.put_routes.clone()),
Method::PATCH => Some(self.patch_routes.clone()),
Method::DELETE => Some(self.delete_routes.clone()),
Method::HEAD => Some(self.head_routes.clone()),
Method::OPTIONS => Some(self.options_routes.clone()),
Method::CONNECT => Some(self.connect_routes.clone()),
Method::TRACE => Some(self.trace_routes.clone()),
_ => None,
}
}

#[inline]
fn get_relevant_map_str(&self, route: &str) -> Option<Arc<RwLock<Node<String>>>> {
if route != "WS" {
let method = match Method::from_bytes(route.as_bytes()) {
Ok(res) => res,
Err(_) => return None,
};

self.get_relevant_map(method)
} else {
None
}
}

// Checks if the functions is an async function
// Inserts them in the router according to their nature(CoRoutine/SyncFunction)
pub fn add_route(
&self,
route_type: &str, // we can just have route type as WS
route: &str,
function: Py<PyAny>,
is_async: bool,
// queries: Rc<RefCell<HashMap<String, String>>>,
number_of_params: u8,
event_loop: &PyAny,
) -> Result<(), Error> {
// TODO:
// allow handlers
// allow routes
// and all others
// spawn a blockking thread for insertion
let table = match self.get_relevant_map_str(route_type) {
Some(table) => table,
None => bail!("No relevant map"),
};
let route = route.to_string();
pyo3_asyncio::tokio::run_until_complete(event_loop, async move {
let output = execute_function(function, number_of_params, is_async)
.await
.unwrap();
debug!("This is the result of the output {:?}", output);
table
.clone()
.write()
.unwrap()
.insert(route, output.get("body").unwrap().to_string())
.unwrap();

Ok(())
})
.unwrap();

Ok(())
}

// Checks if the functions is an async function
// Inserts them in the router according to their nature(CoRoutine/SyncFunction)
pub fn get_route(
&self,
route_method: Method,
route: &str, // check for the route method here
) -> Option<String> {
// need to split this function in multiple smaller functions
let table = self.get_relevant_map(route_method)?;

match table.clone().read().unwrap().at(route) {
Ok(res) => Some(res.value.clone()),
Err(_) => None,
}
}
}
1 change: 1 addition & 0 deletions src/routers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod const_router;
pub mod middleware_router;
pub mod router;
pub mod web_socket_router;
Loading