Skip to content

Commit

Permalink
wip: remove all uses of old log macros
Browse files Browse the repository at this point in the history
  • Loading branch information
SergioBenitez committed May 16, 2024
1 parent ac2e8db commit fcc354c
Show file tree
Hide file tree
Showing 24 changed files with 187 additions and 169 deletions.
39 changes: 19 additions & 20 deletions contrib/dyn_templates/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,25 @@ impl Context {
Ok(_) | Err(_) => continue,
};

let (name, data_type_str) = split_path(&root, entry.path());
if let Some(info) = templates.get(&*name) {
warn_!("Template name '{}' does not have a unique source.", name);
match info.path {
Some(ref path) => info_!("Existing path: {:?}", path),
None => info_!("Existing Content-Type: {}", info.data_type),
}

info_!("Additional path: {:?}", entry.path());
warn_!("Keeping existing template '{}'.", name);
let (template, data_type_str) = split_path(&root, entry.path());
if let Some(info) = templates.get(&*template) {
warn!(
%template,
first_path = %entry.path().display(),
second_path = info.path.as_ref().map(|p| display(p.display())),
data_type = %info.data_type,
"Template name '{template}' can refer to multiple templates.\n\
First path will be used. Second path is ignored."
);

continue;
}

let data_type = data_type_str.as_ref()
.and_then(|ext| ContentType::from_extension(ext))
.unwrap_or(ContentType::Text);

templates.insert(name, TemplateInfo {
templates.insert(template, TemplateInfo {
path: Some(entry.into_path()),
engine_ext: ext,
data_type,
Expand All @@ -75,9 +76,8 @@ impl Context {
}

let mut engines = Engines::init(&templates)?;
if let Err(e) = callback(&mut engines) {
error_!("Template customization callback failed.");
error_!("{}", e);
if let Err(reason) = callback(&mut engines) {
error!(%reason, "template customization callback failed");
return None;
}

Expand Down Expand Up @@ -151,9 +151,8 @@ mod manager {
let watcher = match watcher {
Ok(watcher) => Some((watcher, Mutex::new(rx))),
Err(e) => {
warn!("Failed to enable live template reloading: {}", e);
debug_!("Reload error: {:?}", e);
warn_!("Live template reloading is unavailable.");
warn!("live template reloading initialization failed: {e}\n\
live template reloading is unavailable");
None
}
};
Expand Down Expand Up @@ -182,13 +181,13 @@ mod manager {
.map(|(_, rx)| rx.lock().expect("fsevents lock").try_iter().count() > 0);

if let Some(true) = templates_changes {
info_!("Change detected: reloading templates.");
debug!("template change detected: reloading templates");
let root = self.context().root.clone();
if let Some(new_ctxt) = Context::initialize(&root, callback) {
*self.context_mut() = new_ctxt;
} else {
warn_!("An error occurred while reloading templates.");
warn_!("Existing templates will remain active.");
warn!("error while reloading template\n\
existing templates will remain active.")
};
}
}
Expand Down
20 changes: 10 additions & 10 deletions contrib/dyn_templates/src/engine/handlebars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,26 @@ impl Engine for Handlebars<'static> {
fn init<'a>(templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Option<Self> {
let mut hb = Handlebars::new();
let mut ok = true;
for (name, path) in templates {
if let Err(e) = hb.register_template_file(name, path) {
error!("Handlebars template '{}' failed to register.", name);
error_!("{}", e);
info_!("Template path: '{}'.", path.to_string_lossy());
for (template, path) in templates {
if let Err(e) = hb.register_template_file(template, path) {
error!(template, path = %path.display(),
"failed to register Handlebars template: {e}");

ok = false;
}
}

ok.then_some(hb)
}

fn render<C: Serialize>(&self, name: &str, context: C) -> Option<String> {
if self.get_template(name).is_none() {
error_!("Handlebars template '{}' does not exist.", name);
fn render<C: Serialize>(&self, template: &str, context: C) -> Option<String> {
if self.get_template(template).is_none() {
error!(template, "requested Handlebars template does not exist.");
return None;
}

Handlebars::render(self, name, &context)
.map_err(|e| error_!("Handlebars: {}", e))
Handlebars::render(self, template, &context)
.map_err(|e| error!("Handlebars render error: {}", e))
.ok()
}
}
8 changes: 4 additions & 4 deletions contrib/dyn_templates/src/engine/minijinja.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ impl Engine for Environment<'static> {
Some(env)
}

fn render<C: Serialize>(&self, name: &str, context: C) -> Option<String> {
let Ok(template) = self.get_template(name) else {
error_!("Minijinja template '{name}' was not found.");
fn render<C: Serialize>(&self, template: &str, context: C) -> Option<String> {
let Ok(template) = self.get_template(template) else {
error!(template, "Minijinja template not found");
return None;
};

template.render(context)
.map_err(|e| error_!("Minijinja: {}", e))
.map_err(|e| error!("Minijinja render error: {}", e))
.ok()
}
}
38 changes: 19 additions & 19 deletions contrib/dyn_templates/src/engine/tera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,40 +21,40 @@ impl Engine for Tera {

// Finally try to tell Tera about all of the templates.
if let Err(e) = tera.add_template_files(files) {
error!("Failed to initialize Tera templating.");

let mut error = Some(&e as &dyn Error);
while let Some(err) = error {
info_!("{}", err);
error = err.source();
}
error_span!("Tera templating initialization failed" => {
let mut error = Some(&e as &dyn Error);
while let Some(err) = error {
error!("{err}");
error = err.source();
}
});

None
} else {
Some(tera)
}
}

fn render<C: Serialize>(&self, name: &str, context: C) -> Option<String> {
if self.get_template(name).is_err() {
error_!("Tera template '{}' does not exist.", name);
fn render<C: Serialize>(&self, template: &str, context: C) -> Option<String> {
if self.get_template(template).is_err() {
error!(template, "requested template does not exist");
return None;
};

let tera_ctx = Context::from_serialize(context)
.map_err(|e| error_!("Tera context error: {}.", e))
.map_err(|e| error!("Tera context error: {}.", e))
.ok()?;

match Tera::render(self, name, &tera_ctx) {
match Tera::render(self, template, &tera_ctx) {
Ok(string) => Some(string),
Err(e) => {
error_!("Error rendering Tera template '{}'.", name);

let mut error = Some(&e as &dyn Error);
while let Some(err) = error {
error_!("{}", err);
error = err.source();
}
error_span!("failed to render Tera template" [template] => {
let mut error = Some(&e as &dyn Error);
while let Some(err) = error {
error!("{err}");
error = err.source();
}
});

None
}
Expand Down
2 changes: 1 addition & 1 deletion contrib/dyn_templates/src/fairing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl Fairing for TemplateFairing {
if let Some(ctxt) = Context::initialize(&path, &self.callback) {
Ok(rocket.manage(ContextManager::new(ctxt)))
} else {
error_!("Template initialization failed. Aborting launch.");
error!("Template initialization failed. Aborting launch.");
Err(rocket)
}
}
Expand Down
53 changes: 31 additions & 22 deletions contrib/sync_db_pools/lib/src/connection.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use std::marker::PhantomData;
use std::sync::Arc;
use std::marker::PhantomData;

use rocket::{Phase, Rocket, Ignite, Sentinel};
use rocket::fairing::{AdHoc, Fairing};
use rocket::request::{Request, Outcome, FromRequest};
use rocket::outcome::IntoOutcome;
use rocket::http::Status;
use rocket::trace::Traceable;

use rocket::tokio::sync::{OwnedSemaphorePermit, Semaphore, Mutex};
use rocket::tokio::time::timeout;
use rocket::tokio::sync::{OwnedSemaphorePermit, Semaphore, Mutex};

use crate::{Config, Poolable, Error};

Expand Down Expand Up @@ -60,45 +61,50 @@ async fn run_blocking<F, R>(job: F) -> R
}
}

macro_rules! dberr {
($msg:literal, $db_name:expr, $efmt:literal, $error:expr, $rocket:expr) => ({
rocket::error!(concat!("database ", $msg, " error for pool named `{}`"), $db_name);
error_!($efmt, $error);
return Err($rocket);
});
}

impl<K: 'static, C: Poolable> ConnectionPool<K, C> {
pub fn fairing(fairing_name: &'static str, db: &'static str) -> impl Fairing {
pub fn fairing(fairing_name: &'static str, database: &'static str) -> impl Fairing {
AdHoc::try_on_ignite(fairing_name, move |rocket| async move {
run_blocking(move || {
let config = match Config::from(db, &rocket) {
let config = match Config::from(database, &rocket) {
Ok(config) => config,
Err(e) => dberr!("config", db, "{}", e, rocket),
Err(e) => {
error_span!("database configuration error" [database] => e.trace_error());
return Err(rocket);
}
};

let pool_size = config.pool_size;
match C::pool(db, &rocket) {
match C::pool(database, &rocket) {
Ok(pool) => Ok(rocket.manage(ConnectionPool::<K, C> {
config,
pool: Some(pool),
semaphore: Arc::new(Semaphore::new(pool_size as usize)),
_marker: PhantomData,
})),
Err(Error::Config(e)) => dberr!("config", db, "{}", e, rocket),
Err(Error::Pool(e)) => dberr!("pool init", db, "{}", e, rocket),
Err(Error::Custom(e)) => dberr!("pool manager", db, "{:?}", e, rocket),
Err(Error::Config(e)) => {
error_span!("database configuration error" [database] => e.trace_error());
Err(rocket)
}
Err(Error::Pool(reason)) => {
error!(database, %reason, "database pool initialization failed");
Err(rocket)
}
Err(Error::Custom(reason)) => {
error!(database, ?reason, "database pool failure");
Err(rocket)
}
}
}).await
})
}

pub async fn get(&self) -> Option<Connection<K, C>> {
let type_name = std::any::type_name::<K>();
let duration = std::time::Duration::from_secs(self.config.timeout as u64);
let permit = match timeout(duration, self.semaphore.clone().acquire_owned()).await {
Ok(p) => p.expect("internal invariant broken: semaphore should not be closed"),
Err(_) => {
error_!("database connection retrieval timed out");
error!(type_name, "database connection retrieval timed out");
return None;
}
};
Expand All @@ -113,7 +119,7 @@ impl<K: 'static, C: Poolable> ConnectionPool<K, C> {
_marker: PhantomData,
}),
Err(e) => {
error_!("failed to get a database connection: {}", e);
error!(type_name, "failed to get a database connection: {}", e);
None
}
}
Expand All @@ -125,12 +131,12 @@ impl<K: 'static, C: Poolable> ConnectionPool<K, C> {
Some(pool) => match pool.get().await {
Some(conn) => Some(conn),
None => {
error_!("no connections available for `{}`", std::any::type_name::<K>());
error!("no connections available for `{}`", std::any::type_name::<K>());
None
}
},
None => {
error_!("missing database fairing for `{}`", std::any::type_name::<K>());
error!("missing database fairing for `{}`", std::any::type_name::<K>());
None
}
}
Expand Down Expand Up @@ -165,6 +171,7 @@ impl<K: 'static, C: Poolable> Connection<K, C> {

let conn = connection.as_mut()
.expect("internal invariant broken: self.connection is Some");

f(conn)
}).await
}
Expand Down Expand Up @@ -212,7 +219,9 @@ impl<'r, K: 'static, C: Poolable> FromRequest<'r> for Connection<K, C> {
match request.rocket().state::<ConnectionPool<K, C>>() {
Some(c) => c.get().await.or_error((Status::ServiceUnavailable, ())),
None => {
error_!("Missing database fairing for `{}`", std::any::type_name::<K>());
let conn = std::any::type_name::<K>();
error!("`{conn}::fairing()` is not attached\n\
the fairing must be attached to use `{conn} in routes.");
Outcome::Error((Status::InternalServerError, ()))
}
}
Expand Down
27 changes: 16 additions & 11 deletions core/codegen/src/attribute/route/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,10 @@ fn query_decls(route: &Route) -> Option<TokenStream> {
)*

if !__e.is_empty() {
::rocket::warn_!("Query string failed to match route declaration.");
for _err in __e { ::rocket::warn_!("{}", _err); }
::rocket::info_span!("query string failed to match route declaration" => {
for _err in __e { ::rocket::info!("{_err}"); }
});

return #Outcome::Forward((#__data, #Status::UnprocessableEntity));
}

Expand All @@ -125,11 +127,11 @@ fn request_guard_decl(guard: &Guard) -> TokenStream {
let #ident: #ty = match <#ty as #FromRequest>::from_request(#__req).await {
#Outcome::Success(__v) => __v,
#Outcome::Forward(__e) => {
::rocket::warn_!("Request guard `{}` is forwarding.", stringify!(#ty));
::rocket::info!(type_name = stringify!(#ty), "guard forwarding");
return #Outcome::Forward((#__data, __e));
},
#Outcome::Error((__c, __e)) => {
::rocket::warn_!("Request guard `{}` failed: {:?}.", stringify!(#ty), __e);
::rocket::info!(type_name = stringify!(#ty), "guard failed: {__e:?}");
return #Outcome::Error(__c);
}
};
Expand All @@ -145,8 +147,9 @@ fn param_guard_decl(guard: &Guard) -> TokenStream {

// Returned when a dynamic parameter fails to parse.
let parse_error = quote!({
::rocket::warn_!("Parameter guard `{}: {}` is forwarding: {:?}.",
#name, stringify!(#ty), __error);
::rocket::info!(name: "forward",
reason = %__error, parameter = #name, "type" = stringify!(#ty),
"parameter forwarding");

#Outcome::Forward((#__data, #Status::UnprocessableEntity))
});
Expand All @@ -161,9 +164,11 @@ fn param_guard_decl(guard: &Guard) -> TokenStream {
#_Err(__error) => return #parse_error,
},
#_None => {
::rocket::error_!("Internal invariant broken: dyn param {} not found.", #i);
::rocket::error_!("Please report this to the Rocket issue tracker.");
::rocket::error_!("https://github.com/rwf2/Rocket/issues");
::rocket::error!(
"Internal invariant broken: dyn param {} not found.\n\
Please report this to the Rocket issue tracker.\n\
https://github.com/rwf2/Rocket/issues", #i);

return #Outcome::Forward((#__data, #Status::InternalServerError));
}
}
Expand All @@ -188,11 +193,11 @@ fn data_guard_decl(guard: &Guard) -> TokenStream {
let #ident: #ty = match <#ty as #FromData>::from_data(#__req, #__data).await {
#Outcome::Success(__d) => __d,
#Outcome::Forward((__d, __e)) => {
::rocket::warn_!("Data guard `{}` is forwarding.", stringify!(#ty));
::rocket::info!(type_name = stringify!(#ty), "data guard forwarding");
return #Outcome::Forward((__d, __e));
}
#Outcome::Error((__c, __e)) => {
::rocket::warn_!("Data guard `{}` failed: {:?}.", stringify!(#ty), __e);
::rocket::info!(type_name = stringify!(#ty), "data guard failed: {__e:?}");
return #Outcome::Error(__c);
}
};
Expand Down
Loading

0 comments on commit fcc354c

Please sign in to comment.