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
|
#pragma once
#include "cache.h"
namespace NSQLComplete {
template <NPrivate::CCacheKey TKey, NPrivate::CCacheValue TValue>
class TCachedQuery {
public:
using TFunc = std::function<NThreading::TFuture<TValue>(const TKey& key)>;
TCachedQuery(ICache<TKey, TValue>::TPtr cache, TFunc query)
: Cache_(std::move(cache))
, Query_(std::move(query))
{
}
NThreading::TFuture<TValue> operator()(TKey key) const {
auto promise = NThreading::NewPromise<TValue>();
Cache_->Get(key).Apply([cache = Cache_,
query = Query_,
key = std::move(key),
promise](auto f) mutable {
typename ICache<TKey, TValue>::TEntry entry;
try {
entry = f.ExtractValue();
} catch (...) {
promise.SetException(std::current_exception());
return;
}
if (!entry.IsExpired) {
Y_ENSURE(entry.Value.Defined());
promise.SetValue(std::move(*entry.Value));
return;
}
bool isEmpty = entry.Value.Empty();
if (!isEmpty) {
promise.SetValue(std::move(*entry.Value));
}
query(key).Apply([cache, key = std::move(key), isEmpty, promise](auto f) mutable {
TValue value;
try {
value = f.ExtractValue();
} catch (...) {
promise.SetException(std::current_exception());
return;
}
if (isEmpty) {
promise.SetValue(value);
}
cache->Update(key, std::move(value));
});
});
return promise;
}
private:
ICache<TKey, TValue>::TPtr Cache_;
TFunc Query_;
};
} // namespace NSQLComplete
|