Skip to content

Use Arc<Store> instead of Store for lazy loading #151

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

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 2 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl<Data: Clone + Send + Sync + 'static> App<Data> {
router: Router::new(),
default_handler: EndpointData {
endpoint: BoxedEndpoint::new(async || http::status::StatusCode::NOT_FOUND),
store: Store::new(),
store: Arc::new(Store::new()),
},
};

Expand Down Expand Up @@ -240,7 +240,7 @@ impl<T: Clone + Send + 'static> Extract<T> for AppData<T> {
data: &mut T,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
future::ok(AppData(data.clone()))
}
Expand Down
13 changes: 7 additions & 6 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ use http_service::Body;
use multipart::server::Multipart;
use std::io::Cursor;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

use crate::{configuration::Store, Extract, IntoResponse, Request, Response, RouteMatch};

Expand All @@ -101,7 +102,7 @@ impl<S: 'static> Extract<S> for MultipartForm {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
// https://stackoverflow.com/questions/43424982/how-to-parse-multipart-forms-using-abonander-multipart-with-rocket

Expand Down Expand Up @@ -152,7 +153,7 @@ impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let body = std::mem::replace(req.body_mut(), Body::empty());
FutureObj::new(Box::new(
Expand Down Expand Up @@ -204,7 +205,7 @@ impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let body = std::mem::replace(req.body_mut(), Body::empty());
FutureObj::new(Box::new(
Expand Down Expand Up @@ -252,7 +253,7 @@ impl<S: 'static> Extract<S> for Str {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let body = std::mem::replace(req.body_mut(), Body::empty());

Expand Down Expand Up @@ -288,7 +289,7 @@ impl<S: 'static> Extract<S> for StrLossy {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let body = std::mem::replace(req.body_mut(), Body::empty());

Expand Down Expand Up @@ -324,7 +325,7 @@ impl<S: 'static> Extract<S> for Bytes {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let body = std::mem::replace(req.body_mut(), Body::empty());

Expand Down
3 changes: 2 additions & 1 deletion src/configuration/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::sync::Arc;

use futures::future::FutureObj;

Expand Down Expand Up @@ -106,7 +107,7 @@ where
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
// The return type here is Option<K>, but the return type of the result of the future is
// Result<ExtractConfiguration<T>, Response>, so rustc can infer that K == T, so we do not
Expand Down
3 changes: 2 additions & 1 deletion src/cookies.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use cookie::{Cookie, CookieJar, ParseError};
use futures::future;
use std::sync::Arc;

use crate::{configuration::Store, response::IntoResponse, Extract, Request, Response, RouteMatch};

Expand Down Expand Up @@ -28,7 +29,7 @@ impl<S: 'static> Extract<S> for Cookies {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let cookie_jar = match req.headers().get("Cookie") {
Some(raw_cookies) => parse_from_header(raw_cookies.to_str().unwrap()),
Expand Down
11 changes: 7 additions & 4 deletions src/endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use futures::future::{Future, FutureObj};
use std::sync::Arc;

use crate::{
configuration::Store, extract::Extract, head::Head, IntoResponse, Request, Response, RouteMatch,
Expand Down Expand Up @@ -72,12 +73,14 @@ pub trait Endpoint<Data, Kind>: Send + Sync + 'static {
data: Data,
req: Request,
params: Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut;
}

type BoxedEndpointFn<Data> =
dyn Fn(Data, Request, Option<RouteMatch>, &Store) -> FutureObj<'static, Response> + Send + Sync;
dyn Fn(Data, Request, Option<RouteMatch>, &Arc<Store>) -> FutureObj<'static, Response>
+ Send
+ Sync;

pub(crate) struct BoxedEndpoint<Data> {
endpoint: Box<BoxedEndpointFn<Data>>,
Expand All @@ -100,7 +103,7 @@ impl<Data> BoxedEndpoint<Data> {
data: Data,
req: Request,
params: Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> FutureObj<'static, Response> {
(self.endpoint)(data, req, params, store)
}
Expand Down Expand Up @@ -134,7 +137,7 @@ macro_rules! end_point_impl_raw {
type Fut = FutureObj<'static, Response>;

#[allow(unused_mut, non_snake_case)]
fn call(&self, mut data: Data, mut req: Request, params: Option<RouteMatch<'_>>, store: &Store) -> Self::Fut {
fn call(&self, mut data: Data, mut req: Request, params: Option<RouteMatch<'_>>, store: &Arc<Store>) -> Self::Fut {
let f = self.clone();
$(let $X = $X::extract(&mut data, &mut req, &params, store);)*
FutureObj::new(Box::new(async move {
Expand Down
3 changes: 2 additions & 1 deletion src/extract.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use futures::prelude::*;
use std::sync::Arc;

use crate::{configuration::Store, Request, Response, RouteMatch};

Expand All @@ -15,6 +16,6 @@ pub trait Extract<Data>: Send + Sized + 'static {
data: &mut Data,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut;
}
6 changes: 3 additions & 3 deletions src/head.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl<T: Send + 'static + std::str::FromStr, S: 'static> Extract<S> for Path<T> {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
let &PathIdx(i) = req.extensions().get::<PathIdx>().unwrap_or(&PathIdx(0));
req.extensions_mut().insert(PathIdx(i + 1));
Expand Down Expand Up @@ -185,7 +185,7 @@ impl<T: NamedSegment, S: 'static> Extract<S> for Named<T> {
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
match params {
Some(params) => params
Expand Down Expand Up @@ -215,7 +215,7 @@ where
data: &mut S,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
req.uri().query().and_then(|q| q.parse().ok()).map_or(
future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
Expand Down
3 changes: 2 additions & 1 deletion src/request.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use futures::future;
use http_service::Body;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

use crate::{configuration::Store, Extract, Response, RouteMatch};

Expand Down Expand Up @@ -58,7 +59,7 @@ impl<Data: 'static, T: Compute> Extract<Data> for Computed<T> {
data: &mut Data,
req: &mut Request,
params: &Option<RouteMatch<'_>>,
store: &Store,
store: &Arc<Store>,
) -> Self::Fut {
future::ok(Computed(T::compute(req)))
}
Expand Down
22 changes: 12 additions & 10 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use path_table::{PathTable, RouteMatch};
pub struct Router<Data> {
table: PathTable<ResourceData<Data>>,
middleware_base: Vec<Arc<dyn Middleware<Data> + Send + Sync>>,
pub(crate) store_base: Store,
pub(crate) store_base: Arc<Store>,
}

pub(crate) struct RouteResult<'a, Data> {
Expand Down Expand Up @@ -115,7 +115,7 @@ impl<Data: Clone + Send + Sync + 'static> Router<Data> {
Router {
table: PathTable::new(),
middleware_base: Vec::new(),
store_base: Store::new(),
store_base: Arc::new(Store::new()),
}
}

Expand Down Expand Up @@ -160,7 +160,7 @@ impl<Data: Clone + Send + Sync + 'static> Router<Data> {
///
/// The default configuration will be applied when the router setup ends.
pub fn config<T: Any + Debug + Clone + Send + Sync>(&mut self, item: T) -> &mut Self {
self.store_base.write(item);
Arc::get_mut(&mut self.store_base).unwrap().write(item);
self
}

Expand All @@ -182,7 +182,9 @@ impl<Data> Router<Data> {
pub(crate) fn apply_default_config(&mut self) {
for resource in self.table.iter_mut() {
for endpoint in resource.endpoints.values_mut() {
endpoint.store.merge(&self.store_base);
Arc::get_mut(&mut endpoint.store)
.unwrap()
.merge(&self.store_base);
}
}
}
Expand All @@ -197,13 +199,13 @@ impl<Data> Router<Data> {
/// This can be used to add configuration items to the endpoint.
pub struct EndpointData<Data> {
pub(crate) endpoint: BoxedEndpoint<Data>,
pub(crate) store: Store,
pub(crate) store: Arc<Store>,
}

impl<Data> EndpointData<Data> {
/// Add a configuration `item` for this endpoint.
pub fn config<T: Any + Debug + Clone + Send + Sync>(&mut self, item: T) -> &mut Self {
self.store.write(item);
Arc::get_mut(&mut self.store).unwrap().write(item);
self
}
}
Expand Down Expand Up @@ -238,7 +240,7 @@ impl<'a, Data> Resource<'a, Data> {
let mut subrouter = Router {
table: PathTable::new(),
middleware_base: self.middleware_base.clone(),
store_base: Store::new(),
store_base: Arc::new(Store::new()),
};
builder(&mut subrouter);
subrouter.apply_default_config();
Expand Down Expand Up @@ -268,7 +270,7 @@ impl<'a, Data> Resource<'a, Data> {

let endpoint = EndpointData {
endpoint: BoxedEndpoint::new(ep),
store: Store::new(),
store: Arc::new(Store::new()),
};

entry.or_insert(endpoint)
Expand Down Expand Up @@ -340,7 +342,7 @@ mod tests {
) -> Option<Response> {
let default_handler = Arc::new(EndpointData {
endpoint: BoxedEndpoint::new(async || http::status::StatusCode::NOT_FOUND),
store: Store::new(),
store: Arc::new(Store::new()),
});
let RouteResult {
endpoint,
Expand Down Expand Up @@ -372,7 +374,7 @@ mod tests {
) -> Option<usize> {
let default_handler = Arc::new(EndpointData {
endpoint: BoxedEndpoint::new(async || http::status::StatusCode::NOT_FOUND),
store: Store::new(),
store: Arc::new(Store::new()),
});
let route_result = router.route(path, method, &default_handler);
Some(route_result.middleware.len())
Expand Down