mojay 0.1.0

Topics, partitions, offsets and consumer groups in a local folder, with no server: SQLite for Kafka
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
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
//! A member of a consumer group: it owns partitions, reads them, and
//! commits its position in each one. It shares the partitions with the
//! other live members, with no coordinator.

use std::path::Path;
use std::thread;
use std::time::{Duration, Instant};

use super::config::{ConsumerConfig, StartFrom};
use super::membership::Membership;
use super::{GroupPaths, offsets, quota};
use crate::error::{Error, Result};
use crate::lock::FileLock;
use crate::record::{Header, Record};
use crate::topic::TopicReader;

/// Delay between two rebalances: this is also the reaction time to
/// a member joining or leaving.
const REBALANCE_INTERVAL: Duration = Duration::from_millis(200);
/// Wait between two checks when there is nothing to read: it doubles
/// from `MIN_WAIT` to `MAX_WAIT` as long as nothing arrives.
const MIN_WAIT: Duration = Duration::from_millis(1);
const MAX_WAIT: Duration = Duration::from_millis(50);
/// Estimated overhead of a record, on top of its key, value and headers.
const RECORD_OVERHEAD: usize = 32;

/// A message read by a consumer, with its origin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsumerRecord {
    /// The topic the message was read from.
    pub topic: String,
    /// Its partition in that topic.
    pub partition: u32,
    /// Its offset in that partition.
    pub offset: u64,
    /// Milliseconds since the epoch: given by the producer, or the local
    /// clock at append time.
    pub timestamp: i64,
    /// The message key, as sent.
    pub key: Option<Vec<u8>>,
    /// The message value, as sent.
    pub value: Option<Vec<u8>>,
    /// The message headers, in order.
    pub headers: Vec<Header>,
}

impl ConsumerRecord {
    fn new(topic: &str, partition: u32, record: Record) -> Self {
        Self {
            topic: topic.to_string(),
            partition,
            offset: record.offset,
            timestamp: record.timestamp,
            key: record.key,
            value: record.value,
            headers: record.headers,
        }
    }

    fn approximate_size(&self) -> usize {
        let len = |b: &Option<Vec<u8>>| b.as_ref().map_or(0, Vec::len);
        let headers: usize = self
            .headers
            .iter()
            .map(|h| h.key.len() + h.value.len())
            .sum();
        RECORD_OVERHEAD + len(&self.key) + len(&self.value) + headers
    }
}

/// A change in the partitions owned by a consumer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RebalanceEvent {
    /// The consumer now owns this partition.
    Assigned {
        /// The topic of the partition.
        topic: String,
        /// The partition number in that topic.
        partition: u32,
    },
    /// The consumer handed this partition over to another group member.
    Revoked {
        /// The topic of the partition.
        topic: String,
        /// The partition number in that topic.
        partition: u32,
    },
}

/// A topic the consumer is subscribed to.
#[derive(Debug)]
struct Subscription {
    name: String,
    reader: TopicReader,
}

/// A partition owned by this consumer: it holds its lock.
#[derive(Debug)]
struct OwnedPartition {
    /// Index into `Consumer::topics`.
    topic: usize,
    partition: u32,
    /// Next offset to return.
    position: u64,
    /// Last committed offset, as it is on disk.
    committed: Option<u64>,
    _lock: FileLock,
}

/// A member of a consumer group.
///
/// The live members of a group share its partitions: each one
/// owns those whose lock it holds, and only it reads them for the group.
/// On each `poll` (at most every 200 ms), a member counts the live members,
/// gives up what it has in excess and takes free partitions if it is short.
///
/// *At-least-once* delivery: after a crash, messages returned since the
/// last commit are read again. A member that stops calling `poll` keeps its
/// partitions for as long as it lives (see [`poll`](Self::poll)).
///
/// Members of the same group must subscribe to the same topics: otherwise the
/// assignment stays correct (never two readers per partition), but is no
/// longer balanced.
#[derive(Debug)]
pub struct Consumer {
    group: String,
    paths: GroupPaths,
    config: ConsumerConfig,
    topics: Vec<Subscription>,
    /// Sorted by (topic, partition).
    owned: Vec<OwnedPartition>,
    /// Partition to start the next `poll` with, so that all
    /// partitions are served in turn.
    next_to_serve: usize,
    events: Vec<RebalanceEvent>,
    last_rebalance: Option<Instant>,
    last_commit: Instant,
    /// Declared after `owned`: partitions are released before leaving the group.
    membership: Membership,
}

