2017-04-17 02:48:59 +00:00
|
|
|
# State
|
|
|
|
|
|
|
|
Many web applications have a need to maintain state. This can be as simple as
|
|
|
|
maintaining a counter for the number of visits or as complex as needing to
|
|
|
|
access job queues and multiple databases. Rocket provides the tools to enable
|
|
|
|
these kinds of interactions in a safe and simple manner.
|
|
|
|
|
|
|
|
## Managed State
|
|
|
|
|
|
|
|
The enabling feature for maintaining state is _managed state_. Managed state, as
|
|
|
|
the name implies, is state that Rocket manages for your application. The state
|
|
|
|
is managed on a per-type basis: Rocket will manage at most one value of a given
|
|
|
|
type.
|
|
|
|
|
|
|
|
The process for using managed state is simple:
|
|
|
|
|
|
|
|
1. Call `manage` on the `Rocket` instance corresponding to your application
|
|
|
|
with the initial value of the state.
|
|
|
|
2. Add a `State<T>` type to any request handler, where `T` is the type of the
|
|
|
|
value passed into `manage`.
|
|
|
|
|
|
|
|
### Adding State
|
|
|
|
|
|
|
|
To instruct Rocket to manage state for your application, call the
|
2017-07-06 08:58:57 +00:00
|
|
|
[`manage`](https://api.rocket.rs/rocket/struct.Rocket.html#method.manage) method
|
|
|
|
on an instance of `Rocket`. For example, to ask Rocket to manage a `HitCount`
|
2017-04-17 02:48:59 +00:00
|
|
|
structure with an internal `AtomicUsize` with an initial value of `0`, we can
|
|
|
|
write the following:
|
|
|
|
|
|
|
|
```rust
|
2017-07-06 08:58:57 +00:00
|
|
|
struct HitCount {
|
|
|
|
count: AtomicUsize
|
|
|
|
}
|
2017-04-17 02:48:59 +00:00
|
|
|
|
2017-07-06 08:58:57 +00:00
|
|
|
rocket::ignite().manage(HitCount { count: AtomicUsize::new(0) });
|
2017-04-17 02:48:59 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
The `manage` method can be called any number of times as long as each call
|
|
|
|
refers to a value of a different type. For instance, to have Rocket manage both
|
|
|
|
a `HitCount` value and a `Config` value, we can write:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
rocket::ignite()
|
2017-07-06 08:58:57 +00:00
|
|
|
.manage(HitCount { count: AtomicUsize::new(0) })
|
|
|
|
.manage(Config::from(user_input));
|
2017-04-17 02:48:59 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
### Retrieving State
|
|
|
|
|
|
|
|
State that is being managed by Rocket can be retrieved via the
|
2017-07-06 08:58:57 +00:00
|
|
|
[`State`](https://api.rocket.rs/rocket/struct.State.html) type: a [request
|
2017-04-17 02:48:59 +00:00
|
|
|
guard](/guide/requests/#request-guards) for managed state. To use the request
|
2017-07-06 08:58:57 +00:00
|
|
|
guard, add a `State<T>` type to any request handler, where `T` is the type of
|
|
|
|
the managed state. For example, we can retrieve and respond with the current
|
|
|
|
`HitCount` in a `count` route as follows:
|
2017-04-17 02:48:59 +00:00
|
|
|
|
|
|
|
```rust
|
|
|
|
#[get("/count")]
|
2017-04-30 21:32:21 +00:00
|
|
|
fn count(hit_count: State<HitCount>) -> String {
|
2017-07-06 08:58:57 +00:00
|
|
|
let current_count = hit_count.count.load(Ordering::Relaxed);
|
2017-04-17 02:48:59 +00:00
|
|
|
format!("Number of visits: {}", current_count)
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
You can retrieve more than one `State` type in a single route as well:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
#[get("/state")]
|
2017-04-30 21:32:21 +00:00
|
|
|
fn state(hit_count: State<HitCount>, config: State<Config>) -> T { ... }
|
2017-04-17 02:48:59 +00:00
|
|
|
```
|
|
|
|
|
2017-07-10 11:59:55 +00:00
|
|
|
### Within Guards
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2017-04-17 02:48:59 +00:00
|
|
|
It can also be useful to retrieve managed state from a `FromRequest`
|
2017-10-17 00:43:59 +00:00
|
|
|
implementation. To do so, simply invoke `State<T>` as a guard using the
|
2017-07-06 08:58:57 +00:00
|
|
|
[`Request::guard()`] method.
|
2017-04-17 02:48:59 +00:00
|
|
|
|
|
|
|
```rust
|
|
|
|
fn from_request(req: &'a Request<'r>) -> request::Outcome<T, ()> {
|
2017-07-06 08:58:57 +00:00
|
|
|
let hit_count_state = req.guard::<State<HitCount>>()?;
|
|
|
|
let current_count = hit_count_state.count.load(Ordering::Relaxed);
|
2017-04-17 02:48:59 +00:00
|
|
|
...
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2017-07-06 08:58:57 +00:00
|
|
|
[`Request::guard()`]: https://api.rocket.rs/rocket/struct.Request.html#method.guard
|
|
|
|
|
2017-04-17 02:48:59 +00:00
|
|
|
### Unmanaged State
|
|
|
|
|
|
|
|
If you request a `State<T>` for a `T` that is not `managed`, Rocket won't call
|
|
|
|
the offending route. Instead, Rocket will log an error message and return a
|
|
|
|
**500** error to the client.
|
|
|
|
|
|
|
|
While this behavior is 100% safe, it isn't fun to return **500** errors to
|
|
|
|
clients, especially when the issue can be easily avoided. Because of this,
|
|
|
|
Rocket tries to prevent an application with unmanaged state from ever running
|
|
|
|
via the `unmanaged_state` lint. The lint reads through your code at compile-time
|
|
|
|
and emits a warning when a `State<T>` request guard is being used in a mounted
|
|
|
|
route for a type `T` that isn't being managed.
|
|
|
|
|
|
|
|
As an example, consider the following short application using our `HitCount`
|
|
|
|
type from previous examples:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
#[get("/count")]
|
2017-04-30 21:32:21 +00:00
|
|
|
fn count(hit_count: State<HitCount>) -> String {
|
2017-07-06 08:58:57 +00:00
|
|
|
let current_count = hit_count.count.load(Ordering::Relaxed);
|
2017-04-17 02:48:59 +00:00
|
|
|
format!("Number of visits: {}", current_count)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
rocket::ignite()
|
|
|
|
.manage(Config::from(user_input))
|
|
|
|
.launch()
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
The application is buggy: a value for `HitCount` isn't being `managed`, but a
|
|
|
|
`State<HitCount>` type is being requested in the `count` route. When we compile
|
|
|
|
this application, Rocket emits the following warning:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
warning: HitCount is not currently being managed by Rocket
|
|
|
|
--> src/main.rs:2:17
|
|
|
|
|
|
2017-04-30 21:32:21 +00:00
|
|
|
2 | fn count(hit_count: State<HitCount>) -> String {
|
2017-07-10 11:59:55 +00:00
|
|
|
| ^^^^^^^^
|
2017-04-17 02:48:59 +00:00
|
|
|
|
|
|
|
|
= note: this State request guard will always fail
|
|
|
|
help: maybe add a call to 'manage' here?
|
|
|
|
--> src/main.rs:8:5
|
|
|
|
|
|
|
|
|
8 | rocket::ignite()
|
|
|
|
| ^^^^^^^^^^^^^^^^
|
|
|
|
```
|
|
|
|
|
|
|
|
The `unmanaged_state` lint isn't perfect. In particular, it cannot track calls
|
2017-07-06 08:58:57 +00:00
|
|
|
to `manage` across function boundaries. Because of this, you may find yourself
|
|
|
|
with incorrect warnings. You can disable the lint on a per-route basis by adding
|
|
|
|
`#[allow(unmanaged_state)]` to a route handler. If you wish to disable the lint
|
|
|
|
globally, add `#![allow(unmanaged_state)]` to your crate attributes.
|
2017-04-17 02:48:59 +00:00
|
|
|
|
2017-07-06 08:58:57 +00:00
|
|
|
You can find a complete example using the `HitCount` structure in the [state
|
2017-04-17 02:48:59 +00:00
|
|
|
example on
|
2017-08-11 16:32:27 +00:00
|
|
|
GitHub](https://github.com/SergioBenitez/Rocket/tree/v0.4.0-dev/examples/state) and
|
2017-07-10 11:59:55 +00:00
|
|
|
learn more about the [`manage`
|
2017-04-17 02:48:59 +00:00
|
|
|
method](https://api.rocket.rs/rocket/struct.Rocket.html#method.manage) and
|
2017-07-10 11:59:55 +00:00
|
|
|
[`State` type](https://api.rocket.rs/rocket/struct.State.html) in the API docs.
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-08-08 05:29:38 +00:00
|
|
|
### Request-Local State
|
|
|
|
|
|
|
|
While managed state is *global* and available application-wide, request-local
|
|
|
|
state is *local* to a given request, carried along with the request, and dropped
|
|
|
|
once the request is completed. Request-local state can be used whenever a
|
|
|
|
`Request` is available, such as in a fairing, a request guard, or a responder.
|
|
|
|
|
|
|
|
Request-local state is *cached*: if data of a given type has already been
|
|
|
|
stored, it will be reused. This is especially useful for request guards that
|
|
|
|
might be invoked multiple times during routing and processing of a single
|
|
|
|
request, such as those that deal with authentication.
|
|
|
|
|
|
|
|
As an example, consider the following request guard implementation for
|
|
|
|
`RequestId` that uses request-local state to generate and expose a unique
|
|
|
|
integer ID per request:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
/// A global atomic counter for generating IDs.
|
|
|
|
static request_id_counter: AtomicUsize = AtomicUsize::new(0);
|
|
|
|
|
|
|
|
/// A type that represents a request's ID.
|
|
|
|
struct RequestId(pub usize);
|
|
|
|
|
|
|
|
/// Returns the current request's ID, assigning one only as necessary.
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for RequestId {
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome {
|
|
|
|
// The closure passed to `local_cache` will be executed at most once per
|
|
|
|
// request: the first time the `RequestId` guard is used. If it is
|
|
|
|
// requested again, `local_cache` will return the same value.
|
|
|
|
Outcome::Success(request.local_cache(|| {
|
|
|
|
RequestId(request_id_counter.fetch_add(1, Ordering::Relaxed))
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
Note that, without request-local state, it would not be possible to:
|
|
|
|
|
|
|
|
1. Associate a piece of data, here an ID, directly with a request.
|
|
|
|
2. Ensure that a value is generated at most once per request.
|
|
|
|
|
|
|
|
For more examples, see the [`FromRequest`] documentation, which uses
|
|
|
|
request-local state to cache expensive authentication and authorization
|
|
|
|
computations, and the [`Fairing`] documentation, which uses request-local state
|
|
|
|
to implement request timing.
|
|
|
|
|
|
|
|
[`FromRequest`]: https://api.rocket.rs/rocket/request/trait.FromRequest.htmll#request-local-state
|
|
|
|
[`Fairing`]: https://api.rocket.rs/rocket/fairing/trait.Fairing.html#request-local-state
|
|
|
|
|
2017-07-06 08:58:57 +00:00
|
|
|
## Databases
|
|
|
|
|
|
|
|
While Rocket doesn't have built-in support for databases yet, you can combine a
|
|
|
|
few external libraries to get native-feeling access to databases in a Rocket
|
|
|
|
application. Let's take a look at how we might integrate Rocket with two common
|
|
|
|
database libraries: [`diesel`], a type-safe ORM and query builder, and [`r2d2`],
|
|
|
|
a library for connection pooling.
|
|
|
|
|
|
|
|
Our approach will be to have Rocket manage a pool of database connections using
|
|
|
|
managed state and then implement a request guard that retrieves one connection.
|
|
|
|
This will allow us to get access to the database in a handler by simply adding a
|
|
|
|
`DbConn` argument:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
#[get("/users")]
|
|
|
|
fn handler(conn: DbConn) { ... }
|
|
|
|
```
|
|
|
|
|
|
|
|
[`diesel`]: http://diesel.rs/
|
2017-12-29 23:03:06 +00:00
|
|
|
[`r2d2`]: https://docs.rs/r2d2/
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
### Dependencies
|
|
|
|
|
|
|
|
To get started, we need to depend on the `diesel` and `r2d2` crates. For
|
|
|
|
detailed information on how to use Diesel, please see the [Diesel getting
|
|
|
|
started guide](http://diesel.rs/guides/getting-started/). For this example, we
|
|
|
|
use the following dependencies:
|
|
|
|
|
2017-07-10 11:59:55 +00:00
|
|
|
```
|
2017-07-06 08:58:57 +00:00
|
|
|
[dependencies]
|
2017-08-11 16:32:27 +00:00
|
|
|
rocket = "0.4.0-dev"
|
2018-02-21 15:47:50 +00:00
|
|
|
rocket_codegen = "0.4.0-dev"
|
2018-05-28 15:20:39 +00:00
|
|
|
diesel = { version = "<= 1.2", features = ["sqlite", "r2d2"] }
|
2017-07-06 08:58:57 +00:00
|
|
|
```
|
|
|
|
|
2017-12-29 23:03:06 +00:00
|
|
|
Your `diesel` dependency information may differ. The crates are imported as
|
|
|
|
well:
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
```rust
|
|
|
|
extern crate rocket;
|
|
|
|
#[macro_use] extern crate diesel;
|
|
|
|
```
|
|
|
|
|
|
|
|
### Managed Pool
|
|
|
|
|
|
|
|
The first step is to initialize a pool of database connections. The `init_pool`
|
|
|
|
function below uses `r2d2` to create a new pool of database connections. Diesel
|
|
|
|
advocates for using a `DATABASE_URL` environment variable to set the database
|
|
|
|
URL, and we use the same convention here. Excepting the long-winded types, the
|
|
|
|
code is fairly straightforward: the `DATABASE_URL` environment variable is
|
|
|
|
stored in the `DATABASE_URL` static, and an `r2d2::Pool` is created using the
|
2017-07-10 11:59:55 +00:00
|
|
|
default configuration parameters and a Diesel `SqliteConnection`
|
2017-07-06 08:58:57 +00:00
|
|
|
`ConnectionManager`.
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use diesel::sqlite::SqliteConnection;
|
2018-02-21 15:47:50 +00:00
|
|
|
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
// An alias to the type for a pool of Diesel SQLite connections.
|
2018-02-21 15:47:50 +00:00
|
|
|
type SqlitePool = Pool<ConnectionManager<SqliteConnection>>;
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
// The URL to the database, set via the `DATABASE_URL` environment variable.
|
|
|
|
static DATABASE_URL: &'static str = env!("DATABASE_URL");
|
|
|
|
|
|
|
|
/// Initializes a database pool.
|
2018-05-05 02:32:16 +00:00
|
|
|
fn init_pool() -> SqlitePool {
|
2017-07-06 08:58:57 +00:00
|
|
|
let manager = ConnectionManager::<SqliteConnection>::new(DATABASE_URL);
|
2018-02-21 15:47:50 +00:00
|
|
|
Pool::new(manager).expect("db pool")
|
2017-07-06 08:58:57 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
We then use managed state to have Rocket manage the pool for us:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
fn main() {
|
|
|
|
rocket::ignite()
|
|
|
|
.manage(init_pool())
|
|
|
|
.launch();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2017-07-10 11:59:55 +00:00
|
|
|
### Connection Guard
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
The second and final step is to implement a request guard that retrieves a
|
|
|
|
single connection from the managed connection pool. We create a new type,
|
|
|
|
`DbConn`, that wraps an `r2d2` pooled connection. We then implement
|
|
|
|
`FromRequest` for `DbConn` so that we can use it as a request guard. Finally, we
|
|
|
|
implement `Deref` with a target of `SqliteConnection` so that we can
|
2017-08-09 20:31:22 +00:00
|
|
|
transparently use an `&*DbConn` as an `&SqliteConnection`.
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
```rust
|
|
|
|
use std::ops::Deref;
|
|
|
|
use rocket::http::Status;
|
|
|
|
use rocket::request::{self, FromRequest};
|
|
|
|
use rocket::{Request, State, Outcome};
|
2018-02-21 15:47:50 +00:00
|
|
|
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
// Connection request guard type: a wrapper around an r2d2 pooled connection.
|
2018-02-21 15:47:50 +00:00
|
|
|
pub struct DbConn(pub PooledConnection<ConnectionManager<SqliteConnection>>);
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
/// Attempts to retrieve a single connection from the managed database pool. If
|
|
|
|
/// no pool is currently managed, fails with an `InternalServerError` status. If
|
|
|
|
/// no connections are available, fails with a `ServiceUnavailable` status.
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
|
|
|
|
type Error = ();
|
|
|
|
|
2018-02-21 15:47:50 +00:00
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
let pool = request.guard::<State<SqlitePool>>()?;
|
2017-07-06 08:58:57 +00:00
|
|
|
match pool.get() {
|
|
|
|
Ok(conn) => Outcome::Success(DbConn(conn)),
|
|
|
|
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// For the convenience of using an &DbConn as an &SqliteConnection.
|
|
|
|
impl Deref for DbConn {
|
|
|
|
type Target = SqliteConnection;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### Usage
|
|
|
|
|
|
|
|
With these two pieces in place, we can use `DbConn` as a request guard in any
|
|
|
|
handler or other request guard implementation, giving our application access to
|
|
|
|
a database. As a simple example, we might write a route that returns a JSON
|
|
|
|
array of some `Task` structures that are fetched from a database:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
#[get("/tasks")]
|
2017-07-12 22:11:41 +00:00
|
|
|
fn get_tasks(conn: DbConn) -> QueryResult<Json<Vec<Task>>> {
|
2017-07-06 08:58:57 +00:00
|
|
|
all_tasks.order(tasks::id.desc())
|
2017-08-09 20:31:22 +00:00
|
|
|
.load::<Task>(&*conn)
|
2017-07-12 22:11:41 +00:00
|
|
|
.map(|tasks| Json(tasks))
|
2017-07-06 08:58:57 +00:00
|
|
|
}
|
|
|
|
```
|