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

Implement request-state local cache #655

Closed
wants to merge 6 commits 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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ members = [
"examples/content_types",
"examples/ranking",
"examples/testing",
"examples/request_state_local_cache",
"examples/request_guard",
"examples/stream",
"examples/json",
Expand Down
38 changes: 37 additions & 1 deletion core/lib/src/request/request.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use std::net::{IpAddr, SocketAddr};
use std::fmt;
Expand Down Expand Up @@ -26,6 +27,7 @@ struct RequestState<'r> {
cookies: RefCell<CookieJar>,
accept: Storage<Option<Accept>>,
content_type: Storage<Option<ContentType>>,
cache: Rc<Container>,
}

/// The type of an incoming web request.
Expand All @@ -41,7 +43,7 @@ pub struct Request<'r> {
uri: Uri<'r>,
headers: HeaderMap<'r>,
remote: Option<SocketAddr>,
state: RequestState<'r>
state: RequestState<'r>,
}

impl<'r> Request<'r> {
Expand All @@ -67,6 +69,7 @@ impl<'r> Request<'r> {
cookies: RefCell::new(CookieJar::new()),
accept: Storage::new(),
content_type: Storage::new(),
cache: Rc::new(Container::new()),
}
}
}
Expand All @@ -78,6 +81,39 @@ impl<'r> Request<'r> {
f(&mut request);
}

/// Retrieves the cached value for type `T` from the request-local cached
/// state of `self`. If no such value has previously been cached for
/// this request, `f` is called to produce the value which is subsequently
/// returned.
///
/// # Example
///
/// ```rust
/// # use rocket::http::Method;
/// # use rocket::Request;
/// # struct User;
/// fn current_user() -> User {
/// // Load user...
/// # User
/// }
///
/// # Request::example(Method::Get, "/uri", |request| {
/// let user = request.local_cache(current_user);
/// # });
/// ```
pub fn local_cache<T, F>(&self, f: F) -> &T
where T: Send + Sync + 'static,
F: FnOnce() -> T {

match self.state.cache.try_get() {
Some(cached) => cached,
None => {
self.state.cache.set(f());
self.state.cache.get()
}
}
}

/// Retrieve the method from `self`.
///
/// # Example
Expand Down
9 changes: 9 additions & 0 deletions examples/request_state_local_cache/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "request_state_local_cache"
version = "0.0.0"
workspace = "../../"
publish = false

[dependencies]
rocket = { path = "../../core/lib" }
rocket_codegen = { path = "../../core/codegen" }
55 changes: 55 additions & 0 deletions examples/request_state_local_cache/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#![feature(plugin, decl_macro)]
#![plugin(rocket_codegen)]
extern crate rocket;

use std::sync::atomic::{AtomicUsize, Ordering};

use rocket::request::{self, Request, FromRequest, State};
use rocket::outcome::Outcome::*;

#[cfg(test)] mod tests;

#[derive(Default)]
struct Atomics {
uncached: AtomicUsize,
cached: AtomicUsize,
}

struct Guard1;
struct Guard2;

impl<'a, 'r> FromRequest<'a, 'r> for Guard1 {
type Error = ();

fn from_request(req: &'a Request<'r>) -> request::Outcome<Self, ()> {
let atomics = req.guard::<State<Atomics>>()?;
atomics.uncached.fetch_add(1, Ordering::Relaxed);
req.local_cache(|| atomics.cached.fetch_add(1, Ordering::Relaxed));

Success(Guard1)
}
}

impl<'a, 'r> FromRequest<'a, 'r> for Guard2 {
type Error = ();

fn from_request(req: &'a Request<'r>) -> request::Outcome<Self, ()> {
req.guard::<Guard1>()?;
Success(Guard2)
}
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kill this extra empty line.

#[get("/")]
fn index(_g1: Guard1, _g2: Guard2) {
// This exists only to run the request guards.
}

fn rocket() -> rocket::Rocket {
rocket::ignite()
.manage(Atomics::default())
.mount("/", routes!(index))
}

fn main() {
rocket().launch();
}
15 changes: 15 additions & 0 deletions examples/request_state_local_cache/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::sync::atomic::{Ordering};

use ::Atomics;
use super::rocket;
use rocket::local::Client;

#[test]
fn test() {
let client = Client::new(rocket()).unwrap();
client.get("/").dispatch();

let atomics = client.rocket().state::<Atomics>().unwrap();
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 2);
assert_eq!(atomics.cached.load(Ordering::Relaxed), 1);
}