Skip to content

Commit

Permalink
wip: fix remaining fallout
Browse files Browse the repository at this point in the history
  • Loading branch information
SergioBenitez committed May 21, 2024
1 parent 7bc2fea commit ba82c14
Show file tree
Hide file tree
Showing 18 changed files with 73 additions and 54 deletions.
2 changes: 1 addition & 1 deletion benchmarks/src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ fn generate_matching_requests<'c>(client: &'c Client, routes: &[Route]) -> Vec<L
fn client(routes: Vec<Route>) -> Client {
let config = Config {
profile: Config::RELEASE_PROFILE,
// log_level: rocket::config::LogLevel::Off,
log_level: None,
cli_colors: config::CliColors::Never,
shutdown: config::ShutdownConfig {
ctrlc: false,
Expand Down
7 changes: 6 additions & 1 deletion contrib/db_pools/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ deadpool_redis = ["deadpool-redis", "deadpool"]
# sqlx features
sqlx_mysql = ["sqlx", "sqlx/mysql"]
sqlx_postgres = ["sqlx", "sqlx/postgres"]
sqlx_sqlite = ["sqlx", "sqlx/sqlite"]
sqlx_sqlite = ["sqlx", "sqlx/sqlite", "log"]
sqlx_macros = ["sqlx/macros"]
# diesel features
diesel_postgres = ["diesel-async/postgres", "diesel-async/deadpool", "diesel", "deadpool_09"]
Expand Down Expand Up @@ -86,6 +86,11 @@ default-features = false
features = ["runtime-tokio-rustls"]
optional = true

[dependencies.log]
version = "0.4"
default-features = false
optional = true

[dev-dependencies.rocket]
path = "../../../core/lib"
default-features = false
Expand Down
23 changes: 16 additions & 7 deletions contrib/db_pools/lib/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ mod deadpool_old {
mod sqlx {
use sqlx::ConnectOptions;
use super::{Duration, Error, Config, Figment};
// use rocket::config::LogLevel;
use rocket::tracing::level_filters::LevelFilter;

type Options<D> = <<D as sqlx::Database>::Connection as sqlx::Connection>::Options;

Expand Down Expand Up @@ -302,12 +302,21 @@ mod sqlx {
specialize(&mut opts, &config);

opts = opts.disable_statement_logging();
// if let Ok(level) = figment.extract_inner::<LogLevel>(rocket::Config::LOG_LEVEL) {
// if !matches!(level, LogLevel::Normal | LogLevel::Off) {
// opts = opts.log_statements(level.into())
// .log_slow_statements(level.into(), Duration::default());
// }
// }
if let Ok(value) = figment.find_value(rocket::Config::LOG_LEVEL) {
if let Some(level) = value.as_str().and_then(|v| v.parse().ok()) {
let log_level = match level {
LevelFilter::OFF => log::LevelFilter::Off,
LevelFilter::ERROR => log::LevelFilter::Error,
LevelFilter::WARN => log::LevelFilter::Warn,
LevelFilter::INFO => log::LevelFilter::Info,
LevelFilter::DEBUG => log::LevelFilter::Debug,
LevelFilter::TRACE => log::LevelFilter::Trace,
};

opts = opts.log_statements(log_level)
.log_slow_statements(log_level, Duration::default());
}
}

sqlx::pool::PoolOptions::new()
.max_connections(config.max_connections as u32)
Expand Down
3 changes: 2 additions & 1 deletion contrib/dyn_templates/src/fairing.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use rocket::{Rocket, Build, Orbit};
use rocket::fairing::{self, Fairing, Info, Kind};
use rocket::figment::{Source, value::magic::RelativePathBuf};
use rocket::trace::Trace;

use crate::context::{Callback, Context, ContextManager};
use crate::template::DEFAULT_TEMPLATE_DIR;
Expand Down Expand Up @@ -40,7 +41,7 @@ impl Fairing for TemplateFairing {
Ok(dir) => dir,
Err(e) if e.missing() => DEFAULT_TEMPLATE_DIR.into(),
Err(e) => {
rocket::config::pretty_print_error(e);
e.trace_error();
return Err(rocket);
}
};
Expand Down
16 changes: 16 additions & 0 deletions core/codegen/tests/typed-uris.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,3 +709,19 @@ fn test_vec_in_query() {
uri!(h(v = &[1, 2, 3][..])) => "/?v=%01%02%03",
}
}

#[test]
fn test_either() {
use rocket::either::{Either, Left, Right};

#[get("/<_foo>")]
fn f(_foo: Either<usize, &str>) { }

assert_uri_eq! {
uri!(f(Left::<usize, &str>(123))) => "/123",
uri!(f(_foo = Left::<usize, &str>(710))) => "/710",

uri!(f(Right::<usize, &str>("hello world"))) => "/hello%20world",
uri!(f(_foo = Right::<usize, &str>("bye?"))) => "/bye%3F",
}
}
2 changes: 1 addition & 1 deletion core/lib/fuzz/targets/collision-matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ type TestData<'a> = (
fn fuzz((route_a, route_b, req): TestData<'_>) {
let rocket = rocket::custom(rocket::Config {
workers: 2,
// log_level: rocket::log::LogLevel::Off,
log_level: None,
cli_colors: rocket::config::CliColors::Never,
..rocket::Config::debug_default()
});
Expand Down
17 changes: 4 additions & 13 deletions core/lib/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,10 @@ impl Config {
/// let config = Config::from(figment);
/// ```
pub fn from<T: Provider>(provider: T) -> Self {
Self::try_from(provider).unwrap_or_else(bail_with_config_error)
Self::try_from(provider).unwrap_or_else(|e| {
e.trace_error();
panic!("aborting due to configuration error(s)")
})
}
}

Expand Down Expand Up @@ -433,15 +436,3 @@ impl<'r> FromRequest<'r> for &'r Config {
request::Outcome::Success(req.rocket().config())
}
}

#[doc(hidden)]
pub fn bail_with_config_error<T>(error: figment::Error) -> T {
pretty_print_error(error);
panic!("aborting due to configuration error(s)")
}

#[doc(hidden)]
// FIXME: Remove this function.
pub fn pretty_print_error(error: figment::Error) {
error.trace_error()
}
3 changes: 0 additions & 3 deletions core/lib/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,3 @@ pub use crate::shutdown::Sig;

#[cfg(feature = "secrets")]
pub use secret_key::SecretKey;

#[doc(hidden)]
pub use config::{pretty_print_error, bail_with_config_error};
9 changes: 5 additions & 4 deletions core/lib/src/fairing/ad_hoc.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use futures::future::{Future, BoxFuture, FutureExt};
use parking_lot::Mutex;
use futures::future::{Future, BoxFuture, FutureExt};

use crate::route::RouteUri;
use crate::fairing::{Fairing, Kind, Info, Result};
use crate::{Rocket, Request, Response, Data, Build, Orbit};
use crate::fairing::{Fairing, Kind, Info, Result};
use crate::route::RouteUri;
use crate::trace::Trace;

/// A ad-hoc fairing that can be created from a function or closure.
///
Expand Down Expand Up @@ -235,7 +236,7 @@ impl AdHoc {
let app_config = match rocket.figment().extract::<T>() {
Ok(config) => config,
Err(e) => {
crate::config::pretty_print_error(e);
e.trace_error();
return Err(rocket);
}
};
Expand Down
7 changes: 5 additions & 2 deletions core/lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,11 @@ pub fn async_test<R>(fut: impl std::future::Future<Output = R>) -> R {
/// WARNING: This is unstable! Do not use this method outside of Rocket!
#[doc(hidden)]
pub fn async_main<R>(fut: impl std::future::Future<Output = R> + Send) -> R {
fn bail<T, E: crate::trace::Trace>(e: E) -> T {
e.trace_error();
panic!("aborting due to error")
}

// FIXME: We need to run `fut` to get the user's `Figment` to properly set
// up the async env, but we need the async env to run `fut`. So we're stuck.
// Tokio doesn't let us take the state from one async env and migrate it to
Expand All @@ -262,8 +267,6 @@ pub fn async_main<R>(fut: impl std::future::Future<Output = R> + Send) -> R {
// values won't reflect swaps of `Rocket` in attach fairings with different
// config values, or values from non-Rocket configs. See tokio-rs/tokio#3329
// for a necessary resolution in `tokio`.
use config::bail_with_config_error as bail;

let fig = Config::figment();
let workers = fig.extract_inner(Config::WORKERS).unwrap_or_else(bail);
let max_blocking = fig.extract_inner(Config::MAX_BLOCKING).unwrap_or_else(bail);
Expand Down
2 changes: 1 addition & 1 deletion core/lib/src/local/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ macro_rules! pub_client_impl {
use crate::config;

let figment = rocket.figment().clone()
// .merge((config::Config::LOG_LEVEL, config::LogLevel::Debug))
.merge((config::Config::LOG_LEVEL, "debug"))
.select(config::Config::DEBUG_PROFILE);

Self::tracked(rocket.reconfigure(figment)) $(.$suffix)?
Expand Down
3 changes: 2 additions & 1 deletion core/lib/src/response/responder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,8 @@ impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Option<R> {
match self {
Some(r) => r.respond_to(req),
None => {
debug!("{} responder returned `None`", std::any::type_name::<Self>());
let type_name = std::any::type_name::<Self>();
debug!(type_name, "`Option` responder returned `None`");
Err(Status::NotFound)
},
}
Expand Down
13 changes: 0 additions & 13 deletions core/lib/src/rocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,19 +590,6 @@ impl Rocket<Build> {
}
}

#[tracing::instrument(name = "items", skip_all, fields(kind = kind))]
fn log_items<T, I, B, O>(kind: &str, items: I, base: B, origin: O)
where T: fmt::Display + Copy, I: Iterator<Item = T>,
B: Fn(&T) -> &Origin<'_>, O: Fn(&T) -> &Origin<'_>
{
let mut items: Vec<_> = items.collect();
items.sort_by_key(|i| origin(i).path().as_str().chars().count());
items.sort_by_key(|i| origin(i).path().segments().count());
items.sort_by_key(|i| base(i).path().as_str().chars().count());
items.sort_by_key(|i| base(i).path().segments().count());
items.iter().for_each(|item| info!(name: "item", %item));
}

impl Rocket<Ignite> {
/// Returns the finalized, active configuration. This is guaranteed to
/// remain stable through ignition and into orbit.
Expand Down
5 changes: 4 additions & 1 deletion core/lib/src/trace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ pub mod subscriber;

pub(crate) mod level;

#[doc(inline)]
pub use macros::*;

#[doc(inline)]
pub use traceable::{Trace, TraceAll};

#[doc(inline)]
pub use macros::*;
pub use tracing::{Level, level_filters::LevelFilter};

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
#[serde(crate = "rocket::serde")]
Expand Down
2 changes: 2 additions & 0 deletions examples/config/Rocket.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ port = 8000
workers = 1
keep_alive = 0
log_level = "info"
log_format = "pretty"

[release]
address = "127.0.0.1"
port = 8000
workers = 12
keep_alive = 5
log_level = "error"
log_format = "compact"
# NOTE: Don't (!) use this key! Generate your own and keep it private!
# e.g. via `head -c64 /dev/urandom | base64`
secret_key = "hPRYyVRiMyxpw5sBB1XeCMN1kFsDCqKvBi2QJxBVHQk="
Expand Down
9 changes: 6 additions & 3 deletions examples/config/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use rocket::config::{Config, /* LogLevel */};
use rocket::config::Config;
use rocket::trace::{Level, TraceFormat};

async fn test_config(profile: &str) {
let provider = Config::figment().select(profile);
Expand All @@ -8,12 +9,14 @@ async fn test_config(profile: &str) {
"debug" => {
assert_eq!(config.workers, 1);
assert_eq!(config.keep_alive, 0);
// assert_eq!(config.log_level, LogLevel::Normal);
assert_eq!(config.log_level, Some(Level::INFO));
assert_eq!(config.log_format, TraceFormat::Compact);
}
"release" => {
assert_eq!(config.workers, 12);
assert_eq!(config.keep_alive, 5);
// assert_eq!(config.log_level, LogLevel::Critical);
assert_eq!(config.log_level, Some(Level::ERROR));
assert_eq!(config.log_format, TraceFormat::Compact);
assert!(!config.secret_key.is_zero());
}
_ => {
Expand Down
2 changes: 1 addition & 1 deletion examples/hello/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ edition = "2021"
publish = false

[dependencies]
rocket = { path = "../../core/lib", features = ["secrets"] }
rocket = { path = "../../core/lib" }
2 changes: 1 addition & 1 deletion examples/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ fn wave(name: &str, age: u8) -> String {
// http://127.0.0.1:8000/?name=Rocketeer&lang=en&emoji
// http://127.0.0.1:8000/?lang=ru&emoji&name=Rocketeer
#[get("/?<lang>&<opt..>")]
async fn hello(lang: Option<Lang>, opt: Options<'_>) -> String {
fn hello(lang: Option<Lang>, opt: Options<'_>) -> String {
let mut greeting = String::new();
if opt.emoji {
greeting.push_str("👋 ");
Expand Down

0 comments on commit ba82c14

Please sign in to comment.