eventuary-postgres 0.2.0

PostgreSQL event backend for eventuary
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
use std::num::NonZeroU32;

use sqlx::PgPool;
use testcontainers::core::{IntoContainerPort, WaitFor};
use testcontainers::runners::AsyncRunner;
use testcontainers::{ContainerAsync, GenericImage, ImageExt};

use eventuary_core::Partition;
use eventuary_core::io::reader::CheckpointScope;
use eventuary_core::io::reader::PartitionCoordinator;
use eventuary_core::io::{ConsumerGroupId, OwnerId, StreamId};
use eventuary_postgres::coordinator::{PgPartitionCoordinator, PgPartitionCoordinatorConfig};
use eventuary_postgres::database::PgDatabase;

async fn start_postgres() -> (ContainerAsync<GenericImage>, PgPool) {
    let container = GenericImage::new("postgres", "18-alpine")
        .with_exposed_port(5432.tcp())
        .with_wait_for(WaitFor::message_on_stderr(
            "database system is ready to accept connections",
        ))
        .with_env_var("POSTGRES_USER", "eventuary")
        .with_env_var("POSTGRES_PASSWORD", "eventuary")
        .with_env_var("POSTGRES_DB", "eventuary")
        .start()
        .await
        .expect("postgres start");
    let port = container.get_host_port_ipv4(5432).await.unwrap();
    let url = format!("postgres://eventuary:eventuary@127.0.0.1:{port}/eventuary");
    let db = PgDatabase::connect(&url).await.unwrap();
    let pool = db.pool();
    PgPartitionCoordinator::prepare_schema(&pool, &PgPartitionCoordinatorConfig::default())
        .await
        .unwrap();
    (container, pool)
}

fn coordinator(pool: PgPool) -> PgPartitionCoordinator {
    PgPartitionCoordinator::new(pool, PgPartitionCoordinatorConfig::default())
}

fn scope() -> CheckpointScope {
    CheckpointScope::new(
        ConsumerGroupId::new("group-1").unwrap(),
        StreamId::new("orders").unwrap(),
    )
}

