eventcore-postgres 2.1.0

PostgreSQL event store adapter for EventCore event sourcing library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::any::Any;
use std::fmt;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::time::Duration;

use futures::FutureExt;
use tokio::time::timeout;

pub(crate) async fn cleanup_pair<First, Second>(
    bound: Duration,
    first: First,
    second: Second,
) -> (
    Result<First::Output, tokio::time::error::Elapsed>,
    Result<Second::Output, tokio::time::error::Elapsed>,
)
where
    First: Future,
    Second: Future,
{
    tokio::join!(timeout(bound, first), timeout(bound, second))
}

pub(crate) type FixtureFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;

pub(crate) struct FixtureTimeouts {
    initialization: Duration,
    body: Duration,
    cleanup: Duration,
}

impl FixtureTimeouts {
    pub(crate) fn new(bound: Duration) -> Self {
        Self {
            initialization: bound,
            body: bound,
            cleanup: bound,
        }
    }
}

pub(crate) enum FixtureLifecycleError<E> {
    InitializationError(E),
    InitializationPanicked(Box<dyn Any + Send>),
    InitializationTimedOut,
    BodyError(E),
    BodyPanicked(Box<dyn Any + Send>),
    BodyTimedOut,
    CleanupError(E),
    CleanupPanicked(Box<dyn Any + Send>),
    CleanupTimedOut,
}

impl<E: fmt::Debug> fmt::Debug for FixtureLifecycleError<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InitializationError(error) => formatter
                .debug_tuple("InitializationError")
                .field(error)
                .finish(),
            Self::InitializationPanicked(payload) => formatter
                .debug_tuple("InitializationPanicked")
                .field(&(**payload).type_id())
                .finish(),
            Self::InitializationTimedOut => formatter.write_str("InitializationTimedOut"),
            Self::BodyError(error) => formatter.debug_tuple("BodyError").field(error).finish(),
            Self::BodyPanicked(payload) => formatter
                .debug_tuple("BodyPanicked")
                .field(&(**payload).type_id())
                .finish(),
            Self::BodyTimedOut => formatter.write_str("BodyTimedOut"),
            Self::CleanupError(error) => {
                formatter.debug_tuple("CleanupError").field(error).finish()
            }
            Self::CleanupPanicked(payload) => formatter
                .debug_tuple("CleanupPanicked")
                .field(&(**payload).type_id())
                .finish(),
            Self::CleanupTimedOut => formatter.write_str("CleanupTimedOut"),
        }
    }
}

