Skip to content

Added timeout to flush and wait_for_acks #86

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

Merged
merged 1 commit into from
Jun 14, 2018
Merged
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
47 changes: 47 additions & 0 deletions include/cppkafka/utils/buffered_producer.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,11 +190,27 @@ class CPPKAFKA_API BufferedProducer {
* with respect to other threads.
*/
void flush();

/**
* \brief Flushes the buffered messages and waits up to 'timeout'
*
* \param timeout The maximum time to wait until all acks are received
*
* \return True if the operation completes and all acks have been received.
*/
bool flush(std::chrono::milliseconds timeout);

/**
* Waits for produced message's acknowledgements from the brokers
*/
void wait_for_acks();

/**
* Waits for produced message's acknowledgements from the brokers up to 'timeout'.
*
* \return True if the operation completes and all acks have been received.
*/
bool wait_for_acks(std::chrono::milliseconds timeout);

/**
* Clears any buffered messages
Expand Down Expand Up @@ -515,6 +531,12 @@ void BufferedProducer<BufferType>::flush() {
wait_for_acks();
}

template <typename BufferType>
bool BufferedProducer<BufferType>::flush(std::chrono::milliseconds timeout) {
async_flush();
return wait_for_acks(timeout);
}

template <typename BufferType>
void BufferedProducer<BufferType>::wait_for_acks() {
while (pending_acks_ > 0) {
Expand All @@ -533,6 +555,31 @@ void BufferedProducer<BufferType>::wait_for_acks() {
}
}

template <typename BufferType>
bool BufferedProducer<BufferType>::wait_for_acks(std::chrono::milliseconds timeout) {
auto remaining = timeout;
auto start_time = std::chrono::high_resolution_clock::now();
while ((pending_acks_ > 0) && (remaining.count() > 0)) {
try {
producer_.flush(remaining);
}
catch (const HandleException& ex) {
// If we just hit the timeout, keep going, otherwise re-throw
if (ex.get_error() == RD_KAFKA_RESP_ERR__TIMED_OUT) {
// There is no time remaining
return (pending_acks_ == 0);
}
else {
throw;
}
}
// calculate remaining time
remaining = timeout - std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::high_resolution_clock::now() - start_time);
}
return (pending_acks_ == 0);
}

template <typename BufferType>
void BufferedProducer<BufferType>::clear() {
std::lock_guard<std::mutex> lock(mutex_);
Expand Down