userver: userver/kafka/producer.hpp Source File
Loading...
Searching...
No Matches
producer.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/kafka/producer.hpp
4/// @brief @copybrief kafka::Producer
5
6#include <cstdint>
7#include <type_traits>
8#include <utility>
9
10#include <userver/engine/task/task_processor_fwd.hpp>
11#include <userver/engine/task/task_with_result.hpp>
12#include <userver/kafka/exceptions.hpp>
13#include <userver/kafka/headers.hpp>
14#include <userver/kafka/impl/messages.hpp>
15#include <userver/utils/fast_pimpl.hpp>
16#include <userver/utils/statistics/writer.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace kafka {
21
22/// @brief Unassigned partition.
23///
24/// The unassigned partition is used by the producer API for messages
25/// that should be partitioned using the default partitioner.
26///
27/// @note By default partitions are distributed uniformly.
28extern const std::optional<std::uint32_t> kUnassignedPartition;
29
30namespace impl {
31
32class Configuration;
33class ProducerImpl;
34
35struct ProducerConfiguration;
36struct Secret;
37
38class HeadersHolder;
39
40} // namespace impl
41
42/// @ingroup userver_clients
43///
44/// @brief Apache Kafka Producer Client.
45///
46/// It exposes the API to send an arbitrary message to the Kafka Broker to
47/// certain topic by given key and optional partition.
48///
49/// ## Important implementation details
50///
51/// Message send tasks handling other messages' delivery reports, suspending
52/// their execution while no events exist.
53/// This makes message production parallel and leads to high Producer
54/// scalability.
55///
56/// Producer maintains per topic statistics including the broker
57/// connection errors.
58///
59/// @see https://docs.confluent.io/platform/current/clients/producer.html
60class Producer final {
61public:
62 /// @cond
63 // @param producer_task_processor is task processor where producer creates
64 // tasks for message delivery scheduling and waiting.
65 Producer(
66 const std::string& name,
67 engine::TaskProcessor& producer_task_processor,
68 const impl::ProducerConfiguration& configuration,
69 const impl::Secret& secrets
70 );
71 /// @endcond
72
73 /// @brief Waits without a timeout for outstanding SendAsync tasks, including
74 /// tasks still queued to run. Then flushes Kafka for up to 2 x `delivery_timeout`.
75 ///
76 /// @remark In a basic producer use cases, the destructor returns immediately.
78
79 Producer(const Producer&) = delete;
80 Producer(Producer&&) = delete;
81
82 Producer& operator=(const Producer&) = delete;
83 Producer& operator=(Producer&&) = delete;
84
85 /// @brief Sends given message to topic `topic_name` by given `key`
86 /// and `partition` (if passed) with payload contains the `message`
87 /// data. Asynchronously waits until the message is delivered or the delivery error occurred.
88 ///
89 /// No payload data is copied. Method holds the data until message is delivered.
90 ///
91 /// Thread-safe and can be called from any number of threads concurrently.
92 ///
93 /// If `partition` not passed, partition is chosen by internal Kafka partitioner.
94 ///
95 /// @warning if `enable_idempotence` option is enabled, do not use both explicit partitions and Kafka-chosen ones.
96 ///
97 /// @throws SendException and its descendants if message is not delivered
98 /// and acked by Kafka Broker in configured timeout.
99 ///
100 /// @note Use SendException::IsRetryable method to understand whether there is a sense to retry the message sending.
101 /// @snippet kafka/tests/producer_kafkatest.cpp Producer retryable error
102 void Send(
103 utils::zstring_view topic_name,
104 std::string_view key,
105 std::string_view message,
106 std::optional<std::uint32_t> partition = kUnassignedPartition,
107 HeaderViews headers = {}
108 ) const;
109
110 /// @brief Sends given messages to topic `topic_name` by given `key`
111 /// and `partition` (if passed) with payload contains the `messages`
112 /// data. Asynchronously waits until the messages are delivered or the delivery error occurred.
113 ///
114 /// No payload data is copied. Method holds the data until messages are delivered.
115 ///
116 /// Thread-safe and can be called from any number of threads concurrently.
117 ///
118 /// If `partition` not passed, partition is chosen by internal Kafka partitioner.
119 ///
120 /// @warning if `enable_idempotence` option is enabled, do not use both explicit partitions and Kafka-chosen ones.
121 ///
122 /// @throws BulkSendException if some messages was not delivered
123 /// and acked by Kafka Broker in configured timeout.
124 ///
125 /// @note Use BulkSendException::GetExceptions method to get a list of occured nested exceptions.
126 template <typename Messages>
127 requires(
128 std::is_convertible_v<decltype(std::declval<const Messages&>()[0]), std::string_view> &&
129 std::is_integral_v<decltype(std::declval<const Messages&>().size())>
130 )
131 void Send(
132 utils::zstring_view topic_name,
133 std::string_view key,
134 const Messages& messages,
135 std::optional<std::uint32_t> partition = kUnassignedPartition,
136 HeaderViews headers = {}
137 ) const {
138 SendWrapper(topic_name, key, impl::MessagesAdapter{messages}, partition, std::move(headers));
139 }
140
141 /// @brief Same as Producer::Send, but returns the task which can be
142 /// used to wait the message delivery manually.
143 /// The producer destructor waits for outstanding sends.
144 ///
145 /// @warning If user schedules a batch of send requests with Producer::SendAsync, some send
146 /// requests may be retried by the library (for instance, in case of network
147 /// blink). Though, the order messages are written to partition may differ
148 /// from the order messages are initially sent
149 /// @snippet kafka/tests/producer_kafkatest.cpp Producer batch send async
150 [[nodiscard]] engine::TaskWithResult<void> SendAsync(
151 std::string topic_name,
152 std::string key,
153 std::string message,
154 std::optional<std::uint32_t> partition = kUnassignedPartition,
155 HeaderViews headers = {}
156 ) const;
157
158 /// @brief Dumps per topic messages produce statistics. No expected to be
159 /// called manually.
160 /// @see kafka/impl/stats.hpp
161 void DumpMetric(utils::statistics::Writer& writer) const;
162
163private:
164 void SendImpl(
165 utils::zstring_view topic_name,
166 std::string_view key,
167 std::string_view message,
168 std::optional<std::uint32_t> partition,
169 impl::HeadersHolder&& headers_holder
170 ) const;
171
172 void SendImpl(
173 utils::zstring_view topic_name,
174 std::string_view key,
175 const impl::Messages& messages,
176 std::optional<std::uint32_t> partition,
177 std::vector<impl::HeadersHolder>&& headers_holders
178 ) const;
179
180 void SendWrapper(
181 utils::zstring_view topic_name,
182 std::string_view key,
183 const impl::Messages& messages,
184 std::optional<std::uint32_t> partition,
185 HeaderViews headers
186 ) const;
187
188 const std::string name_;
189 engine::TaskProcessor& producer_task_processor_;
190
191 static constexpr std::size_t kImplSize{960};
192 static constexpr std::size_t kImplAlign{16};
193 utils::FastPimpl<impl::ProducerImpl, kImplSize, kImplAlign> producer_;
194};
195
196} // namespace kafka
197
198USERVER_NAMESPACE_END