use std::{fmt, time::Duration};
use serde::{Deserialize, Serialize};
use crate::{
secret::{ExposeSecret, SecretString},
settings::{SettingsIssues, SettingsValidationError},
};
use super::runtime::{advisory_lock_key, database_name};
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct PostgresPoolConfig {
pub(super) max_connections: u32,
pub(super) min_connections: u32,
pub(super) acquire_timeout: Duration,
pub(super) idle_timeout: Option<Duration>,
pub(super) max_lifetime: Option<Duration>,
pub(super) test_before_acquire: bool,
}
impl Default for PostgresPoolConfig {
fn default() -> Self {
Self {
max_connections: 10,
min_connections: 0,
acquire_timeout: Duration::from_secs(5),
idle_timeout: Some(Duration::from_secs(10 * 60)),
max_lifetime: Some(Duration::from_secs(30 * 60)),
test_before_acquire: true,
}
}
}
impl PostgresPoolConfig {
#[must_use]
pub const fn max_connections(&self) -> u32 {
self.max_connections
}
#[must_use]
pub const fn min_connections(&self) -> u32 {
self.min_connections
}
#[must_use]
pub const fn acquire_timeout(&self) -> Duration {
self.acquire_timeout
}
#[must_use]
pub const fn idle_timeout(&self) -> Option<Duration> {
self.idle_timeout
}
#[must_use]
pub const fn max_lifetime(&self) -> Option<Duration> {
self.max_lifetime
}
#[must_use]
pub const fn test_before_acquire(&self) -> bool {
self.test_before_acquire
}
}
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PostgresPoolSettings {
#[serde(default = "default_max_connections")]
pub max_connections: u32,
#[serde(default)]
pub min_connections: u32,
#[serde(
default = "default_acquire_timeout",
with = "crate::settings::human_duration"
)]
pub acquire_timeout: Duration,
#[serde(
default = "default_idle_timeout",
with = "crate::settings::human_duration::option"
)]
pub idle_timeout: Option<Duration>,
#[serde(
default = "default_max_lifetime",
with = "crate::settings::human_duration::option"
)]
pub max_lifetime: Option<Duration>,
#[serde(default = "default_true")]
pub test_before_acquire: bool,
}
impl Default for PostgresPoolSettings {
fn default() -> Self {
Self::from(PostgresPoolConfig::default())
}
}
impl From<PostgresPoolConfig> for PostgresPoolSettings {
fn from(value: PostgresPoolConfig) -> Self {
Self {
max_connections: value.max_connections,
min_connections: value.min_connections,
acquire_timeout: value.acquire_timeout,
idle_timeout: value.idle_timeout,
max_lifetime: value.max_lifetime,
test_before_acquire: value.test_before_acquire,
}
}
}
impl PostgresPoolSettings {
#[must_use]
pub const fn with_max_connections(mut self, max_connections: u32) -> Self {
self.max_connections = max_connections;
self
}
#[must_use]
pub const fn with_min_connections(mut self, min_connections: u32) -> Self {
self.min_connections = min_connections;
self
}
#[must_use]
pub const fn with_acquire_timeout(mut self, acquire_timeout: Duration) -> Self {
self.acquire_timeout = acquire_timeout;
self
}
#[must_use]
pub const fn with_idle_timeout(mut self, idle_timeout: Option<Duration>) -> Self {
self.idle_timeout = idle_timeout;
self
}
#[must_use]
pub const fn with_max_lifetime(mut self, max_lifetime: Option<Duration>) -> Self {
self.max_lifetime = max_lifetime;
self
}
#[must_use]
pub const fn with_test_before_acquire(mut self, test_before_acquire: bool) -> Self {
self.test_before_acquire = test_before_acquire;
self
}
pub fn build(self) -> Result<PostgresPoolConfig, SettingsValidationError> {
self.validate()?;
Ok(PostgresPoolConfig {
max_connections: self.max_connections,
min_connections: self.min_connections,
acquire_timeout: self.acquire_timeout,
idle_timeout: self.idle_timeout,
max_lifetime: self.max_lifetime,
test_before_acquire: self.test_before_acquire,
})
}
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("postgres.pool")
}
pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
issues.require(
self.max_connections > 0,
format!("{path}.max_connections"),
"must be greater than zero",
);
issues.require(
!self.acquire_timeout.is_zero(),
format!("{path}.acquire_timeout"),
"must be greater than zero",
);
issues.require(
self.min_connections <= self.max_connections,
format!("{path}.min_connections"),
"must be less than or equal to max_connections",
);
issues.into_result()
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct PostgresBootstrapConfig {
pub(super) database_url: SecretString,
pub(super) pool_config: PostgresPoolConfig,
pub(super) create_on_startup: bool,
pub(super) migrate_on_startup: bool,
pub(super) startup_retry: PostgresStartupRetryConfig,
pub(super) migration_lock_key: Option<i64>,
}
impl fmt::Debug for PostgresBootstrapConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PostgresBootstrapConfig")
.field("database_url", &"[REDACTED]")
.field("pool_config", &self.pool_config)
.field("create_on_startup", &self.create_on_startup)
.field("migrate_on_startup", &self.migrate_on_startup)
.field("startup_retry", &self.startup_retry)
.field("migration_lock_key", &self.migration_lock_key)
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PostgresStartupRetryConfig {
pub(super) max_attempts: u32,
pub(super) initial_delay: Duration,
pub(super) max_delay: Duration,
}
impl Default for PostgresStartupRetryConfig {
fn default() -> Self {
Self {
max_attempts: 1,
initial_delay: Duration::from_millis(250),
max_delay: Duration::from_secs(5),
}
}
}
impl PostgresStartupRetryConfig {
#[must_use]
pub const fn disabled() -> Self {
Self {
max_attempts: 1,
initial_delay: Duration::from_millis(250),
max_delay: Duration::from_secs(5),
}
}
#[must_use]
pub const fn max_attempts(&self) -> u32 {
self.max_attempts
}
#[must_use]
pub const fn initial_delay(&self) -> Duration {
self.initial_delay
}
#[must_use]
pub const fn max_delay(&self) -> Duration {
self.max_delay
}
}
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PostgresBootstrapSettings<S = SecretString> {
#[cfg_attr(feature = "tier", tier(secret, leaf))]
pub database_url: S,
#[serde(default)]
pub pool: PostgresPoolSettings,
#[serde(default)]
pub create_on_startup: bool,
#[serde(default = "default_true")]
pub migrate_on_startup: bool,
#[serde(default)]
pub startup_retry: PostgresStartupRetrySettings,
#[serde(default = "default_migration_lock_key")]
pub migration_lock_key: Option<i64>,
}
impl<S> fmt::Debug for PostgresBootstrapSettings<S> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PostgresBootstrapSettings")
.field("database_url", &"[REDACTED]")
.field("pool", &self.pool)
.field("create_on_startup", &self.create_on_startup)
.field("migrate_on_startup", &self.migrate_on_startup)
.field("startup_retry", &self.startup_retry)
.field("migration_lock_key", &self.migration_lock_key)
.finish()
}
}
impl<S> PostgresBootstrapSettings<S> {
#[must_use]
pub fn from_secret(database_url: S) -> Self {
Self {
database_url,
pool: PostgresPoolSettings::default(),
create_on_startup: false,
migrate_on_startup: true,
startup_retry: PostgresStartupRetrySettings::default(),
migration_lock_key: default_migration_lock_key(),
}
}
#[must_use]
pub fn map_database_url<T>(self, map: impl FnOnce(S) -> T) -> PostgresBootstrapSettings<T> {
PostgresBootstrapSettings {
database_url: map(self.database_url),
pool: self.pool,
create_on_startup: self.create_on_startup,
migrate_on_startup: self.migrate_on_startup,
startup_retry: self.startup_retry,
migration_lock_key: self.migration_lock_key,
}
}
#[must_use]
pub fn with_pool(mut self, pool: PostgresPoolSettings) -> Self {
self.pool = pool;
self
}
#[must_use]
pub const fn with_create_on_startup(mut self, create_on_startup: bool) -> Self {
self.create_on_startup = create_on_startup;
self
}
#[must_use]
pub const fn with_migrate_on_startup(mut self, migrate_on_startup: bool) -> Self {
self.migrate_on_startup = migrate_on_startup;
self
}
#[must_use]
pub const fn with_startup_retry(mut self, startup_retry: PostgresStartupRetrySettings) -> Self {
self.startup_retry = startup_retry;
self
}
#[must_use]
pub const fn with_migration_advisory_lock(mut self, key: Option<i64>) -> Self {
self.migration_lock_key = key;
self
}
}
impl<S> PostgresBootstrapSettings<S>
where
S: ExposeSecret<str>,
{
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("postgres")
}
pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
let database_url = self.database_url.expose_secret();
issues.require_non_empty(format!("{path}.database_url"), database_url);
if !database_url.trim().is_empty() {
issues.require(
database_name(database_url).is_some(),
format!("{path}.database_url"),
"must be a valid PostgreSQL URL containing a database name",
);
}
issues.extend_result(self.pool.validate_at(&format!("{path}.pool")));
issues.extend_result(
self.startup_retry
.validate_at(&format!("{path}.startup_retry")),
);
issues.into_result()
}
}
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PostgresStartupRetrySettings {
#[serde(default = "default_startup_retry_attempts")]
pub max_attempts: u32,
#[serde(
default = "default_startup_retry_initial_delay",
with = "crate::settings::human_duration"
)]
pub initial_delay: Duration,
#[serde(
default = "default_startup_retry_max_delay",
with = "crate::settings::human_duration"
)]
pub max_delay: Duration,
}
impl Default for PostgresStartupRetrySettings {
fn default() -> Self {
Self::from(PostgresStartupRetryConfig::default())
}
}
impl From<PostgresStartupRetryConfig> for PostgresStartupRetrySettings {
fn from(value: PostgresStartupRetryConfig) -> Self {
Self {
max_attempts: value.max_attempts,
initial_delay: value.initial_delay,
max_delay: value.max_delay,
}
}
}
impl PostgresStartupRetrySettings {
#[must_use]
pub const fn with_max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = max_attempts;
self
}
#[must_use]
pub const fn with_initial_delay(mut self, initial_delay: Duration) -> Self {
self.initial_delay = initial_delay;
self
}
#[must_use]
pub const fn with_max_delay(mut self, max_delay: Duration) -> Self {
self.max_delay = max_delay;
self
}
pub fn build(self) -> Result<PostgresStartupRetryConfig, SettingsValidationError> {
self.validate()?;
Ok(PostgresStartupRetryConfig {
max_attempts: self.max_attempts,
initial_delay: self.initial_delay,
max_delay: self.max_delay,
})
}
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("postgres.startup_retry")
}
pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
issues.require(
self.max_attempts > 0,
format!("{path}.max_attempts"),
"must be greater than zero",
);
issues.require(
self.max_attempts <= 1 || !self.initial_delay.is_zero(),
format!("{path}.initial_delay"),
"must be greater than zero when max_attempts is greater than one",
);
issues.require(
self.max_delay >= self.initial_delay,
format!("{path}.max_delay"),
"must be greater than or equal to initial_delay",
);
issues.into_result()
}
}
impl PostgresBootstrapSettings {
#[must_use]
pub fn new(database_url: impl Into<String>) -> Self {
Self::from_secret(SecretString::new(database_url))
}
#[must_use]
pub fn with_database_url(mut self, database_url: impl Into<String>) -> Self {
self.database_url = SecretString::new(database_url);
self
}
pub fn build(self) -> Result<PostgresBootstrapConfig, SettingsValidationError> {
self.validate()?;
Ok(PostgresBootstrapConfig {
database_url: self.database_url,
pool_config: PostgresPoolConfig {
max_connections: self.pool.max_connections,
min_connections: self.pool.min_connections,
acquire_timeout: self.pool.acquire_timeout,
idle_timeout: self.pool.idle_timeout,
max_lifetime: self.pool.max_lifetime,
test_before_acquire: self.pool.test_before_acquire,
},
create_on_startup: self.create_on_startup,
migrate_on_startup: self.migrate_on_startup,
startup_retry: PostgresStartupRetryConfig {
max_attempts: self.startup_retry.max_attempts,
initial_delay: self.startup_retry.initial_delay,
max_delay: self.startup_retry.max_delay,
},
migration_lock_key: self.migration_lock_key,
})
}
}
impl From<PostgresBootstrapConfig> for PostgresBootstrapSettings {
fn from(value: PostgresBootstrapConfig) -> Self {
Self {
database_url: value.database_url,
pool: PostgresPoolSettings::from(value.pool_config),
create_on_startup: value.create_on_startup,
migrate_on_startup: value.migrate_on_startup,
startup_retry: PostgresStartupRetrySettings::from(value.startup_retry),
migration_lock_key: value.migration_lock_key,
}
}
}
impl PostgresBootstrapConfig {
#[must_use]
pub const fn database_url(&self) -> &SecretString {
&self.database_url
}
#[must_use]
pub const fn pool_config(&self) -> PostgresPoolConfig {
self.pool_config
}
#[must_use]
pub const fn create_on_startup(&self) -> bool {
self.create_on_startup
}
#[must_use]
pub const fn migrate_on_startup(&self) -> bool {
self.migrate_on_startup
}
#[must_use]
pub const fn startup_retry(&self) -> PostgresStartupRetryConfig {
self.startup_retry
}
#[must_use]
pub const fn migration_lock_key(&self) -> Option<i64> {
self.migration_lock_key
}
}
fn default_max_connections() -> u32 {
PostgresPoolConfig::default().max_connections
}
fn default_acquire_timeout() -> Duration {
PostgresPoolConfig::default().acquire_timeout
}
fn default_idle_timeout() -> Option<Duration> {
PostgresPoolConfig::default().idle_timeout
}
fn default_max_lifetime() -> Option<Duration> {
PostgresPoolConfig::default().max_lifetime
}
fn default_true() -> bool {
true
}
fn default_startup_retry_attempts() -> u32 {
PostgresStartupRetryConfig::default().max_attempts
}
fn default_startup_retry_initial_delay() -> Duration {
PostgresStartupRetryConfig::default().initial_delay
}
fn default_startup_retry_max_delay() -> Duration {
PostgresStartupRetryConfig::default().max_delay
}
fn default_migration_lock_key() -> Option<i64> {
Some(advisory_lock_key("footing", "migrations"))
}