impl Consumer {
    pub(crate) fn open(
        groups_dir: &Path,
        group: &str,
        readers: Vec<TopicReader>,
        config: ConsumerConfig,
    ) -> Result<Self> {
        if readers.is_empty() {
            return Err(Error::InvalidConfig(
                "a consumer must subscribe to at least one topic".into(),
            ));
        }
        let mut topics: Vec<Subscription> = readers
            .into_iter()
            .map(|reader| Subscription {
                name: reader.topic().to_string(),
                reader,
            })
            .collect();
        // The same order on every member: it determines the partition order.
        topics.sort_by(|a, b| a.name.cmp(&b.name));
        if topics.windows(2).any(|w| w[0].name == w[1].name) {
            return Err(Error::InvalidConfig(
                "duplicate topic in subscription".into(),
            ));
        }

        let paths = GroupPaths::open(groups_dir, group)?;
        let membership = Membership::join(&paths.dir)?;
        let mut consumer = Self {
            group: group.to_string(),
            paths,
            config,
            topics,
            owned: Vec::new(),
            next_to_serve: 0,
            events: Vec::new(),
            last_rebalance: None,
            last_commit: Instant::now(),
            membership,
        };
        consumer.rebalance()?;
        Ok(consumer)
    }

    /// The name of the group this consumer is a member of.
    pub fn group(&self) -> &str {
        &self.group
    }

    /// The partitions owned by this consumer, sorted.
    pub fn assignment(&self) -> Vec<(String, u32)> {
        self.owned
            .iter()
            .map(|o| (self.topics[o.topic].name.clone(), o.partition))
            .collect()
    }

    /// The next offset this consumer will return for a partition it owns.
    pub fn position(&self, topic: &str, partition: u32) -> Option<u64> {
        self.owned
            .iter()
            .find(|o| o.partition == partition && self.topics[o.topic].name == topic)
            .map(|o| o.position)
    }

    /// The partitions received or handed over since the last call, in order.
    ///
    /// With manual commit, a handed-over partition resumes at its new
    /// owner from the last commit: committing before each `poll` avoids these re-reads.
    pub fn take_rebalance_events(&mut self) -> Vec<RebalanceEvent> {
        std::mem::take(&mut self.events)
    }

