rocket/rocket.rs
1use std::fmt;
2use std::ops::{Deref, DerefMut};
3use std::sync::Arc;
4use std::time::Duration;
5use std::any::Any;
6use std::future::Future;
7use std::panic::Location;
8
9use either::Either;
10use figment::{Figment, Provider};
11use futures::TryFutureExt;
12
13use crate::shutdown::{Stages, Shutdown};
14use crate::trace::{Trace, TraceAll};
15use crate::{sentinel, shield::Shield, Catcher, Config, Route};
16use crate::listener::{Bind, DefaultListener, Endpoint, Listener};
17use crate::router::Router;
18use crate::fairing::{Fairing, Fairings};
19use crate::phase::{Phase, Build, Building, Ignite, Igniting, Orbit, Orbiting};
20use crate::phase::{Stateful, StateRef, StateRefMut, State};
21use crate::http::uri::Origin;
22use crate::error::{Error, ErrorKind};
23
24/// The application server itself.
25///
26/// # Phases
27///
28/// A `Rocket` instance represents a web server and its state. It progresses
29/// through three statically-enforced phases: build, ignite, orbit.
30///
31/// * **Build**: _application and server configuration_
32///
33/// This phase enables:
34///
35/// * setting configuration options
36/// * mounting/registering routes/catchers
37/// * managing state
38/// * attaching fairings
39///
40/// This is the _only_ phase in which an instance can be modified. To finalize
41/// changes, an instance is ignited via [`Rocket::ignite()`], progressing it
42/// into the _ignite_ phase, or directly launched into orbit with
43/// [`Rocket::launch()`] which progress the instance through ignite into
44/// orbit.
45///
46/// * **Ignite**: _verification and finalization of configuration_
47///
48/// An instance in the [`Ignite`] phase is in its final configuration,
49/// available via [`Rocket::config()`]. Barring user-supplied interior
50/// mutation, application state is guaranteed to remain unchanged beyond this
51/// point. An instance in the ignite phase can be launched into orbit to serve
52/// requests via [`Rocket::launch()`].
53///
54/// * **Orbit**: _a running web server_
55///
56/// An instance in the [`Orbit`] phase represents a _running_ application,
57/// actively serving requests.
58///
59/// # Launching
60///
61/// To launch a `Rocket` application, the suggested approach is to return an
62/// instance of `Rocket<Build>` from a function named `rocket` marked with the
63/// [`#[launch]`](crate::launch) attribute:
64///
65/// ```rust,no_run
66/// # use rocket::launch;
67/// #[launch]
68/// fn rocket() -> _ {
69/// rocket::build()
70/// }
71/// ```
72///
73/// This generates a `main` function with an `async` runtime that runs the
74/// returned `Rocket` instance.
75///
76/// * **Manual Launching**
77///
78/// To launch an instance of `Rocket`, it _must_ progress through all three
79/// phases. To progress into the ignite or launch phases, a tokio `async`
80/// runtime is required. The [`#[main]`](crate::main) attribute initializes a
81/// Rocket-specific tokio runtime and runs the attributed `async fn` inside of
82/// it:
83///
84/// ```rust,no_run
85/// #[rocket::main]
86/// async fn main() -> Result<(), rocket::Error> {
87/// let _rocket = rocket::build()
88/// .ignite().await?
89/// .launch().await?;
90///
91/// Ok(())
92/// }
93/// ```
94///
95/// Note that [`Rocket::launch()`] automatically progresses an instance of
96/// `Rocket` from any phase into orbit:
97///
98/// ```rust,no_run
99/// #[rocket::main]
100/// async fn main() -> Result<(), rocket::Error> {
101/// let _rocket = rocket::build().launch().await?;
102/// Ok(())
103/// }
104/// ```
105///
106/// For extreme and rare cases in which [`#[main]`](crate::main) imposes
107/// obstinate restrictions, use [`rocket::execute()`](crate::execute()) to
108/// execute Rocket's `launch()` future.
109///
110/// * **Automatic Launching**
111///
112/// Manually progressing an instance of Rocket though its phases is only
113/// necessary when either an instance's finalized state is to be inspected (in
114/// the _ignite_ phase) or the instance is expected to deorbit due to
115/// [`Rocket::shutdown()`]. In the more common case when neither is required,
116/// the [`#[launch]`](crate::launch) attribute can be used. When applied to a
117/// function that returns a `Rocket<Build>`, it automatically initializes an
118/// `async` runtime and launches the function's returned instance:
119///
120/// ```rust,no_run
121/// # use rocket::launch;
122/// use rocket::{Rocket, Build};
123///
124/// #[launch]
125/// fn rocket() -> Rocket<Build> {
126/// rocket::build()
127/// }
128/// ```
129///
130/// To avoid needing to import _any_ items in the common case, the `launch`
131/// attribute will infer a return type written as `_` as `Rocket<Build>`:
132///
133/// ```rust,no_run
134/// # use rocket::launch;
135/// #[launch]
136/// fn rocket() -> _ {
137/// rocket::build()
138/// }
139/// ```
140pub struct Rocket<P: Phase>(pub(crate) P::State);
141
142impl Rocket<Build> {
143 /// Create a new `Rocket` application using the default configuration
144 /// provider, [`Config::figment()`].
145 ///
146 /// This method is typically called through the
147 /// [`rocket::build()`](crate::build) alias.
148 ///
149 /// # Examples
150 ///
151 /// ```rust
152 /// # use rocket::launch;
153 /// #[launch]
154 /// fn rocket() -> _ {
155 /// rocket::build()
156 /// }
157 /// ```
158 #[must_use]
159 #[inline(always)]
160 pub fn build() -> Self {
161 Rocket::custom(Config::figment())
162 }
163
164 /// Creates a new `Rocket` application using the supplied configuration
165 /// provider.
166 ///
167 /// This method is typically called through the
168 /// [`rocket::custom()`](crate::custom()) alias.
169 ///
170 /// # Example
171 ///
172 /// ```rust
173 /// # use rocket::launch;
174 /// use rocket::figment::{Figment, providers::{Toml, Env, Format}};
175 ///
176 /// #[launch]
177 /// fn rocket() -> _ {
178 /// let figment = Figment::from(rocket::Config::default())
179 /// .merge(Toml::file("MyApp.toml").nested())
180 /// .merge(Env::prefixed("MY_APP_").global());
181 ///
182 /// rocket::custom(figment)
183 /// }
184 /// ```
185 #[must_use]
186 pub fn custom<T: Provider>(provider: T) -> Self {
187 Rocket::<Build>(Building::default())
188 .reconfigure(provider)
189 .attach(Shield::default())
190 }
191
192 /// Overrides the current configuration provider with `provider`.
193 ///
194 /// The default provider, or a provider previously set with
195 /// [`Rocket::custom()`] or [`Rocket::reconfigure()`], is overridden by
196 /// `provider`.
197 ///
198 /// # Example
199 ///
200 /// ```rust
201 /// use rocket::config::{Config, Ident};
202 /// # use std::net::Ipv4Addr;
203 /// # use std::path::{Path, PathBuf};
204 /// # type Result = std::result::Result<(), rocket::Error>;
205 ///
206 /// let config = Config {
207 /// ident: Ident::try_new("MyServer").expect("valid ident"),
208 /// temp_dir: "/tmp/config-example".into(),
209 /// ..Config::debug_default()
210 /// };
211 ///
212 /// # let _: Result = rocket::async_test(async move {
213 /// let rocket = rocket::custom(&config).ignite().await?;
214 /// assert_eq!(rocket.config().ident.as_str(), Some("MyServer"));
215 /// assert_eq!(rocket.config().temp_dir.relative(), Path::new("/tmp/config-example"));
216 ///
217 /// // Create a new figment which modifies _some_ keys the existing figment:
218 /// let figment = rocket.figment().clone()
219 /// .merge((Config::IDENT, "Example"));
220 ///
221 /// let rocket = rocket::custom(&config)
222 /// .reconfigure(figment)
223 /// .ignite().await?;
224 ///
225 /// assert_eq!(rocket.config().ident.as_str(), Some("Example"));
226 /// assert_eq!(rocket.config().temp_dir.relative(), Path::new("/tmp/config-example"));
227 /// # Ok(())
228 /// # });
229 /// ```
230 #[must_use]
231 pub fn reconfigure<T: Provider>(mut self, provider: T) -> Self {
232 // We initialize the logger here so that logging from fairings and so on
233 // are visible; we use the final config to set a max log-level in ignite
234 self.figment = Figment::from(provider);
235 crate::trace::init(Config::try_from(&self.figment).ok().as_ref());
236 span_trace!("reconfigure" => self.figment().trace_trace());
237
238 self
239 }
240
241 #[track_caller]
242 fn load<T, F, M>(mut self, kind: &str, base: &str, items: Vec<T>, m: M, f: F) -> Self
243 where M: Fn(&str, T) -> T,
244 F: Fn(&mut Self, T),
245 T: Clone + Trace,
246 {
247 let mut base = match Origin::parse_base(base) {
248 Ok(origin) => origin,
249 Err(e) => {
250 error!(%base, location = %Location::caller(), "invalid {kind} base uri: {e}");
251 panic!("aborting due to {} base error", kind);
252 }
253 };
254
255 if base.query().is_some() {
256 warn!(%base, location = %Location::caller(), "query in {kind} base is ignored");
257 base.clear_query();
258 }
259
260 for unmounted_item in items {
261 f(&mut self, m(base.path().as_str(), unmounted_item.clone()))
262 }
263
264 self
265 }
266
267 /// Mounts all of the `routes` at the given `base` mount point.
268 ///
269 /// A route _mounted_ at `base` has an effective URI of `base/route`, where
270 /// `route` is the route URI. In other words, `base` is added as a prefix to
271 /// the route's URI. The URI resulting from joining the `base` URI and the
272 /// route URI is called the route's _effective URI_, as this is the URI used
273 /// for request matching during routing.
274 ///
275 /// Like a route URI, a `base` is never percent-decoded. Instead, it is
276 /// compared against the percent-decoded path of an incoming request. As
277 /// such, a `base` may contain any UTF-8 characters, and `%` is an ordinary
278 /// character: a `base` of `/häcker` matches requests to `/h%C3%A4cker/..`,
279 /// and a `base` of `/a%20b` matches requests to `/a%2520b/..`.
280 ///
281 /// A `base` URI is not allowed to have a query part. If a `base` _does_
282 /// have a query part, it is ignored when producing the effective URI.
283 ///
284 /// A `base` may have an optional trailing slash. A route with a URI path of
285 /// `/` (and any optional query) mounted at a `base` has an effective URI
286 /// equal to the `base` (plus any optional query). That is, if the base has
287 /// a trailing slash, the effective URI path has a trailing slash, and
288 /// otherwise it does not. Routes with URI paths other than `/` are not
289 /// effected by trailing slashes in their corresponding mount point.
290 ///
291 /// As concrete examples, consider the following table:
292 ///
293 /// | mount point | route URI | effective URI |
294 /// |-------------|-----------|---------------|
295 /// | `/` | `/foo` | `/foo` |
296 /// | `/` | `/foo/` | `/foo/` |
297 /// | `/foo` | `/` | `/foo` |
298 /// | `/foo` | `/?bar` | `/foo?bar` |
299 /// | `/foo` | `/bar` | `/foo/bar` |
300 /// | `/foo` | `/bar/` | `/foo/bar/` |
301 /// | `/foo/` | `/` | `/foo/` |
302 /// | `/foo/` | `/bar` | `/foo/bar` |
303 /// | `/foo/` | `/?bar` | `/foo/?bar` |
304 /// | `/foo/bar` | `/` | `/foo/bar` |
305 /// | `/foo/bar/` | `/` | `/foo/bar/` |
306 /// | `/foo/?bar` | `/` | `/foo/` |
307 /// | `/foo/?bar` | `/baz` | `/foo/baz` |
308 /// | `/foo/?bar` | `/baz/` | `/foo/baz/` |
309 ///
310 /// # Panics
311 ///
312 /// Panics if either:
313 ///
314 /// * the `base` mount point is not a valid route URI without dynamic
315 /// parameters
316 ///
317 /// * any route URI is not a valid origin URI. (**Note:** _This kind of
318 /// panic is guaranteed not to occur if the routes were generated using
319 /// Rocket's code generation._)
320 ///
321 /// # Examples
322 ///
323 /// Use the `routes!` macro to mount routes created using the code
324 /// generation facilities. Requests to both `/world` and `/hello/world` URI
325 /// will be dispatched to the `hi` route.
326 ///
327 /// ```rust,no_run
328 /// # #[macro_use] extern crate rocket;
329 /// #
330 /// #[get("/world")]
331 /// fn hi() -> &'static str {
332 /// "Hello!"
333 /// }
334 ///
335 /// #[launch]
336 /// fn rocket() -> _ {
337 /// rocket::build()
338 /// .mount("/", routes![hi])
339 /// .mount("/hello", routes![hi])
340 /// }
341 /// ```
342 ///
343 /// Manually create a route named `hi` at path `"/world"` mounted at base
344 /// `"/hello"`. Requests to the `/hello/world` URI will be dispatched to the
345 /// `hi` route.
346 ///
347 /// ```rust
348 /// # #[macro_use] extern crate rocket;
349 /// use rocket::{Request, Route, Data, route};
350 /// use rocket::http::Method;
351 ///
352 /// fn hi<'r>(req: &'r Request, _: Data<'r>) -> route::BoxFuture<'r> {
353 /// route::Outcome::from(req, "Hello!").pin()
354 /// }
355 ///
356 /// #[launch]
357 /// fn rocket() -> _ {
358 /// let hi_route = Route::new(Method::Get, "/world", hi);
359 /// rocket::build().mount("/hello", vec![hi_route])
360 /// }
361 /// ```
362 #[must_use]
363 #[track_caller]
364 pub fn mount<R>(self, base: &str, routes: R) -> Self
365 where R: Into<Vec<Route>>
366 {
367 self.load("route", base, routes.into(),
368 |base, route| route.rebase(base),
369 |r, route| r.0.routes.push(route))
370 }
371
372 /// Registers all of the catchers in the supplied vector, scoped to `base`.
373 ///
374 /// As with [`Rocket::mount()`], `base` is never percent-decoded. Instead,
375 /// it is compared against the percent-decoded path of the erroring request.
376 ///
377 /// # Panics
378 ///
379 /// Panics if `base` is not a valid static path: a valid route URI without
380 /// dynamic parameters.
381 ///
382 /// # Examples
383 ///
384 /// ```rust,no_run
385 /// # #[macro_use] extern crate rocket;
386 /// use rocket::Request;
387 ///
388 /// #[catch(500)]
389 /// fn internal_error() -> &'static str {
390 /// "Whoops! Looks like we messed up."
391 /// }
392 ///
393 /// #[catch(404)]
394 /// fn not_found(req: &Request) -> String {
395 /// format!("I couldn't find '{}'. Try something else?", req.uri())
396 /// }
397 ///
398 /// #[launch]
399 /// fn rocket() -> _ {
400 /// rocket::build().register("/", catchers![internal_error, not_found])
401 /// }
402 /// ```
403 #[must_use]
404 pub fn register<C>(self, base: &str, catchers: C) -> Self
405 where C: Into<Vec<Catcher>>
406 {
407 self.load("catcher", base, catchers.into(),
408 |base, catcher| catcher.rebase(base),
409 |r, catcher| r.0.catchers.push(catcher))
410 }
411
412 /// Add `state` to the state managed by this instance of Rocket.
413 ///
414 /// This method can be called any number of times as long as each call
415 /// refers to a different `T`.
416 ///
417 /// Managed state can be retrieved by any request handler via the
418 /// [`State`](crate::State) request guard. In particular, if a value of type `T`
419 /// is managed by Rocket, adding `State<T>` to the list of arguments in a
420 /// request handler instructs Rocket to retrieve the managed value.
421 ///
422 /// # Panics
423 ///
424 /// Panics if state of type `T` is already being managed.
425 ///
426 /// # Example
427 ///
428 /// ```rust,no_run
429 /// # #[macro_use] extern crate rocket;
430 /// use rocket::State;
431 ///
432 /// struct MyInt(isize);
433 /// struct MyString(String);
434 ///
435 /// #[get("/int")]
436 /// fn int(state: &State<MyInt>) -> String {
437 /// format!("The stateful int is: {}", state.0)
438 /// }
439 ///
440 /// #[get("/string")]
441 /// fn string(state: &State<MyString>) -> &str {
442 /// &state.0
443 /// }
444 ///
445 /// #[launch]
446 /// fn rocket() -> _ {
447 /// rocket::build()
448 /// .manage(MyInt(10))
449 /// .manage(MyString("Hello, managed state!".to_string()))
450 /// .mount("/", routes![int, string])
451 /// }
452 /// ```
453 #[must_use]
454 pub fn manage<T>(self, state: T) -> Self
455 where T: Send + Sync + 'static
456 {
457 let type_name = std::any::type_name::<T>();
458 if !self.state.set(state) {
459 error!("state for type '{}' is already being managed", type_name);
460 panic!("aborting due to duplicated managed state");
461 }
462
463 self
464 }
465
466 /// Attaches a fairing to this instance of Rocket. No fairings are eagerly
467 /// executed; fairings are executed at their appropriate time.
468 ///
469 /// If the attached fairing is a [singleton] and a fairing of the same type
470 /// has already been attached, this fairing replaces it. Otherwise the
471 /// fairing gets attached without replacing any existing fairing.
472 ///
473 /// [singleton]: crate::fairing::Fairing#singletons
474 ///
475 /// # Example
476 ///
477 /// ```rust,no_run
478 /// # #[macro_use] extern crate rocket;
479 /// use rocket::Rocket;
480 /// use rocket::fairing::AdHoc;
481 ///
482 /// #[launch]
483 /// fn rocket() -> _ {
484 /// rocket::build()
485 /// .attach(AdHoc::on_liftoff("Liftoff Message", |_| Box::pin(async {
486 /// println!("We have liftoff!");
487 /// })))
488 /// }
489 /// ```
490 #[must_use]
491 pub fn attach<F: Fairing>(mut self, fairing: F) -> Self {
492 self.fairings.add(Box::new(fairing));
493 self
494 }
495
496 /// Returns a `Future` that transitions this instance of `Rocket` into the
497 /// _ignite_ phase.
498 ///
499 /// When `await`ed, the future runs all _ignite_ fairings in serial,
500 /// [attach](Rocket::attach()) order, and verifies that `self` represents a
501 /// valid instance of `Rocket` ready for launch. This means that:
502 ///
503 /// * All ignite fairings succeeded.
504 /// * A valid [`Config`] was extracted from [`Rocket::figment()`].
505 /// * If `secrets` are enabled, the extracted `Config` contains a safe
506 /// secret key.
507 /// * There are no [`Route#collisions`] or [`Catcher#collisions`]
508 /// collisions.
509 /// * No [`Sentinel`](crate::Sentinel) triggered an abort.
510 ///
511 /// If any of these conditions fail to be met, a respective [`Error`] is
512 /// returned.
513 ///
514 /// [configured]: Rocket::figment()
515 ///
516 /// # Example
517 ///
518 /// ```rust
519 /// use rocket::fairing::AdHoc;
520 ///
521 /// #[rocket::main]
522 /// async fn main() -> Result<(), rocket::Error> {
523 /// let rocket = rocket::build()
524 /// # .reconfigure(rocket::Config::debug_default())
525 /// .attach(AdHoc::on_ignite("Manage State", |rocket| async move {
526 /// rocket.manage(String::from("managed string"))
527 /// }));
528 ///
529 /// // No fairings are run until ignition occurs.
530 /// assert!(rocket.state::<String>().is_none());
531 ///
532 /// let rocket = rocket.ignite().await?;
533 /// assert_eq!(rocket.state::<String>().unwrap(), "managed string");
534 ///
535 /// Ok(())
536 /// }
537 /// ```
538 pub async fn ignite(mut self) -> Result<Rocket<Ignite>, Error> {
539 self = Fairings::handle_ignite(self).await;
540 self.fairings.audit().map_err(|f| ErrorKind::FailedFairings(f.to_vec()))?;
541
542 // Extract the configuration; initialize default trace subscriber.
543 #[allow(unused_mut)]
544 let mut config = Config::try_from(&self.figment).map_err(ErrorKind::Config)?;
545 crate::trace::init(&config);
546
547 // Check for safely configured secrets.
548 #[cfg(feature = "secrets")]
549 if !config.secret_key.is_provided() {
550 if config.profile != Config::DEBUG_PROFILE {
551 return Err(Error::new(ErrorKind::InsecureSecretKey(config.profile.clone())));
552 }
553
554 if config.secret_key.is_zero() {
555 config.secret_key = crate::config::SecretKey::generate()
556 .unwrap_or_else(crate::config::SecretKey::zero);
557 }
558 }
559
560 // Initialize the router; check for collisions.
561 let mut router = Router::new();
562 self.routes.clone().into_iter().for_each(|r| router.routes.push(r));
563 self.catchers.clone().into_iter().for_each(|c| router.catchers.push(c));
564 let router = router.finalize()
565 .map_err(|(r, c)| ErrorKind::Collisions { routes: r, catchers: c, })?;
566
567 // Finally, freeze managed state for faster access later.
568 self.state.freeze();
569
570 // Log everything we know: config, routes, catchers, fairings.
571 // TODO: Store/print managed state type names?
572 let fairings = self.fairings.unique_set();
573 span_info!("config", profile = %self.figment().profile() => {
574 config.trace_info();
575 self.figment().trace_debug();
576 });
577
578 span_info!("routes", count = self.routes.len() => self.routes().trace_all_info());
579 span_info!("catchers", count = self.catchers.len() => self.catchers().trace_all_info());
580 span_info!("fairings", count = fairings.len() => fairings.trace_all_info());
581
582 // Ignite the rocket.
583 let rocket: Rocket<Ignite> = Rocket(Igniting {
584 shutdown: Stages::new(),
585 figment: self.0.figment,
586 fairings: self.0.fairings,
587 state: self.0.state,
588 router, config,
589 });
590
591 // Query the sentinels, abort if requested.
592 let sentinels = rocket.routes().flat_map(|r| r.sentinels.iter());
593 sentinel::query(sentinels, &rocket).map_err(ErrorKind::SentinelAborts)?;
594
595 Ok(rocket)
596 }
597}
598
599impl Rocket<Ignite> {
600 /// Returns the finalized, active configuration. This is guaranteed to
601 /// remain stable through ignition and into orbit.
602 ///
603 /// # Example
604 ///
605 /// ```rust,no_run
606 /// #[rocket::main]
607 /// async fn main() -> Result<(), rocket::Error> {
608 /// let rocket = rocket::build().ignite().await?;
609 /// let config = rocket.config();
610 /// Ok(())
611 /// }
612 /// ```
613 pub fn config(&self) -> &Config {
614 &self.config
615 }
616
617 /// Returns a handle which can be used to trigger a shutdown and detect a
618 /// triggered shutdown.
619 ///
620 /// A completed graceful shutdown resolves the future returned by
621 /// [`Rocket::launch()`]. If [`Shutdown::notify()`] is called _before_ an
622 /// instance is launched, it will be immediately shutdown after liftoff. See
623 /// [`Shutdown`] and [`ShutdownConfig`](crate::config::ShutdownConfig) for
624 /// details on graceful shutdown.
625 ///
626 /// # Example
627 ///
628 /// ```rust,no_run
629 /// # use std::time::Duration;
630 /// use rocket::tokio::{self, time};
631 ///
632 /// #[rocket::main]
633 /// async fn main() -> Result<(), rocket::Error> {
634 /// let rocket = rocket::build().ignite().await?;
635 ///
636 /// let shutdown = rocket.shutdown();
637 /// tokio::spawn(async move {
638 /// time::sleep(time::Duration::from_secs(5)).await;
639 /// shutdown.notify();
640 /// });
641 ///
642 /// // The `launch()` future resolves after ~5 seconds.
643 /// let result = rocket.launch().await;
644 /// assert!(result.is_ok());
645 ///
646 /// Ok(())
647 /// }
648 /// ```
649 pub fn shutdown(&self) -> Shutdown {
650 self.shutdown.start.clone()
651 }
652
653 pub(crate) fn into_orbit(self, endpoints: Vec<Endpoint>) -> Rocket<Orbit> {
654 // The `Alt-Svc` header value that advertises HTTP/3, if it's served.
655 let alt_svc = endpoints.iter()
656 .find_map(|e| e.quic())
657 .filter(|_| cfg!(feature = "http3-preview"))
658 .map(|addr| format!("h3=\":{}\"", addr.port()));
659
660 Rocket(Orbiting {
661 endpoints,
662 alt_svc,
663 router: self.0.router,
664 fairings: self.0.fairings,
665 figment: self.0.figment,
666 config: self.0.config,
667 state: self.0.state,
668 shutdown: self.0.shutdown,
669 })
670 }
671
672 async fn _local_launch(self, endpoint: Endpoint) -> Rocket<Orbit> {
673 let rocket = self.into_orbit(vec![endpoint]);
674 Rocket::liftoff(&rocket).await;
675 rocket
676 }
677
678 async fn _launch<L: Listener + 'static>(self, listener: L) -> Result<Rocket<Ignite>, Error> {
679 let interval = Duration::from_millis(self.config.wake_interval.into());
680 let _waker = crate::util::RuntimeWaker::start(interval)?;
681 let rocket = self.listen_and_serve(listener, |rocket| async move {
682 let rocket = Arc::new(rocket);
683
684 rocket.shutdown.spawn_listener(&rocket.config.shutdown);
685 if let Err(e) = tokio::spawn(Rocket::liftoff(rocket.clone())).await {
686 let rocket = rocket.try_wait_shutdown().await.map(Box::new);
687 return Err(ErrorKind::Liftoff(rocket, e).into());
688 }
689
690 Ok(rocket)
691 }).await?;
692
693 Ok(rocket.try_wait_shutdown().await.map_err(ErrorKind::Shutdown)?)
694 }
695}
696
697impl Rocket<Orbit> {
698 /// Rocket wraps all connections in a `CancellableIo` struct, an internal
699 /// structure that gracefully closes I/O when it receives a signal. That
700 /// signal is the `shutdown` future. When the future resolves,
701 /// `CancellableIo` begins to terminate in grace, mercy, and finally force
702 /// close phases. Since all connections are wrapped in `CancellableIo`, this
703 /// eventually ends all I/O.
704 ///
705 /// At that point, unless a user spawned an infinite, stand-alone task that
706 /// isn't monitoring `Shutdown`, all tasks should resolve. This means that
707 /// all instances of the shared `Arc<Rocket>` are dropped and we can return
708 /// the owned instance of `Rocket`.
709 ///
710 /// Unfortunately, the Hyper `server` future resolves as soon as it has
711 /// finished processing requests without respect for ongoing responses. That
712 /// is, `server` resolves even when there are running tasks that are
713 /// generating a response. So, `server` resolving implies little to nothing
714 /// about the state of connections. As a result, we wait until all tasks are
715 /// complete, thus all references to `Arc<Rocket>` are dropped and we can
716 /// get back a unique reference. Since all connections should be closed
717 /// after grace + mercy, we wait at most grace + mercy + some buffer.
718 async fn try_wait_shutdown(self: Arc<Self>) -> Result<Rocket<Ignite>, Arc<Self>> {
719 use tokio::time::{sleep_until, Instant};
720
721 info!("Shutting down. Waiting for shutdown fairings and pending I/O...");
722 tokio::spawn({
723 let rocket = self.clone();
724 async move { rocket.fairings.handle_shutdown(&rocket).await }
725 });
726
727 let config = &self.config.shutdown;
728 let buffer = Duration::from_micros(1500);
729 let deadline = Instant::now() + config.grace() + config.mercy() + buffer;
730 let mut wait = Duration::from_micros(250);
731 while Arc::strong_count(&self) != 1 && Instant::now() < deadline {
732 sleep_until((Instant::now() + wait).min(deadline)).await;
733 wait = Duration::from_millis(10);
734 }
735
736 match Arc::try_unwrap(self) {
737 Ok(rocket) => {
738 info!("Graceful shutdown completed successfully.");
739 Ok(rocket.deorbit())
740 }
741 Err(rocket) => {
742 warn!("Shutdown failed: outstanding background I/O.");
743 Err(rocket)
744 }
745 }
746 }
747
748 pub(crate) fn deorbit(self) -> Rocket<Ignite> {
749 Rocket(Igniting {
750 router: self.0.router,
751 fairings: self.0.fairings,
752 figment: self.0.figment,
753 config: self.0.config,
754 state: self.0.state,
755 shutdown: self.0.shutdown,
756 })
757 }
758
759 pub(crate) async fn liftoff<R: Deref<Target = Self>>(rocket: R) {
760 let rocket = rocket.deref();
761 rocket.fairings.handle_liftoff(rocket).await;
762
763 if !crate::running_within_rocket_async_rt().await {
764 warn!(
765 "Rocket is executing inside of a custom runtime.\n\
766 Rocket's runtime is enabled via `#[rocket::main]` or `#[launch]`\n\
767 Forced shutdown is disabled. Runtime settings may be suboptimal."
768 );
769 }
770
771 tracing::info!(name: "liftoff", endpoint = %rocket.endpoints[0]);
772 }
773
774 /// Returns the finalized, active configuration. This is guaranteed to
775 /// remain stable after [`Rocket::ignite()`], through ignition and into
776 /// orbit.
777 ///
778 /// # Example
779 ///
780 /// ```rust,no_run
781 /// # #[macro_use] extern crate rocket;
782 /// use rocket::fairing::AdHoc;
783 ///
784 /// #[launch]
785 /// fn rocket() -> _ {
786 /// rocket::build()
787 /// .attach(AdHoc::on_liftoff("Config", |rocket| Box::pin(async move {
788 /// println!("Rocket launch config: {:?}", rocket.config());
789 /// })))
790 /// }
791 /// ```
792 pub fn config(&self) -> &Config {
793 &self.config
794 }
795
796 pub fn endpoints(&self) -> impl Iterator<Item = &Endpoint> {
797 self.endpoints.iter()
798 }
799
800 /// Returns a handle which can be used to trigger a shutdown and detect a
801 /// triggered shutdown.
802 ///
803 /// A completed graceful shutdown resolves the future returned by
804 /// [`Rocket::launch()`]. See [`Shutdown`] and
805 /// [`ShutdownConfig`](crate::config::ShutdownConfig) for details on
806 /// graceful shutdown.
807 ///
808 /// # Example
809 ///
810 /// ```rust,no_run
811 /// # #[macro_use] extern crate rocket;
812 /// use rocket::tokio::{self, time};
813 /// use rocket::fairing::AdHoc;
814 ///
815 /// #[launch]
816 /// fn rocket() -> _ {
817 /// rocket::build()
818 /// .attach(AdHoc::on_liftoff("Shutdown", |rocket| Box::pin(async move {
819 /// let shutdown = rocket.shutdown();
820 /// tokio::spawn(async move {
821 /// time::sleep(time::Duration::from_secs(5)).await;
822 /// shutdown.notify();
823 /// });
824 /// })))
825 /// }
826 /// ```
827 pub fn shutdown(&self) -> Shutdown {
828 self.shutdown.start.clone()
829 }
830}
831
832impl<P: Phase> Rocket<P> {
833 /// Returns an iterator over all of the routes mounted on this instance of
834 /// Rocket. The order is unspecified.
835 ///
836 /// # Example
837 ///
838 /// ```rust
839 /// # use rocket::*;
840 /// use rocket::Rocket;
841 /// use rocket::fairing::AdHoc;
842 ///
843 /// #[get("/hello")]
844 /// fn hello() -> &'static str {
845 /// "Hello, world!"
846 /// }
847 ///
848 /// let rocket = rocket::build()
849 /// .mount("/", routes![hello])
850 /// .mount("/hi", routes![hello]);
851 ///
852 /// assert_eq!(rocket.routes().count(), 2);
853 /// assert!(rocket.routes().any(|r| r.uri == "/hello"));
854 /// assert!(rocket.routes().any(|r| r.uri == "/hi/hello"));
855 /// ```
856 pub fn routes(&self) -> impl Iterator<Item = &Route> {
857 match self.0.as_ref() {
858 StateRef::Build(p) => Either::Left(p.routes.iter()),
859 StateRef::Ignite(p) => Either::Right(p.router.routes.iter()),
860 StateRef::Orbit(p) => Either::Right(p.router.routes.iter()),
861 }
862 }
863
864 /// Returns an iterator over all of the catchers registered on this instance
865 /// of Rocket. The order is unspecified.
866 ///
867 /// # Example
868 ///
869 /// ```rust
870 /// # use rocket::*;
871 /// use rocket::Rocket;
872 /// use rocket::fairing::AdHoc;
873 ///
874 /// #[catch(404)] fn not_found() -> &'static str { "Nothing here, sorry!" }
875 /// #[catch(500)] fn just_500() -> &'static str { "Whoops!?" }
876 /// #[catch(default)] fn some_default() -> &'static str { "Everything else." }
877 ///
878 /// let rocket = rocket::build()
879 /// .register("/foo", catchers![not_found])
880 /// .register("/", catchers![just_500, some_default]);
881 ///
882 /// assert_eq!(rocket.catchers().count(), 3);
883 /// assert!(rocket.catchers().any(|c| c.code == Some(404) && c.base() == "/foo"));
884 /// assert!(rocket.catchers().any(|c| c.code == Some(500) && c.base() == "/"));
885 /// assert!(rocket.catchers().any(|c| c.code == None && c.base() == "/"));
886 /// ```
887 pub fn catchers(&self) -> impl Iterator<Item = &Catcher> {
888 match self.0.as_ref() {
889 StateRef::Build(p) => Either::Left(p.catchers.iter()),
890 StateRef::Ignite(p) => Either::Right(p.router.catchers.iter()),
891 StateRef::Orbit(p) => Either::Right(p.router.catchers.iter()),
892 }
893 }
894
895 /// Returns `Some` of the managed state value for the type `T` if it is
896 /// being managed by `self`. Otherwise, returns `None`.
897 ///
898 /// # Example
899 ///
900 /// ```rust
901 /// #[derive(PartialEq, Debug)]
902 /// struct MyState(&'static str);
903 ///
904 /// let rocket = rocket::build().manage(MyState("hello!"));
905 /// assert_eq!(rocket.state::<MyState>().unwrap(), &MyState("hello!"));
906 /// ```
907 pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
908 match self.0.as_ref() {
909 StateRef::Build(p) => p.state.try_get(),
910 StateRef::Ignite(p) => p.state.try_get(),
911 StateRef::Orbit(p) => p.state.try_get(),
912 }
913 }
914
915 /// Returns a reference to the first fairing of type `F` if it is attached.
916 /// Otherwise, returns `None`.
917 ///
918 /// To retrieve a _mutable_ reference to fairing `F`, use
919 /// [`Rocket::fairing_mut()`] instead.
920 ///
921 /// # Example
922 ///
923 /// ```rust
924 /// # use rocket::{Rocket, Request, Data, Response, Build, Orbit};
925 /// # use rocket::fairing::{self, Fairing, Info, Kind};
926 /// #
927 /// # #[rocket::async_trait]
928 /// # impl Fairing for MyFairing {
929 /// # fn info(&self) -> Info {
930 /// # Info { name: "", kind: Kind::Ignite }
931 /// # }
932 /// # }
933 /// #
934 /// # #[rocket::async_trait]
935 /// # impl Fairing for MySingletonFairing {
936 /// # fn info(&self) -> Info {
937 /// # Info { name: "", kind: Kind::Ignite | Kind::Singleton }
938 /// # }
939 /// # }
940 /// // A regular, non-singleton fairing.
941 /// struct MyFairing(&'static str);
942 ///
943 /// // A singleton fairing.
944 /// struct MySingletonFairing(&'static str);
945 ///
946 /// // fairing is not attached, returns `None`
947 /// let rocket = rocket::build();
948 /// assert!(rocket.fairing::<MyFairing>().is_none());
949 /// assert!(rocket.fairing::<MySingletonFairing>().is_none());
950 ///
951 /// // attach fairing, now returns `Some`
952 /// let rocket = rocket.attach(MyFairing("some state"));
953 /// assert!(rocket.fairing::<MyFairing>().is_some());
954 /// assert_eq!(rocket.fairing::<MyFairing>().unwrap().0, "some state");
955 ///
956 /// // it returns the first fairing of a given type only
957 /// let rocket = rocket.attach(MyFairing("other state"));
958 /// assert_eq!(rocket.fairing::<MyFairing>().unwrap().0, "some state");
959 ///
960 /// // attach fairing, now returns `Some`
961 /// let rocket = rocket.attach(MySingletonFairing("first"));
962 /// assert_eq!(rocket.fairing::<MySingletonFairing>().unwrap().0, "first");
963 ///
964 /// // recall that new singletons replace existing attached singletons
965 /// let rocket = rocket.attach(MySingletonFairing("second"));
966 /// assert_eq!(rocket.fairing::<MySingletonFairing>().unwrap().0, "second");
967 /// ```
968 pub fn fairing<F: Fairing>(&self) -> Option<&F> {
969 match self.0.as_ref() {
970 StateRef::Build(p) => p.fairings.filter::<F>().next(),
971 StateRef::Ignite(p) => p.fairings.filter::<F>().next(),
972 StateRef::Orbit(p) => p.fairings.filter::<F>().next(),
973 }
974 }
975
976 /// Returns an iterator over all attached fairings of type `F`, if any.
977 ///
978 /// # Example
979 ///
980 /// ```rust
981 /// # use rocket::{Rocket, Request, Data, Response, Build, Orbit};
982 /// # use rocket::fairing::{self, Fairing, Info, Kind};
983 /// #
984 /// # #[rocket::async_trait]
985 /// # impl Fairing for MyFairing {
986 /// # fn info(&self) -> Info {
987 /// # Info { name: "", kind: Kind::Ignite }
988 /// # }
989 /// # }
990 /// #
991 /// # #[rocket::async_trait]
992 /// # impl Fairing for MySingletonFairing {
993 /// # fn info(&self) -> Info {
994 /// # Info { name: "", kind: Kind::Ignite | Kind::Singleton }
995 /// # }
996 /// # }
997 /// // A regular, non-singleton fairing.
998 /// struct MyFairing(&'static str);
999 ///
1000 /// // A singleton fairing.
1001 /// struct MySingletonFairing(&'static str);
1002 ///
1003 /// let rocket = rocket::build();
1004 /// assert_eq!(rocket.fairings::<MyFairing>().count(), 0);
1005 /// assert_eq!(rocket.fairings::<MySingletonFairing>().count(), 0);
1006 ///
1007 /// let rocket = rocket.attach(MyFairing("some state"))
1008 /// .attach(MySingletonFairing("first"))
1009 /// .attach(MySingletonFairing("second"))
1010 /// .attach(MyFairing("other state"))
1011 /// .attach(MySingletonFairing("third"));
1012 ///
1013 /// let my_fairings: Vec<_> = rocket.fairings::<MyFairing>().collect();
1014 /// assert_eq!(my_fairings.len(), 2);
1015 /// assert_eq!(my_fairings[0].0, "some state");
1016 /// assert_eq!(my_fairings[1].0, "other state");
1017 ///
1018 /// let my_singleton: Vec<_> = rocket.fairings::<MySingletonFairing>().collect();
1019 /// assert_eq!(my_singleton.len(), 1);
1020 /// assert_eq!(my_singleton[0].0, "third");
1021 /// ```
1022 pub fn fairings<F: Fairing>(&self) -> impl Iterator<Item = &F> {
1023 match self.0.as_ref() {
1024 StateRef::Build(p) => Either::Left(p.fairings.filter::<F>()),
1025 StateRef::Ignite(p) => Either::Right(p.fairings.filter::<F>()),
1026 StateRef::Orbit(p) => Either::Right(p.fairings.filter::<F>()),
1027 }
1028 }
1029
1030 /// Returns a mutable reference to the first fairing of type `F` if it is
1031 /// attached. Otherwise, returns `None`.
1032 ///
1033 /// # Example
1034 ///
1035 /// ```rust
1036 /// # use rocket::{Rocket, Request, Data, Response, Build, Orbit};
1037 /// # use rocket::fairing::{self, Fairing, Info, Kind};
1038 /// #
1039 /// # #[rocket::async_trait]
1040 /// # impl Fairing for MyFairing {
1041 /// # fn info(&self) -> Info {
1042 /// # Info { name: "", kind: Kind::Ignite }
1043 /// # }
1044 /// # }
1045 /// // A regular, non-singleton fairing.
1046 /// struct MyFairing(&'static str);
1047 ///
1048 /// // fairing is not attached, returns `None`
1049 /// let mut rocket = rocket::build();
1050 /// assert!(rocket.fairing_mut::<MyFairing>().is_none());
1051 ///
1052 /// // attach fairing, now returns `Some`
1053 /// let mut rocket = rocket.attach(MyFairing("some state"));
1054 /// assert!(rocket.fairing_mut::<MyFairing>().is_some());
1055 /// assert_eq!(rocket.fairing_mut::<MyFairing>().unwrap().0, "some state");
1056 ///
1057 /// // we can modify the fairing
1058 /// rocket.fairing_mut::<MyFairing>().unwrap().0 = "other state";
1059 /// assert_eq!(rocket.fairing_mut::<MyFairing>().unwrap().0, "other state");
1060 ///
1061 /// // it returns the first fairing of a given type only
1062 /// let mut rocket = rocket.attach(MyFairing("yet more state"));
1063 /// assert_eq!(rocket.fairing_mut::<MyFairing>().unwrap().0, "other state");
1064 /// ```
1065 pub fn fairing_mut<F: Fairing>(&mut self) -> Option<&mut F> {
1066 match self.0.as_mut() {
1067 StateRefMut::Build(p) => p.fairings.filter_mut::<F>().next(),
1068 StateRefMut::Ignite(p) => p.fairings.filter_mut::<F>().next(),
1069 StateRefMut::Orbit(p) => p.fairings.filter_mut::<F>().next(),
1070 }
1071 }
1072
1073 /// Returns an iterator of mutable references to all attached fairings of
1074 /// type `F`, if any.
1075 ///
1076 /// # Example
1077 ///
1078 /// ```rust
1079 /// # use rocket::{Rocket, Request, Data, Response, Build, Orbit};
1080 /// # use rocket::fairing::{self, Fairing, Info, Kind};
1081 /// #
1082 /// # #[rocket::async_trait]
1083 /// # impl Fairing for MyFairing {
1084 /// # fn info(&self) -> Info {
1085 /// # Info { name: "", kind: Kind::Ignite }
1086 /// # }
1087 /// # }
1088 /// // A regular, non-singleton fairing.
1089 /// struct MyFairing(&'static str);
1090 ///
1091 /// let mut rocket = rocket::build()
1092 /// .attach(MyFairing("some state"))
1093 /// .attach(MyFairing("other state"))
1094 /// .attach(MyFairing("yet more state"));
1095 ///
1096 /// let mut fairings: Vec<_> = rocket.fairings_mut::<MyFairing>().collect();
1097 /// assert_eq!(fairings.len(), 3);
1098 /// assert_eq!(fairings[0].0, "some state");
1099 /// assert_eq!(fairings[1].0, "other state");
1100 /// assert_eq!(fairings[2].0, "yet more state");
1101 ///
1102 /// // we can modify the fairings
1103 /// fairings[1].0 = "modified state";
1104 ///
1105 /// let fairings: Vec<_> = rocket.fairings::<MyFairing>().collect();
1106 /// assert_eq!(fairings.len(), 3);
1107 /// assert_eq!(fairings[0].0, "some state");
1108 /// assert_eq!(fairings[1].0, "modified state");
1109 /// assert_eq!(fairings[2].0, "yet more state");
1110 /// ```
1111 pub fn fairings_mut<F: Fairing>(&mut self) -> impl Iterator<Item = &mut F> {
1112 match self.0.as_mut() {
1113 StateRefMut::Build(p) => Either::Left(p.fairings.filter_mut::<F>()),
1114 StateRefMut::Ignite(p) => Either::Right(p.fairings.filter_mut::<F>()),
1115 StateRefMut::Orbit(p) => Either::Right(p.fairings.filter_mut::<F>()),
1116 }
1117 }
1118
1119 /// Returns the figment derived from the configuration provider set for
1120 /// `self`. To extract a typed config, prefer to use
1121 /// [`AdHoc::config()`](crate::fairing::AdHoc::config()).
1122 ///
1123 /// Note; A [`Figment`] generated from the current `provider` can _always_
1124 /// be retrieved via this method. However, because the provider can be
1125 /// changed at any point prior to ignition, a [`Config`] can only be
1126 /// retrieved in the ignite or orbit phases, or by manually extracting one
1127 /// from a particular figment.
1128 ///
1129 /// # Example
1130 ///
1131 /// ```rust
1132 /// let rocket = rocket::build();
1133 /// let figment = rocket.figment();
1134 /// ```
1135 pub fn figment(&self) -> &Figment {
1136 match self.0.as_ref() {
1137 StateRef::Build(p) => &p.figment,
1138 StateRef::Ignite(p) => &p.figment,
1139 StateRef::Orbit(p) => &p.figment,
1140 }
1141 }
1142
1143 async fn into_ignite(self) -> Result<Rocket<Ignite>, Error> {
1144 match self.0.into_state() {
1145 State::Build(s) => Rocket::from(s).ignite().await,
1146 State::Ignite(s) => Ok(Rocket::from(s)),
1147 State::Orbit(s) => Ok(Rocket::from(s).deorbit()),
1148 }
1149 }
1150
1151 pub(crate) async fn local_launch(self, e: Endpoint) -> Result<Rocket<Orbit>, Error> {
1152 Ok(self.into_ignite().await?._local_launch(e).await)
1153 }
1154
1155 /// Returns a `Future` that transitions this instance of `Rocket` from any
1156 /// phase into the _orbit_ phase. When `await`ed, the future drives the
1157 /// server forward, listening for and dispatching requests to mounted routes
1158 /// and catchers.
1159 ///
1160 /// In addition to all of the processes that occur during
1161 /// [ignition](Rocket::ignite()), a successful launch results in _liftoff_
1162 /// fairings being executed _after_ binding to any respective network
1163 /// interfaces but before serving the first request. Liftoff fairings are
1164 /// run concurrently; resolution of all fairings is `await`ed before
1165 /// resuming request serving.
1166 ///
1167 /// The `Future` resolves as an `Err` if any of the following occur:
1168 ///
1169 /// * there is an error igniting; see [`Rocket::ignite()`].
1170 /// * there is an I/O error starting the server.
1171 /// * an unrecoverable, system-level error occurs while running.
1172 ///
1173 /// The `Future` resolves as an `Ok` if any of the following occur:
1174 ///
1175 /// * graceful shutdown via [`Shutdown::notify()`] completes.
1176 ///
1177 /// The returned value on `Ok(())` is previously running instance.
1178 ///
1179 /// The `Future` does not resolve otherwise.
1180 ///
1181 /// # Error
1182 ///
1183 /// If there is a problem starting the application or the application fails
1184 /// unexpectedly while running, an [`Error`] is returned. Use
1185 /// [`Error::report()`] to log the error and obtain an exit code. See the
1186 /// [`Error`] documentation for more information.
1187 ///
1188 /// # Listener
1189 ///
1190 /// This method binds to the network interface described by the
1191 /// configuration via [`DefaultListener`]. To bind via a different listener,
1192 /// use [`Rocket::launch_with()`]. To serve on an existing listener, use
1193 /// [`Rocket::launch_on()`] or [`Rocket::try_launch_on()`].
1194 ///
1195 /// # Example
1196 ///
1197 /// ```rust,no_run
1198 /// #[rocket::main]
1199 /// async fn main() {
1200 /// let result = rocket::build().launch().await;
1201 ///
1202 /// // this is reachable only after `Shutdown::notify()` or `Ctrl+C`.
1203 /// println!("Rocket: deorbit.");
1204 /// }
1205 /// ```
1206 pub async fn launch(self) -> Result<Rocket<Ignite>, Error> {
1207 self.launch_with::<DefaultListener>().await
1208 }
1209
1210 /// Like [`Rocket::launch()`] but binds via the listener `B`.
1211 ///
1212 /// The instance is first [ignited](Rocket::ignite()). Then, a listener is
1213 /// created via [`B::bind()`](Bind::bind()), which reads its configuration
1214 /// from the ignited instance. Finally, the instance is launched on the
1215 /// listener as described in [`Rocket::launch()`]. [`Rocket::launch()`] is
1216 /// equivalent to `launch_with::<DefaultListener>()`.
1217 ///
1218 /// Use this method to launch on a listener that is configured via Rocket's
1219 /// configuration, either one of Rocket's own or a custom implementation of
1220 /// [`Bind`].
1221 ///
1222 /// # Error
1223 ///
1224 /// In addition to the errors returned by [`Rocket::launch()`], returns an
1225 /// [`ErrorKind::Bind`] error if `B` fails to bind.
1226 ///
1227 /// # Example
1228 ///
1229 /// Launch on a plain TCP listener, ignoring any `tls` configuration:
1230 ///
1231 /// ```rust,no_run
1232 /// use rocket::listener::tcp::TcpListener;
1233 ///
1234 /// #[rocket::main]
1235 /// async fn main() -> Result<(), rocket::Error> {
1236 /// let rocket = rocket::build().launch_with::<TcpListener>().await?;
1237 /// Ok(())
1238 /// }
1239 /// ```
1240 pub async fn launch_with<B: Bind>(self) -> Result<Rocket<Ignite>, Error> {
1241 let rocket = self.into_ignite().await?;
1242 let bind_endpoint = B::bind_endpoint(&rocket).ok();
1243 let listener: B = B::bind(&rocket).await
1244 .map_err(|e| ErrorKind::Bind(bind_endpoint, Box::new(e)))?;
1245
1246 let any: Box<dyn Any + Send + Sync> = Box::new(listener);
1247 match any.downcast::<DefaultListener>() {
1248 Ok(listener) => {
1249 let listener = *listener;
1250 crate::util::for_both!(listener, listener => {
1251 crate::util::for_both!(listener, listener => {
1252 rocket._launch(listener).await
1253 })
1254 })
1255 }
1256 Err(any) => {
1257 let listener = *any.downcast::<B>().unwrap();
1258 rocket._launch(listener).await
1259 }
1260 }
1261 }
1262
1263 /// Like [`Rocket::launch_on()`] but takes a future that resolves to a
1264 /// listener or an error.
1265 ///
1266 /// The future `listener` is awaited first. If it resolves to an error, an
1267 /// [`ErrorKind::Bind`] error is returned. Otherwise, the instance is
1268 /// [ignited](Rocket::ignite()) and launched on the resulting listener as
1269 /// described in [`Rocket::launch()`].
1270 ///
1271 /// Use this method to bind a listener without Rocket's configuration and
1272 /// report a binding failure as a Rocket [`Error`].
1273 ///
1274 /// # Example
1275 ///
1276 /// Launch on a TCP listener bound to a random, available port:
1277 ///
1278 /// ```rust,no_run
1279 /// use std::net::Ipv4Addr;
1280 /// use rocket::listener::tcp::TcpListener;
1281 ///
1282 /// #[rocket::main]
1283 /// async fn main() -> Result<(), rocket::Error> {
1284 /// let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0));
1285 /// let rocket = rocket::build().try_launch_on(listener).await?;
1286 /// Ok(())
1287 /// }
1288 /// ```
1289 pub async fn try_launch_on<L, F, E>(self, listener: F) -> Result<Rocket<Ignite>, Error>
1290 where L: Listener + 'static,
1291 F: Future<Output = Result<L, E>>,
1292 E: std::error::Error + Send + 'static
1293 {
1294 let listener = listener.map_err(|e| ErrorKind::Bind(None, Box::new(e))).await?;
1295 self.into_ignite().await?._launch(listener).await
1296 }
1297
1298 /// Like [`Rocket::launch()`] but launches on the existing `listener`.
1299 ///
1300 /// The instance is [ignited](Rocket::ignite()) and launched on `listener`
1301 /// as described in [`Rocket::launch()`]. Rocket's configuration is not
1302 /// consulted to bind: `listener` is used as is.
1303 ///
1304 /// Use this method when your application has already created a listener. To
1305 /// await a listener that may fail to bind, use [`Rocket::try_launch_on()`].
1306 ///
1307 /// # Example
1308 ///
1309 /// ```rust,no_run
1310 /// use std::net::Ipv4Addr;
1311 /// use rocket::listener::tcp::TcpListener;
1312 ///
1313 /// #[rocket::main]
1314 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
1315 /// let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8000)).await?;
1316 /// let rocket = rocket::build().launch_on(listener).await?;
1317 /// Ok(())
1318 /// }
1319 /// ```
1320 pub async fn launch_on<L>(self, listener: L) -> Result<Rocket<Ignite>, Error>
1321 where L: Listener + 'static,
1322 {
1323 self.into_ignite().await?._launch(listener).await
1324 }
1325}
1326
1327#[doc(hidden)]
1328impl<P: Phase> Deref for Rocket<P> {
1329 type Target = P::State;
1330
1331 fn deref(&self) -> &Self::Target {
1332 &self.0
1333 }
1334}
1335
1336#[doc(hidden)]
1337impl<P: Phase> DerefMut for Rocket<P> {
1338 fn deref_mut(&mut self) -> &mut Self::Target {
1339 &mut self.0
1340 }
1341}
1342
1343impl<P: Phase> fmt::Debug for Rocket<P> {
1344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345 self.0.fmt(f)
1346 }
1347}