feat(config): App can take environ variables

- Change log level of SQLx to TRACE
This commit is contained in:
minhtrannhat 2024-05-11 22:30:21 -04:00
parent 96a6b6a351
commit d96eae1fec
Signed by: minhtrannhat
GPG Key ID: E13CFA85C53F8062
7 changed files with 57 additions and 27 deletions

12
Cargo.lock generated
View File

@ -618,6 +618,7 @@ dependencies = [
"reqwest", "reqwest",
"secrecy", "secrecy",
"serde", "serde",
"serde-aux",
"sqlx", "sqlx",
"tokio", "tokio",
"tracing", "tracing",
@ -1987,6 +1988,17 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "serde-aux"
version = "4.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d2e8bfba469d06512e11e3311d4d051a4a387a5b42d010404fecf3200321c95"
dependencies = [
"chrono",
"serde",
"serde_json",
]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.197" version = "1.0.197"

View File

@ -30,6 +30,7 @@ once_cell = "1.19.0"
secrecy = { version = "0.8.0", features = ["serde"] } secrecy = { version = "0.8.0", features = ["serde"] }
tracing-actix-web = "0.7.10" tracing-actix-web = "0.7.10"
h2 = "0.3.26" h2 = "0.3.26"
serde-aux = "4.5.0"
[dependencies.sqlx] [dependencies.sqlx]
version = "0.7" version = "0.7"

View File

@ -1,2 +1,4 @@
application: application:
host: 127.0.0.1 host: 127.0.0.1
database:
require_ssl: false

View File

@ -1,2 +1,4 @@
application: application:
host: 0.0.0.0 host: 0.0.0.0
database:
require_ssl: true

View File

@ -1,4 +1,7 @@
use secrecy::{ExposeSecret, Secret}; use secrecy::{ExposeSecret, Secret};
use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::postgres::{PgConnectOptions, PgSslMode};
use sqlx::ConnectOptions;
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct Settings { pub struct Settings {
@ -8,6 +11,7 @@ pub struct Settings {
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct ApplicationSettings { pub struct ApplicationSettings {
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16, pub port: u16,
pub host: String, pub host: String,
} }
@ -16,9 +20,11 @@ pub struct ApplicationSettings {
pub struct DatabaseSettings { pub struct DatabaseSettings {
pub username: String, pub username: String,
pub password: Secret<String>, pub password: Secret<String>,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16, pub port: u16,
pub host: String, pub host: String,
pub database_name: String, pub database_name: String,
pub require_ssl: bool,
} }
pub fn get_configuration() -> Result<Settings, config::ConfigError> { pub fn get_configuration() -> Result<Settings, config::ConfigError> {
@ -39,6 +45,15 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
.add_source(config::File::from( .add_source(config::File::from(
configuration_directory.join(environment_filename), configuration_directory.join(environment_filename),
)) ))
// take settings from environment variables
// with a prefix of APP and __ as separator
//
// E.g `APP_APPLICATION_PORT=5001` would set Settings.application.port
.add_source(
config::Environment::with_prefix("APP")
.prefix_separator("_")
.separator("__"),
)
.build()?; .build()?;
settings.try_deserialize::<Settings>() settings.try_deserialize::<Settings>()
@ -73,24 +88,26 @@ Use either `local` or `production`.",
} }
impl DatabaseSettings { impl DatabaseSettings {
pub fn connection_string(&self) -> Secret<String> { // for normal usage
Secret::new(format!( pub fn with_db(&self) -> PgConnectOptions {
"postgres://{}:{}@{}:{}/{}", let mut options = self.without_db().database(&self.database_name);
self.username, options = options.log_statements(tracing_log::log::LevelFilter::Trace);
self.password.expose_secret(), options
self.host,
self.port,
self.database_name
))
} }
pub fn connection_string_without_db(&self) -> Secret<String> { // for testings, we will set the database name with arbitrary values
Secret::new(format!( pub fn without_db(&self) -> PgConnectOptions {
"postgres://{}:{}@{}:{}", let ssl_mode = if self.require_ssl {
self.username, PgSslMode::Require
self.password.expose_secret(), } else {
self.host, PgSslMode::Prefer
self.port };
))
PgConnectOptions::new()
.host(&self.host)
.username(&self.username)
.password(self.password.expose_secret())
.port(self.port)
.ssl_mode(ssl_mode)
} }
} }

View File

@ -2,8 +2,7 @@ use std::net::TcpListener;
use email_newsletter_api::telemetry::{get_subscriber, init_subscriber}; use email_newsletter_api::telemetry::{get_subscriber, init_subscriber};
use email_newsletter_api::{configuration::get_configuration, startup}; use email_newsletter_api::{configuration::get_configuration, startup};
use secrecy::ExposeSecret; use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), std::io::Error> { async fn main() -> Result<(), std::io::Error> {
@ -16,8 +15,7 @@ async fn main() -> Result<(), std::io::Error> {
); );
init_subscriber(subscriber); init_subscriber(subscriber);
let db_conn = PgPool::connect_lazy(configuration.database.connection_string().expose_secret()) let db_conn = PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
.expect("Failed to connect to PostgreSQL");
let listener = TcpListener::bind(format!( let listener = TcpListener::bind(format!(
"{}:{}", "{}:{}",

View File

@ -3,7 +3,6 @@ use email_newsletter_api::{
telemetry::{get_subscriber, init_subscriber}, telemetry::{get_subscriber, init_subscriber},
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use secrecy::ExposeSecret;
use sqlx::{Connection, Executor, PgConnection, PgPool}; use sqlx::{Connection, Executor, PgConnection, PgPool};
use std::net::TcpListener; use std::net::TcpListener;
use uuid::Uuid; use uuid::Uuid;
@ -58,17 +57,16 @@ pub async fn spawn_app() -> TestApp {
} }
pub async fn configure_test_database(db_config: &DatabaseSettings) -> PgPool { pub async fn configure_test_database(db_config: &DatabaseSettings) -> PgPool {
let mut connection = let mut connection = PgConnection::connect_with(&db_config.without_db())
PgConnection::connect(db_config.connection_string_without_db().expose_secret()) .await
.await .expect("Failed to connect to Postgres");
.expect("Failed to connect to Postgres");
connection connection
.execute(format!(r#"CREATE DATABASE "{}";"#, db_config.database_name).as_str()) .execute(format!(r#"CREATE DATABASE "{}";"#, db_config.database_name).as_str())
.await .await
.expect("Failed to create database"); .expect("Failed to create database");
let conn_pool = PgPool::connect(db_config.connection_string().expose_secret()) let conn_pool = PgPool::connect_with(db_config.with_db())
.await .await
.expect("Failed to connect to PostgreSQL pool"); .expect("Failed to connect to PostgreSQL pool");