xrpld
Loading...
Searching...
No Matches
CachedView.cpp
1#include <xrpl/ledger/CachedView.h>
2
3#include <xrpl/basics/CountedObject.h>
4#include <xrpl/basics/TaggedCache.ipp> // IWYU pragma: keep
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/protocol/Keylet.h>
8#include <xrpl/protocol/STLedgerEntry.h>
9
10#include <mutex>
11#include <optional>
12
13namespace xrpl::detail {
14
15bool
17{
18 return read(k) != nullptr;
19}
20
23{
24 static CountedObjects::Counter kHits{"CachedView::hit"};
25 static CountedObjects::Counter kHitsExpired{"CachedView::hitExpired"};
26 static CountedObjects::Counter kMisses{"CachedView::miss"};
27 bool cacheHit = false;
28 bool baseRead = false;
29
30 auto const digest = [&]() -> std::optional<uint256> {
31 {
32 std::scoped_lock const lock(mutex_);
33 auto const iter = map_.find(k.key);
34 if (iter != map_.end())
35 {
36 cacheHit = true;
37 return iter->second;
38 }
39 }
40 return base_.digest(k.key);
41 }();
42 if (!digest)
43 return nullptr;
44 auto sle = cache_.fetch(*digest, [&]() {
45 baseRead = true;
46 return base_.read(k);
47 });
48 // If the sle is null, then a failure must have occurred in base_.read()
49 XRPL_ASSERT(sle || baseRead, "xrpl::CachedView::read : null SLE result from base");
50 if (cacheHit && baseRead)
51 {
52 kHitsExpired.increment();
53 }
54 else if (cacheHit)
55 {
56 kHits.increment();
57 }
58 else
59 {
60 kMisses.increment();
61 }
62
63 if (!cacheHit)
64 {
65 // Avoid acquiring this lock unless necessary. It is only necessary if
66 // the key was not found in the map_. The lock is needed to add the key
67 // and digest.
68 std::scoped_lock const lock(mutex_);
69 map_.emplace(k.key, *digest);
70 }
71 if (!sle || !k.check(*sle))
72 return nullptr;
73 return sle;
74}
75
76} // namespace xrpl::detail
Implementation for CountedObject.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
std::shared_ptr< STLedgerEntry const > const_pointer
SharedPointerType fetch(key_type const &key)
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
std::optional< digest_type > digest(key_type const &key) const override
Return the digest associated with the key.
Definition CachedView.h:119
DigestAwareReadView const & base_
Definition CachedView.h:17
std::unordered_map< key_type, uint256, HardenedHash<> > map_
Definition CachedView.h:20
bool exists(Keylet const &k) const override
Determine if a state item exists.
T lock(T... args)
static Hasher::result_type digest(void const *data, std::size_t size) noexcept
Definition tokens.cpp:139
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:19
uint256 key
Definition Keylet.h:20
bool check(STLedgerEntry const &) const
Returns true if the SLE matches the type.
Definition Keylet.cpp:10