userver: userver/cache/base_postgres_cache.hpp Source File
Loading...
Searching...
No Matches
base_postgres_cache.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/cache/base_postgres_cache.hpp
4/// @brief @copybrief components::PostgreCache
5
6#include <userver/cache/base_postgres_cache_fwd.hpp>
7
8#include <chrono>
9#include <map>
10#include <string_view>
11#include <type_traits>
12#include <unordered_map>
13
14#include <fmt/format.h>
15
16#include <userver/cache/cache_statistics.hpp>
17#include <userver/cache/caching_component_base.hpp>
18#include <userver/components/component_config.hpp>
19#include <userver/components/component_context.hpp>
20
21#include <userver/storages/postgres/cluster.hpp>
22#include <userver/storages/postgres/component.hpp>
23#include <userver/storages/postgres/io/chrono.hpp>
24
25#include <userver/compiler/demangle.hpp>
26#include <userver/engine/sleep.hpp>
27#include <userver/logging/log.hpp>
28#include <userver/tracing/span.hpp>
29#include <userver/utils/assert.hpp>
30#include <userver/utils/cpu_relax.hpp>
31#include <userver/utils/meta.hpp>
32#include <userver/utils/void_t.hpp>
33#include <userver/yaml_config/merge_schemas.hpp>
34
35USERVER_NAMESPACE_BEGIN
36
37namespace components {
38
39/// @page pg_cache Caching Component for PostgreSQL
40///
41/// A typical components::PostgreCache usage consists of trait definition:
42///
43/// @snippet postgresql/src/cache/postgres_cache_test.cpp Pg Cache Policy Trivial
44///
45/// and registration of the component in components::ComponentList:
46///
47/// @snippet postgresql/src/cache/postgres_cache_test.cpp Pg Cache Trivial Usage
48///
49/// See @ref scripts/docs/en/userver/caches.md for introduction into caches.
50///
51///
52/// @section pg_cc_configuration Configuration
53///
54/// components::PostgreCache static configuration file should have a PostgreSQL
55/// component name specified in `pgcomponent` configuration parameter.
56///
57/// Optionally the operation timeouts for cache loading can be specified.
58///
59/// For avoiding "memory leaks", see the respective section
60/// in @ref components::CachingComponentBase.
61///
62/// @include{doc} scripts/docs/en/components_schema/postgresql/src/cache/base_postgres_cache.md
63///
64/// Options inherited from @ref components::CachingComponentBase :
65/// @include{doc} scripts/docs/en/components_schema/core/src/cache/caching_component_base.md
66///
67/// Options inherited from @ref components::ComponentBase :
68/// @include{doc} scripts/docs/en/components_schema/core/src/components/impl/component_base.md
69///
70/// @section pg_cc_cache_policy Cache policy
71///
72/// Cache policy is the template argument of components::PostgreCache component.
73/// Please see the following code snippet for documentation.
74///
75/// @snippet cache/postgres_cache_test.cpp Pg Cache Policy Example
76///
77/// The query can be a std::string. But due to non-guaranteed order of static
78/// data members initialization, std::string should be returned from a static
79/// member function, please see the following code snippet.
80///
81/// @snippet cache/postgres_cache_test.cpp Pg Cache Policy GetQuery Example
82///
83/// Policy may have static function GetLastKnownUpdated. It should be used
84/// when new entries from database are taken via revision, identifier, or
85/// anything else, but not timestamp of the last update.
86/// If this function is supplied, new entries are taken from db with condition
87/// 'WHERE kUpdatedField > GetLastKnownUpdated(cache_container)'.
88/// Otherwise, condition is
89/// 'WHERE kUpdatedField > last_update - correction_'.
90/// See the following code snippet for an example of usage
91///
92/// @snippet cache/postgres_cache_test.cpp Pg Cache Policy Custom Updated Example
93///
94/// Cache can also store only subset of data. For example for the database that is is defined in the following way:
95///
96/// @include samples/postgres_cache_order_by/schemas/postgresql/key_value.sql
97///
98/// it is possible to create a cache that stores only the latest `value`:
99///
100/// @snippet samples/postgres_cache_order_by/main.cpp Last pg cache
101///
102/// In case one provides a custom CacheContainer within Policy, it is notified
103/// of Update completion via its public member function OnWritesDone, if any.
104/// Custom CacheContainer must provide size method and insert_or_assign method
105/// similar to std::unordered_map's one or CacheInsertOrAssign function similar
106/// to one defined in namespace utils::impl::projected_set (i.e. used for
107/// utils::ProjectedUnorderedSet).
108/// See the following code snippet for an example of usage:
109///
110/// @snippet cache/postgres_cache_test.cpp Pg Cache Policy Custom Container With Write Notification Example
111///
112/// @section pg_cc_forward_declaration Forward Declaration
113///
114/// To forward declare a cache you can forward declare a trait and
115/// include userver/cache/base_postgres_cache_fwd.hpp header. It is also useful to
116/// forward declare the cache value type.
117///
118/// @snippet cache/postgres_cache_test_fwd.hpp Pg Cache Fwd Example
119///
120/// ----------
121///
122/// @htmlonly <div class="bottom-nav"> @endhtmlonly
123/// ⇦ @ref scripts/docs/en/userver/cache_dumps.md | @ref scripts/docs/en/userver/lru_cache.md ⇨
124/// @htmlonly </div> @endhtmlonly
125
126namespace pg_cache::detail {
127
128template <typename T>
129using ValueType = typename T::ValueType;
130template <typename T>
131inline constexpr bool kHasValueType = meta::IsDetected<ValueType, T>;
132
133template <typename T>
134using RawValueTypeImpl = typename T::RawValueType;
135template <typename T>
136inline constexpr bool kHasRawValueType = meta::IsDetected<RawValueTypeImpl, T>;
137template <typename T>
138using RawValueType = meta::DetectedOr<ValueType<T>, RawValueTypeImpl, T>;
139
140template <typename PostgreCachePolicy>
141auto ExtractValue(RawValueType<PostgreCachePolicy>&& raw) {
142 if constexpr (kHasRawValueType<PostgreCachePolicy>) {
143 return Convert(std::move(raw), formats::parse::To<ValueType<PostgreCachePolicy>>());
144 } else {
145 return std::move(raw);
146 }
147}
148
149// Component name in policy
150template <typename T>
151using HasNameImpl = std::enable_if_t<!std::string_view{T::kName}.empty()>;
152template <typename T>
153inline constexpr bool kHasName = meta::IsDetected<HasNameImpl, T>;
154
155// Component query in policy
156template <typename T>
157using HasQueryImpl = decltype(T::kQuery);
158template <typename T>
159inline constexpr bool kHasQuery = meta::IsDetected<HasQueryImpl, T>;
160
161// Component GetQuery in policy
162template <typename T>
163using HasGetQueryImpl = decltype(T::GetQuery());
164template <typename T>
165inline constexpr bool kHasGetQuery = meta::IsDetected<HasGetQueryImpl, T>;
166
167// Component kWhere in policy
168template <typename T>
169using HasWhere = decltype(T::kWhere);
170template <typename T>
171inline constexpr bool kHasWhere = meta::IsDetected<HasWhere, T>;
172
173// Component kOrderBy in policy
174template <typename T>
175using HasOrderBy = decltype(T::kOrderBy);
176template <typename T>
177inline constexpr bool kHasOrderBy = meta::IsDetected<HasOrderBy, T>;
178
179// Update field
180template <typename T>
181using HasUpdatedField = decltype(T::kUpdatedField);
182template <typename T>
183inline constexpr bool kHasUpdatedField = meta::IsDetected<HasUpdatedField, T>;
184
185template <typename T>
186using WantIncrementalUpdates = std::enable_if_t<!std::string_view{T::kUpdatedField}.empty()>;
187template <typename T>
188inline constexpr bool kWantIncrementalUpdates = meta::IsDetected<WantIncrementalUpdates, T>;
189
190// Key member in policy
191template <typename T>
192using KeyMemberTypeImpl = std::decay_t<std::invoke_result_t<decltype(T::kKeyMember), ValueType<T>>>;
193template <typename T>
194inline constexpr bool kHasKeyMember = meta::IsDetected<KeyMemberTypeImpl, T>;
195template <typename T>
196using KeyMemberType = meta::DetectedType<KeyMemberTypeImpl, T>;
197
198// size method in custom container in policy
199template <typename T>
200using SizeMethodInvokeResultImpl = decltype(std::declval<T>().size());
201template <typename T>
202inline constexpr bool kHasSizeMethod =
203 meta::IsDetected<SizeMethodInvokeResultImpl, T> &&
204 std::is_convertible_v<SizeMethodInvokeResultImpl<T>, std::size_t>;
205
206// insert_or_assign method in custom container in policy
207template <typename T>
208using InsertOrAssignMethodInvokeResultImpl =
209 decltype(std::declval<typename T::CacheContainer>()
210 .insert_or_assign(std::declval<KeyMemberTypeImpl<T>>(), std::declval<ValueType<T>>()));
211template <typename T>
212inline constexpr bool kHasInsertOrAssignMethod = meta::IsDetected<InsertOrAssignMethodInvokeResultImpl, T>;
213
214// CacheInsertOrAssign function for custom container in policy
215template <typename T>
216using CacheInsertOrAssignFunctionInvokeResultImpl = decltype(CacheInsertOrAssign(
217 std::declval<typename T::CacheContainer&>(),
218 std::declval<ValueType<T>>(),
219 std::declval<KeyMemberTypeImpl<T>>()
220));
221template <typename T>
222inline constexpr bool
223 kHasCacheInsertOrAssignFunction = meta::IsDetected<CacheInsertOrAssignFunctionInvokeResultImpl, T>;
224
225// Data container for cache
226template <typename T, typename = USERVER_NAMESPACE::utils::void_t<>>
227struct DataCacheContainer {
228 static_assert(
229 meta::kIsStdHashable<KeyMemberType<T>>,
230 "With default CacheContainer, key type must be std::hash-able"
231 );
232
233 using type = std::unordered_map<KeyMemberType<T>, ValueType<T>>;
234};
235
236template <typename T>
237struct DataCacheContainer<T, USERVER_NAMESPACE::utils::void_t<typename T::CacheContainer>> {
238 static_assert(kHasSizeMethod<typename T::CacheContainer>, "Custom CacheContainer must provide `size` method");
239 static_assert(
240 kHasInsertOrAssignMethod<T> || kHasCacheInsertOrAssignFunction<T>,
241 "Custom CacheContainer must provide `insert_or_assign` method similar to std::unordered_map's "
242 "one or CacheInsertOrAssign function"
243 );
244
245 using type = typename T::CacheContainer;
246};
247
248template <typename T>
249using DataCacheContainerType = typename DataCacheContainer<T>::type;
250
251// We have to whitelist container types, for which we perform by-element
252// copying, because it's not correct for certain custom containers.
253template <typename T>
254inline constexpr bool kIsContainerCopiedByElement =
255 meta::kIsInstantiationOf<std::unordered_map, T> || meta::kIsInstantiationOf<std::map, T>;
256
257template <typename T>
258std::unique_ptr<T> CopyContainer(
259 const T& container,
260 [[maybe_unused]] std::size_t cpu_relax_iterations,
261 tracing::ScopeTime& scope
262) {
263 if constexpr (kIsContainerCopiedByElement<T>) {
264 auto copy = std::make_unique<T>();
265 if constexpr (meta::kIsReservable<T>) {
266 copy->reserve(container.size());
267 }
268
269 utils::CpuRelax relax{cpu_relax_iterations, &scope};
270 for (const auto& kv : container) {
271 relax.Relax();
272 copy->insert(kv);
273 }
274 return copy;
275 } else {
276 return std::make_unique<T>(container);
277 }
278}
279
280template <typename Container, typename Value, typename KeyMember, typename... Args>
281void CacheInsertOrAssign(Container& container, Value&& value, const KeyMember& key_member, Args&&... /*args*/) {
282 // Args are only used to de-prioritize this default overload.
283 static_assert(sizeof...(Args) == 0);
284 // Copy 'key' to avoid aliasing issues in 'insert_or_assign'.
285 auto key = std::invoke(key_member, value);
286 container.insert_or_assign(std::move(key), std::forward<Value>(value));
287}
288
289template <typename T>
290using HasOnWritesDoneImpl = decltype(std::declval<T&>().OnWritesDone());
291
292template <typename T>
293void OnWritesDone(T& container) {
294 if constexpr (meta::IsDetected<HasOnWritesDoneImpl, T>) {
295 container.OnWritesDone();
296 }
297}
298
299template <typename T>
300using HasCustomUpdatedImpl = decltype(T::GetLastKnownUpdated(std::declval<DataCacheContainerType<T>>()));
301
302template <typename T>
303inline constexpr bool kHasCustomUpdated = meta::IsDetected<HasCustomUpdatedImpl, T>;
304
305template <typename T>
306using UpdatedFieldTypeImpl = typename T::UpdatedFieldType;
307template <typename T>
308inline constexpr bool kHasUpdatedFieldType = meta::IsDetected<UpdatedFieldTypeImpl, T>;
309template <typename T>
310using UpdatedFieldType = meta::DetectedOr<storages::postgres::TimePointTz, UpdatedFieldTypeImpl, T>;
311
312template <typename T>
313constexpr bool CheckUpdatedFieldType() {
314 if constexpr (kHasUpdatedFieldType<T>) {
315#if USERVER_POSTGRES_ENABLE_LEGACY_TIMESTAMP
316 static_assert(
317 std::is_same_v<typename T::UpdatedFieldType, storages::postgres::TimePointTz> ||
318 std::is_same_v<typename T::UpdatedFieldType, storages::postgres::TimePointWithoutTz> ||
319 std::is_same_v<typename T::UpdatedFieldType, storages::postgres::TimePoint> || kHasCustomUpdated<T>,
320 "Invalid UpdatedFieldType, must be either TimePointTz or "
321 "TimePointWithoutTz"
322 "or (legacy) system_clock::time_point"
323 );
324#else
325 static_assert(
326 std::is_same_v<typename T::UpdatedFieldType, storages::postgres::TimePointTz> ||
327 std::is_same_v<typename T::UpdatedFieldType, storages::postgres::TimePointWithoutTz> ||
328 kHasCustomUpdated<T>,
329 "Invalid UpdatedFieldType, must be either TimePointTz or "
330 "TimePointWithoutTz"
331 );
332#endif
333 } else {
334 static_assert(
335 !kWantIncrementalUpdates<T>,
336 "UpdatedFieldType must be explicitly specified when using "
337 "incremental updates"
338 );
339 }
340 return true;
341}
342
343// Cluster host type policy
344template <typename T>
345using HasClusterHostTypeImpl = decltype(T::kClusterHostType);
346
347template <typename T>
348constexpr storages::postgres::ClusterHostTypeFlags ClusterHostType() {
349 if constexpr (meta::IsDetected<HasClusterHostTypeImpl, T>) {
350 return T::kClusterHostType;
351 } else {
352 return storages::postgres::ClusterHostType::kSlave;
353 }
354}
355
356// May return null policy
357template <typename T>
358using HasMayReturnNull = decltype(T::kMayReturnNull);
359
360template <typename T>
361constexpr bool MayReturnNull() {
362 if constexpr (meta::IsDetected<HasMayReturnNull, T>) {
363 return T::kMayReturnNull;
364 } else {
365 return false;
366 }
367}
368
369template <typename PostgreCachePolicy>
370struct PolicyChecker {
371 // Static assertions for cache traits
372 static_assert(kHasName<PostgreCachePolicy>, "The PosgreSQL cache policy must contain a static member `kName`");
373 static_assert(kHasValueType<PostgreCachePolicy>, "The PosgreSQL cache policy must define a type alias `ValueType`");
374 static_assert(
375 kHasKeyMember<PostgreCachePolicy>,
376 "The PostgreSQL cache policy must contain a static member `kKeyMember` "
377 "with a pointer to a data or a function member with the object's key"
378 );
379 static_assert(
380 kHasQuery<PostgreCachePolicy> || kHasGetQuery<PostgreCachePolicy>,
381 "The PosgreSQL cache policy must contain a static data member "
382 "`kQuery` with a select statement or a static member function "
383 "`GetQuery` returning the query"
384 );
385 static_assert(
386 !(kHasQuery<PostgreCachePolicy> && kHasGetQuery<PostgreCachePolicy>),
387 "The PosgreSQL cache policy must define `kQuery` or "
388 "`GetQuery`, not both"
389 );
390 static_assert(
391 kHasUpdatedField<PostgreCachePolicy>,
392 "The PosgreSQL cache policy must contain a static member "
393 "`kUpdatedField`. If you don't want to use incremental updates, "
394 "please set its value to `nullptr`"
395 );
396 static_assert(CheckUpdatedFieldType<PostgreCachePolicy>());
397
398 static_assert(
399 ClusterHostType<PostgreCachePolicy>() & storages::postgres::kClusterHostRolesMask,
400 "Cluster host role must be specified for caching component, "
401 "please be more specific"
402 );
403
404 static storages::postgres::Query GetQuery() {
405 if constexpr (kHasGetQuery<PostgreCachePolicy>) {
406 return PostgreCachePolicy::GetQuery();
407 } else {
408 return PostgreCachePolicy::kQuery;
409 }
410 }
411
412 using BaseType = CachingComponentBase<DataCacheContainerType<PostgreCachePolicy>>;
413};
414
415inline constexpr std::chrono::minutes kDefaultFullUpdateTimeout{1};
416inline constexpr std::chrono::seconds kDefaultIncrementalUpdateTimeout{1};
417inline constexpr std::chrono::milliseconds kStatementTimeoutOff{0};
418inline constexpr std::chrono::milliseconds kCpuRelaxThreshold{10};
419inline constexpr std::chrono::milliseconds kCpuRelaxInterval{2};
420
421inline constexpr std::string_view kCopyStage = "copy_data";
422inline constexpr std::string_view kFetchStage = "fetch";
423inline constexpr std::string_view kParseStage = "parse";
424
425inline constexpr std::size_t kDefaultChunkSize = 1000;
426inline constexpr std::chrono::milliseconds kDefaultSleepBetweenChunks{0};
427} // namespace pg_cache::detail
428
429/// @ingroup userver_components
430///
431/// @brief Caching component for PostgreSQL. See @ref pg_cache.
432///
433/// @see @ref pg_cache, @ref scripts/docs/en/userver/caches.md
434template <typename PostgreCachePolicy>
435class PostgreCache final : public pg_cache::detail::PolicyChecker<PostgreCachePolicy>::BaseType {
436public:
437 // Type aliases
438 using PolicyType = PostgreCachePolicy;
439 using ValueType = pg_cache::detail::ValueType<PolicyType>;
440 using RawValueType = pg_cache::detail::RawValueType<PolicyType>;
441 using DataType = pg_cache::detail::DataCacheContainerType<PolicyType>;
442 using PolicyCheckerType = pg_cache::detail::PolicyChecker<PostgreCachePolicy>;
443 using UpdatedFieldType = pg_cache::detail::UpdatedFieldType<PostgreCachePolicy>;
444 using BaseType = typename PolicyCheckerType::BaseType;
445
446 // Calculated constants
447 constexpr static bool kIncrementalUpdates = pg_cache::detail::kWantIncrementalUpdates<PolicyType>;
448 constexpr static auto kClusterHostTypeFlags = pg_cache::detail::ClusterHostType<PolicyType>();
449 constexpr static auto kName = PolicyType::kName;
450
451 PostgreCache(const ComponentConfig&, const ComponentContext&);
452
453 static yaml_config::Schema GetStaticConfigSchema();
454
455private:
456 using CachedData = std::unique_ptr<DataType>;
457
458 UpdatedFieldType GetLastUpdated(std::chrono::system_clock::time_point last_update, const DataType& cache) const;
459
460 void Update(
461 cache::UpdateType type,
462 const std::chrono::system_clock::time_point& last_update,
463 const std::chrono::system_clock::time_point& now,
464 cache::UpdateStatisticsScope& stats_scope
465 ) override;
466
467 bool MayReturnNull() const override;
468
469 CachedData GetDataSnapshot(cache::UpdateType type, tracing::ScopeTime& scope);
470 void CacheResults(
471 storages::postgres::ResultSet res,
472 CachedData& data_cache,
473 cache::UpdateStatisticsScope& stats_scope,
474 tracing::ScopeTime& scope
475 );
476
477 static storages::postgres::Query GetAllQuery();
478 static storages::postgres::Query GetDeltaQuery();
479 static std::string GetWhereClause();
480 static std::string GetDeltaWhereClause();
481 static std::string GetOrderByClause();
482
483 std::chrono::milliseconds ParseCorrection(const ComponentConfig& config);
484
485 std::vector<storages::postgres::ClusterPtr> clusters_;
486
487 const std::chrono::system_clock::duration correction_;
488 const std::chrono::milliseconds full_update_timeout_;
489 const std::chrono::milliseconds incremental_update_timeout_;
490 const std::size_t chunk_size_;
491 const std::chrono::milliseconds sleep_between_chunks_;
492 std::size_t cpu_relax_iterations_parse_{0};
493 std::size_t cpu_relax_iterations_copy_{0};
494};
495
496template <typename PostgreCachePolicy>
497inline constexpr bool kHasValidate<PostgreCache<PostgreCachePolicy>> = true;
498
499template <typename PostgreCachePolicy>
500PostgreCache<PostgreCachePolicy>::PostgreCache(const ComponentConfig& config, const ComponentContext& context)
501 : BaseType{config, context},
502 correction_{ParseCorrection(config)},
503 full_update_timeout_{
504 config["full-update-op-timeout"].As<std::chrono::milliseconds>(pg_cache::detail::kDefaultFullUpdateTimeout)
505 },
506 incremental_update_timeout_{
507 config["incremental-update-op-timeout"]
508 .As<std::chrono::milliseconds>(pg_cache::detail::kDefaultIncrementalUpdateTimeout)
509 },
510 chunk_size_{config["chunk-size"].As<size_t>(pg_cache::detail::kDefaultChunkSize)},
511 sleep_between_chunks_{
512 config["sleep-between-chunks"].As<std::chrono::milliseconds>(pg_cache::detail::kDefaultSleepBetweenChunks)
513 }
514{
515 UINVARIANT(
516 !chunk_size_ || storages::postgres::Portal::IsSupportedByDriver(),
517 "Either set 'chunk-size' to 0, or enable PostgreSQL portals by building "
518 "the framework with CMake option USERVER_FEATURE_PATCH_LIBPQ set to ON."
519 );
520
521 if (this->GetAllowedUpdateTypes() == cache::AllowedUpdateTypes::kFullAndIncremental && !kIncrementalUpdates) {
522 throw std::logic_error(
523 "Incremental update support is requested in config but no update field "
524 "name is specified in traits of '" +
525 config.Name() + "' cache"
526 );
527 }
528 if (correction_.count() < 0) {
529 throw std::logic_error(
530 "Refusing to set forward (negative) update correction requested in "
531 "config for '" +
532 config.Name() + "' cache"
533 );
534 }
535
536 const auto pg_alias = config["pgcomponent"].As<std::string>("");
537 if (pg_alias.empty()) {
538 throw storages::postgres::InvalidConfig{"No `pgcomponent` entry in configuration"};
539 }
540 auto& pg_cluster_comp = context.FindComponent<components::Postgres>(pg_alias);
541 const auto shard_count = pg_cluster_comp.GetShardCount();
542 clusters_.resize(shard_count);
543 for (size_t i = 0; i < shard_count; ++i) {
544 clusters_[i] = pg_cluster_comp.GetClusterForShard(i);
545 }
546
547 LOG_INFO()
548 << "Cache " << kName << " full update query `" << GetAllQuery().GetStatementView()
549 << "` incremental update query `" << GetDeltaQuery().GetStatementView() << "`";
550}
551
552template <typename PostgreCachePolicy>
553std::string PostgreCache<PostgreCachePolicy>::GetWhereClause() {
554 if constexpr (pg_cache::detail::kHasWhere<PostgreCachePolicy>) {
555 return fmt::format(FMT_COMPILE("where {}"), PostgreCachePolicy::kWhere);
556 } else {
557 return "";
558 }
559}
560
561template <typename PostgreCachePolicy>
562std::string PostgreCache<PostgreCachePolicy>::GetDeltaWhereClause() {
563 if constexpr (pg_cache::detail::kHasWhere<PostgreCachePolicy>) {
564 return fmt::format(
565 FMT_COMPILE("where ({}) and {} >= $1"),
566 PostgreCachePolicy::kWhere,
567 PostgreCachePolicy::kUpdatedField
568 );
569 } else {
570 return fmt::format(FMT_COMPILE("where {} >= $1"), PostgreCachePolicy::kUpdatedField);
571 }
572}
573
574template <typename PostgreCachePolicy>
575std::string PostgreCache<PostgreCachePolicy>::GetOrderByClause() {
576 if constexpr (pg_cache::detail::kHasOrderBy<PostgreCachePolicy>) {
577 return fmt::format(FMT_COMPILE("order by {}"), PostgreCachePolicy::kOrderBy);
578 } else {
579 return "";
580 }
581}
582
583template <typename PostgreCachePolicy>
584storages::postgres::Query PostgreCache<PostgreCachePolicy>::GetAllQuery() {
585 const storages::postgres::Query query = PolicyCheckerType::GetQuery();
586 return fmt::format("{} {} {}", query.GetStatementView(), GetWhereClause(), GetOrderByClause());
587}
588
589template <typename PostgreCachePolicy>
590storages::postgres::Query PostgreCache<PostgreCachePolicy>::GetDeltaQuery() {
591 if constexpr (kIncrementalUpdates) {
592 const storages::postgres::Query query = PolicyCheckerType::GetQuery();
593 return storages::postgres::Query{
594 fmt::format("{} {} {}", query.GetStatementView(), GetDeltaWhereClause(), GetOrderByClause()),
595 query.GetOptionalName(),
596 };
597 } else {
598 return GetAllQuery();
599 }
600}
601
602template <typename PostgreCachePolicy>
603std::chrono::milliseconds PostgreCache<PostgreCachePolicy>::ParseCorrection(const ComponentConfig& config) {
604 static constexpr std::string_view kUpdateCorrection = "update-correction";
605 if (pg_cache::detail::kHasCustomUpdated<PostgreCachePolicy> ||
606 this->GetAllowedUpdateTypes() == cache::AllowedUpdateTypes::kOnlyFull)
607 {
608 return config[kUpdateCorrection].As<std::chrono::milliseconds>(0);
609 } else {
610 return config[kUpdateCorrection].As<std::chrono::milliseconds>();
611 }
612}
613
614template <typename PostgreCachePolicy>
615typename PostgreCache<PostgreCachePolicy>::UpdatedFieldType PostgreCache<PostgreCachePolicy>::GetLastUpdated(
616 [[maybe_unused]] std::chrono::system_clock::time_point last_update,
617 const DataType& cache
618) const {
619 if constexpr (pg_cache::detail::kHasCustomUpdated<PostgreCachePolicy>) {
620 return PostgreCachePolicy::GetLastKnownUpdated(cache);
621 } else {
622 return UpdatedFieldType{last_update - correction_};
623 }
624}
625
626template <typename PostgreCachePolicy>
627void PostgreCache<PostgreCachePolicy>::Update(
628 cache::UpdateType type,
629 const std::chrono::system_clock::time_point& last_update,
630 const std::chrono::system_clock::time_point& /*now*/,
631 cache::UpdateStatisticsScope& stats_scope
632) {
633 namespace pg = storages::postgres;
634 if constexpr (!kIncrementalUpdates) {
635 type = cache::UpdateType::kFull;
636 }
637 const auto query = (type == cache::UpdateType::kFull) ? GetAllQuery() : GetDeltaQuery();
638 const std::chrono::milliseconds
639 timeout = (type == cache::UpdateType::kFull) ? full_update_timeout_ : incremental_update_timeout_;
640
641 // COPY current cached data
642 auto scope = tracing::Span::CurrentSpan().CreateScopeTime(std::string{pg_cache::detail::kCopyStage});
643 auto data_cache = GetDataSnapshot(type, scope);
644 [[maybe_unused]] const auto old_size = data_cache->size();
645
646 scope.Reset(std::string{pg_cache::detail::kFetchStage});
647
648 size_t changes = 0;
649 // Iterate clusters
650 for (auto& cluster : clusters_) {
651 if (chunk_size_ > 0) {
652 auto trx = cluster->Begin(
653 kClusterHostTypeFlags,
654 pg::Transaction::RO,
655 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff}
656 );
657 auto portal = trx.MakePortal(query, GetLastUpdated(last_update, *data_cache));
658 while (portal) {
659 scope.Reset(std::string{pg_cache::detail::kFetchStage});
660 auto res = portal.Fetch(chunk_size_);
661 stats_scope.IncreaseDocumentsReadCount(res.Size());
662
663 scope.Reset(std::string{pg_cache::detail::kParseStage});
664 CacheResults(res, data_cache, stats_scope, scope);
665 changes += res.Size();
666 if (sleep_between_chunks_.count() > 0) {
667 engine::InterruptibleSleepFor(sleep_between_chunks_);
668 }
669 }
670 trx.Commit();
671 } else {
672 const bool has_parameter = query.GetStatementView().find('$') != std::string::npos;
673 auto res =
674 has_parameter
675 ? cluster->Execute(
676 kClusterHostTypeFlags,
677 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff},
678 query,
679 GetLastUpdated(last_update, *data_cache)
680 )
681 : cluster->Execute(
682 kClusterHostTypeFlags,
683 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff},
684 query
685 );
686 stats_scope.IncreaseDocumentsReadCount(res.Size());
687
688 scope.Reset(std::string{pg_cache::detail::kParseStage});
689 CacheResults(res, data_cache, stats_scope, scope);
690 changes += res.Size();
691 }
692 }
693
694 scope.Reset();
695
696 if constexpr (pg_cache::detail::kIsContainerCopiedByElement<DataType>) {
697 if (old_size > 0) {
698 const auto elapsed_copy = scope.ElapsedTotal(std::string{pg_cache::detail::kCopyStage});
699 if (elapsed_copy > pg_cache::detail::kCpuRelaxThreshold) {
700 cpu_relax_iterations_copy_ = static_cast<
701 std::size_t>(static_cast<double>(old_size) / (elapsed_copy / pg_cache::detail::kCpuRelaxInterval));
702 LOG_TRACE()
703 << "Elapsed time for copying " << kName << " " << elapsed_copy.count() << " for " << changes
704 << " data items is over threshold. Will relax CPU every " << cpu_relax_iterations_parse_
705 << " iterations";
706 }
707 }
708 }
709
710 if (changes > 0) {
711 const auto elapsed_parse = scope.ElapsedTotal(std::string{pg_cache::detail::kParseStage});
712 if (elapsed_parse > pg_cache::detail::kCpuRelaxThreshold) {
713 cpu_relax_iterations_parse_ = static_cast<
714 std::size_t>(static_cast<double>(changes) / (elapsed_parse / pg_cache::detail::kCpuRelaxInterval));
715 LOG_TRACE()
716 << "Elapsed time for parsing " << kName << " " << elapsed_parse.count() << " for " << changes
717 << " data items is over threshold. Will relax CPU every " << cpu_relax_iterations_parse_
718 << " iterations";
719 }
720 }
721 if (changes > 0 || type == cache::UpdateType::kFull) {
722 // Set current cache
723 pg_cache::detail::OnWritesDone(*data_cache);
724 stats_scope.Finish(data_cache->size());
725 this->Set(std::move(data_cache));
726 } else {
727 stats_scope.FinishNoChanges();
728 }
729}
730
731template <typename PostgreCachePolicy>
732bool PostgreCache<PostgreCachePolicy>::MayReturnNull() const {
733 return pg_cache::detail::MayReturnNull<PolicyType>();
734}
735
736template <typename PostgreCachePolicy>
737void PostgreCache<PostgreCachePolicy>::CacheResults(
738 storages::postgres::ResultSet res,
739 CachedData& data_cache,
740 cache::UpdateStatisticsScope& stats_scope,
741 tracing::ScopeTime& scope
742) {
743 auto values = res.AsSetOf<RawValueType>(storages::postgres::kRowTag);
744 utils::CpuRelax relax{cpu_relax_iterations_parse_, &scope};
745 for (auto p = values.begin(); p != values.end(); ++p) {
746 relax.Relax();
747 try {
748 using pg_cache::detail::CacheInsertOrAssign;
749 CacheInsertOrAssign(
750 *data_cache,
751 pg_cache::detail::ExtractValue<PostgreCachePolicy>(*p),
752 PostgreCachePolicy::kKeyMember
753 );
754 } catch (const std::exception& e) {
756 LOG_ERROR()
757 << "Error parsing data row in cache '" << kName << "' to '" << compiler::GetTypeName<ValueType>()
758 << "': " << e.what();
759 }
760 }
761}
762
763template <typename PostgreCachePolicy>
764typename PostgreCache<PostgreCachePolicy>::CachedData PostgreCache<
765 PostgreCachePolicy>::GetDataSnapshot(cache::UpdateType type, tracing::ScopeTime& scope) {
766 if (type == cache::UpdateType::kIncremental) {
767 auto data = this->Get();
768 if (data) {
769 return pg_cache::detail::CopyContainer(*data, cpu_relax_iterations_copy_, scope);
770 }
771 }
772 return std::make_unique<DataType>();
773}
774
775namespace impl {
776
777std::string GetPostgreCacheSchema();
778
779} // namespace impl
780
781template <typename PostgreCachePolicy>
782yaml_config::Schema PostgreCache<PostgreCachePolicy>::GetStaticConfigSchema() {
783 using ParentType = typename pg_cache::detail::PolicyChecker<PostgreCachePolicy>::BaseType;
784 return yaml_config::MergeSchemas<ParentType>(impl::GetPostgreCacheSchema());
785}
786
787} // namespace components
788
789namespace utils::impl::projected_set {
790
791template <typename Set, typename Value, typename KeyMember>
792void CacheInsertOrAssign(Set& set, Value&& value, const KeyMember& /*key_member*/) {
793 DoInsert(set, std::forward<Value>(value));
794}
795
796} // namespace utils::impl::projected_set
797
798USERVER_NAMESPACE_END