kafka_client_engine/consumer/group_batch/
checkpoint_builder.rs1use super::{
4 GroupConsumerCheckpoint, GroupConsumerRecord, GroupConsumerRecords,
5 checkpoint::checkpoint_from_delivery_at,
6};
7use crate::consumer::group::ClassicGroupFetchDelivery;
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum GroupConsumerCheckpointMarkErrorKind {
12 ForeignRecord,
14 OutOfOrder,
16}
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct GroupConsumerCheckpointMarkError {
21 kind: GroupConsumerCheckpointMarkErrorKind,
22}
23
24impl GroupConsumerCheckpointMarkError {
25 const fn new(kind: GroupConsumerCheckpointMarkErrorKind) -> Self {
26 Self { kind }
27 }
28
29 pub const fn kind(&self) -> GroupConsumerCheckpointMarkErrorKind {
31 self.kind
32 }
33}
34
35impl std::fmt::Display for GroupConsumerCheckpointMarkError {
36 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 write!(
38 formatter,
39 "group checkpoint record rejected: {:?}",
40 self.kind
41 )
42 }
43}
44
45impl std::error::Error for GroupConsumerCheckpointMarkError {}
46
47#[must_use = "finish the builder to retain its processed-prefix checkpoint"]
49pub struct GroupConsumerCheckpointBuilder<'batch> {
50 delivery: &'batch ClassicGroupFetchDelivery,
51 next_ordinal: usize,
52 next_offset: i64,
53}
54
55impl<'batch> GroupConsumerCheckpointBuilder<'batch> {
56 pub(super) fn new(delivery: &'batch ClassicGroupFetchDelivery) -> Self {
57 let next_offset = GroupConsumerRecords::new(delivery)
58 .next()
59 .map_or_else(|| delivery.next_offset().get(), |record| record.offset());
60 Self {
61 delivery,
62 next_ordinal: 0,
63 next_offset,
64 }
65 }
66
67 pub fn mark_processed(
72 &mut self,
73 record: &GroupConsumerRecord<'_>,
74 ) -> Result<(), GroupConsumerCheckpointMarkError> {
75 if !record.belongs_to(self.delivery) {
76 return Err(GroupConsumerCheckpointMarkError::new(
77 GroupConsumerCheckpointMarkErrorKind::ForeignRecord,
78 ));
79 }
80 if record.ordinal() != self.next_ordinal {
81 return Err(GroupConsumerCheckpointMarkError::new(
82 GroupConsumerCheckpointMarkErrorKind::OutOfOrder,
83 ));
84 }
85 let next_offset = record
86 .offset()
87 .checked_add(1)
88 .unwrap_or_else(|| unreachable!("Fetch normalization rejects next-offset overflow"));
89 self.next_ordinal = self.next_ordinal.saturating_add(1);
90 self.next_offset = next_offset;
91 Ok(())
92 }
93
94 pub fn finish(self) -> GroupConsumerCheckpoint {
99 checkpoint_from_delivery_at(self.delivery, self.next_offset)
100 }
101}
102
103impl std::fmt::Debug for GroupConsumerCheckpointBuilder<'_> {
104 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 formatter
106 .debug_struct("GroupConsumerCheckpointBuilder")
107 .field("topic", &self.delivery.topic())
108 .field("partition", &self.delivery.partition())
109 .field("next_ordinal", &self.next_ordinal)
110 .field("next_offset", &self.next_offset)
111 .finish()
112 }
113}