1use std::time::Duration;
2
3#[derive(Debug)]
5pub struct DeferredCleanupFailure {
6 database_name: String,
7 source: Box<Error>,
8}
9
10impl DeferredCleanupFailure {
11 pub(crate) fn new(database_name: String, source: Error) -> Self {
12 Self {
13 database_name,
14 source: Box::new(source),
15 }
16 }
17
18 pub fn database_name(&self) -> &str {
20 &self.database_name
21 }
22
23 pub fn source_error(&self) -> &Error {
25 &self.source
26 }
27}
28
29impl std::fmt::Display for DeferredCleanupFailure {
30 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 write!(
32 formatter,
33 "deferred cleanup failed for database '{}': {}",
34 self.database_name, self.source
35 )
36 }
37}
38
39impl std::error::Error for DeferredCleanupFailure {
40 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
41 Some(self.source.as_ref())
42 }
43}
44
45pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
47
48pub type Result<T> = std::result::Result<T, Error>;
50
51#[derive(Debug, thiserror::Error)]
53#[non_exhaustive]
54pub enum Error {
55 #[error("invalid PostgreSQL test-harness configuration: {reason}")]
56 InvalidConfiguration { reason: &'static str },
57
58 #[error("invalid PostgreSQL test project name '{name}': {reason}")]
59 InvalidProjectName { name: String, reason: &'static str },
60
61 #[error("invalid PostgreSQL test image reference: {reason}")]
62 InvalidImageReference { reason: &'static str },
63
64 #[error("invalid PostgreSQL admin database URL: {reason}")]
65 InvalidAdminDatabaseUrl { reason: &'static str },
66
67 #[error("invalid template fingerprint")]
68 InvalidTemplateFingerprint,
69
70 #[error("invalid managed test database name '{name}'")]
71 InvalidDatabaseName { name: String },
72
73 #[error("PostgreSQL test connection failed during {operation}: {source}")]
74 Postgres {
75 operation: &'static str,
76 #[source]
77 source: tokio_postgres::Error,
78 },
79
80 #[error("PostgreSQL test connection timed out during {operation} after {timeout:?}")]
81 PostgresConnectTimeout {
82 operation: &'static str,
83 timeout: Duration,
84 },
85
86 #[error("PostgreSQL test operation timed out during {operation} after {timeout:?}")]
87 PostgresOperationTimeout {
88 operation: &'static str,
89 timeout: Duration,
90 },
91
92 #[error("failed to initialize PostgreSQL admin runtime during {operation}: {source}")]
93 PostgresRuntime {
94 operation: &'static str,
95 #[source]
96 source: std::io::Error,
97 },
98
99 #[error(
100 "PostgreSQL 18 is required; connected server reported server_version_num={server_version_num}"
101 )]
102 UnsupportedPostgresVersion { server_version_num: i32 },
103
104 #[error("PostgreSQL 18 capability check failed: uuidv7() is unavailable")]
105 MissingUuidV7,
106
107 #[cfg(not(feature = "containers"))]
108 #[error(
109 "an external PostgreSQL admin URL is required because the 'containers' feature is disabled; configure HarnessConfig::with_admin_database_url or POSTGRES_TEST_ADMIN_URL"
110 )]
111 ExternalAdminUrlRequired,
112
113 #[cfg(feature = "containers")]
114 #[error("failed to start the PostgreSQL test container: {source}")]
115 ContainerStart {
116 #[source]
117 source: testcontainers::TestcontainersError,
118 },
119
120 #[cfg(feature = "containers")]
121 #[error(
122 "failed to start the PostgreSQL test container with a {tmpfs_size_bytes}-byte tmpfs storage cap; if this Docker daemon does not support tmpfs mounts, disable tmpfs through OwnedContainerProfile::without_tmpfs: {source}"
123 )]
124 ContainerStorageStart {
125 tmpfs_size_bytes: u64,
126 #[source]
127 source: testcontainers::TestcontainersError,
128 },
129
130 #[cfg(feature = "containers")]
131 #[error(
132 "the PostgreSQL test container did not reach its final TCP server within the {timeout:?} startup timeout: {source}"
133 )]
134 ContainerReadinessTimeout {
135 timeout: Duration,
136 #[source]
137 source: Box<Error>,
138 },
139
140 #[cfg(feature = "containers")]
141 #[error(
142 "the PostgreSQL test container stopped before its final TCP server was ready (exit code {exit_code:?})"
143 )]
144 ContainerExitedBeforeReady { exit_code: Option<i64> },
145
146 #[cfg(feature = "containers")]
147 #[error(
148 "the PostgreSQL test container exhausted its {tmpfs_size_bytes}-byte tmpfs before its final TCP server was ready ({evidence}); increase the cap with OwnedContainerProfile::with_tmpfs_size_bytes or disable tmpfs with OwnedContainerProfile::without_tmpfs"
149 )]
150 ContainerStorageExhausted {
151 tmpfs_size_bytes: u64,
152 evidence: &'static str,
153 },
154
155 #[cfg(feature = "containers")]
156 #[error(
157 "the PostgreSQL test container encountered memory exhaustion while using a {tmpfs_size_bytes}-byte tmpfs before its final TCP server was ready ({evidence}); reduce memory pressure, increase the Docker memory allowance, or disable tmpfs with OwnedContainerProfile::without_tmpfs"
158 )]
159 ContainerMemoryExhausted {
160 tmpfs_size_bytes: u64,
161 evidence: &'static str,
162 },
163
164 #[cfg(feature = "containers")]
165 #[error(
166 "the PostgreSQL test container did not finish starting within the {timeout:?} startup timeout"
167 )]
168 ContainerStartupTimeout { timeout: Duration },
169
170 #[cfg(feature = "containers")]
171 #[error("failed to remove the PostgreSQL test container: {source}")]
172 ContainerRemove {
173 #[source]
174 source: testcontainers::TestcontainersError,
175 },
176
177 #[cfg(feature = "containers")]
178 #[error("failed to start the PostgreSQL container owner thread: {source}")]
179 ContainerWorkerStart {
180 #[source]
181 source: std::io::Error,
182 },
183
184 #[cfg(feature = "containers")]
185 #[error("the PostgreSQL container owner thread stopped unexpectedly")]
186 ContainerWorkerStopped,
187
188 #[cfg(feature = "containers")]
189 #[error("the PostgreSQL container owner thread panicked")]
190 ContainerWorkerPanicked,
191
192 #[cfg(feature = "containers")]
193 #[error("failed to register PostgreSQL container process-exit cleanup")]
194 ExitCleanupRegistration,
195
196 #[error("PostgreSQL test blocking worker failed: {source}")]
197 BlockingTask {
198 #[source]
199 source: tokio::task::JoinError,
200 },
201
202 #[error("PostgreSQL test state lock was poisoned during {operation}")]
203 StatePoisoned { operation: &'static str },
204
205 #[error("PostgreSQL test connection budget is closed")]
206 ConnectionBudgetClosed,
207
208 #[error(
209 "prewarmed database queue capacity must be between 1 and the effective lease limit of {max_capacity}, got {capacity}"
210 )]
211 InvalidPrewarmCapacity {
212 capacity: usize,
213 max_capacity: usize,
214 },
215
216 #[error("the prewarmed PostgreSQL database queue is closed")]
217 PrewarmPoolClosed,
218
219 #[error("the disposable PostgreSQL admin-session pool is closed")]
220 AdminSessionPoolClosed,
221
222 #[error("timed out waiting for a disposable PostgreSQL admin session after {timeout:?}")]
223 AdminSessionCheckoutTimeout { timeout: Duration },
224
225 #[error("the deferred PostgreSQL database cleanup queue is closed")]
226 CleanupQueueClosed,
227
228 #[error("a deferred PostgreSQL database cleanup worker stopped unexpectedly")]
229 CleanupWorkerStopped,
230
231 #[error("a deferred PostgreSQL database cleanup worker panicked")]
232 CleanupWorkerPanicked,
233
234 #[error(
235 "deferred PostgreSQL database cleanup failed for {} database(s)",
236 .failures.len()
237 )]
238 #[non_exhaustive]
239 DeferredCleanup {
240 failures: Vec<DeferredCleanupFailure>,
241 },
242
243 #[error("template initialization failed: {source}")]
244 TemplateInitializer {
245 #[source]
246 source: BoxError,
247 },
248
249 #[error("template initialization failed ({initializer}); cleanup also failed ({cleanup})")]
250 TemplateInitializerAndCleanup {
251 #[source]
252 initializer: BoxError,
253 cleanup: Box<Error>,
254 },
255
256 #[error(
257 "failed to tag a managed PostgreSQL database ({tagging}); compensating FORCE drop also failed ({cleanup})"
258 )]
259 ManagedDatabaseTagAndCleanup {
260 #[source]
261 tagging: Box<Error>,
262 cleanup: Box<Error>,
263 },
264
265 #[error("managed PostgreSQL resource metadata is inconsistent for database '{database_name}'")]
266 InconsistentMetadata { database_name: String },
267
268 #[error("duration {duration:?} is outside the supported millisecond timeout range")]
269 TimeoutOutOfRange { duration: Duration },
270
271 #[error(
272 "connections to PostgreSQL template database '{database_name}' could not be terminated"
273 )]
274 TemplateConnectionsRemain { database_name: String },
275
276 #[error("failed to start a deferred PostgreSQL database cleanup worker: {source}")]
277 CleanupWorkerStart {
278 #[source]
279 source: std::io::Error,
280 },
281
282 #[cfg(feature = "containers")]
283 #[error(
284 "deferred PostgreSQL database cleanup failed ({cleanup}); owned-container shutdown also failed ({shutdown})"
285 )]
286 CleanupAndContainerShutdown {
287 #[source]
288 cleanup: Box<Error>,
289 shutdown: Box<Error>,
290 },
291
292 #[cfg(feature = "containers")]
293 #[error(
294 "PostgreSQL container startup failed ({startup}); cleanup of the partially started container also failed ({cleanup})"
295 )]
296 ContainerStartupAndCleanup {
297 #[source]
298 startup: Box<Error>,
299 cleanup: Box<Error>,
300 },
301}
302
303impl Error {
304 pub(crate) fn postgres(operation: &'static str, source: tokio_postgres::Error) -> Self {
305 Self::Postgres { operation, source }
306 }
307
308 pub(crate) fn deferred_cleanup(failures: Vec<DeferredCleanupFailure>) -> Self {
309 Self::DeferredCleanup { failures }
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use std::error::Error as _;
316
317 use super::{DeferredCleanupFailure, Error};
318
319 #[test]
320 fn deferred_cleanup_count_is_derived_from_failures() {
321 let error = Error::deferred_cleanup(vec![
322 DeferredCleanupFailure::new(
323 "first".to_owned(),
324 Error::InvalidConfiguration { reason: "one" },
325 ),
326 DeferredCleanupFailure::new(
327 "second".to_owned(),
328 Error::InvalidConfiguration { reason: "two" },
329 ),
330 ]);
331
332 assert_eq!(
333 error.to_string(),
334 "deferred PostgreSQL database cleanup failed for 2 database(s)"
335 );
336 }
337
338 #[test]
339 fn combined_initializer_error_preserves_a_source() {
340 let error = Error::TemplateInitializerAndCleanup {
341 initializer: std::io::Error::other("initializer").into(),
342 cleanup: Box::new(Error::InvalidConfiguration { reason: "cleanup" }),
343 };
344 assert_eq!(error.source().unwrap().to_string(), "initializer");
345 }
346
347 #[test]
348 fn combined_managed_database_error_preserves_the_tagging_source() {
349 let error = Error::ManagedDatabaseTagAndCleanup {
350 tagging: Box::new(Error::InvalidConfiguration { reason: "tagging" }),
351 cleanup: Box::new(Error::InvalidConfiguration { reason: "cleanup" }),
352 };
353 assert_eq!(
354 error.source().unwrap().to_string(),
355 "invalid PostgreSQL test-harness configuration: tagging"
356 );
357 assert!(error.to_string().contains("cleanup"));
358 }
359}