fn partition(id: u32) -> Partition {
    Partition::new(id, NonZeroU32::new(64).unwrap()).unwrap()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_heartbeat_and_live_count() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let owner_c = OwnerId::new("worker-c").unwrap();

    let long_lease = std::time::Duration::from_secs(60);
    let short_lease = std::time::Duration::from_millis(50);

    coord.heartbeat(&s, &owner_a, long_lease).await.unwrap();
    coord.heartbeat(&s, &owner_b, long_lease).await.unwrap();
    coord.heartbeat(&s, &owner_c, short_lease).await.unwrap();

    let live = coord.live_consumers(&s).await.unwrap();
    assert_eq!(live, 3);

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    let live_after = coord.live_consumers(&s).await.unwrap();
    assert_eq!(live_after, 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_claim_free_partition_succeeds() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner = OwnerId::new("worker-a").unwrap();
    let lease_dur = std::time::Duration::from_secs(60);

    let result = coord
        .claim(&s, &owner, partition(0), lease_dur)
        .await
        .unwrap();
    let lease = result.expect("should get lease");

    assert_eq!(lease.generation.get(), 1);
    assert!(lease.checkpoint_cursor.is_none());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_claim_contested_returns_none() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let lease_dur = std::time::Duration::from_secs(60);

    let first = coord
        .claim(&s, &owner_a, partition(0), lease_dur)
        .await
        .unwrap();
    assert!(first.is_some());

    let second = coord
        .claim(&s, &owner_b, partition(0), lease_dur)
        .await
        .unwrap();
    assert!(second.is_none());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_claim_after_expiry_succeeds() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let short_lease = std::time::Duration::from_millis(50);
    let long_lease = std::time::Duration::from_secs(60);

    let first = coord
        .claim(&s, &owner_a, partition(0), short_lease)
        .await
        .unwrap();
    assert_eq!(first.unwrap().generation.get(), 1);

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    let second = coord
        .claim(&s, &owner_b, partition(0), long_lease)
        .await
        .unwrap();
    let lease = second.expect("should succeed after expiry");
    assert_eq!(lease.generation.get(), 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_renew_with_matching_generation() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner = OwnerId::new("worker-a").unwrap();
    let lease_dur = std::time::Duration::from_secs(60);

    let lease = coord
        .claim(&s, &owner, partition(0), lease_dur)
        .await
        .unwrap()
        .unwrap();
    coord.renew(&lease, lease_dur).await.unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_renew_with_stale_generation_returns_ownership_lost() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let short_lease = std::time::Duration::from_millis(50);
    let long_lease = std::time::Duration::from_secs(60);

    let lease_a = coord
        .claim(&s, &owner_a, partition(0), short_lease)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(lease_a.generation.get(), 1);

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    coord
        .claim(&s, &owner_b, partition(0), long_lease)
        .await
        .unwrap()
        .unwrap();

    let err = coord.renew(&lease_a, long_lease).await.unwrap_err();
    assert!(matches!(err, eventuary_core::Error::OwnershipLost(_)));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_release_with_matching_generation() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let lease_dur = std::time::Duration::from_secs(60);

    let lease = coord
        .claim(&s, &owner_a, partition(0), lease_dur)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(lease.generation.get(), 1);

    coord.release(&lease).await.unwrap();

    let new_lease = coord
        .claim(&s, &owner_b, partition(0), lease_dur)
        .await
        .unwrap()
        .expect("should claim after release");
    assert_eq!(new_lease.generation.get(), 3);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_release_with_stale_generation_returns_ownership_lost() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let short_lease = std::time::Duration::from_millis(50);
    let long_lease = std::time::Duration::from_secs(60);

    let lease_a = coord
        .claim(&s, &owner_a, partition(0), short_lease)
        .await
        .unwrap()
        .unwrap();

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    coord
        .claim(&s, &owner_b, partition(0), long_lease)
        .await
        .unwrap()
        .unwrap();

    let err = coord.release(&lease_a).await.unwrap_err();
    assert!(matches!(err, eventuary_core::Error::OwnershipLost(_)));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_checkpoint_with_matching_generation_advances() {
    use eventuary_postgres::reader::PgCursor;

    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let long_lease = std::time::Duration::from_secs(60);

    let lease = coord
        .claim(&s, &owner_a, partition(0), long_lease)
        .await
        .unwrap()
        .unwrap();

    coord
        .checkpoint(&lease, PgCursor::new(100, partition(0)))
        .await
        .unwrap();

    coord.release(&lease).await.unwrap();

    let new_lease = coord
        .claim(&s, &owner_b, partition(0), long_lease)
        .await
        .unwrap()
        .expect("should claim after release");
    assert_eq!(new_lease.checkpoint_cursor.unwrap().sequence, 100);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_checkpoint_is_monotonic() {
    use eventuary_postgres::reader::PgCursor;

    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let long_lease = std::time::Duration::from_secs(60);

    let lease = coord
        .claim(&s, &owner_a, partition(0), long_lease)
        .await
        .unwrap()
        .unwrap();

    coord
        .checkpoint(&lease, PgCursor::new(100, partition(0)))
        .await
        .unwrap();
    coord
        .checkpoint(&lease, PgCursor::new(50, partition(0)))
        .await
        .unwrap();

    coord.release(&lease).await.unwrap();

    let new_lease = coord
        .claim(&s, &owner_b, partition(0), long_lease)
        .await
        .unwrap()
        .expect("should claim after release");
    assert_eq!(new_lease.checkpoint_cursor.unwrap().sequence, 100);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_checkpoint_after_release_returns_ownership_lost() {
    use eventuary_postgres::reader::PgCursor;

    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let lease_dur = std::time::Duration::from_secs(60);

    let lease = coord
        .claim(&s, &owner_a, partition(0), lease_dur)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(lease.generation.get(), 1);

    coord.release(&lease).await.unwrap();

    let err = coord
        .checkpoint(&lease, PgCursor::new(100, partition(0)))
        .await
        .unwrap_err();
    assert!(matches!(err, eventuary_core::Error::OwnershipLost(_)));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_rejects_partition_count_mismatch() {
    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);
    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let p_four = Partition::new(0, NonZeroU32::new(4).unwrap()).unwrap();
    let p_eight = Partition::new(0, NonZeroU32::new(8).unwrap()).unwrap();

    coord
        .claim(&s, &owner_a, p_four, std::time::Duration::from_millis(1))
        .await
        .unwrap()
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(5)).await;

    let err = coord
        .claim(&s, &owner_b, p_eight, std::time::Duration::from_secs(10))
        .await
        .unwrap_err();
    assert!(
        matches!(err, eventuary_core::Error::Config(ref message) if message.contains("partition count mismatch")),
        "expected partition count mismatch error, got {err:?}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pg_coordinator_checkpoint_with_stale_generation_returns_ownership_lost() {
    use eventuary_postgres::reader::PgCursor;

    let (_c, pool) = start_postgres().await;
    let coord = coordinator(pool);

    let s = scope();
    let owner_a = OwnerId::new("worker-a").unwrap();
    let owner_b = OwnerId::new("worker-b").unwrap();
    let short_lease = std::time::Duration::from_millis(50);
    let long_lease = std::time::Duration::from_secs(60);

    let lease_a = coord
        .claim(&s, &owner_a, partition(0), short_lease)
        .await
        .unwrap()
        .unwrap();

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    coord
        .claim(&s, &owner_b, partition(0), long_lease)
        .await
        .unwrap()
        .unwrap();

    let err = coord
        .checkpoint(&lease_a, PgCursor::new(100, partition(0)))
        .await
        .unwrap_err();
    assert!(matches!(err, eventuary_core::Error::OwnershipLost(_)));
}