Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ingestion-consumer): demux polls into groups (#92585)

José Sequeira01d42032d4b8
diff --git a/rust/common/kafka-consumer/README.md b/rust/common/kafka-consumer/README.md
index 1e293335eb5e..dda9dd55eda2 100644
--- a/rust/common/kafka-consumer/README.md
+++ b/rust/common/kafka-consumer/README.md
@@ -5,6 +5,7 @@ Kafka consumption primitives shared by stateful services.
## Modules
- `config`: `ConsumerConfigBuilder`, the rdkafka `ClientConfig` builder with PostHog consumer defaults.
-- `types`: `Offset`.
+- `types`: `Offset` and `Partition`.
+- `accumulator`: `Group`, one routing key's messages from one poll on one partition, and `Accumulator`, the demux that builds a poll's groups.
- `charge`: `Charge`, a message's cost (events and bytes) against consumer admission budgets.
- `ledger`: `OffsetLedger`, offset accounting scoped to one partition assignment: completion in any order, an observable contiguous frontier, and explicit consumption at commit points.
diff --git a/rust/common/kafka-consumer/src/accumulator.rs b/rust/common/kafka-consumer/src/accumulator.rs
new file mode 100644
index 000000000000..509cf2002ecc
--- /dev/null
+++ b/rust/common/kafka-consumer/src/accumulator.rs
@@ -0,0 +1,175 @@
+use std::collections::HashMap;
+use std::hash::Hash;
+
+use crate::types::{Offset, Partition};
+
+/// One polled message as the demux sees it. The crate never reads `inner`.
+#[derive(Debug)]
+pub struct PolledMessage<K, M> {
+ pub offset: Offset,
+ /// The routing key. `None` owes no order to any other message and forms
+ /// a group of its own.
+ pub key: Option<K>,
+ pub inner: M,
+}
+
+/// One message in a group, paired with its offset so the two cannot diverge.
+#[derive(Debug)]
+pub struct GroupMessage<M> {
+ pub offset: Offset,
+ pub message: M,
+}
+
+/// One key's messages from one poll on one partition, or one keyless message
+/// on its own. Messages keep submission order; ordering by offset is the
+/// caller's contract, not the accumulator's.
+#[derive(Debug)]
+pub struct Group<K, M> {
+ pub partition: Partition,
+ pub key: Option<K>,
+ pub messages: Vec<GroupMessage<M>>,
+}
+
+impl<K, M> Group<K, M> {
+ pub fn len(&self) -> usize {
+ self.messages.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.messages.is_empty()
+ }
+}
+
+/// Demuxes one poll into groups. Push messages in delivery order: a keyed
+/// message joins its partition's group for that key, a keyless message opens
+/// a group of its own. Groups come out in first-seen order, and each group
+/// keeps its messages in submission order.
+#[derive(Debug)]
+pub struct Accumulator<K, M> {
+ groups: Vec<Group<K, M>>,
+ /// Nested rather than keyed by `(Partition, K)`, so a lookup borrows the
+ /// key instead of cloning it per message.
+ group_index_by_key: HashMap<Partition, HashMap<K, usize>>,
+ message_count: usize,
+}
+
+impl<K, M> Default for Accumulator<K, M> {
+ fn default() -> Self {
+ Self {
+ groups: Vec::new(),
+ group_index_by_key: HashMap::new(),
+ message_count: 0,
+ }
+ }
+}
+
+impl<K: Hash + Eq + Clone, M> Accumulator<K, M> {
+ pub fn push(&mut self, partition: Partition, message: PolledMessage<K, M>) {
+ let PolledMessage { offset, key, inner } = message;
+ let index = match key {
+ None => {
+ self.groups.push(Group {
+ partition,
+ key: None,
+ messages: Vec::with_capacity(1),
+ });
+ self.groups.len() - 1
+ }
+ Some(key) => {
+ let group_index_by_key = self.group_index_by_key.entry(partition).or_default();
+ match group_index_by_key.get(&key) {
+ Some(&index) => index,
+ None => {
+ let index = self.groups.len();
+ self.groups.push(Group {
+ partition,
+ key: Some(key.clone()),
+ messages: Vec::new(),
+ });
+ group_index_by_key.insert(key, index);
+ index
+ }
+ }
+ }
+ };
+ self.groups[index].messages.push(GroupMessage {
+ offset,
+ message: inner,
+ });
+ self.message_count += 1;
+ }
+
+ pub fn message_count(&self) -> usize {
+ self.message_count
+ }
+
+ pub fn into_groups(self) -> Vec<Group<K, M>> {
+ self.groups
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn push(
+ acc: &mut Accumulator<&'static str, i64>,
+ partition: i32,
+ offset: i64,
+ key: Option<&'static str>,
+ ) {
+ acc.push(
+ Partition(partition),
+ PolledMessage {
+ offset: Offset(offset),
+ key,
+ inner: offset,
+ },
+ );
+ }
+
+ fn offsets<K>(group: &Group<K, i64>) -> Vec<Offset> {
+ group.messages.iter().map(|m| m.offset).collect()
+ }
+
+ #[test]
+ fn keyed_messages_group_per_partition_and_key_in_submission_order() {
+ let mut acc = Accumulator::default();
+ push(&mut acc, 0, 0, Some("a"));
+ push(&mut acc, 0, 1, Some("b"));
+ push(&mut acc, 1, 5, Some("a"));
+ push(&mut acc, 0, 2, Some("a"));
+
+ assert_eq!(acc.message_count(), 4);
+ let groups = acc.into_groups();
+ let shapes: Vec<(Partition, Option<&str>, Vec<Offset>)> = groups
+ .iter()
+ .map(|g| (g.partition, g.key, offsets(g)))
+ .collect();
+ assert_eq!(
+ shapes,
+ vec![
+ (Partition(0), Some("a"), vec![Offset(0), Offset(2)]),
+ (Partition(0), Some("b"), vec![Offset(1)]),
+ (Partition(1), Some("a"), vec![Offset(5)]),
+ ]
+ );
+ let bodies: Vec<i64> = groups[0].messages.iter().map(|m| m.message).collect();
+ assert_eq!(bodies, vec![0, 2]);
+ }
+
+ #[test]
+ fn keyless_messages_each_form_their_own_group() {
+ let mut acc = Accumulator::default();
+ push(&mut acc, 0, 0, None);
+ push(&mut acc, 0, 1, Some("a"));
+ push(&mut acc, 0, 2, None);
+
+ let groups = acc.into_groups();
+ assert_eq!(groups.len(), 3);
+ assert_eq!(groups[0].key, None);
+ assert_eq!(offsets(&groups[0]), vec![Offset(0)]);
+ assert_eq!(groups[2].key, None);
+ assert_eq!(offsets(&groups[2]), vec![Offset(2)]);
+ }
+}
diff --git a/rust/common/kafka-consumer/src/lib.rs b/rust/common/kafka-consumer/src/lib.rs
index 177d17f21c3f..08b5aa5752ec 100644
--- a/rust/common/kafka-consumer/src/lib.rs
+++ b/rust/common/kafka-consumer/src/lib.rs
@@ -1,11 +1,13 @@
//! Kafka consumption primitives shared by stateful services.
+pub mod accumulator;
pub mod charge;
pub mod config;
pub mod ledger;
pub mod types;
+pub use accumulator::{Accumulator, Group, GroupMessage, PolledMessage};
pub use charge::Charge;
pub use config::ConsumerConfigBuilder;
pub use ledger::{OffsetLedger, TakenFrontier};
-pub use types::Offset;
+pub use types::{Offset, Partition};
diff --git a/rust/common/kafka-consumer/src/types.rs b/rust/common/kafka-consumer/src/types.rs
index 878b09b78aa3..f05863943598 100644
--- a/rust/common/kafka-consumer/src/types.rs
+++ b/rust/common/kafka-consumer/src/types.rs
@@ -1,6 +1,17 @@
use std::fmt;
use std::ops::{Add, Sub};
+/// A partition index on the consumer's single topic. It carries no topic, so
+/// a consumer of several topics must not key on it alone.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Partition(pub i32);
+
+impl fmt::Display for Partition {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.0)
+ }
+}
+
/// A Kafka message offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Offset(pub i64);
diff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.md
index b458f3b6e92e..4d7f14a9214b 100644
--- a/rust/ingestion-consumer/docs/driver-model-plan.md
+++ b/rust/ingestion-consumer/docs/driver-model-plan.md
@@ -28,8 +28,9 @@ Both stacks start from this plan branch ([#91468](https://github.com/PostHog/pos
| --- | --- | --- |
| Cycle 1 | `c1-delete-eager-flush` | Change 1. |
| Cycle 2 | `c2-common-ledger` -> `c2-ledger-shadow` -> `c2-ledger-active` -> `c2-ledger-cleanup` | Changes 2 through 5, one PR per plan step. |
+| Cycle 3 | `c3-demux-groups` -> `c3-batcher` -> `c3-scheduler-seam` -> `c3-key-table` -> `c3-scheduler-switch` | Changes 6 through 10, one PR per plan step. |
-The stacks are independent: cycle 2 can begin without cycle 1. The merge gates remain part of the plan: change 4 cannot merge until change 3 has soaked with a zero mismatch counter, and change 5 cannot merge until change 4 is stable on every lane. Draft PRs may be prepared earlier, but they must not collapse those gates.
+The stacks are independent: cycle 2 can begin without cycle 1, and cycle 3 needs only cycle 1 and the crate from change 2. The merge gates remain part of the plan: change 4 cannot merge until change 3 has soaked with a zero mismatch counter, and change 5 cannot merge until change 4 is stable on every lane. Draft PRs may be prepared earlier, but they must not collapse those gates.
## The cycle model
@@ -239,12 +240,13 @@ Exit criterion: zero key-order sentinel violations, `ingestion_consumer_transpor
- Group messages per partition first, then per routing key. Keep offset order inside each group.
- The dispatcher flattens the groups back into one message list. Sub-batch assembly does not change.
- Change 7 submits them to the batcher as the accumulator.
+- The group is the seam vocabulary between the consumer loop and the batcher, so it lives in `common-kafka-consumer`, generic over the key and the message body. The crate's demux knows no routing key of its own: a keyless message is one group on its own, and the dispatcher keeps naming such a group with its synthetic per-message key.
**Interfaces:**
-- Add `Group` in `types.rs`: partition, routing key, messages in offset order.
+- Add `Partition` to the crate's `types.rs`, and `Group` and `Accumulator` in `accumulator.rs`: a group is a partition, an optional key, and its offsets and messages in offset order; the accumulator is the demux that builds one poll's groups.
- Modify `CollectedBatch`: carries `Vec<Group>` instead of a flat message list.
-- Modify `Dispatcher::assign_and_send`: takes groups and flattens them. `group_messages_by_routing_key` moves to the collect path.
+- Modify `Dispatcher::assign_and_send`: takes groups and flattens them. The demux moves to the collect path; the dispatcher keeps only the routing-key naming.
### 7. Encapsulate the worker batcher (prepare)
@@ -267,7 +269,7 @@ Exit criterion: zero key-order sentinel violations, `ingestion_consumer_transpor
**Interfaces:**
-- Add `Accumulator`: one poll's groups, in poll order.
+- Submit the `Accumulator` from change 6 as one poll's groups, in poll order.
- Add `Batcher` in `batcher.rs`: `submit(Accumulator)` in, a channel of `GroupCompletion` out. It owns `Dispatcher` and the send tasks, and holds shared handles to `GrpcTransport`, `Router`, and `WorkerRegistry`. It creates batch ids internally.
- Add `GroupCompletion`: partition, assignment epoch, offsets, accepted count. No batch id and no messages: the batcher keeps the bodies for retry, and the ledger needs only the offsets.
- Modify `IngestionConsumer`: drop `scatter` and `flush_deferred` — they move into the batcher. Keep collect, commit, and the admission cap. Correlate completions to polls by partition and offset.
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index 4a459b8b20e4..39da25e6b2cf 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -3,6 +3,7 @@ use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};
+use common_kafka_consumer::Partition;
use futures::StreamExt;
use lifecycle::Handle;
use metrics::{counter, gauge, histogram};
@@ -19,7 +20,7 @@ use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch};
use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};
use crate::transport::SendError;
-use crate::types::SerializedKafkaMessage;
+use crate::types::{Accumulator, Group, SerializedKafkaMessage};
use crate::worker_registry::WorkerId;
/// Statistics gathered while collecting a batch, used to emit parity metrics.
@@ -47,7 +48,8 @@ impl BatchStats {
/// Output of `collect_batch`.
struct CollectedBatch {
- messages: Vec<SerializedKafkaMessage>,
+ /// The poll's messages, demuxed per partition and routing key.
+ groups: Vec<Group>,
offsets: HashMap<(String, i32), OffsetSpan>,
stats: BatchStats,
}
@@ -274,7 +276,7 @@ impl IngestionConsumer {
}
};
- if collected.messages.is_empty() {
+ if collected.groups.is_empty() {
self.handle.report_healthy();
if in_flight_batches.is_empty() {
continue;
@@ -301,7 +303,7 @@ impl IngestionConsumer {
}
fn spawn_batch_processing(&self, mut collected: CollectedBatch) -> InFlightBatch {
- let batch_size = collected.messages.len();
+ let batch_size: usize = collected.groups.iter().map(Group::len).sum();
let batch_id = make_batch_id();
// Register AND assign here, on the consumer loop, so both happen in
// true batch order. Registration first, so the stash learns batch
@@ -317,14 +319,14 @@ impl IngestionConsumer {
partitions: debug_partition_offsets(&collected.offsets, &collected.stats.max_lag_ms),
});
let assign_start = Instant::now();
- let messages = std::mem::take(&mut collected.messages);
+ let groups = std::mem::take(&mut collected.groups);
// Send order is established here too, still on the consumer loop and
// under the dispatcher's lock: `begin_send` is synchronous, so a key's
// sub-batches enter its worker's stream in assignment order — spawned
// tasks racing to send would scramble it.
let pending = self
.dispatcher
- .assign_and_send(&batch_id, messages, |sub_batch| {
+ .assign_and_send(&batch_id, groups, |sub_batch| {
Self::begin_send(&self.transport, &batch_id, sub_batch, false)
});
// Assignment serializes on the consumer loop (it no longer overlaps
@@ -699,7 +701,7 @@ impl IngestionConsumer {
/// bound still moves rather than wedging the partition — and overshoot is
/// at most one message, itself bounded by `fetch.message.max.bytes`.
async fn collect_batch(&self) -> anyhow::Result<CollectedBatch> {
- let mut messages = Vec::with_capacity(self.batch_size);
+ let mut accumulator = Accumulator::default();
let mut offsets: HashMap<(String, i32), OffsetSpan> = HashMap::new();
let mut stats = BatchStats::new();
let deadline = Instant::now() + self.batch_timeout;
@@ -708,7 +710,7 @@ impl IngestionConsumer {
let mut stream = self.consumer.stream();
loop {
- if messages.len() >= self.batch_size {
+ if accumulator.message_count() >= self.batch_size {
break;
}
@@ -790,7 +792,7 @@ impl IngestionConsumer {
headers,
};
- messages.push(serialized);
+ accumulator.push(Partition(partition), serialized.into());
}
Ok(Some(Err(err))) => {
warn!(error = %err, "Kafka recv error");
@@ -816,7 +818,7 @@ impl IngestionConsumer {
}
Ok(CollectedBatch {
- messages,
+ groups: accumulator.into_groups(),
offsets,
stats,
})
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index ced8b26f38c3..f10fdcfa1d25 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
+use common_kafka_consumer::{Offset, Partition};
use k8s_awareness::PeerTracker;
use metrics::{counter, gauge, histogram};
@@ -11,7 +12,7 @@ use crate::debug_recorder::{
use crate::order_sentinel::{KeyOrderSentinel, SendKind};
use crate::routing::{Router, RoutingStrategy, WorkerLoad};
use crate::stash::{DeferredGroup, Stash};
-use crate::types::SerializedKafkaMessage;
+use crate::types::{Accumulator, Group, SerializedKafkaMessage};
use crate::worker_registry::{WorkerId, WorkerRegistry};
/// The max offset a sub-batch carries for one routing key, over keyed
@@ -293,9 +294,23 @@ impl Dispatcher {
}
}
- /// Assign a batch of messages to workers.
+ /// Assign a batch of messages to workers. Demuxes the messages into
+ /// groups first, as the collect path does for a poll, then assigns them
+ /// like [`Dispatcher::assign_and_send`].
+ pub fn assign(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {
+ let mut table = self.pin_table.lock().unwrap();
+ self.assign_locked(&mut table, batch_id, demux(messages))
+ }
+
+ /// Assign a poll's groups to workers, then hand each sub-batch to `send`
+ /// before releasing the pin table. A key admitted here because nothing of
+ /// its is deferred must enter its worker stream before `defer_failed` can
+ /// stash an older group for it: with the lock released in between, the
+ /// stash could land first, the worker stream's fence could lift, and the
+ /// newer group would ride the next stream ahead of the older one. `send`
+ /// must not block.
///
- /// Groups messages by routing key, then per group:
+ /// Per group:
/// - honor an existing pin to a worker still taking work;
/// - **defer** (stash under `batch_id`) a key pinned to a draining/dead
/// worker, or one that already has deferred groups pending, so newer
@@ -304,27 +319,16 @@ impl Dispatcher {
/// group when no worker is routable at all, so a transient full-pool
/// outage holds messages instead of failing the batch.
///
- /// Returns one `SubBatch` per worker to send now. Deferred groups stay in
- /// the stash and are flushed later via [`Dispatcher::flush_deferred`].
- pub fn assign(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {
- let mut table = self.pin_table.lock().unwrap();
- self.assign_locked(&mut table, batch_id, messages)
- }
-
- /// Assign, then hand each sub-batch to `send` before releasing the pin
- /// table. A key admitted here because nothing of its is deferred must
- /// enter its worker stream before `defer_failed` can stash an older group for it:
- /// with the lock released in between, the stash could land first, the
- /// worker stream's fence could lift, and the newer group would ride the next
- /// stream ahead of the older one. `send` must not block.
+ /// Sends one `SubBatch` per worker. Deferred groups stay in the stash and
+ /// are flushed later via [`Dispatcher::flush_deferred`].
pub fn assign_and_send<T>(
&self,
batch_id: &str,
- messages: Vec<SerializedKafkaMessage>,
+ groups: Vec<Group>,
send: impl FnMut(SubBatch) -> T,
) -> Vec<T> {
let mut table = self.pin_table.lock().unwrap();
- self.assign_locked(&mut table, batch_id, messages)
+ self.assign_locked(&mut table, batch_id, groups)
.into_iter()
.map(send)
.collect()
@@ -334,12 +338,12 @@ impl Dispatcher {
&self,
table: &mut PinTable,
batch_id: &str,
- messages: Vec<SerializedKafkaMessage>,
+ groups: Vec<Group>,
) -> Vec<SubBatch> {
let GroupedMessages {
groups: key_groups,
unkeyed_count,
- } = group_messages_by_routing_key(messages);
+ } = routing_groups(groups);
if unkeyed_count > 0 {
counter!("ingestion_consumer_dispatcher_unkeyed_messages_total")
@@ -932,32 +936,56 @@ struct GroupedMessages {
unkeyed_count: u64,
}
+/// Demux messages into groups the way the collect path does for a poll.
+fn demux(messages: Vec<SerializedKafkaMessage>) -> Vec<Group> {
+ let mut accumulator = Accumulator::default();
+ for message in messages {
+ accumulator.push(Partition(message.partition), message.into());
+ }
+ accumulator.into_groups()
+}
+
fn group_messages_by_routing_key(messages: Vec<SerializedKafkaMessage>) -> GroupedMessages {
- let mut grouped_messages: HashMap<String, Vec<SerializedKafkaMessage>> = HashMap::new();
- let mut unkeyed_count = 0u64;
+ routing_groups(demux(messages))
+}
- for message in messages {
- let routing_key = message.key.clone().unwrap_or_else(|| {
- unkeyed_count += 1;
- // An unkeyed message has no order to preserve, so it can go to any
- // worker. A synthetic per-message key spreads such messages across
- // workers instead of pinning them all to one shared fallback key.
- format!(":{}:{}", message.partition, message.offset)
- });
- grouped_messages
- .entry(routing_key)
- .or_default()
- .push(message);
+/// Name each group for the pin table. A keyed group's routing key is its
+/// Kafka key. An unkeyed message has no order to preserve, so it can go to
+/// any worker: a synthetic per-message key spreads such messages across
+/// workers instead of pinning them all to one shared fallback key.
+///
+/// The pin table is keyed by routing key alone, so a key that arrives on two
+/// partitions in one poll (a partition-count change leaves its backlog on the
+/// old partition) merges into one group: two groups for one key could route
+/// to two workers at once.
+fn routing_groups(groups: Vec<Group>) -> GroupedMessages {
+ let mut unkeyed_count = 0u64;
+ let mut merged: Vec<MessageGroup> = Vec::with_capacity(groups.len());
+ let mut index_by_key: HashMap<String, usize> = HashMap::new();
+ for group in groups {
+ let routing_key = match group.key {
+ Some(key) => key,
+ None => {
+ unkeyed_count += 1;
+ let first = group.messages.first().map_or(Offset(-1), |m| m.offset);
+ format!(":{}:{}", group.partition, first)
+ }
+ };
+ let messages = group.messages.into_iter().map(|m| m.message);
+ match index_by_key.get(&routing_key) {
+ Some(&index) => merged[index].messages.extend(messages),
+ None => {
+ index_by_key.insert(routing_key.clone(), merged.len());
+ merged.push(MessageGroup {
+ routing_key,
+ messages: messages.collect(),
+ });
+ }
+ }
}
GroupedMessages {
- groups: grouped_messages
- .into_iter()
- .map(|(routing_key, messages)| MessageGroup {
- routing_key,
- messages,
- })
- .collect(),
+ groups: merged,
unkeyed_count,
}
}
@@ -1075,6 +1103,29 @@ mod tests {
assert_eq!(grouped.groups[0].messages.len(), 2);
}
+ #[test]
+ fn test_same_routing_key_on_two_partitions_stays_one_group() {
+ let grouped = group_messages_by_routing_key(vec![
+ SerializedKafkaMessage {
+ partition: 0,
+ offset: 1,
+ ..make_msg("tok:user-1")
+ },
+ SerializedKafkaMessage {
+ partition: 3,
+ offset: 9,
+ ..make_msg("tok:user-1")
+ },
+ ]);
+
+ assert_eq!(
+ grouped.groups.len(),
+ 1,
+ "one key must not split across workers"
+ );
+ assert_eq!(grouped.groups[0].messages.len(), 2);
+ }
+
// ---- worker assignments ----
#[test]
@@ -2027,21 +2078,22 @@ mod tests {
let racing = Arc::clone(&dispatcher);
let mut race = None;
- let sent = dispatcher.assign_and_send("batch-2", make_msgs(&["t:user-1"]), |sub_batch| {
- // Admitted behind batch-1's live pin. batch-1's send now fails
- // and tries to stash its messages before this group is enqueued.
- let dispatcher = Arc::clone(&racing);
- let handle = std::thread::spawn(move || {
- dispatcher.defer_failed("batch-1", make_msgs(&["t:user-1"]));
+ let sent =
+ dispatcher.assign_and_send("batch-2", demux(make_msgs(&["t:user-1"])), |sub_batch| {
+ // Admitted behind batch-1's live pin. batch-1's send now fails
+ // and tries to stash its messages before this group is enqueued.
+ let dispatcher = Arc::clone(&racing);
+ let handle = std::thread::spawn(move || {
+ dispatcher.defer_failed("batch-1", make_msgs(&["t:user-1"]));
+ });
+ std::thread::sleep(Duration::from_millis(50));
+ assert!(
+ !handle.is_finished(),
+ "defer_failed must wait until the admitted group is enqueued"
+ );
+ race = Some(handle);
+ sub_batch
});
- std::thread::sleep(Duration::from_millis(50));
- assert!(
- !handle.is_finished(),
- "defer_failed must wait until the admitted group is enqueued"
- );
- race = Some(handle);
- sub_batch
- });
assert_eq!(sent.len(), 1, "batch-2 was admitted and handed to send");
race.take().expect("send ran").join().expect("defer_failed");
diff --git a/rust/ingestion-consumer/src/types.rs b/rust/ingestion-consumer/src/types.rs
index 102f90e48794..4e9d4738fc71 100644
--- a/rust/ingestion-consumer/src/types.rs
+++ b/rust/ingestion-consumer/src/types.rs
@@ -1,5 +1,6 @@
use std::collections::HashMap;
+use common_kafka_consumer::{Offset, PolledMessage};
use serde::{Deserialize, Serialize};
/// Matches `SerializedKafkaMessage` in `nodejs/src/ingestion/api/types.ts`.
@@ -14,3 +15,20 @@ pub struct SerializedKafkaMessage {
pub value: Option<String>,
pub headers: HashMap<String, String>,
}
+
+/// The demux's view of a message: the Kafka key is the routing key.
+impl From<SerializedKafkaMessage> for PolledMessage<String, SerializedKafkaMessage> {
+ fn from(message: SerializedKafkaMessage) -> Self {
+ PolledMessage {
+ offset: Offset(message.offset),
+ key: message.key.clone(),
+ inner: message,
+ }
+ }
+}
+
+/// One poll's messages for one routing key on one partition, in offset order.
+pub type Group = common_kafka_consumer::Group<String, SerializedKafkaMessage>;
+
+/// The demux that builds one poll's groups.
+pub type Accumulator = common_kafka_consumer::Accumulator<String, SerializedKafkaMessage>;