22#include "data/BackendInterface.hpp"
24#include "data/LedgerCacheInterface.hpp"
25#include "data/LedgerHeaderCache.hpp"
26#include "data/Types.hpp"
27#include "data/cassandra/Concepts.hpp"
28#include "data/cassandra/Handle.hpp"
29#include "data/cassandra/Schema.hpp"
30#include "data/cassandra/SettingsProvider.hpp"
31#include "data/cassandra/Types.hpp"
32#include "data/cassandra/impl/ExecutionStrategy.hpp"
33#include "util/Assert.hpp"
34#include "util/LedgerUtils.hpp"
35#include "util/Profiler.hpp"
36#include "util/log/Logger.hpp"
38#include <boost/asio/spawn.hpp>
39#include <boost/json/object.hpp>
40#include <boost/uuid/string_generator.hpp>
41#include <boost/uuid/uuid.hpp>
43#include <fmt/format.h>
44#include <xrpl/basics/Blob.h>
45#include <xrpl/basics/base_uint.h>
46#include <xrpl/basics/strHex.h>
47#include <xrpl/protocol/AccountID.h>
48#include <xrpl/protocol/Indexes.h>
49#include <xrpl/protocol/LedgerHeader.h>
50#include <xrpl/protocol/nft.h>
66class CacheBackendCassandraTest;
80 SomeSettingsProvider SettingsProviderType,
81 SomeExecutionStrategy ExecutionStrategyType,
82 typename FetchLedgerCacheType = FetchLedgerCache>
86 SettingsProviderType settingsProvider_;
88 std::atomic_uint32_t ledgerSequence_ = 0u;
89 friend class ::CacheBackendCassandraTest;
95 mutable ExecutionStrategyType executor_;
97 mutable FetchLedgerCacheType ledgerCache_{};
109 , settingsProvider_{std::move(settingsProvider)}
110 , schema_{settingsProvider_}
111 , handle_{settingsProvider_.getSettings()}
112 , executor_{settingsProvider_.getSettings(), handle_}
114 if (
auto const res = handle_.
connect(); not res)
115 throw std::runtime_error(
"Could not connect to database: " + res.error());
118 if (
auto const res = handle_.
execute(schema_.createKeyspace); not res) {
121 if (res.error().code() != CASS_ERROR_SERVER_UNAUTHORIZED)
122 throw std::runtime_error(
"Could not create keyspace: " + res.error());
125 if (
auto const res = handle_.
executeEach(schema_.createSchema); not res)
126 throw std::runtime_error(
"Could not create schema: " + res.error());
131 }
catch (std::runtime_error
const& ex) {
132 auto const error = fmt::format(
133 "Failed to prepare the statements: {}; readOnly: {}. ReadOnly should be turned off or another Clio "
134 "node with write access to DB should be started first.",
138 LOG(log_.
error()) << error;
139 throw std::runtime_error(error);
141 LOG(log_.
info()) <<
"Created (revamped) CassandraBackend";
151 ripple::AccountID
const& account,
152 std::uint32_t
const limit,
154 std::optional<TransactionsCursor>
const& cursorIn,
155 boost::asio::yield_context yield
160 return {.txns = {}, .cursor = {}};
162 Statement const statement = [
this, forward, &account]() {
164 return schema_->selectAccountTxForward.bind(account);
166 return schema_->selectAccountTx.bind(account);
169 auto cursor = cursorIn;
171 statement.
bindAt(1, cursor->asTuple());
172 LOG(log_.
debug()) <<
"account = " << ripple::strHex(account) <<
" tuple = " << cursor->ledgerSequence
173 << cursor->transactionIndex;
175 auto const seq = forward ? rng->minSequence : rng->maxSequence;
176 auto const placeHolder = forward ? 0u : std::numeric_limits<std::uint32_t>::max();
178 statement.
bindAt(1, std::make_tuple(placeHolder, placeHolder));
179 LOG(log_.
debug()) <<
"account = " << ripple::strHex(account) <<
" idx = " << seq
180 <<
" tuple = " << placeHolder;
187 auto const res = executor_.read(yield, statement);
188 auto const& results = res.value();
189 if (not results.hasRows()) {
190 LOG(log_.
debug()) <<
"No rows returned";
194 std::vector<ripple::uint256> hashes = {};
195 auto numRows = results.numRows();
196 LOG(log_.
info()) <<
"num_rows = " << numRows;
198 for (
auto [hash,
data] :
extract<ripple::uint256, std::tuple<uint32_t, uint32_t>>(results)) {
199 hashes.push_back(hash);
200 if (--numRows == 0) {
201 LOG(log_.
debug()) <<
"Setting cursor";
207 LOG(log_.
debug()) <<
"Txns = " << txns.size();
209 if (txns.size() == limit) {
210 LOG(log_.
debug()) <<
"Returning cursor";
211 return {txns, cursor};
229 executor_.writeSync(schema_->updateLedgerRange, ledgerSequence_,
false, ledgerSequence_);
232 if (not executeSyncUpdate(schema_->updateLedgerRange.bind(ledgerSequence_,
true, ledgerSequence_ - 1))) {
233 LOG(log_.
warn()) <<
"Update failed for ledger " << ledgerSequence_;
237 LOG(log_.
info()) <<
"Committed ledger " << ledgerSequence_;
242 writeLedger(ripple::LedgerHeader
const& ledgerHeader, std::string&& blob)
override
244 executor_.write(schema_->insertLedgerHeader, ledgerHeader.seq, std::move(blob));
246 executor_.write(schema_->insertLedgerHash, ledgerHeader.hash, ledgerHeader.seq);
248 ledgerSequence_ = ledgerHeader.seq;
251 std::optional<std::uint32_t>
254 if (
auto const res = executor_.read(yield, schema_->selectLatestLedger); res) {
255 if (
auto const& result = res.value(); result) {
256 if (
auto const maybeValue = result.template get<uint32_t>(); maybeValue)
259 LOG(log_.
error()) <<
"Could not fetch latest ledger - no rows";
263 LOG(log_.
error()) <<
"Could not fetch latest ledger - no result";
265 LOG(log_.
error()) <<
"Could not fetch latest ledger: " << res.error();
271 std::optional<ripple::LedgerHeader>
274 if (
auto const lock = ledgerCache_.get(); lock.has_value() && lock->seq == sequence)
277 auto const res = executor_.read(yield, schema_->selectLedgerBySeq, sequence);
279 if (
auto const& result = res.value(); result) {
280 if (
auto const maybeValue = result.template get<std::vector<unsigned char>>(); maybeValue) {
286 LOG(log_.
error()) <<
"Could not fetch ledger by sequence - no rows";
290 LOG(log_.
error()) <<
"Could not fetch ledger by sequence - no result";
292 LOG(log_.
error()) <<
"Could not fetch ledger by sequence: " << res.error();
298 std::optional<ripple::LedgerHeader>
301 if (
auto const res = executor_.read(yield, schema_->selectLedgerByHash, hash); res) {
302 if (
auto const& result = res.value(); result) {
303 if (
auto const maybeValue = result.template get<uint32_t>(); maybeValue)
306 LOG(log_.
error()) <<
"Could not fetch ledger by hash - no rows";
310 LOG(log_.
error()) <<
"Could not fetch ledger by hash - no result";
312 LOG(log_.
error()) <<
"Could not fetch ledger by hash: " << res.error();
318 std::optional<LedgerRange>
321 auto const res = executor_.read(yield, schema_->selectLedgerRange);
323 auto const& results = res.value();
324 if (not results.hasRows()) {
325 LOG(log_.
debug()) <<
"Could not fetch ledger range - no rows";
336 range.maxSequence = range.minSequence = seq;
337 }
else if (idx == 1) {
338 range.maxSequence = seq;
344 if (range.minSequence > range.maxSequence)
345 std::swap(range.minSequence, range.maxSequence);
347 LOG(log_.
debug()) <<
"After hardFetchLedgerRange range is " << range.minSequence <<
":"
348 << range.maxSequence;
351 LOG(log_.
error()) <<
"Could not fetch ledger range: " << res.error();
356 std::vector<TransactionAndMetadata>
363 std::vector<ripple::uint256>
365 std::uint32_t
const ledgerSequence,
366 boost::asio::yield_context yield
369 auto start = std::chrono::system_clock::now();
370 auto const res = executor_.read(yield, schema_->selectAllTransactionHashesInLedger, ledgerSequence);
373 LOG(log_.
error()) <<
"Could not fetch all transaction hashes: " << res.error();
377 auto const& result = res.value();
378 if (not result.hasRows()) {
379 LOG(log_.
warn()) <<
"Could not fetch all transaction hashes - no rows; ledger = "
380 << std::to_string(ledgerSequence);
384 std::vector<ripple::uint256> hashes;
386 hashes.push_back(std::move(hash));
388 auto end = std::chrono::system_clock::now();
389 LOG(log_.
debug()) <<
"Fetched " << hashes.size() <<
" transaction hashes from database in "
390 << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
398 ripple::uint256
const& tokenID,
399 std::uint32_t
const ledgerSequence,
400 boost::asio::yield_context yield
403 auto const res = executor_.read(yield, schema_->selectNFT, tokenID, ledgerSequence);
407 if (
auto const maybeRow = res->template get<uint32_t, ripple::AccountID, bool>(); maybeRow) {
408 auto [seq, owner, isBurned] = *maybeRow;
409 auto result = std::make_optional<NFT>(tokenID, seq, owner, isBurned);
422 auto uriRes = executor_.read(yield, schema_->selectNFTURI, tokenID, ledgerSequence);
424 if (
auto const maybeUri = uriRes->template get<ripple::Blob>(); maybeUri)
425 result->uri = *maybeUri;
431 LOG(log_.
error()) <<
"Could not fetch NFT - no rows";
437 ripple::uint256
const& tokenID,
438 std::uint32_t
const limit,
440 std::optional<TransactionsCursor>
const& cursorIn,
441 boost::asio::yield_context yield
446 return {.txns = {}, .cursor = {}};
448 Statement const statement = [
this, forward, &tokenID]() {
450 return schema_->selectNFTTxForward.bind(tokenID);
452 return schema_->selectNFTTx.bind(tokenID);
455 auto cursor = cursorIn;
457 statement.
bindAt(1, cursor->asTuple());
458 LOG(log_.
debug()) <<
"token_id = " << ripple::strHex(tokenID) <<
" tuple = " << cursor->ledgerSequence
459 << cursor->transactionIndex;
461 auto const seq = forward ? rng->minSequence : rng->maxSequence;
462 auto const placeHolder = forward ? 0 : std::numeric_limits<std::uint32_t>::max();
464 statement.
bindAt(1, std::make_tuple(placeHolder, placeHolder));
465 LOG(log_.
debug()) <<
"token_id = " << ripple::strHex(tokenID) <<
" idx = " << seq
466 <<
" tuple = " << placeHolder;
471 auto const res = executor_.read(yield, statement);
472 auto const& results = res.value();
473 if (not results.hasRows()) {
474 LOG(log_.
debug()) <<
"No rows returned";
478 std::vector<ripple::uint256> hashes = {};
479 auto numRows = results.numRows();
480 LOG(log_.
info()) <<
"num_rows = " << numRows;
482 for (
auto [hash,
data] :
extract<ripple::uint256, std::tuple<uint32_t, uint32_t>>(results)) {
483 hashes.push_back(hash);
484 if (--numRows == 0) {
485 LOG(log_.
debug()) <<
"Setting cursor";
491 ++cursor->transactionIndex;
496 LOG(log_.
debug()) <<
"NFT Txns = " << txns.size();
498 if (txns.size() == limit) {
499 LOG(log_.
debug()) <<
"Returning cursor";
500 return {txns, cursor};
508 ripple::AccountID
const& issuer,
509 std::optional<std::uint32_t>
const& taxon,
510 std::uint32_t
const ledgerSequence,
511 std::uint32_t
const limit,
512 std::optional<ripple::uint256>
const& cursorIn,
513 boost::asio::yield_context yield
518 Statement const idQueryStatement = [&taxon, &issuer, &cursorIn, &limit,
this]() {
519 if (taxon.has_value()) {
520 auto r = schema_->selectNFTIDsByIssuerTaxon.bind(issuer);
522 r.bindAt(2, cursorIn.value_or(ripple::uint256(0)));
523 r.bindAt(3,
Limit{limit});
527 auto r = schema_->selectNFTIDsByIssuer.bind(issuer);
531 cursorIn.has_value() ? ripple::nft::toUInt32(ripple::nft::getTaxon(*cursorIn)) : 0,
532 cursorIn.value_or(ripple::uint256(0))
535 r.bindAt(2,
Limit{limit});
540 auto const res = executor_.read(yield, idQueryStatement);
542 auto const& idQueryResults = res.value();
543 if (not idQueryResults.hasRows()) {
544 LOG(log_.
debug()) <<
"No rows returned";
548 std::vector<ripple::uint256> nftIDs;
550 nftIDs.push_back(nftID);
555 if (nftIDs.size() == limit)
556 ret.cursor = nftIDs.back();
558 std::vector<Statement> selectNFTStatements;
559 selectNFTStatements.reserve(nftIDs.size());
562 std::cbegin(nftIDs), std::cend(nftIDs), std::back_inserter(selectNFTStatements), [&](
auto const& nftID) {
563 return schema_->selectNFT.bind(nftID, ledgerSequence);
567 auto const nftInfos = executor_.readEach(yield, selectNFTStatements);
569 std::vector<Statement> selectNFTURIStatements;
570 selectNFTURIStatements.reserve(nftIDs.size());
573 std::cbegin(nftIDs), std::cend(nftIDs), std::back_inserter(selectNFTURIStatements), [&](
auto const& nftID) {
574 return schema_->selectNFTURI.bind(nftID, ledgerSequence);
578 auto const nftUris = executor_.readEach(yield, selectNFTURIStatements);
580 for (
auto i = 0u; i < nftIDs.size(); i++) {
581 if (
auto const maybeRow = nftInfos[i].
template get<uint32_t, ripple::AccountID, bool>(); maybeRow) {
582 auto [seq, owner, isBurned] = *maybeRow;
583 NFT nft(nftIDs[i], seq, owner, isBurned);
584 if (
auto const maybeUri = nftUris[i].
template get<ripple::Blob>(); maybeUri)
586 ret.nfts.push_back(nft);
594 ripple::uint192
const& mptID,
595 std::uint32_t
const limit,
596 std::optional<ripple::AccountID>
const& cursorIn,
597 std::uint32_t
const ledgerSequence,
598 boost::asio::yield_context yield
601 auto const holderEntries = executor_.read(
602 yield, schema_->selectMPTHolders, mptID, cursorIn.value_or(ripple::AccountID(0)),
Limit{limit}
605 auto const& holderResults = holderEntries.value();
606 if (not holderResults.hasRows()) {
607 LOG(log_.
debug()) <<
"No rows returned";
611 std::vector<ripple::uint256> mptKeys;
612 std::optional<ripple::AccountID> cursor;
614 mptKeys.push_back(ripple::keylet::mptoken(mptID, holder).key);
620 auto it = std::remove_if(mptObjects.begin(), mptObjects.end(), [](Blob
const& mpt) { return mpt.empty(); });
622 mptObjects.erase(it, mptObjects.end());
624 ASSERT(mptKeys.size() <= limit,
"Number of keys can't exceed the limit");
625 if (mptKeys.size() == limit)
626 return {mptObjects, cursor};
628 return {mptObjects, {}};
633 ripple::uint256
const& key,
634 std::uint32_t
const sequence,
635 boost::asio::yield_context yield
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>(); result) {
644 LOG(log_.
debug()) <<
"Could not fetch ledger object - no rows";
647 LOG(log_.
error()) <<
"Could not fetch ledger object: " << res.error();
653 std::optional<std::uint32_t>
655 ripple::uint256
const& key,
656 std::uint32_t
const sequence,
657 boost::asio::yield_context yield
660 LOG(log_.
debug()) <<
"Fetching ledger object for seq " << sequence <<
", key = " << ripple::to_string(key);
661 if (
auto const res = executor_.read(yield, schema_->selectObject, key, sequence); res) {
662 if (
auto const result = res->template get<Blob, std::uint32_t>(); result) {
663 auto [_, seq] = result.value();
666 LOG(log_.
debug()) <<
"Could not fetch ledger object sequence - no rows";
668 LOG(log_.
error()) <<
"Could not fetch ledger object sequence: " << res.error();
674 std::optional<TransactionAndMetadata>
675 fetchTransaction(ripple::uint256
const& hash, boost::asio::yield_context yield)
const override
677 if (
auto const res = executor_.read(yield, schema_->selectTransaction, hash); res) {
678 if (
auto const maybeValue = res->template get<Blob, Blob, uint32_t, uint32_t>(); maybeValue) {
679 auto [transaction, meta, seq, date] = *maybeValue;
680 return std::make_optional<TransactionAndMetadata>(transaction, meta, seq, date);
683 LOG(log_.
debug()) <<
"Could not fetch transaction - no rows";
685 LOG(log_.
error()) <<
"Could not fetch transaction: " << res.error();
691 std::optional<ripple::uint256>
694 std::uint32_t
const ledgerSequence,
695 boost::asio::yield_context yield
698 if (
auto const res = executor_.read(yield, schema_->selectSuccessor, key, ledgerSequence); res) {
699 if (
auto const result = res->template get<ripple::uint256>(); result) {
700 if (*result == kLAST_KEY)
705 LOG(log_.
debug()) <<
"Could not fetch successor - no rows";
707 LOG(log_.
error()) <<
"Could not fetch successor: " << res.error();
713 std::vector<TransactionAndMetadata>
714 fetchTransactions(std::vector<ripple::uint256>
const& hashes, boost::asio::yield_context yield)
const override
719 auto const numHashes = hashes.size();
720 std::vector<TransactionAndMetadata> results;
721 results.reserve(numHashes);
723 std::vector<Statement> statements;
724 statements.reserve(numHashes);
726 auto const timeDiff =
util::timed([
this, yield, &results, &hashes, &statements]() {
729 std::cbegin(hashes), std::cend(hashes), std::back_inserter(statements), [
this](
auto const& hash) {
730 return schema_->selectTransaction.bind(hash);
734 auto const entries = executor_.readEach(yield, statements);
736 std::cbegin(entries),
738 std::back_inserter(results),
740 if (
auto const maybeRow = res.template get<Blob, Blob, uint32_t, uint32_t>(); maybeRow)
748 ASSERT(numHashes == results.size(),
"Number of hashes and results must match");
749 LOG(log_.
debug()) <<
"Fetched " << numHashes <<
" transactions from database in " << timeDiff
756 std::vector<ripple::uint256>
const& keys,
757 std::uint32_t
const sequence,
758 boost::asio::yield_context yield
764 auto const numKeys = keys.size();
765 LOG(log_.
trace()) <<
"Fetching " << numKeys <<
" objects";
767 std::vector<Blob> results;
768 results.reserve(numKeys);
770 std::vector<Statement> statements;
771 statements.reserve(numKeys);
775 std::cbegin(keys), std::cend(keys), std::back_inserter(statements), [
this, &sequence](
auto const& key) {
776 return schema_->selectObject.bind(key, sequence);
780 auto const entries = executor_.readEach(yield, statements);
782 std::cbegin(entries), std::cend(entries), std::back_inserter(results), [](
auto const& res) -> Blob {
783 if (
auto const maybeValue = res.template get<Blob>(); maybeValue)
790 LOG(log_.
trace()) <<
"Fetched " << numKeys <<
" objects";
794 std::vector<ripple::uint256>
796 std::uint32_t number,
797 std::uint32_t pageSize,
799 boost::asio::yield_context yield
802 std::vector<ripple::uint256> liveAccounts;
803 std::optional<ripple::AccountID> lastItem;
805 while (liveAccounts.size() < number) {
806 Statement const statement = lastItem ? schema_->selectAccountFromToken.bind(*lastItem,
Limit{pageSize})
807 : schema_->selectAccountFromBeginning.bind(
Limit{pageSize});
809 auto const res = executor_.read(yield, statement);
811 auto const& results = res.value();
812 if (not results.hasRows()) {
813 LOG(log_.
debug()) <<
"No rows returned";
817 std::vector<ripple::uint256> fullAccounts;
819 fullAccounts.push_back(ripple::keylet::account(account).key);
824 for (
auto i = 0u; i < fullAccounts.size(); i++) {
825 if (not objs[i].empty()) {
826 if (liveAccounts.size() < number) {
827 liveAccounts.push_back(fullAccounts[i]);
834 LOG(log_.
error()) <<
"Could not fetch account from account_tx: " << res.error();
842 std::vector<LedgerObject>
843 fetchLedgerDiff(std::uint32_t
const ledgerSequence, boost::asio::yield_context yield)
const override
845 auto const [keys, timeDiff] =
util::timed([
this, &ledgerSequence, yield]() -> std::vector<ripple::uint256> {
846 auto const res = executor_.read(yield, schema_->selectDiff, ledgerSequence);
848 LOG(log_.
error()) <<
"Could not fetch ledger diff: " << res.error() <<
"; ledger = " << ledgerSequence;
852 auto const& results = res.value();
854 LOG(log_.
error()) <<
"Could not fetch ledger diff - no rows; ledger = " << ledgerSequence;
858 std::vector<ripple::uint256> resultKeys;
860 resultKeys.push_back(key);
869 LOG(log_.
debug()) <<
"Fetched " << keys.size() <<
" diff hashes from database in " << timeDiff
873 std::vector<LedgerObject> results;
874 results.reserve(keys.size());
880 std::back_inserter(results),
881 [](
auto const& key,
auto const& obj) {
return LedgerObject{key, obj}; }
887 std::optional<std::string>
890 auto const res = executor_.read(yield, schema_->selectMigratorStatus,
Text(migratorName));
892 LOG(log_.
error()) <<
"Could not fetch migrator status: " << res.error();
896 auto const& results = res.value();
907 std::expected<std::vector<std::pair<boost::uuids::uuid, std::string>>, std::string>
910 auto const readResult = executor_.read(yield, schema_->selectClioNodesData);
912 return std::unexpected{readResult.error().message()};
914 std::vector<std::pair<boost::uuids::uuid, std::string>> result;
917 result.emplace_back(uuid, std::move(message));
926 LOG(log_.
trace()) <<
" Writing ledger object " << key.size() <<
":" << seq <<
" [" << blob.size() <<
" bytes]";
929 executor_.write(schema_->insertDiff, seq, key);
931 executor_.write(schema_->insertObject, std::move(key), seq, std::move(blob));
935 writeSuccessor(std::string&& key, std::uint32_t
const seq, std::string&& successor)
override
937 LOG(log_.
trace()) <<
"Writing successor. key = " << key.size() <<
" bytes. "
938 <<
" seq = " << std::to_string(seq) <<
" successor = " << successor.size() <<
" bytes.";
939 ASSERT(!key.empty(),
"Key must not be empty");
940 ASSERT(!successor.empty(),
"Successor must not be empty");
942 executor_.write(schema_->insertSuccessor, std::move(key), seq, std::move(successor));
948 std::vector<Statement> statements;
949 statements.reserve(
data.size() * 10);
951 for (
auto& record :
data) {
952 std::ranges::transform(record.accounts, std::back_inserter(statements), [
this, &record](
auto&& account) {
953 return schema_->insertAccountTx.bind(
954 std::forward<decltype(account)>(account),
955 std::make_tuple(record.ledgerSequence, record.transactionIndex),
961 executor_.write(std::move(statements));
967 std::vector<Statement> statements;
968 statements.reserve(record.accounts.size());
970 std::ranges::transform(record.accounts, std::back_inserter(statements), [
this, &record](
auto&& account) {
971 return schema_->insertAccountTx.bind(
972 std::forward<decltype(account)>(account),
973 std::make_tuple(record.ledgerSequence, record.transactionIndex),
978 executor_.write(std::move(statements));
984 std::vector<Statement> statements;
985 statements.reserve(
data.size());
987 std::ranges::transform(
data, std::back_inserter(statements), [
this](
auto const& record) {
988 return schema_->insertNFTTx.bind(
989 record.tokenID, std::make_tuple(record.ledgerSequence, record.transactionIndex), record.txHash
993 executor_.write(std::move(statements));
999 std::uint32_t
const seq,
1000 std::uint32_t
const date,
1001 std::string&& transaction,
1002 std::string&& metadata
1005 LOG(log_.
trace()) <<
"Writing txn to database";
1007 executor_.write(schema_->insertLedgerTransaction, seq, hash);
1009 schema_->insertTransaction, std::move(hash), seq, date, std::move(transaction), std::move(metadata)
1016 std::vector<Statement> statements;
1017 statements.reserve(
data.size() * 3);
1020 if (!record.onlyUriChanged) {
1021 statements.push_back(
1022 schema_->insertNFT.bind(record.tokenID, record.ledgerSequence, record.owner, record.isBurned)
1031 statements.push_back(schema_->insertIssuerNFT.bind(
1032 ripple::nft::getIssuer(record.tokenID),
1033 static_cast<uint32_t
>(ripple::nft::getTaxon(record.tokenID)),
1036 statements.push_back(
1037 schema_->insertNFTURI.bind(record.tokenID, record.ledgerSequence, record.uri.value())
1042 statements.push_back(
1043 schema_->insertNFTURI.bind(record.tokenID, record.ledgerSequence, record.uri.value())
1048 executor_.writeEach(std::move(statements));
1054 std::vector<Statement> statements;
1055 statements.reserve(
data.size());
1056 for (
auto [mptId, holder] :
data)
1057 statements.push_back(schema_->insertMPTHolder.bind(mptId, holder));
1059 executor_.write(std::move(statements));
1072 executor_.writeSync(
1080 executor_.writeSync(schema_->updateClioNodeMessage,
data::cassandra::Text{std::move(message)}, uuid);
1086 return executor_.isTooBusy();
1092 return executor_.stats();
1099 auto const res = executor_.writeSync(statement);
1100 auto maybeSuccess = res->template get<bool>();
1101 if (not maybeSuccess) {
1102 LOG(log_.
error()) <<
"executeSyncUpdate - error getting result - no row";
1106 if (not maybeSuccess.value()) {
1107 LOG(log_.
warn()) <<
"Update failed. Checking if DB state is what we expect";
1114 return rng && rng->maxSequence == ledgerSequence_;
1121using CassandraBackend = BasicCassandraBackend<SettingsProvider, impl::DefaultExecutionStrategy<>>;
The interface to the database used by Clio.
Definition BackendInterface.hpp:139
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:164
Cache for an entire ledger.
Definition LedgerCacheInterface.hpp:38
Implements BackendInterface for Cassandra/ScyllaDB.
Definition CassandraBackend.hpp:83
bool isTooBusy() const override
Definition CassandraBackend.hpp:1084
std::optional< std::uint32_t > fetchLatestLedgerSequence(boost::asio::yield_context yield) const override
Fetches the latest ledger sequence.
Definition CassandraBackend.hpp:252
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:593
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:364
void writeMPTHolders(std::vector< MPTHolderData > const &data) override
Write accounts that started holding onto a MPT.
Definition CassandraBackend.hpp:1052
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:632
std::optional< LedgerRange > hardFetchLedgerRange(boost::asio::yield_context yield) const override
Fetches the ledger range from DB.
Definition CassandraBackend.hpp:319
void writeSuccessor(std::string &&key, std::uint32_t const seq, std::string &&successor) override
Write a new successor.
Definition CassandraBackend.hpp:935
void waitForWritesToFinish() override
Wait for all pending writes to finish.
Definition CassandraBackend.hpp:218
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:299
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:357
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:272
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:755
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:150
void writeAccountTransaction(AccountTransactionsData record) override
Write a new account transaction.
Definition CassandraBackend.hpp:965
void writeAccountTransactions(std::vector< AccountTransactionsData > data) override
Write a new set of account transactions.
Definition CassandraBackend.hpp:946
BasicCassandraBackend(SettingsProviderType settingsProvider, data::LedgerCacheInterface &cache, bool readOnly)
Create a new cassandra/scylla backend instance.
Definition CassandraBackend.hpp:107
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:397
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:795
void writeNFTs(std::vector< NFTsData > const &data) override
Writes NFTs to the database.
Definition CassandraBackend.hpp:1014
std::vector< LedgerObject > fetchLedgerDiff(std::uint32_t const ledgerSequence, boost::asio::yield_context yield) const override
Returns the difference between ledgers.
Definition CassandraBackend.hpp:843
void writeLedger(ripple::LedgerHeader const &ledgerHeader, std::string &&blob) override
Writes to a specific ledger.
Definition CassandraBackend.hpp:242
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:654
void writeNodeMessage(boost::uuids::uuid const &uuid, std::string message) override
Write a node message. Used by ClusterCommunicationService.
Definition CassandraBackend.hpp:1078
std::optional< TransactionAndMetadata > fetchTransaction(ripple::uint256 const &hash, boost::asio::yield_context yield) const override
Fetches a specific transaction.
Definition CassandraBackend.hpp:675
std::vector< TransactionAndMetadata > fetchTransactions(std::vector< ripple::uint256 > const &hashes, boost::asio::yield_context yield) const override
Fetches multiple transactions.
Definition CassandraBackend.hpp:714
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:888
void startWrites() const override
Starts a write transaction with the DB. No-op for cassandra.
Definition CassandraBackend.hpp:1063
void doWriteLedgerObject(std::string &&key, std::uint32_t const seq, std::string &&blob) override
Writes a ledger object to the database.
Definition CassandraBackend.hpp:924
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:436
boost::json::object stats() const override
Definition CassandraBackend.hpp:1090
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:908
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:507
void writeNFTTransactions(std::vector< NFTTransactionsData > const &data) override
Write NFTs transactions.
Definition CassandraBackend.hpp:982
bool doFinishWrites() override
The implementation should wait for all pending writes to finish.
Definition CassandraBackend.hpp:224
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:692
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:997
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:1070
Represents a handle to the cassandra database cluster.
Definition Handle.hpp:46
MaybeErrorType connect() const
Synchronous version of the above.
Definition Handle.cpp:55
MaybeErrorType executeEach(std::vector< StatementType > const &statements) const
Synchronous version of the above.
Definition Handle.cpp:109
ResultOrErrorType execute(std::string_view query, Args &&... args) const
Synchronous 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:964
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:317
Pump error(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::ERR severity.
Definition Logger.cpp:322
Pump debug(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::DBG severity.
Definition Logger.cpp:307
Pump trace(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::TRC severity.
Definition Logger.cpp:302
Pump info(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:312
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:205
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
Struct to store ledger header cache entry and the sequence it belongs to.
Definition LedgerHeaderCache.hpp:48
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