userver: userver/ydb/topic.hpp Source File
Loading...
Searching...
No Matches
topic.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/ydb/topic.hpp
4/// @brief YDB Topic client
5
6#include <atomic>
7#include <chrono>
8#include <cstdint>
9#include <memory>
10#include <optional>
11#include <string>
12#include <string_view>
13
14#include <ydb-cpp-sdk/client/topic/client.h>
15#include <ydb-cpp-sdk/client/topic/producer.h>
16#include <ydb-cpp-sdk/client/types/executor/executor.h>
17
18#include <userver/compiler/impl/lifetime.hpp>
19#include <userver/engine/deadline.hpp>
20#include <userver/utils/impl/internal_tag.hpp>
21#include <userver/utils/statistics/fwd.hpp>
22
23USERVER_NAMESPACE_BEGIN
24
25namespace ydb {
26
27namespace impl {
28class Driver;
29struct TopicProducerStatistics;
30struct TopicSettings;
31} // namespace impl
32
33/// @brief Read session used to connect to one or more topics for reading
34///
35/// @see https://ydb.tech/docs/en/reference/ydb-sdk/topic#reading
36///
37/// ## Example usage:
38///
39/// @ref samples/ydb_service/components/topic_reader.hpp
40/// @ref samples/ydb_service/components/topic_reader.cpp
41///
42/// @example samples/ydb_service/components/topic_reader.hpp
43class TopicReadSession final {
44public:
45 /// @cond
46 // For internal use only.
47 explicit TopicReadSession(std::shared_ptr<NYdb::NTopic::IReadSession> read_session);
48 /// @endcond
49
50 /// @brief Get read session events
51 ///
52 /// Waits until event occurs
53 /// @param max_events_count maximum events count in batch
54 /// @param max_size_bytes total size limit for data messages in batch
55 /// if not specified, read session chooses event batch size automatically
59 );
60
61 /// @brief Get read session events
62 ///
63 /// Waits until event occurs
64 /// @param settings ydb native read session settings
67 );
68
69 /// @brief Close read session
70 ///
71 /// Waits for all commit acknowledgments to arrive.
72 /// Force close after timeout
73 bool Close(std::chrono::milliseconds timeout);
74
75 /// @brief Get native read session
76 ///
77 /// @warning Use with care! Facilities from @ref userver/drivers/subscribable_futures.hpp can help
78 /// with non-blocking wait operations.
79 NYdb::NTopic::IReadSession& GetNativeTopicReadSession() USERVER_IMPL_LIFETIME_BOUND;
80
81private:
82 std::shared_ptr<NYdb::NTopic::IReadSession> read_session_;
83};
84
85/// @brief Write session used to connect to a topic for writting
86///
87/// @see https://ydb.tech/docs/en/reference/ydb-sdk/topic#write
88class TopicWriteSession final {
89public:
90 /// @cond
91 /// For internal use only.
92 explicit TopicWriteSession(std::shared_ptr<NYdb::NTopic::IWriteSession> write_session);
93 /// @endcond
94
95 /// @brief Wait for the next write session event
96 ///
97 /// Suspends the current coroutine until an event is available, then returns it without blocking the thread.
98 NYdb::NTopic::TWriteSessionEvent::TEvent GetEvent();
99
100 /// @brief Poll for a write session event without waiting
101 ///
102 /// Returns the next buffered event immediately if one is available, or `std::nullopt` if the event queue is empty.
103 /// Does not suspend the coroutine.
104 ///
105 /// @note Sometimes may return `std::nullopt` even if an event is available. Intended for use in loops.
106 std::optional<NYdb::NTopic::TWriteSessionEvent::TEvent> TryGetEvent();
107
108 /// @brief Write a messsage using a continuation token from TReadyToAcceptEvent
109 ///
110 /// Must be called only after receiving TReadyToAcceptEvent from GetEvent() or TryGetEvent().
111 void Write(NYdb::NTopic::TContinuationToken&& token, NYdb::NTopic::TWriteMessage&& message);
112
113 /// @brief Close write session
114 ///
115 /// Waits for all in-flights messages to be acknowledged.
116 /// Force closes after timeout
117 bool Close(std::chrono::milliseconds timeout);
118
119 /// @brief Get native write session
120 ///
121 /// @warning Use with care! Facilities from @ref userver/drivers/subscribable_futures.hpp can help
122 /// with non-blocking wait operations.
123 NYdb::NTopic::IWriteSession& GetNativeTopicWriteSession() USERVER_IMPL_LIFETIME_BOUND;
124
125private:
126 std::shared_ptr<NYdb::NTopic::IWriteSession> write_session_;
127};
128
129/// @brief Simple write session used to write messages to a topic without
130/// manually handling write session events.
131///
132/// This is a userver-native analogue of YDB SDK
133/// `ISimpleBlockingWriteSession`: methods may wait for YDB flow-control
134/// continuation tokens, but waiting suspends the current coroutine instead of
135/// blocking an OS thread. It wraps a single `IWriteSession`; its simple API does
136/// not expose the native event loop or acknowledgments.
137///
138/// @see https://ydb.tech/docs/en/reference/ydb-sdk/topic#write
139class TopicSimpleWriteSession final {
140public:
141 /// @cond
142 /// For internal use only.
143 explicit TopicSimpleWriteSession(std::shared_ptr<NYdb::NTopic::IWriteSession> write_session);
144 /// @endcond
145
146 TopicSimpleWriteSession(const TopicSimpleWriteSession&) = delete;
147 TopicSimpleWriteSession& operator=(const TopicSimpleWriteSession&) = delete;
148 TopicSimpleWriteSession(TopicSimpleWriteSession&&) noexcept;
149 TopicSimpleWriteSession& operator=(TopicSimpleWriteSession&&) noexcept;
150
151 /// @brief Write a single message.
152 ///
153 /// Waits until YDB provides a continuation token or until `deadline`.
154 /// @returns true if the message was enqueued for writing, false if the
155 /// deadline was reached or the session was closed before a token arrived.
156 bool Write(
157 NYdb::NTopic::TWriteMessage&& message,
158 NYdb::TTransactionBase* tx = nullptr,
159 engine::Deadline deadline = {}
160 );
161
162 /// @brief Write a single message using basic message options.
163 bool Write(
164 std::string_view data,
165 std::optional<std::uint64_t> seq_no = std::nullopt,
166 std::optional<std::chrono::system_clock::time_point> create_timestamp = std::nullopt,
167 engine::Deadline deadline = {}
168 );
169
170 /// @brief Wait until initial SeqNo is discovered from the server.
171 std::uint64_t GetInitSeqNo(engine::Deadline deadline = {});
172
173 /// @brief Close the write session.
174 ///
175 /// Waits for all in-flight messages to be acknowledged.
176 /// Force closes after `timeout`.
177 /// @returns `true` if all writes were completed and acknowledged. Returns
178 /// `false` if the timeout expired and some writes were aborted; in that
179 /// case their delivery is not guaranteed and should be handled as an
180 /// application-level delivery failure.
181 bool Close(std::chrono::milliseconds timeout);
182
183 /// @brief Returns true if the write session is alive and active.
184 bool IsAlive() const noexcept;
185
186 /// @brief Get native write session
187 ///
188 /// @warning Use with care! Facilities from @ref userver/drivers/subscribable_futures.hpp can help
189 /// with non-blocking wait operations.
190 NYdb::NTopic::IWriteSession& GetNativeTopicWriteSession() USERVER_IMPL_LIFETIME_BOUND;
191
192private:
193 std::optional<NYdb::NTopic::TContinuationToken> WaitForToken(engine::Deadline deadline);
194
195 std::shared_ptr<NYdb::NTopic::IWriteSession> write_session_;
196 std::atomic_bool closed_{false};
197};
198
199/// @brief Settings for TopicProducer.
200class TopicProducerSettings final : public NYdb::NTopic::TProducerSettings {
201public:
202 /// @brief Sets the timeout for waiting for buffered message acknowledgments
203 /// when TopicProducer is destroyed.
204 ///
205 /// Defaults to 0ms: does not wait for acknowledgments. If the timeout
206 /// expires, delivery of unacknowledged messages is not guaranteed.
207 TopicProducerSettings& CloseTimeout(std::chrono::milliseconds timeout) noexcept;
208
209 /// @brief Get the graceful close timeout.
210 std::chrono::milliseconds GetCloseTimeout() const noexcept;
211
212private:
213 using NYdb::NTopic::TProducerSettings::MaxBlockTimeout;
214 using NYdb::NTopic::TProducerSettings::MaxBlockTimeout_;
215 using NYdb::NTopic::TProducerSettings::MaxMemoryUsage;
216 using NYdb::NTopic::TProducerSettings::MaxMemoryUsage_;
217
218 std::chrono::milliseconds close_timeout_{std::chrono::milliseconds::zero()};
219};
220
221/// @brief Native YDB producer used for partition-aware writes to a topic.
222///
223/// Unlike TopicSimpleWriteSession, this is a wrapper around the YDB SDK
224/// `IProducer`. It selects partitions by message key or explicit partition and
225/// manages the corresponding write sessions internally.
226///
227/// Write() fails immediately if the internal buffer is overloaded.
228///
229/// The SDK close call runs on the blocking task processor and suspends the calling
230/// coroutine until it completes. It requires a userver coroutine context.
231/// Destruction and move assignment close an existing producer if
232/// @ref ydb::TopicProducer::Close has not been called.
233///
234/// @warning The destruction timeout configured with
235/// @ref ydb::TopicProducerSettings::CloseTimeout defaults to zero: pending
236/// messages are not guaranteed to be delivered.
237///
238/// @see https://ydb.tech/docs/en/reference/ydb-sdk/topic#write
239class TopicProducer final {
240public:
241 /// @cond
242 /// For internal use only.
243 explicit TopicProducer(
244 utils::impl::InternalTag,
245 std::shared_ptr<NYdb::NTopic::IProducer> producer,
246 std::chrono::milliseconds close_timeout
247 );
248 /// @endcond
249
250 TopicProducer(const TopicProducer&) = delete;
251 TopicProducer(TopicProducer&&) noexcept;
252 TopicProducer& operator=(const TopicProducer&) = delete;
253 TopicProducer& operator=(TopicProducer&&) noexcept;
254 ~TopicProducer();
255
256 /// @brief Write a single message to the topic.
257 ///
258 /// Adds the message to the internal buffer and returns its queueing status.
259 /// Fails immediately with `EWriteStatus::Timeout` if the buffer is full.
260 /// Use Flush() to wait for the buffered messages to be persistently written.
261 NYdb::NTopic::TWriteResult Write(NYdb::NTopic::TWriteMessage&& message);
262
263 /// @brief Flush all buffered messages to the server.
264 ///
265 /// Waits until all in-flight messages are acknowledged.
266 /// @param deadline timeout for flush completion
267 NYdb::NTopic::TFlushResult Flush(engine::Deadline deadline = {});
268
269 /// @brief Close the producer.
270 ///
271 /// Waits for all in-flight messages to be acknowledged.
272 /// Force closes after timeout.
273 /// Repeated calls return `AlreadyClosed`.
274 NYdb::NTopic::TCloseResult Close(std::chrono::milliseconds timeout);
275
276 /// @brief Get native producer.
277 ///
278 /// @warning Use with care! Facilities from @ref userver/drivers/subscribable_futures.hpp can help
279 /// with non-blocking wait operations.
280 NYdb::NTopic::IProducer& GetNativeTopicProducer() USERVER_IMPL_LIFETIME_BOUND;
281
282private:
283 class Impl;
284 std::unique_ptr<Impl> impl_;
285 std::shared_ptr<impl::TopicProducerStatistics> statistics_;
286
287 friend void DumpMetric(utils::statistics::Writer& writer, const TopicProducer& producer);
288};
289
290/// @brief Export local write counters preserved across producer moves.
291/// Counts completed wrapper calls only; queue acceptance does not mean delivery.
292void DumpMetric(utils::statistics::Writer& writer, const TopicProducer& producer);
293
294/// @ingroup userver_clients
295///
296/// @brief YDB Topic Client
297///
298/// @see https://ydb.tech/docs/en/concepts/topic
299class TopicClient final {
300public:
301 static constexpr std::uint64_t kDefaultProducerMaxMemoryUsageBytes = 2ULL * 1024 * 1024 * 1024;
302
303 /// @cond
304 // For internal use only.
305 TopicClient(std::shared_ptr<impl::Driver> driver, impl::TopicSettings settings);
306 /// @endcond
307
308 ~TopicClient();
309
310 /// Alter topic
311 void AlterTopic(const std::string& path, const NYdb::NTopic::TAlterTopicSettings& settings);
312
313 /// Describe topic
314 NYdb::NTopic::TDescribeTopicResult DescribeTopic(const std::string& path);
315
316 /// Create read session
317 TopicReadSession CreateReadSession(const NYdb::NTopic::TReadSessionSettings& settings);
318
319 /// Create write session
320 TopicWriteSession CreateWriteSession(const NYdb::NTopic::TWriteSessionSettings& settings);
321
322 /// Create simple write session.
323 ///
324 /// @note Event handlers from `settings` are not compatible with
325 /// TopicSimpleWriteSession. They are reset with a warning.
326 TopicSimpleWriteSession CreateSimpleWriteSession(const NYdb::NTopic::TWriteSessionSettings& settings);
327
328 /// Create producer.
329 ///
330 /// Unlike TopicSimpleWriteSession, TopicProducer is a native YDB
331 /// multi-session producer: it routes each message by key or explicit
332 /// partition and fails immediately if its buffer is overloaded. Flush()
333 /// waits for persistence without closing the producer;
334 /// TopicSimpleWriteSession instead flushes pending writes as part of
335 /// Close().
336 /// @param settings producer settings (topic path, partitioner, etc.)
337 /// @param max_memory_usage_bytes maximum buffered message memory in bytes
338 TopicProducer CreateProducer(
339 const TopicProducerSettings& settings,
340 std::uint64_t max_memory_usage_bytes = kDefaultProducerMaxMemoryUsageBytes
341 );
342
343 /// Get native topic client
344 /// @warning Use with care! Facilities from
345 /// `<core/include/userver/drivers/subscribable_futures.hpp>` can help with
346 /// non-blocking wait operations.
347 NYdb::NTopic::TTopicClient& GetNativeTopicClient() USERVER_IMPL_LIFETIME_BOUND;
348
349private:
350 std::shared_ptr<impl::Driver> driver_;
351 // Owned executors: Stop() only after `topic_client_` is destroyed (see
352 // ~TopicClient). Joining these threads after the native client is gone
353 // avoids atexit use-after-destroy (e.g. SEGV in TCodecMap). Stopping them
354 // while TTopicClient is still alive would deadlock or stall writes.
355 NYdb::IExecutor::TPtr compression_executor_;
356 NYdb::IExecutor::TPtr handlers_executor_;
357 // `reset()` in ~TopicClient runs before Stop() on the executors above.
358 std::optional<NYdb::NTopic::TTopicClient> topic_client_;
359};
360
361} // namespace ydb
362
363USERVER_NAMESPACE_END