Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
LedgerPublisher.hpp
1#pragma once
2
3#include "data/BackendInterface.hpp"
4#include "data/DBHelpers.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"
16
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>
27
28#include <algorithm>
29#include <atomic>
30#include <chrono>
31#include <cstddef>
32#include <cstdint>
33#include <functional>
34#include <memory>
35#include <mutex>
36#include <optional>
37#include <shared_mutex>
38#include <string>
39#include <thread>
40#include <utility>
41#include <vector>
42
43namespace etl::impl {
44
58 util::Logger log_{"ETL"};
59
60 util::async::AnyStrand publishStrand_;
61
62 std::atomic_bool stop_{false};
63
64 std::shared_ptr<BackendInterface> backend_;
65 std::shared_ptr<feed::SubscriptionManagerInterface> subscriptions_;
66 std::reference_wrapper<SystemState const> state_; // shared state for ETL
67
68 util::Mutex<std::chrono::time_point<xrpl::NetClock>, std::shared_mutex> lastCloseTime_;
69
70 std::reference_wrapper<util::prometheus::CounterInt> lastPublishSeconds_ =
72 "etl_last_publish_seconds",
73 {},
74 "Seconds since epoch of the last published ledger"
75 );
76
77 util::Mutex<std::optional<uint32_t>, std::shared_mutex> lastPublishedSequence_;
78
79 std::chrono::steady_clock::duration maxWaitForDbProgress_;
80
81public:
86 static constexpr std::chrono::steady_clock::duration kDefaultMaxWaitForDbProgress =
87 std::chrono::minutes{5};
88
101 std::shared_ptr<BackendInterface> backend,
102 std::shared_ptr<feed::SubscriptionManagerInterface> subscriptions,
103 SystemState const& state,
104 std::chrono::steady_clock::duration maxWaitForDbProgress = kDefaultMaxWaitForDbProgress
105 )
106 : publishStrand_{ctx.makeStrand()}
107 , backend_{std::move(backend)}
108 , subscriptions_{std::move(subscriptions)}
109 , state_{std::cref(state)}
110 , maxWaitForDbProgress_{maxWaitForDbProgress}
111 {
112 }
113
129 bool
131 uint32_t ledgerSequence,
132 std::optional<uint32_t> maxAttempts,
133 std::chrono::steady_clock::duration attemptsDelay = std::chrono::seconds{1}
134 ) override
135 {
136 LOG(log_.info()) << "Attempting to publish ledger = " << ledgerSequence;
137 size_t numAttempts = 0;
138
139 // Tracks when the DB was last seen making progress while staying behind ledgerSequence
140 struct DbProgress {
141 uint32_t maxSequence;
142 std::chrono::steady_clock::time_point since;
143 };
144 std::optional<DbProgress> lastDbProgress;
145
146 while (not stop_) {
147 auto range = backend_->hardFetchLedgerRangeNoThrow();
148
149 if (!range || range->maxSequence < ledgerSequence) {
150 ++numAttempts;
151
152 // We try maxAttempts times to publish the ledger, waiting attemptsDelay in between
153 // each attempt.
154 if (maxAttempts && numAttempts >= maxAttempts) {
155 LOG(log_.warn())
156 << "Failed to publish ledger after " << numAttempts << " attempts.";
157 return false;
158 }
159
160 if (not range.has_value()) {
161 // The DB is unavailable: waiting is all we can do
162 LOG(log_.warn()) << "Could not fetch ledger range to publish ledger "
163 << ledgerSequence << ". Retrying";
164 } else {
165 auto const now = std::chrono::steady_clock::now();
166 if (not lastDbProgress.has_value() or
167 range->maxSequence > lastDbProgress->maxSequence) {
168 lastDbProgress =
169 DbProgress{.maxSequence = range->maxSequence, .since = now};
170 }
171
172 auto const stalledFor = now - lastDbProgress->since;
173 auto const stalledSeconds =
174 std::chrono::duration_cast<std::chrono::seconds>(stalledFor).count();
175 LOG(log_.warn())
176 << "Ledger " << ledgerSequence << " is not in DB yet; DB max sequence is "
177 << range->maxSequence << ", no progress for " << stalledSeconds << "s";
178
179 // The caller only asks for ledgers it has seen committed, so a DB that stays
180 // behind means a bug or an external change to the DB. Unless another node
181 // writes the ledger, this would block publishing (and the Monitor) forever.
182 ASSERT(
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",
186 ledgerSequence,
187 range->maxSequence,
188 stalledSeconds
189 );
190 }
191
192 std::this_thread::sleep_for(attemptsDelay);
193 continue;
194 }
195
196 auto lgr = data::synchronousAndRetryOnTimeout([&](auto yield) {
197 return backend_->fetchLedgerBySequence(ledgerSequence, yield);
198 });
199
200 ASSERT(
201 lgr.has_value(),
202 "Ledger must exist in database. Ledger sequence = {}",
203 ledgerSequence
204 );
205 if (!lgr)
206 return false;
207 publish(*lgr);
208
209 return true;
210 }
211 return false;
212 }
213
222 void
223 publish(xrpl::LedgerHeader const& lgrInfo)
224 {
225 publishStrand_.submit([this, lgrInfo = lgrInfo] {
226 LOG(log_.info()) << "Publishing ledger " << std::to_string(lgrInfo.seq);
227
228 setLastClose(lgrInfo.closeTime);
229 auto age = lastCloseAgeSeconds();
230
231 // if the ledger closed over MAX_LEDGER_AGE_SECONDS ago, assume we are still catching up
232 // and don't publish
233 static constexpr std::uint32_t kMaxLedgerAgeSeconds = 600;
234 if (age < kMaxLedgerAgeSeconds) {
235 std::optional<xrpl::Fees> fees =
236 data::synchronousAndRetryOnTimeout([&](auto yield) {
237 return backend_->fetchFees(lgrInfo.seq, yield);
238 });
239 ASSERT(fees.has_value(), "Fees must exist for ledger {}", lgrInfo.seq);
240
241 auto transactions = data::synchronousAndRetryOnTimeout([&](auto yield) {
242 return backend_->fetchAllTransactionsInLedger(lgrInfo.seq, yield);
243 });
244
245 auto const ledgerRange = backend_->fetchLedgerRange();
246 ASSERT(ledgerRange.has_value(), "Ledger range must exist");
247
248 auto const range =
249 fmt::format("{}-{}", ledgerRange->minSequence, ledgerRange->maxSequence);
250 subscriptions_->pubLedger(lgrInfo, *fees, range, transactions.size());
251
252 // order with transaction index
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);
260 });
261
262 for (auto const& txAndMeta : transactions)
263 subscriptions_->pubTransaction(txAndMeta, lgrInfo);
264
265 subscriptions_->pubBookChanges(lgrInfo, transactions);
266
267 setLastPublishTime();
268 LOG(log_.info()) << "Published ledger " << lgrInfo.seq;
269 } else {
270 LOG(log_.info()) << "Skipping publishing ledger " << lgrInfo.seq;
271 }
272 });
273
274 // we track latest publish-requested seq, not necessarily already published
275 setLastPublishedSequence(lgrInfo.seq);
276 }
277
281 std::uint32_t
282 lastPublishAgeSeconds() const override
283 {
284 return std::chrono::duration_cast<std::chrono::seconds>(
285 std::chrono::system_clock::now() - getLastPublish()
286 )
287 .count();
288 }
289
293 std::chrono::time_point<std::chrono::system_clock>
294 getLastPublish() const override
295 {
296 return std::chrono::time_point<std::chrono::system_clock>{
297 std::chrono::seconds{lastPublishSeconds_.get().value()}
298 };
299 }
300
304 std::uint32_t
305 lastCloseAgeSeconds() const override
306 {
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()
310 )
311 .count();
312 if (now < (kRippleEpochStart + closeTime))
313 return 0;
314 return now - (kRippleEpochStart + closeTime);
315 }
316
321 std::optional<uint32_t>
323 {
324 return *lastPublishedSequence_.lock();
325 }
326
333 void
334 stop() override
335 {
336 stop_ = true;
337 }
338
339private:
340 void
341 setLastClose(std::chrono::time_point<xrpl::NetClock> lastCloseTime)
342 {
343 auto closeTime = lastCloseTime_.lock<std::scoped_lock>();
344 *closeTime = lastCloseTime;
345 }
346
347 void
348 setLastPublishTime()
349 {
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);
354 }
355
356 void
357 setLastPublishedSequence(std::optional<uint32_t> lastPublishedSequence)
358 {
359 auto lastPublishSeq = lastPublishedSequence_.lock();
360 *lastPublishSeq = lastPublishedSequence;
361 }
362};
363
364} // namespace etl::impl
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