    /// Waits at most `timeout` for messages, and returns them as soon as there are any.
    ///
    /// Returns an empty list if nothing arrived in time. The partitions of
    /// each `poll` are served in turn, so that none is starved.
    ///
    /// `poll` is also when this member takes part in the group: there is no
    /// background thread. At most every 200 ms, while it runs, the member
    /// gives up its surplus partitions to newcomers and takes free ones.
    /// A member that stops calling `poll` keeps its partitions, and a new
    /// member gets none of them until it polls again, closes or dies. Call
    /// `poll` regularly, even with a short timeout, or drop the consumer
    /// when it stops reading.
    ///
    /// # Errors
    ///
    /// - [`Error::Corrupt`] if a partition's data is unreadable.
    /// - [`Error::Io`] on a file system error, including an automatic
    ///   commit that fails.
    pub fn poll(&mut self, timeout: Duration) -> Result<Vec<ConsumerRecord>> {
        self.auto_commit_if_due()?;
        let deadline = Instant::now() + timeout;
        let mut wait = MIN_WAIT;
        loop {
            if self.rebalance_is_due() {
                self.rebalance()?;
            }
            // Even with nothing to read: an idle consumer must not keep
            // segments deleted by retention open.
            for topic in &mut self.topics {
                topic.reader.release_deleted_segments()?;
            }
            let records = self.fetch()?;
            if !records.is_empty() {
                return Ok(records);
            }
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                return Ok(records);
            }
            thread::sleep(wait.min(left));
            wait = (wait * 2).min(MAX_WAIT);
        }
    }

    /// Commits the position of each owned partition: all messages
    /// already returned by `poll` are considered processed.
    ///
    /// Each offset is written atomically and durably. Only partitions
    /// still owned are committed: a handed-over partition
    /// belongs to its new owner.
    pub fn commit(&mut self) -> Result<()> {
        for i in 0..self.owned.len() {
            self.commit_owned(i)?;
        }
        self.last_commit = Instant::now();
        Ok(())
    }

    fn commit_owned(&mut self, i: usize) -> Result<()> {
        let owned = &mut self.owned[i];
        if owned.committed != Some(owned.position) {
            let path = self
                .paths
                .committed_offset(&self.topics[owned.topic].name, owned.partition);
            offsets::write(&path, owned.position)?;
            owned.committed = Some(owned.position);
        }
        Ok(())
    }

    fn auto_commit_if_due(&mut self) -> Result<()> {
        match self.config.auto_commit {
            Some(every) if self.last_commit.elapsed() >= every => self.commit(),
            _ => Ok(()),
        }
    }

    fn rebalance_is_due(&self) -> bool {
        self.last_rebalance
            .is_none_or(|at| at.elapsed() >= REBALANCE_INTERVAL)
    }

    /// Adjusts the owned partitions to this member's share: gives up the
    /// surplus, then takes free partitions if some are missing.
    fn rebalance(&mut self) -> Result<()> {
        self.last_rebalance = Some(Instant::now());
        let members = self.membership.living_members()?;
        let rank = members
            .iter()
            .position(|m| m == self.membership.id())
            .unwrap_or(members.len());
        let all = self.all_partitions();
        let quota = quota::quota(all.len(), members.len(), rank);

        while self.owned.len() > quota {
            self.release_last()?;
        }
        if self.owned.len() < quota {
            let start = quota::claim_start(all.len(), members.len(), rank);
            for k in 0..all.len() {
                if self.owned.len() >= quota {
                    break;
                }
                let (topic, partition) = all[(start + k) % all.len()];
                self.try_claim(topic, partition)?;
            }
            self.owned.sort_by_key(|o| (o.topic, o.partition));
        }
        Ok(())
    }

    /// All partitions of the subscribed topics, in the same order on every
    /// member (topics sorted by name).
    fn all_partitions(&self) -> Vec<(usize, u32)> {
        self.topics
            .iter()
            .enumerate()
            .flat_map(|(t, sub)| (0..sub.reader.partitions()).map(move |p| (t, p)))
            .collect()
    }

    /// Gives up the last owned partition. With automatic commit, its
    /// position is committed *before* releasing the lock: the next member
    /// resumes exactly there, with no duplicates.
    fn release_last(&mut self) -> Result<()> {
        let last = self.owned.len() - 1;
        if self.config.auto_commit.is_some() {
            self.commit_owned(last)?;
        }
        if let Some(owned) = self.owned.pop() {
            self.events.push(RebalanceEvent::Revoked {
                topic: self.topics[owned.topic].name.clone(),
                partition: owned.partition,
            });
            // The lock is released here, by dropping `owned`.
        }
        Ok(())
    }

    /// Takes the partition if it is free, and resumes at its committed offset.
    /// The offset is read *after* taking the lock: the previous member has
    /// finished writing its own before releasing.
    fn try_claim(&mut self, topic: usize, partition: u32) -> Result<()> {
        if self
            .owned
            .iter()
            .any(|o| o.topic == topic && o.partition == partition)
        {
            return Ok(());
        }
        let name = &self.topics[topic].name;
        let Some(lock) = FileLock::try_exclusive(&self.paths.partition_lock(name, partition))?
        else {
            return Ok(());
        };
        let committed = offsets::read(&self.paths.committed_offset(name, partition))?;
        let position = self.start_position(topic, partition, committed)?;
        self.events.push(RebalanceEvent::Assigned {
            topic: name.clone(),
            partition,
        });
        self.owned.push(OwnedPartition {
            topic,
            partition,
            position,
            committed,
            _lock: lock,
        });
        Ok(())
    }

    /// Where to resume a partition, based on the committed offset if it is usable.
    fn start_position(&self, topic: usize, partition: u32, committed: Option<u64>) -> Result<u64> {
        let reader = &self.topics[topic].reader;
        let start = reader.start_offset(partition)?;
        let limit = reader.read_limit(partition)?;
        Ok(match committed {
            // Deleted by retention: apply the start policy.
            Some(c) if c < start => self.policy_position(start, limit),
            // Beyond the limit (messages lost with a non-guaranteeing fsync
            // policy): resume at the limit, without skipping any new message.
            Some(c) => c.min(limit),
            None => self.policy_position(start, limit),
        })
    }

    fn policy_position(&self, start: u64, limit: u64) -> u64 {
        match self.config.start_from {
            StartFrom::Earliest => start,
            StartFrom::Latest => limit,
        }
    }

    /// Reads what is available in the owned partitions, in turn,
    /// within the `max_poll_bytes` limit.
    fn fetch(&mut self) -> Result<Vec<ConsumerRecord>> {
        let count = self.owned.len();
        let mut out = Vec::new();
        let mut budget = self.config.max_poll_bytes;
        for k in 0..count {
            if !out.is_empty() && budget == 0 {
                break;
            }
            let i = (self.next_to_serve + k) % count;
            let (topic, partition) = (self.owned[i].topic, self.owned[i].partition);
            let records = match self.read_owned(i, budget) {
                Err(Error::OffsetOutOfRange { .. }) => {
                    // Retention deleted the position: apply the start policy.
                    self.owned[i].position = self.start_position(topic, partition, None)?;
                    continue;
                }
                other => other?,
            };
            for record in records {
                let record = ConsumerRecord::new(&self.topics[topic].name, partition, record);
                budget = budget.saturating_sub(record.approximate_size());
                self.owned[i].position = record.offset + 1;
                out.push(record);
            }
        }
        if count > 0 {
            self.next_to_serve = (self.next_to_serve + 1) % count;
        }
        Ok(out)
    }

    fn read_owned(&mut self, i: usize, budget: usize) -> Result<Vec<Record>> {
        let owned = &self.owned[i];
        let reader = &mut self.topics[owned.topic].reader;
        if owned.position >= reader.read_limit(owned.partition)? {
            return Ok(Vec::new());
        }
        reader.read(owned.partition, owned.position, budget)
    }
}

