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<ripple::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
79public:
85 std::shared_ptr<BackendInterface> backend,
86 std::shared_ptr<feed::SubscriptionManagerInterface> subscriptions,
87 SystemState const& state
88 )
89 : publishStrand_{ctx.makeStrand()}
90 , backend_{std::move(backend)}
91 , subscriptions_{std::move(subscriptions)}
92 , state_{std::cref(state)}
93 {
94 }
95
105 bool
107 uint32_t ledgerSequence,
108 std::optional<uint32_t> maxAttempts,
109 std::chrono::steady_clock::duration attemptsDelay = std::chrono::seconds{1}
110 ) override
111 {
112 LOG(log_.info()) << "Attempting to publish ledger = " << ledgerSequence;
113 size_t numAttempts = 0;
114 while (not stop_) {
115 auto range = backend_->hardFetchLedgerRangeNoThrow();
116
117 if (!range || range->maxSequence < ledgerSequence) {
118 ++numAttempts;
119 LOG(log_.debug()) << "Trying to publish. Could not find ledger with sequence = "
120 << ledgerSequence;
121
122 // We try maxAttempts times to publish the ledger, waiting one second in between
123 // each attempt.
124 if (maxAttempts && numAttempts >= maxAttempts) {
125 LOG(log_.debug())
126 << "Failed to publish ledger after " << numAttempts << " attempts.";
127 return false;
128 }
129 std::this_thread::sleep_for(attemptsDelay);
130 continue;
131 }
132
133 auto lgr = data::synchronousAndRetryOnTimeout([&](auto yield) {
134 return backend_->fetchLedgerBySequence(ledgerSequence, yield);
135 });
136
137 ASSERT(
138 lgr.has_value(),
139 "Ledger must exist in database. Ledger sequence = {}",
140 ledgerSequence
141 );
142 if (!lgr)
143 return false;
144 publish(*lgr);
145
146 return true;
147 }
148 return false;
149 }
150
159 void
160 publish(ripple::LedgerHeader const& lgrInfo)
161 {
162 publishStrand_.submit([this, lgrInfo = lgrInfo] {
163 LOG(log_.info()) << "Publishing ledger " << std::to_string(lgrInfo.seq);
164
165 setLastClose(lgrInfo.closeTime);
166 auto age = lastCloseAgeSeconds();
167
168 // if the ledger closed over MAX_LEDGER_AGE_SECONDS ago, assume we are still catching up
169 // and don't publish
170 static constexpr std::uint32_t kMaxLedgerAgeSeconds = 600;
171 if (age < kMaxLedgerAgeSeconds) {
172 std::optional<ripple::Fees> fees =
173 data::synchronousAndRetryOnTimeout([&](auto yield) {
174 return backend_->fetchFees(lgrInfo.seq, yield);
175 });
176 ASSERT(fees.has_value(), "Fees must exist for ledger {}", lgrInfo.seq);
177
178 auto transactions = data::synchronousAndRetryOnTimeout([&](auto yield) {
179 return backend_->fetchAllTransactionsInLedger(lgrInfo.seq, yield);
180 });
181
182 auto const ledgerRange = backend_->fetchLedgerRange();
183 ASSERT(ledgerRange.has_value(), "Ledger range must exist");
184
185 auto const range =
186 fmt::format("{}-{}", ledgerRange->minSequence, ledgerRange->maxSequence);
187 subscriptions_->pubLedger(lgrInfo, *fees, range, transactions.size());
188
189 // order with transaction index
190 std::ranges::sort(transactions, [](auto const& t1, auto const& t2) {
191 ripple::SerialIter iter1{t1.metadata.data(), t1.metadata.size()};
192 ripple::STObject const object1(iter1, ripple::sfMetadata);
193 ripple::SerialIter iter2{t2.metadata.data(), t2.metadata.size()};
194 ripple::STObject const object2(iter2, ripple::sfMetadata);
195 return object1.getFieldU32(ripple::sfTransactionIndex) <
196 object2.getFieldU32(ripple::sfTransactionIndex);
197 });
198
199 for (auto const& txAndMeta : transactions)
200 subscriptions_->pubTransaction(txAndMeta, lgrInfo);
201
202 subscriptions_->pubBookChanges(lgrInfo, transactions);
203
204 setLastPublishTime();
205 LOG(log_.info()) << "Published ledger " << lgrInfo.seq;
206 } else {
207 LOG(log_.info()) << "Skipping publishing ledger " << lgrInfo.seq;
208 }
209 });
210
211 // we track latest publish-requested seq, not necessarily already published
212 setLastPublishedSequence(lgrInfo.seq);
213 }
214
218 std::uint32_t
219 lastPublishAgeSeconds() const override
220 {
221 return std::chrono::duration_cast<std::chrono::seconds>(
222 std::chrono::system_clock::now() - getLastPublish()
223 )
224 .count();
225 }
226
230 std::chrono::time_point<std::chrono::system_clock>
231 getLastPublish() const override
232 {
233 return std::chrono::time_point<std::chrono::system_clock>{
234 std::chrono::seconds{lastPublishSeconds_.get().value()}
235 };
236 }
237
241 std::uint32_t
242 lastCloseAgeSeconds() const override
243 {
244 auto closeTime = lastCloseTime_.lock()->time_since_epoch().count();
245 auto now = std::chrono::duration_cast<std::chrono::seconds>(
246 std::chrono::system_clock::now().time_since_epoch()
247 )
248 .count();
249 if (now < (kRippleEpochStart + closeTime))
250 return 0;
251 return now - (kRippleEpochStart + closeTime);
252 }
253
258 std::optional<uint32_t>
260 {
261 return *lastPublishedSequence_.lock();
262 }
263
270 void
272 {
273 stop_ = true;
274 }
275
276private:
277 void
278 setLastClose(std::chrono::time_point<ripple::NetClock> lastCloseTime)
279 {
280 auto closeTime = lastCloseTime_.lock<std::scoped_lock>();
281 *closeTime = lastCloseTime;
282 }
283
284 void
285 setLastPublishTime()
286 {
287 using namespace std::chrono;
288 auto const nowSeconds =
289 duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
290 lastPublishSeconds_.get().set(nowSeconds);
291 }
292
293 void
294 setLastPublishedSequence(std::optional<uint32_t> lastPublishedSequence)
295 {
296 auto lastPublishSeq = lastPublishedSequence_.lock();
297 *lastPublishSeq = lastPublishedSequence;
298 }
299};
300
301} // namespace etl::impl
static constexpr std::uint32_t kRippleEpochStart
The ripple epoch start timestamp. Midnight on 1st January 2000.
Definition DBHelpers.hpp:273
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:231
LedgerPublisher(util::async::AnyExecutionContext ctx, std::shared_ptr< BackendInterface > backend, std::shared_ptr< feed::SubscriptionManagerInterface > subscriptions, SystemState const &state)
Create an instance of the publisher.
Definition LedgerPublisher.hpp:83
void publish(ripple::LedgerHeader const &lgrInfo)
Publish the passed ledger asynchronously.
Definition LedgerPublisher.hpp:160
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:259
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:106
void stop()
Stops publishing.
Definition LedgerPublisher.hpp:271
std::uint32_t lastCloseAgeSeconds() const override
Get time passed since last ledger close, in seconds.
Definition LedgerPublisher.hpp:242
std::uint32_t lastPublishAgeSeconds() const override
Get time passed since last publish, in seconds.
Definition LedgerPublisher.hpp:219
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:78
Pump debug(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::DBG severity.
Definition Logger.cpp:497
Pump info(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:502
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:22
A type-erased execution context.
Definition AnyStrand.hpp:21
auto synchronousAndRetryOnTimeout(FnType &&func)
Synchronously execute the given function object and retry until no DatabaseTimeout is thrown.
Definition BackendInterface.hpp:117
The interface of a scheduler for the extraction process.
Definition LedgerPublisherInterface.hpp:12
Represents the state of the ETL subsystem.
Definition SystemState.hpp:20