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"
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>
23#include <condition_variable>
36namespace data::cassandra::impl {
46template <
typename HandleType = Handle, SomeBackendCounters BackendCountersType = BackendCounters>
50 std::uint32_t maxWriteRequestsOutstanding_;
51 std::atomic_uint32_t numWriteRequestsOutstanding_ = 0;
53 std::uint32_t maxReadRequestsOutstanding_;
54 std::atomic_uint32_t numReadRequestsOutstanding_ = 0;
56 std::size_t writeBatchSize_;
58 std::mutex throttleMutex_;
59 std::condition_variable throttleCv_;
61 std::mutex syncMutex_;
62 std::condition_variable syncCv_;
64 boost::asio::io_context ioc_;
65 std::optional<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> work_;
67 std::reference_wrapper<HandleType const> handle_;
70 BackendCountersType::PtrType counters_;
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;
88 HandleType
const& handle,
89 BackendCountersType::PtrType counters = BackendCountersType::make()
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)}
99 LOG(log_.
info()) <<
"Max write requests outstanding is " << maxWriteRequestsOutstanding_
100 <<
"; Max read requests outstanding is " << maxReadRequestsOutstanding_;
103 ~DefaultExecutionStrategy()
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.";
128 bool const result = numReadRequestsOutstanding_ >= maxReadRequestsOutstanding_;
130 counters_->registerTooBusy();
142 auto const startTime = std::chrono::steady_clock::now();
144 auto res = handle_.get().execute(statement);
146 counters_->registerWriteSync(startTime);
150 counters_->registerWriteSyncRetry();
151 LOG(log_.warn()) <<
"Cassandra sync write error, retrying: " << res.error();
152 std::this_thread::sleep_for(std::chrono::milliseconds(5));
161 template <
typename... Args>
163 writeSync(PreparedStatementType
const& preparedStatement, Args&&... args)
165 return writeSync(preparedStatement.bind(std::forward<Args>(args)...));
177 template <
typename... Args>
179 write(PreparedStatementType
const& preparedStatement, Args&&... args)
181 auto statement = preparedStatement.bind(std::forward<Args>(args)...);
182 write(std::move(statement));
196 auto const startTime = std::chrono::steady_clock::now();
198 incrementOutstandingRequestCount();
200 counters_->registerWriteStarted();
202 AsyncExecutor<std::decay_t<
decltype(statement)>, HandleType>::run(
205 std::move(statement),
206 [
this, startTime](
auto const&) {
207 decrementOutstandingRequestCount();
209 counters_->registerWriteFinished(startTime);
211 [
this] { counters_->registerWriteRetry(); }
224 write(std::vector<StatementType>&& statements)
226 if (statements.empty())
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>{};
233 chunk.reserve(std::distance(begin, end));
234 std::move(begin, end, std::back_inserter(chunk));
236 incrementOutstandingRequestCount();
237 counters_->registerWriteStarted();
240 AsyncExecutor<std::decay_t<
decltype(chunk)>, HandleType>::run(
244 [
this, startTime](
auto const&) {
245 decrementOutstandingRequestCount();
246 counters_->registerWriteFinished(startTime);
248 [
this] { counters_->registerWriteRetry(); }
265 std::ranges::for_each(std::move(statements), [
this](
auto& statement) {
266 this->
write(std::move(statement));
281 template <
typename... Args>
282 [[maybe_unused]] ResultOrErrorType
283 read(CompletionTokenType token, PreparedStatementType
const& preparedStatement, Args&&... args)
285 return read(token, preparedStatement.bind(std::forward<Args>(args)...));
298 [[maybe_unused]] ResultOrErrorType
299 read(CompletionTokenType token, std::vector<StatementType>
const& statements)
301 auto const startTime = std::chrono::steady_clock::now();
303 auto const numStatements = statements.size();
304 std::optional<FutureWithCallbackType> future;
305 counters_->registerReadStarted(numStatements);
309 numReadRequestsOutstanding_ += numStatements;
311 auto init = [
this, &statements, &future]<
typename Self>(Self& self) {
312 auto const sself = std::make_shared<Self>(std::move(self));
314 future.emplace(handle_.get().asyncExecute(statements, [sself](
auto&& res)
mutable {
316 boost::asio::get_associated_executor(*sself),
317 [sself, res = std::forward<decltype(res)>(res)] mutable {
318 sself->complete(std::move(res));
324 auto res = boost::asio::async_compose<CompletionTokenType, void(ResultOrErrorType)>(
325 std::move(init), token, boost::asio::get_associated_executor(token)
327 numReadRequestsOutstanding_ -= numStatements;
330 counters_->registerReadFinished(startTime, numStatements);
334 LOG(log_.error()) <<
"Failed batch read in coroutine: " << res.error();
336 throwErrorIfNeeded(res.error());
338 counters_->registerReadError(numStatements);
341 counters_->registerReadRetry(numStatements);
355 [[maybe_unused]] ResultOrErrorType
356 read(CompletionTokenType token, StatementType
const& statement)
358 auto const startTime = std::chrono::steady_clock::now();
360 std::optional<FutureWithCallbackType> future;
361 counters_->registerReadStarted();
365 ++numReadRequestsOutstanding_;
366 auto init = [
this, &statement, &future]<
typename Self>(Self& self) {
367 auto const sself = std::make_shared<Self>(std::move(self));
369 future.emplace(handle_.get().asyncExecute(statement, [sself](
auto&& res)
mutable {
371 boost::asio::get_associated_executor(*sself),
372 [sself, res = std::forward<decltype(res)>(res)] mutable {
373 sself->complete(std::move(res));
379 auto res = boost::asio::async_compose<CompletionTokenType, void(ResultOrErrorType)>(
380 std::move(init), token, boost::asio::get_associated_executor(token)
382 --numReadRequestsOutstanding_;
385 counters_->registerReadFinished(startTime);
389 LOG(log_.error()) <<
"Failed read in coroutine: " << res.error();
391 throwErrorIfNeeded(res.error());
393 counters_->registerReadError();
396 counters_->registerReadRetry();
411 std::vector<ResultType>
412 readEach(CompletionTokenType token, std::vector<StatementType>
const& statements)
414 auto const startTime = std::chrono::steady_clock::now();
416 std::atomic_uint64_t errorsCount = 0u;
417 std::atomic_int numOutstanding = statements.size();
418 numReadRequestsOutstanding_ += statements.size();
420 auto futures = std::vector<FutureWithCallbackType>{};
421 futures.reserve(numOutstanding);
422 counters_->registerReadStarted(statements.size());
424 auto init = [
this, &statements, &futures, &errorsCount, &numOutstanding]<
typename Self>(
427 auto const sself = std::make_shared<Self>(std::move(self));
428 auto executionHandler =
429 [&errorsCount, &numOutstanding, sself](
auto const& res)
mutable {
434 if (--numOutstanding == 0) {
436 boost::asio::get_associated_executor(*sself),
437 [sself]
mutable { sself->complete(); }
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);
452 boost::asio::async_compose<CompletionTokenType, void()>(
453 std::move(init), token, boost::asio::get_associated_executor(token)
455 numReadRequestsOutstanding_ -= statements.size();
457 if (errorsCount > 0) {
459 errorsCount <= statements.size(),
"Errors number cannot exceed statements number"
461 counters_->registerReadError(errorsCount);
462 counters_->registerReadFinished(startTime, statements.size() - errorsCount);
465 counters_->registerReadFinished(startTime, statements.size());
467 std::vector<ResultType> results;
468 results.reserve(futures.size());
473 std::make_move_iterator(std::begin(futures)),
474 std::make_move_iterator(std::end(futures)),
475 std::back_inserter(results),
479 auto entry = future.get();
480 auto&& res = entry.value();
481 return std::move(res);
486 futures.size() == statements.size(),
487 "Futures size must be equal to statements size. Got {} and {}",
492 results.size() == statements.size(),
493 "Results size must be equal to statements size. Got {} and {}",
503 [[nodiscard]] boost::json::object
506 return counters_->report();
511 incrementOutstandingRequestCount()
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(); });
521 ++numWriteRequestsOutstanding_;
525 decrementOutstandingRequestCount()
528 ASSERT(numWriteRequestsOutstanding_ > 0,
"Decrementing num outstanding below 0");
529 size_t const cur = (--numWriteRequestsOutstanding_);
533 std::scoped_lock
const lck(throttleMutex_);
534 throttleCv_.notify_one();
539 std::scoped_lock
const lck(syncMutex_);
540 syncCv_.notify_one();
545 canAddWriteRequest()
const
547 return numWriteRequestsOutstanding_ < maxWriteRequestsOutstanding_;
551 finishedAllWriteRequests()
const
553 return numWriteRequestsOutstanding_ == 0;
557 throwErrorIfNeeded(CassandraError err)
const
561 if (err.isInvalidQuery())
562 throw std::runtime_error(
"Invalid query");
565 throw DatabaseError{fmt::format(
"Database error [{}]: {}", err.code(), err.message())};
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