Skip to content

Commit

Permalink
Human readable config error
Browse files Browse the repository at this point in the history
  • Loading branch information
Bluemangoo authored Apr 30, 2024
1 parent cbba61c commit fb53c10
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 34 deletions.
11 changes: 7 additions & 4 deletions src/config/import_able.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::util::path;
use anyhow::anyhow;
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer};
use std::fs::File;
Expand Down Expand Up @@ -31,7 +32,7 @@ where
}
}

impl<'de, T> Importable<T>
impl<T> Importable<T>
where
T: serde::de::DeserializeOwned,
{
Expand All @@ -40,10 +41,12 @@ where
Importable::Some(v) => Ok((v, String::from(base))),
Importable::Import(path) => {
let path = path::resolve(base, &path);
let mut file = File::open(&path)?;
let mut file = File::open(&path).or(Err(anyhow!("Cannot read file {}", &path)))?;
let mut toml_str = String::new();
file.read_to_string(&mut toml_str)?;
let t: T = toml::from_str(toml_str.as_str())?;
file.read_to_string(&mut toml_str)
.or(Err(anyhow!("Cannot read file {}", &path)))?;
let t: T = toml::from_str(toml_str.as_str())
.map_err(|err| anyhow!("Failed to parse {}: {}", &path, err.message()))?;
Ok((t, path))
}
}
Expand Down
62 changes: 32 additions & 30 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod util;
use crate::config::Importable;
use crate::gateway::Gateway;
use crate::util::path;
use anyhow::anyhow;
use log::error;
use pingora::prelude::*;
use simplelog::*;
Expand All @@ -27,13 +28,13 @@ pub struct Opt {
pub test: bool,
}

impl Into<Option<pingora::prelude::Opt>> for Opt {
fn into(self) -> Option<pingora::prelude::Opt> {
impl From<Opt> for Option<pingora::prelude::Opt> {
fn from(opt: Opt) -> Self {
Some(pingora::prelude::Opt {
upgrade: self.upgrade,
daemon: self.daemon,
nocapture: self.nocapture,
test: self.test,
upgrade: opt.upgrade,
daemon: opt.daemon,
nocapture: opt.nocapture,
test: opt.test,
conf: None,
})
}
Expand All @@ -48,27 +49,28 @@ struct CommandOpt {
base_opts: Opt,
}

fn main() {
fn main() -> anyhow::Result<()> {
let command_opts = CommandOpt::from_args();

let config_base: Importable<config::ConfigRaw> = Importable::Import(command_opts.config);
let config: config::Config = {
let c = config_base
.import(env::current_exe().unwrap().to_str().unwrap())
.unwrap();
config::Config::from_raw(c.0, &c.1).unwrap()
let c = config_base.import(env::current_exe()?.to_str().unwrap())?;
config::Config::from_raw(c.0, &c.1)?
};

#[inline(always)]
fn create_log(level: LevelFilter, path: &Option<String>) -> Box<dyn SharedLogger> {
fn create_log(
level: LevelFilter,
path: &Option<String>,
) -> anyhow::Result<Box<dyn SharedLogger>> {
let path = match path {
None => None,
Some(path) => {
let path = path::resolve(env::current_exe().unwrap().to_str().unwrap(), path);
let path = path::resolve(env::current_exe()?.to_str().unwrap(), path);
match path::create(&path) {
Ok(_) => Some(path),
Err(error) => {
println!("{}", error.to_string());
println!("{}", error);
println!(
"Failed to init {} logger, fallback to terminal.",
level.as_str()
Expand All @@ -79,38 +81,33 @@ fn main() {
}
};
match path {
Some(path) => WriteLogger::new(
Some(path) => Ok(WriteLogger::new(
level,
Config::default(),
OpenOptions::new()
.write(true)
.append(true)
.open(path)
.unwrap(),
),
None => TermLogger::new(
OpenOptions::new().append(true).open(path)?,
)),
None => Ok(TermLogger::new(
level,
Config::default(),
TerminalMode::Mixed,
ColorChoice::Auto,
),
)),
}
}

CombinedLogger::init(vec![
create_log(LevelFilter::Info, &config.log.access),
create_log(LevelFilter::Error, &config.log.error),
])
.unwrap();
create_log(LevelFilter::Info, &config.log.access)?,
create_log(LevelFilter::Error, &config.log.error)?,
])?;

let mut server = Server::new(command_opts.base_opts).unwrap();
let mut server = Server::new(command_opts.base_opts)?;

config.merge_into_pingora_config(&mut server.configuration);

server.bootstrap();

for i in config.server {
let port = u16::from_str(&i.0).unwrap();
let port = u16::from_str(&i.0)?;
let mut service_config: HashMap<String, (String, config::Source)> = HashMap::new();

for source in i.1.source {
Expand Down Expand Up @@ -155,12 +152,17 @@ fn main() {
Some(ssl) => {
service
.add_tls(&format!("0.0.0.0:{}", port), &ssl.cert, &ssl.key)
.expect(format!("Failed to read cert:\n{}\n{}", &ssl.cert, &ssl.key).as_str());
.or(Err(anyhow!(
"Failed to read cert:\n{}\n{}",
&ssl.cert,
&ssl.key
)))?;
}
}

server.add_service(service)
}

server.run_forever();
Ok(())
}

0 comments on commit fb53c10

Please sign in to comment.