ClpMap.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9#ifndef SQUID__SRC_BASE_CLPMAP_H
10#define SQUID__SRC_BASE_CLPMAP_H
11
13#include "SquidMath.h"
14#include "time/gadgets.h"
15
16#include <functional>
17#include <limits>
18#include <list>
19#include <optional>
20#include <unordered_map>
21
22template<class Value>
23uint64_t
24DefaultMemoryUsage(const Value &e)
25{
26 return sizeof(e);
27}
28
39template <class Key, class Value, uint64_t MemoryUsedBy(const Value &) = DefaultMemoryUsage>
40class ClpMap
41{
42public:
43 using key_type = Key;
44 using mapped_type = Value;
45
47 using Ttl = int;
48
49 explicit ClpMap(const uint64_t capacity) { setMemLimit(capacity); }
50 ClpMap(uint64_t capacity, Ttl defaultTtl);
51 ~ClpMap() = default;
52
53 // copying disabled because it may be expensive for large maps
54 // moving (implicitly) disabled for simplicity sake
55 ClpMap(const ClpMap &) = delete;
56 ClpMap &operator =(const ClpMap &) = delete;
57
62 const Value *get(const Key &);
63
67 bool add(const Key &, const Value &, Ttl);
68
70 bool add(const Key &key, const Value &v) { return add(key, v, defaultTtl_); }
71
73 void del(const Key &);
74
76 void setMemLimit(uint64_t newLimit);
77
79 uint64_t memLimit() const { return memLimit_; }
80
82 uint64_t freeMem() const { return memLimit() - memoryUsed(); }
83
85 uint64_t memoryUsed() const { return memUsed_; }
86
88 size_t entries() const { return entries_.size(); }
89
90private:
92 class Entry
93 {
94 public:
95 Entry(const Key &, const Value &, const Ttl);
96
98 bool expired() const { return expires < squid_curtime; }
99
100 public:
101 Key key;
102 Value value;
103 time_t expires = 0;
104 uint64_t memCounted = 0;
105 };
106
108 using Entries = std::list<Entry, PoolingAllocator<Entry> >;
109 using EntriesIterator = typename Entries::iterator;
110
111 using IndexItem = std::pair<const Key, EntriesIterator>;
113 using Index = std::unordered_map<Key, EntriesIterator, std::hash<Key>, std::equal_to<Key>, PoolingAllocator<IndexItem> >;
114 using IndexIterator = typename Index::iterator;
115
116 static std::optional<uint64_t> MemoryCountedFor(const Key &, const Value &);
117
118 void trim(uint64_t wantSpace);
119 void erase(const IndexIterator &);
120 IndexIterator find(const Key &);
121
124
127
130
132 uint64_t memLimit_ = 0;
133
135 uint64_t memUsed_ = 0;
136};
137
138template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
139ClpMap<Key, Value, MemoryUsedBy>::ClpMap(const uint64_t capacity, const Ttl defaultTtl):
140 defaultTtl_(defaultTtl)
141{
142 assert(defaultTtl >= 0);
143 setMemLimit(capacity);
144}
145
146template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
147void
149{
150 if (memUsed_ > newLimit)
151 trim(memLimit_ - newLimit);
152 memLimit_ = newLimit;
153}
154
156template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
159{
160 const auto i = index_.find(key);
161 if (i == index_.end())
162 return i;
163
164 const auto entryPosition = i->second;
165 if (!entryPosition->expired()) {
166 if (entryPosition != entries_.begin())
167 entries_.splice(entries_.begin(), entries_, entryPosition);
168 return i;
169 }
170 // else fall through to cleanup
171
172 erase(i);
173 return index_.end();
174}
175
176template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
177const Value *
179{
180 const auto i = find(key);
181 if (i != index_.end()) {
182 const auto &entry = *(i->second);
183 return &entry.value;
184 }
185 return nullptr;
186}
187
188template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
189std::optional<uint64_t>
191{
192 // Both storage and index store keys, but we count keySz once, assuming that
193 // copying a Key does not consume more memory. This assumption holds for
194 // Key=SBuf, but, ideally, we should be outsourcing this decision to another
195 // configurable function, storing each key once, or hard-coding Key=SBuf.
196 const auto keySz = k.length();
197
198 // approximate calculation (e.g., containers store wrappers not value_types)
199 return NaturalSum<uint64_t>(
200 keySz,
201 // storage
202 sizeof(typename Entries::value_type),
203 MemoryUsedBy(v),
204 // index
205 sizeof(typename Index::value_type));
206}
207
208template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
209bool
210ClpMap<Key, Value, MemoryUsedBy>::add(const Key &key, const Value &v, const Ttl ttl)
211{
212 // optimization: avoid del() search, MemoryCountedFor() in always-empty maps
213 if (memLimit() == 0)
214 return false;
215
216 del(key);
217
218 if (ttl < 0)
219 return false; // already expired; will never be returned by get()
220
221 const auto memoryRequirements = MemoryCountedFor(key, v);
222 if (!memoryRequirements)
223 return false; // cannot even compute memory requirements
224
225 const auto wantSpace = memoryRequirements.value();
226 if (wantSpace > memLimit() || wantSpace == 0) // 0 is 64-bit integer overflow
227 return false; // will never fit
228 trim(wantSpace);
229
230 auto &addedEntry = entries_.emplace_front(key, v, ttl);
231 index_.emplace(key, entries_.begin());
232
233 addedEntry.memCounted = wantSpace;
234 memUsed_ += wantSpace;
235 assert(memUsed_ >= wantSpace); // no overflows
236 return true;
237}
238
240template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
241void
243{
244 assert(i != index_.end());
245 const auto entryPosition = i->second;
246
247 assert(entryPosition != entries_.end());
248 const auto sz = entryPosition->memCounted;
249 assert(memUsed_ >= sz);
250 memUsed_ -= sz;
251
252 index_.erase(i); // destroys a "pointer" to our Entry
253 entries_.erase(entryPosition); // destroys our Entry
254}
255
256template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
257void
259{
260 const auto i = find(key);
261 if (i != index_.end())
262 erase(i);
263}
264
266template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
267void
269{
270 assert(wantSpace <= memLimit()); // no infinite loops and in-vain trimming
271 while (freeMem() < wantSpace) {
272 assert(!entries_.empty());
273 // TODO: Purge expired entries first. They are useless, but their
274 // presence may lead to purging potentially useful fresh entries here.
275 del(entries_.rbegin()->key);
276 }
277}
278
279template <class Key, class Value, uint64_t MemoryUsedBy(const Value &)>
280ClpMap<Key, Value, MemoryUsedBy>::Entry::Entry(const Key &aKey, const Value &v, const Ttl ttl) :
281 key(aKey),
282 value(v),
283 expires(0) // reset below
284{
286}
287
288#endif /* SQUID__SRC_BASE_CLPMAP_H */
289
uint64_t DefaultMemoryUsage(const Value &e)
Definition: ClpMap.h:24
static char const * trim(char const *s)
Definition: Expression.cc:674
time_t squid_curtime
Definition: stub_libtime.cc:20
S SetToNaturalSumOrMax(S &var, const Args... args)
Definition: SquidMath.h:176
#define assert(EX)
Definition: assert.h:17
the keeper of cache entry Key, Value, and caching-related entry metadata
Definition: ClpMap.h:93
bool expired() const
whether the entry is stale
Definition: ClpMap.h:98
Value value
cached value provided by the map user
Definition: ClpMap.h:102
time_t expires
get() stops returning the entry after this time
Definition: ClpMap.h:103
uint64_t memCounted
memory accounted for this entry in our ClpMap
Definition: ClpMap.h:104
Key key
the entry search key; see ClpMap::get()
Definition: ClpMap.h:101
Entry(const Key &, const Value &, const Ttl)
Definition: ClpMap.h:280
Definition: ClpMap.h:41
const Value * get(const Key &)
Definition: ClpMap.h:178
std::pair< const Key, EntriesIterator > IndexItem
Definition: ClpMap.h:111
ClpMap(const ClpMap &)=delete
ClpMap(const uint64_t capacity)
Definition: ClpMap.h:49
void del(const Key &)
Remove the corresponding entry (if any)
Definition: ClpMap.h:258
void trim(uint64_t wantSpace)
purges entries to make free memory large enough to fit wantSpace bytes
Definition: ClpMap.h:268
typename Entries::iterator EntriesIterator
Definition: ClpMap.h:109
uint64_t memLimit() const
The memory capacity for the map.
Definition: ClpMap.h:79
uint64_t freeMem() const
The free space of the map.
Definition: ClpMap.h:82
ClpMap & operator=(const ClpMap &)=delete
Ttl defaultTtl_
entry TTL to use if none provided to add()
Definition: ClpMap.h:129
typename Index::iterator IndexIterator
Definition: ClpMap.h:114
uint64_t memUsed_
the total amount of memory we currently use for all cached entries
Definition: ClpMap.h:135
void erase(const IndexIterator &)
removes the cached entry (identified by its index) from the map
Definition: ClpMap.h:242
Index index_
entries_ positions indexed by the entry key
Definition: ClpMap.h:126
static std::optional< uint64_t > MemoryCountedFor(const Key &, const Value &)
Definition: ClpMap.h:190
uint64_t memLimit_
the maximum memory we are allowed to use for all cached entries
Definition: ClpMap.h:132
IndexIterator find(const Key &)
Definition: ClpMap.h:158
std::unordered_map< Key, EntriesIterator, std::hash< Key >, std::equal_to< Key >, PoolingAllocator< IndexItem > > Index
key:entry_position mapping for fast entry lookups by key
Definition: ClpMap.h:113
Key key_type
Definition: ClpMap.h:43
int Ttl
maximum desired entry caching duration (a.k.a. TTL), in seconds
Definition: ClpMap.h:47
void setMemLimit(uint64_t newLimit)
Reset the memory capacity for this map, purging if needed.
Definition: ClpMap.h:148
size_t entries() const
The number of currently stored entries, including expired ones.
Definition: ClpMap.h:88
~ClpMap()=default
bool add(const Key &, const Value &, Ttl)
Definition: ClpMap.h:210
Value mapped_type
Definition: ClpMap.h:44
uint64_t memoryUsed() const
The current (approximate) memory usage of the map.
Definition: ClpMap.h:85
Entries entries_
cached entries, including expired ones, in LRU order
Definition: ClpMap.h:123
std::list< Entry, PoolingAllocator< Entry > > Entries
Entries in LRU order.
Definition: ClpMap.h:108
bool add(const Key &key, const Value &v)
Copy the given value into the map (with the given key and default TTL)
Definition: ClpMap.h:70
STL Allocator that uses Squid memory pools for memory management.
A const & max(A const &lhs, A const &rhs)
int unsigned int
Definition: stub_fd.cc:19
static StoreEntry * addedEntry(Store::Disk *aStore, String name, String, String)

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors