|
| 1 | +use std::{ |
| 2 | + collections::HashSet, |
| 3 | + env, |
| 4 | + ffi::OsStr, |
| 5 | + fmt::{Debug, Display}, |
| 6 | +}; |
| 7 | + |
| 8 | +use error_stack::{Context, Result, ResultExt}; |
| 9 | +use secrecy::{ExposeSecret, Secret}; |
| 10 | +use sqlx::postgres::PgConnectOptions; |
| 11 | + |
| 12 | +use crate::supermarket::{get_supermarket_type, Supermarket}; |
| 13 | + |
| 14 | +pub struct Config { |
| 15 | + pub(crate) application: ApplicationConfig, |
| 16 | + pub(crate) database: DatabaseConfig, |
| 17 | +} |
| 18 | + |
| 19 | +#[allow(clippy::module_name_repetitions)] |
| 20 | +pub struct ApplicationConfig { |
| 21 | + /// The supermarket we are targeting to get price information for. |
| 22 | + pub(crate) supermarket: Supermarket, |
| 23 | +} |
| 24 | + |
| 25 | +#[allow(clippy::module_name_repetitions)] |
| 26 | +pub struct DatabaseConfig { |
| 27 | + /// If we should insert information into the Postgres database, or if we |
| 28 | + /// are in read-only mode. |
| 29 | + pub(crate) should_insert: bool, |
| 30 | + /// The username to use when connect to the Postgres database. |
| 31 | + /// |
| 32 | + /// Common values include `postgres`. |
| 33 | + username: String, |
| 34 | + /// The password to use when connecting to the Postgres database. |
| 35 | + password: Secret<String>, |
| 36 | + /// The host to use to connect to the database. Commonly `localhost`. |
| 37 | + host: String, |
| 38 | + /// The name of the database to use. Commonly `supermarket_tracker`. |
| 39 | + name: String, |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Debug)] |
| 43 | +#[allow(clippy::module_name_repetitions)] |
| 44 | +pub enum ConfigError { |
| 45 | + /// The variable that was missing when trying to load it. |
| 46 | + LoadVariable { variable: String }, |
| 47 | + InvalidOption { |
| 48 | + /// The invalid option the user passed. |
| 49 | + option: String, |
| 50 | + }, |
| 51 | +} |
| 52 | + |
| 53 | +impl Display for ConfigError { |
| 54 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 55 | + match self { |
| 56 | + Self::LoadVariable { variable } => { |
| 57 | + write!(f, "Failed to load environment variable '{variable}'") |
| 58 | + } |
| 59 | + Self::InvalidOption { option } => write!(f, "Invalid option '{option}'"), |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | +impl Context for ConfigError {} |
| 64 | + |
| 65 | +impl Config { |
| 66 | + /// Reads configuration values from environment and arguments passed to the application. |
| 67 | + /// |
| 68 | + /// # Errors |
| 69 | + /// - If unable to load a section of the config. |
| 70 | + pub fn read_from_env() -> Result<Self, ConfigError> { |
| 71 | + dotenvy::dotenv().ok(); |
| 72 | + let args = env::args().skip(1).collect::<Vec<_>>(); |
| 73 | + |
| 74 | + Ok(Self { |
| 75 | + application: ApplicationConfig::read_from_env(&args) |
| 76 | + .attach_printable("When loading application configuration")?, |
| 77 | + database: DatabaseConfig::read_from_env(&args) |
| 78 | + .attach_printable("When loading database configuration")?, |
| 79 | + }) |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +impl ApplicationConfig { |
| 84 | + /// Reads the application configuration from environment variables passed |
| 85 | + /// as the primary argument. |
| 86 | + /// |
| 87 | + /// # Errors |
| 88 | + /// Errors if the user provides an invalid `--supermarket` option. |
| 89 | + fn read_from_env(args: &[String]) -> Result<Self, ConfigError> { |
| 90 | + let supermarket = |
| 91 | + get_supermarket_type(args).change_context(ConfigError::InvalidOption { |
| 92 | + option: "--supermarket".to_string(), |
| 93 | + })?; |
| 94 | + |
| 95 | + Ok(Self { supermarket }) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +fn load_env<U>(variable: U) -> Result<String, ConfigError> |
| 100 | +where |
| 101 | + U: AsRef<OsStr> + Into<String> + Clone, |
| 102 | +{ |
| 103 | + env::var(variable.clone()).change_context(ConfigError::LoadVariable { |
| 104 | + variable: variable.into(), |
| 105 | + }) |
| 106 | +} |
| 107 | + |
| 108 | +impl DatabaseConfig { |
| 109 | + /// Reads the database configuration from environment variables passed as |
| 110 | + /// the primary argument. |
| 111 | + fn read_from_env(args: &[String]) -> Result<Self, ConfigError> { |
| 112 | + let user = load_env("DATABASE_USER")?; |
| 113 | + let password = load_env("DATABASE_PASSWORD").map(Secret::new)?; |
| 114 | + let host = load_env("DATABASE_HOST")?; |
| 115 | + let name = load_env("DATABASE_NAME")?; |
| 116 | + |
| 117 | + let hashed_args = args.iter().collect::<HashSet<_>>(); |
| 118 | + let no_insert = hashed_args.contains(&"--no-insert".to_string()); |
| 119 | + |
| 120 | + Ok(Self { |
| 121 | + should_insert: !no_insert, |
| 122 | + |
| 123 | + username: user, |
| 124 | + password, |
| 125 | + host, |
| 126 | + name, |
| 127 | + }) |
| 128 | + } |
| 129 | + |
| 130 | + /// Generates the Postgres connection string to use to connect to the |
| 131 | + /// database. |
| 132 | + /// |
| 133 | + /// Because this string contains the database password, it is wrapped with |
| 134 | + /// the [`Secret`] type. |
| 135 | + pub fn connection_string(&self) -> PgConnectOptions { |
| 136 | + PgConnectOptions::new() |
| 137 | + .application_name("supermarket-tracker") |
| 138 | + .database(&self.name) |
| 139 | + .host(&self.host) |
| 140 | + .password(self.password.expose_secret()) |
| 141 | + .username(&self.username) |
| 142 | + } |
| 143 | +} |
0 commit comments