userver
C++ Async Framework
Toggle main menu visibility
Loading...
Searching...
No Matches
caching_component_base.hpp
Go to the documentation of this file.
1
#
pragma
once
2
3
/// @file userver/cache/caching_component_base.hpp
4
/// @brief @copybrief components::CachingComponentBase
5
6
#
include
<
memory
>
7
#
include
<
string
>
8
#
include
<
utility
>
9
10
#
include
<
fmt
/
format
.
h
>
11
12
#
include
<
userver
/
cache
/
cache_update_trait
.
hpp
>
13
#
include
<
userver
/
cache
/
data_provider
.
hpp
>
14
#
include
<
userver
/
cache
/
exceptions
.
hpp
>
15
#
include
<
userver
/
compiler
/
demangle
.
hpp
>
16
#
include
<
userver
/
components
/
component_base
.
hpp
>
17
#
include
<
userver
/
components
/
component_context
.
hpp
>
18
#
include
<
userver
/
components
/
component_fwd
.
hpp
>
19
#
include
<
userver
/
concurrent
/
async_event_channel
.
hpp
>
20
#
include
<
userver
/
dump
/
helpers
.
hpp
>
21
#
include
<
userver
/
dump
/
meta
.
hpp
>
22
#
include
<
userver
/
dump
/
operations
.
hpp
>
23
#
include
<
userver
/
engine
/
async
.
hpp
>
24
#
include
<
userver
/
rcu
/
rcu
.
hpp
>
25
#
include
<
userver
/
utils
/
assert
.
hpp
>
26
#
include
<
userver
/
utils
/
impl
/
wait_token_storage
.
hpp
>
27
#
include
<
userver
/
utils
/
meta
.
hpp
>
28
#
include
<
userver
/
utils
/
resource_scopes
.
hpp
>
29
#
include
<
userver
/
utils
/
shared_readable_ptr
.
hpp
>
30
#
include
<
userver
/
yaml_config
/
schema
.
hpp
>
31
32
USERVER_NAMESPACE_BEGIN
33
34
namespace
components
{
35
36
/// @ingroup userver_components userver_base_classes
37
///
38
/// @brief Base class for caching components
39
///
40
/// Provides facilities for creating periodically updated caches.
41
/// You need to override cache::CacheUpdateTrait::Update.
42
/// You can also override cache::CachingComponentBase::PreAssignCheck and set
43
/// has-pre-assign-check: true in the static config to enable check.
44
///
45
/// Caching components must be configured in service config (see options below)
46
/// and may be reconfigured dynamically via components::DynamicConfig.
47
///
48
/// @ref scripts/docs/en/userver/caches.md provide a more detailed introduction.
49
///
50
/// ## CachingComponentBase Dynamic config
51
/// * @ref USERVER_CACHES
52
/// * @ref USERVER_DUMPS
53
///
54
/// ## Static options of components::CachingComponentBase :
55
/// @include{doc} scripts/docs/en/components_schema/core/src/cache/caching_component_base.md
56
///
57
/// Options inherited from @ref components::ComponentBase :
58
/// @include{doc} scripts/docs/en/components_schema/core/src/components/impl/component_base.md
59
///
60
/// ### Update types
61
/// * `full-and-incremental`: both `update-interval` and `full-update-interval`
62
/// must be specified. Updates with UpdateType::kIncremental will be triggered
63
/// each `update-interval` (adjusted by jitter) unless `full-update-interval`
64
/// has passed and UpdateType::kFull is triggered.
65
/// * `only-full`: only `update-interval` must be specified. UpdateType::kFull
66
/// will be triggered each `update-interval` (adjusted by jitter).
67
/// * `only-incremental`: only `update-interval` must be specified. UpdateType::kFull is triggered
68
/// on the first update, afterwards UpdateType::kIncremental will be triggered
69
/// each `update-interval` (adjusted by jitter). Warning: use carefully.
70
/// If the cache loses any data, it is lost until service restart (in the worst case). If possible,
71
/// use `full-and-incremental` with rare full updates, and completely avoid `only-incremental`.
72
/// Also you have to explicitly remove outdated items from the cache container, otherwise
73
/// the cache might grow indefinitely and eventually will lead to OOM.
74
/// If not sure, just use `full-and-incremental`.
75
///
76
/// ### Avoiding memory leaks
77
///
78
/// If you don't implement the deletion of objects that are deleted from the data source and don't use full updates,
79
/// you may get an effective memory leak, because garbage objects will pile up in the cached data.
80
///
81
/// Calculation example:
82
/// * size of database: 1000 objects
83
/// * removal rate: 30 objects per minute (0.5 objects per second)
84
///
85
/// Let's say we allow 20% extra garbage objects in cache in addition to the actual objects from the database. In this
86
/// case we need:
87
///
88
/// full-update-interval = (size-of-database * 20% / removal-rate) = 400s
89
///
90
/// ### Dealing with nullptr data in CachingComponentBase
91
///
92
/// The cache can become `nullptr` through multiple ways:
93
///
94
/// * If the first cache update fails, and `first-update-fail-ok` config
95
/// option is set to `true` (otherwise the service shutdown at start)
96
/// * Through manually calling @ref Set with `nullptr` in @ref Update
97
/// * If `failed-updates-before-expiration` is set, and that many periodic
98
/// updates fail in a row
99
///
100
/// By default, the cache's user can expect that the pointer returned
101
/// from @ref Get will never be `nullptr`. If the cache for some reason is
102
/// in `nullptr` state, then @ref Get will throw. This is the safe default
103
/// behavior for most cases.
104
///
105
/// If all systems of a service are expected to work with a cache in `nullptr`
106
/// state, then such a cache should override `MayReturnNull` to return `true`.
107
/// It will also serve self-documentation purposes: if a cache defines
108
/// @ref MayReturnNull, then pointers returned from @ref Get should be checked
109
/// for `nullptr` before usage.
110
///
111
/// ### `first-update-mode` modes
112
///
113
/// Further customizes the behavior of @ref dump::Dumper "cache dumps".
114
///
115
/// Mode | Description
116
/// ----------- | -----------
117
/// skip | after successful load from dump, do nothing
118
/// required | make a synchronous update of type `first-update-type`, stop the service on failure
119
/// best-effort | make a synchronous update of type `first-update-type`, keep working and use data from dump on failure
120
///
121
/// ### testsuite-force-periodic-update
122
/// use it to enable periodic cache update for a component in testsuite environment
123
/// where testsuite-periodic-update-enabled from TestsuiteSupport config is false
124
///
125
/// By default, update types are guessed based on update intervals presence.
126
/// If both `update-interval` and `full-update-interval` are present,
127
/// `full-and-incremental` types is assumed. Otherwise `only-full` is used.
128
///
129
/// @see `dump::Dumper` for more info on persistent cache dumps and
130
/// corresponding config options.
131
///
132
/// @see @ref scripts/docs/en/userver/caches.md. pytest_userver.client.Client.invalidate_caches()
133
/// for a function to force cache update from testsuite.
134
template
<
typename
T>
135
// NOLINTNEXTLINE(fuchsia-multiple-inheritance)
136
class
CachingComponentBase
:
public
ComponentBase
,
public
cache
::
DataProvider
<T>,
protected
cache
::
CacheUpdateTrait
{
137
public
:
138
CachingComponentBase(
const
ComponentConfig& config,
const
ComponentContext&);
139
~CachingComponentBase()
override
;
140
141
using
cache
::
CacheUpdateTrait
::Name;
142
143
using
cache
::
CacheUpdateTrait
::InvalidateAsync;
144
145
using
DataType = T;
146
147
/// @return cache contents. May be `nullptr` if and only if `MayReturnNull`
148
/// returns `true`.
149
/// @throws cache::EmptyCacheError if the contents are `nullptr`, and
150
/// `MayReturnNull` returns `false` (which is the default behavior).
151
utils
::SharedReadablePtr<T>
Get
()
const
final
;
152
153
/// @return cache contents. May be nullptr regardless of `MayReturnNull`.
154
utils
::SharedReadablePtr<T>
GetUnsafe
()
const
;
155
156
/// Subscribes to cache updates using a member function. Also immediately
157
/// invokes the function with the current cache contents.
158
///
159
/// Further updates are delivered after @ref utils::ResourceScopeStorage::AfterConstruction, including those updates
160
/// that arrived before it. Unsubscribe runs in @ref utils::ResourceScopeStorage::BeforeDestruction.
161
///
162
/// @param scopes storage that owns the subscription lifetime.
163
/// See @ref resource_scopes_parameter "where to obtain scopes".
164
template
<
class
Class>
165
void
UpdateAndListen
(
166
utils
::ResourceScopeStorage& scopes,
167
Class* obj,
168
std::string name,
169
void
(Class::*func)(
const
std::shared_ptr<
const
T>&)
170
);
171
172
#
ifndef
ARCADIA_ROOT
173
/// @overload
174
/// @deprecated Use the overload that takes @ref utils::ResourceScopeStorage.
175
///
176
/// Store the returned scope as a member and call `Unsubscribe` explicitly.
177
template
<
class
Class>
178
concurrent
::AsyncEventSubscriberScope
UpdateAndListen
(
179
Class* obj,
180
std::string name,
181
void
(Class::*func)(
const
std::shared_ptr<
const
T>&)
182
);
183
#
endif
184
185
concurrent
::
AsyncEventChannel
<
const
std::shared_ptr<
const
T>&>& GetEventChannel();
186
187
static
yaml_config::Schema GetStaticConfigSchema();
188
189
protected
:
190
/// @brief Sets the new value of cache. As a result, @ref Get member function starts returning the new value.
191
///
192
/// Notifies subscribers after setting the new value, see @ref UpdateAndListen.
193
/// Should only be called from @ref Update normally.
194
///
195
/// @warning Do not forget to update @ref cache::UpdateStatisticsScope, otherwise the behavior is undefined.
196
void
Set
(std::unique_ptr<
const
T> value_ptr);
197
198
/// @overload
199
void
Set
(T&& value);
200
201
/// Attach the value of cache. As a result the `Get()` member function starts returning the value passed into
202
/// this function after the `Update()` finishes. Does not take over into sole ownership. Do not use unless
203
/// absolutely necessary. The object must be strictly thread-safe.
204
///
205
/// @warning Do not forget to update @ref cache::UpdateStatisticsScope, otherwise
206
/// the behavior is undefined.
207
void
Attach
(
const
std::shared_ptr<
const
T>& value_ptr);
208
209
/// @overload Set()
210
template
<
typename
... Args>
211
void
Emplace(Args&&... args);
212
213
/// Clears the content of the cache by string a default constructed T.
214
void
Clear
();
215
216
/// Whether @ref Get is expected to return `nullptr`.
217
virtual
bool
MayReturnNull
()
const
;
218
219
/// @{
220
/// Override to use custom serialization for cache dumps
221
virtual
void
WriteContents
(
dump
::
Writer
& writer,
const
T& contents)
const
;
222
223
virtual
std::unique_ptr<
const
T> ReadContents(
dump
::
Reader
& reader)
const
;
224
/// @}
225
226
/// @brief If the option has-pre-assign-check is set true in static config,
227
/// this function is called before assigning the new value to the cache
228
/// @note old_value_ptr and new_value_ptr can be nullptr.
229
virtual
void
PreAssignCheck
(
const
T* old_value_ptr,
const
T* new_value_ptr)
const
;
230
231
private
:
232
void
Cleanup()
final
;
233
234
void
MarkAsExpired()
final
;
235
236
void
GetAndWrite(
dump
::
Writer
& writer)
const
final
;
237
void
ReadAndSet(
dump
::
Reader
& reader)
final
;
238
239
std::shared_ptr<
const
T> TransformNewValue(std::unique_ptr<
const
T> new_value);
240
241
rcu
::
Variable
<std::shared_ptr<
const
T>> cache_;
242
concurrent
::
AsyncEventChannel
<
const
std::shared_ptr<
const
T>&> event_channel_;
243
utils
::impl::WaitTokenStorage wait_token_storage_;
244
};
245
246
template
<
typename
T>
247
CachingComponentBase
<T>::CachingComponentBase(
const
ComponentConfig& config,
const
ComponentContext& context)
248
:
ComponentBase
(config, context),
249
cache
::
CacheUpdateTrait
(config, context),
250
event_channel_(
251
components
::
GetCurrentComponentName
(
context
)
,
252
[
this
](
const
auto
& function) {
253
const
auto
ptr = cache_.ReadCopy();
254
if
(ptr) {
255
function(ptr);
256
}
257
}
258
)
259
{}
260
261
template
<
typename
T>
262
CachingComponentBase
<T>::~CachingComponentBase() {
263
// Avoid a deadlock in WaitForAllTokens
264
cache_.Assign(
nullptr
);
265
// We must wait for destruction of all instances of T to finish, otherwise
266
// it's UB if T's destructor accesses dependent components
267
wait_token_storage_.WaitForAllTokens();
268
}
269
270
template
<
typename
T>
271
utils
::SharedReadablePtr<T>
CachingComponentBase
<T>::
Get
()
const
{
272
auto
ptr =
GetUnsafe
(
)
;
273
if
(!ptr && !
MayReturnNull
(
)
) {
274
throw
cache
::EmptyCacheError(
Name
(
)
);
275
}
276
return
ptr;
277
}
278
279
template
<
typename
T
>
280
template
<
typename
Class>
281
void
CachingComponentBase
<T>::
UpdateAndListen
(
282
utils
::ResourceScopeStorage& scopes,
283
Class* obj,
284
std::string name,
285
void
(Class::*func)(
const
std::shared_ptr<
const
T>&)
286
) {
287
event_channel_.DoUpdateAndListen(scopes, obj, std::move(name), func, [
this
, obj, func] {
288
auto
ptr =
Get
(
)
;
// TODO: extra ref
289
(obj->*func)(ptr);
290
});
291
}
292
293
#
ifndef
ARCADIA_ROOT
294
template
<
typename
T
>
295
template
<
typename
Class>
296
concurrent
::AsyncEventSubscriberScope
CachingComponentBase
<
297
T>::
UpdateAndListen
(Class* obj, std::string name,
void
(Class::*func)(
const
std::shared_ptr<
const
T>&)) {
298
return
event_channel_.DoUpdateAndListen(obj, std::move(name), func, [&] {
299
auto
ptr =
Get
(
)
;
// TODO: extra ref
300
(obj->*func)(ptr);
301
});
302
}
303
#
endif
304
305
template
<
typename
T>
306
concurrent
::
AsyncEventChannel
<
const
std::shared_ptr<
const
T>&>&
CachingComponentBase
<T>::GetEventChannel() {
307
return
event_channel_;
308
}
309
310
template
<
typename
T>
311
utils
::SharedReadablePtr<T>
CachingComponentBase
<T>::
GetUnsafe
()
const
{
312
return
utils
::SharedReadablePtr<T>(cache_.ReadCopy());
313
}
314
315
template
<
typename
T>
316
void
CachingComponentBase
<T>::
Set
(std::unique_ptr<
const
T> value_ptr) {
317
Attach
(
TransformNewValue(std::move(value_ptr))
)
;
318
}
319
320
template
<
typename
T>
321
void
CachingComponentBase
<T>::
Set
(T&& value) {
322
Emplace(std::move(value));
323
}
324
325
template
<
typename
T>
326
void
CachingComponentBase
<T>::
Attach
(
const
std::shared_ptr<
const
T>& value_ptr) {
327
if
(HasPreAssignCheck()) {
328
auto
old_value = cache_.Read();
329
PreAssignCheck
(
old_value->get()
,
value_ptr.get()
)
;
330
}
331
332
cache_.Assign(value_ptr);
333
event_channel_.SendEvent(value_ptr);
334
OnCacheModified
(
)
;
335
}
336
337
template
<
typename
T
>
338
template
<
typename
... Args>
339
void
CachingComponentBase
<T>::Emplace(Args&&... args) {
340
Set(std::make_unique<T>(std::forward<Args>(args)...));
341
}
342
343
template
<
typename
T>
344
void
CachingComponentBase
<T>::
Clear
() {
345
cache_.Assign(std::make_unique<
const
T>());
346
}
347
348
template
<
typename
T>
349
bool
CachingComponentBase
<T>::
MayReturnNull
()
const
{
350
return
false
;
351
}
352
353
template
<
typename
T>
354
void
CachingComponentBase
<T>::GetAndWrite(
dump
::
Writer
& writer)
const
{
355
const
auto
contents =
GetUnsafe
(
)
;
356
if
(!contents) {
357
throw
cache
::EmptyCacheError(
Name
(
)
);
358
}
359
WriteContents
(
writer
,
*contents
)
;
360
}
361
362
template
<
typename
T>
363
void
CachingComponentBase
<T>::ReadAndSet(
dump
::
Reader
& reader) {
364
auto
data = ReadContents(reader);
365
if
constexpr
(
meta
::
IsSizable
<T>) {
366
if
(data) {
367
SetDataSizeStatistic(std::size(*data));
368
}
369
}
370
Set(std::move(data));
371
}
372
373
template
<
typename
T>
374
void
CachingComponentBase
<T>::
WriteContents
(
dump
::
Writer
& writer,
const
T& contents)
const
{
375
if
constexpr
(
dump
::
kIsDumpable
<T>) {
376
writer.Write(contents);
377
}
else
{
378
dump
::ThrowDumpUnimplemented(
Name
(
)
);
379
}
380
}
381
382
template
<
typename
T>
383
std::unique_ptr<
const
T>
CachingComponentBase
<T>::ReadContents(
dump
::
Reader
& reader)
const
{
384
if
constexpr
(
dump
::
kIsDumpable
<T>) {
385
// To avoid an extra move and avoid including common_containers.hpp
386
return
std::unique_ptr<
const
T>{
new
T(reader.Read<T>())};
387
}
else
{
388
dump
::ThrowDumpUnimplemented(
Name
(
)
);
389
}
390
}
391
392
template
<
typename
T>
393
void
CachingComponentBase
<T>::Cleanup() {
394
cache_.Cleanup();
395
}
396
397
template
<
typename
T>
398
void
CachingComponentBase
<T>::MarkAsExpired() {
399
Set(std::unique_ptr<
const
T>{});
400
}
401
402
namespace
impl {
403
404
yaml_config::Schema GetCachingComponentBaseSchema();
405
406
template
<
typename
T,
typename
Deleter>
407
auto
MakeAsyncDeleter(engine::TaskProcessor& task_processor, Deleter deleter) {
408
return
[&task_processor, deleter = std::move(deleter)](
const
T* raw_ptr)
mutable
{
409
std::unique_ptr<
const
T, Deleter> ptr(raw_ptr, std::move(deleter));
410
411
engine::DetachUnscopedUnsafe(engine::CriticalAsyncNoTracing(task_processor, [ptr = std::move(ptr)]()
mutable
{})
412
);
413
};
414
}
415
416
}
// namespace impl
417
418
template
<
typename
T>
419
yaml_config::Schema
CachingComponentBase
<T>::GetStaticConfigSchema() {
420
return
impl::GetCachingComponentBaseSchema();
421
}
422
423
template
<
typename
T>
424
void
CachingComponentBase
<T>::
PreAssignCheck
(
const
T*, [[
maybe_unused
]]
const
T* new_value_ptr)
const
{
425
UINVARIANT
(
426
meta
::
IsSizable
<T>,
427
fmt
::format(
428
"{} type does not support std::size(), add implementation of "
429
"the method size() for this type or "
430
"override cache::CachingComponentBase::PreAssignCheck."
,
431
compiler
::GetTypeName<T>()
432
)
433
);
434
435
if
constexpr
(
meta
::
IsSizable
<T>) {
436
if
(!new_value_ptr || std::size(*new_value_ptr) == 0) {
437
throw
cache
::EmptyDataError(
Name
(
)
);
438
}
439
}
440
}
441
442
template
<
typename
T>
443
std::shared_ptr<
const
T>
CachingComponentBase
<T>::TransformNewValue(std::unique_ptr<
const
T> new_value) {
444
// Kill garbage asynchronously as T::~T() might be very slow
445
if
(IsSafeDataLifetime()) {
446
// Use token only if `safe-data-lifetime` is true
447
auto
deleter_with_token = [token = wait_token_storage_.GetToken()](
const
T* raw_ptr) {
448
// Make sure *raw_ptr is deleted before token is destroyed
449
std::default_delete<
const
T>{}(raw_ptr);
450
};
451
return
std::shared_ptr<
const
T>(
452
new_value.release(),
453
impl::MakeAsyncDeleter<T>(GetCacheTaskProcessor(), std::move(deleter_with_token))
454
);
455
}
else
{
456
return
std::shared_ptr<
const
T>(
457
new_value.release(),
458
impl::MakeAsyncDeleter<T>(GetCacheTaskProcessor(), std::default_delete<
const
T>{})
459
);
460
}
461
}
462
463
}
// namespace components
464
465
USERVER_NAMESPACE_END
userver
cache
caching_component_base.hpp
Generated on
for userver by
Doxygen
1.17.0