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`.
|
|
|
|
|
2018-10-22 21:47:35 +00:00
|
|
|
! note: All managed state must be thread-safe.
|
|
|
|
|
2018-11-13 14:47:11 +00:00
|
|
|
Because Rocket automatically multithreads your application, handlers can
|
2018-10-22 21:47:35 +00:00
|
|
|
concurrently access managed state. As a result, managed state must be
|
|
|
|
thread-safe. Thanks to Rust, this condition is checked at compile-time by
|
|
|
|
ensuring that the type of values you store in managed state implement `Send` +
|
|
|
|
`Sync`.
|
|
|
|
|
2017-04-17 02:48:59 +00:00
|
|
|
### Adding State
|
|
|
|
|
|
|
|
To instruct Rocket to manage state for your application, call the
|
2018-10-16 05:50:35 +00:00
|
|
|
[`manage`](@api/rocket/struct.Rocket.html#method.manage) method
|
2017-07-06 08:58:57 +00:00
|
|
|
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
|
2018-10-22 21:47:35 +00:00
|
|
|
use std::sync::atomic::AtomicUsize;
|
|
|
|
|
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
|
2020-02-15 11:43:47 +00:00
|
|
|
# use std::sync::atomic::AtomicUsize;
|
|
|
|
# struct HitCount { count: AtomicUsize }
|
|
|
|
# type Config = &'static str;
|
|
|
|
# let user_input = "input";
|
|
|
|
|
2017-04-17 02:48:59 +00:00
|
|
|
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
|
2018-10-16 05:50:35 +00:00
|
|
|
[`State`](@api/rocket/struct.State.html) type: a [request
|
|
|
|
guard](../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
|
2020-02-15 11:43:47 +00:00
|
|
|
# #[macro_use] extern crate rocket;
|
|
|
|
# fn main() {}
|
|
|
|
|
|
|
|
# use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
# struct HitCount { count: AtomicUsize }
|
|
|
|
|
2018-10-22 21:47:35 +00:00
|
|
|
use rocket::State;
|
|
|
|
|
2017-04-17 02:48:59 +00:00
|
|
|
#[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
|
2020-02-15 11:43:47 +00:00
|
|
|
# #[macro_use] extern crate rocket;
|
|
|
|
# fn main() {}
|
|
|
|
|
|
|
|
# struct HitCount;
|
|
|
|
# struct Config;
|
|
|
|
# use rocket::State;
|
|
|
|
|
2017-04-17 02:48:59 +00:00
|
|
|
#[get("/state")]
|
2020-02-15 11:43:47 +00:00
|
|
|
fn state(hit_count: State<HitCount>, config: State<Config>) { /* .. */ }
|
2017-04-17 02:48:59 +00:00
|
|
|
```
|
|
|
|
|
2018-10-22 21:47:35 +00:00
|
|
|
! warning
|
|
|
|
|
|
|
|
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.
|
2018-08-08 06:55:25 +00:00
|
|
|
|
|
|
|
You can find a complete example using the `HitCount` structure in the [state
|
2018-10-16 05:50:35 +00:00
|
|
|
example on GitHub](@example/state) and learn more about the [`manage`
|
|
|
|
method](@api/rocket/struct.Rocket.html#method.manage) and [`State`
|
|
|
|
type](@api/rocket/struct.State.html) in the API docs.
|
2018-08-08 06:55:25 +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
|
2020-02-15 11:43:47 +00:00
|
|
|
# #[macro_use] extern crate rocket;
|
|
|
|
# fn main() {}
|
|
|
|
|
|
|
|
use rocket::State;
|
|
|
|
use rocket::request::{self, Request, FromRequest};
|
|
|
|
# use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
|
|
|
|
# struct T;
|
|
|
|
# struct HitCount { count: AtomicUsize }
|
|
|
|
# type ErrorType = ();
|
2020-07-11 16:41:53 +00:00
|
|
|
#[rocket::async_trait]
|
2020-02-15 11:43:47 +00:00
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for T {
|
|
|
|
type Error = ErrorType;
|
|
|
|
|
2020-07-11 16:41:53 +00:00
|
|
|
async fn from_request(req: &'a Request<'r>) -> request::Outcome<T, Self::Error> {
|
|
|
|
let hit_count_state = try_outcome!(req.guard::<State<HitCount>>().await);
|
2020-02-15 11:43:47 +00:00
|
|
|
let current_count = hit_count_state.count.load(Ordering::Relaxed);
|
|
|
|
/* ... */
|
|
|
|
# request::Outcome::Success(T)
|
|
|
|
}
|
2017-04-17 02:48:59 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-10-16 05:50:35 +00:00
|
|
|
[`Request::guard()`]: @api/rocket/struct.Request.html#method.guard
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-10-22 21:47:35 +00:00
|
|
|
## Request-Local State
|
2018-08-08 05:29:38 +00:00
|
|
|
|
|
|
|
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
|
2020-02-15 11:43:47 +00:00
|
|
|
# #[macro_use] extern crate rocket;
|
|
|
|
# fn main() {}
|
|
|
|
# use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
|
|
|
|
use rocket::request::{self, Request, FromRequest};
|
|
|
|
|
2018-08-08 05:29:38 +00:00
|
|
|
/// A global atomic counter for generating IDs.
|
2020-02-15 11:43:47 +00:00
|
|
|
static ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
|
2018-08-08 05:29:38 +00:00
|
|
|
|
|
|
|
/// A type that represents a request's ID.
|
|
|
|
struct RequestId(pub usize);
|
|
|
|
|
|
|
|
/// Returns the current request's ID, assigning one only as necessary.
|
2020-07-11 16:41:53 +00:00
|
|
|
#[rocket::async_trait]
|
2020-02-15 11:43:47 +00:00
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for &'a RequestId {
|
|
|
|
type Error = ();
|
|
|
|
|
2020-07-11 16:41:53 +00:00
|
|
|
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
2018-08-08 05:29:38 +00:00
|
|
|
// 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.
|
2020-02-15 11:43:47 +00:00
|
|
|
request::Outcome::Success(request.local_cache(|| {
|
|
|
|
RequestId(ID_COUNTER.fetch_add(1, Ordering::Relaxed))
|
2018-08-08 05:29:38 +00:00
|
|
|
}))
|
|
|
|
}
|
|
|
|
}
|
2020-02-15 11:43:47 +00:00
|
|
|
|
|
|
|
#[get("/")]
|
|
|
|
fn id(id: &RequestId) -> String {
|
|
|
|
format!("This is request #{}.", id.0)
|
|
|
|
}
|
2018-08-08 05:29:38 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
Note that, without request-local state, it would not be possible to:
|
|
|
|
|
2018-10-22 21:47:35 +00:00
|
|
|
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.
|
2018-08-08 05:29:38 +00:00
|
|
|
|
2018-10-16 06:24:23 +00:00
|
|
|
For more examples, see the [`FromRequest` request-local state] 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.
|
2018-08-08 05:29:38 +00:00
|
|
|
|
2018-10-16 06:24:23 +00:00
|
|
|
[`FromRequest` request-local state]: @api/rocket/request/trait.FromRequest.html#request-local-state
|
2018-10-16 05:50:35 +00:00
|
|
|
[`Fairing`]: @api/rocket/fairing/trait.Fairing.html#request-local-state
|
2018-08-08 05:29:38 +00:00
|
|
|
|
2017-07-06 08:58:57 +00:00
|
|
|
## Databases
|
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
Rocket includes built-in, ORM-agnostic support for databases. In particular,
|
|
|
|
Rocket provides a procedural macro that allows you to easily connect your Rocket
|
|
|
|
application to databases through connection pools. A _database connection pool_
|
|
|
|
is a data structure that maintains active database connections for later use in
|
|
|
|
the application. This implementation of connection pooling support is based on
|
|
|
|
[`r2d2`] and exposes connections through request guards. Databases are
|
|
|
|
individually configured through Rocket's regular configuration mechanisms: a
|
|
|
|
`Rocket.toml` file, environment variables, or procedurally.
|
|
|
|
|
|
|
|
Connecting your Rocket application to a database using this library occurs in
|
|
|
|
three simple steps:
|
|
|
|
|
|
|
|
1. Configure the databases in `Rocket.toml`.
|
|
|
|
2. Associate a request guard type and fairing with each database.
|
2020-07-11 18:17:43 +00:00
|
|
|
3. Use the request guard to retrieve and use a connection in a handler.
|
2018-08-15 09:07:17 +00:00
|
|
|
|
|
|
|
Presently, Rocket provides built-in support for the following databases:
|
|
|
|
|
2019-05-27 17:43:15 +00:00
|
|
|
<!-- Note: Keep this table in sync with contrib/lib/src/databases.rs -->
|
|
|
|
| Kind | Driver | Version | `Poolable` Type | Feature |
|
|
|
|
|----------|-----------------------|-----------|--------------------------------|------------------------|
|
|
|
|
| MySQL | [Diesel] | `1` | [`diesel::MysqlConnection`] | `diesel_mysql_pool` |
|
2020-07-14 18:01:42 +00:00
|
|
|
| MySQL | [`rust-mysql-simple`] | `18` | [`mysql::Conn`] | `mysql_pool` |
|
2019-05-27 17:43:15 +00:00
|
|
|
| Postgres | [Diesel] | `1` | [`diesel::PgConnection`] | `diesel_postgres_pool` |
|
2020-01-20 22:50:37 +00:00
|
|
|
| Postgres | [Rust-Postgres] | `0.17` | [`postgres::Client`] | `postgres_pool` |
|
2019-05-27 17:43:15 +00:00
|
|
|
| Sqlite | [Diesel] | `1` | [`diesel::SqliteConnection`] | `diesel_sqlite_pool` |
|
2020-07-14 18:04:13 +00:00
|
|
|
| Sqlite | [`Rusqlite`] | `0.23` | [`rusqlite::Connection`] | `sqlite_pool` |
|
2021-01-09 19:02:48 +00:00
|
|
|
| Memcache | [`memcache`] | `0.15` | [`memcache::Client`] | `memcache_pool` |
|
2018-08-15 09:07:17 +00:00
|
|
|
|
|
|
|
[`r2d2`]: https://crates.io/crates/r2d2
|
|
|
|
[Diesel]: https://diesel.rs
|
2020-07-14 18:04:13 +00:00
|
|
|
[`rusqlite::Connection`]: https://docs.rs/rusqlite/0.23.0/rusqlite/struct.Connection.html
|
2021-01-21 01:28:54 +00:00
|
|
|
[`diesel::SqliteConnection`]: https://docs.diesel.rs/diesel/prelude/struct.SqliteConnection.html
|
2020-01-20 22:50:37 +00:00
|
|
|
[`postgres::Client`]: https://docs.rs/postgres/0.17/postgres/struct.Client.html
|
2021-01-21 01:28:54 +00:00
|
|
|
[`diesel::PgConnection`]: https://docs.diesel.rs/diesel/pg/struct.PgConnection.html
|
2020-07-14 18:01:42 +00:00
|
|
|
[`mysql::Conn`]: https://docs.rs/mysql/18/mysql/struct.Conn.html
|
2021-01-21 01:28:54 +00:00
|
|
|
[`diesel::MysqlConnection`]: https://docs.diesel.rs/diesel/mysql/struct.MysqlConnection.html
|
2020-01-20 22:50:37 +00:00
|
|
|
[`Rusqlite`]: https://github.com/jgallagher/rusqlite
|
2018-08-15 09:07:17 +00:00
|
|
|
[Rust-Postgres]: https://github.com/sfackler/rust-postgres
|
|
|
|
[`rust-mysql-simple`]: https://github.com/blackbeam/rust-mysql-simple
|
2021-01-21 01:28:54 +00:00
|
|
|
[`diesel::PgConnection`]: https://docs.diesel.rs/diesel/pg/struct.PgConnection.html
|
2019-01-04 16:19:09 +00:00
|
|
|
[`memcache`]: https://github.com/aisk/rust-memcache
|
2021-01-09 19:02:48 +00:00
|
|
|
[`memcache::Client`]: https://docs.rs/memcache/0.15/memcache/struct.Client.html
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
### Usage
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
To connect your Rocket application to a given database, first identify the
|
|
|
|
"Kind" and "Driver" in the table that matches your environment. The feature
|
|
|
|
corresponding to your database type must be enabled. This is the feature
|
|
|
|
identified in the "Feature" column. For instance, for Diesel-based SQLite
|
|
|
|
databases, you'd write in `Cargo.toml`:
|
|
|
|
|
|
|
|
```toml
|
|
|
|
[dependencies.rocket_contrib]
|
2019-05-13 23:18:48 +00:00
|
|
|
version = "0.5.0-dev"
|
2018-08-15 09:07:17 +00:00
|
|
|
default-features = false
|
|
|
|
features = ["diesel_sqlite_pool"]
|
2017-07-06 08:58:57 +00:00
|
|
|
```
|
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
Then, in `Rocket.toml` or the equivalent via environment variables, configure
|
|
|
|
the URL for the database in the `databases` table:
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
```toml
|
|
|
|
[global.databases]
|
|
|
|
sqlite_logs = { url = "/path/to/database.sqlite" }
|
2017-07-06 08:58:57 +00:00
|
|
|
```
|
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
In your application's source code, create a unit-like struct with one internal
|
|
|
|
type. This type should be the type listed in the "`Poolable` Type" column. Then
|
|
|
|
decorate the type with the `#[database]` attribute, providing the name of the
|
|
|
|
database that you configured in the previous step as the only parameter.
|
2019-08-22 17:18:44 +00:00
|
|
|
You will need to either add `#[macro_use] extern crate rocket_contrib` to the
|
|
|
|
crate root or have a `use rocket_contrib::database` in scope, otherwise the
|
|
|
|
`database` attribute will not be available.
|
2018-08-15 09:07:17 +00:00
|
|
|
Finally, attach the fairing returned by `YourType::fairing()`, which was
|
|
|
|
generated by the `#[database]` attribute:
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
```rust
|
2020-02-15 11:43:47 +00:00
|
|
|
# #[macro_use] extern crate rocket;
|
2018-10-16 06:24:23 +00:00
|
|
|
#[macro_use] extern crate rocket_contrib;
|
|
|
|
|
|
|
|
use rocket_contrib::databases::diesel;
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
#[database("sqlite_logs")]
|
|
|
|
struct LogsDbConn(diesel::SqliteConnection);
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2020-07-22 23:10:02 +00:00
|
|
|
#[launch]
|
2020-07-11 16:42:05 +00:00
|
|
|
fn rocket() -> rocket::Rocket {
|
|
|
|
rocket::ignite().attach(LogsDbConn::fairing())
|
2017-07-06 08:58:57 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
That's it! Whenever a connection to the database is needed, use your type as a
|
2020-07-11 18:17:43 +00:00
|
|
|
request guard. The database can be accessed by calling the `run` method:
|
2017-07-06 08:58:57 +00:00
|
|
|
|
|
|
|
```rust
|
2020-02-15 11:43:47 +00:00
|
|
|
# #[macro_use] extern crate rocket;
|
|
|
|
# #[macro_use] extern crate rocket_contrib;
|
|
|
|
# fn main() {}
|
|
|
|
|
|
|
|
# use rocket_contrib::databases::diesel;
|
|
|
|
|
|
|
|
# #[database("sqlite_logs")]
|
|
|
|
# struct LogsDbConn(diesel::SqliteConnection);
|
|
|
|
# type Logs = ();
|
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
#[get("/logs/<id>")]
|
2020-07-11 18:17:43 +00:00
|
|
|
async fn get_logs(conn: LogsDbConn, id: usize) -> Logs {
|
2020-02-15 11:43:47 +00:00
|
|
|
# /*
|
2020-07-11 18:17:43 +00:00
|
|
|
conn.run(|c| logs::filter(id.eq(log_id)).load(c)).await
|
2020-02-15 11:43:47 +00:00
|
|
|
# */
|
2017-07-06 08:58:57 +00:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-02-16 03:47:50 +00:00
|
|
|
! note The above examples uses [Diesel] with some fictional `Logs` type.
|
|
|
|
|
|
|
|
The example above contains the use of a `Logs` type that is application
|
|
|
|
specific and not built into Rocket. It also uses [Diesel]'s query-building
|
|
|
|
syntax. Rocket does not provide an ORM. It is up to you to decide how to model
|
|
|
|
your application's data.
|
|
|
|
|
2020-07-11 18:17:43 +00:00
|
|
|
! note
|
|
|
|
|
|
|
|
The database engines supported by `#[database]` are *synchronous*. Normally,
|
|
|
|
using such a database would block the thread of execution. To prevent this,
|
|
|
|
the `run()` function automatically uses a thread pool so that database access
|
|
|
|
does not interfere with other in-flight requests. See [Cooperative
|
|
|
|
Multitasking](../overview/#cooperative-multitasking) for more information on
|
|
|
|
why this is necessary.
|
|
|
|
|
2019-05-27 17:43:15 +00:00
|
|
|
If your application uses features of a database engine that are not available
|
|
|
|
by default, for example support for `chrono` or `uuid`, you may enable those
|
|
|
|
features by adding them in `Cargo.toml` like so:
|
|
|
|
|
|
|
|
```toml
|
|
|
|
[dependencies]
|
|
|
|
postgres = { version = "0.15", features = ["with-chrono"] }
|
|
|
|
```
|
|
|
|
|
2018-08-15 09:07:17 +00:00
|
|
|
For more on Rocket's built-in database support, see the
|
|
|
|
[`rocket_contrib::databases`] module documentation.
|
2017-07-06 08:58:57 +00:00
|
|
|
|
2018-10-16 05:50:35 +00:00
|
|
|
[`rocket_contrib::databases`]: @api/rocket_contrib/databases/index.html
|