impl Drop for Consumer {
    /// With automatic commit, commits before releasing the partitions:
    /// the next member resumes exactly where this one stopped.
    /// The partitions are then released, then the member leaves the group.
    fn drop(&mut self) {
        if self.config.auto_commit.is_some() {
            // An error here can no longer be returned: at worst, messages
            // since the last commit will be read again (at-least-once).
            let _ = self.commit();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Db, LogConfig, Message, Retention, TopicConfig};

    /// Small segments whose sealed ones expire after `AGE`.
    const AGE: Duration = Duration::from_millis(300);
    const COUNT: u64 = 30;

    /// A topic whose first partition holds `COUNT` messages over several
    /// segments, all younger than `AGE`.
    fn topic_with_segments(partitions: u32) -> (tempfile::TempDir, Db) {
        let dir = tempfile::TempDir::new().unwrap();
        let db = Db::open(dir.path()).unwrap();
        let log = LogConfig {
            segment_max_bytes: 256,
            retention: Retention {
                max_bytes: None,
                max_age: Some(AGE),
            },
            ..LogConfig::default()
        };
        db.create_topic("t", TopicConfig { partitions, log })
            .unwrap();
        let mut producer = db.producer("t").unwrap();
        for i in 0..COUNT {
            producer
                .send_to(0, &Message::new("k", format!("value-{i}")))
                .unwrap();
        }
        (dir, db)
    }

    /// Lets the sealed segments expire, then has a producer delete them
    /// (opening it is enough: it applies retention).
    fn expire_sealed_segments(db: &Db) {
        thread::sleep(AGE + Duration::from_millis(100));
        let mut producer = db.producer("t").unwrap();
        producer.enforce_retention().unwrap();
        assert!(db.reader("t").unwrap().start_offset(0).unwrap() > 0);
    }

    #[test]
    fn idle_consumer_releases_segments_deleted_by_retention() {
        let (_dir, db) = topic_with_segments(1);
        let mut consumer = db.consumer("g", &["t"], ConsumerConfig::default()).unwrap();
        let mut read = 0;
        while read < COUNT {
            read += consumer.poll(Duration::from_secs(1)).unwrap().len() as u64;
        }
        let reader = &consumer.topics[0].reader;
        assert!(reader.open_segment_bases(0).len() > 1);

        expire_sealed_segments(&db);
        // Nothing new to read: the consumer stays at the read limit.
        assert!(
            consumer
                .poll(Duration::from_millis(600))
                .unwrap()
                .is_empty()
        );
        let reader = &consumer.topics[0].reader;
        assert_eq!(
            reader.open_segment_bases(0),
            vec![reader.start_offset(0).unwrap()],
            "only the active segment is still open"
        );
    }

    #[test]
    fn reading_one_partition_releases_deleted_segments_of_the_others() {
        let (_dir, db) = topic_with_segments(2);
        let mut reader = db.reader("t").unwrap();
        assert!(reader.open_segment_bases(0).len() > 1);

        expire_sealed_segments(&db);
        thread::sleep(Duration::from_millis(500));
        assert!(reader.read(1, 0, usize::MAX).unwrap().is_empty());
        assert_eq!(
            reader.open_segment_bases(0),
            vec![reader.start_offset(0).unwrap()]
        );
    }
}