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;
const REBALANCE_INTERVAL: Duration = Duration::from_millis(200);
const MIN_WAIT: Duration = Duration::from_millis(1);
const MAX_WAIT: Duration = Duration::from_millis(50);
const RECORD_OVERHEAD: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsumerRecord {
pub topic: String,
pub partition: u32,
pub offset: u64,
pub timestamp: i64,
pub key: Option<Vec<u8>>,
pub value: Option<Vec<u8>>,
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
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RebalanceEvent {
Assigned {
topic: String,
partition: u32,
},
Revoked {
topic: String,
partition: u32,
},
}
#[derive(Debug)]
struct Subscription {
name: String,
reader: TopicReader,
}
#[derive(Debug)]
struct OwnedPartition {
topic: usize,
partition: u32,
position: u64,
committed: Option<u64>,
_lock: FileLock,
}
#[derive(Debug)]
pub struct Consumer {
group: String,
paths: GroupPaths,
config: ConsumerConfig,
topics: Vec<Subscription>,
owned: Vec<OwnedPartition>,
next_to_serve: usize,
events: Vec<RebalanceEvent>,
last_rebalance: Option<Instant>,
last_commit: Instant,
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();
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)
}
pub fn group(&self) -> &str {
&self.group
}
pub fn assignment(&self) -> Vec<(String, u32)> {
self.owned
.iter()
.map(|o| (self.topics[o.topic].name.clone(), o.partition))
.collect()
}
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)
}
pub fn take_rebalance_events(&mut self) -> Vec<RebalanceEvent> {
std::mem::take(&mut self.events)
}
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()?;
}
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);
}
}
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)
}
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(())
}
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()
}
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,
});
}
Ok(())
}
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(())
}
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 {
Some(c) if c < start => self.policy_position(start, limit),
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,
}
}
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 { .. }) => {
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 {
fn drop(&mut self) {
if self.config.auto_commit.is_some() {
let _ = self.commit();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Db, LogConfig, Message, Retention, TopicConfig};
const AGE: Duration = Duration::from_millis(300);
const COUNT: u64 = 30;
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)
}
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);
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()]
);
}
}