eventuary-sqlite 0.3.0-rc.1

SQLite event backend for eventuary
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use std::collections::HashSet;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;

use futures::StreamExt;
use tokio::time::timeout;

use eventuary_core::io::reader::CheckpointScope;
use eventuary_core::io::{ConsumerGroupId, OwnerId, Reader, StreamId, Writer};
use eventuary_core::partition::{EventKeyPartitionKeyResolver, Fnv1a64PartitionHasher};
use eventuary_core::{Event, Payload, StartFrom};
use eventuary_sqlite::coordinator::{SqlitePartitionCoordinator, SqlitePartitionCoordinatorConfig};
use eventuary_sqlite::database::{SqliteConn, SqliteDatabase};
use eventuary_sqlite::reader::{
    SqliteCoordinatedReader, SqliteCoordinatedReaderConfig, SqliteCoordinatedSubscription,
    SqliteReader, SqliteReaderConfig, SqliteSubscription,
};
use eventuary_sqlite::writer::{SqlitePartitioningConfig, SqliteWriter, SqliteWriterConfig};

fn prepare_test_schema(conn: &SqliteConn) {
    SqliteWriter::prepare_schema(conn, &SqliteWriterConfig::default()).unwrap();
    SqlitePartitionCoordinator::prepare_schema(conn, &SqlitePartitionCoordinatorConfig::default())
        .unwrap();
}

fn event_with_key(key: &str) -> Event {
    Event::builder(
        "acme",
        "/orders",
        "order.placed",
        key,
        Payload::from_string("{}"),
    )
    .unwrap()
    .build()
    .unwrap()
}

#[tokio::test]
async fn sqlite_coordinated_reader_claims_and_delivers_partition_events() {
    let partition_count = NonZeroU32::new(4).unwrap();

    let db = SqliteDatabase::open_in_memory().unwrap();
    prepare_test_schema(&db.conn());

    let writer = SqliteWriter::new_with_config(
        db.conn(),
        SqliteWriterConfig {
            partitioning: SqlitePartitioningConfig::inline(
                partition_count,
                EventKeyPartitionKeyResolver::new(),
                Fnv1a64PartitionHasher,
            ),
            ..SqliteWriterConfig::default()
        },
    );

    for key in ["k0", "k1", "k2", "k3"] {
        writer.write(&event_with_key(key)).await.unwrap();
    }

    let coordinator = Arc::new(SqlitePartitionCoordinator::new(
        db.conn(),
        SqlitePartitionCoordinatorConfig::default(),
    ));

    let reader = SqliteCoordinatedReader::new(
        SqliteReader::new(
            db.conn(),
            SqliteReaderConfig {
                poll_interval: Duration::from_millis(20),
                ..SqliteReaderConfig::default()
            },
        ),
        Arc::clone(&coordinator),
        OwnerId::generate(),
        SqliteCoordinatedReaderConfig {
            rebalance_interval: Duration::from_millis(100),
            partition_lease_duration: Duration::from_secs(10),
            ..SqliteCoordinatedReaderConfig::default()
        },
    );

    let subscription = SqliteCoordinatedSubscription {
        inner: SqliteSubscription {
            start: StartFrom::Earliest,
            ..SqliteSubscription::default()
        },
        scope: CheckpointScope::new(
            ConsumerGroupId::new("sqlite-projection").unwrap(),
            StreamId::new("sqlite-events").unwrap(),
        ),
        partition_count,
        start: StartFrom::Earliest,
    };

    let mut stream = reader.read(subscription).await.unwrap();

    let mut count = 0usize;
    while let Ok(Some(Ok(msg))) = timeout(Duration::from_secs(5), stream.next()).await {
        assert_eq!(
            msg.cursor().partition.count(),
            partition_count.get(),
            "expected partition count to match"
        );
        // Cursor partition correctness: the partition stamped on the
        // outer cursor must match the partition stamped on the inner
        // source cursor (the writer's persisted partition_id). The
        // shared-fetch data plane routes by the inner cursor's
        // partition, so this is the single source of truth.
        assert_eq!(
            msg.cursor().partition.id(),
            msg.cursor().inner.inner().partition.id(),
            "outer partition must match inner source partition"
        );
        msg.ack().await.unwrap();
        count += 1;
        if count == 4 {
            break;
        }
    }

    assert_eq!(count, 4, "expected all 4 events to be delivered");
}

#[tokio::test]
async fn sqlite_coordinated_reader_fresh_latest_skips_existing_events() {
    let partition_count = NonZeroU32::new(4).unwrap();
    let db = SqliteDatabase::open_in_memory().unwrap();
    prepare_test_schema(&db.conn());

    let writer = SqliteWriter::new_with_config(
        db.conn(),
        SqliteWriterConfig {
            partitioning: SqlitePartitioningConfig::inline(
                partition_count,
                EventKeyPartitionKeyResolver::new(),
                Fnv1a64PartitionHasher,
            ),
            ..SqliteWriterConfig::default()
        },
    );

    writer.write(&event_with_key("old-1")).await.unwrap();
    writer.write(&event_with_key("old-2")).await.unwrap();

    let coordinator = Arc::new(SqlitePartitionCoordinator::new(
        db.conn(),
        SqlitePartitionCoordinatorConfig::default(),
    ));

    let reader = SqliteCoordinatedReader::new(
        SqliteReader::new(
            db.conn(),
            SqliteReaderConfig {
                poll_interval: Duration::from_millis(20),
                ..SqliteReaderConfig::default()
            },
        ),
        Arc::clone(&coordinator),
        OwnerId::new("fresh-latest-owner").unwrap(),
        SqliteCoordinatedReaderConfig {
            rebalance_interval: Duration::from_millis(50),
            partition_lease_duration: Duration::from_secs(10),
            partition_slack: 0,
            ..SqliteCoordinatedReaderConfig::default()
        },
    );

    let subscription = SqliteCoordinatedSubscription {
        inner: SqliteSubscription::default(),
        scope: CheckpointScope::new(
            ConsumerGroupId::new("fresh-latest-group").unwrap(),
            StreamId::new("sqlite-events").unwrap(),
        ),
        partition_count,
        start: StartFrom::Latest,
    };

    let mut stream = reader.read(subscription).await.unwrap();
    tokio::time::sleep(Duration::from_millis(200)).await;

    writer.write(&event_with_key("new-1")).await.unwrap();

    let mut delivered = Vec::new();
    while let Ok(Some(Ok(msg))) = timeout(Duration::from_secs(3), stream.next()).await {
        let key = msg.event().key().as_str().to_owned();
        msg.ack().await.unwrap();
        delivered.push(key);
        if delivered.len() == 1 {
            break;
        }
    }

    assert_eq!(delivered, vec!["new-1".to_owned()]);
}

#[tokio::test]
async fn sqlite_coordinated_reader_fresh_timestamp_skips_pre_cutoff_events() {
    let partition_count = NonZeroU32::new(4).unwrap();
    let db = SqliteDatabase::open_in_memory().unwrap();
    prepare_test_schema(&db.conn());

    let writer = SqliteWriter::new_with_config(
        db.conn(),
        SqliteWriterConfig {
            partitioning: SqlitePartitioningConfig::inline(
                partition_count,
                EventKeyPartitionKeyResolver::new(),
                Fnv1a64PartitionHasher,
            ),
            ..SqliteWriterConfig::default()
        },
    );

    writer
        .write(&event_with_key("old-before-cutoff"))
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(20)).await;
    let cutoff = chrono::Utc::now();
    tokio::time::sleep(Duration::from_millis(20)).await;
    writer
        .write(&event_with_key("new-after-cutoff"))
        .await
        .unwrap();

    let coordinator = Arc::new(SqlitePartitionCoordinator::new(
        db.conn(),
        SqlitePartitionCoordinatorConfig::default(),
    ));

    let reader = SqliteCoordinatedReader::new(
        SqliteReader::new(
            db.conn(),
            SqliteReaderConfig {
                poll_interval: Duration::from_millis(20),
                ..SqliteReaderConfig::default()
            },
        ),
        Arc::clone(&coordinator),
        OwnerId::new("fresh-timestamp-owner").unwrap(),
        SqliteCoordinatedReaderConfig {
            rebalance_interval: Duration::from_millis(50),
            partition_lease_duration: Duration::from_secs(10),
            partition_slack: 0,
            ..SqliteCoordinatedReaderConfig::default()
        },
    );

    let subscription = SqliteCoordinatedSubscription {
        inner: SqliteSubscription::default(),
        scope: CheckpointScope::new(
            ConsumerGroupId::new("fresh-timestamp-group").unwrap(),
            StreamId::new("sqlite-events").unwrap(),
        ),
        partition_count,
        start: StartFrom::Timestamp(cutoff),
    };

    let mut stream = reader.read(subscription).await.unwrap();

    let mut delivered = Vec::new();
    while let Ok(Some(Ok(msg))) = timeout(Duration::from_secs(3), stream.next()).await {
        let key = msg.event().key().as_str().to_owned();
        msg.ack().await.unwrap();
        delivered.push(key);
        if delivered.len() == 1 {
            break;
        }
    }

    assert_eq!(delivered, vec!["new-after-cutoff".to_owned()]);
}

