Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 49 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ pub struct Config {
/// The path to the runtime config file
pub runtime_config_path: Option<String>,

/// 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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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,
Expand All @@ -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(())
});
Expand Down
19 changes: 12 additions & 7 deletions src/kafka/consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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<dyn ActivationStore>,
spawn_actors: impl FnMut(Arc<AsyncKafkaConsumer>, Assignment) -> ActorHandles,
spawn_actors: impl FnMut(Arc<ConsumerBackend>, 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!(
Expand Down Expand Up @@ -215,7 +220,7 @@ macro_rules! processing_strategy {
reduce: $reduce_first:expr $(,$reduce_rest:expr)*,
}
) => {{
|consumer: Arc<sentry_arroyo::backends::kafka::async_consumer::AsyncKafkaConsumer>,
|consumer: Arc<$crate::kafka::consumer_backend::ConsumerBackend>,
assignment: $crate::kafka::consumer_backend::Assignment|
-> $crate::kafka::consumer::ActorHandles {
let start = std::time::Instant::now();
Expand Down Expand Up @@ -279,10 +284,10 @@ enum ConsumerState {

#[instrument(skip_all)]
pub async fn handle_events(
consumer: Arc<AsyncKafkaConsumer>,
consumer: Arc<ConsumerBackend>,
events: UnboundedReceiver<(Event, SyncSender<()>)>,
activation_store: Arc<dyn ActivationStore>,
mut spawn_actors: impl FnMut(Arc<AsyncKafkaConsumer>, Assignment) -> ActorHandles,
mut spawn_actors: impl FnMut(Arc<ConsumerBackend>, Assignment) -> ActorHandles,
topics_tag: String,
) -> Result<(), anyhow::Error> {
const CALLBACK_DURATION: Duration = Duration::from_secs(4);
Expand Down
65 changes: 51 additions & 14 deletions src/kafka/consumer_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AsyncKafkaConsumer, Error> {
use_reloading: bool,
) -> Result<ConsumerBackend, Error> {
let arroyo_config = KafkaConfig::new_config(
vec![
config
Expand All @@ -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() {
Expand All @@ -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")
}
}

Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -223,6 +252,7 @@ mod tests {
&["test"],
&config,
KafkaContext::new(sender, "test".to_owned()),
use_reloading,
)
.unwrap(),
);
Expand All @@ -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))?;
Expand All @@ -272,15 +306,18 @@ 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")
.set("group.id", "test-offset-reset-aliases")
.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
Expand Down
5 changes: 2 additions & 3 deletions src/kafka/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading