diff options
Diffstat (limited to 'lib/warden-core/src/state')
| -rw-r--r-- | lib/warden-core/src/state/database.rs | 16 | ||||
| -rw-r--r-- | lib/warden-core/src/state/mod.rs | 24 |
2 files changed, 40 insertions, 0 deletions
diff --git a/lib/warden-core/src/state/database.rs b/lib/warden-core/src/state/database.rs new file mode 100644 index 0000000..cf34484 --- /dev/null +++ b/lib/warden-core/src/state/database.rs @@ -0,0 +1,16 @@ +use sqlx::PgPool; +use tracing::{debug, error}; + +use crate::{WardenError, config::cli::database::Database}; + +pub async fn connect(config: &Database) -> Result<PgPool, WardenError> { + let url = config.get_url()?; + let host = url.host_str(); + debug!(host = host, "connecting to database"); + + Ok(sqlx::postgres::PgPoolOptions::new() + .max_connections(config.database_pool_size.unwrap_or(10)) + .connect(url.as_str()) + .await + .inspect_err(|e| error!("{e}"))?) +} diff --git a/lib/warden-core/src/state/mod.rs b/lib/warden-core/src/state/mod.rs new file mode 100644 index 0000000..f4692c2 --- /dev/null +++ b/lib/warden-core/src/state/mod.rs @@ -0,0 +1,24 @@ +pub(crate) mod database; +use sqlx::PgPool; +use tracing_subscriber::EnvFilter; + +use crate::{WardenError, config::Configuration}; + +pub type LogHandle = tracing_subscriber::reload::Handle<EnvFilter, tracing_subscriber::Registry>; + +#[derive(Debug, Clone)] +pub struct AppState { + pub log_handle: LogHandle, + pub database: PgPool, +} + +impl AppState { + pub async fn new(log_handle: LogHandle, config: &Configuration) -> Result<Self, WardenError> { + let database = database::connect(&config.database).await?; + + Ok(Self { + log_handle, + database, + }) + } +} |