#[tokio::test]
async fn sqlite_coordinated_reader_persists_checkpoint_on_ack() {
    let partition_count = NonZeroU32::new(4).unwrap();

    let db = SqliteDatabase::open_in_memory().unwrap();
    prepare_test_schema(&db.conn());

    let writer = SqliteWriter::new_with_config(
        db.conn(),
        SqliteWriterConfig {
            partitioning: SqlitePartitioningConfig::inline(
                partition_count,
                EventKeyPartitionKeyResolver::new(),
                Fnv1a64PartitionHasher,
            ),
            ..SqliteWriterConfig::default()
        },
    );

    for key in ["k0", "k1", "k2", "k3"] {
        writer.write(&event_with_key(key)).await.unwrap();
    }

    let coordinator = Arc::new(SqlitePartitionCoordinator::new(
        db.conn(),
        SqlitePartitionCoordinatorConfig::default(),
    ));

    let scope = CheckpointScope::new(
        ConsumerGroupId::new("checkpoint-test").unwrap(),
        StreamId::new("orders").unwrap(),
    );

    let reader = SqliteCoordinatedReader::new(
        SqliteReader::new(
            db.conn(),
            SqliteReaderConfig {
                poll_interval: Duration::from_millis(20),
                ..SqliteReaderConfig::default()
            },
        ),
        Arc::clone(&coordinator),
        OwnerId::new("owner-1").unwrap(),
        SqliteCoordinatedReaderConfig {
            rebalance_interval: Duration::from_millis(100),
            partition_lease_duration: Duration::from_secs(10),
            ..SqliteCoordinatedReaderConfig::default()
        },
    );

    let sub = SqliteCoordinatedSubscription {
        scope: scope.clone(),
        partition_count,
        start: StartFrom::Earliest,
        inner: SqliteSubscription::default(),
    };

    let mut stream = reader.read(sub).await.unwrap();

    for _ in 0..4 {
        let msg = timeout(Duration::from_secs(5), stream.next())
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        msg.ack().await.unwrap();
    }

    // Stream drop triggers release, but checkpoints are already committed
    // Query the partitions table to verify checkpoints were persisted
    let conn = db.conn();
    let guard = conn.lock().unwrap();
    let mut stmt = guard
        .prepare(
            "SELECT checkpoint_sequence FROM event_stream_partitions \
                   WHERE consumer_group_id = ?1 AND stream_id = ?2",
        )
        .unwrap();
    let checkpoints: Vec<i64> = stmt
        .query_map(rusqlite::params!["checkpoint-test", "orders"], |r| {
            r.get::<_, i64>(0)
        })
        .unwrap()
        .filter_map(|r| r.ok())
        .collect();
    drop(stmt);
    drop(guard);

    assert!(
        !checkpoints.is_empty(),
        "expected at least one checkpoint entry"
    );
    assert!(
        checkpoints.iter().all(|s| *s > 0),
        "all partitions should have checkpoint_sequence > 0; got {checkpoints:?}"
    );
}

