Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
CacheLoader.hpp
1#pragma once
2
3#include "data/BackendInterface.hpp"
4#include "data/LedgerCacheInterface.hpp"
5#include "data/LedgerCacheLoadingState.hpp"
6#include "data/Types.hpp"
7#include "etl/CacheLoaderInterface.hpp"
8#include "etl/CacheLoaderSettings.hpp"
9#include "etl/impl/CacheLoader.hpp"
10#include "etl/impl/CursorFromAccountProvider.hpp"
11#include "etl/impl/CursorFromDiffProvider.hpp"
12#include "etl/impl/CursorFromFixDiffNumProvider.hpp"
13#include "util/Assert.hpp"
14#include "util/Profiler.hpp"
15#include "util/async/context/BasicExecutionContext.hpp"
16#include "util/config/ConfigDefinition.hpp"
17#include "util/log/Logger.hpp"
18
19#include <algorithm>
20#include <cstdint>
21#include <functional>
22#include <memory>
23#include <utility>
24
25namespace etl {
26
34template <typename ExecutionContextType = util::async::CoroExecutionContext>
37
38 util::Logger log_{"ETL"};
39 std::shared_ptr<BackendInterface> backend_;
40 std::reference_wrapper<data::LedgerCacheInterface> cache_;
41
42 CacheLoaderSettings settings_;
43 std::unique_ptr<data::LedgerCacheLoadingStateInterface const> cacheLoadingState_;
44 ExecutionContextType ctx_;
45 std::unique_ptr<CacheLoaderType> loader_;
46
47public:
58 std::shared_ptr<BackendInterface> backend,
60 std::unique_ptr<data::LedgerCacheLoadingStateInterface const> cacheLoadingState
61 )
62 : backend_{std::move(backend)}
63 , cache_{cache}
64 , settings_{makeCacheLoaderSettings(config)}
65 , cacheLoadingState_(std::move(cacheLoadingState))
66 , ctx_{settings_.numThreads}
67 {
68 }
69
78 void
79 load(uint32_t const seq) override
80 {
81 ASSERT(not cache_.get().isFull(), "Cache must not be full. seq = {}", seq);
82
83 if (settings_.isDisabled()) {
84 cache_.get().setDisabled();
85 LOG(log_.warn()) << "Cache is disabled. Not loading";
86 return;
87 }
88
89 if (loadCacheFromFile()) {
90 // Cache file may contain outdated data, so fetch whatever left up to seq from DB
91 updateCacheToSeq(seq);
92 cache_.get().setFull();
93 return;
94 }
95
96 LOG(log_.info()) << "Waiting for ledger cache loading to become allowed";
97 cacheLoadingState_->waitForLoadingAllowed();
98 LOG(log_.info()) << "Ledger cache loading is now allowed. Start loading...";
99 cache_.get().startLoading();
100
101 std::shared_ptr<impl::BaseCursorProvider> provider;
102 if (settings_.numCacheCursorsFromDiff != 0) {
103 LOG(log_.info()) << "Loading cache with cursor from num_cursors_from_diff="
104 << settings_.numCacheCursorsFromDiff;
105 provider = std::make_shared<impl::CursorFromDiffProvider>(
106 backend_, settings_.numCacheCursorsFromDiff
107 );
108 } else if (settings_.numCacheCursorsFromAccount != 0) {
109 LOG(log_.info()) << "Loading cache with cursor from num_cursors_from_account="
110 << settings_.numCacheCursorsFromAccount;
111 provider = std::make_shared<impl::CursorFromAccountProvider>(
112 backend_, settings_.numCacheCursorsFromAccount, settings_.cachePageFetchSize
113 );
114 } else {
115 LOG(log_.info()) << "Loading cache with cursor from num_diffs="
116 << settings_.numCacheDiffs;
117 provider = std::make_shared<impl::CursorFromFixDiffNumProvider>(
118 backend_, settings_.numCacheDiffs
119 );
120 }
121
122 loader_ = std::make_unique<CacheLoaderType>(
123 ctx_,
124 backend_,
125 cache_,
126 seq,
127 settings_.numCacheMarkers,
128 settings_.cachePageFetchSize,
129 provider->getCursors(seq)
130 );
131
132 if (settings_.isSync()) {
133 loader_->wait();
134 ASSERT(cache_.get().isFull(), "Cache must be full after sync load. seq = {}", seq);
135 }
136 }
137
141 void
142 stop() noexcept override
143 {
144 if (loader_ != nullptr)
145 loader_->stop();
146 }
147
151 void
152 wait() noexcept override
153 {
154 if (loader_ != nullptr)
155 loader_->wait();
156 }
157
158private:
159 bool
160 loadCacheFromFile()
161 {
162 if (not settings_.cacheFileSettings.has_value()) {
163 return false;
164 }
165 LOG(log_.info()) << "Loading ledger cache from " << settings_.cacheFileSettings->path;
166 auto const minLatestSequence =
167 backend_->fetchLedgerRange()
168 .transform([this](data::LedgerRange const& range) {
169 return std::max(
170 range.maxSequence - settings_.cacheFileSettings->maxAge, range.minSequence
171 );
172 })
173 .value_or(0);
174
175 auto const [success, durationMs] = util::timed([&] {
176 return cache_.get().loadFromFile(settings_.cacheFileSettings->path, minLatestSequence);
177 });
178
179 if (not success.has_value()) {
180 LOG(log_.warn()) << "Error loading cache from file: " << success.error();
181 return false;
182 }
183
184 LOG(log_.info()) << "Loaded cache from file in " << durationMs
185 << " ms. Latest sequence: " << cache_.get().latestLedgerSequence();
186 return true;
187 }
188
189 void
190 updateCacheToSeq(uint32_t const seq)
191 {
192 while (cache_.get().latestLedgerSequence() < seq) {
193 auto const seqToLoad = cache_.get().latestLedgerSequence() + 1;
194 LOG(log_.info()) << "Fetching ledger " << seqToLoad
195 << "from DB after loading cache from file";
196 auto const diff = data::synchronousAndRetryOnTimeout([this, seqToLoad](auto yield) {
197 return backend_->fetchLedgerDiff(seqToLoad, yield);
198 });
199 cache_.get().update(diff, seqToLoad);
200 LOG(log_.info()) << "Updated cache to " << seqToLoad;
201 }
202 }
203};
204
205} // namespace etl
Cache for an entire ledger.
Definition LedgerCacheInterface.hpp:21
void load(uint32_t const seq) override
Load the cache for the given sequence number.
Definition CacheLoader.hpp:79
void stop() noexcept override
Requests the loader to stop asap.
Definition CacheLoader.hpp:142
void wait() noexcept override
Waits for the loader to finish background work.
Definition CacheLoader.hpp:152
CacheLoader(util::config::ClioConfigDefinition const &config, std::shared_ptr< BackendInterface > backend, data::LedgerCacheInterface &cache, std::unique_ptr< data::LedgerCacheLoadingStateInterface const > cacheLoadingState)
Construct a new Cache Loader object.
Definition CacheLoader.hpp:56
Definition CacheLoader.hpp:36
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
All the config data will be stored and extracted from this class.
Definition ConfigDefinition.hpp:31
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
This namespace contains everything to do with the ETL and ETL sources.
Definition AmendmentBlockHandlerInterface.hpp:6
CacheLoaderSettings makeCacheLoaderSettings(util::config::ClioConfigDefinition const &config)
Create a CacheLoaderSettings object from a Config object.
Definition CacheLoaderSettings.cpp:33
auto timed(FnType &&func)
Profiler function to measure the time a function execution consumes.
Definition Profiler.hpp:21
Stores a range of sequences as a min and max pair.
Definition Types.hpp:246
std::uint32_t minSequence
Lowest ledger sequence in the range (inclusive).
Definition Types.hpp:247
std::uint32_t maxSequence
Highest ledger sequence in the range (inclusive).
Definition Types.hpp:248
An interface for the Cache Loader.
Definition CacheLoaderInterface.hpp:10
Settings for the cache loader.
Definition CacheLoaderSettings.hpp:15
std::optional< CacheFileSettings > cacheFileSettings
optional settings for cache file operations
Definition CacheLoaderSettings.hpp:46