Add config file parsing

Use the `serde` and `toml` crates to handle config file parsing.
This commit is contained in:
finga 2023-01-24 00:46:25 +01:00
parent 665015c296
commit d37f31dd8a
5 changed files with 160 additions and 12 deletions

47
src/config.rs Normal file
View file

@ -0,0 +1,47 @@
use serde::Deserialize;
fn default_host() -> String {
"localhost".to_string()
}
const fn default_port() -> u16 {
5432
}
fn default_name() -> String {
"whakarite".to_string()
}
fn default_user() -> String {
"whakarite".to_string()
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Database {
/// Host of the database
#[serde(default = "default_host")]
pub host: String,
/// Port of the database
#[serde(default = "default_port")]
pub port: u16,
/// Name of the database
#[serde(default = "default_name")]
pub name: String,
/// Name of the user to connect to the database
#[serde(default = "default_user")]
pub user: String,
/// Password of the user to connect to the database
pub pass: String,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// Database configuration
pub database: Database,
}

View file

@ -8,16 +8,18 @@ use std::{env, thread::park_timeout};
use time::{Duration, OffsetDateTime};
use tracing::{debug, info, trace};
mod config;
mod models;
mod schema;
use config::Config;
use models::{NewReminder, Reminder};
fn remind(
db: &mut PooledConnection<ConnectionManager<PgConnection>>,
mailer: &SmtpTransport,
) -> Result<()> {
debug!("executing remind run");
info!("checking for reminders");
for reminder in schema::reminders::dsl::reminders
.filter(schema::reminders::executed.is_null())
@ -40,16 +42,12 @@ fn remind(
debug!("email sent to {}", reminder.receiver);
} else {
info!(
"parking reminder for {:?}",
reminder.planned - OffsetDateTime::now_utc(),
);
let duration = reminder.planned - OffsetDateTime::now_utc();
info!(?duration, "parking reminder");
park_timeout(<std::time::Duration>::try_from(
reminder.planned - OffsetDateTime::now_utc(),
)?);
park_timeout(<std::time::Duration>::try_from(duration)?);
}
// Check for another remnd job if none dont loop forever
// Check for another remind job if none dont loop forever
}
Ok(())
@ -64,9 +62,20 @@ fn main() -> Result<()> {
env!("CARGO_PKG_VERSION")
);
let db_pool = Pool::builder().build(ConnectionManager::<PgConnection>::new(
"postgresql://whakarite:whakarite@localhost/whakarite",
))?;
let config_path = "./config.toml";
let config: Config = toml::from_str(&std::fs::read_to_string(config_path)?)?;
trace!(?config, config_path, "loaded config");
let db_pool = Pool::builder().build(ConnectionManager::<PgConnection>::new(format!(
"postgresql://{}:{}@{}:{}/{}",
config.database.user,
config.database.pass,
config.database.host,
config.database.port,
config.database.name
)))?;
let test_reminder = NewReminder {
created: OffsetDateTime::now_utc(),