Skip to content

fix: Apply timeout on batch basis #1133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
21 changes: 19 additions & 2 deletions src/workers.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* of the MIT license. See the LICENSE.txt file for details.
*/

#include <chrono>
#include <string>
#include <vector>

Expand Down Expand Up @@ -808,10 +809,26 @@ KafkaConsumerConsumeNum::~KafkaConsumerConsumeNum() {}
void KafkaConsumerConsumeNum::Execute() {
std::size_t max = static_cast<std::size_t>(m_num_messages);
bool looping = true;
int timeout_ms = m_timeout_ms;
std::size_t eof_event_count = 0;

auto start_time = std::chrono::steady_clock::now();
int timeout_ms = m_timeout_ms;
int early_exit_ms = 1;

while (m_messages.size() - eof_event_count < max && looping) {
// Allow timeout_ms = early_exit_ms to take precedence
// timeout_ms > 1
if (timeout_ms > early_exit_ms) {
// Calc next single consume timeout remaining for batch
auto now = std::chrono::steady_clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time)
.count();
// `timeout_ms` of 0 triggers non-blocking behavior https://github.com/confluentinc/librdkafka/blob/3f52de491f8aae1d71a9a0b3f1c07bfd6df4aec3/src/rdkafka_int.h#L1189-L1190
// This still returns ERR_TIMED_OUT if no message available
timeout_ms = std::max(0, m_timeout_ms - static_cast<int>(elapsed));
}

// Get a message
Baton b = m_consumer->Consume(timeout_ms);
if (b.err() == RdKafka::ERR_NO_ERROR) {
Expand All @@ -822,7 +839,7 @@ void KafkaConsumerConsumeNum::Execute() {
// If partition EOF and have consumed messages, retry with timeout 1
// This allows getting ready messages, while not waiting for new ones
if (m_messages.size() > eof_event_count) {
timeout_ms = 1;
timeout_ms = early_exit_ms;
}

// We will only go into this code path when `enable.partition.eof` is set to true
Expand Down