90 lines
2.7 KiB
Rust
90 lines
2.7 KiB
Rust
use thiserror::Error;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct PostgresPoolConfig {
|
|
pub max_connections: u32,
|
|
pub min_connections: u32,
|
|
pub acquire_timeout_ms: u64,
|
|
pub idle_timeout_ms: u64,
|
|
pub max_lifetime_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Error, PartialEq, Eq)]
|
|
pub enum PostgresPoolConfigError {
|
|
#[error("postgres pool setting is outside its allowed bounds: {field}")]
|
|
OutOfRange { field: &'static str },
|
|
#[error("minimum connections must not exceed maximum connections")]
|
|
MinConnectionsExceedMax,
|
|
}
|
|
|
|
impl Default for PostgresPoolConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
max_connections: 20,
|
|
min_connections: 2,
|
|
acquire_timeout_ms: 5_000,
|
|
idle_timeout_ms: 600_000,
|
|
max_lifetime_ms: 1_800_000,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl PostgresPoolConfig {
|
|
pub fn try_new(
|
|
max_connections: u32,
|
|
min_connections: u32,
|
|
acquire_timeout_ms: u64,
|
|
idle_timeout_ms: u64,
|
|
max_lifetime_ms: u64,
|
|
) -> Result<Self, PostgresPoolConfigError> {
|
|
for (field, value, minimum, maximum) in [
|
|
("max_connections", u64::from(max_connections), 1, 1024),
|
|
("min_connections", u64::from(min_connections), 0, 1024),
|
|
("acquire_timeout_ms", acquire_timeout_ms, 1, 300_000),
|
|
("idle_timeout_ms", idle_timeout_ms, 1_000, 86_400_000),
|
|
("max_lifetime_ms", max_lifetime_ms, 1_000, 86_400_000),
|
|
] {
|
|
if !(minimum..=maximum).contains(&value) {
|
|
return Err(PostgresPoolConfigError::OutOfRange { field });
|
|
}
|
|
}
|
|
if min_connections > max_connections {
|
|
return Err(PostgresPoolConfigError::MinConnectionsExceedMax);
|
|
}
|
|
Ok(Self {
|
|
max_connections,
|
|
min_connections,
|
|
acquire_timeout_ms,
|
|
idle_timeout_ms,
|
|
max_lifetime_ms,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{PostgresPoolConfig, PostgresPoolConfigError};
|
|
|
|
#[test]
|
|
fn explicit_defaults_remain_valid() {
|
|
assert_eq!(
|
|
PostgresPoolConfig::try_new(20, 2, 5_000, 600_000, 1_800_000).unwrap(),
|
|
PostgresPoolConfig::default()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_invalid_bounds_and_cross_fields() {
|
|
assert_eq!(
|
|
PostgresPoolConfig::try_new(0, 0, 5_000, 600_000, 1_800_000).unwrap_err(),
|
|
PostgresPoolConfigError::OutOfRange {
|
|
field: "max_connections"
|
|
}
|
|
);
|
|
assert_eq!(
|
|
PostgresPoolConfig::try_new(2, 3, 5_000, 600_000, 1_800_000).unwrap_err(),
|
|
PostgresPoolConfigError::MinConnectionsExceedMax
|
|
);
|
|
}
|
|
}
|