1use std::{fmt, num::NonZeroU32, time::Duration};
2
3use crate::{Error, Result};
4
5pub const POSTGRES_TEST_ADMIN_URL_ENV: &str = "POSTGRES_TEST_ADMIN_URL";
6pub const POSTGRES_TEST_IMAGE_ENV: &str = "POSTGRES_TEST_IMAGE";
7
8#[cfg(feature = "containers")]
9const DEFAULT_IMAGE: &str = "postgres:18";
10const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(60);
11const DEFAULT_OPERATION_TIMEOUT: Duration = Duration::from_secs(90);
12const DEFAULT_TEMPLATE_WAIT_TIMEOUT: Duration = Duration::from_secs(15 * 60);
13const DEFAULT_STALE_AFTER: Duration = Duration::from_secs(60 * 60);
14const DEFAULT_CONNECTION_BUDGET: u32 = 120;
15const DEFAULT_CONNECTIONS_PER_DATABASE: u32 = 11;
16const MAX_PROJECT_NAME_LEN: usize = 16;
17
18pub const DEFAULT_OWNED_CONTAINER_TMPFS_SIZE_BYTES: u64 = 1024 * 1024 * 1024;
21
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub struct OwnedContainerProfile {
38 initdb_no_sync: bool,
39 tmpfs_size_bytes: Option<u64>,
40}
41
42impl OwnedContainerProfile {
43 pub const fn performance() -> Self {
45 Self {
46 initdb_no_sync: true,
47 tmpfs_size_bytes: Some(DEFAULT_OWNED_CONTAINER_TMPFS_SIZE_BYTES),
48 }
49 }
50
51 pub const fn with_initdb_no_sync(mut self, enabled: bool) -> Self {
57 self.initdb_no_sync = enabled;
58 self
59 }
60
61 pub fn with_tmpfs_size_bytes(mut self, size_bytes: u64) -> Result<Self> {
64 if size_bytes == 0 || size_bytes > i64::MAX as u64 {
65 return Err(Error::InvalidConfiguration {
66 reason: "owned-container tmpfs size must be between 1 and i64::MAX bytes",
67 });
68 }
69 self.tmpfs_size_bytes = Some(size_bytes);
70 Ok(self)
71 }
72
73 pub const fn without_tmpfs(mut self) -> Self {
79 self.tmpfs_size_bytes = None;
80 self
81 }
82
83 pub const fn initdb_no_sync(&self) -> bool {
85 self.initdb_no_sync
86 }
87
88 pub const fn tmpfs_size_bytes(&self) -> Option<u64> {
91 self.tmpfs_size_bytes
92 }
93}
94
95impl Default for OwnedContainerProfile {
96 fn default() -> Self {
97 Self::performance()
98 }
99}
100
101#[derive(Clone, Debug, Eq, PartialEq)]
103pub struct ProjectName(String);
104
105impl ProjectName {
106 pub fn new(name: impl Into<String>) -> Result<Self> {
107 let name = name.into();
108 if name.is_empty() {
109 return Err(Error::InvalidProjectName {
110 name,
111 reason: "the name must not be empty",
112 });
113 }
114 if name.len() > MAX_PROJECT_NAME_LEN {
115 return Err(Error::InvalidProjectName {
116 name,
117 reason: "the name must be at most 16 ASCII characters",
118 });
119 }
120 if !name
121 .bytes()
122 .next()
123 .is_some_and(|byte| byte.is_ascii_lowercase())
124 {
125 return Err(Error::InvalidProjectName {
126 name,
127 reason: "the name must start with a lowercase ASCII letter",
128 });
129 }
130 if !name
131 .bytes()
132 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
133 {
134 return Err(Error::InvalidProjectName {
135 name,
136 reason: "only lowercase ASCII letters, digits, and underscores are allowed",
137 });
138 }
139 Ok(Self(name))
140 }
141
142 pub fn as_str(&self) -> &str {
143 &self.0
144 }
145}
146
147#[derive(Clone)]
149pub struct HarnessConfig {
150 pub(crate) project: ProjectName,
151 pub(crate) admin_database_url: Option<String>,
152 pub(crate) image: Option<String>,
153 pub(crate) owned_container_profile: OwnedContainerProfile,
154 pub(crate) startup_timeout: Duration,
155 pub(crate) operation_timeout: Duration,
156 pub(crate) template_wait_timeout: Duration,
157 pub(crate) stale_after: Duration,
158 connection_budget_override: Option<NonZeroU32>,
159 connections_per_database_override: Option<NonZeroU32>,
160 pub(crate) cleanup_on_start: bool,
161}
162
163#[derive(Clone, Copy, Debug, Eq, PartialEq)]
171pub struct ConnectionLimits {
172 pub(crate) connection_budget: usize,
173 pub(crate) connections_per_database: u32,
174}
175
176impl ConnectionLimits {
177 pub const fn connection_budget(&self) -> usize {
179 self.connection_budget
180 }
181
182 pub const fn connections_per_database(&self) -> u32 {
187 self.connections_per_database
188 }
189
190 pub const fn max_simultaneous_leases(&self) -> usize {
194 self.connection_budget / self.connections_per_database as usize
195 }
196}
197
198impl HarnessConfig {
199 pub fn new(project: impl Into<String>) -> Result<Self> {
200 Ok(Self {
201 project: ProjectName::new(project)?,
202 admin_database_url: None,
203 image: None,
204 owned_container_profile: OwnedContainerProfile::default(),
205 startup_timeout: DEFAULT_STARTUP_TIMEOUT,
206 operation_timeout: DEFAULT_OPERATION_TIMEOUT,
207 template_wait_timeout: DEFAULT_TEMPLATE_WAIT_TIMEOUT,
208 stale_after: DEFAULT_STALE_AFTER,
209 connection_budget_override: None,
210 connections_per_database_override: None,
211 cleanup_on_start: true,
212 })
213 }
214
215 pub fn with_admin_database_url(mut self, admin_database_url: impl Into<String>) -> Self {
216 self.admin_database_url = Some(admin_database_url.into());
217 self
218 }
219
220 pub fn with_image(mut self, image: impl Into<String>) -> Result<Self> {
225 let image = image.into();
226 ImageReference::parse(&image)?;
227 self.image = Some(image);
228 Ok(self)
229 }
230
231 pub fn with_owned_container_profile(mut self, profile: OwnedContainerProfile) -> Self {
235 self.owned_container_profile = profile;
236 self
237 }
238
239 pub fn with_startup_timeout(mut self, timeout: Duration) -> Result<Self> {
240 validate_millisecond_timeout(timeout)?;
241 self.startup_timeout = timeout;
242 Ok(self)
243 }
244
245 pub fn with_operation_timeout(mut self, timeout: Duration) -> Result<Self> {
246 validate_postgres_timeout(timeout)?;
247 self.operation_timeout = timeout;
248 Ok(self)
249 }
250
251 pub fn with_template_wait_timeout(mut self, timeout: Duration) -> Result<Self> {
255 validate_postgres_timeout(timeout)?;
256 self.template_wait_timeout = timeout;
257 Ok(self)
258 }
259
260 pub fn with_stale_after(mut self, stale_after: Duration) -> Self {
261 self.stale_after = stale_after;
262 self
263 }
264
265 pub fn with_connection_budget(mut self, permits: usize) -> Result<Self> {
269 let Some(permits) = u32::try_from(permits).ok().and_then(NonZeroU32::new) else {
270 return Err(Error::InvalidConfiguration {
271 reason: "the connection budget must fit in a positive u32",
272 });
273 };
274 self.connection_budget_override = Some(permits);
275 Ok(self)
276 }
277
278 pub fn with_connections_per_database(mut self, permits: u32) -> Result<Self> {
282 let Some(permits) = NonZeroU32::new(permits) else {
283 return Err(Error::InvalidConfiguration {
284 reason: "per-database permits must be positive",
285 });
286 };
287 self.connections_per_database_override = Some(permits);
288 Ok(self)
289 }
290
291 pub fn with_cleanup_on_start(mut self, cleanup_on_start: bool) -> Self {
292 self.cleanup_on_start = cleanup_on_start;
293 self
294 }
295
296 pub fn project(&self) -> &ProjectName {
297 &self.project
298 }
299
300 pub fn owned_container_profile(&self) -> &OwnedContainerProfile {
302 &self.owned_container_profile
303 }
304
305 pub fn connection_limits(&self) -> Result<ConnectionLimits> {
313 let connection_budget = self
314 .connection_budget_override
315 .map_or(DEFAULT_CONNECTION_BUDGET, NonZeroU32::get);
316 let connections_per_database = self.connections_per_database_override.map_or(
317 DEFAULT_CONNECTIONS_PER_DATABASE.min(connection_budget),
318 NonZeroU32::get,
319 );
320 if connections_per_database > connection_budget {
321 return Err(Error::InvalidConfiguration {
322 reason: "per-database permits must be no greater than the connection budget",
323 });
324 }
325 Ok(ConnectionLimits {
326 connection_budget: connection_budget as usize,
327 connections_per_database,
328 })
329 }
330
331 pub(crate) fn resolved_admin_database_url(&self) -> Option<String> {
332 self.admin_database_url
333 .clone()
334 .or_else(|| std::env::var(POSTGRES_TEST_ADMIN_URL_ENV).ok())
335 }
336
337 #[cfg(feature = "containers")]
338 pub(crate) fn resolved_image(&self) -> Result<ImageReference> {
339 let image = self
340 .image
341 .clone()
342 .or_else(|| std::env::var(POSTGRES_TEST_IMAGE_ENV).ok())
343 .unwrap_or_else(|| DEFAULT_IMAGE.to_owned());
344 ImageReference::parse(&image)
345 }
346}
347
348impl fmt::Debug for HarnessConfig {
349 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
350 formatter
351 .debug_struct("HarnessConfig")
352 .field("project", &self.project)
353 .field(
354 "admin_database_url",
355 &self.admin_database_url.as_ref().map(|_| "[REDACTED]"),
356 )
357 .field("image", &self.image)
358 .field("owned_container_profile", &self.owned_container_profile)
359 .field("startup_timeout", &self.startup_timeout)
360 .field("operation_timeout", &self.operation_timeout)
361 .field("template_wait_timeout", &self.template_wait_timeout)
362 .field("stale_after", &self.stale_after)
363 .field(
364 "connection_budget_override",
365 &self.connection_budget_override.map(NonZeroU32::get),
366 )
367 .field(
368 "connections_per_database_override",
369 &self.connections_per_database_override.map(NonZeroU32::get),
370 )
371 .field("cleanup_on_start", &self.cleanup_on_start)
372 .finish()
373 }
374}
375
376#[derive(Clone, Debug, Eq, PartialEq)]
377pub(crate) struct ImageReference {
378 pub(crate) repository: String,
379 pub(crate) tag: String,
380}
381
382impl ImageReference {
383 pub(crate) fn parse(image: &str) -> Result<Self> {
384 if image.is_empty() || image.chars().any(char::is_whitespace) {
385 return Err(Error::InvalidImageReference {
386 reason: "the image must be non-empty and contain no whitespace",
387 });
388 }
389
390 let (name_and_tag, digest) = image
391 .split_once('@')
392 .map_or((image, None), |(name, digest)| (name, Some(digest)));
393 if name_and_tag.is_empty() || digest.is_some_and(str::is_empty) {
394 return Err(Error::InvalidImageReference {
395 reason: "the repository and optional digest must be non-empty",
396 });
397 }
398
399 let last_slash = name_and_tag.rfind('/');
400 let tag_separator = name_and_tag
401 .rfind(':')
402 .filter(|index| last_slash.is_none_or(|slash| *index > slash));
403 let (repository, mut tag) = tag_separator.map_or_else(
404 || (name_and_tag.to_owned(), "latest".to_owned()),
405 |index| {
406 (
407 name_and_tag[..index].to_owned(),
408 name_and_tag[index + 1..].to_owned(),
409 )
410 },
411 );
412 if repository.is_empty() || tag.is_empty() {
413 return Err(Error::InvalidImageReference {
414 reason: "the repository and tag must be non-empty",
415 });
416 }
417 if let Some(digest) = digest {
418 tag.push('@');
419 tag.push_str(digest);
420 }
421 Ok(Self { repository, tag })
422 }
423}
424
425fn validate_millisecond_timeout(timeout: Duration) -> Result<()> {
426 if timeout.as_millis() == 0 {
427 return Err(Error::TimeoutOutOfRange { duration: timeout });
428 }
429 Ok(())
430}
431
432fn validate_postgres_timeout(timeout: Duration) -> Result<()> {
433 validate_millisecond_timeout(timeout)?;
434 if timeout.as_millis() > i32::MAX as u128 {
435 return Err(Error::TimeoutOutOfRange { duration: timeout });
436 }
437 Ok(())
438}
439
440#[cfg(test)]
441mod tests {
442 use super::{
443 ConnectionLimits, DEFAULT_OWNED_CONTAINER_TMPFS_SIZE_BYTES, HarnessConfig, ImageReference,
444 OwnedContainerProfile, ProjectName,
445 };
446
447 #[test]
448 fn project_names_are_deliberately_narrow() {
449 assert!(ProjectName::new("creditkit").is_ok());
450 assert!(ProjectName::new("credit_kit2").is_ok());
451 assert!(ProjectName::new("").is_err());
452 assert!(ProjectName::new("CreditKit").is_err());
453 assert!(ProjectName::new("2creditkit").is_err());
454 assert!(ProjectName::new("credit-kit").is_err());
455 assert!(ProjectName::new("a_name_that_is_too_long").is_err());
456 }
457
458 #[test]
459 fn image_reference_handles_registry_ports_and_digests() {
460 assert_eq!(
461 ImageReference::parse("postgres:18").unwrap(),
462 ImageReference {
463 repository: "postgres".to_owned(),
464 tag: "18".to_owned(),
465 }
466 );
467 assert_eq!(
468 ImageReference::parse("registry.example:5000/postgres:18@sha256:abc").unwrap(),
469 ImageReference {
470 repository: "registry.example:5000/postgres".to_owned(),
471 tag: "18@sha256:abc".to_owned(),
472 }
473 );
474 }
475
476 #[test]
477 fn config_debug_redacts_an_explicit_admin_url() {
478 let config = HarnessConfig::new("creditkit")
479 .unwrap()
480 .with_admin_database_url("postgres://user:secret@localhost/postgres");
481 let debug = format!("{config:?}");
482 assert!(debug.contains("[REDACTED]"));
483 assert!(!debug.contains("secret"));
484 }
485
486 #[test]
487 fn owned_container_profile_defaults_are_explicit_and_replaceable() {
488 let profile = OwnedContainerProfile::default();
489 assert!(profile.initdb_no_sync());
490 assert_eq!(
491 profile.tmpfs_size_bytes(),
492 Some(DEFAULT_OWNED_CONTAINER_TMPFS_SIZE_BYTES)
493 );
494
495 let compatible = profile.with_initdb_no_sync(false).without_tmpfs();
496 let config = HarnessConfig::new("creditkit")
497 .unwrap()
498 .with_owned_container_profile(compatible);
499 assert_eq!(config.owned_container_profile(), &compatible);
500 assert!(format!("{config:?}").contains("tmpfs_size_bytes: None"));
501 }
502
503 #[test]
504 fn owned_container_tmpfs_cap_is_positive_and_fits_the_engine_api() {
505 assert!(
506 OwnedContainerProfile::default()
507 .with_tmpfs_size_bytes(0)
508 .is_err()
509 );
510 assert!(
511 OwnedContainerProfile::default()
512 .with_tmpfs_size_bytes(i64::MAX as u64 + 1)
513 .is_err()
514 );
515 let profile = OwnedContainerProfile::default()
516 .with_tmpfs_size_bytes(2 * 1024 * 1024 * 1024)
517 .unwrap();
518 assert_eq!(profile.tmpfs_size_bytes(), Some(2 * 1024 * 1024 * 1024));
519 }
520
521 #[test]
522 fn connection_limit_values_are_validated_at_their_setters() {
523 let error = HarnessConfig::new("creditkit")
524 .unwrap()
525 .with_connection_budget(0)
526 .unwrap_err();
527 assert!(matches!(error, crate::Error::InvalidConfiguration { .. }));
528
529 let error = HarnessConfig::new("creditkit")
530 .unwrap()
531 .with_connections_per_database(0)
532 .unwrap_err();
533 assert!(matches!(
534 error,
535 crate::Error::InvalidConfiguration {
536 reason: "per-database permits must be positive"
537 }
538 ));
539
540 if let Ok(too_large) = usize::try_from(u64::from(u32::MAX) + 1) {
541 let error = HarnessConfig::new("creditkit")
542 .unwrap()
543 .with_connection_budget(too_large)
544 .unwrap_err();
545 assert!(matches!(error, crate::Error::InvalidConfiguration { .. }));
546 }
547 }
548
549 #[test]
550 fn connection_limit_defaults_and_implicit_clamping_are_resolved() {
551 assert_eq!(
552 HarnessConfig::new("creditkit")
553 .unwrap()
554 .connection_limits()
555 .unwrap(),
556 ConnectionLimits {
557 connection_budget: 120,
558 connections_per_database: 11,
559 }
560 );
561
562 let small_budget = HarnessConfig::new("creditkit")
563 .unwrap()
564 .with_connection_budget(5)
565 .unwrap();
566 assert_eq!(
567 small_budget.connection_limits().unwrap(),
568 ConnectionLimits {
569 connection_budget: 5,
570 connections_per_database: 5,
571 }
572 );
573
574 let raised_budget = small_budget.with_connection_budget(20).unwrap();
575 assert_eq!(
576 raised_budget.connection_limits().unwrap(),
577 ConnectionLimits {
578 connection_budget: 20,
579 connections_per_database: 11,
580 }
581 );
582 }
583
584 #[test]
585 fn connection_limit_overrides_are_order_independent_and_last_wins() {
586 let budget_then_per_database = HarnessConfig::new("creditkit")
587 .unwrap()
588 .with_connection_budget(30)
589 .unwrap()
590 .with_connections_per_database(20)
591 .unwrap();
592 let per_database_then_budget = HarnessConfig::new("creditkit")
593 .unwrap()
594 .with_connections_per_database(20)
595 .unwrap()
596 .with_connection_budget(30)
597 .unwrap();
598 assert_eq!(
599 budget_then_per_database.connection_limits().unwrap(),
600 per_database_then_budget.connection_limits().unwrap()
601 );
602
603 let repeated = HarnessConfig::new("creditkit")
604 .unwrap()
605 .with_connection_budget(5)
606 .unwrap()
607 .with_connections_per_database(20)
608 .unwrap()
609 .with_connection_budget(30)
610 .unwrap()
611 .with_connections_per_database(15)
612 .unwrap();
613 assert_eq!(
614 repeated.connection_limits().unwrap(),
615 ConnectionLimits {
616 connection_budget: 30,
617 connections_per_database: 15,
618 }
619 );
620 }
621
622 #[test]
623 fn incompatible_connection_limit_overrides_fail_during_resolution() {
624 let standalone_per_database = HarnessConfig::new("creditkit")
625 .unwrap()
626 .with_connections_per_database(121)
627 .unwrap();
628 assert!(matches!(
629 standalone_per_database.connection_limits(),
630 Err(crate::Error::InvalidConfiguration { .. })
631 ));
632
633 let per_database_then_budget = HarnessConfig::new("creditkit")
634 .unwrap()
635 .with_connections_per_database(20)
636 .unwrap()
637 .with_connection_budget(10)
638 .unwrap();
639 let budget_then_per_database = HarnessConfig::new("creditkit")
640 .unwrap()
641 .with_connection_budget(10)
642 .unwrap()
643 .with_connections_per_database(20)
644 .unwrap();
645 assert!(per_database_then_budget.connection_limits().is_err());
646 assert!(budget_then_per_database.connection_limits().is_err());
647 }
648
649 #[test]
650 fn resolved_connection_limits_expose_effective_floor_division() {
651 let limits = HarnessConfig::new("creditkit")
652 .unwrap()
653 .with_connection_budget(120)
654 .unwrap()
655 .with_connections_per_database(11)
656 .unwrap()
657 .connection_limits()
658 .unwrap();
659
660 assert_eq!(limits.connection_budget(), 120);
661 assert_eq!(limits.connections_per_database(), 11);
662 assert_eq!(limits.max_simultaneous_leases(), 10);
663
664 let exact = HarnessConfig::new("creditkit")
665 .unwrap()
666 .with_connection_budget(33)
667 .unwrap()
668 .with_connections_per_database(11)
669 .unwrap()
670 .connection_limits()
671 .unwrap();
672 assert_eq!(exact.max_simultaneous_leases(), 3);
673 }
674
675 #[test]
676 fn config_debug_reports_raw_connection_limit_overrides() {
677 let defaults = format!("{:?}", HarnessConfig::new("creditkit").unwrap());
678 assert!(defaults.contains("connection_budget_override: None"));
679 assert!(defaults.contains("connections_per_database_override: None"));
680
681 let configured = HarnessConfig::new("creditkit")
682 .unwrap()
683 .with_connection_budget(30)
684 .unwrap()
685 .with_connections_per_database(20)
686 .unwrap();
687 let configured = format!("{configured:?}");
688 assert!(configured.contains("connection_budget_override: Some(30)"));
689 assert!(configured.contains("connections_per_database_override: Some(20)"));
690 }
691
692 #[test]
693 fn postgres_timeouts_have_millisecond_precision() {
694 let too_short = HarnessConfig::new("creditkit")
695 .unwrap()
696 .with_operation_timeout(std::time::Duration::from_nanos(1));
697 assert!(matches!(
698 too_short,
699 Err(crate::Error::TimeoutOutOfRange { .. })
700 ));
701
702 let one_millisecond = HarnessConfig::new("creditkit")
703 .unwrap()
704 .with_operation_timeout(std::time::Duration::from_millis(1));
705 assert!(one_millisecond.is_ok());
706 }
707}