#[tokio::test]
async fn sqlite_coordinated_reader_resumes_from_checkpoint_on_restart() {
    let partition_count = NonZeroU32::new(4).unwrap();

    let db = SqliteDatabase::open_in_memory().unwrap();
    prepare_test_schema(&db.conn());

    let writer = SqliteWriter::new_with_config(
        db.conn(),
        SqliteWriterConfig {
            partitioning: SqlitePartitioningConfig::inline(
                partition_count,
                EventKeyPartitionKeyResolver::new(),
                Fnv1a64PartitionHasher,
            ),
            ..SqliteWriterConfig::default()
        },
    );

    let keys = [
        "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta",
    ];
    for key in &keys {
        writer.write(&event_with_key(key)).await.unwrap();
    }

    let coordinator = Arc::new(SqlitePartitionCoordinator::new(
        db.conn(),
        SqlitePartitionCoordinatorConfig::default(),
    ));

    let scope = CheckpointScope::new(
        ConsumerGroupId::new("resume-group").unwrap(),
        StreamId::new("orders").unwrap(),
    );

    let reader_config = SqliteCoordinatedReaderConfig {
        partition_lease_duration: Duration::from_secs(60),
        partition_renew_interval: Duration::from_secs(15),
        consumer_lease_duration: Duration::from_secs(30),
        consumer_heartbeat_interval: Duration::from_secs(10),
        rebalance_interval: Duration::from_millis(100),
        partition_slack: 0,
        ..SqliteCoordinatedReaderConfig::default()
    };

    let make_sub = || SqliteCoordinatedSubscription {
        scope: scope.clone(),
        partition_count,
        start: StartFrom::Earliest,
        inner: SqliteSubscription::default(),
    };

    let mut acked_keys: Vec<String> = Vec::new();

    {
        let reader = SqliteCoordinatedReader::new(
            SqliteReader::new(
                db.conn(),
                SqliteReaderConfig {
                    poll_interval: Duration::from_millis(20),
                    ..SqliteReaderConfig::default()
                },
            ),
            Arc::clone(&coordinator),
            OwnerId::new("owner-1").unwrap(),
            reader_config,
        );

        let mut stream = reader.read(make_sub()).await.unwrap();

        for _ in 0..4 {
            let msg = timeout(Duration::from_secs(5), stream.next())
                .await
                .unwrap()
                .unwrap()
                .unwrap();
            acked_keys.push(msg.event().key().as_str().to_owned());
            msg.ack().await.unwrap();
        }
    }

    tokio::time::sleep(Duration::from_millis(300)).await;

    let mut resumed_keys: Vec<String> = Vec::new();

    {
        let reader2 = SqliteCoordinatedReader::new(
            SqliteReader::new(
                db.conn(),
                SqliteReaderConfig {
                    poll_interval: Duration::from_millis(20),
                    ..SqliteReaderConfig::default()
                },
            ),
            Arc::clone(&coordinator),
            OwnerId::new("owner-2").unwrap(),
            reader_config,
        );

        let mut stream2 = reader2.read(make_sub()).await.unwrap();

        while let Ok(Some(Ok(msg))) = timeout(Duration::from_secs(5), stream2.next()).await {
            resumed_keys.push(msg.event().key().as_str().to_owned());
            msg.ack().await.unwrap();
            if resumed_keys.len() >= 4 {
                break;
            }
        }
    }

    let acked_set: HashSet<&String> = acked_keys.iter().collect();
    let resumed_set: HashSet<&String> = resumed_keys.iter().collect();
    let overlap: HashSet<_> = acked_set.intersection(&resumed_set).collect();
    assert!(
        overlap.is_empty(),
        "resumed reader should not re-deliver already-acked events; overlap={overlap:?}"
    );

    let all_keys: HashSet<&str> = keys.iter().copied().collect();
    let mut combined: HashSet<String> = acked_keys.into_iter().collect();
    combined.extend(resumed_keys);
    assert_eq!(
        combined.len(),
        8,
        "combined total should be 8; got {}",
        combined.len()
    );
    for key in &all_keys {
        assert!(
            combined.contains(*key),
            "missing event key={key}; combined={combined:?}"
        );
    }
}

