3#include "data/BackendInterface.hpp"
5#include "etl/LedgerPublisherInterface.hpp"
6#include "etl/SystemState.hpp"
7#include "etl/impl/Loading.hpp"
8#include "feed/SubscriptionManagerInterface.hpp"
9#include "util/Assert.hpp"
10#include "util/Mutex.hpp"
11#include "util/async/AnyExecutionContext.hpp"
12#include "util/async/AnyStrand.hpp"
13#include "util/log/Logger.hpp"
14#include "util/prometheus/Counter.hpp"
15#include "util/prometheus/Prometheus.hpp"
17#include <boost/asio/io_context.hpp>
18#include <boost/asio/post.hpp>
19#include <boost/asio/strand.hpp>
20#include <fmt/format.h>
21#include <xrpl/basics/chrono.h>
22#include <xrpl/protocol/Fees.h>
23#include <xrpl/protocol/LedgerHeader.h>
24#include <xrpl/protocol/SField.h>
25#include <xrpl/protocol/STObject.h>
26#include <xrpl/protocol/Serializer.h>
37#include <shared_mutex>
62 std::atomic_bool stop_{
false};
64 std::shared_ptr<BackendInterface> backend_;
65 std::shared_ptr<feed::SubscriptionManagerInterface> subscriptions_;
66 std::reference_wrapper<SystemState const> state_;
70 std::reference_wrapper<util::prometheus::CounterInt> lastPublishSeconds_ =
72 "etl_last_publish_seconds",
74 "Seconds since epoch of the last published ledger"
79 std::chrono::steady_clock::duration maxWaitForDbProgress_;
87 std::chrono::minutes{5};
101 std::shared_ptr<BackendInterface> backend,
102 std::shared_ptr<feed::SubscriptionManagerInterface> subscriptions,
106 : publishStrand_{ctx.makeStrand()}
107 , backend_{std::move(backend)}
108 , subscriptions_{std::move(subscriptions)}
109 , state_{std::cref(state)}
110 , maxWaitForDbProgress_{maxWaitForDbProgress}
131 uint32_t ledgerSequence,
132 std::optional<uint32_t> maxAttempts,
133 std::chrono::steady_clock::duration attemptsDelay = std::chrono::seconds{1}
136 LOG(log_.
info()) <<
"Attempting to publish ledger = " << ledgerSequence;
137 size_t numAttempts = 0;
141 uint32_t maxSequence;
142 std::chrono::steady_clock::time_point since;
144 std::optional<DbProgress> lastDbProgress;
147 auto range = backend_->hardFetchLedgerRangeNoThrow();
149 if (!range || range->maxSequence < ledgerSequence) {
154 if (maxAttempts && numAttempts >= maxAttempts) {
156 <<
"Failed to publish ledger after " << numAttempts <<
" attempts.";
160 if (not range.has_value()) {
162 LOG(log_.
warn()) <<
"Could not fetch ledger range to publish ledger "
163 << ledgerSequence <<
". Retrying";
165 auto const now = std::chrono::steady_clock::now();
166 if (not lastDbProgress.has_value() or
167 range->maxSequence > lastDbProgress->maxSequence) {
169 DbProgress{.maxSequence = range->maxSequence, .since = now};
172 auto const stalledFor = now - lastDbProgress->since;
173 auto const stalledSeconds =
174 std::chrono::duration_cast<std::chrono::seconds>(stalledFor).count();
176 <<
"Ledger " << ledgerSequence <<
" is not in DB yet; DB max sequence is "
177 << range->maxSequence <<
", no progress for " << stalledSeconds <<
"s";
183 stalledFor < maxWaitForDbProgress_,
184 "Ledger {} was expected to be in DB, but DB max sequence stayed at {} for "
185 "{}s. Restarting is the only way to recover",
192 std::this_thread::sleep_for(attemptsDelay);
197 return backend_->fetchLedgerBySequence(ledgerSequence, yield);
202 "Ledger must exist in database. Ledger sequence = {}",
225 publishStrand_.submit([
this, lgrInfo = lgrInfo] {
226 LOG(log_.info()) <<
"Publishing ledger " << std::to_string(lgrInfo.seq);
228 setLastClose(lgrInfo.closeTime);
233 static constexpr std::uint32_t kMaxLedgerAgeSeconds = 600;
234 if (age < kMaxLedgerAgeSeconds) {
235 std::optional<xrpl::Fees> fees =
237 return backend_->fetchFees(lgrInfo.seq, yield);
239 ASSERT(fees.has_value(),
"Fees must exist for ledger {}", lgrInfo.seq);
242 return backend_->fetchAllTransactionsInLedger(lgrInfo.seq, yield);
245 auto const ledgerRange = backend_->fetchLedgerRange();
246 ASSERT(ledgerRange.has_value(),
"Ledger range must exist");
249 fmt::format(
"{}-{}", ledgerRange->minSequence, ledgerRange->maxSequence);
250 subscriptions_->pubLedger(lgrInfo, *fees, range, transactions.size());
253 std::ranges::sort(transactions, [](
auto const& t1,
auto const& t2) {
254 xrpl::SerialIter iter1{t1.metadata.data(), t1.metadata.size()};
255 xrpl::STObject
const object1(iter1, xrpl::sfMetadata);
256 xrpl::SerialIter iter2{t2.metadata.data(), t2.metadata.size()};
257 xrpl::STObject
const object2(iter2, xrpl::sfMetadata);
258 return object1.getFieldU32(xrpl::sfTransactionIndex) <
259 object2.getFieldU32(xrpl::sfTransactionIndex);
262 for (
auto const& txAndMeta : transactions)
263 subscriptions_->pubTransaction(txAndMeta, lgrInfo);
265 subscriptions_->pubBookChanges(lgrInfo, transactions);
267 setLastPublishTime();
268 LOG(log_.info()) <<
"Published ledger " << lgrInfo.seq;
270 LOG(log_.info()) <<
"Skipping publishing ledger " << lgrInfo.seq;
275 setLastPublishedSequence(lgrInfo.seq);
284 return std::chrono::duration_cast<std::chrono::seconds>(
293 std::chrono::time_point<std::chrono::system_clock>
296 return std::chrono::time_point<std::chrono::system_clock>{
297 std::chrono::seconds{lastPublishSeconds_.get().value()}
307 auto const closeTime = lastCloseTime_.lock()->time_since_epoch().count();
308 auto const now = std::chrono::duration_cast<std::chrono::seconds>(
309 std::chrono::system_clock::now().time_since_epoch()
321 std::optional<uint32_t>
324 return *lastPublishedSequence_.lock();
341 setLastClose(std::chrono::time_point<xrpl::NetClock> lastCloseTime)
343 auto closeTime = lastCloseTime_.
lock<std::scoped_lock>();
344 *closeTime = lastCloseTime;
350 using namespace std::chrono;
351 auto const nowSeconds =
352 duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
353 lastPublishSeconds_.get().set(nowSeconds);
357 setLastPublishedSequence(std::optional<uint32_t> lastPublishedSequence)
359 auto lastPublishSeq = lastPublishedSequence_.lock();
360 *lastPublishSeq = lastPublishedSequence;
static constexpr std::uint32_t kRippleEpochStart
The ripple epoch start timestamp. Midnight on 1st January 2000.
Definition DBHelpers.hpp:296
static util::prometheus::CounterInt & counterInt(std::string name, util::prometheus::Labels labels, std::optional< std::string > description=std::nullopt)
Get an integer based counter metric. It will be created if it doesn't exist.
Definition Prometheus.cpp:211
std::chrono::time_point< std::chrono::system_clock > getLastPublish() const override
Get last publish time as a time point.
Definition LedgerPublisher.hpp:294
std::optional< uint32_t > getLastPublishedSequence() const
Get the sequence of the last schueduled ledger to publish, Be aware that the ledger may not have been...
Definition LedgerPublisher.hpp:322
bool publish(uint32_t ledgerSequence, std::optional< uint32_t > maxAttempts, std::chrono::steady_clock::duration attemptsDelay=std::chrono::seconds{1}) override
Attempt to read the specified ledger from the database, and then publish that ledger to the ledgers s...
Definition LedgerPublisher.hpp:130
LedgerPublisher(util::async::AnyExecutionContext ctx, std::shared_ptr< BackendInterface > backend, std::shared_ptr< feed::SubscriptionManagerInterface > subscriptions, SystemState const &state, std::chrono::steady_clock::duration maxWaitForDbProgress=kDefaultMaxWaitForDbProgress)
Create an instance of the publisher.
Definition LedgerPublisher.hpp:99
std::uint32_t lastCloseAgeSeconds() const override
Get time passed since last ledger close, in seconds.
Definition LedgerPublisher.hpp:305
std::uint32_t lastPublishAgeSeconds() const override
Get time passed since last publish, in seconds.
Definition LedgerPublisher.hpp:282
void publish(xrpl::LedgerHeader const &lgrInfo)
Publish the passed ledger asynchronously.
Definition LedgerPublisher.hpp:223
void stop() override
Stops publishing.
Definition LedgerPublisher.hpp:334
static constexpr std::chrono::steady_clock::duration kDefaultMaxWaitForDbProgress
Default for how long publish() waits while the DB is reachable but stays behind the requested ledger ...
Definition LedgerPublisher.hpp:86
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 warn(std::source_location const &loc=std::source_location::current()) const
Interface for logging at Severity::WRN severity.
Definition Logger.cpp:504
A container for data that is protected by a mutex. Inspired by Mutex in Rust.
Definition Mutex.hpp:82
Lock< ProtectedDataType const, LockType, MutexType > lock() const
Lock the mutex and get a lock object allowing access to the protected data.
Definition Mutex.hpp:120
A type-erased execution context.
Definition AnyExecutionContext.hpp:23
A type-erased execution context.
Definition AnyStrand.hpp:22
auto synchronousAndRetryOnTimeout(FnType &&func, util::Retry::Delays delays=kDefaultRetryDelays)
Synchronously execute the given function object and retry until no DatabaseError is thrown.
Definition BackendInterface.hpp:203
The interface of a scheduler for the extraction process.
Definition LedgerPublisherInterface.hpp:12
Represents the state of the ETL subsystem.
Definition SystemState.hpp:20