Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
ExecutionStrategy.hpp
1#pragma once
2
3#include "data/BackendCounters.hpp"
4#include "data/BackendInterface.hpp"
5#include "data/cassandra/Handle.hpp"
6#include "data/cassandra/Types.hpp"
7#include "data/cassandra/impl/AsyncExecutor.hpp"
8#include "util/Assert.hpp"
9#include "util/Batching.hpp"
10#include "util/log/Logger.hpp"
11
12#include <boost/asio.hpp>
13#include <boost/asio/associated_executor.hpp>
14#include <boost/asio/executor_work_guard.hpp>
15#include <boost/asio/io_context.hpp>
16#include <boost/asio/spawn.hpp>
17#include <boost/json/object.hpp>
18#include <fmt/format.h>
19
20#include <algorithm>
21#include <atomic>
22#include <chrono>
23#include <condition_variable>
24#include <cstddef>
25#include <cstdint>
26#include <functional>
27#include <memory>
28#include <mutex>
29#include <optional>
30#include <stdexcept>
31#include <string>
32#include <thread>
33#include <type_traits>
34#include <vector>
35
36namespace data::cassandra::impl {
37
38// TODO: this could probably be also moved out of impl and into the main cassandra namespace.
39
46template <typename HandleType = Handle, SomeBackendCounters BackendCountersType = BackendCounters>
48 util::Logger log_{"Backend"};
49
50 std::uint32_t maxWriteRequestsOutstanding_;
51 std::atomic_uint32_t numWriteRequestsOutstanding_ = 0;
52
53 std::uint32_t maxReadRequestsOutstanding_;
54 std::atomic_uint32_t numReadRequestsOutstanding_ = 0;
55
56 std::size_t writeBatchSize_;
57
58 std::mutex throttleMutex_;
59 std::condition_variable throttleCv_;
60
61 std::mutex syncMutex_;
62 std::condition_variable syncCv_;
63
64 boost::asio::io_context ioc_;
65 std::optional<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> work_;
66
67 std::reference_wrapper<HandleType const> handle_;
68 std::thread thread_;
69
70 BackendCountersType::PtrType counters_;
71
72public:
73 using ResultOrErrorType = HandleType::ResultOrErrorType;
74 using StatementType = HandleType::StatementType;
75 using PreparedStatementType = HandleType::PreparedStatementType;
76 using FutureType = HandleType::FutureType;
77 using FutureWithCallbackType = HandleType::FutureWithCallbackType;
78 using ResultType = HandleType::ResultType;
79 using CompletionTokenType = boost::asio::yield_context;
80
87 Settings const& settings,
88 HandleType const& handle,
89 BackendCountersType::PtrType counters = BackendCountersType::make()
90 )
91 : maxWriteRequestsOutstanding_{settings.maxWriteRequestsOutstanding}
92 , maxReadRequestsOutstanding_{settings.maxReadRequestsOutstanding}
93 , writeBatchSize_{settings.writeBatchSize}
94 , work_{boost::asio::make_work_guard(ioc_)}
95 , handle_{std::cref(handle)}
96 , thread_{[this] { ioc_.run(); }}
97 , counters_{std::move(counters)}
98 {
99 LOG(log_.info()) << "Max write requests outstanding is " << maxWriteRequestsOutstanding_
100 << "; Max read requests outstanding is " << maxReadRequestsOutstanding_;
101 }
102
103 ~DefaultExecutionStrategy()
104 {
105 work_.reset();
106 ioc_.stop();
107 thread_.join();
108 }
109
113 void
115 {
116 LOG(log_.debug()) << "Waiting to sync all writes...";
117 std::unique_lock<std::mutex> lck(syncMutex_);
118 syncCv_.wait(lck, [this] { return finishedAllWriteRequests(); });
119 LOG(log_.debug()) << "Sync done.";
120 }
121
125 [[nodiscard]] bool
126 isTooBusy() const
127 {
128 bool const result = numReadRequestsOutstanding_ >= maxReadRequestsOutstanding_;
129 if (result)
130 counters_->registerTooBusy();
131 return result;
132 }
133
139 ResultOrErrorType
140 writeSync(StatementType const& statement)
141 {
142 auto const startTime = std::chrono::steady_clock::now();
143 while (true) {
144 auto res = handle_.get().execute(statement);
145 if (res) {
146 counters_->registerWriteSync(startTime);
147 return res;
148 }
149
150 counters_->registerWriteSyncRetry();
151 LOG(log_.warn()) << "Cassandra sync write error, retrying: " << res.error();
152 std::this_thread::sleep_for(std::chrono::milliseconds(5));
153 }
154 }
155
161 template <typename... Args>
162 ResultOrErrorType
163 writeSync(PreparedStatementType const& preparedStatement, Args&&... args)
164 {
165 return writeSync(preparedStatement.bind(std::forward<Args>(args)...));
166 }
167
177 template <typename... Args>
178 void
179 write(PreparedStatementType const& preparedStatement, Args&&... args)
180 {
181 auto statement = preparedStatement.bind(std::forward<Args>(args)...);
182 write(std::move(statement));
183 }
184
193 void
194 write(StatementType&& statement)
195 {
196 auto const startTime = std::chrono::steady_clock::now();
197
198 incrementOutstandingRequestCount();
199
200 counters_->registerWriteStarted();
201 // Note: lifetime is controlled by std::shared_from_this internally
202 AsyncExecutor<std::decay_t<decltype(statement)>, HandleType>::run(
203 ioc_,
204 handle_,
205 std::move(statement),
206 [this, startTime](auto const&) {
207 decrementOutstandingRequestCount();
208
209 counters_->registerWriteFinished(startTime);
210 },
211 [this] { counters_->registerWriteRetry(); }
212 );
213 }
214
223 void
224 write(std::vector<StatementType>&& statements)
225 {
226 if (statements.empty())
227 return;
228
229 util::forEachBatch(std::move(statements), writeBatchSize_, [this](auto begin, auto end) {
230 auto const startTime = std::chrono::steady_clock::now();
231 auto chunk = std::vector<StatementType>{};
232
233 chunk.reserve(std::distance(begin, end));
234 std::move(begin, end, std::back_inserter(chunk));
235
236 incrementOutstandingRequestCount();
237 counters_->registerWriteStarted();
238
239 // Note: lifetime is controlled by std::shared_from_this internally
240 AsyncExecutor<std::decay_t<decltype(chunk)>, HandleType>::run(
241 ioc_,
242 handle_,
243 std::move(chunk),
244 [this, startTime](auto const&) {
245 decrementOutstandingRequestCount();
246 counters_->registerWriteFinished(startTime);
247 },
248 [this] { counters_->registerWriteRetry(); }
249 );
250 });
251 }
252
262 void
263 writeEach(std::vector<StatementType>&& statements)
264 {
265 std::ranges::for_each(std::move(statements), [this](auto& statement) {
266 this->write(std::move(statement));
267 });
268 }
269
281 template <typename... Args>
282 [[maybe_unused]] ResultOrErrorType
283 read(CompletionTokenType token, PreparedStatementType const& preparedStatement, Args&&... args)
284 {
285 return read(token, preparedStatement.bind(std::forward<Args>(args)...));
286 }
287
298 [[maybe_unused]] ResultOrErrorType
299 read(CompletionTokenType token, std::vector<StatementType> const& statements)
300 {
301 auto const startTime = std::chrono::steady_clock::now();
302
303 auto const numStatements = statements.size();
304 std::optional<FutureWithCallbackType> future;
305 counters_->registerReadStarted(numStatements);
306
307 // todo: perhaps use policy instead
308 while (true) {
309 numReadRequestsOutstanding_ += numStatements;
310
311 auto init = [this, &statements, &future]<typename Self>(Self& self) {
312 auto const sself = std::make_shared<Self>(std::move(self));
313
314 future.emplace(handle_.get().asyncExecute(statements, [sself](auto&& res) mutable {
315 boost::asio::post(
316 boost::asio::get_associated_executor(*sself),
317 [sself, res = std::forward<decltype(res)>(res)] mutable {
318 sself->complete(std::move(res));
319 }
320 );
321 }));
322 };
323
324 auto res = boost::asio::async_compose<CompletionTokenType, void(ResultOrErrorType)>(
325 std::move(init), token, boost::asio::get_associated_executor(token)
326 );
327 numReadRequestsOutstanding_ -= numStatements;
328
329 if (res) {
330 counters_->registerReadFinished(startTime, numStatements);
331 return res;
332 }
333
334 LOG(log_.error()) << "Failed batch read in coroutine: " << res.error();
335 try {
336 throwErrorIfNeeded(res.error());
337 } catch (...) {
338 counters_->registerReadError(numStatements);
339 throw;
340 }
341 counters_->registerReadRetry(numStatements);
342 }
343 }
344
355 [[maybe_unused]] ResultOrErrorType
356 read(CompletionTokenType token, StatementType const& statement)
357 {
358 auto const startTime = std::chrono::steady_clock::now();
359
360 std::optional<FutureWithCallbackType> future;
361 counters_->registerReadStarted();
362
363 // todo: perhaps use policy instead
364 while (true) {
365 ++numReadRequestsOutstanding_;
366 auto init = [this, &statement, &future]<typename Self>(Self& self) {
367 auto const sself = std::make_shared<Self>(std::move(self));
368
369 future.emplace(handle_.get().asyncExecute(statement, [sself](auto&& res) mutable {
370 boost::asio::post(
371 boost::asio::get_associated_executor(*sself),
372 [sself, res = std::forward<decltype(res)>(res)] mutable {
373 sself->complete(std::move(res));
374 }
375 );
376 }));
377 };
378
379 auto res = boost::asio::async_compose<CompletionTokenType, void(ResultOrErrorType)>(
380 std::move(init), token, boost::asio::get_associated_executor(token)
381 );
382 --numReadRequestsOutstanding_;
383
384 if (res) {
385 counters_->registerReadFinished(startTime);
386 return res;
387 }
388
389 LOG(log_.error()) << "Failed read in coroutine: " << res.error();
390 try {
391 throwErrorIfNeeded(res.error());
392 } catch (...) {
393 counters_->registerReadError();
394 throw;
395 }
396 counters_->registerReadRetry();
397 }
398 }
399
411 std::vector<ResultType>
412 readEach(CompletionTokenType token, std::vector<StatementType> const& statements)
413 {
414 auto const startTime = std::chrono::steady_clock::now();
415
416 std::atomic_uint64_t errorsCount = 0u;
417 std::atomic_int numOutstanding = statements.size();
418 numReadRequestsOutstanding_ += statements.size();
419
420 auto futures = std::vector<FutureWithCallbackType>{};
421 futures.reserve(numOutstanding);
422 counters_->registerReadStarted(statements.size());
423
424 auto init = [this, &statements, &futures, &errorsCount, &numOutstanding]<typename Self>(
425 Self& self
426 ) {
427 auto const sself = std::make_shared<Self>(std::move(self));
428 auto executionHandler =
429 [&errorsCount, &numOutstanding, sself](auto const& res) mutable {
430 if (not res)
431 ++errorsCount;
432
433 // when all async operations complete unblock the result
434 if (--numOutstanding == 0) {
435 boost::asio::post(
436 boost::asio::get_associated_executor(*sself),
437 [sself] mutable { sself->complete(); }
438 );
439 }
440 };
441
442 std::transform(
443 std::cbegin(statements),
444 std::cend(statements),
445 std::back_inserter(futures),
446 [this, &executionHandler](auto const& statement) {
447 return handle_.get().asyncExecute(statement, executionHandler);
448 }
449 );
450 };
451
452 boost::asio::async_compose<CompletionTokenType, void()>(
453 std::move(init), token, boost::asio::get_associated_executor(token)
454 );
455 numReadRequestsOutstanding_ -= statements.size();
456
457 if (errorsCount > 0) {
458 ASSERT(
459 errorsCount <= statements.size(), "Errors number cannot exceed statements number"
460 );
461 counters_->registerReadError(errorsCount);
462 counters_->registerReadFinished(startTime, statements.size() - errorsCount);
463 throw DatabaseError{};
464 }
465 counters_->registerReadFinished(startTime, statements.size());
466
467 std::vector<ResultType> results;
468 results.reserve(futures.size());
469
470 // it's safe to call blocking get on futures here as we already waited for the coroutine to
471 // resume above.
472 std::transform(
473 std::make_move_iterator(std::begin(futures)),
474 std::make_move_iterator(std::end(futures)),
475 std::back_inserter(results),
476 [](auto&& future) {
477 // Must be non-const so the result can be moved out below
478 // NOLINTNEXTLINE(misc-const-correctness)
479 auto entry = future.get();
480 auto&& res = entry.value();
481 return std::move(res);
482 }
483 );
484
485 ASSERT(
486 futures.size() == statements.size(),
487 "Futures size must be equal to statements size. Got {} and {}",
488 futures.size(),
489 statements.size()
490 );
491 ASSERT(
492 results.size() == statements.size(),
493 "Results size must be equal to statements size. Got {} and {}",
494 results.size(),
495 statements.size()
496 );
497 return results;
498 }
499
503 [[nodiscard]] boost::json::object
504 stats() const
505 {
506 return counters_->report();
507 }
508
509private:
510 void
511 incrementOutstandingRequestCount()
512 {
513 {
514 std::unique_lock<std::mutex> lck(throttleMutex_);
515 if (!canAddWriteRequest()) {
516 LOG(log_.trace()) << "Max outstanding requests reached. "
517 << "Waiting for other requests to finish";
518 throttleCv_.wait(lck, [this] { return canAddWriteRequest(); });
519 }
520 }
521 ++numWriteRequestsOutstanding_;
522 }
523
524 void
525 decrementOutstandingRequestCount()
526 {
527 // sanity check
528 ASSERT(numWriteRequestsOutstanding_ > 0, "Decrementing num outstanding below 0");
529 size_t const cur = (--numWriteRequestsOutstanding_);
530 {
531 // mutex lock required to prevent race condition around spurious
532 // wakeup
533 std::scoped_lock const lck(throttleMutex_);
534 throttleCv_.notify_one();
535 }
536 if (cur == 0) {
537 // mutex lock required to prevent race condition around spurious
538 // wakeup
539 std::scoped_lock const lck(syncMutex_);
540 syncCv_.notify_one();
541 }
542 }
543
544 [[nodiscard]] bool
545 canAddWriteRequest() const
546 {
547 return numWriteRequestsOutstanding_ < maxWriteRequestsOutstanding_;
548 }
549
550 [[nodiscard]] bool
551 finishedAllWriteRequests() const
552 {
553 return numWriteRequestsOutstanding_ == 0;
554 }
555
556 void
557 throwErrorIfNeeded(CassandraError err) const
558 {
559 // NOTE: etl::impl::Loader and etl::impl::Extractor treat std::runtime_error as
560 // "amendment blocked", so only genuinely permanent failures may be thrown as one.
561 if (err.isInvalidQuery())
562 throw std::runtime_error("Invalid query");
563
564 // anything else, including unclassified codes, is transient and gets retried
565 throw DatabaseError{fmt::format("Database error [{}]: {}", err.code(), err.message())};
566 }
567};
568
569} // namespace data::cassandra::impl
Represents a transient database error that the caller should retry.
Definition BackendInterface.hpp:41
A query executor with a changeable retry policy.
Definition AsyncExecutor.hpp:37
ResultOrErrorType read(CompletionTokenType token, StatementType const &statement)
Coroutine-based query execution used for reading data.
Definition ExecutionStrategy.hpp:356
void write(StatementType &&statement)
Non-blocking query execution used for writing data.
Definition ExecutionStrategy.hpp:194
ResultOrErrorType read(CompletionTokenType token, PreparedStatementType const &preparedStatement, Args &&... args)
Coroutine-based query execution used for reading data.
Definition ExecutionStrategy.hpp:283
ResultOrErrorType read(CompletionTokenType token, std::vector< StatementType > const &statements)
Coroutine-based query execution used for reading data.
Definition ExecutionStrategy.hpp:299
void write(PreparedStatementType const &preparedStatement, Args &&... args)
Non-blocking query execution used for writing data.
Definition ExecutionStrategy.hpp:179
void write(std::vector< StatementType > &&statements)
Non-blocking batched query execution used for writing data.
Definition ExecutionStrategy.hpp:224
void sync()
Wait for all async writes to finish before unblocking.
Definition ExecutionStrategy.hpp:114
ResultOrErrorType writeSync(PreparedStatementType const &preparedStatement, Args &&... args)
Blocking query execution used for writing data.
Definition ExecutionStrategy.hpp:163
DefaultExecutionStrategy(Settings const &settings, HandleType const &handle, BackendCountersType::PtrType counters=BackendCountersType::make())
Definition ExecutionStrategy.hpp:86
bool isTooBusy() const
Definition ExecutionStrategy.hpp:126
ResultOrErrorType writeSync(StatementType const &statement)
Blocking query execution used for writing data.
Definition ExecutionStrategy.hpp:140
std::vector< ResultType > readEach(CompletionTokenType token, std::vector< StatementType > const &statements)
Coroutine-based query execution used for reading data.
Definition ExecutionStrategy.hpp:412
boost::json::object stats() const
Get statistics about the backend.
Definition ExecutionStrategy.hpp:504
void writeEach(std::vector< StatementType > &&statements)
Non-blocking query execution used for writing data. Contrast with write, this method does not execute...
Definition ExecutionStrategy.hpp:263
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:110
Pump info(std::source_location const &loc=std::source_location::current()) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:499
Pump trace(std::source_location const &loc=std::source_location::current()) const
Interface for logging at Severity::TRC severity.
Definition Logger.cpp:489
void forEachBatch(std::ranges::forward_range auto &&container, std::size_t batchSize, auto &&fn)
Iterate over a container in batches.
Definition Batching.hpp:19
Bundles all cassandra settings in one place.
Definition Cluster.hpp:37