Skip to main content

rocket/
lib.rs

1#![recursion_limit="256"]
2
3#![doc(html_root_url = "https://api.rocket.rs/v0.6-rc")]
4#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
5#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
6#![cfg_attr(nightly, feature(doc_cfg))]
7#![cfg_attr(nightly, feature(decl_macro))]
8
9//! # Rocket - Core API Documentation
10//!
11//! Hello, and welcome to the core Rocket API documentation!
12//!
13//! This API documentation is highly technical and is purely a reference.
14//! There's an [overview] of Rocket on the main site as well as a [full,
15//! detailed guide]. If you'd like pointers on getting started, see the
16//! [quickstart] or [getting started] chapters of the guide.
17//!
18//! [overview]: https://rocket.rs/v0.6-rc/overview
19//! [full, detailed guide]: https://rocket.rs/v0.6-rc/guide
20//! [quickstart]: https://rocket.rs/v0.6-rc/guide/quickstart
21//! [getting started]: https://rocket.rs/v0.6-rc/guide/getting-started
22//!
23//! ## Usage
24//!
25//! Depend on `rocket` in `Cargo.toml`:
26//!
27//! ```toml
28//! [dependencies]
29//! rocket = "=0.6.0-rc.1"
30//! ```
31//!
32//! <small>Note that development versions, tagged with `-dev`, are not published
33//! and need to be specified as [git dependencies].</small>
34//!
35//! See the [guide](https://rocket.rs/v0.6-rc/guide) for more information on how
36//! to write Rocket applications. Here's a simple example to get you started:
37//!
38//! [git dependencies]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-dependencies-from-git-repositories
39//!
40//! ```rust,no_run
41//! #[macro_use] extern crate rocket;
42//!
43//! #[get("/")]
44//! fn hello() -> &'static str {
45//!     "Hello, world!"
46//! }
47//!
48//! #[launch]
49//! fn rocket() -> _ {
50//!     rocket::build().mount("/", routes![hello])
51//! }
52//! ```
53//!
54//! ## Features
55//!
56//! To avoid compiling unused dependencies, Rocket feature-gates optional
57//! functionality, some enabled by default:
58//!
59//! | Feature         | Default? | Description                                             |
60//! |-----------------|----------|---------------------------------------------------------|
61//! | `trace`         | Yes      | Enables the default Rocket tracing [subscriber].        |
62//! | `http2`         | Yes      | Support for HTTP/2 (enabled by default).                |
63//! | `tokio-macros`  | Yes      | Enables the `macros` feature in the exported `tokio`.   |
64//! | `secrets`       | No       | Support for authenticated, encrypted [private cookies]. |
65//! | `tls`           | No       | Support for [TLS] encrypted connections.                |
66//! | `mtls`          | No       | Support for verified clients via [mutual TLS].          |
67//! | `json`          | No       | Support for [JSON (de)serialization].                   |
68//! | `xml`           | No       | Support for [XML (de)serialization].                    |
69//! | `msgpack`       | No       | Support for [MessagePack (de)serialization].            |
70//! | `uuid`          | No       | Support for [UUID value parsing and (de)serialization]. |
71//! | `http3-preview` | No       | Experimental preview support for [HTTP/3].              |
72//!
73//! Disabled features can be selectively enabled in `Cargo.toml`:
74//!
75//! ```toml
76//! [dependencies]
77//! rocket = { version = "=0.6.0-rc.1", features = ["secrets", "tls", "json"] }
78//! ```
79//!
80//! Conversely, the default features, including HTTP/2, can be disabled:
81//!
82//! ```toml
83//! [dependencies]
84//! rocket = { version = "=0.6.0-rc.1", default-features = false }
85//! ```
86//!
87//! [subscriber]: crate::trace::subscriber
88//! [JSON (de)serialization]: crate::serde::json
89//! [XML (de)serialization]: crate::serde::xml
90//! [MessagePack (de)serialization]: crate::serde::msgpack
91//! [UUID value parsing and (de)serialization]: crate::serde::uuid
92//! [private cookies]: https://rocket.rs/v0.6-rc/guide/requests/#private-cookies
93//! [TLS]: https://rocket.rs/v0.6-rc/guide/configuration/#tls
94//! [mutual TLS]: crate::mtls
95//! [HTTP/3]: crate::listener::quic
96//!
97//! ## Configuration
98//!
99//! Rocket offers a rich, extensible configuration system built on [Figment]. By
100//! default, Rocket applications are configured via a `Rocket.toml` file
101//! and/or `ROCKET_{PARAM}` environment variables, but applications may
102//! configure their own sources. See the [configuration guide] for full details.
103//!
104//! ## Testing
105//!
106//! The [`local`] module contains structures that facilitate unit and
107//! integration testing of a Rocket application. The top-level [`local`] module
108//! documentation and the [testing guide] include detailed examples.
109//!
110//! [configuration guide]: https://rocket.rs/v0.6-rc/guide/configuration/
111//! [testing guide]: https://rocket.rs/v0.6-rc/guide/testing/#testing
112//! [Figment]: https://docs.rs/figment
113
114// Allows using Rocket's codegen in Rocket itself.
115extern crate self as rocket;
116
117/// These are public dependencies! Update docs if these are changed, especially
118/// figment's version number in docs.
119#[doc(hidden)]
120pub use yansi;
121#[doc(hidden)]
122pub use async_stream;
123pub use futures;
124pub use tokio;
125pub use figment;
126pub use time;
127pub use tracing;
128pub use either;
129
130#[macro_use]
131pub mod trace;
132#[macro_use]
133pub mod outcome;
134#[macro_use]
135pub mod data;
136#[doc(hidden)]
137pub mod sentinel;
138pub mod local;
139pub mod request;
140pub mod response;
141pub mod config;
142pub mod form;
143pub mod fairing;
144pub mod error;
145pub mod catcher;
146pub mod route;
147pub mod serde;
148pub mod shield;
149pub mod fs;
150pub mod http;
151pub mod listener;
152pub mod shutdown;
153#[cfg(feature = "tls")]
154#[cfg_attr(nightly, doc(cfg(feature = "tls")))]
155pub mod tls;
156#[cfg(feature = "mtls")]
157#[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
158pub mod mtls;
159
160#[path = "rocket.rs"]
161mod rkt;
162mod util;
163mod server;
164mod lifecycle;
165mod state;
166mod router;
167mod phase;
168mod erased;
169
170#[doc(inline)] pub use rocket_codegen::*;
171
172#[doc(inline)] pub use crate::response::Response;
173#[doc(inline)] pub use crate::data::Data;
174#[doc(inline)] pub use crate::config::Config;
175#[doc(inline)] pub use crate::catcher::Catcher;
176#[doc(inline)] pub use crate::route::Route;
177#[doc(inline)] pub use crate::phase::{Phase, Build, Ignite, Orbit};
178#[doc(inline)] pub use crate::error::Error;
179#[doc(inline)] pub use crate::sentinel::{Sentinel, Sentry};
180#[doc(inline)] pub use crate::request::Request;
181#[doc(inline)] pub use crate::rkt::Rocket;
182#[doc(inline)] pub use crate::shutdown::Shutdown;
183#[doc(inline)] pub use crate::state::State;
184
185/// Retrofits support for `async fn` in trait impls and declarations.
186///
187/// Any trait declaration or trait `impl` decorated with `#[async_trait]` is
188/// retrofitted with support for `async fn`s:
189///
190/// ```rust
191/// # use rocket::*;
192/// #[async_trait]
193/// trait MyAsyncTrait {
194///     async fn do_async_work();
195/// }
196///
197/// #[async_trait]
198/// impl MyAsyncTrait for () {
199///     async fn do_async_work() { /* .. */ }
200/// }
201/// ```
202///
203/// All `impl`s for a trait declared with `#[async_trait]` must themselves be
204/// decorated with `#[async_trait]`. Many of Rocket's traits, such as
205/// [`FromRequest`](crate::request::FromRequest) and
206/// [`Fairing`](crate::fairing::Fairing) are `async`. As such, implementations
207/// of said traits must be decorated with `#[async_trait]`. See the individual
208/// trait docs for trait-specific details.
209///
210/// For more details on `#[async_trait]`, see [`async_trait`](mod@async_trait).
211#[doc(inline)]
212pub use async_trait::async_trait;
213
214const WORKER_PREFIX: &str = "rocket-worker";
215
216/// Creates a [`Rocket`] instance with the default config provider: aliases
217/// [`Rocket::build()`].
218pub fn build() -> Rocket<Build> {
219    Rocket::build()
220}
221
222/// Creates a [`Rocket`] instance with a custom config provider: aliases
223/// [`Rocket::custom()`].
224pub fn custom<T: figment::Provider>(provider: T) -> Rocket<Build> {
225    Rocket::custom(provider)
226}
227
228/// WARNING: This is unstable! Do not use this method outside of Rocket!
229#[doc(hidden)]
230pub fn async_run<F, R>(fut: F, workers: usize, sync: usize, force_end: bool, name: &str) -> R
231    where F: std::future::Future<Output = R>
232{
233    let runtime = tokio::runtime::Builder::new_multi_thread()
234        .thread_name(name)
235        .worker_threads(workers)
236        .max_blocking_threads(sync)
237        .enable_all()
238        .build()
239        .expect("create tokio runtime");
240
241    let result = runtime.block_on(fut);
242    if force_end {
243        runtime.shutdown_timeout(std::time::Duration::from_millis(500));
244    }
245
246    result
247}
248
249/// WARNING: This is unstable! Do not use this method outside of Rocket!
250#[doc(hidden)]
251pub fn async_test<R>(fut: impl std::future::Future<Output = R>) -> R {
252    async_run(fut, 1, 32, true, &format!("{WORKER_PREFIX}-test-thread"))
253}
254
255/// WARNING: This is unstable! Do not use this method outside of Rocket!
256#[doc(hidden)]
257pub fn async_main<R>(fut: impl std::future::Future<Output = R> + Send) -> R {
258    fn bail<T, E: crate::trace::Trace>(e: E) -> T {
259        e.trace_error();
260        panic!("aborting due to error")
261    }
262
263    // FIXME: We need to run `fut` to get the user's `Figment` to properly set
264    // up the async env, but we need the async env to run `fut`. So we're stuck.
265    // Tokio doesn't let us take the state from one async env and migrate it to
266    // another, so we need to use one, making this impossible.
267    //
268    // So as a result, we only use values from Rocket's figment. These
269    // values won't reflect swaps of `Rocket` in attach fairings with different
270    // config values, or values from non-Rocket configs. See tokio-rs/tokio#3329
271    // for a necessary resolution in `tokio`.
272    let fig = Config::figment();
273    let workers = fig.extract_inner(Config::WORKERS).unwrap_or_else(bail);
274    let max_blocking = fig.extract_inner(Config::MAX_BLOCKING).unwrap_or_else(bail);
275    let force = fig.focus(Config::SHUTDOWN).extract_inner("force").unwrap_or_else(bail);
276    async_run(fut, workers, max_blocking, force, &format!("{WORKER_PREFIX}-thread"))
277}
278
279/// Executes a `future` to completion on a new tokio-based Rocket async runtime.
280///
281/// The runtime is terminated on shutdown, and the future's resolved value is
282/// returned.
283///
284/// # Considerations
285///
286/// This function is a low-level mechanism intended to be used to execute the
287/// future returned by [`Rocket::launch()`] in a self-contained async runtime
288/// designed for Rocket. It runs futures in exactly the same manner as
289/// [`#[launch]`](crate::launch) and [`#[main]`](crate::main) do and is thus
290/// _never_ the preferred mechanism for running a Rocket application. _Always_
291/// prefer to use the [`#[launch]`](crate::launch) or [`#[main]`](crate::main)
292/// attributes. For example [`#[main]`](crate::main) can be used even when
293/// Rocket is just a small part of a bigger application:
294///
295/// ```rust,no_run
296/// #[rocket::main]
297/// async fn main() {
298///     # let should_start_server_in_foreground = false;
299///     # let should_start_server_in_background = false;
300///     let rocket = rocket::build();
301///     if should_start_server_in_foreground {
302///         rocket::build().launch().await;
303///     } else if should_start_server_in_background {
304///         rocket::tokio::spawn(rocket.launch());
305///     } else {
306///         // do something else
307///     }
308/// }
309/// ```
310///
311/// See [Rocket#launching] for more on using these attributes.
312///
313/// # Example
314///
315/// Build an instance of Rocket, launch it, and wait for shutdown:
316///
317/// ```rust,no_run
318/// use rocket::fairing::AdHoc;
319///
320/// let rocket = rocket::build()
321///     .attach(AdHoc::on_liftoff("Liftoff Printer", |_| Box::pin(async move {
322///         println!("Stalling liftoff for a second...");
323///         rocket::tokio::time::sleep(std::time::Duration::from_secs(1)).await;
324///         println!("And we're off!");
325///     })));
326///
327/// rocket::execute(rocket.launch());
328/// ```
329///
330/// Launch a pre-built instance of Rocket and wait for it to shutdown:
331///
332/// ```rust,no_run
333/// use rocket::{Rocket, Ignite, Phase, Error};
334///
335/// fn launch<P: Phase>(rocket: Rocket<P>) -> Result<Rocket<Ignite>, Error> {
336///     rocket::execute(rocket.launch())
337/// }
338/// ```
339///
340/// Do async work to build an instance of Rocket, launch, and wait for shutdown:
341///
342/// ```rust,no_run
343/// use rocket::fairing::AdHoc;
344///
345/// // This line can also be inside of the `async` block.
346/// let rocket = rocket::build();
347///
348/// rocket::execute(async move {
349///     let rocket = rocket.ignite().await?;
350///     let config = rocket.config();
351///     rocket.launch().await
352/// });
353/// ```
354pub fn execute<R, F>(future: F) -> R
355    where F: std::future::Future<Output = R> + Send
356{
357    async_main(future)
358}
359
360/// Returns a future that evaluates to `true` exactly when there is a presently
361/// running tokio async runtime that was likely started by Rocket.
362fn running_within_rocket_async_rt() -> impl std::future::Future<Output = bool> {
363    use futures::FutureExt;
364
365    tokio::task::spawn_blocking(|| {
366        let this = std::thread::current();
367        this.name().map_or(false, |s| s.starts_with(WORKER_PREFIX))
368    }).map(|r| r.unwrap_or(false))
369}