userver
C++ Async Framework
Toggle main menu visibility
Loading...
Searching...
No Matches
consumer_scope.hpp
Go to the documentation of this file.
1
#
pragma
once
2
3
/// @file userver/kafka/consumer_scope.hpp
4
/// @brief @copybrief kafka::ConsumerScope
5
6
#
include
<
functional
>
7
8
#
include
<
userver
/
kafka
/
message
.
hpp
>
9
#
include
<
userver
/
kafka
/
offset_range
.
hpp
>
10
#
include
<
userver
/
kafka
/
rebalance_types
.
hpp
>
11
#
include
<
userver
/
utils
/
zstring_view
.
hpp
>
12
13
USERVER_NAMESPACE_BEGIN
14
15
namespace
kafka {
16
17
namespace
impl {
18
19
class
Consumer;
20
21
}
// namespace impl
22
23
/// @ingroup userver_clients
24
///
25
/// @brief RAII class that used as interface for Apache Kafka Consumer interaction
26
/// and proper lifetime management.
27
///
28
/// Its main purpose is to stop the message polling in user
29
/// component (that holds ConsumerScope) destructor, because ConsumerScope::Callback
30
/// often captures `this` pointer on user component.
31
///
32
/// Common usage:
33
///
34
/// @snippet samples/kafka_service/src/consumer_handler.cpp Kafka service sample - consumer usage
35
///
36
/// ## Important implementation details
37
///
38
/// ConsumerScope holds reference to kafka::impl::Consumer that actually
39
/// represents the Apache Kafka Balanced Consumer.
40
///
41
/// It exposes the API for asynchronous message batches processing that is
42
/// polled from the subscribed topics partitions.
43
///
44
/// Consumer periodically polls the message batches from the
45
/// subscribed topics partitions and invokes processing callback on each batch.
46
///
47
/// Also, Consumer maintains per topic statistics including the broker
48
/// connection errors.
49
///
50
/// @note Each ConsumerScope instance is not thread-safe. To speed up the topic
51
/// messages processing, create more consumers with the same `group_id`.
52
///
53
/// @see https://docs.confluent.io/platform/current/clients/consumer.html for
54
/// basic consumer concepts
55
/// @see
56
/// https://docs.confluent.io/platform/current/clients/librdkafka/html/md_INTRODUCTION.html#autotoc_md62
57
/// for understanding of balanced consumer groups
58
///
59
/// @warning ConsumerScope::Start and ConsumerScope::Stop maybe called multiple
60
/// times, but only in "start-stop" order and **NOT** concurrently.
61
///
62
/// @note Must be placed as one of the last fields in the consumer component.
63
/// Make sure to add a comment before the field:
64
///
65
/// @code
66
/// // Subscription must be the last field! Add new fields above this comment.
67
/// @endcode
68
class
ConsumerScope
final
{
69
public
:
70
/// @brief Callback that is invoked on each polled message batch.
71
/// @warning If callback throws, it called over and over again with the batch
72
/// with the same messages, until successful invocation.
73
/// Though, user should consider idempotent message processing mechanism.
74
/// @note On fatal librdkafka consumer errors the client is recreated automatically
75
/// (see `restart_after_failure_delay`).
76
using
Callback
= std::function<
void
(MessageBatchView)>;
77
78
/// @brief Stops the consumer (if not yet stopped).
79
~
ConsumerScope
();
80
81
ConsumerScope(ConsumerScope&&)
noexcept
=
delete
;
82
ConsumerScope& operator=(ConsumerScope&&)
noexcept
=
delete
;
83
84
/// @brief Topics list consumer configured to subscribe.
85
const
std::vector<std::string>&
GetTopics
()
const
;
86
87
/// @brief Subscribes for configured topics and starts the consumer polling
88
/// process.
89
/// @note If `callback` throws an exception, entire message batch (also
90
/// with successfully processed messages) come again, until callback succeeds
91
/// @warning Each callback duration must not exceed the
92
/// `max_callback_duration` time. Otherwise, consumer may stop consuming the
93
/// message for unpredictable amount of time.
94
void
Start
(
Callback
callback);
95
96
/// @brief Revokes all topic partition consumer was subscribed on. Also closes
97
/// the consumer, leaving the consumer balanced group.
98
///
99
/// Called in the destructor of ConsumerScope automatically.
100
///
101
/// Can be called in the beginning of your destructor if some other
102
/// actions in that destructor prevent the callback from functioning
103
/// correctly.
104
///
105
/// After ConsumerScope::Stop call, subscribed topics partitions are
106
/// distributed between other consumers with the same `group_id`.
107
///
108
/// @warning Blocks until all kafka::Message destroyed (e.g. consumer cannot
109
/// be stopped until user-callback is executing).
110
void
Stop
()
noexcept
;
111
112
/// @brief Schedules the current assignment offsets commitment task.
113
/// Intended to be called after each message batch processing cycle (but not
114
/// necessarily).
115
///
116
/// @warning Commit does not ensure that messages do not come again --
117
/// they do not come again also without the commit within the same process.
118
/// Commit, indeed, restricts other consumers in consumers group from reading
119
/// messages already processed (committed) by the current consumer if current
120
/// has stopped and leaved the group
121
void
AsyncCommit
();
122
123
/// @brief Retrieves the lowest and highest offsets for the specified topic and partition.
124
/// @throws OffsetRangeException if offsets could not be retrieved
125
/// @throws OffsetRangeTimeoutException if `timeout` is set and is reached
126
/// @warning This is a blocking call
127
/// @param topic The name of the topic.
128
/// @param partition The partition number of the topic.
129
/// @param timeout The optional timeout for the operation.
130
/// @returns Lowest and highest offsets for the given topic and partition.
131
/// @see OffsetRange for more explanation
132
OffsetRange
GetOffsetRange
(
133
utils
::
zstring_view
topic,
134
std::uint32_t partition,
135
std::optional<std::chrono::milliseconds> timeout = std::nullopt
136
)
const
;
137
138
/// @brief Retrieves the partition IDs for the specified topic.
139
/// @throws GetMetadataException if failed to fetch metadata
140
/// @throws TopicNotFoundException if topic not found
141
/// @throws OffsetRangeTimeoutException if `timeout` is set and is reached
142
/// @warning This is a blocking call
143
/// @param topic The name of the topic.
144
/// @param timeout The optional timeout for the operation.
145
/// @returns A vector of partition IDs for the given topic.
146
std::vector<std::
uint32_t
>
GetPartitionIds
(
147
utils
::
zstring_view
topic,
148
std::optional<std::chrono::milliseconds> timeout = std::nullopt
149
)
const
;
150
151
/// @brief Sets the rebalance callback for a consumer.
152
/// @warning The rebalance callback must be set before calling ConsumerScope::Start or after calling
153
/// ConsumerScope::Stop. The callback must not throw exceptions; any thrown exceptions will be caught and logged
154
/// by the consumer implementation.
155
/// @note The callback is invoked after the assign or revoke event has been successfully processed.
156
void
SetRebalanceCallback
(
ConsumerRebalanceCallback
rebalance_callback);
157
158
/// @brief Resets the rebalance callback for a consumer.
159
/// @warning The rebalance callback must be set before calling ConsumerScope::Start or after calling
160
/// ConsumerScope::Stop. The callback must not throw exceptions; any thrown exceptions will be caught and logged
161
/// by the consumer implementation.
162
/// @note The callback is invoked after the assign or revoke event has been successfully processed.
163
void
ResetRebalanceCallback
();
164
165
/// @brief Seeks the specified topic partition to the given \b offset.
166
/// @throws TimeoutException if the operation times out.
167
/// @throws SeekException if an error occurs during the seek operation.
168
/// @throws SeekInvalidArgumentException if invalid \b timeout or \b offset is passed.
169
/// @warning This is a blocking call and should only be invoked after ConsumerScope::Start call and before
170
/// ConsumerScope::Stop call. It works only when the consumer has assigned partitions; otherwise, it throws
171
/// SeekException.
172
/// @warning Currently, it is required to call this from within the ConsumerRebalanceCallback.
173
/// @ref ConsumerScope::SetRebalanceCallback
174
/// @param topic The name of the topic.
175
/// @param partition_id The partition ID of the given topic.
176
/// @param offset The offset to seek to, must be <= std::int64_t::max() or SeekInvalidArgumentException occurs.
177
/// @param timeout The timeout duration for the operation, must be > 0 or SeekInvalidArgumentException occurs.
178
void
Seek
(
179
utils
::
zstring_view
topic,
180
std::uint32_t partition_id,
181
std::uint64_t offset,
182
std::chrono::milliseconds timeout
183
)
const
;
184
185
/// @brief Seeks the specified topic partition to the beginning.
186
/// @throws SeekException if an error occurs during the seek operation.
187
/// @throws SeekInvalidArgumentException if invalid \b timeout is passed.
188
/// @warning This is a blocking call and should only be invoked after ConsumerScope::Start call and before
189
/// ConsumerScope::Stop call. It works only when the consumer has assigned partitions; otherwise, it throws
190
/// SeekException.
191
/// @warning Currently, it is required to call this from within the ConsumerRebalanceCallback.
192
/// @ref ConsumerScope::SetRebalanceCallback
193
/// @param topic The name of the topic.
194
/// @param partition_id The partition ID of the given topic.
195
/// @param timeout The timeout duration for the operation, must be > 0 or SeekInvalidArgumentException occurs.
196
void
SeekToBeginning
(
utils
::
zstring_view
topic, std::uint32_t partition_id, std::chrono::milliseconds timeout)
197
const
;
198
199
/// @brief Seeks the specified topic partition to the end.
200
/// @throws SeekException if an error occurs during the seek operation.
201
/// @throws SeekInvalidArgumentException if invalid \b timeout is passed.
202
/// @warning This is a blocking call and should only be invoked after ConsumerScope::Start call and before
203
/// ConsumerScope::Stop call. It works only when the consumer has assigned partitions; otherwise, it throws
204
/// SeekException.
205
/// @warning Currently, it is required to call this from within the ConsumerRebalanceCallback.
206
/// @ref ConsumerScope::SetRebalanceCallback
207
/// @param topic The name of the topic.
208
/// @param partition_id The partition ID of the given topic.
209
/// @param timeout The timeout duration for the operation, must be > 0 or SeekInvalidArgumentException occurs.
210
void
SeekToEnd
(
utils
::
zstring_view
topic, std::uint32_t partition_id, std::chrono::milliseconds timeout)
const
;
211
212
private
:
213
friend
class
impl::Consumer;
214
215
explicit
ConsumerScope(impl::Consumer& consumer)
noexcept
;
216
217
impl::Consumer& consumer_;
218
};
219
220
}
// namespace kafka
221
222
USERVER_NAMESPACE_END
userver
kafka
consumer_scope.hpp
Generated on
for userver by
Doxygen
1.17.0