From c453c1aebc8c2d87ab322b1c93e1bd0452af939b Mon Sep 17 00:00:00 2001 From: Tony Le Date: Mon, 30 Nov 2026 16:44:17 -0500 Subject: [PATCH] feat(consumer): Add config to use Arroyo's reloading consumer --- .github/workflows/ci.yml | 56 ++++++++++++++++++++++++++---- Cargo.lock | 4 +-- Cargo.toml | 2 +- src/config/mod.rs | 7 ++++ src/kafka/consumer.rs | 19 ++++++---- src/kafka/consumer_backend.rs | 65 +++++++++++++++++++++++++++-------- src/kafka/producer.rs | 5 ++- src/main.rs | 1 + 8 files changed, 125 insertions(+), 34 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8d3e44b..17f1ca38 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -268,8 +268,14 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} rebalance-integration-test: - name: Rebalance integration test + name: Rebalance integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 @@ -306,8 +312,14 @@ jobs: make test-rebalance worker-processing-integration-test: - name: Worker processing integration test + name: Worker processing integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 @@ -344,8 +356,14 @@ jobs: make test-worker-processing upkeep-retry-integration-test: - name: Upkeep retry integration test + name: Upkeep retry integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 @@ -382,8 +400,14 @@ jobs: make test-upkeep-retry upkeep-expiry-integration-test: - name: Upkeep expiry integration test + name: Upkeep expiry integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 @@ -458,8 +482,14 @@ jobs: make test-heartbeat upkeep-delay-integration-test: - name: Upkeep delay integration test + name: Upkeep delay integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 @@ -496,8 +526,14 @@ jobs: make test-upkeep-delay failed-tasks-integration-test: - name: Failed tasks integration test + name: Failed tasks integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 @@ -534,8 +570,14 @@ jobs: make test-failed-tasks multi-topic-integration-test: - name: Multi-topic integration test + name: Multi-topic integration test${{ matrix.consumer_backend == 'reloading' && ' (reloading)' || '' }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + consumer_backend: [arroyo, reloading] + env: + TASKBROKER_USE_RELOADING_CONSUMER: ${{ matrix.consumer_backend == 'reloading' }} steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2 diff --git a/Cargo.lock b/Cargo.lock index ff0b6361..7185daf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2996,9 +2996,9 @@ dependencies = [ [[package]] name = "sentry_arroyo" -version = "2.49.2" +version = "2.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "264346ef3695c76f10f4cc4e6224f3d198ff3d9034280036f857b110f6ad9336" +checksum = "299f6004415e07c407397a34cd7a4874b7846f928aaa4e37c30e09792b9d5f91" dependencies = [ "async-stream", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 2ac8cf5f..10767265 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ validator = { version = "0.20.0", features = ["derive"] } prost-types = "0.14" rand = "0.8.5" rdkafka = { version = "0.37.0", features = ["cmake-build", "ssl"] } -sentry_arroyo = { version = "=2.49.2", features = ["ssl"] } +sentry_arroyo = { version = "=2.52.0", features = ["ssl"] } rmp-serde = "1.3" sentry = { version = "0.41.0", default-features = false, features = [ # default features, except `release-health` is disabled diff --git a/src/config/mod.rs b/src/config/mod.rs index 201706bf..1a8549f9 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -155,6 +155,9 @@ pub struct Config { /// The path to the runtime config file pub runtime_config_path: Option, + /// Consume with Arroyo's reloading async consumer instead of its plain async consumer. + pub use_reloading_consumer: bool, + /// The frequency at which upkeep tasks /// (discarding, retrying activations, etc.) are executed. pub upkeep_task_interval_ms: u64, @@ -295,6 +298,7 @@ impl Default for Config { kafka_send_timeout_ms: 500, store: StoreConfig::default(), runtime_config_path: None, + use_reloading_consumer: false, upkeep_task_interval_ms: 1000, upkeep_deadline_reset_skip_after_startup_sec: 60, maintenance_task_interval_ms: 6000, @@ -1092,6 +1096,7 @@ mod tests { assert_eq!(config.store.sqlite.vacuum_page_count, None); assert_eq!(config.canary_tasks, 0); assert!(config.worker_map.is_empty()); + assert!(!config.use_reloading_consumer); } #[test] @@ -1286,6 +1291,7 @@ mod tests { jail.set_env("TASKBROKER_DATABASE_ADAPTER", "postgres"); jail.set_env("TASKBROKER_MAX_PROCESSING_ATTEMPTS", "5"); jail.set_env("TASKBROKER_CANARY_TASKS", "2"); + jail.set_env("TASKBROKER_USE_RELOADING_CONSUMER", "true"); let args = Args { run: Run::Broker, @@ -1296,6 +1302,7 @@ mod tests { assert_eq!(config.store.adapter, DatabaseAdapter::Postgres); assert_eq!(config.store.max_processing_attempts, 5); assert_eq!(config.canary_tasks, 2); + assert!(config.use_reloading_consumer); Ok(()) }); diff --git a/src/kafka/consumer.rs b/src/kafka/consumer.rs index 629a3502..af0a43dd 100644 --- a/src/kafka/consumer.rs +++ b/src/kafka/consumer.rs @@ -23,13 +23,12 @@ use tokio_util::sync::CancellationToken; use anyhow::{Error, anyhow}; use futures::{Stream, StreamExt, future, pin_mut}; -use sentry_arroyo::backends::kafka::async_consumer::AsyncKafkaConsumer; use tracing::{debug, error, info, instrument}; use crate::store::traits::ActivationStore; use crate::store::types::TopicPartition; -use super::consumer_backend::{Assignment, KafkaContext, create_consumer}; +use super::consumer_backend::{Assignment, ConsumerBackend, KafkaContext, create_consumer}; use super::message::MessageBackend; pub async fn start_no_consume_mode( @@ -86,15 +85,21 @@ pub async fn start_no_consume_mode( pub async fn start_consumer( topics: &[&str], kafka_client_config: &ClientConfig, + use_reloading_consumer: bool, activation_store: Arc, - spawn_actors: impl FnMut(Arc, Assignment) -> ActorHandles, + spawn_actors: impl FnMut(Arc, Assignment) -> ActorHandles, ) -> Result<(), Error> { let (event_sender, event_receiver) = unbounded_channel(); // Metrics tag only. Ownership keys come per-topic from the assignment `tpl`, // never from this string — so a multi-topic consumer stays correct. let topics_tag = topics.join(","); let context = KafkaContext::new(event_sender.clone(), topics_tag.clone()); - let consumer = Arc::new(create_consumer(topics, kafka_client_config, context)?); + let consumer = Arc::new(create_consumer( + topics, + kafka_client_config, + context, + use_reloading_consumer, + )?); handle_shutdown_signals(event_sender.clone()); metrics::gauge!( @@ -215,7 +220,7 @@ macro_rules! processing_strategy { reduce: $reduce_first:expr $(,$reduce_rest:expr)*, } ) => {{ - |consumer: Arc, + |consumer: Arc<$crate::kafka::consumer_backend::ConsumerBackend>, assignment: $crate::kafka::consumer_backend::Assignment| -> $crate::kafka::consumer::ActorHandles { let start = std::time::Instant::now(); @@ -279,10 +284,10 @@ enum ConsumerState { #[instrument(skip_all)] pub async fn handle_events( - consumer: Arc, + consumer: Arc, events: UnboundedReceiver<(Event, SyncSender<()>)>, activation_store: Arc, - mut spawn_actors: impl FnMut(Arc, Assignment) -> ActorHandles, + mut spawn_actors: impl FnMut(Arc, Assignment) -> ActorHandles, topics_tag: String, ) -> Result<(), anyhow::Error> { const CALLBACK_DURATION: Duration = Duration::from_secs(4); diff --git a/src/kafka/consumer_backend.rs b/src/kafka/consumer_backend.rs index fb1b664b..6627d643 100644 --- a/src/kafka/consumer_backend.rs +++ b/src/kafka/consumer_backend.rs @@ -2,26 +2,37 @@ use std::collections::{BTreeSet, HashMap}; use std::fmt::Debug; use std::sync::mpsc::{SyncSender, sync_channel}; -use anyhow::{Context, Error}; -use futures::Stream; -use rdkafka::error::KafkaError; -use rdkafka::{ClientConfig, TopicPartitionList}; use sentry_arroyo::backends::kafka::async_consumer::{ AsyncAssignmentCallbacks, AsyncKafkaConsumer, AsyncPartitionQueue, }; use sentry_arroyo::backends::kafka::config::KafkaConfig; +use sentry_arroyo::backends::kafka::config_blob::ConsumerSelector; +use sentry_arroyo::backends::kafka::reload::ReloadConfig; +use sentry_arroyo::backends::kafka::reloading_async_consumer::ReloadingAsyncKafkaConsumer; use sentry_arroyo::types::{Partition, Topic}; + +use anyhow::{Context, Error, bail}; +use futures::Stream; +use rdkafka::error::KafkaError; +use rdkafka::{ClientConfig, TopicPartitionList}; use tokio::sync::mpsc::UnboundedSender; use tracing::{info, warn}; use super::consumer::{CommitClient, Event, KafkaMessage, MessageQueue}; use super::message::MessageBackend; +/// The Arroyo consumer taskbroker runs, chosen by `Config::use_reloading_consumer`. +pub enum ConsumerBackend { + Arroyo(AsyncKafkaConsumer), + Reloading(ReloadingAsyncKafkaConsumer), +} + pub fn create_consumer( topics: &[&str], config: &ClientConfig, context: KafkaContext, -) -> Result { + use_reloading: bool, +) -> Result { let arroyo_config = KafkaConfig::new_config( vec![ config @@ -31,12 +42,27 @@ pub fn create_consumer( ], Some(config.config_map().clone()), ); + if use_reloading { + let &[topic] = topics else { + bail!("Expected exactly one topic per consumer, got {topics:?}"); + }; + let group_id = config.get("group.id").context("Missing group.id")?; + return ReloadingAsyncKafkaConsumer::from_config( + arroyo_config, + ConsumerSelector::new(topic, "taskbroker", group_id), + ReloadConfig::default(), + context, + ) + .map(ConsumerBackend::Reloading) + .context("Could not create reloading Arroyo consumer"); + } let topics: Vec<_> = topics.iter().map(|topic| Topic::new(topic)).collect(); AsyncKafkaConsumer::new(arroyo_config, &topics, context) + .map(ConsumerBackend::Arroyo) .context("Could not create Arroyo consumer") } -impl CommitClient for AsyncKafkaConsumer { +impl CommitClient for ConsumerBackend { fn store_offsets(&self, tpl: &TopicPartitionList) -> Result<(), Error> { let mut offsets = HashMap::with_capacity(tpl.count()); for element in tpl.elements() { @@ -50,9 +76,11 @@ impl CommitClient for AsyncKafkaConsumer { offset, ); } - // The inherent method, not this trait method. - AsyncKafkaConsumer::store_offsets(self, offsets) - .context("Arroyo consumer offset storage failed") + match self { + Self::Arroyo(consumer) => consumer.store_offsets(offsets), + Self::Reloading(consumer) => consumer.store_offsets(offsets), + } + .context("Arroyo consumer offset storage failed") } } @@ -192,10 +220,11 @@ mod tests { use crate::kafka::consumer::{CommitClient, Event, KafkaMessage, MessageQueue}; - use super::{KafkaContext, create_consumer}; + use super::{ConsumerBackend, KafkaContext, create_consumer}; + #[rstest::rstest] #[tokio::test] - async fn test_partition_receive_and_commit() { + async fn test_partition_receive_and_commit(#[values(false, true)] use_reloading: bool) { let cluster = MockCluster::new(1).unwrap(); cluster.create_topic("test", 1, 1).unwrap(); let mut config = ClientConfig::new(); @@ -223,6 +252,7 @@ mod tests { &["test"], &config, KafkaContext::new(sender, "test".to_owned()), + use_reloading, ) .unwrap(), ); @@ -249,7 +279,11 @@ mod tests { offsets.add_partition_offset("test", 0, next_offset)?; CommitClient::store_offsets(consumer.as_ref(), &offsets)?; let committer = consumer.clone(); - task::spawn_blocking(move || committer.commit_consumer_state()).await??; + task::spawn_blocking(move || match committer.as_ref() { + ConsumerBackend::Arroyo(consumer) => consumer.commit_consumer_state(), + ConsumerBackend::Reloading(consumer) => consumer.commit_consumer_state(), + }) + .await??; task::spawn_blocking(move || -> Result<(), Error> { let observer: BaseConsumer = config.create()?; let committed = observer.committed_offsets(offsets, Duration::from_secs(5))?; @@ -272,7 +306,10 @@ mod tests { #[case::largest("largest")] #[case::end("end")] #[tokio::test] - async fn test_consumer_accepts_offset_reset_aliases(#[case] policy: &str) { + async fn test_consumer_accepts_offset_reset_aliases( + #[case] policy: &str, + #[values(false, true)] use_reloading: bool, + ) { let mut config = ClientConfig::new(); config .set("bootstrap.servers", "127.0.0.1:1") @@ -280,7 +317,7 @@ mod tests { .set("auto.offset.reset", policy); let (events, _) = mpsc::unbounded_channel(); let context = KafkaContext::new(events, "test".to_owned()); - let consumer = create_consumer(&["test"], &config, context) + let consumer = create_consumer(&["test"], &config, context, use_reloading) .unwrap_or_else(|error| panic!("{policy}: {error}")); tokio::task::spawn_blocking(move || drop(consumer)) .await diff --git a/src/kafka/producer.rs b/src/kafka/producer.rs index 66fd4e61..66e99b2c 100644 --- a/src/kafka/producer.rs +++ b/src/kafka/producer.rs @@ -3,9 +3,8 @@ use std::time::{Duration, Instant}; use sentry_arroyo::backends::kafka::config::KafkaConfig; use sentry_arroyo::backends::kafka::config_blob::ProducerSelector; -use sentry_arroyo::backends::kafka::reloading_producer::{ - ReloadConfig, ReloadError, ReloadingKafkaProducer, -}; +use sentry_arroyo::backends::kafka::reload::{ReloadConfig, ReloadError}; +use sentry_arroyo::backends::kafka::reloading_producer::ReloadingKafkaProducer; use sentry_arroyo::backends::kafka::types::KafkaPayload; use sentry_arroyo::backends::{AsyncProducer, ProducerError}; use sentry_arroyo::types::{Topic, TopicOrPartition}; diff --git a/src/main.rs b/src/main.rs index 65c92dfc..9547d464 100644 --- a/src/main.rs +++ b/src/main.rs @@ -207,6 +207,7 @@ async fn main() -> Result<(), Error> { start_consumer( &topic_refs, &consumer_config.kafka_consumer_config_for(&task_topic), + consumer_config.use_reloading_consumer, consumer_store.clone(), processing_strategy!({ err: