1use std::{env, fmt, str::FromStr, time::Duration};
5
6use sqlx_postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};
7
8use crate::ConfigurationError;
9
10const MAX_POSTGRES_TIMEOUT_MILLISECONDS: u128 = i32::MAX as u128;
11
12pub const DATABASE_URL_ENV: &str = "DATABASE_URL";
14pub const MIGRATION_DATABASE_URL_ENV: &str = "STATEKNOT_MIGRATION_DATABASE_URL";
17pub const DEV_MODE_ENV: &str = "STATEKNOT_DEV_MODE";
19pub const AUTO_MIGRATE_ENV: &str = "STATEKNOT_AUTO_MIGRATE";
21
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24#[non_exhaustive]
25pub enum PostgresConfigurationProfile {
26 #[default]
28 Production,
29 Development,
31}
32
33#[derive(Clone)]
40pub struct PostgresStoreConfig {
41 runtime_database_url: Box<str>,
42 migration_database_url: Option<Box<str>>,
43 options: PostgresStoreOptions,
44 auto_migrate: bool,
45 profile: PostgresConfigurationProfile,
46}
47
48impl PostgresStoreConfig {
49 #[must_use]
51 pub fn builder(database_url: impl Into<String>) -> PostgresStoreConfigBuilder {
52 PostgresStoreConfigBuilder::new(database_url)
53 }
54
55 pub fn development(database_url: impl Into<String>) -> Result<Self, ConfigurationError> {
67 PostgresStoreConfigBuilder::new(database_url)
68 .with_development_defaults()
69 .build()
70 }
71
72 pub fn from_env() -> Result<Self, ConfigurationError> {
87 Self::from_environment(|name| match env::var(name) {
88 Ok(value) => Ok(Some(value)),
89 Err(env::VarError::NotPresent) => Ok(None),
90 Err(env::VarError::NotUnicode(_)) => Err(()),
91 })
92 }
93
94 fn from_environment(
95 mut read: impl FnMut(&str) -> Result<Option<String>, ()>,
96 ) -> Result<Self, ConfigurationError> {
97 let database_url = required_environment_value(&mut read, DATABASE_URL_ENV)?;
98 let development = optional_environment_bool(&mut read, DEV_MODE_ENV)?.unwrap_or(false);
99 let configured_auto_migrate = optional_environment_bool(&mut read, AUTO_MIGRATE_ENV)?;
100 let migration_database_url = read(MIGRATION_DATABASE_URL_ENV)
101 .map_err(|()| ConfigurationError::InvalidEnvironmentVariable {
102 name: MIGRATION_DATABASE_URL_ENV,
103 })?
104 .filter(|value| !value.is_empty());
105
106 let mut builder = Self::builder(database_url);
107 if development {
108 builder = builder.with_development_defaults();
109 }
110 if let Some(auto_migrate) = configured_auto_migrate {
111 builder = builder.with_auto_migrate(auto_migrate);
112 }
113 if let Some(migration_database_url) = migration_database_url {
114 builder = builder.with_migration_database_url(migration_database_url);
115 }
116 builder.build()
117 }
118
119 #[must_use]
121 pub const fn options(&self) -> &PostgresStoreOptions {
122 &self.options
123 }
124
125 #[must_use]
128 pub const fn auto_migrate(&self) -> bool {
129 self.auto_migrate
130 }
131
132 #[must_use]
134 pub const fn profile(&self) -> PostgresConfigurationProfile {
135 self.profile
136 }
137
138 pub(crate) fn into_parts(self) -> (Box<str>, Option<Box<str>>, PostgresStoreOptions, bool) {
139 (
140 self.runtime_database_url,
141 self.migration_database_url,
142 self.options,
143 self.auto_migrate,
144 )
145 }
146}
147
148impl fmt::Debug for PostgresStoreConfig {
149 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150 formatter
151 .debug_struct("PostgresStoreConfig")
152 .field("runtime_database_url", &"[REDACTED]")
153 .field(
154 "migration_database_url",
155 &self.migration_database_url.as_ref().map(|_| "[REDACTED]"),
156 )
157 .field("options", &self.options)
158 .field("auto_migrate", &self.auto_migrate)
159 .field("profile", &self.profile)
160 .finish()
161 }
162}
163
164pub struct PostgresStoreConfigBuilder {
166 runtime_database_url: String,
167 migration_database_url: Option<String>,
168 options: PostgresStoreOptions,
169 auto_migrate: bool,
170 profile: PostgresConfigurationProfile,
171}
172
173impl PostgresStoreConfigBuilder {
174 fn new(database_url: impl Into<String>) -> Self {
175 Self {
176 runtime_database_url: database_url.into(),
177 migration_database_url: None,
178 options: PostgresStoreOptions::default(),
179 auto_migrate: false,
180 profile: PostgresConfigurationProfile::Production,
181 }
182 }
183
184 #[must_use]
186 pub fn with_options(mut self, options: PostgresStoreOptions) -> Self {
187 self.options = options;
188 self
189 }
190
191 #[must_use]
193 pub fn with_migration_database_url(mut self, database_url: impl Into<String>) -> Self {
194 self.migration_database_url = Some(database_url.into());
195 self
196 }
197
198 #[must_use]
200 pub const fn with_auto_migrate(mut self, enabled: bool) -> Self {
201 self.auto_migrate = enabled;
202 self
203 }
204
205 #[must_use]
212 pub fn with_development_defaults(mut self) -> Self {
213 self.profile = PostgresConfigurationProfile::Development;
214 self.options = PostgresStoreOptions::default()
215 .with_transport_security(PostgresTransportSecurity::Disabled)
216 .with_pool_size(1, 4);
217 self.auto_migrate = true;
218 self
219 }
220
221 pub fn build(self) -> Result<PostgresStoreConfig, ConfigurationError> {
228 if self.runtime_database_url.is_empty() {
229 return Err(ConfigurationError::EmptyDatabaseUrl);
230 }
231 self.options.connect_options(&self.runtime_database_url)?;
232
233 let migration_database_url = match self.migration_database_url {
234 Some(value) if value.is_empty() => return Err(ConfigurationError::EmptyDatabaseUrl),
235 Some(value) => {
236 self.options.connect_options(&value)?;
237 Some(value)
238 }
239 None => None,
240 };
241
242 let migration_database_url = if self.auto_migrate {
243 match (self.profile, migration_database_url) {
244 (PostgresConfigurationProfile::Development, None) => {
245 Some(self.runtime_database_url.clone())
246 }
247 (PostgresConfigurationProfile::Production, None) => {
248 return Err(ConfigurationError::MigrationDatabaseUrlRequired);
249 }
250 (PostgresConfigurationProfile::Production, Some(value))
251 if value == self.runtime_database_url =>
252 {
253 return Err(ConfigurationError::SharedProductionMigrationCredential);
254 }
255 (_, value) => value,
256 }
257 } else {
258 migration_database_url
259 };
260
261 Ok(PostgresStoreConfig {
262 runtime_database_url: self.runtime_database_url.into_boxed_str(),
263 migration_database_url: migration_database_url.map(String::into_boxed_str),
264 options: self.options,
265 auto_migrate: self.auto_migrate,
266 profile: self.profile,
267 })
268 }
269}
270
271impl fmt::Debug for PostgresStoreConfigBuilder {
272 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
273 formatter
274 .debug_struct("PostgresStoreConfigBuilder")
275 .field("runtime_database_url", &"[REDACTED]")
276 .field(
277 "migration_database_url",
278 &self.migration_database_url.as_ref().map(|_| "[REDACTED]"),
279 )
280 .field("options", &self.options)
281 .field("auto_migrate", &self.auto_migrate)
282 .field("profile", &self.profile)
283 .finish()
284 }
285}
286
287fn required_environment_value(
288 read: &mut impl FnMut(&str) -> Result<Option<String>, ()>,
289 name: &'static str,
290) -> Result<String, ConfigurationError> {
291 match read(name) {
292 Ok(Some(value)) if !value.is_empty() => Ok(value),
293 Ok(Some(_)) => Err(ConfigurationError::EmptyDatabaseUrl),
294 Ok(None) => Err(ConfigurationError::MissingEnvironmentVariable { name }),
295 Err(()) => Err(ConfigurationError::InvalidEnvironmentVariable { name }),
296 }
297}
298
299fn optional_environment_bool(
300 read: &mut impl FnMut(&str) -> Result<Option<String>, ()>,
301 name: &'static str,
302) -> Result<Option<bool>, ConfigurationError> {
303 let Some(value) =
304 read(name).map_err(|()| ConfigurationError::InvalidEnvironmentVariable { name })?
305 else {
306 return Ok(None);
307 };
308 if value.eq_ignore_ascii_case("true") {
309 Ok(Some(true))
310 } else if value.eq_ignore_ascii_case("false") {
311 Ok(Some(false))
312 } else {
313 Err(ConfigurationError::InvalidEnvironmentVariable { name })
314 }
315}
316
317#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
323#[non_exhaustive]
324pub enum PostgresTransportSecurity {
325 #[default]
327 VerifyFull,
328 RequireEncryption,
330 Disabled,
332}
333
334impl PostgresTransportSecurity {
335 const fn ssl_mode(self) -> PgSslMode {
336 match self {
337 Self::VerifyFull => PgSslMode::VerifyFull,
338 Self::RequireEncryption => PgSslMode::Require,
339 Self::Disabled => PgSslMode::Disable,
340 }
341 }
342}
343
344#[derive(Clone, Debug)]
346pub struct PostgresStoreOptions {
347 pub(crate) transport_security: PostgresTransportSecurity,
348 pub(crate) max_connections: u32,
349 pub(crate) min_connections: u32,
350 pub(crate) acquire_timeout: Duration,
351 pub(crate) idle_timeout: Option<Duration>,
352 pub(crate) max_lifetime: Option<Duration>,
353 pub(crate) lock_timeout: Duration,
354 pub(crate) statement_timeout: Duration,
355 pub(crate) lease_duration: Duration,
356 pub(crate) maximum_lease_horizon: Duration,
357 pub(crate) outbox_attempt_lease_duration: Duration,
358}
359
360impl PostgresStoreOptions {
361 #[must_use]
363 pub const fn transport_security(&self) -> PostgresTransportSecurity {
364 self.transport_security
365 }
366
367 #[must_use]
369 pub const fn lease_duration(&self) -> Duration {
370 self.lease_duration
371 }
372
373 #[must_use]
375 pub const fn maximum_lease_horizon(&self) -> Duration {
376 self.maximum_lease_horizon
377 }
378
379 #[must_use]
381 pub const fn with_transport_security(
382 mut self,
383 transport_security: PostgresTransportSecurity,
384 ) -> Self {
385 self.transport_security = transport_security;
386 self
387 }
388
389 #[must_use]
391 pub const fn with_pool_size(mut self, minimum: u32, maximum: u32) -> Self {
392 self.min_connections = minimum;
393 self.max_connections = maximum;
394 self
395 }
396
397 #[must_use]
399 pub const fn with_acquire_timeout(mut self, timeout: Duration) -> Self {
400 self.acquire_timeout = timeout;
401 self
402 }
403
404 #[must_use]
406 pub const fn with_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
407 self.idle_timeout = timeout;
408 self
409 }
410
411 #[must_use]
413 pub const fn with_max_lifetime(mut self, lifetime: Option<Duration>) -> Self {
414 self.max_lifetime = lifetime;
415 self
416 }
417
418 #[must_use]
420 pub const fn with_transaction_timeouts(
421 mut self,
422 lock_timeout: Duration,
423 statement_timeout: Duration,
424 ) -> Self {
425 self.lock_timeout = lock_timeout;
426 self.statement_timeout = statement_timeout;
427 self
428 }
429
430 #[must_use]
432 pub const fn with_lease_timing(
433 mut self,
434 lease_duration: Duration,
435 maximum_lease_horizon: Duration,
436 ) -> Self {
437 self.lease_duration = lease_duration;
438 self.maximum_lease_horizon = maximum_lease_horizon;
439 self
440 }
441
442 #[must_use]
448 pub const fn with_outbox_attempt_lease(mut self, lease_duration: Duration) -> Self {
449 self.outbox_attempt_lease_duration = lease_duration;
450 self
451 }
452
453 pub(crate) fn validate(&self) -> Result<(), ConfigurationError> {
454 if self.max_connections == 0 {
455 return Err(ConfigurationError::ZeroMaximumConnections);
456 }
457 if self.min_connections > self.max_connections {
458 return Err(ConfigurationError::PoolMinimumExceedsMaximum);
459 }
460 for (name, duration) in [
461 ("acquire timeout", self.acquire_timeout),
462 ("lock timeout", self.lock_timeout),
463 ("statement timeout", self.statement_timeout),
464 ("lease duration", self.lease_duration),
465 ("maximum lease horizon", self.maximum_lease_horizon),
466 (
467 "outbox attempt lease duration",
468 self.outbox_attempt_lease_duration,
469 ),
470 ] {
471 validate_nonzero_duration(name, duration)?;
472 }
473 validate_postgres_timeout("lock timeout", self.lock_timeout)?;
474 validate_postgres_timeout("statement timeout", self.statement_timeout)?;
475 if duration_millisecond_count(self.lock_timeout)
476 >= duration_millisecond_count(self.statement_timeout)
477 {
478 return Err(ConfigurationError::LockTimeoutNotBelowStatementTimeout);
479 }
480 validate_lease_timing("lease duration", self.lease_duration)?;
481 validate_lease_timing("maximum lease horizon", self.maximum_lease_horizon)?;
482 validate_lease_timing(
483 "outbox attempt lease duration",
484 self.outbox_attempt_lease_duration,
485 )?;
486 if self.lease_duration > self.maximum_lease_horizon {
487 return Err(ConfigurationError::LeaseDurationExceedsMaximumHorizon);
488 }
489 if self.outbox_attempt_lease_duration > Duration::from_secs(5 * 60) {
490 return Err(ConfigurationError::OutboxAttemptLeaseTooLong);
491 }
492 if let Some(duration) = self.idle_timeout {
493 validate_nonzero_duration("idle timeout", duration)?;
494 }
495 if let Some(duration) = self.max_lifetime {
496 validate_nonzero_duration("maximum connection lifetime", duration)?;
497 }
498 Ok(())
499 }
500
501 pub(crate) fn connect_options(
502 &self,
503 database_url: &str,
504 ) -> Result<PgConnectOptions, ConfigurationError> {
505 self.validate()?;
506 let options = PgConnectOptions::from_str(database_url)
507 .map_err(|_| ConfigurationError::InvalidDatabaseUrl)?
508 .ssl_mode(self.transport_security.ssl_mode())
509 .options([("search_path", "public,pg_catalog")])
510 .application_name("stateknot");
511 Ok(options)
512 }
513
514 pub(crate) fn pool_options(&self) -> PgPoolOptions {
515 let mut options = PgPoolOptions::new()
516 .min_connections(self.min_connections)
517 .max_connections(self.max_connections)
518 .acquire_timeout(self.acquire_timeout)
519 .idle_timeout(self.idle_timeout)
520 .max_lifetime(self.max_lifetime);
521 options = options.test_before_acquire(true);
522 options
523 }
524
525 pub(crate) fn lock_timeout_setting(&self) -> String {
526 duration_milliseconds(self.lock_timeout)
527 }
528
529 pub(crate) fn statement_timeout_setting(&self) -> String {
530 duration_milliseconds(self.statement_timeout)
531 }
532}
533
534impl Default for PostgresStoreOptions {
535 fn default() -> Self {
536 Self {
537 transport_security: PostgresTransportSecurity::VerifyFull,
538 max_connections: 16,
539 min_connections: 1,
540 acquire_timeout: Duration::from_secs(5),
541 idle_timeout: Some(Duration::from_secs(10 * 60)),
542 max_lifetime: Some(Duration::from_secs(30 * 60)),
543 lock_timeout: Duration::from_secs(5),
544 statement_timeout: Duration::from_secs(15),
545 lease_duration: Duration::from_secs(30),
546 maximum_lease_horizon: Duration::from_secs(5 * 60),
547 outbox_attempt_lease_duration: Duration::from_secs(60),
548 }
549 }
550}
551
552fn validate_nonzero_duration(
553 name: &'static str,
554 duration: Duration,
555) -> Result<(), ConfigurationError> {
556 if duration.is_zero() {
557 return Err(ConfigurationError::ZeroDuration { name });
558 }
559 if duration.as_micros() > i64::MAX as u128 {
560 return Err(ConfigurationError::DurationTooLarge { name });
561 }
562 Ok(())
563}
564
565fn duration_milliseconds(duration: Duration) -> String {
566 let milliseconds = duration_millisecond_count(duration);
567 format!("{milliseconds}ms")
568}
569
570fn duration_millisecond_count(duration: Duration) -> u128 {
571 duration.as_nanos().div_ceil(1_000_000)
572}
573
574fn validate_postgres_timeout(
575 name: &'static str,
576 duration: Duration,
577) -> Result<(), ConfigurationError> {
578 if duration_millisecond_count(duration) > MAX_POSTGRES_TIMEOUT_MILLISECONDS {
579 return Err(ConfigurationError::PostgresTimeoutTooLarge { name });
580 }
581 Ok(())
582}
583
584fn validate_lease_timing(name: &'static str, duration: Duration) -> Result<(), ConfigurationError> {
585 if duration.as_micros() == 0 || duration.subsec_nanos() % 1_000 != 0 {
586 return Err(ConfigurationError::LeaseTimingNotMicrosecondAligned { name });
587 }
588 Ok(())
589}
590
591#[cfg(test)]
592mod tests {
593 use std::collections::BTreeMap;
594
595 use super::*;
596
597 const RUNTIME_URL: &str = "postgres://runtime:secret@db.example/stateknot";
598 const MIGRATION_URL: &str = "postgres://migrator:secret@db.example/stateknot";
599
600 fn from_values(
601 values: impl IntoIterator<Item = (&'static str, &'static str)>,
602 ) -> Result<PostgresStoreConfig, ConfigurationError> {
603 let values = values
604 .into_iter()
605 .map(|(name, value)| (name, value.to_owned()))
606 .collect::<BTreeMap<_, _>>();
607 PostgresStoreConfig::from_environment(|name| Ok(values.get(name).cloned()))
608 }
609
610 #[test]
611 fn production_builder_defaults_are_safe_and_urls_are_redacted() {
612 let config = PostgresStoreConfig::builder(RUNTIME_URL).build().unwrap();
613
614 assert_eq!(config.profile(), PostgresConfigurationProfile::Production);
615 assert!(!config.auto_migrate());
616 assert_eq!(
617 config.options().transport_security(),
618 PostgresTransportSecurity::VerifyFull
619 );
620 let debug = format!("{config:?}");
621 assert!(!debug.contains(RUNTIME_URL));
622 assert!(!debug.contains("db.example"));
623 assert!(!debug.contains("secret"));
624 assert!(debug.contains("[REDACTED]"));
625 }
626
627 #[test]
628 fn development_profile_is_explicit_bounded_and_self_migrating() {
629 let config = PostgresStoreConfig::development(RUNTIME_URL).unwrap();
630 let (runtime, migration, options, auto_migrate) = config.into_parts();
631
632 assert_eq!(runtime.as_ref(), RUNTIME_URL);
633 assert_eq!(migration.as_deref(), Some(RUNTIME_URL));
634 assert_eq!(
635 options.transport_security(),
636 PostgresTransportSecurity::Disabled
637 );
638 assert_eq!(options.min_connections, 1);
639 assert_eq!(options.max_connections, 4);
640 assert!(auto_migrate);
641 }
642
643 #[test]
644 fn production_auto_migration_requires_distinct_credentials() {
645 assert_eq!(
646 PostgresStoreConfig::builder(RUNTIME_URL)
647 .with_auto_migrate(true)
648 .build()
649 .unwrap_err(),
650 ConfigurationError::MigrationDatabaseUrlRequired
651 );
652 assert_eq!(
653 PostgresStoreConfig::builder(RUNTIME_URL)
654 .with_auto_migrate(true)
655 .with_migration_database_url(RUNTIME_URL)
656 .build()
657 .unwrap_err(),
658 ConfigurationError::SharedProductionMigrationCredential
659 );
660
661 let config = PostgresStoreConfig::builder(RUNTIME_URL)
662 .with_auto_migrate(true)
663 .with_migration_database_url(MIGRATION_URL)
664 .build()
665 .unwrap();
666 assert!(config.auto_migrate());
667 }
668
669 #[test]
670 fn environment_profiles_are_closed_and_deterministic() {
671 let development =
672 from_values([(DATABASE_URL_ENV, RUNTIME_URL), (DEV_MODE_ENV, "TrUe")]).unwrap();
673 assert_eq!(
674 development.profile(),
675 PostgresConfigurationProfile::Development
676 );
677 assert!(development.auto_migrate());
678
679 let production = from_values([
680 (DATABASE_URL_ENV, RUNTIME_URL),
681 (AUTO_MIGRATE_ENV, "true"),
682 (MIGRATION_DATABASE_URL_ENV, MIGRATION_URL),
683 ])
684 .unwrap();
685 assert_eq!(
686 production.profile(),
687 PostgresConfigurationProfile::Production
688 );
689 assert!(production.auto_migrate());
690
691 assert_eq!(
692 from_values([(DATABASE_URL_ENV, RUNTIME_URL), (DEV_MODE_ENV, "yes")]).unwrap_err(),
693 ConfigurationError::InvalidEnvironmentVariable { name: DEV_MODE_ENV }
694 );
695 assert_eq!(
696 from_values([]).unwrap_err(),
697 ConfigurationError::MissingEnvironmentVariable {
698 name: DATABASE_URL_ENV
699 }
700 );
701 }
702}