userver: userver/cache/expirable_lru_cache.hpp Source File
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
17#include <userver/utils/impl/cached_time.hpp>
18#include <userver/utils/impl/wait_token_storage.hpp>
20
21USERVER_NAMESPACE_BEGIN
22
23namespace cache {
24
25namespace impl {
26
27template <typename Value>
28struct ExpirableValue final {
29 Value value;
30 std::chrono::steady_clock::time_point update_time;
31};
32
33template <typename Value>
34void 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
40template <typename Value>
41impl::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
58template <typename Key, typename Value, typename Hash = std::hash<Key>, typename Equal = std::equal_to<Key>>
59class ExpirableLruCache final {
60public:
62 using UpdateValueFunc = std::function<Value(const Key&)>;
63
65 enum class ReadMode {
68 };
69
76 ExpirableLruCache(size_t ways, size_t way_size, const Hash& hash = Hash(), const Equal& equal = Equal());
77
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
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
231private:
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
244template <typename Key, typename Value, typename Hash, typename Equal>
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
253template <typename Key, typename Value, typename Hash, typename Equal>
255 wait_token_storage_.WaitForAllTokens();
256}
257
258template <typename Key, typename Value, typename Hash, typename Equal>
260 lru_.UpdateWaySize(way_size);
261}
262
263template <typename Key, typename Value, typename Hash, typename Equal>
264std::chrono::milliseconds ExpirableLruCache<Key, Value, Hash, Equal>::GetMaxLifetime() const noexcept {
265 return max_lifetime_.load();
266}
267
268template <typename Key, typename Value, typename Hash, typename Equal>
269void ExpirableLruCache<Key, Value, Hash, Equal>::SetMaxLifetime(std::chrono::milliseconds max_lifetime) {
270 max_lifetime_ = max_lifetime;
271}
272
273template <typename Key, typename Value, typename Hash, typename Equal>
274void ExpirableLruCache<Key, Value, Hash, Equal>::SetBackgroundUpdate(BackgroundUpdateMode background_update) {
275 background_update_mode_ = background_update;
276}
277
278template <typename Key, typename Value, typename Hash, typename Equal>
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
306template <typename Key, typename Value, typename Hash, typename Equal>
307std::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
333template <typename Key, typename Value, typename Hash, typename Equal>
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
346template <typename Key, typename Value, typename Hash, typename Equal>
347std::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
369template <typename Key, typename Value, typename Hash, typename Equal>
370std::optional<impl::ExpirableValue<Value>> ExpirableLruCache<
371 Key,
372 Value,
373 Hash,
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
389template <typename Key, typename Value, typename Hash, typename Equal>
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
398template <typename Key, typename Value, typename Hash, typename Equal>
399void 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
403template <typename Key, typename Value, typename Hash, typename Equal>
404void 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
408template <typename Key, typename Value, typename Hash, typename Equal>
409const impl::ExpirableLruCacheStatistics& ExpirableLruCache<Key, Value, Hash, Equal>::GetStatistics() const {
410 return stats_;
411}
412
413template <typename Key, typename Value, typename Hash, typename Equal>
415 return lru_.GetSize();
416}
417
418template <typename Key, typename Value, typename Hash, typename Equal>
422
423template <typename Key, typename Value, typename Hash, typename Equal>
425 lru_.InvalidateByKey(key);
426}
427
428template <typename Key, typename Value, typename Hash, typename Equal>
429template <typename Predicate>
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
442template <typename Key, typename Value, typename Hash, typename Equal>
444 impl::CacheBackgroundUpdate(stats_);
445
446 // cache will wait for all detached tasks in ~ExpirableLruCache()
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
463template <typename Key, typename Value, typename Hash, typename Equal>
464bool 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
474template <typename Key, typename Value, typename Hash, typename Equal>
475bool 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
490template <typename Key, typename Value, typename Hash = std::hash<Key>, typename Equal = std::equal_to<Key>>
491class LruCacheWrapper final {
492public:
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
552private:
553 std::shared_ptr<Cache> cache_;
554 typename Cache::UpdateValueFunc update_func_;
555};
556
557template <typename Key, typename Value, typename Hash, typename Equal>
559 utils::impl::UpdateGlobalTime();
560 lru_.Write(writer);
561}
562
563template <typename Key, typename Value, typename Hash, typename Equal>
565 utils::impl::UpdateGlobalTime();
566 lru_.Read(reader);
567}
568
569template <typename Key, typename Value, typename Hash, typename Equal>
570void ExpirableLruCache<Key, Value, Hash, Equal>::SetDumper(std::shared_ptr<dump::Dumper> dumper) {
571 lru_.SetDumper(std::move(dumper));
572}
573
574template <typename Key, typename Value, typename Hash, typename Equal>
576 writer["current-documents-count"] = cache.GetSizeApproximate();
577 writer = cache.GetStatistics();
578}
579
580} // namespace cache
581
582USERVER_NAMESPACE_END