userver
C++ Async Framework
Toggle main menu visibility
Loading...
Searching...
No Matches
expirable_lru_cache.hpp
Go to the documentation of this file.
1
#pragma once
2
5
6
#include <atomic>
7
#include <chrono>
8
#include <optional>
9
10
#include <
userver/cache/lru_cache_config.hpp
>
11
#include <
userver/cache/lru_cache_statistics.hpp
>
12
#include <
userver/cache/nway_lru_cache.hpp
>
13
#include <
userver/dump/common.hpp
>
14
#include <
userver/dump/dumper.hpp
>
15
#include <
userver/engine/async.hpp
>
16
#include <
userver/utils/datetime.hpp
>
17
#include <userver/utils/impl/cached_time.hpp>
18
#include <userver/utils/impl/wait_token_storage.hpp>
19
#include <
userver/utils/statistics/writer.hpp
>
20
21
USERVER_NAMESPACE_BEGIN
22
23
namespace
cache
{
24
25
namespace
impl {
26
27
template
<
typename
Value>
28
struct
ExpirableValue final {
29
Value value;
30
std::chrono::steady_clock::time_point update_time;
31
};
32
33
template
<
typename
Value>
34
void
Write(dump::Writer& writer,
const
impl::ExpirableValue<Value>& value) {
35
const
auto
[now, steady_now] = utils::impl::GetGlobalTime();
36
writer.
Write
(value.value);
37
writer.
Write
(value.update_time - steady_now + now);
38
}
39
40
template
<
typename
Value>
41
impl::ExpirableValue<Value> Read(dump::Reader& reader, dump::To<impl::ExpirableValue<Value>>) {
42
const
auto
[now, steady_now] = utils::impl::GetGlobalTime();
43
// Evaluation order of arguments is guaranteed in brace-initialization.
44
return
impl::ExpirableValue<Value>{
45
.value = reader.
Read
<Value>(),
46
.update_time = reader.
Read
<std::chrono::system_clock::time_point>() - now + steady_now,
47
};
48
}
49
50
}
// namespace impl
51
58
template
<
typename
Key,
typename
Value,
typename
Hash = std::hash<Key>,
typename
Equal = std::equal_to<Key>>
59
class
ExpirableLruCache
final {
60
public
:
62
using
UpdateValueFunc
= std::function<Value(
const
Key&)>;
63
65
enum class
ReadMode
{
66
kSkipCache
,
67
kUseCache
,
68
};
69
76
ExpirableLruCache
(
size_t
ways,
size_t
way_size,
const
Hash& hash = Hash(),
const
Equal& equal = Equal());
77
80
~ExpirableLruCache
();
81
85
void
SetWaySize
(
size_t
way_size);
86
91
std::chrono::milliseconds
GetMaxLifetime
() const noexcept;
92
97
void
SetMaxLifetime
(
std
::chrono::milliseconds max_lifetime);
98
106
void
SetBackgroundUpdate
(BackgroundUpdateMode background_update);
107
119
Value
Get
(const Key& key, const
UpdateValueFunc
& update_func,
ReadMode
read_mode =
ReadMode
::
kUseCache
);
120
131
std
::optional<Value>
GetOptional
(const Key& key, const
UpdateValueFunc
& update_func);
132
138
std
::optional<Value>
GetOptionalUnexpirable
(const Key& key);
139
147
std
::optional<Value>
GetOptionalUnexpirableWithUpdate
(const Key& key, const
UpdateValueFunc
& update_func);
148
154
std
::optional<Value>
GetOptionalNoUpdate
(const Key& key);
155
162
std
::optional<impl::ExpirableValue<Value>>
GetOptionalNoUpdateWithLastUpdateTime
(const Key& key);
163
169
void
Put
(const Key& key, const Value& value);
170
176
void
Put
(const Key& key, Value&& value);
177
181
const impl::ExpirableLruCacheStatistics&
GetStatistics
() const;
182
186
size_t
GetSizeApproximate
() const;
187
189
void
Invalidate
();
190
194
void
InvalidateByKey
(const Key& key);
195
202
template <typename Predicate>
203
void
InvalidateByKeyIf
(const Key& key, Predicate pred);
204
209
void
UpdateInBackground
(const Key& key,
UpdateValueFunc
update_func);
210
216
void
Write
(
dump
::Writer& writer) const;
217
223
void
Read
(
dump
::Reader& reader);
224
229
void
SetDumper
(
std
::shared_ptr<
dump
::Dumper> dumper);
230
231
private:
232
bool
IsExpired(
std
::chrono::steady_clock::time_point update_time,
std
::chrono::steady_clock::time_point now) const;
233
234
bool
ShouldUpdate(
std
::chrono::steady_clock::time_point update_time,
std
::chrono::steady_clock::time_point now)
235
const;
236
237
cache
::
NWayLRU
<Key, impl::ExpirableValue<Value>, Hash, Equal> lru_;
238
std
::atomic<
std
::chrono::milliseconds> max_lifetime_{std::chrono::milliseconds(0)};
239
std::atomic<BackgroundUpdateMode> background_update_mode_{BackgroundUpdateMode::kDisabled};
240
impl::ExpirableLruCacheStatistics stats_;
241
utils::impl::WaitTokenStorage wait_token_storage_;
242
};
243
244
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
245
ExpirableLruCache
<
246
Key,
247
Value,
248
Hash,
249
Equal>
::ExpirableLruCache
(
size_t
ways,
size_t
way_size,
const
Hash& hash,
const
Equal& equal)
250
: lru_(ways, way_size, hash, equal)
251
{}
252
253
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
254
ExpirableLruCache<Key, Value, Hash, Equal>::~ExpirableLruCache
() {
255
wait_token_storage_.WaitForAllTokens();
256
}
257
258
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
259
void
ExpirableLruCache<Key, Value, Hash, Equal>::SetWaySize
(
size_t
way_size) {
260
lru_.UpdateWaySize(way_size);
261
}
262
263
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
264
std::chrono::milliseconds
ExpirableLruCache<Key, Value, Hash, Equal>::GetMaxLifetime
() const noexcept {
265
return
max_lifetime_.load();
266
}
267
268
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
269
void
ExpirableLruCache<Key, Value, Hash, Equal>::SetMaxLifetime
(std::chrono::milliseconds max_lifetime) {
270
max_lifetime_ = max_lifetime;
271
}
272
273
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
274
void
ExpirableLruCache<Key, Value, Hash, Equal>::SetBackgroundUpdate
(BackgroundUpdateMode background_update) {
275
background_update_mode_ = background_update;
276
}
277
278
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
279
Value
ExpirableLruCache
<
280
Key,
281
Value,
282
Hash,
283
Equal>
::Get
(
const
Key& key,
const
UpdateValueFunc
& update_func,
ReadMode
read_mode) {
284
auto
now =
utils::datetime::SteadyNow
();
285
auto
opt_old_value =
GetOptional
(key, update_func);
286
if
(opt_old_value) {
287
return
std::move(*opt_old_value);
288
}
289
290
auto
mutex = lru_.GetMutexForKey(key);
291
const
std::lock_guard lock(mutex);
292
// Test one more time - concurrent ExpirableLruCache::Get()
293
// might have put the value
294
auto
old_value = lru_.Get(key);
295
if
(old_value && !IsExpired(old_value->update_time, now)) {
296
return
std::move(old_value->value);
297
}
298
299
auto
value = update_func(key);
300
if
(read_mode ==
ReadMode::kUseCache
) {
301
lru_.Put(key, {.value = value, .update_time = now});
302
}
303
return
value;
304
}
305
306
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
307
std::optional<Value>
ExpirableLruCache
<
308
Key,
309
Value,
310
Hash,
311
Equal>
::GetOptional
(
const
Key& key,
const
UpdateValueFunc
& update_func) {
312
auto
now =
utils::datetime::SteadyNow
();
313
auto
old_value = lru_.Get(key);
314
315
if
(old_value) {
316
if
(!IsExpired(old_value->update_time, now)) {
317
impl::CacheHit(stats_);
318
319
if
(ShouldUpdate(old_value->update_time, now)) {
320
UpdateInBackground
(key, update_func);
321
}
322
323
return
std::move(old_value->value);
324
}
else
{
325
impl::CacheStale(stats_);
326
}
327
}
328
impl::CacheMiss(stats_);
329
330
return
std::nullopt;
331
}
332
333
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
334
std::optional<Value>
ExpirableLruCache<Key, Value, Hash, Equal>::GetOptionalUnexpirable
(
const
Key& key) {
335
auto
old_value = lru_.Get(key);
336
337
if
(old_value) {
338
impl::CacheHit(stats_);
339
return
old_value->value;
340
}
341
impl::CacheMiss(stats_);
342
343
return
std::nullopt;
344
}
345
346
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
347
std::optional<Value>
ExpirableLruCache
<
348
Key,
349
Value,
350
Hash,
351
Equal>
::GetOptionalUnexpirableWithUpdate
(
const
Key& key,
const
UpdateValueFunc
& update_func) {
352
auto
now =
utils::datetime::SteadyNow
();
353
auto
old_value = lru_.Get(key);
354
355
if
(old_value) {
356
impl::CacheHit(stats_);
357
358
if
(ShouldUpdate(old_value->update_time, now)) {
359
UpdateInBackground
(key, update_func);
360
}
361
362
return
old_value->value;
363
}
364
impl::CacheMiss(stats_);
365
366
return
std::nullopt;
367
}
368
369
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
370
std::optional<impl::ExpirableValue<Value>>
ExpirableLruCache
<
371
Key,
372
Value,
373
Hash,
374
Equal>
::GetOptionalNoUpdateWithLastUpdateTime
(
const
Key& key) {
375
const
auto
now =
utils::datetime::SteadyNow
();
376
const
auto
old_value = lru_.Get(key);
377
if
(old_value) {
378
if
(!IsExpired(old_value->update_time, now)) {
379
impl::CacheHit(stats_);
380
return
old_value;
381
}
else
{
382
impl::CacheStale(stats_);
383
}
384
}
385
impl::CacheMiss(stats_);
386
return
std::nullopt;
387
}
388
389
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
390
std::optional<Value>
ExpirableLruCache<Key, Value, Hash, Equal>::GetOptionalNoUpdate
(
const
Key& key) {
391
auto
value_with_update_time =
GetOptionalNoUpdateWithLastUpdateTime
(key);
392
if
(value_with_update_time.has_value()) {
393
return
value_with_update_time->value;
394
}
395
return
std::nullopt;
396
}
397
398
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
399
void
ExpirableLruCache<Key, Value, Hash, Equal>::Put
(
const
Key& key,
const
Value& value) {
400
lru_.Put(key, {.value = value, .update_time =
utils::datetime::SteadyNow
()});
401
}
402
403
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
404
void
ExpirableLruCache<Key, Value, Hash, Equal>::Put
(
const
Key& key, Value&& value) {
405
lru_.Put(key, {.value = std::move(value), .update_time =
utils::datetime::SteadyNow
()});
406
}
407
408
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
409
const
impl::ExpirableLruCacheStatistics&
ExpirableLruCache<Key, Value, Hash, Equal>::GetStatistics
()
const
{
410
return
stats_;
411
}
412
413
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
414
size_t
ExpirableLruCache<Key, Value, Hash, Equal>::GetSizeApproximate
()
const
{
415
return
lru_.GetSize();
416
}
417
418
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
419
void
ExpirableLruCache<Key, Value, Hash, Equal>::Invalidate
() {
420
lru_.Invalidate();
421
}
422
423
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
424
void
ExpirableLruCache<Key, Value, Hash, Equal>::InvalidateByKey
(
const
Key& key) {
425
lru_.InvalidateByKey(key);
426
}
427
428
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
429
template
<
typename
Predicate>
430
void
ExpirableLruCache<Key, Value, Hash, Equal>::InvalidateByKeyIf
(
const
Key& key, Predicate pred) {
431
auto
now =
utils::datetime::SteadyNow
();
432
433
auto
mutex = lru_.GetMutexForKey(key);
434
const
std::lock_guard lock(mutex);
435
const
auto
cur_value = lru_.Get(key);
436
437
if
(cur_value.has_value() && !IsExpired(cur_value->update_time, now) && pred(cur_value->value)) {
438
InvalidateByKey
(key);
439
}
440
}
441
442
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
443
void
ExpirableLruCache<Key, Value, Hash, Equal>::UpdateInBackground
(
const
Key& key,
UpdateValueFunc
update_func) {
444
impl::CacheBackgroundUpdate(stats_);
445
446
// cache will wait for all detached tasks in ~ExpirableLruCache()
447
engine::DetachUnscopedUnsafe
(
engine::AsyncNoTracing
(
448
[token = wait_token_storage_.GetToken(),
this
, key, update_func = std::move(update_func)] {
449
auto mutex = lru_.GetMutexForKey(key);
450
const std::unique_lock lock(mutex, std::try_to_lock);
451
if (!lock) {
452
// someone is updating the key right now
453
return;
454
}
455
456
auto
now =
utils::datetime::SteadyNow
();
457
auto
value = update_func(key);
458
lru_.Put(key, {.value = value, .update_time = now});
459
}
460
));
461
}
462
463
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
464
bool
ExpirableLruCache<
465
Key,
466
Value,
467
Hash,
468
Equal>::IsExpired(std::chrono::steady_clock::time_point update_time, std::chrono::steady_clock::time_point now)
469
const
{
470
auto
max_lifetime = max_lifetime_.load();
471
return
max_lifetime.count() != 0 && update_time + max_lifetime < now;
472
}
473
474
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
475
bool
ExpirableLruCache<
476
Key,
477
Value,
478
Hash,
479
Equal>::ShouldUpdate(std::chrono::steady_clock::time_point update_time, std::chrono::steady_clock::time_point now)
480
const
{
481
auto
max_lifetime = max_lifetime_.load();
482
return
(background_update_mode_.load() == BackgroundUpdateMode::kEnabled) && max_lifetime.count() != 0 &&
483
update_time + max_lifetime / 2 < now;
484
}
485
490
template
<
typename
Key,
typename
Value,
typename
Hash = std::hash<Key>,
typename
Equal = std::equal_to<Key>>
491
class
LruCacheWrapper
final {
492
public
:
494
using
Cache
=
ExpirableLruCache<Key, Value, Hash, Equal>
;
496
using
ReadMode
=
typename
Cache::ReadMode
;
497
506
LruCacheWrapper
(std::shared_ptr<Cache>
cache
,
typename
Cache::UpdateValueFunc
update_func)
507
: cache_(
std
::move(
cache
)),
508
update_func_(
std
::move(update_func))
509
{}
510
516
Value
Get
(
const
Key& key,
ReadMode
read_mode = ReadMode::kUseCache) {
517
return
cache_->Get(key, update_func_, read_mode);
518
}
519
524
std::optional<Value>
GetOptional
(
const
Key& key) {
return
cache_->GetOptional(key, update_func_); }
525
529
void
InvalidateByKey
(
const
Key& key) { cache_->InvalidateByKey(key); }
530
536
template
<
typename
Predicate>
537
void
InvalidateByKeyIf
(
const
Key& key, Predicate pred) {
538
cache_->InvalidateByKeyIf(key, pred);
539
}
540
544
void
UpdateInBackground
(
const
Key& key) { cache_->UpdateInBackground(key, update_func_); }
545
550
std::shared_ptr<Cache>
GetCache
() {
return
cache_; }
551
552
private
:
553
std::shared_ptr<Cache> cache_;
554
typename
Cache::UpdateValueFunc update_func_;
555
};
556
557
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
558
void
ExpirableLruCache<Key, Value, Hash, Equal>::Write
(
dump::Writer
& writer)
const
{
559
utils::impl::UpdateGlobalTime();
560
lru_.Write(writer);
561
}
562
563
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
564
void
ExpirableLruCache<Key, Value, Hash, Equal>::Read
(
dump::Reader
& reader) {
565
utils::impl::UpdateGlobalTime();
566
lru_.Read(reader);
567
}
568
569
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
570
void
ExpirableLruCache<Key, Value, Hash, Equal>::SetDumper
(std::shared_ptr<dump::Dumper> dumper) {
571
lru_.SetDumper(std::move(dumper));
572
}
573
574
template
<
typename
Key,
typename
Value,
typename
Hash,
typename
Equal>
575
void
DumpMetric(
utils::statistics::Writer
& writer,
const
ExpirableLruCache<Key, Value, Hash, Equal>
&
cache
) {
576
writer[
"current-documents-count"
] =
cache
.GetSizeApproximate();
577
writer =
cache
.GetStatistics();
578
}
579
580
}
// namespace cache
581
582
USERVER_NAMESPACE_END
userver
cache
expirable_lru_cache.hpp
Generated on
for userver by
Doxygen
1.17.0