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 manage method on an instance of Rocket. For example, to ask Rocket to manage a HitCount structure with an internal AtomicUsize with an initial value of 0, we can write the following:

  1. struct HitCount {
  2. count: AtomicUsize
  3. }
  4. rocket::ignite().manage(HitCount { count: AtomicUsize::new(0) });

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:

  1. rocket::ignite()
  2. .manage(HitCount { count: AtomicUsize::new(0) })
  3. .manage(Config::from(user_input));

Retrieving State

State that is being managed by Rocket can be retrieved via the State type: a request guard for managed state. To use the request 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:

  1. #[get("/count")]
  2. fn count(hit_count: State<HitCount>) -> String {
  3. let current_count = hit_count.count.load(Ordering::Relaxed);
  4. format!("Number of visits: {}", current_count)
  5. }

You can retrieve more than one State type in a single route as well:

  1. #[get("/state")]
  2. fn state(hit_count: State<HitCount>, config: State<Config>) -> T { ... }

Within Guards

It can also be useful to retrieve managed state from a FromRequest implementation. To do so, simply invoke State<T> as a guard using the Request::guard() method.

  1. fn from_request(req: &'a Request<'r>) -> request::Outcome<T, ()> {
  2. let hit_count_state = req.guard::<State<HitCount>>()?;
  3. let current_count = hit_count_state.count.load(Ordering::Relaxed);
  4. ...
  5. }

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:

  1. #[get("/count")]
  2. fn count(hit_count: State<HitCount>) -> String {
  3. let current_count = hit_count.count.load(Ordering::Relaxed);
  4. format!("Number of visits: {}", current_count)
  5. }
  6. fn main() {
  7. rocket::ignite()
  8. .manage(Config::from(user_input))
  9. .launch()
  10. }

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:

  1. warning: HitCount is not currently being managed by Rocket
  2. --> src/main.rs:2:17
  3. |
  4. 2 | fn count(hit_count: State<HitCount>) -> String {
  5. | ^^^^^^^^
  6. |
  7. = note: this State request guard will always fail
  8. help: maybe add a call to 'manage' here?
  9. --> src/main.rs:8:5
  10. |
  11. 8 | rocket::ignite()
  12. | ^^^^^^^^^^^^^^^^

The unmanaged_state lint isn’t perfect. In particular, it cannot track calls 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.

You can find a complete example using the HitCount structure in the state example on GitHub and learn more about the manage method and State type in the API docs.