use std::{
fmt,
time::{Duration, Instant},
};
use serde::{Deserialize, Serialize};
use crate::{
secret::{ExposeSecret, SecretString},
settings::{SettingsIssues, SettingsValidationError, field_path},
};
use super::{PostgresConnectionConfig, PostgresConnectionSettings, identity::database_name};
pub const DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_POSTGRES_MIGRATION_TIMEOUT: Duration = Duration::from_secs(5 * 60);
pub const DEFAULT_POSTGRES_ENSURE_DATABASE_TIMEOUT: Duration = Duration::from_secs(30);
#[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(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct PostgresPoolSettings {
pub max_connections: u32,
pub min_connections: u32,
#[serde(with = "crate::settings::human_duration")]
pub acquire_timeout: Duration,
#[serde(with = "crate::settings::human_duration::option")]
pub idle_timeout: Option<Duration>,
#[serde(with = "crate::settings::human_duration::option")]
pub max_lifetime: Option<Duration>,
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(self.into_config())
}
pub(super) fn into_config(self) -> PostgresPoolConfig {
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 fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
issues.require(
self.max_connections > 0,
field_path(path, "max_connections"),
"must be greater than zero",
);
issues.require(
!self.acquire_timeout.is_zero()
&& Instant::now().checked_add(self.acquire_timeout).is_some(),
field_path(path, "acquire_timeout"),
"must be greater than zero and fit the runtime timer range",
);
issues.require(
self.min_connections <= self.max_connections,
field_path(path, "min_connections"),
"must be less than or equal to max_connections",
);
for (field, timeout) in [
("idle_timeout", self.idle_timeout),
("max_lifetime", self.max_lifetime),
] {
issues.require(
timeout.is_none_or(|timeout| {
!timeout.is_zero() && Instant::now().checked_add(timeout).is_some()
}),
field_path(path, field),
"must be omitted or greater than zero and fit the runtime timer range",
);
}
issues.into_result()
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct PostgresBootstrapConfig {
pub(super) connection: PostgresConnectionConfig,
pub(super) pool_config: PostgresPoolConfig,
pub(super) create_on_startup: bool,
pub(super) ensure_database_timeout: Duration,
pub(super) migrate_on_startup: bool,
pub(super) startup_retry: PostgresStartupRetryConfig,
pub(super) migration_lock_key: Option<i64>,
pub(super) migration_lock_timeout: Duration,
pub(super) migration_timeout: Duration,
}
impl fmt::Debug for PostgresBootstrapConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PostgresBootstrapConfig")
.field("connection", &self.connection)
.field("pool_config", &self.pool_config)
.field("create_on_startup", &self.create_on_startup)
.field("ensure_database_timeout", &self.ensure_database_timeout)
.field("migrate_on_startup", &self.migrate_on_startup)
.field("startup_retry", &self.startup_retry)
.field("migration_lock_key", &self.migration_lock_key)
.field("migration_lock_timeout", &self.migration_lock_timeout)
.field("migration_timeout", &self.migration_timeout)
.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,
pub(super) jitter: bool,
}
impl Default for PostgresStartupRetryConfig {
fn default() -> Self {
Self::disabled()
}
}
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),
jitter: false,
}
}
#[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
}
#[must_use]
pub const fn jitter(&self) -> bool {
self.jitter
}
}
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PostgresBootstrapSettings<S = SecretString> {
pub connection: PostgresConnectionSettings<S>,
#[serde(default)]
pub pool: PostgresPoolSettings,
#[serde(default)]
pub create_on_startup: bool,
#[serde(
default = "default_ensure_database_timeout",
with = "crate::settings::human_duration"
)]
pub ensure_database_timeout: Duration,
#[serde(default = "default_true")]
pub migrate_on_startup: bool,
#[serde(default)]
pub startup_retry: PostgresStartupRetrySettings,
#[serde(default)]
pub migration_lock_key: Option<i64>,
#[serde(
default = "default_migration_lock_timeout",
with = "crate::settings::human_duration"
)]
pub migration_lock_timeout: Duration,
#[serde(
default = "default_migration_timeout",
with = "crate::settings::human_duration"
)]
pub migration_timeout: Duration,
}
impl<S> fmt::Debug for PostgresBootstrapSettings<S> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PostgresBootstrapSettings")
.field("connection", &self.connection)
.field("pool", &self.pool)
.field("create_on_startup", &self.create_on_startup)
.field("ensure_database_timeout", &self.ensure_database_timeout)
.field("migrate_on_startup", &self.migrate_on_startup)
.field("startup_retry", &self.startup_retry)
.field("migration_lock_key", &self.migration_lock_key)
.field("migration_lock_timeout", &self.migration_lock_timeout)
.field("migration_timeout", &self.migration_timeout)
.finish()
}
}
impl<S> PostgresBootstrapSettings<S> {
#[must_use]
pub fn from_secret(database_url: S) -> Self {
Self {
connection: PostgresConnectionSettings::from_secret(database_url),
pool: PostgresPoolSettings::default(),
create_on_startup: false,
ensure_database_timeout: default_ensure_database_timeout(),
migrate_on_startup: true,
startup_retry: PostgresStartupRetrySettings::default(),
migration_lock_key: None,
migration_lock_timeout: default_migration_lock_timeout(),
migration_timeout: default_migration_timeout(),
}
}
#[must_use]
pub fn map_database_url<T>(self, map: impl FnOnce(S) -> T) -> PostgresBootstrapSettings<T> {
PostgresBootstrapSettings {
connection: self.connection.map_database_url(map),
pool: self.pool,
create_on_startup: self.create_on_startup,
ensure_database_timeout: self.ensure_database_timeout,
migrate_on_startup: self.migrate_on_startup,
startup_retry: self.startup_retry,
migration_lock_key: self.migration_lock_key,
migration_lock_timeout: self.migration_lock_timeout,
migration_timeout: self.migration_timeout,
}
}
#[must_use]
pub fn with_connection(mut self, connection: PostgresConnectionSettings<S>) -> Self {
self.connection = connection;
self
}
#[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_ensure_database_timeout(mut self, timeout: Duration) -> Self {
self.ensure_database_timeout = timeout;
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_additional_migration_advisory_lock(mut self, key: Option<i64>) -> Self {
self.migration_lock_key = key;
self
}
#[must_use]
pub const fn with_migration_lock_timeout(mut self, timeout: Duration) -> Self {
self.migration_lock_timeout = timeout;
self
}
#[must_use]
pub const fn with_migration_timeout(mut self, timeout: Duration) -> Self {
self.migration_timeout = timeout;
self
}
pub fn build(self) -> Result<PostgresBootstrapConfig, SettingsValidationError>
where
S: Into<SecretString>,
{
let settings: PostgresBootstrapSettings = self.map_database_url(Into::into);
settings.validate()?;
Ok(PostgresBootstrapConfig {
connection: settings.connection.into_config(),
pool_config: settings.pool.into_config(),
create_on_startup: settings.create_on_startup,
ensure_database_timeout: settings.ensure_database_timeout,
migrate_on_startup: settings.migrate_on_startup,
startup_retry: settings.startup_retry.into_config(),
migration_lock_key: settings.migration_lock_key,
migration_lock_timeout: settings.migration_lock_timeout,
migration_timeout: settings.migration_timeout,
})
}
}
impl<S> PostgresBootstrapSettings<S>
where
S: ExposeSecret<str>,
{
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("postgres")
}
pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
let connection_path = field_path(path, "connection");
let connection_validation = self.connection.validate_at(&connection_path);
if connection_validation.is_ok() {
issues.require(
database_name(self.connection.database_url.expose_secret()).is_some(),
field_path(&connection_path, "database_url"),
"must contain an explicit database name for bootstrap",
);
}
issues.extend_result(connection_validation);
issues.extend_result(self.pool.validate_at(&field_path(path, "pool")));
issues.extend_result(
self.startup_retry
.validate_at(&field_path(path, "startup_retry")),
);
for (field, timeout) in [
("ensure_database_timeout", self.ensure_database_timeout),
("migration_lock_timeout", self.migration_lock_timeout),
("migration_timeout", self.migration_timeout),
] {
issues.require(
!timeout.is_zero() && Instant::now().checked_add(timeout).is_some(),
field_path(path, field),
"must be greater than zero and fit the runtime timer range",
);
}
issues.into_result()
}
}
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct PostgresStartupRetrySettings {
pub max_attempts: u32,
#[serde(with = "crate::settings::human_duration")]
pub initial_delay: Duration,
#[serde(with = "crate::settings::human_duration")]
pub max_delay: Duration,
pub jitter: bool,
}
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,
jitter: value.jitter,
}
}
}
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
}
#[must_use]
pub const fn with_jitter(mut self, enabled: bool) -> Self {
self.jitter = enabled;
self
}
pub fn build(self) -> Result<PostgresStartupRetryConfig, SettingsValidationError> {
self.validate()?;
Ok(self.into_config())
}
fn into_config(self) -> PostgresStartupRetryConfig {
PostgresStartupRetryConfig {
max_attempts: self.max_attempts,
initial_delay: self.initial_delay,
max_delay: self.max_delay,
jitter: self.jitter,
}
}
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("postgres.startup_retry")
}
pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
issues.require(
self.max_attempts > 0,
field_path(path, "max_attempts"),
"must be greater than zero",
);
issues.require(
self.max_attempts <= 1 || !self.initial_delay.is_zero(),
field_path(path, "initial_delay"),
"must be greater than zero when max_attempts is greater than one",
);
issues.require(
self.max_delay >= self.initial_delay,
field_path(path, "max_delay"),
"must be greater than or equal to initial_delay",
);
issues.require(
Instant::now().checked_add(self.max_delay).is_some(),
field_path(path, "max_delay"),
"must fit the runtime timer range",
);
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.connection.database_url = SecretString::new(database_url);
self
}
}
impl From<PostgresBootstrapConfig> for PostgresBootstrapSettings {
fn from(value: PostgresBootstrapConfig) -> Self {
Self {
connection: value.connection.into(),
pool: PostgresPoolSettings::from(value.pool_config),
create_on_startup: value.create_on_startup,
ensure_database_timeout: value.ensure_database_timeout,
migrate_on_startup: value.migrate_on_startup,
startup_retry: PostgresStartupRetrySettings::from(value.startup_retry),
migration_lock_key: value.migration_lock_key,
migration_lock_timeout: value.migration_lock_timeout,
migration_timeout: value.migration_timeout,
}
}
}
impl PostgresBootstrapConfig {
#[must_use]
pub const fn database_url(&self) -> &SecretString {
self.connection.database_url()
}
#[must_use]
pub const fn connection_config(&self) -> &PostgresConnectionConfig {
&self.connection
}
#[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 ensure_database_timeout(&self) -> Duration {
self.ensure_database_timeout
}
#[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
}
#[must_use]
pub const fn migration_lock_timeout(&self) -> Duration {
self.migration_lock_timeout
}
#[must_use]
pub const fn migration_timeout(&self) -> Duration {
self.migration_timeout
}
}
fn default_true() -> bool {
true
}
fn default_migration_lock_timeout() -> Duration {
DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT
}
fn default_migration_timeout() -> Duration {
DEFAULT_POSTGRES_MIGRATION_TIMEOUT
}
pub(super) fn default_ensure_database_timeout() -> Duration {
DEFAULT_POSTGRES_ENSURE_DATABASE_TIMEOUT
}