22#include "data/BackendInterface.hpp"
24#include "data/LedgerCacheInterface.hpp"
25#include "data/Types.hpp"
26#include "data/cassandra/Concepts.hpp"
27#include "data/cassandra/Handle.hpp"
28#include "data/cassandra/Schema.hpp"
29#include "data/cassandra/SettingsProvider.hpp"
30#include "data/cassandra/Types.hpp"
31#include "data/cassandra/impl/ExecutionStrategy.hpp"
32#include "util/Assert.hpp"
33#include "util/LedgerUtils.hpp"
34#include "util/Profiler.hpp"
35#include "util/log/Logger.hpp"
37#include <boost/asio/spawn.hpp>
38#include <boost/json/object.hpp>
39#include <boost/uuid/string_generator.hpp>
40#include <boost/uuid/uuid.hpp>
43#include <xrpl/basics/Blob.h>
44#include <xrpl/basics/base_uint.h>
45#include <xrpl/basics/strHex.h>
46#include <xrpl/protocol/AccountID.h>
47#include <xrpl/protocol/Indexes.h>
48#include <xrpl/protocol/LedgerHeader.h>
49#include <xrpl/protocol/nft.h>
75template <SomeSettingsProv
ider SettingsProv
iderType, SomeExecutionStrategy ExecutionStrategyType>
79 SettingsProviderType settingsProvider_;
82 std::atomic_uint32_t ledgerSequence_ = 0u;
88 mutable ExecutionStrategyType executor_;
100 , settingsProvider_{std::move(settingsProvider)}
101 , schema_{settingsProvider_}
102 , handle_{settingsProvider_.getSettings()}
103 , executor_{settingsProvider_.getSettings(), handle_}
105 if (
auto const res = handle_.
connect(); not res)
106 throw std::runtime_error(
"Could not connect to database: " + res.error());
109 if (
auto const res = handle_.
execute(schema_.createKeyspace); not res) {
112 if (res.error().code() != CASS_ERROR_SERVER_UNAUTHORIZED)
113 throw std::runtime_error(
"Could not create keyspace: " + res.error());
116 if (
auto const res = handle_.
executeEach(schema_.createSchema); not res)
117 throw std::runtime_error(
"Could not create schema: " + res.error());
122 }
catch (std::runtime_error
const& ex) {
123 auto const error = fmt::format(
124 "Failed to prepare the statements: {}; readOnly: {}. ReadOnly should be turned off or another Clio "
125 "node with write access to DB should be started first.",
129 LOG(log_.
error()) << error;
130 throw std::runtime_error(error);
133 LOG(log_.
info()) <<
"Created (revamped) CassandraBackend";
143 ripple::AccountID
const& account,
144 std::uint32_t
const limit,
146 std::optional<TransactionsCursor>
const& cursorIn,
147 boost::asio::yield_context yield
152 return {.txns = {}, .cursor = {}};
154 Statement const statement = [
this, forward, &account]() {
156 return schema_->selectAccountTxForward.bind(account);
158 return schema_->selectAccountTx.bind(account);
161 auto cursor = cursorIn;
163 statement.
bindAt(1, cursor->asTuple());
164 LOG(log_.
debug()) <<
"account = " << ripple::strHex(account) <<
" tuple = " << cursor->ledgerSequence
165 << cursor->transactionIndex;
167 auto const seq = forward ? rng->minSequence : rng->maxSequence;
168 auto const placeHolder = forward ? 0u : std::numeric_limits<std::uint32_t>::max();
170 statement.
bindAt(1, std::make_tuple(placeHolder, placeHolder));
171 LOG(log_.
debug()) <<
"account = " << ripple::strHex(account) <<
" idx = " << seq
172 <<
" tuple = " << placeHolder;
179 auto const res = executor_.read(yield, statement);
180 auto const& results = res.value();
181 if (not results.hasRows()) {
182 LOG(log_.
debug()) <<
"No rows returned";
186 std::vector<ripple::uint256> hashes = {};
187 auto numRows = results.numRows();
188 LOG(log_.
info()) <<
"num_rows = " << numRows;
190 for (
auto [hash,
data] :
extract<ripple::uint256, std::tuple<uint32_t, uint32_t>>(results)) {
191 hashes.push_back(hash);
192 if (--numRows == 0) {
193 LOG(log_.
debug()) <<
"Setting cursor";
199 LOG(log_.
debug()) <<
"Txns = " << txns.size();
201 if (txns.size() == limit) {
202 LOG(log_.
debug()) <<
"Returning cursor";
203 return {txns, cursor};
221 executor_.writeSync(schema_->updateLedgerRange, ledgerSequence_,
false, ledgerSequence_);
224 if (not executeSyncUpdate(schema_->updateLedgerRange.bind(ledgerSequence_,
true, ledgerSequence_ - 1))) {
225 LOG(log_.
warn()) <<
"Update failed for ledger " << ledgerSequence_;
229 LOG(log_.
info()) <<
"Committed ledger " << ledgerSequence_;
234 writeLedger(ripple::LedgerHeader
const& ledgerHeader, std::string&& blob)
override
236 executor_.write(schema_->insertLedgerHeader, ledgerHeader.seq, std::move(blob));
238 executor_.write(schema_->insertLedgerHash, ledgerHeader.hash, ledgerHeader.seq);
240 ledgerSequence_ = ledgerHeader.seq;
243 std::optional<std::uint32_t>
246 if (
auto const res = executor_.read(yield, schema_->selectLatestLedger); res) {
247 if (
auto const& result = res.value(); result) {
248 if (
auto const maybeValue = result.template get<uint32_t>(); maybeValue)
251 LOG(log_.
error()) <<
"Could not fetch latest ledger - no rows";
255 LOG(log_.
error()) <<
"Could not fetch latest ledger - no result";
257 LOG(log_.
error()) <<
"Could not fetch latest ledger: " << res.error();
263 std::optional<ripple::LedgerHeader>
266 auto const res = executor_.read(yield, schema_->selectLedgerBySeq, sequence);
268 if (
auto const& result = res.value(); result) {
269 if (
auto const maybeValue = result.template get<std::vector<unsigned char>>(); maybeValue) {
273 LOG(log_.
error()) <<
"Could not fetch ledger by sequence - no rows";
277 LOG(log_.
error()) <<
"Could not fetch ledger by sequence - no result";
279 LOG(log_.
error()) <<
"Could not fetch ledger by sequence: " << res.error();
285 std::optional<ripple::LedgerHeader>
288 if (
auto const res = executor_.read(yield, schema_->selectLedgerByHash, hash); res) {
289 if (
auto const& result = res.value(); result) {
290 if (
auto const maybeValue = result.template get<uint32_t>(); maybeValue)
293 LOG(log_.
error()) <<
"Could not fetch ledger by hash - no rows";
297 LOG(log_.
error()) <<
"Could not fetch ledger by hash - no result";
299 LOG(log_.
error()) <<
"Could not fetch ledger by hash: " << res.error();
305 std::optional<LedgerRange>
308 auto const res = executor_.read(yield, schema_->selectLedgerRange);
310 auto const& results = res.value();
311 if (not results.hasRows()) {
312 LOG(log_.
debug()) <<
"Could not fetch ledger range - no rows";
323 range.maxSequence = range.minSequence = seq;
324 }
else if (idx == 1) {
325 range.maxSequence = seq;
331 if (range.minSequence > range.maxSequence)
332 std::swap(range.minSequence, range.maxSequence);
334 LOG(log_.
debug()) <<
"After hardFetchLedgerRange range is " << range.minSequence <<
":"
335 << range.maxSequence;
338 LOG(log_.
error()) <<
"Could not fetch ledger range: " << res.error();
343 std::vector<TransactionAndMetadata>
350 std::vector<ripple::uint256>
354 auto start = std::chrono::system_clock::now();
355 auto const res = executor_.read(yield, schema_->selectAllTransactionHashesInLedger, ledgerSequence);
358 LOG(log_.
error()) <<
"Could not fetch all transaction hashes: " << res.error();
362 auto const& result = res.value();
363 if (not result.hasRows()) {
364 LOG(log_.
warn()) <<
"Could not fetch all transaction hashes - no rows; ledger = "
365 << std::to_string(ledgerSequence);
369 std::vector<ripple::uint256> hashes;
371 hashes.push_back(std::move(hash));
373 auto end = std::chrono::system_clock::now();
374 LOG(log_.
debug()) <<
"Fetched " << hashes.size() <<
" transaction hashes from database in "
375 << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
382 fetchNFT(ripple::uint256
const& tokenID, std::uint32_t
const ledgerSequence, boost::asio::yield_context yield)
385 auto const res = executor_.read(yield, schema_->selectNFT, tokenID, ledgerSequence);
389 if (
auto const maybeRow = res->template get<uint32_t, ripple::AccountID, bool>(); maybeRow) {
390 auto [seq, owner, isBurned] = *maybeRow;
391 auto result = std::make_optional<NFT>(tokenID, seq, owner, isBurned);
404 auto uriRes = executor_.read(yield, schema_->selectNFTURI, tokenID, ledgerSequence);
406 if (
auto const maybeUri = uriRes->template get<ripple::Blob>(); maybeUri)
407 result->uri = *maybeUri;
413 LOG(log_.
error()) <<
"Could not fetch NFT - no rows";
419 ripple::uint256
const& tokenID,
420 std::uint32_t
const limit,
422 std::optional<TransactionsCursor>
const& cursorIn,
423 boost::asio::yield_context yield
428 return {.txns = {}, .cursor = {}};
430 Statement const statement = [
this, forward, &tokenID]() {
432 return schema_->selectNFTTxForward.bind(tokenID);
434 return schema_->selectNFTTx.bind(tokenID);
437 auto cursor = cursorIn;
439 statement.
bindAt(1, cursor->asTuple());
440 LOG(log_.
debug()) <<
"token_id = " << ripple::strHex(tokenID) <<
" tuple = " << cursor->ledgerSequence
441 << cursor->transactionIndex;
443 auto const seq = forward ? rng->minSequence : rng->maxSequence;
444 auto const placeHolder = forward ? 0 : std::numeric_limits<std::uint32_t>::max();
446 statement.
bindAt(1, std::make_tuple(placeHolder, placeHolder));
447 LOG(log_.
debug()) <<
"token_id = " << ripple::strHex(tokenID) <<
" idx = " << seq
448 <<
" tuple = " << placeHolder;
453 auto const res = executor_.read(yield, statement);
454 auto const& results = res.value();
455 if (not results.hasRows()) {
456 LOG(log_.
debug()) <<
"No rows returned";
460 std::vector<ripple::uint256> hashes = {};
461 auto numRows = results.numRows();
462 LOG(log_.
info()) <<
"num_rows = " << numRows;
464 for (
auto [hash,
data] :
extract<ripple::uint256, std::tuple<uint32_t, uint32_t>>(results)) {
465 hashes.push_back(hash);
466 if (--numRows == 0) {
467 LOG(log_.
debug()) <<
"Setting cursor";
473 ++cursor->transactionIndex;
478 LOG(log_.
debug()) <<
"NFT Txns = " << txns.size();
480 if (txns.size() == limit) {
481 LOG(log_.
debug()) <<
"Returning cursor";
482 return {txns, cursor};
490 ripple::AccountID
const& issuer,
491 std::optional<std::uint32_t>
const& taxon,
492 std::uint32_t
const ledgerSequence,
493 std::uint32_t
const limit,
494 std::optional<ripple::uint256>
const& cursorIn,
495 boost::asio::yield_context yield
500 Statement const idQueryStatement = [&taxon, &issuer, &cursorIn, &limit,
this]() {
501 if (taxon.has_value()) {
502 auto r = schema_->selectNFTIDsByIssuerTaxon.bind(issuer);
504 r.bindAt(2, cursorIn.value_or(ripple::uint256(0)));
505 r.bindAt(3,
Limit{limit});
509 auto r = schema_->selectNFTIDsByIssuer.bind(issuer);
513 cursorIn.has_value() ? ripple::nft::toUInt32(ripple::nft::getTaxon(*cursorIn)) : 0,
514 cursorIn.value_or(ripple::uint256(0))
517 r.bindAt(2,
Limit{limit});
522 auto const res = executor_.read(yield, idQueryStatement);
524 auto const& idQueryResults = res.value();
525 if (not idQueryResults.hasRows()) {
526 LOG(log_.
debug()) <<
"No rows returned";
530 std::vector<ripple::uint256> nftIDs;
532 nftIDs.push_back(nftID);
537 if (nftIDs.size() == limit)
538 ret.cursor = nftIDs.back();
540 std::vector<Statement> selectNFTStatements;
541 selectNFTStatements.reserve(nftIDs.size());
546 std::back_inserter(selectNFTStatements),
547 [&](
auto const& nftID) {
return schema_->selectNFT.bind(nftID, ledgerSequence); }
550 auto const nftInfos = executor_.readEach(yield, selectNFTStatements);
552 std::vector<Statement> selectNFTURIStatements;
553 selectNFTURIStatements.reserve(nftIDs.size());
558 std::back_inserter(selectNFTURIStatements),
559 [&](
auto const& nftID) {
return schema_->selectNFTURI.bind(nftID, ledgerSequence); }
562 auto const nftUris = executor_.readEach(yield, selectNFTURIStatements);
564 for (
auto i = 0u; i < nftIDs.size(); i++) {
565 if (
auto const maybeRow = nftInfos[i].
template get<uint32_t, ripple::AccountID, bool>(); maybeRow) {
566 auto [seq, owner, isBurned] = *maybeRow;
567 NFT nft(nftIDs[i], seq, owner, isBurned);
568 if (
auto const maybeUri = nftUris[i].
template get<ripple::Blob>(); maybeUri)
570 ret.nfts.push_back(nft);
578 ripple::uint192
const& mptID,
579 std::uint32_t
const limit,
580 std::optional<ripple::AccountID>
const& cursorIn,
581 std::uint32_t
const ledgerSequence,
582 boost::asio::yield_context yield
585 auto const holderEntries = executor_.read(
586 yield, schema_->selectMPTHolders, mptID, cursorIn.value_or(ripple::AccountID(0)),
Limit{limit}
589 auto const& holderResults = holderEntries.value();
590 if (not holderResults.hasRows()) {
591 LOG(log_.
debug()) <<
"No rows returned";
595 std::vector<ripple::uint256> mptKeys;
596 std::optional<ripple::AccountID> cursor;
598 mptKeys.push_back(ripple::keylet::mptoken(mptID, holder).key);
604 auto it = std::remove_if(mptObjects.begin(), mptObjects.end(), [](Blob
const& mpt) { return mpt.empty(); });
606 mptObjects.erase(it, mptObjects.end());
608 ASSERT(mptKeys.size() <= limit,
"Number of keys can't exceed the limit");
609 if (mptKeys.size() == limit)
610 return {mptObjects, cursor};
612 return {mptObjects, {}};
616 doFetchLedgerObject(ripple::uint256
const& key, std::uint32_t
const sequence, boost::asio::yield_context yield)
619 LOG(log_.
debug()) <<
"Fetching ledger object for seq " << sequence <<
", key = " << ripple::to_string(key);
620 if (
auto const res = executor_.read(yield, schema_->selectObject, key, sequence); res) {
621 if (
auto const result = res->template get<Blob>(); result) {
625 LOG(log_.
debug()) <<
"Could not fetch ledger object - no rows";
628 LOG(log_.
error()) <<
"Could not fetch ledger object: " << res.error();
634 std::optional<std::uint32_t>
638 LOG(log_.
debug()) <<
"Fetching ledger object for seq " << sequence <<
", key = " << ripple::to_string(key);
639 if (
auto const res = executor_.read(yield, schema_->selectObject, key, sequence); res) {
640 if (
auto const result = res->template get<Blob, std::uint32_t>(); result) {
641 auto [_, seq] = result.value();
644 LOG(log_.
debug()) <<
"Could not fetch ledger object sequence - no rows";
646 LOG(log_.
error()) <<
"Could not fetch ledger object sequence: " << res.error();
652 std::optional<TransactionAndMetadata>
653 fetchTransaction(ripple::uint256
const& hash, boost::asio::yield_context yield)
const override
655 if (
auto const res = executor_.read(yield, schema_->selectTransaction, hash); res) {
656 if (
auto const maybeValue = res->template get<Blob, Blob, uint32_t, uint32_t>(); maybeValue) {
657 auto [transaction, meta, seq, date] = *maybeValue;
658 return std::make_optional<TransactionAndMetadata>(transaction, meta, seq, date);
661 LOG(log_.
debug()) <<
"Could not fetch transaction - no rows";
663 LOG(log_.
error()) <<
"Could not fetch transaction: " << res.error();
669 std::optional<ripple::uint256>
670 doFetchSuccessorKey(ripple::uint256 key, std::uint32_t
const ledgerSequence, boost::asio::yield_context yield)
673 if (
auto const res = executor_.read(yield, schema_->selectSuccessor, key, ledgerSequence); res) {
674 if (
auto const result = res->template get<ripple::uint256>(); result) {
675 if (*result == kLAST_KEY)
680 LOG(log_.
debug()) <<
"Could not fetch successor - no rows";
682 LOG(log_.
error()) <<
"Could not fetch successor: " << res.error();
688 std::vector<TransactionAndMetadata>
689 fetchTransactions(std::vector<ripple::uint256>
const& hashes, boost::asio::yield_context yield)
const override
694 auto const numHashes = hashes.size();
695 std::vector<TransactionAndMetadata> results;
696 results.reserve(numHashes);
698 std::vector<Statement> statements;
699 statements.reserve(numHashes);
701 auto const timeDiff =
util::timed([
this, yield, &results, &hashes, &statements]() {
706 std::back_inserter(statements),
707 [
this](
auto const& hash) {
return schema_->selectTransaction.bind(hash); }
710 auto const entries = executor_.readEach(yield, statements);
712 std::cbegin(entries),
714 std::back_inserter(results),
716 if (
auto const maybeRow = res.template get<Blob, Blob, uint32_t, uint32_t>(); maybeRow)
724 ASSERT(numHashes == results.size(),
"Number of hashes and results must match");
725 LOG(log_.
debug()) <<
"Fetched " << numHashes <<
" transactions from database in " << timeDiff
732 std::vector<ripple::uint256>
const& keys,
733 std::uint32_t
const sequence,
734 boost::asio::yield_context yield
740 auto const numKeys = keys.size();
741 LOG(log_.
trace()) <<
"Fetching " << numKeys <<
" objects";
743 std::vector<Blob> results;
744 results.reserve(numKeys);
746 std::vector<Statement> statements;
747 statements.reserve(numKeys);
753 std::back_inserter(statements),
754 [
this, &sequence](
auto const& key) {
return schema_->selectObject.bind(key, sequence); }
757 auto const entries = executor_.readEach(yield, statements);
759 std::cbegin(entries),
761 std::back_inserter(results),
762 [](
auto const& res) -> Blob {
763 if (
auto const maybeValue = res.template get<Blob>(); maybeValue)
770 LOG(log_.
trace()) <<
"Fetched " << numKeys <<
" objects";
774 std::vector<ripple::uint256>
775 fetchAccountRoots(std::uint32_t number, std::uint32_t pageSize, std::uint32_t seq, boost::asio::yield_context yield)
778 std::vector<ripple::uint256> liveAccounts;
779 std::optional<ripple::AccountID> lastItem;
781 while (liveAccounts.size() < number) {
782 Statement const statement = lastItem ? schema_->selectAccountFromToken.bind(*lastItem,
Limit{pageSize})
783 : schema_->selectAccountFromBegining.bind(
Limit{pageSize});
785 auto const res = executor_.read(yield, statement);
787 auto const& results = res.value();
788 if (not results.hasRows()) {
789 LOG(log_.
debug()) <<
"No rows returned";
793 std::vector<ripple::uint256> fullAccounts;
795 fullAccounts.push_back(ripple::keylet::account(account).key);
800 for (
auto i = 0u; i < fullAccounts.size(); i++) {
801 if (not objs[i].empty()) {
802 if (liveAccounts.size() < number) {
803 liveAccounts.push_back(fullAccounts[i]);
810 LOG(log_.
error()) <<
"Could not fetch account from account_tx: " << res.error();
818 std::vector<LedgerObject>
819 fetchLedgerDiff(std::uint32_t
const ledgerSequence, boost::asio::yield_context yield)
const override
821 auto const [keys, timeDiff] =
util::timed([
this, &ledgerSequence, yield]() -> std::vector<ripple::uint256> {
822 auto const res = executor_.read(yield, schema_->selectDiff, ledgerSequence);
824 LOG(log_.
error()) <<
"Could not fetch ledger diff: " << res.error() <<
"; ledger = " << ledgerSequence;
828 auto const& results = res.value();
830 LOG(log_.
error()) <<
"Could not fetch ledger diff - no rows; ledger = " << ledgerSequence;
834 std::vector<ripple::uint256> resultKeys;
836 resultKeys.push_back(key);
845 LOG(log_.
debug()) <<
"Fetched " << keys.size() <<
" diff hashes from database in " << timeDiff
849 std::vector<LedgerObject> results;
850 results.reserve(keys.size());
856 std::back_inserter(results),
857 [](
auto const& key,
auto const& obj) {
return LedgerObject{key, obj}; }
863 std::optional<std::string>
866 auto const res = executor_.read(yield, schema_->selectMigratorStatus,
Text(migratorName));
868 LOG(log_.
error()) <<
"Could not fetch migrator status: " << res.error();
872 auto const& results = res.value();
883 std::expected<std::vector<std::pair<boost::uuids::uuid, std::string>>, std::string>
886 auto const readResult = executor_.read(yield, schema_->selectClioNodesData);
888 return std::unexpected{readResult.error().message()};
890 std::vector<std::pair<boost::uuids::uuid, std::string>> result;
893 result.emplace_back(uuid, std::move(message));
902 LOG(log_.
trace()) <<
" Writing ledger object " << key.size() <<
":" << seq <<
" [" << blob.size() <<
" bytes]";
905 executor_.write(schema_->insertDiff, seq, key);
907 executor_.write(schema_->insertObject, std::move(key), seq, std::move(blob));
911 writeSuccessor(std::string&& key, std::uint32_t
const seq, std::string&& successor)
override
913 LOG(log_.
trace()) <<
"Writing successor. key = " << key.size() <<
" bytes. "
914 <<
" seq = " << std::to_string(seq) <<
" successor = " << successor.size() <<
" bytes.";
915 ASSERT(!key.empty(),
"Key must not be empty");
916 ASSERT(!successor.empty(),
"Successor must not be empty");
918 executor_.write(schema_->insertSuccessor, std::move(key), seq, std::move(successor));
924 std::vector<Statement> statements;
925 statements.reserve(
data.size() * 10);
927 for (
auto& record :
data) {
928 std::ranges::transform(record.accounts, std::back_inserter(statements), [
this, &record](
auto&& account) {
929 return schema_->insertAccountTx.bind(
930 std::forward<decltype(account)>(account),
931 std::make_tuple(record.ledgerSequence, record.transactionIndex),
937 executor_.write(std::move(statements));
943 std::vector<Statement> statements;
944 statements.reserve(record.accounts.size());
946 std::ranges::transform(record.accounts, std::back_inserter(statements), [
this, &record](
auto&& account) {
947 return schema_->insertAccountTx.bind(
948 std::forward<decltype(account)>(account),
949 std::make_tuple(record.ledgerSequence, record.transactionIndex),
954 executor_.write(std::move(statements));
960 std::vector<Statement> statements;
961 statements.reserve(
data.size());
963 std::ranges::transform(
data, std::back_inserter(statements), [
this](
auto const& record) {
964 return schema_->insertNFTTx.bind(
965 record.tokenID, std::make_tuple(record.ledgerSequence, record.transactionIndex), record.txHash
969 executor_.write(std::move(statements));
975 std::uint32_t
const seq,
976 std::uint32_t
const date,
977 std::string&& transaction,
978 std::string&& metadata
981 LOG(log_.
trace()) <<
"Writing txn to database";
983 executor_.write(schema_->insertLedgerTransaction, seq, hash);
985 schema_->insertTransaction, std::move(hash), seq, date, std::move(transaction), std::move(metadata)
992 std::vector<Statement> statements;
993 statements.reserve(
data.size() * 3);
996 if (!record.onlyUriChanged) {
997 statements.push_back(
998 schema_->insertNFT.bind(record.tokenID, record.ledgerSequence, record.owner, record.isBurned)
1007 statements.push_back(schema_->insertIssuerNFT.bind(
1008 ripple::nft::getIssuer(record.tokenID),
1009 static_cast<uint32_t
>(ripple::nft::getTaxon(record.tokenID)),
1012 statements.push_back(
1013 schema_->insertNFTURI.bind(record.tokenID, record.ledgerSequence, record.uri.value())
1018 statements.push_back(
1019 schema_->insertNFTURI.bind(record.tokenID, record.ledgerSequence, record.uri.value())
1024 executor_.writeEach(std::move(statements));
1030 std::vector<Statement> statements;
1031 statements.reserve(
data.size());
1032 for (
auto [mptId, holder] :
data)
1033 statements.push_back(schema_->insertMPTHolder.bind(mptId, holder));
1035 executor_.write(std::move(statements));
1048 executor_.writeSync(
1056 executor_.writeSync(schema_->updateClioNodeMessage,
data::cassandra::Text{std::move(message)}, uuid);
1062 return executor_.isTooBusy();
1068 return executor_.stats();
1075 auto const res = executor_.writeSync(statement);
1076 auto maybeSuccess = res->template get<bool>();
1077 if (not maybeSuccess) {
1078 LOG(log_.
error()) <<
"executeSyncUpdate - error getting result - no row";
1082 if (not maybeSuccess.value()) {
1083 LOG(log_.
warn()) <<
"Update failed. Checking if DB state is what we expect";
1090 return rng && rng->maxSequence == ledgerSequence_;
1097using CassandraBackend = BasicCassandraBackend<SettingsProvider, impl::DefaultExecutionStrategy<>>;
The interface to the database used by Clio.
Definition BackendInterface.hpp:140
std::vector< Blob > fetchLedgerObjects(std::vector< ripple::uint256 > const &keys, std::uint32_t sequence, boost::asio::yield_context yield) const
Fetches all ledger objects by their keys.
Definition BackendInterface.cpp:119
std::optional< LedgerRange > hardFetchLedgerRangeNoThrow() const
Fetches the ledger range from DB retrying until no DatabaseTimeout is thrown.
Definition BackendInterface.cpp:77
std::optional< LedgerRange > fetchLedgerRange() const
Fetch the current ledger range.
Definition BackendInterface.cpp:267
LedgerCacheInterface const & cache() const
Definition BackendInterface.hpp:165
Cache for an entire ledger.
Definition LedgerCacheInterface.hpp:38
Implements BackendInterface for Cassandra/ScyllaDB.
Definition CassandraBackend.hpp:76
std::vector< TransactionAndMetadata > fetchTransactions(std::vector< ripple::uint256 > const &hashes, boost::asio::yield_context yield) const override
Fetches multiple transactions.
Definition CassandraBackend.hpp:689
MPTHoldersAndCursor fetchMPTHolders(ripple::uint192 const &mptID, std::uint32_t const limit, std::optional< ripple::AccountID > const &cursorIn, std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Fetches all holders' balances for a MPTIssuanceID.
Definition CassandraBackend.hpp:577
void writeTransaction(std::string &&hash, std::uint32_t const seq, std::uint32_t const date, std::string &&transaction, std::string &&metadata) override
Writes a new transaction.
Definition CassandraBackend.hpp:973
void writeNFTTransactions(std::vector< NFTTransactionsData > const &data) override
Write NFTs transactions.
Definition CassandraBackend.hpp:958
void writeAccountTransaction(AccountTransactionsData record) override
Write a new account transaction.
Definition CassandraBackend.hpp:941
std::vector< ripple::uint256 > fetchAllTransactionHashesInLedger(std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Fetches all transaction hashes from a specific ledger.
Definition CassandraBackend.hpp:351
std::optional< ripple::uint256 > doFetchSuccessorKey(ripple::uint256 key, std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Database-specific implementation of fetching the successor key.
Definition CassandraBackend.hpp:670
std::optional< std::uint32_t > doFetchLedgerObjectSeq(ripple::uint256 const &key, std::uint32_t const sequence, boost::asio::yield_context yield) const override
The database-specific implementation for fetching a ledger object sequence.
Definition CassandraBackend.hpp:635
bool isTooBusy() const override
Definition CassandraBackend.hpp:1060
boost::json::object stats() const override
Definition CassandraBackend.hpp:1066
void writeNodeMessage(boost::uuids::uuid const &uuid, std::string message) override
Write a node message. Used by ClusterCommunicationService.
Definition CassandraBackend.hpp:1054
std::optional< std::string > fetchMigratorStatus(std::string const &migratorName, boost::asio::yield_context yield) const override
Fetches the status of migrator by name.
Definition CassandraBackend.hpp:864
std::optional< NFT > fetchNFT(ripple::uint256 const &tokenID, std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Fetches a specific NFT.
Definition CassandraBackend.hpp:382
void startWrites() const override
Starts a write transaction with the DB. No-op for cassandra.
Definition CassandraBackend.hpp:1039
void writeLedger(ripple::LedgerHeader const &ledgerHeader, std::string &&blob) override
Writes to a specific ledger.
Definition CassandraBackend.hpp:234
void waitForWritesToFinish() override
Wait for all pending writes to finish.
Definition CassandraBackend.hpp:210
void writeMPTHolders(std::vector< MPTHolderData > const &data) override
Write accounts that started holding onto a MPT.
Definition CassandraBackend.hpp:1028
void writeNFTs(std::vector< NFTsData > const &data) override
Writes NFTs to the database.
Definition CassandraBackend.hpp:990
void writeAccountTransactions(std::vector< AccountTransactionsData > data) override
Write a new set of account transactions.
Definition CassandraBackend.hpp:922
std::optional< std::uint32_t > fetchLatestLedgerSequence(boost::asio::yield_context yield) const override
Fetches the latest ledger sequence.
Definition CassandraBackend.hpp:244
TransactionsAndCursor fetchAccountTransactions(ripple::AccountID const &account, std::uint32_t const limit, bool forward, std::optional< TransactionsCursor > const &cursorIn, boost::asio::yield_context yield) const override
Fetches all transactions for a specific account.
Definition CassandraBackend.hpp:142
void doWriteLedgerObject(std::string &&key, std::uint32_t const seq, std::string &&blob) override
Writes a ledger object to the database.
Definition CassandraBackend.hpp:900
NFTsAndCursor fetchNFTsByIssuer(ripple::AccountID const &issuer, std::optional< std::uint32_t > const &taxon, std::uint32_t const ledgerSequence, std::uint32_t const limit, std::optional< ripple::uint256 > const &cursorIn, boost::asio::yield_context yield) const override
Fetches all NFTs issued by a given address.
Definition CassandraBackend.hpp:489
BasicCassandraBackend(SettingsProviderType settingsProvider, data::LedgerCacheInterface &cache, bool readOnly)
Create a new cassandra/scylla backend instance.
Definition CassandraBackend.hpp:98
void writeSuccessor(std::string &&key, std::uint32_t const seq, std::string &&successor) override
Write a new successor.
Definition CassandraBackend.hpp:911
std::optional< TransactionAndMetadata > fetchTransaction(ripple::uint256 const &hash, boost::asio::yield_context yield) const override
Fetches a specific transaction.
Definition CassandraBackend.hpp:653
std::vector< TransactionAndMetadata > fetchAllTransactionsInLedger(std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Fetches all transactions from a specific ledger.
Definition CassandraBackend.hpp:344
std::optional< Blob > doFetchLedgerObject(ripple::uint256 const &key, std::uint32_t const sequence, boost::asio::yield_context yield) const override
The database-specific implementation for fetching a ledger object.
Definition CassandraBackend.hpp:616
bool doFinishWrites() override
The implementation should wait for all pending writes to finish.
Definition CassandraBackend.hpp:216
std::vector< ripple::uint256 > fetchAccountRoots(std::uint32_t number, std::uint32_t pageSize, std::uint32_t seq, boost::asio::yield_context yield) const override
Fetch the specified number of account root object indexes by page, the accounts need to exist for seq...
Definition CassandraBackend.hpp:775
std::vector< LedgerObject > fetchLedgerDiff(std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Returns the difference between ledgers.
Definition CassandraBackend.hpp:819
void writeMigratorStatus(std::string const &migratorName, std::string const &status) override
Mark the migration status of a migrator as Migrated in the database.
Definition CassandraBackend.hpp:1046
TransactionsAndCursor fetchNFTTransactions(ripple::uint256 const &tokenID, std::uint32_t const limit, bool const forward, std::optional< TransactionsCursor > const &cursorIn, boost::asio::yield_context yield) const override
Fetches all transactions for a specific NFT.
Definition CassandraBackend.hpp:418
std::expected< std::vector< std::pair< boost::uuids::uuid, std::string > >, std::string > fetchClioNodesData(boost::asio::yield_context yield) const override
Fetches the data of all nodes in the cluster.
Definition CassandraBackend.hpp:884
std::optional< ripple::LedgerHeader > fetchLedgerBySequence(std::uint32_t const sequence, boost::asio::yield_context yield) const override
Fetches a specific ledger by sequence number.
Definition CassandraBackend.hpp:264
std::vector< Blob > doFetchLedgerObjects(std::vector< ripple::uint256 > const &keys, std::uint32_t const sequence, boost::asio::yield_context yield) const override
The database-specific implementation for fetching ledger objects.
Definition CassandraBackend.hpp:731
std::optional< LedgerRange > hardFetchLedgerRange(boost::asio::yield_context yield) const override
Fetches the ledger range from DB.
Definition CassandraBackend.hpp:306
std::optional< ripple::LedgerHeader > fetchLedgerByHash(ripple::uint256 const &hash, boost::asio::yield_context yield) const override
Fetches a specific ledger by hash.
Definition CassandraBackend.hpp:286
Represents a handle to the cassandra database cluster.
Definition Handle.hpp:46
MaybeErrorType connect() const
Synchonous version of the above.
Definition Handle.cpp:55
MaybeErrorType executeEach(std::vector< StatementType > const &statements) const
Synchonous version of the above.
Definition Handle.cpp:109
ResultOrErrorType execute(std::string_view query, Args &&... args) const
Synchonous version of the above.
Definition Handle.hpp:185
Manages the DB schema and provides access to prepared statements.
Definition Schema.hpp:55
void prepareStatements(Handle const &handle)
Recreates the prepared statements.
Definition Schema.hpp:848
Definition Statement.hpp:47
void bindAt(std::size_t const idx, Type &&value) const
Binds an argument to a specific index.
Definition Statement.hpp:93
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:111
Pump warn(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::WRN severity.
Definition Logger.cpp:224
Pump error(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::ERR severity.
Definition Logger.cpp:229
Pump debug(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::DBG severity.
Definition Logger.cpp:214
Pump trace(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::TRC severity.
Definition Logger.cpp:209
Pump info(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:219
This namespace implements a wrapper for the Cassandra C++ driver.
Definition Concepts.hpp:37
impl::ResultExtractor< Types... > extract(Handle::ResultType const &result)
Extracts the results into series of std::tuple<Types...> by creating a simple wrapper with an STL inp...
Definition Handle.hpp:329
This namespace implements the data access layer and related components.
Definition AmendmentCenter.cpp:70
ripple::LedgerHeader deserializeHeader(ripple::Slice data)
Deserializes a ripple::LedgerHeader from ripple::Slice of data.
Definition LedgerUtils.hpp:203
auto timed(FnType &&func)
Profiler function to measure the time a function execution consumes.
Definition Profiler.hpp:40
Struct used to keep track of what to write to account_transactions/account_tx tables.
Definition DBHelpers.hpp:45
Represents an NFT state at a particular ledger.
Definition DBHelpers.hpp:103
Represents an object in the ledger.
Definition Types.hpp:41
Stores a range of sequences as a min and max pair.
Definition Types.hpp:247
Represents an array of MPTokens.
Definition Types.hpp:239
Represents a NFToken.
Definition Types.hpp:172
Represents a bundle of NFTs with a cursor to the next page.
Definition Types.hpp:231
Represests a bundle of transactions with metadata and a cursor to the next page.
Definition Types.hpp:164
A strong type wrapper for int32_t.
Definition Types.hpp:56
A strong type wrapper for string.
Definition Types.hpp:67