rocket/config/config.rs
1use std::net::{IpAddr, Ipv4Addr};
2
3use figment::{Figment, Profile, Provider, Metadata, error::Result};
4use figment::providers::{Serialized, Env, Toml, Format};
5use figment::value::{Map, Dict, magic::RelativePathBuf};
6use serde::{Deserialize, Serialize};
7use yansi::{Paint, Style, Color::Primary};
8
9use crate::log::PaintExt;
10use crate::config::{LogLevel, Shutdown, Ident};
11use crate::request::{self, Request, FromRequest};
12use crate::http::uncased::Uncased;
13use crate::data::Limits;
14
15#[cfg(feature = "tls")]
16use crate::config::TlsConfig;
17
18#[cfg(feature = "secrets")]
19use crate::config::SecretKey;
20
21/// Rocket server configuration.
22///
23/// See the [module level docs](crate::config) as well as the [configuration
24/// guide] for further details.
25///
26/// [configuration guide]: https://rocket.rs/v0.5/guide/configuration/
27///
28/// # Defaults
29///
30/// All configuration values have a default, documented in the [fields](#fields)
31/// section below. [`Config::debug_default()`] returns the default values for
32/// the debug profile while [`Config::release_default()`] the default values for
33/// the release profile. The [`Config::default()`] method automatically selects
34/// the appropriate of the two based on the selected profile. With the exception
35/// of `log_level`, which is `normal` in `debug` and `critical` in `release`,
36/// and `secret_key`, which is regenerated from a random value if not set in
37/// "debug" mode only, all default values are identical in all profiles.
38///
39/// # Provider Details
40///
41/// `Config` is a Figment [`Provider`] with the following characteristics:
42///
43/// * **Profile**
44///
45/// The profile is set to the value of the `profile` field.
46///
47/// * **Metadata**
48///
49/// This provider is named `Rocket Config`. It does not specify a
50/// [`Source`](figment::Source) and uses default interpolation.
51///
52/// * **Data**
53///
54/// The data emitted by this provider are the keys and values corresponding
55/// to the fields and values of the structure. The dictionary is emitted to
56/// the "default" meta-profile.
57///
58/// Note that these behaviors differ from those of [`Config::figment()`].
59#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
60pub struct Config {
61 /// The selected profile. **(default: _debug_ `debug` / _release_ `release`)**
62 ///
63 /// _**Note:** This field is never serialized nor deserialized. When a
64 /// `Config` is merged into a `Figment` as a `Provider`, this profile is
65 /// selected on the `Figment`. When a `Config` is extracted, this field is
66 /// set to the extracting Figment's selected `Profile`._
67 #[serde(skip)]
68 pub profile: Profile,
69 /// IP address to serve on. **(default: `127.0.0.1`)**
70 pub address: IpAddr,
71 /// Port to serve on. **(default: `8000`)**
72 pub port: u16,
73 /// Number of threads to use for executing futures. **(default: `num_cores`)**
74 ///
75 /// _**Note:** Rocket only reads this value from sources in the [default
76 /// provider](Config::figment())._
77 pub workers: usize,
78 /// Limit on threads to start for blocking tasks. **(default: `512`)**
79 pub max_blocking: usize,
80 /// How, if at all, to identify the server via the `Server` header.
81 /// **(default: `"Rocket"`)**
82 pub ident: Ident,
83 /// The name of a header, whose value is typically set by an intermediary
84 /// server or proxy, which contains the real IP address of the connecting
85 /// client. Used internally and by [`Request::client_ip()`] and
86 /// [`Request::real_ip()`].
87 ///
88 /// To disable using any header for this purpose, set this value to `false`.
89 /// Deserialization semantics are identical to those of [`Ident`] except
90 /// that the value must syntactically be a valid HTTP header name.
91 ///
92 /// **Warning:** Rocket does not verify that this header was set by a proxy.
93 /// Any client can set it to any value. Only use this header if all requests
94 /// go through a trusted proxy that overwrites it. Otherwise, set this to
95 /// `false`.
96 ///
97 /// **(default: `"X-Real-IP"`)**
98 #[serde(deserialize_with = "crate::config::ip_header::deserialize")]
99 pub ip_header: Option<Uncased<'static>>,
100 /// Streaming read size limits. **(default: [`Limits::default()`])**
101 pub limits: Limits,
102 /// Directory to store temporary files in. **(default:
103 /// [`std::env::temp_dir()`])**
104 #[serde(serialize_with = "RelativePathBuf::serialize_relative")]
105 pub temp_dir: RelativePathBuf,
106 /// Keep-alive timeout in seconds; disabled when `0`. **(default: `5`)**
107 pub keep_alive: u32,
108 /// Linger time in seconds; disabled when `0`. **(default: `10`)**
109 ///
110 /// When closing a connection, Rocket shuts down writes and then reads and
111 /// discards incoming data for at most `linger` seconds or until the client
112 /// closes the connection. This prevents a TCP reset from discarding a
113 /// response the client has yet to read, as can happen when the client is
114 /// still sending data, such as the rest of a request body Rocket didn't
115 /// read. See [RFC 9112 §9.6] for details. This is equivalent to nginx's
116 /// `lingering_time` and is unrelated to the `SO_LINGER` socket option.
117 ///
118 /// When disabled, Rocket closes connections immediately, and a client still
119 /// sending data may receive a reset instead of a response. Lingering always
120 /// ends when the shutdown grace period elapses.
121 ///
122 /// Upgraded connections, such as WebSocket connections, never linger: once
123 /// a connection is upgraded, its I/O handler decides when to stop reading.
124 ///
125 /// [RFC 9112 §9.6]: https://www.rfc-editor.org/rfc/rfc9112#section-9.6
126 #[serde(default = "default_linger")]
127 pub linger: u32,
128 /// The TLS configuration, if any. **(default: `None`)**
129 #[cfg(feature = "tls")]
130 #[cfg_attr(nightly, doc(cfg(feature = "tls")))]
131 pub tls: Option<TlsConfig>,
132 /// The secret key for signing and encrypting. **(default: `0`)**
133 ///
134 /// _**Note:** This field _always_ serializes as a 256-bit array of `0`s to
135 /// aid in preventing leakage of the secret key._
136 #[cfg(feature = "secrets")]
137 #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
138 #[serde(serialize_with = "SecretKey::serialize_zero")]
139 pub secret_key: SecretKey,
140 /// Graceful shutdown configuration. **(default: [`Shutdown::default()`])**
141 pub shutdown: Shutdown,
142 /// Max level to log. **(default: _debug_ `normal` / _release_ `critical`)**
143 pub log_level: LogLevel,
144 /// Whether to use colors and emoji when logging. **(default: `true`)**
145 #[serde(deserialize_with = "figment::util::bool_from_str_or_int")]
146 pub cli_colors: bool,
147 /// PRIVATE: This structure may grow (but never change otherwise) in a
148 /// non-breaking release. As such, constructing this structure should
149 /// _always_ be done using a public constructor or update syntax:
150 ///
151 /// ```rust
152 /// use rocket::Config;
153 ///
154 /// let config = Config {
155 /// port: 1024,
156 /// keep_alive: 10,
157 /// ..Default::default()
158 /// };
159 /// ```
160 #[doc(hidden)]
161 #[serde(skip)]
162 pub __non_exhaustive: (),
163}
164
165impl Default for Config {
166 /// Returns the default configuration based on the Rust compilation profile.
167 /// This is [`Config::debug_default()`] in `debug` and
168 /// [`Config::release_default()`] in `release`.
169 ///
170 /// # Example
171 ///
172 /// ```rust
173 /// use rocket::Config;
174 ///
175 /// let config = Config::default();
176 /// ```
177 fn default() -> Config {
178 #[cfg(debug_assertions)] { Config::debug_default() }
179 #[cfg(not(debug_assertions))] { Config::release_default() }
180 }
181}
182
183impl Config {
184 const DEPRECATED_KEYS: &'static [(&'static str, Option<&'static str>)] = &[
185 ("env", Some(Self::PROFILE)), ("log", Some(Self::LOG_LEVEL)),
186 ("read_timeout", None), ("write_timeout", None),
187 ];
188
189 const DEPRECATED_PROFILES: &'static [(&'static str, Option<&'static str>)] = &[
190 ("dev", Some("debug")), ("prod", Some("release")), ("stag", None)
191 ];
192
193 /// Returns the default configuration for the `debug` profile, _irrespective
194 /// of the Rust compilation profile_ and `ROCKET_PROFILE`.
195 ///
196 /// This may differ from the configuration used by default,
197 /// [`Config::default()`], which is selected based on the Rust compilation
198 /// profile. See [defaults](#defaults) and [provider
199 /// details](#provider-details) for specifics.
200 ///
201 /// # Example
202 ///
203 /// ```rust
204 /// use rocket::Config;
205 ///
206 /// let config = Config::debug_default();
207 /// ```
208 pub fn debug_default() -> Config {
209 Config {
210 profile: Self::DEBUG_PROFILE,
211 address: Ipv4Addr::new(127, 0, 0, 1).into(),
212 port: 8000,
213 workers: num_cpus::get(),
214 max_blocking: 512,
215 ident: Ident::default(),
216 ip_header: Some(Uncased::from_borrowed("X-Real-IP")),
217 limits: Limits::default(),
218 temp_dir: std::env::temp_dir().into(),
219 keep_alive: 5,
220 linger: default_linger(),
221 #[cfg(feature = "tls")]
222 tls: None,
223 #[cfg(feature = "secrets")]
224 secret_key: SecretKey::zero(),
225 shutdown: Shutdown::default(),
226 log_level: LogLevel::Normal,
227 cli_colors: true,
228 __non_exhaustive: (),
229 }
230 }
231
232 /// Returns the default configuration for the `release` profile,
233 /// _irrespective of the Rust compilation profile_ and `ROCKET_PROFILE`.
234 ///
235 /// This may differ from the configuration used by default,
236 /// [`Config::default()`], which is selected based on the Rust compilation
237 /// profile. See [defaults](#defaults) and [provider
238 /// details](#provider-details) for specifics.
239 ///
240 /// # Example
241 ///
242 /// ```rust
243 /// use rocket::Config;
244 ///
245 /// let config = Config::release_default();
246 /// ```
247 pub fn release_default() -> Config {
248 Config {
249 profile: Self::RELEASE_PROFILE,
250 log_level: LogLevel::Critical,
251 ..Config::debug_default()
252 }
253 }
254
255 /// Returns the default provider figment used by [`rocket::build()`].
256 ///
257 /// The default figment reads from the following sources, in ascending
258 /// priority order:
259 ///
260 /// 1. [`Config::default()`] (see [defaults](#defaults))
261 /// 2. `Rocket.toml` _or_ filename in `ROCKET_CONFIG` environment variable
262 /// 3. `ROCKET_` prefixed environment variables
263 ///
264 /// The profile selected is the value set in the `ROCKET_PROFILE`
265 /// environment variable. If it is not set, it defaults to `debug` when
266 /// compiled in debug mode and `release` when compiled in release mode.
267 ///
268 /// [`rocket::build()`]: crate::build()
269 ///
270 /// # Example
271 ///
272 /// ```rust
273 /// use rocket::Config;
274 /// use serde::Deserialize;
275 ///
276 /// #[derive(Deserialize)]
277 /// struct MyConfig {
278 /// app_key: String,
279 /// }
280 ///
281 /// let my_config = Config::figment().extract::<MyConfig>();
282 /// ```
283 pub fn figment() -> Figment {
284 Figment::from(Config::default())
285 .merge(Toml::file(Env::var_or("ROCKET_CONFIG", "Rocket.toml")).nested())
286 .merge(Env::prefixed("ROCKET_").ignore(&["PROFILE"]).global())
287 .select(Profile::from_env_or("ROCKET_PROFILE", Self::DEFAULT_PROFILE))
288 }
289
290 /// Attempts to extract a `Config` from `provider`, returning the result.
291 ///
292 /// # Example
293 ///
294 /// ```rust
295 /// use rocket::Config;
296 /// use rocket::figment::providers::{Toml, Format, Env};
297 ///
298 /// // Use Rocket's default `Figment`, but allow values from `MyApp.toml`
299 /// // and `MY_APP_` prefixed environment variables to supersede its values.
300 /// let figment = Config::figment()
301 /// .merge(("some-thing", 123))
302 /// .merge(Env::prefixed("CONFIG_"));
303 ///
304 /// let config = Config::try_from(figment);
305 /// ```
306 pub fn try_from<T: Provider>(provider: T) -> Result<Self> {
307 let figment = Figment::from(provider);
308 let mut config = figment.extract::<Self>()?;
309 config.profile = figment.profile().clone();
310 Ok(config)
311 }
312
313 /// Extract a `Config` from `provider`, panicking if extraction fails.
314 ///
315 /// # Panics
316 ///
317 /// If extraction fails, prints an error message indicating the error and
318 /// panics. For a version that doesn't panic, use [`Config::try_from()`].
319 ///
320 /// # Example
321 ///
322 /// ```rust
323 /// use rocket::Config;
324 /// use rocket::figment::providers::{Toml, Format, Env};
325 ///
326 /// // Use Rocket's default `Figment`, but allow values from `MyApp.toml`
327 /// // and `MY_APP_` prefixed environment variables to supersede its values.
328 /// let figment = Config::figment()
329 /// .merge(Toml::file("MyApp.toml").nested())
330 /// .merge(Env::prefixed("MY_APP_"));
331 ///
332 /// let config = Config::from(figment);
333 /// ```
334 pub fn from<T: Provider>(provider: T) -> Self {
335 Self::try_from(provider).unwrap_or_else(bail_with_config_error)
336 }
337
338 /// Returns `true` if TLS is enabled.
339 ///
340 /// TLS is enabled when the `tls` feature is enabled and TLS has been
341 /// configured with at least one ciphersuite. Note that without changing
342 /// defaults, all supported ciphersuites are enabled in the recommended
343 /// configuration.
344 ///
345 /// # Example
346 ///
347 /// ```rust
348 /// let config = rocket::Config::default();
349 /// if config.tls_enabled() {
350 /// println!("TLS is enabled!");
351 /// } else {
352 /// println!("TLS is disabled.");
353 /// }
354 /// ```
355 pub fn tls_enabled(&self) -> bool {
356 #[cfg(feature = "tls")] {
357 self.tls.as_ref().map_or(false, |tls| !tls.ciphers.is_empty())
358 }
359
360 #[cfg(not(feature = "tls"))] { false }
361 }
362
363 /// Returns `true` if mTLS is enabled.
364 ///
365 /// mTLS is enabled when TLS is enabled ([`Config::tls_enabled()`]) _and_
366 /// the `mtls` feature is enabled _and_ mTLS has been configured with a CA
367 /// certificate chain.
368 ///
369 /// # Example
370 ///
371 /// ```rust
372 /// let config = rocket::Config::default();
373 /// if config.mtls_enabled() {
374 /// println!("mTLS is enabled!");
375 /// } else {
376 /// println!("mTLS is disabled.");
377 /// }
378 /// ```
379 pub fn mtls_enabled(&self) -> bool {
380 if !self.tls_enabled() {
381 return false;
382 }
383
384 #[cfg(feature = "mtls")] {
385 self.tls.as_ref().map_or(false, |tls| tls.mutual.is_some())
386 }
387
388 #[cfg(not(feature = "mtls"))] { false }
389 }
390
391 #[cfg(feature = "secrets")]
392 pub(crate) fn known_secret_key_used(&self) -> bool {
393 const KNOWN_SECRET_KEYS: &'static [&'static str] = &[
394 "hPRYyVRiMyxpw5sBB1XeCMN1kFsDCqKvBi2QJxBVHQk="
395 ];
396
397 KNOWN_SECRET_KEYS.iter().any(|&key_str| {
398 let value = figment::value::Value::from(key_str);
399 self.secret_key == value.deserialize().expect("known key is valid")
400 })
401 }
402
403 #[inline]
404 pub(crate) fn trace_print(&self, figment: &Figment) {
405 if self.log_level != LogLevel::Debug {
406 return;
407 }
408
409 trace!("-- configuration trace information --");
410 for param in Self::PARAMETERS {
411 if let Some(meta) = figment.find_metadata(param) {
412 let (param, name) = (param.blue(), meta.name.primary());
413 if let Some(ref source) = meta.source {
414 trace_!("{:?} parameter source: {} ({})", param, name, source);
415 } else {
416 trace_!("{:?} parameter source: {}", param, name);
417 }
418 }
419 }
420 }
421
422 pub(crate) fn pretty_print(&self, figment: &Figment) {
423 static VAL: Style = Primary.bold();
424
425 self.trace_print(figment);
426 launch_meta!("{}Configured for {}.", "🔧 ".emoji(), self.profile.underline());
427 launch_meta_!("address: {}", self.address.paint(VAL));
428 launch_meta_!("port: {}", self.port.paint(VAL));
429 launch_meta_!("workers: {}", self.workers.paint(VAL));
430 launch_meta_!("max blocking threads: {}", self.max_blocking.paint(VAL));
431 launch_meta_!("ident: {}", self.ident.paint(VAL));
432
433 match self.ip_header {
434 Some(ref name) => launch_meta_!("IP header: {}", name.paint(VAL)),
435 None => launch_meta_!("IP header: {}", "disabled".paint(VAL))
436 }
437
438 launch_meta_!("limits: {}", (&self.limits).paint(VAL));
439 launch_meta_!("temp dir: {}", self.temp_dir.relative().display().paint(VAL));
440 launch_meta_!("http/2: {}", (cfg!(feature = "http2").paint(VAL)));
441
442 match self.keep_alive {
443 0 => launch_meta_!("keep-alive: {}", "disabled".paint(VAL)),
444 ka => launch_meta_!("keep-alive: {}{}", ka.paint(VAL), "s".paint(VAL)),
445 }
446
447 match self.linger {
448 0 => launch_meta_!("linger: {}", "disabled".paint(VAL)),
449 s => launch_meta_!("linger: {}{}", s.paint(VAL), "s".paint(VAL)),
450 }
451
452 match (self.tls_enabled(), self.mtls_enabled()) {
453 (true, true) => launch_meta_!("tls: {}", "enabled w/mtls".paint(VAL)),
454 (true, false) => launch_meta_!("tls: {} w/o mtls", "enabled".paint(VAL)),
455 (false, _) => launch_meta_!("tls: {}", "disabled".paint(VAL)),
456 }
457
458 launch_meta_!("shutdown: {}", self.shutdown.paint(VAL));
459 launch_meta_!("log level: {}", self.log_level.paint(VAL));
460 launch_meta_!("cli colors: {}", self.cli_colors.paint(VAL));
461
462 // Check for now deprecated config values.
463 for (key, replacement) in Self::DEPRECATED_KEYS {
464 if let Some(md) = figment.find_metadata(key) {
465 warn!("found value for deprecated config key `{}`", key.paint(VAL));
466 if let Some(ref source) = md.source {
467 launch_meta_!("in {} {}", source.paint(VAL), md.name);
468 }
469
470 if let Some(new_key) = replacement {
471 launch_meta_!("key has been by replaced by `{}`", new_key.paint(VAL));
472 } else {
473 launch_meta_!("key has no special meaning");
474 }
475 }
476 }
477
478 // Check for now removed config values.
479 for (prefix, replacement) in Self::DEPRECATED_PROFILES {
480 if let Some(profile) = figment.profiles().find(|p| p.starts_with(prefix)) {
481 warn!("found set deprecated profile `{}`", profile.paint(VAL));
482
483 if let Some(new_profile) = replacement {
484 launch_meta_!("profile was replaced by `{}`", new_profile.paint(VAL));
485 } else {
486 launch_meta_!("profile `{}` has no special meaning", profile);
487 }
488 }
489 }
490
491 #[cfg(feature = "secrets")] {
492 launch_meta_!("secret key: {}", self.secret_key.paint(VAL));
493 if !self.secret_key.is_provided() {
494 warn!("secrets enabled without a stable `secret_key`");
495 launch_meta_!("disable `secrets` feature or configure a `secret_key`");
496 launch_meta_!("this becomes an {} in non-debug profiles", "error".red());
497 }
498 }
499 }
500}
501
502/// Associated constants for default profiles.
503impl Config {
504 /// The default debug profile: `debug`.
505 pub const DEBUG_PROFILE: Profile = Profile::const_new("debug");
506
507 /// The default release profile: `release`.
508 pub const RELEASE_PROFILE: Profile = Profile::const_new("release");
509
510 /// The default profile: "debug" on `debug`, "release" on `release`.
511 #[cfg(debug_assertions)]
512 pub const DEFAULT_PROFILE: Profile = Self::DEBUG_PROFILE;
513
514 /// The default profile: "debug" on `debug`, "release" on `release`.
515 #[cfg(not(debug_assertions))]
516 pub const DEFAULT_PROFILE: Profile = Self::RELEASE_PROFILE;
517}
518
519/// Associated constants for stringy versions of configuration parameters.
520impl Config {
521 /// The stringy parameter name for setting/extracting [`Config::profile`].
522 ///
523 /// This isn't `pub` because setting it directly does nothing.
524 const PROFILE: &'static str = "profile";
525
526 /// The stringy parameter name for setting/extracting [`Config::address`].
527 pub const ADDRESS: &'static str = "address";
528
529 /// The stringy parameter name for setting/extracting [`Config::port`].
530 pub const PORT: &'static str = "port";
531
532 /// The stringy parameter name for setting/extracting [`Config::workers`].
533 pub const WORKERS: &'static str = "workers";
534
535 /// The stringy parameter name for setting/extracting [`Config::max_blocking`].
536 pub const MAX_BLOCKING: &'static str = "max_blocking";
537
538 /// The stringy parameter name for setting/extracting [`Config::keep_alive`].
539 pub const KEEP_ALIVE: &'static str = "keep_alive";
540
541 /// The stringy parameter name for setting/extracting [`Config::linger`].
542 pub const LINGER: &'static str = "linger";
543
544 /// The stringy parameter name for setting/extracting [`Config::ident`].
545 pub const IDENT: &'static str = "ident";
546
547 /// The stringy parameter name for setting/extracting [`Config::ip_header`].
548 pub const IP_HEADER: &'static str = "ip_header";
549
550 /// The stringy parameter name for setting/extracting [`Config::limits`].
551 pub const LIMITS: &'static str = "limits";
552
553 /// The stringy parameter name for setting/extracting [`Config::tls`].
554 pub const TLS: &'static str = "tls";
555
556 /// The stringy parameter name for setting/extracting [`Config::secret_key`].
557 pub const SECRET_KEY: &'static str = "secret_key";
558
559 /// The stringy parameter name for setting/extracting [`Config::temp_dir`].
560 pub const TEMP_DIR: &'static str = "temp_dir";
561
562 /// The stringy parameter name for setting/extracting [`Config::log_level`].
563 pub const LOG_LEVEL: &'static str = "log_level";
564
565 /// The stringy parameter name for setting/extracting [`Config::shutdown`].
566 pub const SHUTDOWN: &'static str = "shutdown";
567
568 /// The stringy parameter name for setting/extracting [`Config::cli_colors`].
569 pub const CLI_COLORS: &'static str = "cli_colors";
570
571 /// An array of all of the stringy parameter names.
572 pub const PARAMETERS: &'static [&'static str] = &[
573 Self::ADDRESS, Self::PORT, Self::WORKERS, Self::MAX_BLOCKING,
574 Self::KEEP_ALIVE, Self::LINGER, Self::IDENT, Self::IP_HEADER, Self::LIMITS,
575 Self::TLS, Self::SECRET_KEY, Self::TEMP_DIR, Self::LOG_LEVEL, Self::SHUTDOWN,
576 Self::CLI_COLORS,
577 ];
578}
579
580fn default_linger() -> u32 {
581 10
582}
583
584impl Provider for Config {
585 #[track_caller]
586 fn metadata(&self) -> Metadata {
587 if self == &Config::default() {
588 Metadata::named("rocket::Config::default()")
589 } else {
590 Metadata::named("rocket::Config")
591 }
592 }
593
594 #[track_caller]
595 fn data(&self) -> Result<Map<Profile, Dict>> {
596 #[allow(unused_mut)]
597 let mut map: Map<Profile, Dict> = Serialized::defaults(self).data()?;
598
599 // We need to special-case `secret_key` since its serializer zeroes.
600 #[cfg(feature = "secrets")]
601 if !self.secret_key.is_zero() {
602 if let Some(map) = map.get_mut(&Profile::Default) {
603 map.insert("secret_key".into(), self.secret_key.key.master().into());
604 }
605 }
606
607 Ok(map)
608 }
609
610 fn profile(&self) -> Option<Profile> {
611 Some(self.profile.clone())
612 }
613}
614
615#[crate::async_trait]
616impl<'r> FromRequest<'r> for &'r Config {
617 type Error = std::convert::Infallible;
618
619 async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
620 request::Outcome::Success(req.rocket().config())
621 }
622}
623
624#[doc(hidden)]
625pub fn bail_with_config_error<T>(error: figment::Error) -> T {
626 pretty_print_error(error);
627 panic!("aborting due to configuration error(s)")
628}
629
630#[doc(hidden)]
631pub fn pretty_print_error(error: figment::Error) {
632 use figment::error::{Kind, OneOf};
633
634 crate::log::init_default();
635 error!("Failed to extract valid configuration.");
636 for e in error {
637 fn w<T>(v: T) -> yansi::Painted<T> { Paint::new(v).primary() }
638
639 match e.kind {
640 Kind::Message(msg) => error_!("{}", msg),
641 Kind::InvalidType(v, exp) => {
642 error_!("invalid type: found {}, expected {}", w(v), w(exp));
643 }
644 Kind::InvalidValue(v, exp) => {
645 error_!("invalid value {}, expected {}", w(v), w(exp));
646 },
647 Kind::InvalidLength(v, exp) => {
648 error_!("invalid length {}, expected {}", w(v), w(exp))
649 },
650 Kind::UnknownVariant(v, exp) => {
651 error_!("unknown variant: found `{}`, expected `{}`", w(v), w(OneOf(exp)))
652 }
653 Kind::UnknownField(v, exp) => {
654 error_!("unknown field: found `{}`, expected `{}`", w(v), w(OneOf(exp)))
655 }
656 Kind::MissingField(v) => {
657 error_!("missing field `{}`", w(v))
658 }
659 Kind::DuplicateField(v) => {
660 error_!("duplicate field `{}`", w(v))
661 }
662 Kind::ISizeOutOfRange(v) => {
663 error_!("signed integer `{}` is out of range", w(v))
664 }
665 Kind::USizeOutOfRange(v) => {
666 error_!("unsigned integer `{}` is out of range", w(v))
667 }
668 Kind::Unsupported(v) => {
669 error_!("unsupported type `{}`", w(v))
670 }
671 Kind::UnsupportedKey(a, e) => {
672 error_!("unsupported type `{}` for key: must be `{}`", w(a), w(e))
673 }
674 }
675
676 if let (Some(ref profile), Some(ref md)) = (&e.profile, &e.metadata) {
677 if !e.path.is_empty() {
678 let key = md.interpolate(profile, &e.path);
679 info_!("for key {}", w(key));
680 }
681 }
682
683 if let Some(md) = e.metadata {
684 if let Some(source) = md.source {
685 info_!("in {} {}", w(source), md.name);
686 } else {
687 info_!("in {}", w(md.name));
688 }
689 }
690 }
691}