Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
KeyspaceBackend.hpp
1#pragma once
2
3#include "data/LedgerHeaderCache.hpp"
4#include "data/Types.hpp"
5#include "data/cassandra/CassandraBackendFamily.hpp"
6#include "data/cassandra/Concepts.hpp"
7#include "data/cassandra/KeyspaceSchema.hpp"
8#include "data/cassandra/SettingsProvider.hpp"
9#include "data/cassandra/Types.hpp"
10#include "data/cassandra/impl/ExecutionStrategy.hpp"
11#include "util/Assert.hpp"
12#include "util/log/Logger.hpp"
13
14#include <boost/asio/spawn.hpp>
15#include <boost/json/object.hpp>
16#include <boost/uuid/string_generator.hpp>
17#include <boost/uuid/uuid.hpp>
18#include <cassandra.h>
19#include <fmt/format.h>
20#include <xrpl/basics/Blob.h>
21#include <xrpl/basics/base_uint.h>
22#include <xrpl/basics/strHex.h>
23#include <xrpl/protocol/AccountID.h>
24#include <xrpl/protocol/Indexes.h>
25#include <xrpl/protocol/LedgerHeader.h>
26#include <xrpl/protocol/nft.h>
27
28#include <cstddef>
29#include <cstdint>
30#include <iterator>
31#include <optional>
32#include <stdexcept>
33#include <utility>
34#include <vector>
35
36namespace data::cassandra {
37
45template <
46 SomeSettingsProvider SettingsProviderType,
47 SomeExecutionStrategy ExecutionStrategyType,
48 typename FetchLedgerCacheType = FetchLedgerCache>
50 SettingsProviderType,
51 ExecutionStrategyType,
52 KeyspaceSchema<SettingsProviderType>,
53 FetchLedgerCacheType> {
54 using DefaultCassandraFamily = CassandraBackendFamily<
55 SettingsProviderType,
56 ExecutionStrategyType,
58 FetchLedgerCacheType>;
59
60 using DefaultCassandraFamily::executor_;
61 using DefaultCassandraFamily::ledgerSequence_;
62 using DefaultCassandraFamily::log_;
63 using DefaultCassandraFamily::range_;
64 using DefaultCassandraFamily::schema_;
65
66public:
70 using DefaultCassandraFamily::DefaultCassandraFamily;
71
76
86 bool
87 doFinishWrites() override
88 {
90
91 // !range_.has_value() means the table 'ledger_range' is not populated;
92 // This would be the first write to the table.
93 // In this case, insert both min_sequence/max_sequence range into the table.
94 if (not range_.has_value()) {
95 executor_.writeSync(
96 schema_->insertLedgerRange, /* isLatestLedger =*/false, ledgerSequence_
97 );
98 executor_.writeSync(
99 schema_->insertLedgerRange, /* isLatestLedger =*/true, ledgerSequence_
100 );
101 }
102
103 if (not this->executeSyncUpdate(
104 schema_->updateLedgerRange.bind(ledgerSequence_, true, ledgerSequence_ - 1)
105 )) {
106 log_.warn() << "Update failed for ledger " << ledgerSequence_;
107 return false;
108 }
109
110 log_.info() << "Committed ledger " << ledgerSequence_;
111 return true;
112 }
113
125 [[nodiscard]] NFTsAndCursor
127 xrpl::AccountID const& issuer,
128 std::optional<std::uint32_t> const& taxon,
129 std::uint32_t const ledgerSequence,
130 std::uint32_t const limit,
131 std::optional<xrpl::uint256> const& cursorIn,
132 boost::asio::yield_context yield
133 ) const override
134 {
135 std::vector<xrpl::uint256> nftIDs;
136 if (taxon.has_value()) {
137 // Keyspace and ScyllaDB uses the same logic for taxon-filtered queries
138 nftIDs = fetchNFTIDsByTaxon(issuer, *taxon, limit, cursorIn, yield);
139 } else {
140 // Amazon Keyspaces Workflow for non-taxon queries
141 auto const startTaxon =
142 cursorIn.has_value() ? xrpl::nft::toUInt32(xrpl::nft::getTaxon(*cursorIn)) : 0;
143 auto const startTokenID = cursorIn.value_or(xrpl::uint256(0));
144
145 Statement const firstQuery = schema_->selectNFTIDsByIssuerTaxon.bind(issuer);
146 firstQuery.bindAt(1, startTaxon);
147 firstQuery.bindAt(2, startTokenID);
148 firstQuery.bindAt(3, Limit{limit});
149
150 auto const firstRes = executor_.read(yield, firstQuery);
151 if (firstRes.has_value()) {
152 for (auto const [nftID] : extract<xrpl::uint256>(*firstRes))
153 nftIDs.push_back(nftID);
154 }
155
156 if (nftIDs.size() < limit) {
157 auto const remainingLimit = limit - nftIDs.size();
158 Statement const secondQuery = schema_->selectNFTsAfterTaxonKeyspaces.bind(issuer);
159 secondQuery.bindAt(1, startTaxon);
160 secondQuery.bindAt(2, Limit{remainingLimit});
161
162 auto const secondRes = executor_.read(yield, secondQuery);
163 if (secondRes.has_value()) {
164 for (auto const [nftID] : extract<xrpl::uint256>(*secondRes))
165 nftIDs.push_back(nftID);
166 }
167 }
168 }
169 return populateNFTsAndCreateCursor(nftIDs, ledgerSequence, limit, yield);
170 }
171
185 [[nodiscard]] std::vector<xrpl::uint256>
187 [[maybe_unused]] std::uint32_t number,
188 [[maybe_unused]] std::uint32_t pageSize,
189 [[maybe_unused]] std::uint32_t seq,
190 [[maybe_unused]] boost::asio::yield_context yield
191 ) const override
192 {
193 ASSERT(false, "Fetching account roots is not supported by the Keyspaces backend.");
194 std::unreachable();
195 }
196
197private:
198 [[nodiscard]] std::vector<xrpl::uint256>
199 fetchNFTIDsByTaxon(
200 xrpl::AccountID const& issuer,
201 std::uint32_t const taxon,
202 std::uint32_t const limit,
203 std::optional<xrpl::uint256> const& cursorIn,
204 boost::asio::yield_context yield
205 ) const
206 {
207 std::vector<xrpl::uint256> nftIDs;
208 Statement const statement = schema_->selectNFTIDsByIssuerTaxon.bind(issuer);
209 statement.bindAt(1, taxon);
210 statement.bindAt(2, cursorIn.value_or(xrpl::uint256(0)));
211 statement.bindAt(3, Limit{limit});
212
213 auto const res = executor_.read(yield, statement);
214 if (res.has_value() && res->hasRows()) {
215 for (auto const [nftID] : extract<xrpl::uint256>(*res))
216 nftIDs.push_back(nftID);
217 }
218 return nftIDs;
219 }
220
221 [[nodiscard]] std::vector<xrpl::uint256>
222 fetchNFTIDsWithoutTaxon(
223 xrpl::AccountID const& issuer,
224 std::uint32_t const limit,
225 std::optional<xrpl::uint256> const& cursorIn,
226 boost::asio::yield_context yield
227 ) const
228 {
229 std::vector<xrpl::uint256> nftIDs;
230
231 auto const startTaxon =
232 cursorIn.has_value() ? xrpl::nft::toUInt32(xrpl::nft::getTaxon(*cursorIn)) : 0;
233 auto const startTokenID = cursorIn.value_or(xrpl::uint256(0));
234
235 Statement firstQuery = schema_->selectNFTIDsByIssuerTaxon.bind(issuer);
236 firstQuery.bindAt(1, startTaxon);
237 firstQuery.bindAt(2, startTokenID);
238 firstQuery.bindAt(3, Limit{limit});
239
240 auto const firstRes = executor_.read(yield, firstQuery);
241 if (firstRes.has_value()) {
242 for (auto const [nftID] : extract<xrpl::uint256>(*firstRes))
243 nftIDs.push_back(nftID);
244 }
245
246 if (nftIDs.size() < limit) {
247 auto const remainingLimit = limit - nftIDs.size();
248 Statement secondQuery = schema_->selectNFTsAfterTaxonKeyspaces.bind(issuer);
249 secondQuery.bindAt(1, startTaxon);
250 secondQuery.bindAt(2, Limit{remainingLimit});
251
252 auto const secondRes = executor_.read(yield, secondQuery);
253 if (secondRes.has_value()) {
254 for (auto const [nftID] : extract<xrpl::uint256>(*secondRes))
255 nftIDs.push_back(nftID);
256 }
257 }
258 return nftIDs;
259 }
260
265 [[nodiscard]] NFTsAndCursor
266 populateNFTsAndCreateCursor(
267 std::vector<xrpl::uint256> const& nftIDs,
268 std::uint32_t const ledgerSequence,
269 std::uint32_t const limit,
270 boost::asio::yield_context yield
271 ) const
272 {
273 if (nftIDs.empty()) {
274 LOG(log_.debug()) << "No rows returned";
275 return {};
276 }
277
278 NFTsAndCursor ret;
279 if (nftIDs.size() == limit)
280 ret.cursor = nftIDs.back();
281
282 // Prepare and execute queries to fetch NFT info and URIs in parallel.
283 std::vector<Statement> selectNFTStatements;
284 selectNFTStatements.reserve(nftIDs.size());
285 std::transform(
286 std::cbegin(nftIDs),
287 std::cend(nftIDs),
288 std::back_inserter(selectNFTStatements),
289 [&](auto const& nftID) { return schema_->selectNFT.bind(nftID, ledgerSequence); }
290 );
291
292 std::vector<Statement> selectNFTURIStatements;
293 selectNFTURIStatements.reserve(nftIDs.size());
294 std::transform(
295 std::cbegin(nftIDs),
296 std::cend(nftIDs),
297 std::back_inserter(selectNFTURIStatements),
298 [&](auto const& nftID) { return schema_->selectNFTURI.bind(nftID, ledgerSequence); }
299 );
300
301 auto const nftInfos = executor_.readEach(yield, selectNFTStatements);
302 auto const nftUris = executor_.readEach(yield, selectNFTURIStatements);
303
304 // Combine the results into final NFT objects.
305 for (auto i = 0u; i < nftIDs.size(); ++i) {
306 if (auto const maybeRow = nftInfos[i].template get<uint32_t, xrpl::AccountID, bool>();
307 maybeRow.has_value()) {
308 auto [seq, owner, isBurned] = *maybeRow;
309 NFT nft(nftIDs[i], seq, owner, isBurned);
310 if (auto const maybeUri = nftUris[i].template get<xrpl::Blob>();
311 maybeUri.has_value())
312 nft.uri = *maybeUri;
313 ret.nfts.push_back(nft);
314 }
315 }
316 return ret;
317 }
318};
319
324
325} // namespace data::cassandra
Implements CassandraBackendFamily for Keyspace.
Definition KeyspaceBackend.hpp:53
NFTsAndCursor fetchNFTsByIssuer(xrpl::AccountID const &issuer, std::optional< std::uint32_t > const &taxon, std::uint32_t const ledgerSequence, std::uint32_t const limit, std::optional< xrpl::uint256 > const &cursorIn, boost::asio::yield_context yield) const override
Fetches all NFTs issued by a given address.
Definition KeyspaceBackend.hpp:126
BasicKeyspaceBackend(BasicKeyspaceBackend &&)=delete
Move constructor is deleted because handle_ is shared by reference with executor.
bool doFinishWrites() override
Wait for pending writes and commit the ledger range update for the current ledger.
Definition KeyspaceBackend.hpp:87
std::vector< xrpl::uint256 > fetchAccountRoots(std::uint32_t number, std::uint32_t pageSize, std::uint32_t seq, boost::asio::yield_context yield) const override
(Unsupported in Keyspaces) Fetches account root object indexes by page.
Definition KeyspaceBackend.hpp:186
CassandraBackendFamily(SettingsProviderType settingsProvider, data::LedgerCacheInterface &cache, bool readOnly)
Definition CassandraBackendFamily.hpp:98
Manages the DB schema and provides access to prepared statements.
Definition KeyspaceSchema.hpp:24
void bind(Args &&... args) const
Binds the given arguments to the statement.
Definition Statement.hpp:62
void bindAt(std::size_t const idx, Type &&value) const
Binds an argument to a specific index.
Definition Statement.hpp:76
The requirements of an execution strategy.
Definition Concepts.hpp:39
The requirements of a settings provider.
Definition Concepts.hpp:26
This namespace implements a wrapper for the Cassandra C++ driver.
Definition CassandraBackendFamily.hpp:50
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:318
impl::Statement Statement
A simple or bound statement.
Definition Types.hpp:27
BasicKeyspaceBackend< SettingsProvider, impl::DefaultExecutionStrategy<> > KeyspaceBackend
The Keyspace backend with the default settings provider and execution strategy.
Definition KeyspaceBackend.hpp:323
Represents a bundle of NFTs with a cursor to the next page.
Definition Types.hpp:230
A strong type wrapper for int32_t.
Definition Types.hpp:38