/// Runs a test-owned resource through bounded initialization, body, and cleanup stages.
///
/// Cleanup is attempted exactly once after every initialization/body outcome. When cleanup also
/// fails, the first initialization or body failure remains the returned diagnostic.
pub(crate) async fn run_fixture<R, E, Initialize, Body, Cleanup>(
    mut resource: R,
    timeouts: FixtureTimeouts,
    initialize: Initialize,
    body: Body,
    cleanup: Cleanup,
) -> Result<(), FixtureLifecycleError<E>>
where
    Initialize: for<'a> FnOnce(&'a mut R) -> FixtureFuture<'a, Result<(), E>>,
    Body: for<'a> FnOnce(&'a mut R) -> FixtureFuture<'a, Result<(), E>>,
    Cleanup: for<'a> FnOnce(&'a mut R) -> FixtureFuture<'a, Result<(), E>>,
{
    let mut primary = match timeout(
        timeouts.initialization,
        AssertUnwindSafe(initialize(&mut resource)).catch_unwind(),
    )
    .await
    {
        Ok(Ok(Ok(()))) => None,
        Ok(Ok(Err(error))) => Some(FixtureLifecycleError::InitializationError(error)),
        Ok(Err(payload)) => Some(FixtureLifecycleError::InitializationPanicked(payload)),
        Err(_) => Some(FixtureLifecycleError::InitializationTimedOut),
    };

    if primary.is_none() {
        primary = match timeout(
            timeouts.body,
            AssertUnwindSafe(body(&mut resource)).catch_unwind(),
        )
        .await
        {
            Ok(Ok(Ok(()))) => None,
            Ok(Ok(Err(error))) => Some(FixtureLifecycleError::BodyError(error)),
            Ok(Err(payload)) => Some(FixtureLifecycleError::BodyPanicked(payload)),
            Err(_) => Some(FixtureLifecycleError::BodyTimedOut),
        };
    }

    let cleanup_failure = match timeout(
        timeouts.cleanup,
        AssertUnwindSafe(cleanup(&mut resource)).catch_unwind(),
    )
    .await
    {
        Ok(Ok(Ok(()))) => None,
        Ok(Ok(Err(error))) => Some(FixtureLifecycleError::CleanupError(error)),
        Ok(Err(payload)) => Some(FixtureLifecycleError::CleanupPanicked(payload)),
        Err(_) => Some(FixtureLifecycleError::CleanupTimedOut),
    };

    match primary {
        Some(failure) => Err(failure),
        None => cleanup_failure.map_or(Ok(()), Err),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    use super::{FixtureFuture, FixtureLifecycleError, FixtureTimeouts, run_fixture};
    use tokio::sync::{Notify, oneshot};
    use tokio::time::timeout;

    #[derive(Debug, PartialEq, Eq)]
    enum TestError {
        Initialization,
        Body,
        Cleanup,
    }

    struct TestResource {
        owned: Vec<&'static str>,
        cleaned: Arc<Mutex<Vec<&'static str>>>,
        cleanup_result: Result<(), TestError>,
    }

    fn resource(owned: Vec<&'static str>, cleaned: Arc<Mutex<Vec<&'static str>>>) -> TestResource {
        TestResource {
            owned,
            cleaned,
            cleanup_result: Ok(()),
        }
    }

    fn timeouts() -> FixtureTimeouts {
        FixtureTimeouts::new(Duration::from_millis(20))
    }

    fn succeeds(_: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(async { Ok(()) })
    }

    fn initialization_error(_: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(async { Err(TestError::Initialization) })
    }

    fn initialization_panic(_: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(async { panic!("initialization panic") })
    }

    fn never_completes(_: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(std::future::pending())
    }

    fn body_error(_: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(async { Err(TestError::Body) })
    }

    fn body_panic(_: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(async { panic!("body panic") })
    }

    fn cleanup(resource: &mut TestResource) -> FixtureFuture<'_, Result<(), TestError>> {
        Box::pin(async move {
            resource
                .cleaned
                .lock()
                .expect("cleanup observation mutex should not be poisoned")
                .extend(resource.owned.iter().copied());
            std::mem::replace(&mut resource.cleanup_result, Ok(()))
        })
    }

    // Break caught: returning directly from initialization error leaks resources planned before
    // the async initializer was entered.
    #[tokio::test]
    async fn initialization_error_after_resource_ownership_still_cleans_up() {
        let cleaned = Arc::new(Mutex::new(Vec::new()));

        // Given a resource owned before initialization starts.
        let result = run_fixture(
            resource(vec!["schema"], Arc::clone(&cleaned)),
            timeouts(),
            initialization_error,
            succeeds,
            cleanup,
        )
        .await;

        // Then the initialization error remains primary and cleanup still observes the resource.
        assert!(matches!(
            result,
            Err(FixtureLifecycleError::InitializationError(
                TestError::Initialization
            ))
        ));
        assert_eq!(
            *cleaned.lock().expect("mutex should not be poisoned"),
            ["schema"]
        );
    }

    // Break caught: unwinding initialization before cleanup leaks a schema already named by the
    // fixture owner.
    #[tokio::test]
    async fn initialization_panic_after_resource_ownership_still_cleans_up() {
        let cleaned = Arc::new(Mutex::new(Vec::new()));

        let result = run_fixture(
            resource(vec!["schema"], Arc::clone(&cleaned)),
            timeouts(),
            initialization_panic,
            succeeds,
            cleanup,
        )
        .await;

        assert!(matches!(
            result,
            Err(FixtureLifecycleError::InitializationPanicked(_))
        ));
        assert_eq!(
            *cleaned.lock().expect("mutex should not be poisoned"),
            ["schema"]
        );
    }

    // Break caught: cancelling a timed-out initializer without subsequently cleaning its owner
    // leaks resources created before the await that stalled.
    #[tokio::test]
    async fn initialization_timeout_after_resource_ownership_still_cleans_up() {
        let cleaned = Arc::new(Mutex::new(Vec::new()));

        let result = run_fixture(
            resource(vec!["schema"], Arc::clone(&cleaned)),
            timeouts(),
            never_completes,
            succeeds,
            cleanup,
        )
        .await;

        assert!(matches!(
            result,
            Err(FixtureLifecycleError::InitializationTimedOut)
        ));
        assert_eq!(
            *cleaned.lock().expect("mutex should not be poisoned"),
            ["schema"]
        );
    }

    // Break caught: unwinding or cancelling the contract body before cleanup leaks the fixture.
    #[tokio::test]
    async fn body_panic_and_timeout_each_clean_up() {
        let panic_cleanup = Arc::new(Mutex::new(Vec::new()));
        let timeout_cleanup = Arc::new(Mutex::new(Vec::new()));

        let panic_result = run_fixture(
            resource(vec!["panic-schema"], Arc::clone(&panic_cleanup)),
            timeouts(),
            succeeds,
            body_panic,
            cleanup,
        )
        .await;
        let timeout_result = run_fixture(
            resource(vec!["timeout-schema"], Arc::clone(&timeout_cleanup)),
            timeouts(),
            succeeds,
            never_completes,
            cleanup,
        )
        .await;

        assert!(matches!(
            panic_result,
            Err(FixtureLifecycleError::BodyPanicked(_))
        ));
        assert!(matches!(
            timeout_result,
            Err(FixtureLifecycleError::BodyTimedOut)
        ));
        assert_eq!(
            *panic_cleanup.lock().expect("mutex should not be poisoned"),
            ["panic-schema"]
        );
        assert_eq!(
            *timeout_cleanup
                .lock()
                .expect("mutex should not be poisoned"),
            ["timeout-schema"]
        );
    }

    // Break caught: reporting cleanup failure instead of the body failure hides the first cause
    // and makes the contract diagnosis misleading.
    #[tokio::test]
    async fn cleanup_failure_does_not_replace_primary_failure() {
        let cleaned = Arc::new(Mutex::new(Vec::new()));
        let mut owner = resource(vec!["schema"], Arc::clone(&cleaned));
        owner.cleanup_result = Err(TestError::Cleanup);

        let result = run_fixture(owner, timeouts(), succeeds, body_error, cleanup).await;

        assert!(matches!(
            result,
            Err(FixtureLifecycleError::BodyError(TestError::Body))
        ));
        assert_eq!(
            *cleaned.lock().expect("mutex should not be poisoned"),
            ["schema"]
        );
    }

    // Break caught: cleanup that stops after its first resource leaves the second schema owned by
    // a partially initialized split fixture.
    #[tokio::test]
    async fn two_owned_resources_are_both_cleaned_after_partial_setup() {
        let cleaned = Arc::new(Mutex::new(Vec::new()));

        let result = run_fixture(
            resource(
                vec!["event-schema", "projection-schema"],
                Arc::clone(&cleaned),
            ),
            timeouts(),
            initialization_error,
            succeeds,
            cleanup,
        )
        .await;

        assert!(matches!(
            result,
            Err(FixtureLifecycleError::InitializationError(
                TestError::Initialization
            ))
        ));
        assert_eq!(
            *cleaned.lock().expect("mutex should not be poisoned"),
            ["event-schema", "projection-schema"]
        );
    }

    // Break caught: awaiting the first resource before starting the second means a stalled first
    // cleanup prevents the second resource from receiving any cleanup attempt.
    #[tokio::test]
    async fn pending_first_cleanup_does_not_prevent_observable_second_cleanup() {
        let first_started = Arc::new(Notify::new());
        let first_release = Arc::new(Notify::new());
        let (second_cleaned_sender, second_cleaned_receiver) = oneshot::channel();
        let first_started_by_cleanup = Arc::clone(&first_started);
        let first_release_by_test = Arc::clone(&first_release);
        let first = async move {
            first_started_by_cleanup.notify_one();
            first_release.notified().await;
        };
        let second = async move {
            let _ = second_cleaned_sender.send(());
        };
        let observe_coordination = async move {
            first_started.notified().await;
            let second_observation =
                timeout(Duration::from_millis(50), second_cleaned_receiver).await;
            first_release_by_test.notify_one();
            second_observation
        };

        let ((first_result, second_result), second_observation) = tokio::join!(
            super::cleanup_pair(Duration::from_millis(200), first, second),
            observe_coordination,
        );

        assert!(first_result.is_ok(), "first cleanup should be released");
        assert!(second_result.is_ok(), "second cleanup should complete");
        second_observation
            .expect("second cleanup must start while the first remains pending")
            .expect("second cleanup observation channel should remain open");
    }
}