/// Exercises the shared-fetch rebalance path: a second consumer joins
/// after the first has claimed all partitions, the coordinator
/// reassigns half of them, and the combined delivery still covers
/// every event written after the join.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn sqlite_coordinated_reader_rebalances_when_second_owner_joins() {
    use std::sync::Mutex as StdMutex;

    let partition_count = NonZeroU32::new(4).unwrap();
    let db = SqliteDatabase::open_in_memory().unwrap();
    prepare_test_schema(&db.conn());

    let writer = SqliteWriter::new_with_config(
        db.conn(),
        SqliteWriterConfig {
            partitioning: SqlitePartitioningConfig::inline(
                partition_count,
                EventKeyPartitionKeyResolver::new(),
                Fnv1a64PartitionHasher,
            ),
            ..SqliteWriterConfig::default()
        },
    );

    let coordinator = Arc::new(SqlitePartitionCoordinator::new(
        db.conn(),
        SqlitePartitionCoordinatorConfig::default(),
    ));

    let scope = CheckpointScope::new(
        ConsumerGroupId::new("rebalance-group").unwrap(),
        StreamId::new("sqlite-events").unwrap(),
    );

    let reader_config = SqliteCoordinatedReaderConfig {
        partition_lease_duration: Duration::from_secs(10),
        partition_renew_interval: Duration::from_millis(200),
        consumer_lease_duration: Duration::from_secs(10),
        consumer_heartbeat_interval: Duration::from_millis(100),
        rebalance_interval: Duration::from_millis(100),
        partition_slack: 0,
        ..SqliteCoordinatedReaderConfig::default()
    };

    let make_sub = || SqliteCoordinatedSubscription {
        scope: scope.clone(),
        partition_count,
        start: StartFrom::Earliest,
        inner: SqliteSubscription::default(),
    };

    let reader_a = SqliteCoordinatedReader::new(
        SqliteReader::new(
            db.conn(),
            SqliteReaderConfig {
                poll_interval: Duration::from_millis(20),
                ..SqliteReaderConfig::default()
            },
        ),
        Arc::clone(&coordinator),
        OwnerId::new("rebalance-a").unwrap(),
        reader_config,
    );
    let stream_a = reader_a.read(make_sub()).await.unwrap();
    let a_keys: Arc<StdMutex<HashSet<String>>> = Arc::new(StdMutex::new(HashSet::new()));
    let a_keys_in = Arc::clone(&a_keys);
    let drain_a = tokio::spawn(async move {
        let mut stream = stream_a;
        while let Ok(Some(Ok(msg))) = timeout(Duration::from_secs(3), stream.next()).await {
            let key = msg.event().key().as_str().to_owned();
            // The rebalance releases partitions while in-flight messages
            // may still be on their way to ack, which is the documented
            // fenced-checkpoint behavior. Swallow OwnershipLost on ack so
            // the test focuses on the combined delivery invariant.
            let _ = msg.ack().await;
            a_keys_in.lock().unwrap().insert(key);
        }
    });

    // Give A time to claim all 4 partitions.
    tokio::time::sleep(Duration::from_millis(400)).await;

    // Start B; rebalance will reassign 2 partitions to B.
    let reader_b = SqliteCoordinatedReader::new(
        SqliteReader::new(
            db.conn(),
            SqliteReaderConfig {
                poll_interval: Duration::from_millis(20),
                ..SqliteReaderConfig::default()
            },
        ),
        Arc::clone(&coordinator),
        OwnerId::new("rebalance-b").unwrap(),
        reader_config,
    );
    let stream_b = reader_b.read(make_sub()).await.unwrap();
    let b_keys: Arc<StdMutex<HashSet<String>>> = Arc::new(StdMutex::new(HashSet::new()));
    let b_keys_in = Arc::clone(&b_keys);
    let drain_b = tokio::spawn(async move {
        let mut stream = stream_b;
        while let Ok(Some(Ok(msg))) = timeout(Duration::from_secs(3), stream.next()).await {
            let key = msg.event().key().as_str().to_owned();
            let _ = msg.ack().await;
            b_keys_in.lock().unwrap().insert(key);
        }
    });

    // Give the rebalance time to settle before writing events.
    tokio::time::sleep(Duration::from_millis(600)).await;

    let keys: Vec<String> = (0..32).map(|i| format!("post-{i}")).collect();
    for key in &keys {
        writer.write(&event_with_key(key)).await.unwrap();
    }

    let _ = tokio::join!(drain_a, drain_b);

    let a = a_keys.lock().unwrap().clone();
    let b = b_keys.lock().unwrap().clone();
    let combined: HashSet<String> = a.union(&b).cloned().collect();

    let all: HashSet<String> = keys.iter().cloned().collect();
    let missing: Vec<&String> = all.difference(&combined).collect();
    assert!(
        missing.is_empty(),
        "events missing from delivery after rebalance: {missing:?}"
    );

    // Both owners should have observed at least one post-join event.
    let a_post: usize = a.iter().filter(|k| k.starts_with("post-")).count();
    let b_post: usize = b.iter().filter(|k| k.starts_with("post-")).count();
    assert!(
        a_post > 0 && b_post > 0,
        "expected both owners to deliver post-rebalance events; a={a_post} b={b_post}"
    );
}