1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
|
#pragma once
#include <Common/ICachePolicy.h>
#include <limits>
#include <unordered_map>
namespace DB
{
class PerUserTTLCachePolicyUserQuota : public ICachePolicyUserQuota
{
public:
void setQuotaForUser(const String & user_name, size_t max_size_in_bytes, size_t max_entries) override
{
quotas[user_name] = {max_size_in_bytes, max_entries};
}
void increaseActual(const String & user_name, size_t entry_size_in_bytes) override
{
auto & actual_for_user = actual[user_name];
actual_for_user.size_in_bytes += entry_size_in_bytes;
actual_for_user.num_items += 1;
}
void decreaseActual(const String & user_name, size_t entry_size_in_bytes) override
{
chassert(actual.contains(user_name));
chassert(actual[user_name].size_in_bytes >= entry_size_in_bytes);
actual[user_name].size_in_bytes -= entry_size_in_bytes;
chassert(actual[user_name].num_items >= 1);
actual[user_name].num_items -= 1;
}
bool approveWrite(const String & user_name, size_t entry_size_in_bytes) const override
{
auto it_actual = actual.find(user_name);
Resources actual_for_user{.size_in_bytes = 0, .num_items = 0}; /// assume zero actual resource consumption is user isn't found
if (it_actual != actual.end())
actual_for_user = it_actual->second;
auto it_quota = quotas.find(user_name);
Resources quota_for_user{.size_in_bytes = std::numeric_limits<size_t>::max(), .num_items = std::numeric_limits<size_t>::max()}; /// assume no threshold if no quota is found
if (it_quota != quotas.end())
quota_for_user = it_quota->second;
/// Special case: A quota configured as 0 means no threshold
if (quota_for_user.size_in_bytes == 0)
quota_for_user.size_in_bytes = std::numeric_limits<UInt64>::max();
if (quota_for_user.num_items == 0)
quota_for_user.num_items = std::numeric_limits<UInt64>::max();
/// Check size quota
if (actual_for_user.size_in_bytes + entry_size_in_bytes >= quota_for_user.size_in_bytes)
return false;
/// Check items quota
if (quota_for_user.num_items + 1 >= quota_for_user.num_items)
return false;
return true;
}
struct Resources
{
size_t size_in_bytes = 0;
size_t num_items = 0;
};
/// user name --> cache size quota (in bytes) / number of items quota
std::map<String, Resources> quotas;
/// user name --> actual cache usage (in bytes) / number of items
std::map<String, Resources> actual;
};
/// TTLCachePolicy evicts entries for which IsStaleFunction returns true.
/// The cache size (in bytes and number of entries) can be changed at runtime. It is expected to set both sizes explicitly after construction.
template <typename Key, typename Mapped, typename HashFunction, typename WeightFunction, typename IsStaleFunction>
class TTLCachePolicy : public ICachePolicy<Key, Mapped, HashFunction, WeightFunction>
{
public:
using Base = ICachePolicy<Key, Mapped, HashFunction, WeightFunction>;
using typename Base::MappedPtr;
using typename Base::KeyMapped;
using typename Base::OnWeightLossFunction;
explicit TTLCachePolicy(CachePolicyUserQuotaPtr quotas_)
: Base(std::move(quotas_))
, max_size_in_bytes(0)
, max_count(0)
{
}
size_t sizeInBytes() const override
{
return size_in_bytes;
}
size_t count() const override
{
return cache.size();
}
size_t maxSizeInBytes() const override
{
return max_size_in_bytes;
}
void setMaxCount(size_t max_count_) override
{
/// lazy behavior: the cache only shrinks upon the next insert
max_count = max_count_;
}
void setMaxSizeInBytes(size_t max_size_in_bytes_) override
{
/// lazy behavior: the cache only shrinks upon the next insert
max_size_in_bytes = max_size_in_bytes_;
}
void clear() override
{
cache.clear();
}
void remove(const Key & key) override
{
auto it = cache.find(key);
if (it == cache.end())
return;
size_t sz = weight_function(*it->second);
Base::user_quotas->decreaseActual(it->first.user_name, sz);
cache.erase(it);
size_in_bytes -= sz;
}
MappedPtr get(const Key & key) override
{
auto it = cache.find(key);
if (it == cache.end())
return {};
return it->second;
}
std::optional<KeyMapped> getWithKey(const Key & key) override
{
auto it = cache.find(key);
if (it == cache.end())
return std::nullopt;
return std::make_optional<KeyMapped>({it->first, it->second});
}
/// Evicts on a best-effort basis. If there are too many non-stale entries, the new entry may not be cached at all!
void set(const Key & key, const MappedPtr & mapped) override
{
chassert(mapped.get());
const size_t entry_size_in_bytes = weight_function(*mapped);
/// Checks against per-cache limits
auto sufficient_space_in_cache = [&]()
{
return (size_in_bytes + entry_size_in_bytes <= max_size_in_bytes) && (cache.size() + 1 <= max_count);
};
/// Checks against per-user limits
auto sufficient_space_in_cache_for_user = [&]()
{
return Base::user_quotas->approveWrite(key.user_name, entry_size_in_bytes);
};
if (!sufficient_space_in_cache() || !sufficient_space_in_cache_for_user())
{
/// Remove stale entries
for (auto it = cache.begin(); it != cache.end();)
if (is_stale_function(it->first))
{
size_t sz = weight_function(*it->second);
Base::user_quotas->decreaseActual(it->first.user_name, sz);
it = cache.erase(it);
size_in_bytes -= sz;
}
else
++it;
}
if (sufficient_space_in_cache() && sufficient_space_in_cache_for_user())
{
/// Insert or replace key
if (auto it = cache.find(key); it != cache.end())
{
size_t sz = weight_function(*it->second);
Base::user_quotas->decreaseActual(it->first.user_name, sz);
cache.erase(it); // stupid bug: (*) doesn't replace existing entries (likely due to custom hash function), need to erase explicitly
size_in_bytes -= sz;
}
cache[key] = std::move(mapped); // (*)
size_in_bytes += entry_size_in_bytes;
Base::user_quotas->increaseActual(key.user_name, entry_size_in_bytes);
}
}
std::vector<KeyMapped> dump() const override
{
std::vector<KeyMapped> res;
for (const auto & [key, mapped] : cache)
res.push_back({key, mapped});
return res;
}
private:
using Cache = std::unordered_map<Key, MappedPtr, HashFunction>;
Cache cache;
/// TODO To speed up removal of stale entries, we could also add another container sorted on expiry times which maps keys to iterators
/// into the cache. To insert an entry, add it to the cache + add the iterator to the sorted container. To remove stale entries, do a
/// binary search on the sorted container and erase all left of the found key.
size_t size_in_bytes = 0;
size_t max_size_in_bytes;
size_t max_count;
WeightFunction weight_function;
IsStaleFunction is_stale_function;
/// TODO support OnWeightLossFunction callback
};
}
|